junidude14 commited on
Commit
89263db
·
verified ·
1 Parent(s): b13088d

Archive 4 checkpoints (1-4)

Browse files
.gitattributes CHANGED
@@ -81,3 +81,5 @@ paper-releases/pbisc-diffusion/updates/20261002T022002Z-deck-time-to-apply-scsem
81
  paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf filter=lfs diff=lfs merge=lfs -text
82
  paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
83
  paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec01_slide_a.pdf filter=lfs diff=lfs merge=lfs -text
 
 
 
81
  paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf filter=lfs diff=lfs merge=lfs -text
82
  paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
83
  paper-releases/pbisc-diffusion/updates/20261002T085943Z-deck-restructure-contrast-metrics-zeroshot-len/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec01_slide_a.pdf filter=lfs diff=lfs merge=lfs -text
84
+ paper-releases/pbisc-diffusion/updates/20261003T105229Z-deck-cross-cohort-loco-k1000/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf filter=lfs diff=lfs merge=lfs -text
85
+ paper-releases/pbisc-diffusion/updates/20261003T105229Z-deck-cross-cohort-loco-k1000/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx filter=lfs diff=lfs merge=lfs -text
paper-releases/pbisc-diffusion/updates/20261003T105229Z-deck-cross-cohort-loco-k1000/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pdf ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7029e8bfb338531ab52973e2ea9c63c8ca5b7b1e86b3aa77b4702a89710f07a0
3
+ size 6539814
paper-releases/pbisc-diffusion/updates/20261003T105229Z-deck-cross-cohort-loco-k1000/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_paper_summary_20260930.pptx ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:44022fdd49d0de8d42863a82f85ac76ee29f5ab7b09a54278f7e660df8e28688
3
+ size 7370841
paper-releases/pbisc-diffusion/updates/20261003T105229Z-deck-cross-cohort-loco-k1000/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/README.md ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PBISC-Diffusion paper summary deck (2026-09-30, r00; restructured 2026-10-02)
2
+
3
+ 35-slide English summary of the PBISC-Diffusion (Model 8) paper experiments: title, outline and 10 sections
4
+ (33 content slides). There is no Backup section: every slide sits in the section it supports. Short keyword lines
5
+ only; the figures carry the results. Every slide that uses a published method, metric or baseline has a one-line
6
+ "References:" footer; full citations are in the speaker notes. Section 10 is planned work.
7
+
8
+ - `PBISC-Diffusion_paper_summary_20260930.pptx`: the deck
9
+ - `PBISC-Diffusion_paper_summary_20260930.pdf`: LibreOffice PDF of the deck
10
+ - `data/slides_spec.json`: slide order, titles, keywords, footnotes, references, speaker-note text
11
+ - `generate_deck.py`: builds the pptx from `data/slides_spec.json` only (python-pptx)
12
+ - `figures/`: exactly the figures the slides show (PNG + PDF), made by `tools/sec*.py`. Intermediate panels go to a
13
+ temporary folder; superseded figures are deleted, not kept (2026-10-02, user request; every deleted file was
14
+ checked to be in the paper archive by sha256 first).
15
+ - `data/sec*.csv` and `data/*_slide_text.json`: every plotted or quoted number with its source path
16
+ - `render/`: PDF and 70-dpi slide JPGs for checking
17
+
18
+ ## Slide order
19
+
20
+ | section | slides |
21
+ |---|---|
22
+ | 1 Model overview | bulk in, cells out; denoiser |
23
+ | 2 Backbone | SDD → PBISC-Diffusion; bulk conditioning |
24
+ | 3 Architecture ablation | width & context (loss, benchmark); gene panel |
25
+ | 4 Metrics + SLE benchmark | **how we score generated cells** (metric table with references); SLE benchmark; per cell type; bulk broadcast baseline |
26
+ | 5 Real bulk vs pseudobulk | input shift; same shift in three cohorts; cells off-manifold; disease direction flips |
27
+ | 6 Paired fine-tuning | method; evaluation design |
28
+ | 7 LoRA ablations | full vs LoRA vs cond.-encoder-only; LoRA rank r = 4 / 16 / 64; K diversification |
29
+ | 8 Pairs needed | composition / coverage / steps; donor and disease signal |
30
+ | 9 Paired validation | cohorts; 5 donors: cells, realism beyond P/C, P/C at k = 3 / 5 / 10, scSemiProfiler copies its representative, disease signal, CAT curves, time to apply; 5-fold CV and its realism metrics |
31
+ | 10 Paired-subset cohorts | planned |
32
+
33
+ ## Rebuild
34
+
35
+ Everything is CPU only; no GPU or checkpoint is touched.
36
+
37
+ ```bash
38
+ # prerequisites (plan folder plans/paired_finetune_intradataset_20260927/, CPU):
39
+ # scsemi/tools/representative_dependence.py -> scsemi/analysis/representative_dependence_20261002/
40
+ # tools/contrast_extra.py (+ tools/contrast_extra_tables.py) -> scores_contrast/ (Spearman, ceiling, limma, CAT, RBO)
41
+ # tools/build_tpm_zeroshot.py + tools/score_tpm_zeroshot.sh -> scores/<ds>/zeroshot_tpm_20261002/pooled/
42
+ # (the length-corrected zero-shot arm needs one GPU sampling step: tools/sample_lockwait.sh, coordinator only)
43
+ cd /home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00
44
+ # shared helpers, not run directly: style.py, sec03_common.py, scsemi_results.py, fold_sizes.py
45
+ for f in sec01_overview sec02_backbone sec03_width_loss sec03_width_bench sec03_panel \
46
+ sec04_metrics_overview sec04_sle_benchmark sec05_condition_space sec05_cells_offmanifold \
47
+ sec05_behcet_direction sec05_shift_cohorts sec06_finetune_method sec07_ft_modes \
48
+ sec07_k_aug sec07_rank_sweep sec08_pairs_needed sec08_cross_cohort sec09_paired_validation sec09_extra_metrics \
49
+ sec09_time_to_apply sec09_scsemi_representative sec09_cat_curves sec10_paired_subset_cohorts; do
50
+ python3 "tools/$f.py" || break
51
+ done
52
+ python3 tools/sync_sec09_text.py # copy every generated slide text (sec09_index / text_source) into the spec
53
+ python3 generate_deck.py # -> PBISC-Diffusion_paper_summary_20260930.pptx
54
+ soffice --headless --convert-to pdf --outdir render PBISC-Diffusion_paper_summary_20260930.pptx
55
+ pdftoppm -jpeg -r 70 render/PBISC-Diffusion_paper_summary_20260930.pdf render/slide
56
+ cp render/PBISC-Diffusion_paper_summary_20260930.pdf .
57
+ ```
58
+
59
+ `generate_deck.py` stops with an error if a figure is missing, a title does not fit on one line, a footnote needs
60
+ more than 2 lines (1 line when the slide has references), the reference line needs more than 1 line, or any text
61
+ contains Korean or placeholder words. `tools/restructure_20261002.py` is the one-off script that produced the current
62
+ slide order and the references (it refuses to run twice).
63
+
64
+ ## Notes
65
+
66
+ - **No "all" label (2026-10-02).** The 5-fold arm trains each fold model on the other four folds minus 7–8
67
+ inner-validation donors; its test fold is never trained on (RUN.json `test_rows_never_loaded_for_training`). Figures
68
+ label it "5-fold CV (other 4 folds)" and learning-curve ticks show the training-pair count per fold (78–79 ImMicro,
69
+ 58–59 sepsis), read by `tools/fold_sizes.py`.
70
+ - **Learning curve x = 0 uses no pairs (2026-10-02).** It shows the zero-shot model fed the real bulk as measured
71
+ and after exon-length correction (counts / Ensembl union-exon kb, then the same fixed-depth arithmetic;
72
+ `plans/.../tools/build_tpm_zeroshot.py`, scored in `scores/<ds>/zeroshot_tpm_20261002/pooled`). The old x = 0
73
+ calibration point, whose alpha used every training pair of the fold, is gone; calibration appears only fitted on the
74
+ same n pairs as the LoRA point (squares; `cal_budget_20261001`).
75
+ - **Disease metrics (2026-10-02).** Next to Pearson logFC r and the Welch top-50 DEG overlap: Spearman r, the
76
+ split-half ceiling (observed vs observed, Spearman–Brown), limma-voom top-50 DEG, each arm's chance overlap, and
77
+ CAT curves with the k / 2G chance line (`plans/.../scores_contrast/`, tools/contrast_extra.py; every Pearson r and
78
+ Welch count reproduced exactly). Repeated samples of one patient (Imperial, Giroux, Ji) count as separate samples in
79
+ both DE tests, as in the scorer (footnote).
80
+ - Section 9 text is generated: `tools/sec09_paired_validation.py`, `sec09_extra_metrics.py`, `sec07_rank_sweep.py`,
81
+ `sec09_time_to_apply.py`, `sec09_scsemi_representative.py`, `sec09_cat_curves.py` write slide text JSON; sync copies
82
+ it. Hand-written: the keywords of the two "Pairs needed" slides (section 8) and of every slide in sections 1–7 and 10.
83
+ - Giroux's disease metrics exclude 196 sex-linked genes (severity is confounded with sex), from
84
+ `plans/.../scores_nosex/`. The calibration comparator is "Zero-shot + calibration" (user decision 2026-10-01).
85
+ - Story rule (user decision 2026-09-30): no PBISC-VAE and no reference calibration (refcal). The exon-length-corrected
86
+ input is used only as the no-pair x = 0 point of the learning curve (user decision 2026-10-02).
87
+ `tools/sec04_immicro.py` (refcal vs scSemiProfiler on ImMicro) is kept but is not part of the deck or the rebuild.
88
+ - scSemiProfiler 5-fold and equal-budget results are picked up automatically when they appear (`tools/scsemi_results.py`;
89
+ arm `scsemi__raw` in `scores/<cohort>/scsemi_cv_20261002/pooled*/`, `scsemi_n{5,10,20,40}__raw` in
90
+ `scores/<cohort>/scsemi_budget_20261002/pooled*/`; same donors and reference cells as the main pooled call only).
91
+ Then rerun sections 8 and 9, sync, recheck the section 8 keywords and rebuild.
92
+ - Earlier versions: `_archive/2026-09-30_before_no_vae_refcal/`, `_archive/2026-10-01_before_extra_metrics/`,
93
+ `_archive/2026-10-02_before_time_to_apply/`, `_archive/2026-10-02_before_restructure/` (pptx, PDF, spec; their
94
+ figures are in the paper archive). `DRAFT_1150_*`: the copy shown at the 2026-09-30 12:00 meeting.
95
+
96
+ - Added 2026-10-03 (user decision: the cross-cohort experiment is reported at K = 1000 only and is the figure that explains
97
+ why PBISC fits LoRA on a few pairs of each cohort): slides 25-26 in section 8, `tools/sec08_cross_cohort.py`.
98
+ - Slide 25 "Pairs from other cohorts do not transfer": per held-out cohort, composition L1 / coverage / disease logFC r of
99
+ zero-shot, calibration fitted on the other cohorts, LoRA r16 / r64 / full fine-tune trained on the other cohorts
100
+ (+ Liu 2021) at step saturation, and LoRA on the cohort's own pairs (5-fold pooled).
101
+ - Slide 26 "Longer training on other cohorts: no gain": the same metrics at every 20k-step milestone.
102
+ - Source plan: `plans/paired_crosscohort_20261002/` (README; same-reference and same-sample checks in the script).
103
+ Agenda item 8 now reads "How many pairs, and do other cohorts' pairs transfer". The deck has 37 slides.
104
+ Pre-update copy: `_archive/2026-10-03_before_cross_cohort/`.
105
+
106
+ ## Sources
107
+
108
+ Final model: `runs/f01_6k_1x_seed20260627` (epoch 16, EMA). Scores and receipts come from
109
+ `plans/utility_studies_final6k_20260925/`, `plans/paired_finetune_intradataset_20260927/`,
110
+ `plans/immicro_scsemi_comparison_20260927/`, `plans/floor01_campaign_20260923/`,
111
+ `analysis/scsemi_benchmark_diffusion_20260913/` and the run folders named in each `data/sec*.csv`. Reference PDFs:
112
+ `/home/sj_server_1/PBISC/paper-release-20260928/reference-papers/` (INDEX.md). Manuscript:
113
+ `/home/sj_server_1/PBISC/paper-release-20260928/manuscript/`.
paper-releases/pbisc-diffusion/updates/20261003T105229Z-deck-cross-cohort-loco-k1000/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_cross_cohort.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Section 8 of the 2026-09-30 paper-summary deck: do bulk-sc pairs from OTHER cohorts transfer? (added 2026-10-03)
3
+
4
+ The leave-one-cohort-out (LOCO) benchmark of plans/paired_crosscohort_20261002 (user decision 2026-10-03: report
5
+ K = 1000 only and use it to explain why PBISC fits LoRA on a few pairs of each cohort instead of one cross-cohort
6
+ model). CPU only; reads score summaries and run receipts, draws two slide figures:
7
+ figures/sec08_cross_cohort.{png,pdf} FULL: composition L1, coverage, disease logFC r per held-out cohort
8
+ figures/sec08_cross_cohort_steps.{png,pdf} FULL: the same test metrics against training steps (block milestones)
9
+ data/sec08_cross_cohort.csv, data/sec08_cross_cohort_steps.csv every plotted value with its source file
10
+ data/sec08_cross_cohort_slide_text.json titles, keywords, footnotes, quoted numbers (synced into the spec)
11
+
12
+ Arms (every one scores the held-out cohort's usable samples against the same frozen reference; checked):
13
+ zero-shot base model, real bulk (zs_K1000)
14
+ calibration (other) base model, bulk x alpha fitted on the OTHER cohorts' pairs (xcalL_K1000) 0 target pairs
15
+ LoRA r16 / r64 / full fine-tuned on the other PBMC cohorts + Liu 2021 (Liu: training only), step-saturation
16
+ protocol (20k blocks, stop below 1 % block improvement); value = last milestone 0 target pairs
17
+ own-cohort LoRA LoRA r16 on the cohort's own pairs, 5-fold pooled (plans/paired_finetune_intradataset_20260927)
18
+ Giroux's logFC r excludes the 196 sex-linked genes (scores_nosex/), as everywhere else in the deck.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import json
23
+ import os
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
31
+ "2026-09-30--paper-summary--r00")
32
+ sys.path.insert(0, str(DECK / "tools"))
33
+ import style # noqa: E402
34
+ import matplotlib.pyplot as plt # noqa: E402
35
+ from matplotlib.patches import Patch # noqa: E402
36
+ from matplotlib.lines import Line2D # noqa: E402
37
+
38
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
39
+ LOCO = M8 / "plans/paired_crosscohort_20261002"
40
+ SRC = M8 / "plans/paired_finetune_intradataset_20260927"
41
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
42
+ OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
43
+ ORDER = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
44
+ NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
45
+ "ji2025_chili": "Ji (whole blood)"}
46
+ MODES = [("lora16sat", "LoRA r16"), ("lora64sat", "LoRA r64"), ("fullsat", "Full fine-tune")]
47
+ COL = {"zs": style.ARM["zs_raw"], "xcal": style.ARM["zs_cal"], "lora16sat": "#44AA99", "lora64sat": "#117733",
48
+ "fullsat": "#332288", "own": style.ARM["lora"]}
49
+ LAB = {"zs": "Zero-shot", "xcal": "Calibration from other cohorts", "lora16sat": "LoRA r16, other cohorts",
50
+ "lora64sat": "LoRA r64, other cohorts", "fullsat": "Full fine-tune, other cohorts",
51
+ "own": "LoRA on the cohort's own pairs"}
52
+ ARMS = ["zs", "xcal", "lora16sat", "lora64sat", "fullsat", "own"]
53
+ METRICS = [("comp_l1", "Composition L1\nlower = better"), ("coverage", "Coverage\nhigher = better"),
54
+ ("logfc_r", "Disease logFC r\nhigher = better")]
55
+ EDGE, SUB, FS = "#333333", "#595959", style.FS
56
+
57
+
58
+ def summary_metrics(summary_path: Path, arm: str, disease_path: Path | None) -> dict:
59
+ s = json.loads(summary_path.read_text())
60
+ h = s["headline"][arm]
61
+ out = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
62
+ "logfc_r": h.get("contrast_mean_cp10k_r_gen"), "reference_sha256": s["reference"]["reference_sha256"],
63
+ "donors": sorted(s["donors"]), "source": str(summary_path), "source_disease": None}
64
+ if disease_path is not None and disease_path.is_file():
65
+ d = json.loads(disease_path.read_text())
66
+ out["logfc_r"] = d["headline"][arm].get("contrast_mean_cp10k_r_gen")
67
+ out["source_disease"] = str(disease_path)
68
+ return out
69
+
70
+
71
+ def final_arm(cohort: str, tag: str) -> tuple[str, int, dict]:
72
+ run = json.loads((LOCO / "runs" / f"hoL_{cohort}" / "K1000" / tag / "RUN.json").read_text())
73
+ st = run["milestones"][-1]["milestone_step"]
74
+ return f"locoL_{tag}_s{st}_K1000", st, run
75
+
76
+
77
+ def loco_paths(cohort: str, arm: str) -> tuple[Path, Path | None]:
78
+ main = LOCO / "scores" / cohort / arm / "summary.json"
79
+ dis = LOCO / "scores_nosex" / cohort / arm / "summary.json" if cohort == "giroux2022" else None
80
+ return main, dis
81
+
82
+
83
+ def collect() -> tuple[pd.DataFrame, pd.DataFrame, dict]:
84
+ rows, steps, runs = [], [], {}
85
+ for c in ORDER:
86
+ refs = set()
87
+ for a, arm in (("zs", "zs_K1000"), ("xcal", "xcalL_K1000")):
88
+ m = summary_metrics(*loco_paths(c, arm)[:1], arm, loco_paths(c, arm)[1])
89
+ rows.append({"cohort": c, "arm": a, "score_arm": arm, "steps": None, **m})
90
+ refs.add(m["reference_sha256"])
91
+ for tag, _ in MODES:
92
+ arm, st, run = final_arm(c, tag)
93
+ runs[(c, tag)] = run
94
+ m = summary_metrics(*loco_paths(c, arm)[:1], arm, loco_paths(c, arm)[1])
95
+ rows.append({"cohort": c, "arm": tag, "score_arm": arm, "steps": st, **m})
96
+ refs.add(m["reference_sha256"])
97
+ for ms in run["milestones"]:
98
+ a2 = f"locoL_{tag}_s{ms['milestone_step']}_K1000"
99
+ m2 = summary_metrics(*loco_paths(c, a2)[:1], a2, loco_paths(c, a2)[1])
100
+ steps.append({"cohort": c, "mode": tag, "step": ms["milestone_step"],
101
+ "inner_val_loss": ms["selected_inner_val_loss"], "score_arm": a2,
102
+ **{k: m2[k] for k in ("comp_l1", "coverage", "precision", "logfc_r", "source",
103
+ "source_disease")}})
104
+ refs.add(m2["reference_sha256"])
105
+ own = summary_metrics(SRC / "scores" / c / "pooled" / "summary.json", "real_lora__raw",
106
+ SRC / "scores_nosex" / c / "pooled" / "summary.json" if c == "giroux2022" else None)
107
+ rows.append({"cohort": c, "arm": "own", "score_arm": "real_lora__raw", "steps": None, **own})
108
+ refs.add(own["reference_sha256"])
109
+ donors = {tuple(r["donors"]) for r in rows if r["cohort"] == c}
110
+ if len(refs) != 1 or len(donors) != 1:
111
+ raise SystemExit(f"{c}: scoring calls differ in reference or samples")
112
+ t = pd.DataFrame(rows).drop(columns=["donors", "reference_sha256"])
113
+ return t, pd.DataFrame(steps), runs
114
+
115
+
116
+ def draw_main(t: pd.DataFrame) -> None:
117
+ fig, axs = plt.subplots(len(METRICS), len(ORDER), figsize=(12.3, 5.0), sharey="row",
118
+ gridspec_kw={"hspace": 0.32, "wspace": 0.08})
119
+ x = np.arange(len(ARMS))
120
+ for j, c in enumerate(ORDER):
121
+ sub = t[t.cohort == c].set_index("arm").loc[ARMS]
122
+ for i, (key, label) in enumerate(METRICS):
123
+ ax = axs[i, j]
124
+ v = sub[key].astype(float).to_numpy()
125
+ if np.isnan(v).all():
126
+ ax.text(0.5, 0.5, "no case–control groups", ha="center", va="center", fontsize=FS - 3, color=SUB,
127
+ transform=ax.transAxes)
128
+ else:
129
+ ax.bar(x, np.nan_to_num(v), 0.78, color=[COL[a] for a in ARMS], edgecolor="none")
130
+ for xi, a in zip(x, ARMS):
131
+ if a in ("lora16sat", "lora64sat", "fullsat"):
132
+ st = sub.loc[a, "steps"]
133
+ if i == 0:
134
+ ax.text(xi, 0.012, f"{int(st) // 1000}k", ha="center", va="bottom", rotation=90,
135
+ fontsize=FS - 6, color="white")
136
+ ax.set_xticks([])
137
+ if j == 0:
138
+ ax.set_ylabel(label, fontsize=FS - 3)
139
+ if i == 0:
140
+ ax.set_title(NAME[c], fontsize=FS - 1)
141
+ ax.tick_params(axis="y", labelsize=FS - 4)
142
+ ax.axhline(0, color=EDGE, lw=0.8)
143
+ handles = [Patch(color=COL[a], label=LAB[a]) for a in ARMS]
144
+ fig.legend(handles=handles, loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.08), fontsize=FS - 3,
145
+ handlelength=1.1, columnspacing=1.4)
146
+ style.save(fig, "sec08_cross_cohort", FIGDIR)
147
+
148
+
149
+ def draw_steps(t: pd.DataFrame, st: pd.DataFrame) -> None:
150
+ mets = METRICS[:2] + [METRICS[2]]
151
+ fig, axs = plt.subplots(len(mets), len(ORDER), figsize=(12.3, 5.0), sharex=True, sharey="row",
152
+ gridspec_kw={"hspace": 0.3, "wspace": 0.08})
153
+ for j, c in enumerate(ORDER):
154
+ ref = t[t.cohort == c].set_index("arm")
155
+ for i, (key, label) in enumerate(mets):
156
+ ax = axs[i, j]
157
+ if ref[key].isna().all():
158
+ ax.text(0.5, 0.5, "no case–control groups", ha="center", va="center", fontsize=FS - 3, color=SUB,
159
+ transform=ax.transAxes)
160
+ else:
161
+ for tag, _ in MODES:
162
+ s = st[(st.cohort == c) & (st["mode"] == tag)].sort_values("step")
163
+ ax.plot(s.step / 1000, s[key], "-o", color=COL[tag], ms=3.5, lw=1.6)
164
+ for a, ls in (("xcal", "--"), ("own", ":")):
165
+ ax.axhline(ref.loc[a, key], color=COL[a], ls=ls, lw=1.4)
166
+ if j == 0:
167
+ ax.set_ylabel(label, fontsize=FS - 3)
168
+ if i == 0:
169
+ ax.set_title(NAME[c], fontsize=FS - 1)
170
+ if i == len(mets) - 1:
171
+ ax.set_xlabel("training steps (k)", fontsize=FS - 3)
172
+ ax.tick_params(labelsize=FS - 4)
173
+ handles = [Line2D([0], [0], color=COL[t_], marker="o", ms=4, lw=1.6, label=LAB[t_]) for t_, _ in MODES]
174
+ handles += [Line2D([0], [0], color=COL["xcal"], ls="--", lw=1.4, label=LAB["xcal"]),
175
+ Line2D([0], [0], color=COL["own"], ls=":", lw=1.4, label=LAB["own"])]
176
+ fig.legend(handles=handles, loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.09), fontsize=FS - 3,
177
+ handlelength=1.8, columnspacing=1.4)
178
+ style.save(fig, "sec08_cross_cohort_steps", FIGDIR)
179
+
180
+
181
+ def slide_text(t: pd.DataFrame, st: pd.DataFrame, runs: dict) -> dict:
182
+ piv = {k: t.pivot(index="cohort", columns="arm", values=k).loc[ORDER] for k, _ in METRICS}
183
+ loco = ["lora16sat", "lora64sat", "fullsat"]
184
+ best_l1 = piv["comp_l1"][["xcal"] + loco].idxmin(axis=1)
185
+ n_cal_l1 = int((piv["comp_l1"]["xcal"] <= piv["comp_l1"][loco].min(axis=1) + 0.01).sum())
186
+ own_cov = piv["coverage"]["own"]
187
+ zero_cov = piv["coverage"][["xcal"] + loco].max(axis=1)
188
+ dis = [c for c in ORDER if not np.isnan(piv["logfc_r"].loc[c, "own"])]
189
+ own_r = piv["logfc_r"].loc[dis, "own"]
190
+ zero_r = piv["logfc_r"].loc[dis, ["zs", "xcal"] + loco].max(axis=1)
191
+ n_own_cov = int((own_cov > zero_cov).sum())
192
+ n_own_r = int((own_r > zero_r).sum())
193
+ sat = {tag: [r["milestones"][-1]["milestone_step"] for (c, tg), r in runs.items() if tg == tag] for tag in loco}
194
+ ji = st[(st.cohort == "ji2025_chili") & (st["mode"] == "fullsat")].sort_values("step")
195
+ ji_first, ji_last = ji.comp_l1.iloc[0], ji.comp_l1.iloc[-1]
196
+ s1 = {"title": "Pairs from other cohorts do not transfer", "layout": "full",
197
+ "figures": [str(FIGDIR / "sec08_cross_cohort.png")],
198
+ "keywords": ["Train on the other cohorts, test the held-out one",
199
+ f"Calibration ties or beats them on composition in {n_cal_l1}/5",
200
+ f"Own-cohort pairs best on coverage {n_own_cov}/5, disease r {n_own_r}/{len(dis)}"],
201
+ "footnote_short": "Leave-one-cohort-out, K = 1000; train on the other cohorts (+ Liu 2021), test the held-out one.",
202
+ "footnote": ("Each held-out cohort is scored on all its usable samples against the same frozen reference as "
203
+ "its within-cohort benchmark. Zero-shot = base model on real bulk. Calibration from other cohorts = "
204
+ "gene-wise alpha (mean pseudobulk CPM / mean bulk CPM) fitted on the training cohorts' pairs, "
205
+ "cohort-balanced; 0 target pairs. LoRA r16 / r64 / full fine-tune = trained on the other PBMC "
206
+ "cohorts' pairs plus Liu 2021 (training only: its cells are in the pretraining corpus; 44 pairs "
207
+ "after excluding 14 hashtag-negative-heavy rows), cohort-balanced batches, inner-validation on "
208
+ "10 % of each training cohort's donors, step-saturation protocol (20k-step blocks, stop when a "
209
+ "block lowers the inner-validation loss by < 1 % of the total), value at the last milestone "
210
+ "(number in the bar = steps). Ji's bulk is whole blood and is never trained on. Own-cohort LoRA = "
211
+ "LoRA r16 on the cohort's own pairs, 5-fold pooled. Giroux's logFC r excludes 196 sex-linked "
212
+ "genes. Best on composition among zero-target-pair arms: " +
213
+ ", ".join(f"{NAME[c]} {LAB[best_l1[c]]}" for c in ORDER) + "."),
214
+ "numbers": [{"value": f"{NAME[c]}: L1 " + " / ".join(f"{a} {piv['comp_l1'].loc[c, a]:.3f}" for a in ARMS)
215
+ + "; coverage " + " / ".join(f"{a} {piv['coverage'].loc[c, a]:.2f}" for a in ARMS)
216
+ + ("; logFC r " + " / ".join(f"{a} {piv['logfc_r'].loc[c, a]:.2f}" for a in ARMS)
217
+ if c in dis else ""), "source": "data/sec08_cross_cohort.csv"} for c in ORDER]}
218
+ s2 = {"title": "Longer training on other cohorts: no gain", "layout": "full",
219
+ "figures": [str(FIGDIR / "sec08_cross_cohort_steps.png")],
220
+ "keywords": [f"Saturation: r16 by {max(sat['lora16sat']) // 1000}k, r64 by {max(sat['lora64sat']) // 1000}k, "
221
+ f"full by {max(sat['fullsat']) // 1000}k steps",
222
+ f"Full fine-tune drifts away (Ji L1 {ji_first:.2f} → {ji_last:.2f})",
223
+ "So PBISC fits LoRA on a few pairs per cohort"],
224
+ "footnote_short": "Test metrics at every 20k-step milestone (best inner-validation state so far). K = 1000.",
225
+ "footnote": ("Same runs as the previous slide. Each point = the milestone checkpoint at the end of a 20k-step "
226
+ "block (or at the early stop), sampled and scored on the held-out cohort. Dashed = calibration "
227
+ "from other cohorts; dotted = LoRA on the cohort's own pairs. Training stopped (steps): " +
228
+ "; ".join(f"{dict(MODES)[tg]} " + ", ".join(f"{NAME[c].split(' ')[0]} {runs[(c, tg)]['milestones'][-1]['milestone_step'] // 1000}k"
229
+ for c in ORDER) for tg in loco) + "."),
230
+ "numbers": [{"value": f"{NAME[c]} {dict(MODES)[tg]}: " + ", ".join(
231
+ f"{int(r.step) // 1000}k L1 {r.comp_l1:.3f} cov {r.coverage:.2f}" for r in
232
+ st[(st.cohort == c) & (st["mode"] == tg)].sort_values("step").itertuples()),
233
+ "source": "data/sec08_cross_cohort_steps.csv"} for c in ORDER for tg in loco]}
234
+ return {"section": "08-cross-cohort", "scripts": [str(Path(__file__).resolve())],
235
+ "generated_from": "tools/sec08_cross_cohort.py (rerun to refresh; do not edit by hand)",
236
+ "slides": [s1, s2]}
237
+
238
+
239
+ def main() -> int:
240
+ t, st, runs = collect()
241
+ agg = pd.read_csv(LOCO / "scores" / "aggregate.csv")
242
+ for r in t[t.arm.isin(["zs", "xcal", "lora16sat", "lora64sat", "fullsat"])].itertuples():
243
+ g = agg[(agg.cohort == r.cohort) & (agg.arm == r.score_arm)]
244
+ if len(g) != 1 or abs(float(g.comp_l1.iloc[0]) - r.comp_l1) > 1e-9:
245
+ raise SystemExit(f"{r.cohort} {r.score_arm}: differs from scores/aggregate.csv")
246
+ OUTDATA.mkdir(exist_ok=True)
247
+ t.to_csv(OUTDATA / "sec08_cross_cohort.csv", index=False)
248
+ st.to_csv(OUTDATA / "sec08_cross_cohort_steps.csv", index=False)
249
+ draw_main(t)
250
+ draw_steps(t, st)
251
+ txt = slide_text(t, st, runs)
252
+ (OUTDATA / "sec08_cross_cohort_slide_text.json").write_text(json.dumps(txt, indent=1, ensure_ascii=False))
253
+ for s in txt["slides"]:
254
+ print(s["title"]); print(" " + "\n ".join(s["keywords"]))
255
+ return 0
256
+
257
+
258
+ if __name__ == "__main__":
259
+ sys.exit(main())