PQFL_Schizophrenia / PUBLICATION_FIX_PROGRESS.md
Dev2506's picture
Upload full project state: code, results (175), anonymized NPZs, Obsidian vault, reports - manuscript excluded, pre-anonymization data purged
7577181 verified
|
Raw History Blame Contribute Delete
65.7 kB

PUBLICATION FIX — PROGRESS TRACKER

Single source of truth for the fix roadmap. Every /loop iteration ("i want you to start doing zero to the end") reads this file and continues from NEXT. Full catalog of the 118 problems (100 original audit + post-audit findings #101–#118): PQFL_Obsidian_Vault/01 - Overview/Problem Catalog for Publication.md.

Loop job: session cron 81c198da (every 10 min, auto-expires 7d). Started: 2026-08-13. Target: publishable research paper.


✅ DONE (verified)

Phase 0 — Security & privacy triage

  • Synapse PAT redacted — pqfl_project/scripts/download_brainlat.py now reads SYNAPSE_AUTH_TOKEN from env; hardcoded JWT removed. User action required: revoke the old token at Synapse → Account Settings → Personal Access Tokens. (The old token is in your clipboard history / git-if-ever-pushed; treat as compromised.)
  • Project-wide credential scan — 0 remaining JWT/authToken/password/api-key/secret matches.
  • NDAR GUIDs scrubbed from data_inventory.txt (21 lines) and decode_dsm.py example → [REDACTED]/SUBJ-....
  • Processed npz anonymized — new pqfl_project/scripts/anonymize_npz.py wrote data/processed_anon/ (4 files, 1047 subjects): subject_ids replaced by non-reversible SUBJ-<site>-NNNN-<sha256[:10]>. Verified all data arrays byte-identical, 0 NDAR keys remain. Pipeline never reads subject_ids back, so anon copies are drop-in.
  • .gitignore created at project root — excludes data/, .npz, manifest.csv, data_inventory.txt, Dataset.zip, lp-dev/, *.log, *.bak, venv, caches. NOTE: data_inventory.txt and manifest*.csv are force-excluded but still on disk (redacted GUIDs only in inventory); remove them from any zip you share.
  • Vault catalog note redacted — full JWT fragment removed from evidence (was embedded by the audit's security finder).

Security decisions for the USER (deletion is yours to call, not mine)

  • pqfl_project/Dataset.zip (93.4 MB) — third-party clinical omics (SCZ/ROSMAP/BRCA/STAD), no provenance or license. Recommend: delete, or move out of the repo to a private archive.
  • pqfl_project/lp-dev/ (167 MB) — proprietary third-party LLM serving framework + HF caches. Recommend: delete.
  • manifest.csv + 6 timestamped copies — restricted BrainLat download manifests. Recommend: move to private archive.
  • Whether data/processed/ (181 MB, original subject keys) stays on disk: fine locally, but never share it; share data/processed_anon/ only under DUA.

🔄 IN PROGRESS / NEXT

Phase 1 — research-integrity defects (task #18). Order matters — every downstream number depends on these:

1a. AUC sentinels — remove all except: auc = 0.5 ✅ COMPLETE (2026-08-13)

Canonical pattern everywhere: AUC computed over classes present in BOTH train and val, returned as None (never 0.5/0.0) when uncomputable; ALL downstream aggregation/logging skips None/NaN. Shared helpers: compute_auc(y_val_m, y_proba, n_present) + remap_labels (unseen held-out class → len(present_train), NOT folded into class 0). sklearn 1.8.0 quirks handled: single-class roc_auc_score returns nan (not ValueError) → explicit len(np.unique)>1 + np.isfinite guards; 2-class multi_class='ovr' raises ValueError → special-cased binary path roc_auc_score((y==c1).astype(int), p[:,c1]).

Files fixed (all verified py_compile clean; helper logic runtime-tested):

File Notes
pqfl/evaluation/metrics.py ROOT: binary + multi-class AUC both return None when uncomputable (np.isfinite guard)
tier1_enhanced_training.py SVM baseline rewritten (real AUC, None instead of 0.5)
tier4_gpu_baselines.py 7 sentinel blocks + TabNet val_classes NameError → compute_auc; leak removed (eval_set); linear-SVM probs sigmoid/softmax
tier4_strong_baselines.py compute_auc; leak removed (GNN early-stop on held-out site → fixed epochs); fabricated pqfl_ba=0.394 comparison deleted
tier4_proper_federation.py None-based AUC + aggregation
quantum_kernel_svm.py, quantum_kernel_svm_amp.py None-based AUC + aggregation
tier6_quantum_kernel_fl.py, pqfl_improvements/pqfl/federated/hybrid_strategy.py None-based AUC + aggregation
tier4_other_class_analysis.py, tier4_imbalance_comparison.py, tier4_hyperparam_sweep.py, tier4_combat_leakage_analysis.py, tier4_circuit_comparison.py, tier4_circuit_comparison_simple.py, tier4_advanced_baselines.py remap_labels + compute_auc + None-tolerant aggregation
tier4_brain_clinical_analysis.py compute_auc; label-convention bug fixed in DCA (cls=1→cls=0, per 0=SZ)
experiments/final_training.py, experiments/evaluate_pqfl_cv.py best_auc=None, baseline AUC nan-guarded, _summ None-filtering, all logs None-tolerant
experiments/hyperparameter_sweep.py same + failed-config placeholder auc_mean: 0.5 → None
experiments/train_federated.py baseline AUC None-based + None-tolerant summary
experiments/train_pqfl_phase2.py round-history val_auc None-tolerant, fold/aggregate/log/plot guards
experiments/visualize_results.py _auc_value() → NaN (renders absent, never fake 0.5)
tier4_permutation_test.py failed fold → None (NOT 0.0/0.5); null distribution/p-values/JSON guard empty & None
tier4_statistical_tests.py, analyze_tier5_results.py None/NaN filtering before np.mean

⚠️ Phase-3 cleanup hazard: replace_xgboost_function.py (and the .ipynb_checkpoints/*-checkpoint.py files) are stale fixer utilities that still contain the OLD auc = 0.5 snippets — running replace_xgboost_function.py would re-insert the bug into tier4_gpu_baselines.py. Newly-found stale patchers to delete too (contain OLD leaky/AUC snippets, do NOT run): fix_fedper_eval.py, fix_fedper_eval_v2.py, fix_all_issues_v2.py, fix_vqc_device.py. Delete them all in Phase 3. ALL DELETED 2026-08-14 (16 patchers incl. these; see Phase 3).

1b. Label conventions — one truth: 0=SZ, 1=HC, 2=Other, 3=BP ✅ COMPLETE (2026-08-13)

Canonical 3-class decision: SZ / HC / BP (keep {0,1,3}, relabel BP 3→2, drop Other=2). Rationale: matches tier1 flagship + tier4 (baselines must be head-to-head comparable with PQFL), and BP is clinically more meaningful than heterogeneous "Other". This overrides the train_pqfl_phase2.py header that previously called "SZ/HC/Other primary". Verified: tier1/2/3/phase2 all load the identical 3-class pool {0:423 SZ, 1:288 HC, 2:225 BP} = 936 subjects (1047 − 111 Other ✓).

Per-file reconciliation record (all py_compile clean; label/remap/AUC logic runtime-tested):

Area File Fix
3-class unification tier2_baselines.py, tier3_attention.py, tier3_uncertainty.py, experiments/train_pqfl_phase2.py canonical mask (l==0)|(l==1)|(l==3) + np.where(l==3,2,l); CLASS_NAMES {3:["SZ","HC","BP"]} (was ["SZ","HC","Other"])
3-class adapter pqfl/data/dataset_adapters.py remap_labels_for_n_classes 3-class now drops Other, relabels BP 3→2 (was BP→Other = wrong pool)
3-class test scripts/test_adapters.py assertion updated to canonical remap (8 samples: 3 SZ/3 HC/2 BP); class_names ["SZ","HC","BP"]
Binary CLASS_NAMES tier2_baselines.py:25, tier3_attention.py:60, tier3_uncertainty.py:51, phase2 {2:["SZ","HC"]} (was inverted ["HC","SZ"])
Binary-on-4-class crash experiments/final_training.py, evaluate_pqfl_cv.py, train_federated.py, analyze_significance.py binary filter labels<2 before load (was feeding 4-class labels to CrossEntropyLoss); accounting (labels==0)/(labels==1) (was labels.sum())
Library root pqfl/data/dataset.py FCDataset.n_sz/n_hc (labels==0)/(labels==1) (was labels.sum()); get_class_weights index-aligned [w_SZ, w_HC] (was swapped); stratified-split sz_indices/hc_indices swapped (this session)
Library root pqfl/federated/client.py class-weight log SZ first; stale y_prob[:,1] comment removed
Saliency pqfl/evaluation/saliency.py target_class default 1→0 in BOTH compute_saliency + compute_integrated_gradients (0=SZ)
Saliency experiments/analyze_significance.py, demo_e2e.py SZ samples selected via labels==0; target_class=0
Label-encoder corruption scripts/preprocess_all_datasets.py, preprocess_real_data.py get_diagnosis_label returned 1=SZ/0=HC → now 0=SZ/1=HC (any re-run would have silently written inverted npz labels); all accounting fixed
Label-encoder corruption scripts/preprocess_new_datasets.py removed deliberate SZ 0→1 inversion in the 2-class write path (npz would have been 1=SZ); stale --n_classes help text
Accounting/logs scripts/integrate_datasets.py, scripts/check_dataset_status.py n_sz/n_hc written into npz/metadata via (labels==0)/(labels==1)
Docstrings pqfl/baselines/classical.py:62, pqfl/harmonization/combat.py:193 (0=HC,1=SZ) → (0=SZ,1=HC)
Docstrings pqfl/evaluation/metrics.py, dataset_adapters.py 3-class default class_names=["SZ","HC","BP"]; MLSP raw-source convention clarified
Tier4 distribution tier4_other_class_analysis.py distribution table had 0=HC/1=SZ/2=BD/3=Other (inverted + BD/Other swapped); other_mask = y_all==3 (BP as "Other") → fixed to canonical
Already fixed prior session pqfl/data/site_partitioning.py, tier1_enhanced_training.py:75, transdiagnostic_adapter.py overwrite guard verified correct this session

⚠️ NEW research-integrity find (AUC inversion, caught by residual sweep): metrics.py AUC contract is roc_auc_score((y==0), p(class 0)) — 1-D y_prob must be p(SZ). experiments/train_federated.py passed probs[:,1] = p(HC) at 3 sites (SVM :528, LR :536, quantum model :700) → reported AUC = 1 − true SZ-AUC. Numerically verified: true 0.9912, old-reported 0.0088. All 3 fixed to [:,0]. (Other callers pass full 2-D matrices or use roc_auc_score(y, p(HC)) directly — both correct.)

1c. LOSO leakage — fit inside the fold ✅ COMPLETE (2026-08-14)

Canonical pattern (all refactored scripts): aggregate_raw(sites) (no-fit concat of raw FC) → split on raw FC → per fold loso_fold_features(fc_all, train_idx, val_idx, n_rois, n_components, metric, y_all, site_ids_all, combat) = fit RiemannianEngine on fc_all[train_idx] + transform train/val + optional combat_fit_transform (fit on train sites only; held-out site left unadjusted — must be disclosed in manuscript). Inline-equivalent used where a script needs extra control: per-fold engine.fit(fc_train) + combat_fit_transform. The n_components clamp is caller responsibility (RiemannianEngine.fit does NOT clamp): tangent_dim = n_rois*(n_rois+1)//2, min(BASE_CONFIG["n_components"], tangent_dim, n-1), per-fold max(1, min(n_components, len(train_idx)-1)). Hardcoded 5050 removed everywhere.

Files refactored (all py_compile clean; grep-swept for aggregate_features/apply_combat/X_all/5050 — the only live hits left are the disclosed exceptions below):

Area Files
Helper root tier1_enhanced_training.py (new aggregate_raw, combat_fit_transform, loso_fold_features)
tier2/3/5/6 tier2_baselines.py, tier3_attention.py, tier3_uncertainty.py, tier5_improved_pqfl.py + duplicate pqfl_improvements/tier5_improved_pqfl.py, tier6_quantum_kernel_fl.py, tier6_amp_qksvm.py
tier4 family tier4_advanced_baselines.py, tier4_binary_szhc.py, tier4_brain_clinical_analysis.py, tier4_circuit_comparison.py, tier4_circuit_comparison_simple.py, tier4_explainability.py, tier4_explainability_simple.py, tier4_gpu_baselines.py, tier4_hyperparam_sweep.py, tier4_imbalance_comparison.py, tier4_other_class_analysis.py, tier4_permutation_test.py, tier4_proper_federation.py, tier4_site_confound.py, tier4_strong_baselines.py
experiments final_training.py, evaluate_pqfl_cv.py, train_pqfl_phase2.py, train_federated.py, hyperparameter_sweep.py (last one completed this iteration)
Special tier4_combat_leakage_analysis.py (measures leakage; arms A/B deliberately all-data engine to ISOLATE ComBat effect — disclosed), tier4_external_validation.py (train-only ComBat; external site left unharmonized — disclosed), tier4_heterogeneity_analysis.py (descriptive), map_brain_regions.py (descriptive post-hoc mapper, no CV metric)

Intentional all-data fits that REMAIN (each disclosed in-script and must be stated in manuscript): aggregate_features/apply_combat only in tier4_heterogeneity_analysis.py + map_brain_regions.py (dataset-characterization/post-hoc, NOT benchmark numbers — never quote as CV performance); tier4_combat_leakage_analysis.py arms A/B (deliberate leaky-vs-correct measurement).

Stale duplicates: .ipynb_checkpoints/*-checkpoint.py still contain the old leaky pattern — delete in Phase 3 (never run them; replace_xgboost_function.py likewise) DELETED 2026-08-14 (see Phase 3).

1d. Fabricated statistics — delete or recompute ✅ COMPLETE (2026-08-14) — category_a_metrics.py (runtime-verified against real results; py_compile clean; exit 0)

  • ✅ McNemar magic-0.7 fabrication REMOVED — McNemar requires per-subject paired predictions (2×2 PQFL-vs-SVM agreement per subject), which the results JSON does not store; the 0.7 overlap factor was invented. Now prints + stores an explicit mcnemar_test.note; relies on the legitimate fold-paired t-test / Wilcoxon (Section 6).
  • ✅ Comm-cost derived from the REAL model — builds the actual HybridVQC from the tier1 results' recorded config (input_dim=71, 8 qubits, 2 base + 1 personal layers, fdt=0, 4-class) and counts shared/personal params via count_shared_params()/count_personal_params() (12,854 shared / 8,780 personal — vs the fabricated 12632/2202), plus REAL total_rounds from the fold results (avg 16.4 — vs the fabricated 25). create_rqfm_circuit hardcodes lightning.gpu; the count is backend-independent, so pennylane.device is patched to default.qubit for construction. Falls back to an explicit "NOT DERIVED" note if the model can't be built.
  • ✅ Permutation p reported WITH resolution floor — stores p_value + explicit p_value_floor = 1/(n_permutations+1) + n_permutations (100 → floor 0.0099), printed as "true p ≤ floor". The low-N permutation null is a Phase 2 re-run item (tier4_permutation_test.py:166).
  • ✅ Bootstrap CI mispairing FIXED — new paired_metric_arrays() helper pairs PQFL-vs-SVM by position and drops pairs where EITHER side is NaN/None (old code filtered NaN on the PQFL side only, then truncated SVM by position → mispaired CI). All §3 bootstraps + §6 t-tests now use the same aligned pairs.

1e. Model selection on held-out site ✅ COMPLETE (2026-08-14)

Canonical pattern: best-round selection / early stopping runs on a set drawn from the TRAINING sites ONLY; the held-out site is evaluated ONCE, on the selected checkpoint, at the end. Every trainer now records model_selection metadata in its result JSON (inner_stratified_20pct / inner_per_client_val / no_inner_split_select_on_train).

Trainer Fix
tier1_enhanced_training.py::train_one_fold (SHARED by tier4_binary_szhc, tier4_site_confound, tier4_permutation_test, tier4_external_validation, proper_federation centralized/local) stratified inner split (default 20% via inner_val_frac, _inner_val_split helper w/ unstratified fallback) of TRAINING sites; selection on inner-val through client.val_loader; val_loader swapped to the held-out loader before the FINAL evaluate(None, {}); class weights from inner-train
tier4_proper_federation.py::_run_federated_loop new _make_inner_val_set(clients) concatenates the per-client 10% internal val_loaders (already carved in _create_clients) → selection evals (fedbn + common block) on X_sel/y_sel; final return eval stays on held-out X_val; if no internal set → best-round selection disabled (fixed rounds)
tier2_baselines.py::train_one_fold (own) same inner-split pattern; val_loader swapped before final eval (both mlp + pqfl paths)
tier3_attention.py::train_one_fold (own) same; attention-weight extraction kept (post-hoc on held-out)
tier3_uncertainty.py::train_and_evaluate_fold same; final metrics already MC-dropout on held-out X_val (kept); dead val_loader removed
experiments/train_pqfl_phase2.py::train_one_fold (own, +fdt) same, with None-safe fdt split (sklearn train_test_split raises TypeError on None arrays — fdt split only when present); best_params now tracked; final metrics recomputed on held-out y_val
tier5_improved_pqfl.py + duplicate pqfl_improvements/ _make_inner_val_set from per-client val_loaders; selection evals on X_sel; best-round model state snapshotted + restored for the final held-out eval

4 experiment harnesses — selection-on-test leak FIXED (2026-08-14). ⚠️ Correction to the audit above: the 1e audit claimed client.fit(...) returns TRAIN-only metrics so the harnesses' early stopping never fires. Empirically false — PQFLClient.fit (client.py:239-254) calls self.evaluate() when val_loader is set and merges real val metrics (balanced_accuracy etc.); runtime-verified (TinyNet fit returned balanced_accuracy=0.389). The real defect was worse: all 4 harnesses passed the held-out fold as the client's val_loader, so best-round selection ran on the test fold and the reported BA was the best-on-test value (selection-on-test leakage, optimistic bias). Fixed by carving a stratified inner-validation split from the TRAINING data (make_inner_val_split, 20%, unstratified fallback, single-class inner-val → ok=False) for selection, and scoring the selected checkpoint on the held-out fold only (evaluate_held_out). Each result records selection: inner_val_20pct / fixed_rounds_no_inner_split (disclosed fixed-rounds fallback). Files: experiments/{hyperparameter_sweep,evaluate_pqfl_cv,final_training,analyze_significance}.py. All py_compile clean; helpers runtime-tested.

Runtime-verified (2026-08-14, dev box; lightning.gpu → default.qubit patched for construction — backend-independent):

  • tier1 train_one_fold smoke: model_selection=inner_stratified_20pct, best_round picked on inner-val, final metrics on held-out (n_total=held-out size), per-class + confusion matrix intact.
  • tier4 _make_inner_val_set + _run_federated_loop fedavg/fedper/moon: selection on 12-sample internal set; final BA/AUC on held-out X_val.
  • All edited files py_compile clean.

Also fixed

  • ✅ k_splits NameError (tier1:578) → uses args.n_folds
  • ✅ Verified: all 34 tier/adapter/kernel scripts + all experiments/*.py py_compile clean (2026-08-13)
  • ✅ scripts/test_adapters.py label-remap + SPD tests pass (FNC test has a pre-existing flaky synthetic-data eigen-convergence issue, unrelated)

Phase 2 — experimental design (task #19) ✅ COMPLETE (2026-08-14) — every item code-complete and verified:

Item Fix Verified
Real centralized baseline (tier2_baselines.py) centralized now n_personal_layers=0 (no FedPer layers); was byte-identical to pqfl (BA 0.3871); model_desc recorded smoke: pqfl 0.1111 vs centralized 0.3056
Real seeds (QKSVM/RBF/Amp) random_state=seed threaded through QuantumKernelSVM, AmplitudeQKSVM, ClassicalRBFSVM, FederatedQKSVM, FederatedAmplitudeQKSVM + tier6 drivers; genuine variation via SVC(probability=True) Platt CV probs differ (max|diff| 0.154 / 0.129)
Conformal split (tier3_uncertainty.py) dedicated calibration carve (15%) disjoint from selection; correct LAS score (sorted_probs[:true_pos].sum()); calibration_source disclosed per result coverage 0.922/0.821/0.716 at α=.1/.2/.3
Permutation null (tier4_permutation_test.py) N 100→1000 (p floor ≈0.001); p_value_floor + n_permutations_valid in JSON; ComBat re-fit per fold under the null (1c already honest) py_compile + logic verified
Pseudo-replication (tier1 stats + tier4_statistical_tests.py) paired tests cluster by fold (mean across seeds); independent unit = held-out site, NOT (seed×fold); flat fallback disclosed fold-mean clustering verified
Holm monotonicity (tier4_statistical_tests.py) adjusted p = running max of step-down products (was non-monotone: n=3 p=[.04,.05,.05] → 0.12,0.10); sequential rejection kept regression test passes
4 experiment harnesses selection-on-test leak FIXED (see 1e note above): inner-val selection + held-out final eval; selection metadata py_compile + helpers runtime-tested

NEXT → Phase 3 (task #20) in progress. Clean re-run on the A100 box (quantum311 env); single 3-class + binary convention; leak-free LOSO; then manuscript rewrite from HONEST_ASSESSMENT.md.

Phase 3 — clean re-run prep ✅ PARTIAL (2026-08-14) — ALL LOCAL VALIDATION COMPLETE: every manifest step (1–7) and every Part B consumer (B1 tier5 v2 ablations, B2 analyze_tier5, B3 final_training, B4 analyze_significance, plus evaluate_pqfl_cv + hyperparameter_sweep) is smoke-proven end-to-end on real data with the fixes below. Remaining is user-side: A100 sync + verify, then the canonical run (10 seeds / 50 rounds), then fill-tool + §4 consumers.

  • ✅ Stale patchers deleted (16 total) — the 6 roadmap-listed (replace_xgboost_function.py, fix_all_auc_v2.py, fix_fedper_eval.py, fix_fedper_eval_v2.py, fix_all_issues_v2.py, fix_vqc_device.py) + 9 more found during the sweep (fix_all_device_issues.py, fix_auc_computation.py, fix_concerns_scripts.py, fix_escaped_quotes.py, fix_la5c_swap.py, fix_moon_deepcopy.py, fix_parameter_utils.py, fix_xgboost_auc_scope.py, fix_xgboost_definitive.py) + scripts/fix_la5c_structure.py. All verified zero-import / zero-subprocess-ref before deletion. All .ipynb_checkpoints/ dirs removed (full-repo sweep = 0 remaining). No fix_*.py/replace_*.py left anywhere.
  • ✅ Full-repo compileall clean after all Phase-2/3 edits (exit 0, 0 errors).
  • ✅ CRITICAL DATA REALITY — 4 sites, not 9 (2026-08-14). The runnable data is exactly 4 *_processed.npz sites (COBRE site_id=4, KagglePsychosis=20, LA5c=3, Transdiagnostic=19; 1047 subjects → 3-class pool 936 = {SZ 423, HC 288, BP 225} ✓ matches canonical). The 7-site registry (FBIRN/MCIC/SRPBS/BSNIP2/TCP2025) was never processed (vault 03 - Data/Datasets.md). Consequences for the paper (MUST disclose):
    • 3-class LOSO = 4 folds; binary SZ-vs-HC LOSO = 3 folds (KagglePsychosis {SZ,BP} has no HC → dropped; it's 45% of the data).
    • n=4 statistical power ceiling: two-sided paired Wilcoxon p cannot fall below 2^(1−4)=0.125; even a perfect 4-site result cannot reach p<0.05 on paired Wilcoxon. The permutation test is the appropriate primary significance check at this site count (label-permutation null within the same folds, not cross-site replication).
    • Fold-clustered tests must still RUN at n=4 (strictly more honest than flat pseudo-replication), with low_n_sites + power_warning recorded and reported.
  • ✅ Finding #101 (2nd half) FIXED — n-gate fix (found while prepping): all 3 stats consumers silently disabled the ONLY correct test on 4 sites. The >=5-fold gates (written when 9 sites were assumed) meant fold-clustered tests would never trigger on real data → silent fallback to flat pseudo-replicated pairing. Fixed in tier1_enhanced_training.py (fold-clustered Wilcoxon/ttest at n≥2 + low_n_sites/power_warning), tier4_statistical_tests.py (same + paired_ttest/wilcoxon_test floor 5→2 + per-algo CI now fold-clustered independent-unit CI), and analyze_tier5_results.py::paired_t_test_vs_tier5 (was flat 40-value positional pairing = pseudo-replication; now fold-keyed clustering, skip-if-no-fold-ids, low-n disclosure). All regression-tested: 4-folds x 3-seeds collapses to n=4; shuffled-order pairing still matches by fold; n=1 → None; no-fold-ids → skip, never flat-pair. All py_compile clean. (The #101 first half — n=4 power ceiling disclosure — is the "CRITICAL DATA REALITY" bullet above.)
  • ✅ Finding #103 FIXED: binary loader kept KagglePsychosis (SZ-only) — code contradicted the documented n=3 / N=423 design (2026-08-14) — while auditing manifest step 7 (binary SZ-vs-HC), empirically confirmed tier1_enhanced_training.py::load_sites (with mask = labels < 2) keeps KP's 288 SZ subjects: the binary site set was 711 subjects / 4 sites / 4 folds with a degenerate single-class KP fold, contradicting the docs table + manuscript §2.1/§3.3/D2 (N=423 = 135 SZ / 288 HC, n=3 folds, KP dropped). tier2_baselines.py::load_sites had the identical defect. Fix: both loaders now skip any site whose subjects collapse to a single class in the target scheme (every held-out fold needs ≥2 classes to score). Re-verified: binary → 3 sites / 423 (135 SZ / 288 HC) with [SKIP] KagglePsychosis logged; 3-class unchanged → 4 sites / 936. Matches docs + manuscript + fill-tool §3.3 n=3 gate exactly. All py_compile clean. This was a must-fix before the A100 step-7 run — it would otherwise have produced 4-fold binary numbers contradicting the paper.
  • ✅ Finding #104 FIXED: post-suite binary harnesses (experiments/) never propagated the #103 KP-drop + analyze_significance.py all-data Riemannian leak + AirM default (2026-08-14) — the four binary significance harnesses keep KP by a different mechanism: binary_mask = combined_labels < 2 applied at the combined-array level (final_training.py, evaluate_pqfl_cv.py, analyze_significance.py) and a per-site mask with no single-class drop (hyperparameter_sweep.py) → empirical pool 711 / 4 sites, contradicting N=423 / n=3. Separately analyze_significance.py fit the Fréchet mean + tangent PCA on ALL subjects before the CV split (held-out subjects shaped the validation tangent features — a leak the other three already fixed via transform_fold), and all four built RiemannianEngine with the default affine_invariant metric, re-introducing the AirM path (#102; measured 0.39 s/matrix vs 0.04 s/matrix for LE ≈ 132 s vs ~14 s per train fold). Fix: all four loaders now mask per-site and skip single-class sites (verified 423 / 135 SZ / 288 HC / 3 sites on real data, [SKIP] KagglePsychosis logged); analyze_significance.py now returns raw FC and fits the engine per fold on train only (transform_fold, verified 15.4 s LE fit+transform on a 338-subject train fold); all four pass metric="log_euclidean". All py_compile clean. Residual design caveat documented in docs/PUBLICATION_CLEAN_RUN.md §4: these remain subject-level random StratifiedKFold sensitivity analyses (leak-free, pool-consistent) — their DeLong/McNemar p-values are pseudo-replicated across same-site subjects and must NOT be cited as site-independent significance; binary primary significance = tier1 step-7 LOSO + permutation test.
  • ✅ Manuscript draft written (manuscript/PQFL_manuscript_draft.md, v0.1): full honest-arc draft with methods verified against the fixed code (RQFM angle encoding + StronglyEntanglingLayers shared / BasicEntanglerLayers personal; train-site-only ComBat; inner-val model selection; fold-clustered n=4 statistics + permutation primary; 4-site data table; binary-drops-KP disclosure). Every result number is a [TBD] placeholder with its exact source JSON path — no fabricated numbers. Includes the Disclosure checklist (D1–D9) that must pass before submission.
  • ✅ MANUSCRIPT_UPDATE_GUIDE.md reconciled (2026-08-14) — the old v1→v2 upgrade template was marked SUPERSEDED with a banner. Its numeric examples (v1 BA=0.2764, Local=0.4272, Centralized=0.3847, FedAvg=0.3278) are all pre-fix (old protocol: 4-class, selection-on-test, 9-site assumption) and are flagged to never appear in Results; its HEA-as-flagship and FedBN+FedPer-hybrid claims contradict the implemented code (RQFM + StronglyEntanglingLayers/BasicEntanglerLayers, FedPer split). Retained only as a structural template (ablation table §IV-B, per-fold breakdown §IV-C, lessons-learned narrative §V) — the draft's §3.5 now names the 5 real tier5 conditions and cites the guide for table structure only.
  • ✅ Manifest N_QUBITS case bug fixed (2026-08-14, found by local smoke prep) — lines 71/78/86/119 passed --n_qubits $N_QUbits (unset var, bash case-sensitive) → would crash step 1 with "expected one argument" (or silently run default 8 qubits instead of the intended 6). All four fixed to $N_QUBITS; full variable audit: all 5 refs ($OUT/$DATA_DIR/$DEVICE/$SEEDS/$N_QUBITS) resolve; bash -n clean.
  • ✅ Catalog #3 FIXED: hardcoded lightning.gpu → robust device fallback (2026-08-14, surfaced by local GPU smoke) — the local box (RTX 5060, CUDA available, pennylane 0.44) has NO lightning-gpu plugin, proving the hardcode crashed the flagship anywhere but the A100. Added module-level create_device(n_qubits, prefer_gpu=True, shots=None) to simulator.py (chain: lightning.gpu → lightning.qubit → default.qubit); rqfm.py (RQFM + QCNN), rqfm_v2.py (HEA+reupload + RealAmplitudes), and secondary scripts tier4_brain_clinical_analysis.py/tier4_circuit_comparison.py/tier4_circuit_comparison_simple.py/tier4_explainability_simple.py all use it. Runtime-verified on the plugin-less box: falls back to lightning.qubit, both circuits build, forward pass finite. A100 behavior unchanged (plugin present → still lightning.gpu first).
  • ✅ Finding #102 FIXED: metric=log_euclidean was dead config — pipeline silently ran AirM (2026-08-14) — RiemannianEngine stored self.metric but never forwarded it; TangentSpaceProjector unconditionally ran the iterative affine-invariant mean (20× scipy.linalg.logm/iter) while tier1's config, comment ("log_euclidean is 10x faster"), and the manuscript all claimed Log-Euclidean. Measured on real COBRE FC: AirM fit 63.5 s vs LE closed-form 2.1 s (30×); references differ (Fro 31.9) → different features entirely. Fix: spd_utils.py added spd_log_euclidean_reference/spd_log_euclidean_mean (closed-form expm(mean log P)); TangentSpaceProjector now branches fit/transform/inverse on metric (default affine_invariant = historical); TangentPCA + RiemannianEngine forward it. Verified: LE finite, SPD, round-trip err 0.0010; AirM unchanged. All manifest scripts default --metric log_euclidean → canonical run is now consistently, actually LE. Manuscript §2.1 corrected ("at the identity" → "at the per-fold Log-Euclidean mean"). Saves ~3 h on the A100 run (engine.fit is per seed×fold).
  • ✅ Stats-input integration fix (tier4_statistical_tests.py::load_results) — found while wiring the manifest: the CURRENT tier4_proper_federation.py/tier4_gpu_baselines.py write flat result JSONs at output_dir/tier4_all_fl_results.json, but load_results only scanned per-condition subdirs (the pre-2026-07 legacy layout) → the stats step would silently read nothing. Now ingests BOTH layouts (root wins on collision, no double-count) + tier2_results.json (wasn't in the recognized names at all). Regression-tested on synthetic flat/legacy/both/tier2 dirs AND the real results/fl_20260730_171012 (all 9 conditions ingest; federated n_runs=40).
  • ✅ End-to-end stats run verified on REAL historical data (fl_20260730_171012): every pairwise comparison now clustered at n=4 sites with low_n_sites=True + power_warning; t_p 0.07–0.15 (none significant — the honest answer at n=4); Holm monotone; fold-clustered independent-unit CIs (e.g. local 0.4256 [0.3057,0.5335] — wide honest CI; federated 0.2377 [0.2204,0.2491]). This reframes the paper: at n=4 sites no paired FL comparison can be called statistically significant; permutation test is primary significance evidence.
  • ✅ Manuscript TBD-fill tool built + corrected against ACTUAL writer schemas (2026-08-14) — scripts/fill_manuscript_tbds.py turns a clean-run output dir into a manuscript-keyed digest so every [TBD] number has a stated source, and runs the §5 verification gates (0.5/0.0 AUC sentinels, fold-clustered n=4 / n=3, Holm monotone, permutation p-floor ~0.001; hard-fails via exit 1). First version guessed the JSON schemas; cross-checking the writer scripts (tier4_gpu_baselines.py, tier4_proper_federation.py, tier4_statistical_tests.py, tier4_permutation_test.py) exposed five real mismatches now fixed: (1) all_results is a {baseline/condition: [runs]} dict, not a flat list; (2) per-run keys are balanced_accuracy/auc_roc_macro/seed/fold (no ba, no per-run condition); (3) pairwise stat key is ttest (not t_test); (4) clustering metadata lives in pairwise_tests[algo]["clustering"]; (5) holm is a dict (adjusted_p_values list) — so the Holm-monotone gate had been silently skipped; null-distribution percentiles are at 5/50/95 (not p2.5/p97.5). Rebuilt parser reads condition_summaries (best classical), re-computes fold-clustered per-condition ordering from all_results[cond] grouped by fold, and maps federated→PQFL for readability. Verified against synthetic fixtures in the real schema: all sections parse, all gates PASS, exit 0. Real-data validation pending on the in-flight local tier1 smoke run.
  • ✅ Local tier1 smoke run COMPLETE (2026-08-14) — full leak-free tier1 3-class pipeline (1 seed, 12 rounds, --n_rounds 12 --patience 5) ran end-to-end on the local GPU box in 39.9 min: LE Fréchet mean 11–12 s/747–790 SPD matrices ✓, PCA→71 components (52–60% var) ✓, ComBat fit-on-train-only (held-out unadjusted) ✓, device fallback to lightning.qubit ✓, HybridVQC 12632 shared + 8713 personal params ✓, inner-val early-stop working per fold ✓. Held-out fold results: LA5c BA 0.34/AUC 0.605 (HC-heavy, only 17 BP — per-class penalty expected), COBRE BA 0.50/AUC 0.7315, Transdiagnostic (mid-run), KP BA 0.4748/AUC 0.4647 (2-class SZ+BP, below chance untuned). Aggregate (n=4 folds): PQFL BA 0.4159 ± 0.0833 (fold-clustered) vs SVM 0.3254 ± 0.2404; AUC 0.5750 ± 0.1041; Wilcoxon p=1.0, paired t p=0.535, d=0.349 — pipeline + statistics + JSON all correct; numbers are a 1-seed untuned sanity check, NOT paper results. tier1_results.json schema confirmed matches the fill tool's expectations.
  • ✅ TBD-fill tool validated on REAL tier1 output (2026-08-14) — ran fill_manuscript_tbds.py against the smoke run's actual tier1_results.json staged in the clean-run layout: §2.2 reads the real config keys (learning_rate, not lr; n_personal_layers/encoding_type annotated as hardcoded-in-code; n_rounds/patience annotated as argparse defaults), §3.1 PQFL/SVM numbers, statistical_tests sub-dict (wilcoxon_ba/paired_ttest_ba/cohens_d_ba), fold-clustered-n=4 and no-AUC-sentinel gates all PASS, unrun steps print MISSING, exit 0.
  • ✅ Local tier4 FL smoke COMPLETE (2026-08-14) — full 9-condition FL comparison (tier4_proper_federation.py, 3-class, 1 seed, n_rounds=2/patience=1) ran end-to-end on the local GPU in 1.4 h, exit 0: all 9 conditions × 4 LOSO folds executed with device fallback per client, early stopping firing (Early stop at round 2), per-fold train/val split selection metadata (model_selection: inner_stratified_20pct), tier4_all_fl_results.json written with the flat layout the fill tool + stats step expect (all_results = {condition: [runs]} with balanced_accuracy/auc_roc_macro/seed/fold/held_out_site; condition_summaries = {ba_mean, ba_std, auc_mean, auc_std, n_runs, n_auc_runs}). Fold-clustered ordering (smoke, 1 seed — NOT paper numbers): FedBN 0.446 → FedAvg/FedProx 0.427 → Centralized 0.414 → PQFL(federated) 0.410 → MOON 0.409 → SCAFFOLD 0.403 → FedNova 0.384 → Local 0.351, all n_sites=4. A100 step 2 is thus proven to produce ingestible output.
  • ✅ TBD-fill tool validated on REAL FL JSON (2026-08-14) — staged tier1 + tier4 smoke outputs into a clean-run layout (results/smoke_clean_stage_*) and ran fill_manuscript_tbds.py: §3.2 fold-clustered per-condition means parse + order correctly from the real all_results dict (all n_sites=4); §3.1 tier1 numbers + stat sub-dicts + gates (fold-clustered n=4, no AUC sentinels) all PASS; unrun steps (baselines/permutation/stats/binary) print MISSING; exit 0. Also fixed a residual non-ASCII in the tool's NOTE (§3.1/§2.4 → Section 3.1/2.4) that rendered as a replacement char on the Windows cp1252 console; py_compile clean.
  • ✅ TBD-fill tool validated on REAL GPU-baselines JSON (2026-08-14) — last unproven path closed — step-4 baseline smoke (tier4_gpu_baselines.py, svm_rbf + extra_trees, seed 42, 3-class LOSO, LE, exit 0 in 0.2 h) wrote the real tier4_gpu_baselines_results.json (condition_summaries = {svm_rbf BA 0.3487±0.1794/AUC 0.5793, extra_trees BA 0.3421±0.2757/AUC 0.6119}, per-run fold/seed, zero 0.0/0.5 AUC sentinels — the fold-4 BA=0.0000 is a balanced-accuracy value, not an AUC sentinel). Re-ran fill_manuscript_tbds.py on the staged clean-run dir: §3.1 "Best classical baseline" now resolves from real data (svm_rbf <-- best), gpu no-AUC-sentinel gate PASS, all §2.2/§3.1/§3.2 paths + gates PASS, exit 0. Every fill-tool path that steps 1–7 can produce is now proven end-to-end on real data; only §3.3/§3.4 (steps 7/5) still print MISSING because those smokes haven't run.
  • ⚠️ Finding #105 MEASURED: step-5 permutation test is infeasible at n_permutations=1000 (2026-08-14) — timing smoke (--n_permutations 2 --n_rounds 4 --patience 2 --device cuda) on the local box: tangent precompute 11 min (one-time, honest); Perm 1 = 16.5 min, Perm 2 = 13.9 min → 3.5–4.1 min/fold-run at 4 rounds; steady-state ~21 s/round after a one-time ~350 s compile spike. Projected per fold-run at n_rounds=50 ≈ 19–23 min → 1000 perms = 4000 runs ≈ 1300–1500 h ≈ 56–64 days local; even at an optimistic A100 10× ≈ 5.6 days just for step 5 (and #107 says the 6-qubit A100 speedup is likely much less than 10×). The manifest's 48–96 h total claim cannot include step 5 at 1000 perms. Decision pending — see the question I put to the user: fixed n=200 (p-floor 0.005) / n=100 (0.0099) / adaptive time-budget / keep 1000 with A100 pre-benchmark. Any choice also requires the fill-tool §3.4 gate to become n-consistent and a docs/manuscript disclosure of the actual floor.
  • ✅ Finding #106 FIXED: tier4_permutation_test.py has never completed end-to-end (2026-08-14) — the timing smoke ran all 8 PQFL runs + p-values, then crashed at logger.info() (lines 272/277, no msg arg → TypeError on any Python) before writing tier4_permutation_results.json. On the A100 this would have burned days then died with no output. Fixed → logger.info(""); py_compile clean. End-to-end JSON re-verification bundled with the #105 n_permutations re-run.
  • ⚠️ Finding #107: create_device prefers lightning.gpu for the 6-qubit flagship, contradicting the library's own recommend_backend (CPU beats GPU at ≤20 qubits per simulator.py docstring + recommend_backend). On the A100 the flagship will run lightning.gpu — likely slower than lightning.qubit for 6 qubits — so the assumed A100 speedup may not materialize, making #105 worse. USER DECISION (2026-08-14): keep lightning.gpu first — no code change. Documented in docs/PUBLICATION_CLEAN_RUN.md §3 (record which backend actually ran; A/B it in the step-7 smoke if convenient).
  • ✅ Manifest restructured for the deferred permutation decision (2026-08-14) — per user decision, step 5 (permutation) now runs last as step 7 (after binary step 6), with a loud DEFERRED banner + the exact 2-permutation smoke command to size --n_permutations from measured per-permutation wall time on the target box, and a note that the p-value floor 1/(n+1) must be disclosed in the manuscript. Steps 1–6 unchanged (~48–96 h on one A100); step 7 is additional and sized by the chosen n. Header + closing echoes updated; bash -n clean.
  • ✅ Fill-tool §3.4 p-floor gate made n-consistent (2026-08-14) — no longer hard-codes "floor ≈ 0.001": it now checks internal consistency floor == 1/(n_valid+1) (hard-fail on mismatch) and WARNs (not fails) below n=200, since n is a deferred decision. py_compile clean.
  • ⏳ Step-5 re-run smoke launched (2026-08-14) — after the #106 crash fix, a fresh 2-permutation measure run (smoke_permutation_measure2) verifies the script completes end-to-end and writes tier4_permutation_results.json, and gives a real per-permutation number to size n from (the user will decide n after a smoke, then run the full step 7 last).
  • ✅ Step-5 re-run smoke COMPLETE + §3.4 fill-tool path proven (2026-08-14) — tier4_permutation_test.py now runs end-to-end and writes the JSON (crash fix #106 verified). Warm-box per-permutation time at n_rounds=4: 4.55 min (Perm 1 = 4.6, Perm 2 = 4.5; the 16.5-min cold run was compile warmup). null BA 0.337 / AUC 0.509 vs real 0.416 / 0.575; empirical p=0.333 (n=2, not meaningful). Staged into the clean-run layout: fill-tool §3.4 reads real_pqfl/null_distribution/empirical_p_values from the real JSON, the n-consistent p-floor gate PASSes (floor 0.333 = 1/(2+1)) and the n<200 gate-warn prints (finding #105 disclosure note). Every fill-tool path from steps 1–7 is now proven end-to-end on real data. Extrapolation for the n decision: warm steady-state ~17 s/fold-round → 50-round fold-run ≈ 14–18 min → 1000 perms ≈ 39–50 days local, ~4–10 days on the A100 (finding #105 robust).
  • ✅ Binary tier1 smoke COMPLETE (2026-08-14) — 2-class LOSO, 1 seed, 12 rounds, into the staged 7_tier1_2class/ — end-to-end proves the #103/#104 per-site KP-drop (3 sites / 423 = 135 SZ / 288 HC, [SKIP] KagglePsychosis in the log): PQFL BA 0.575 ± 0.071 (fold-clustered, n=3) / AUC 0.635; SVM BA 0.500 ± 0.000 / AUC 0.672. Fill-tool §3.3 now resolves from real data with the n=3 gate PASS. These are 1-seed untuned smoke numbers, NOT paper results.
  • ✅ Tier2 baselines smoke COMPLETE (2026-08-14) — tier2_baselines.py (mlp, 3-class LOSO, seed 42) ran end-to-end in 160 s, exit 0, wrote 3_tier2_baselines_3class/tier2_results.json (ingestible by the stats step load_results tier2 path).
  • ✅ ALL-FILL-TOOL-PATHS MILESTONE (2026-08-14) — final fill_manuscript_tbds.py run against the complete staged clean-run layout (results/smoke_clean_stage_20260814_035013, all 7 step-dirs present) resolves every section from real data: §2.2 config, §3.1 PQFL vs SVM + best classical (svm_rbf <-- best), §3.2 all 9 FL conditions fold-clustered + Holm monotone PASS, §3.3 binary n=3 gate PASS, §3.4 permutation n-consistent p-floor gate PASS + n<200 gate-warn (finding #105), §3.5 Part B off, §3.6 consumers noted. ALL gates PASS, exit 0. Every manifest step (1–7) and every fill-tool path is now proven end-to-end on real data; the canonical A100 run is a scaling exercise (10 seeds / 50 rounds), not a protocol risk.
  • ✅ Deployment verifier BUILT (2026-08-14) — closes the no-git gap — scripts/verify_deployment.py + scripts/deployment_manifest.json (sha256 of the code tree): on the A100, python scripts/verify_deployment.py verify . scripts/deployment_manifest.json proves the copied code matches the source of truth byte-for-byte, listing any missing/changed file. Manifest scope = 151 files of code+shell+docs+configs (1.7 MB); data/, results/, __pycache__, lp-dev/, nilearn_cache/, sweep_results/, zips/logs excluded; verifier also reports the 4 *_processed.npz data sites present by name. Tested: clean source → PASS/exit 0; tampered+partial copy → FAIL/exit 1 listing the exact mismatched file. py_compile clean. Runbook §2b updated with the verify step + the two new files added to the deploy table.
  • ✅ §4 post-suite consumers — three latent crashes/stat-defects fixed (2026-08-14), then validated end-to-end on real data (findings #108–#110) — the last unproven layer of the pipeline (these feed manuscript §3.6 secondary analyses):
    • tier4_external_validation.py had NEVER completed end-to-end (#108): len(train_labels) used before assignment (NameError), numpy-int64-keyed label-distribution dicts crashed the final json.dump after all training finished, and Mode-2's 3-class mask (labels < 3) wrongly kept Other=2 as a class. Fixed all three + ba_std→None at n_seeds<2. Validated: Mode-1 hold-out COBRE (3-class, --combat, 1 seed, n_rounds=4) → exit 0, JSON written, train dist {0:351,1:214,2:225} correct.
    • tier4_combat_leakage_analysis.py (#109): flat (seed×fold) paired t-tests behind >=5 gates (9-site assumption) → replaced with fold-clustered paired (mean across seeds within fold, n=4, LOW-n disclosure). Validated: exit 0, JSON written; Leakage-vs-Correct t=0.010/p=0.993 (smoke), all 3 arms report.
    • tier4_calibration_analysis.py (#110): is a stub that cannot compute ECE/Brier (real conformal analysis is tier3_uncertainty.py); now ingests the flat canonical FL layout, warns loudly, and runbook §4 + manuscript §3.6 corrected to name tier3_uncertainty.py as the calibration source and fill_manuscript_tbds.py+statistical_tests.json as the primary metrics report (legacy category_a_metrics.py reads old-layout paths and must not be run on the clean-run output). Validated: all 9 conditions ingested from the flat layout, exit 0.
    • Deployment manifest regenerated + re-verified clean (151 files); runbook §2b table now lists the three fixed consumers.
  • ✅ Manuscript de-hardcoded for the deferred permutation n (2026-08-14) — manuscript/PQFL_manuscript_draft.md no longer claims "N=1,000 label permutations, p floor ≈0.001" (would be wrong under any deferred-n choice). §2.4 now states the permutation test is primary with N sized from the run-box per-permutation benchmark (finding #105) and p floor 1/(N+1) disclosed in Results; §3.4 [TBD] note updated to match. All other permutation mentions (Abstract/Discussion/D1) were already n-agnostic; verified by grep — no hard-coded 1000/0.001 remains.
  • ✅ Finding #111 FIXED: analyze_tier5_results.py loaders expected per-condition subdirs neither producer writes — B2 would silently compare nothing (2026-08-14) — tier5_improved_pqfl.py writes a single flat tier5_dir/tier5_results.json and manifest step 2 a single flat tier4_dir/tier4_all_fl_results.json (both condition_summaries + all_results per condition), but load_tier5_results scanned tier5_dir/*/tier5_results.json and load_tier4_results scanned tier4_dir/<cond>/tier4_all_fl_results.json → both returned {}, so B2's ablation table + fold-clustered paired tests would compare nothing while looking like they ran. Fix: both loaders now read the flat file first via a shared _consolidate_flat() (honours stored summaries, rebuilds from records if absent) with the legacy per-subdir layout as fallback (keeps pqfl_improvements/scripts/run_tier5_full.sh's per-condition style working). Fixed copy synced over the stale pqfl_improvements/analyze_tier5_results.py (2026-08-11; they were identical pre-fix, and tier5_improved_pqfl.py is identical in both trees). Validated on real flat outputs: 9 tier4 conditions ingest, fold-clustered improved_pqfl_vs_* paired stats with low_n_sites, combined summary table. Manifest regenerated + verify PASS.
  • ✅ Finding #112 FIXED: Part-B harnesses crash on size-1 last batch (BatchNorm); hyperparameter_sweep --mode random feeds torch a np.int64 batch_size (2026-08-14) — first end-to-end Part-B smokes exposed two latent defects:
    • (a) PQFLClient.fit crashed (ValueError: Expected more than 1 value per channel ... torch.Size([1, 35])) in final_training.py/analyze_significance.py/evaluate_pqfl_cv.py: the inner-val 80% split leaves sel=225 samples and 225 % 16 == 1, so the DataLoader's last batch is 1 sample and the encoder BatchNorm1d cannot train on it — deterministic whenever sel_size % batch_size == 1. Fix: PQFLClient.fit now skips size-1 training batches (one-time warning) — a size-1 batch carries no meaningful normalization statistics; this guard protects every consumer that trains through PQFLClient (tier1/tier2/tier4/tier5/experiments) from the whole crash class. Previously-passing smokes are unaffected (they had no size-1 batches, which would have crashed).
    • (b) hyperparameter_sweep.py --mode random failed every trial (batch_size should be a positive integer value, but got batch_size=16): rng.choice(values) returns numpy.int64, and numpy≥2.4 np.int64 is not isinstance(int) (verified numpy 2.4.6), so torch's strict DataLoader check rejects it. Fix: generate_configs random branch casts np.integer → native int.
    • Validated: all four harnesses re-run clean at smoke scale (final_training/analyze_significance/evaluate_pqfl_cv: 3 folds × 2 rounds; sweep: 2 random trials × 2 folds × 2 rounds) — see the in-flight smoke log; py_compile clean; manifest regenerated + verify PASS.
  • ✅ Finding #113 FIXED: improved_pqfl_no_reupload (tier5 v2 ablation) fails — TorchLayer requires a shape for every non-input parameter in the QNode (2026-08-14) — the condition FAILED in every fold with ValueError: Must specify a shape for every non-input parameter in the QNode (from pennylane/qnn/torch.py::_signature_validation). Root cause: with reupload=False, the QNode kept reupload_weights=None in its signature while weight_shapes omitted it; PennyLane 0.44 demands set(weight_shapes) | {input_arg} == set(signature.keys()) exactly. Fix: create_hea_reupload_circuit refactored into a shared _hea_circuit_body(...) + two thin qnode wrappers — reupload_weights present in the signature when reupload=True, absent when False. Unit-verified both paths build + forward finite through qml.qnn.TorchLayer. py_compile clean. Full 5-condition tier5 smoke re-run completes all conditions (was previously stuck at 4/5).
  • ✅ Finding #114 FIXED: analyze_significance.py held-out loop + saliency phase crash on CUDA — batches never moved to the model's device (2026-08-14) — after the #112a guard unblocked training, the harness crashed at the end of fold 1 with RuntimeError: Expected all tensors to be on the same device ... mat1 is on cpu ... cuda:0 (encoder Linear, vqc.py:127). The hand-rolled held-out loop read x = batch["tangent_features"] and called client.model(x, …) directly, but the model is on CUDA after PQFLClient construction — PQFLClient.evaluate() moves batches, this loop didn't. The same latent bug sat in Phase 3 compute_saliency_maps (CPU X/fdt into CUDA model). CPU-only runs masked both. Fix: held-out loop moves x/y/fdt to device and returns predictions via .cpu().numpy(); compute_saliency_maps moves inputs to next(model.parameters()).device. Re-ran end-to-end on CUDA: all folds + DeLong/McNemar/bootstrap + saliency complete, analysis_results.json + figures written.
  • ✅ Finding #115 FIXED: evaluate_pqfl_cv.py crashes writing cv_results.json — NameError: name 'engine' is not defined (2026-08-14) — after a fully successful CV run, the crash happened at the last statement before save: "pca_variance_explained": float(engine.tangent_pca.total_explained_variance). Root cause: engine was only ever a local inside transform_fold (which returns (X_train, X_val, variance), not the engine) — the summary block referenced it out of scope, so no results were ever written after ~6 min of training. Fix: main now captures the per-fold variance transform_fold already returns into fold_variances and reports float(np.mean(fold_variances)) (guarded to None). Re-ran end-to-end: cv_results.json written with pca_variance_explained=0.7102 (matches logged tangent-space variance). py_compile clean.
  • ✅ Finding #116 FIXED: tier5 v2 eval silently drops AUC for held-out folds missing a class (2026-08-14) — hybrid_strategy.py::ensemble_evaluate/single_model_evaluate called roc_auc_score(y_val, probs, multi_class='ovr', labels=val_classes) with the full n_classes-column probs but fewer labels; sklearn 1.8 routes 2-column-y_score+2-class-y_true to the binary path and raises on the 2D y_score, so the except swallowed it → auc=None. In the 3-class LOSO smoke, fold 2 (held-out COBRE {SZ,HC}) logged AUC=N/A for every condition (fold 1, 3-class LA5c, had real AUCs). In the canonical run this hits 2 of 4 folds (COBRE no-BP, KP no-HC) → v2's auc_mean averaged over half the folds while tier1/tier4 computed per-present-class AUC. Fix: per-class binary AUC over the classes present in y_val (identical to the suite-wide metrics.compute_classification_metrics pattern), None only when uncomputable. Unit-verified: {0,1}→0.529 (was None), {0,2}→0.445 (was None), 3-class→0.5475 (unchanged), single-class→None. Fixed copy synced over the stale pqfl_improvements/pqfl/federated/hybrid_strategy.py. py_compile clean; manifest regenerated + verify PASS. (The in-flight tier5 smoke predates the fix — its fold-2/4 AUCs are N/A; the canonical A100 run uses the fixed code.)
  • ✅ Finding #117 FIXED: deploy manifest silently dropped the pqfl/data/ code package → A100 import crash No module named 'pqfl.data' (2026-08-14) — the user's first canonical A100 run printed the correct pre-flight site check (4 sites / 936) then crashed at import in tier1/tier2/tier4 (tier1_enhanced_training.py:53 from pqfl.data.dataset import ...). Root cause: verify_deployment.py::collect excluded any path whose any component matched an output-dir name (EXCLUDE_DIRS incl. "data"), so pqfl/data/ (a code subpackage: dataset loaders, site partitioning) was excluded together with the top-level data/ (the npz dir). The manifest had 0 of the 6 pqfl/data/* files, so the verifier's local "PASS 151/151" was meaningless for manifest completeness — it only checks listed files. Fix: exclusion split into EXCLUDE_TOP_LEVEL (first path component only: data, results, analysis_results, cv_results, final_results, figures, lp-dev, sweep_results) + EXCLUDE_ANY_DEPTH (__pycache__, .git, .claude, nilearn_cache); pqfl/data/ now ships. Rebuilt E:\PQFL_Full_Project\pqfl_deploy_full_20260814.tar.gz (v2, 56.4 MB) with a regenerated 157-file manifest (was 151; +6 pqfl/data/*), all 4 anon npz, updated DEPLOY_README.txt (extract is idempotent over the old tree — it adds pqfl/data/ and refreshes the manifest/verifier). Proven end-to-end: extract → verify → PASS 157/157, 4/4 sites; import pqfl.data.dataset etc. succeeds (the exact crash). The user's empty results/publication_clean_20260814_144159/ dir (created pre-crash) contains no results and will be recreated.
  • ✅ Finding #118 FIXED: -> qml.Device: return annotation crashes at import on the A100 — Python-version-dependent lazy-annotation bug (2026-08-14) — after the #117 fix, the second A100 run passed the site pre-flight then crashed at import in the whole quantum tier: AttributeError: module 'pennylane' has no attribute 'Device' (raised from simulator.py:152 ) -> qml.Device:). Root cause is a Python-version asymmetry, not a code logic bug: the dev box runs Python 3.14, where PEP 649 makes all annotations lazy (never evaluated at def time), so qml.Device — which does not exist in PennyLane 0.44 (renamed to pennylane.devices.Device/LegacyDevice) — was never looked up locally and every local tier1 smoke passed. The A100 runs Python 3.11, where annotations are eagerly evaluated at import → qml.Device lookup → AttributeError. Local re-proof confirmed the asymmetry: qml.Device raises on 3.14 too, but import pqfl.quantum.simulator succeeds on 3.14 while it crashes on 3.11. Fix: from __future__ import annotations added to all 24 run-chain modules carrying module-attribute annotations (qml.Device, Tuple[qml.QNode, Dict], np.ndarray, torch.Tensor, torch.optim.lr_scheduler.LambdaLR, pd.DataFrame) — making every annotation lazy on all Python versions (≥3.7), so the chain imports identically on 3.11 and 3.14 and the whole "annotation references a symbol absent in one env" bug class is gone. Files: pqfl/quantum/{simulator,rqfm,rqfm_v2,vqc,vqc_v2,kernels}.py, pqfl/baselines/classical.py, pqfl/data/{dataset,fc_construction,fmri_pipeline}.py, pqfl/evaluation/saliency.py, pqfl/federated/{client,hybrid_strategy}.py, pqfl/harmonization/combat.py, pqfl/riemannian/{aggregation,engine,spd_utils,tangent_space}.py, and the pqfl_improvements/ mirrors (rqfm_v2.py, vqc_v2.py, hybrid_strategy.py, analyze_tier5_results.py) + analyze_tier5_results.py + experiments/train_pqfl_phase2.py. dataset_adapters.py already had it. Verified: no get_type_hints/inspect/__annotations__ anywhere (safe), py_compile clean ×24, all 16 manifest entrypoints import, create_device(6) works. Rebuilt pqfl_deploy_full_20260814.tar.gz (v3), re-proven end-to-end. Process lesson recorded in the runbook: the pre-flight import smoke (import tier1_enhanced_training, ...) is now mandatory before the 48–96 h run, and the DEPLOY_README lists the exact commands (import smoke + version report) so any remaining env drift is caught in seconds, not at hour 30.

Canonical A100 re-run manifest: pqfl_project/scripts/run_publication_clean.sh + pqfl_project/docs/PUBLICATION_CLEAN_RUN.md (3-class primary SZ/HC/BP, binary SZ-vs-HC secondary, leak-free LOSO, 10 seeds, ComBat fit-on-train-sites-only, pre-flight site-count check with allow_pickle=False, per-script expected outputs, verification gate list, manuscript disclosure checklist). Steps 1–7 sequential: tier1-3class → tier4-FL-3class → tier2-3class → tier4-baselines-3class → statistical-tests-3class → tier1-2class → permutation-3class LAST (step 7), --n_permutations a deferred decision sized from the 2-perm smoke on the A100 (finding #105; p-floor 1/(n+1) disclosed). Part B (off by default): tier5-v2 ablation table (5 conditions) + v1-vs-v2 fold-clustered analysis + binary significance harnesses. All CLI flags verified against the scripts.

IN-PROGRESS (2026-08-14, ~06:20): the fixed tier5 smoke re-run (results/smoke_tier5_20260814_0830, 3-class LOSO 4 folds × 5 conditions × 1 seed × 3 rounds) is running to produce the complete 5-condition flat tier5_results.json (finding #113). Fold 1 fully complete — all 5 conditions incl. no_reupload PASSED, 0 FAILED; fold 2 complete, fold 3 in progress (all conditions PASSING). Caveat: this in-flight smoke predates the finding #116 AUC-eval fix, so its fold-2/4 AUCs log N/A for 2-class held-out folds — expected; the canonical A100 run uses the fixed code. The other Part-B consumers are already validated end-to-end (final_training ✓, analyze_significance ✓, evaluate_pqfl_cv ✓, hyperparameter_sweep ✓). On completion: run analyze_tier5_results.py --tier5_dir results/smoke_tier5_20260814_0830 --tier4_dir results/smoke_clean_stage_20260814_035013/2_tier4_fl_3class to prove B2, then report firing. Deployment manifest regenerate + verify already PASS (151/151) after all edits incl. #116.

UPDATE (2026-08-14, ~06:52) — PART B CLOSED: tier5 re-run COMPLETED (exit 0, 0.8 h, 0 FAILED) — all 5 conditions wrote the flat results/smoke_tier5_20260814_0830/tier5_results.json; per-fold records confirm fold-2/4 (COBRE/KP, 2-class held-out) log AUC=None exactly as #116 predicted for pre-fix code, and the harness's own summary averaged only the 2 computable folds (IMPROVED_PQFL AUC=0.5777±0.0140 = mean of folds 1/3). B2 analysis proven end-to-end: analyze_tier5_results.py --tier5_dir results/smoke_tier5_20260814_0830 --tier4_dir results/smoke_clean_stage_20260814_035013/2_tier4_fl_3class --output_dir results/smoke_tier5_analysis loaded 5 tier5 + 9 tier4 conditions, wrote summary_table.csv/.md, per_fold_breakdown.csv, statistical_tests.json (9 paired t-tests), and both figures. Smoke caveat (disclosed, canonical-run-clean): the smoke table's tier5 AUC_mean averages 2 folds vs tier4's 4 (pre-#116 code); the canonical run's fixed code computes per-class AUC on all folds, so the real comparison is apples-to-apples. ALL PART-B LOCAL VALIDATION COMPLETE. Remaining: user-side A100 sync → verify → canonical run → step-7 permutation sizing → fill-tool/§4 consumers.

UPDATE (2026-08-14, ~06:55) — DEPLOY ARTIFACT READY: final pre-sync verify_deployment.py verify re-run → PASS (151/151, 4 data sites found). Built E:\PQFL_Full_Project\pqfl_deploy_20260814.tar.gz (code-only, 153 files, 0.42 MB) from the manifest scope and proved it locally: extract + verify → 151/151 identical, RESULT: PASS. The loop has reached the user-side boundary — no automatable work remains; everything downstream is A100-side. Handoff commands are in the "Still-open user actions" section.

UPDATE (2026-08-14, ~07:00) — MANUSCRIPT FACTUAL AUDIT PASS (v0.1). Re-verified every pre-fillable factual claim in manuscript/PQFL_manuscript_draft.md against the source of truth — all correct, zero stale claims: (i) §2.1 dataset numbers vs the actual *_processed.npz files — COBRE 146 (72 SZ/74 HC), KP 471 (288 SZ/183 BP), LA5c 189 (50/122/17), Transdiag 241 (13/92/111/25), total 1047; 3-class pool 936 = 423 SZ/288 HC/225 BP; binary 423 = 135 SZ/288 HC (KP dropped). (ii) §2.2 flagship config vs tier1_enhanced_training.py BASE_CONFIG + manifest override — 6 qubits (code default 8, but the manifest passes N_QUBITS=6), 2 base (n_base_layers=2) + 1 personal (n_personal_layers=1 hardcoded), angle encoding, dropout 0.5, batch 16, lr 5e-4, label smoothing 0.1. (iii) §3.5 Part B paths match the manifest ($OUT/B1_tier5_v2_3class, $OUT/B2_tier5_analysis). The 14 remaining [TBD]s are all result numbers (correctly deferred to the canonical run). Post-run, only the fill tool's numeric outputs remain.


⚠️ Still-open user actions

  1. A100 deploy — v3 payload is ready and PROVEN (2026-08-14, findings #117 + #118): E:\PQFL_Full_Project\pqfl_deploy_full_20260814.tar.gz (56.4 MB) = the 157-file code tree (incl. pqfl/data/ — finding #117 — and the 24 annotation-laziness fixes so the run chain imports on the A100's Python 3.11 — finding #118) + the 2 verifier tools + data/processed/ with all 4 *_processed.npz sites (anonymized copies, byte-identical arrays, no original subject keys — never share those) + DEPLOY_README.txt. Locally re-proven: extract → verifier → 157/157 identical, 4/4 data sites, RESULT: PASS; all 16 manifest entrypoints import and create_device(6) works from the extracted tree. Re-extracting over your current A100 tree is idempotent (adds/changes only code + manifest; data/ and results/ untouched). Then:
    tar -xzf pqfl_deploy_full_20260814.tar.gz        # safe to run over the old tree
    cd pqfl_project && python scripts/verify_deployment.py verify . scripts/deployment_manifest.json
    # expect: RESULT: PASS - the A100 code copy matches the source of truth.  (157 files, 4 data sites)
    # MANDATORY pre-flight (catches any remaining env drift in seconds, not at hour 30):
    python -c "import tier1_enhanced_training, tier2_baselines, tier4_proper_federation, tier4_gpu_baselines, tier4_statistical_tests, tier4_permutation_test; print('ALL ENTRYPOINTS IMPORT OK')"
    python -c "from pqfl.quantum.simulator import create_device; print('device:', create_device(6).name)"
    python -c "import pennylane, torch, numpy, scipy, sklearn; print('PL', pennylane.__version__, '| torch', torch.__version__, '| np', numpy.__version__, '| scipy', scipy.__version__, '| sk', sklearn.__version__)"
    conda activate quantum311 && bash scripts/run_publication_clean.sh   # steps 1–6, ~48–96 h
    
    Before step 7, run the 2-permutation smoke the banner prints, read per-permutation time, set --n_permutations (p-floor 1/(n+1) must be disclosed). Full instructions: docs/PUBLICATION_CLEAN_RUN.md §2b/§3.
  2. Revoke the Synapse PAT (was at download_brainlat.py:5).
  3. Decide fate of Dataset.zip, lp-dev/, manifest*.csv.
  4. Decide whether to git init the repo (recommended) — .gitignore is ready.