junidude14 commited on
Commit
9b08c22
·
verified ·
1 Parent(s): d725efc

Archive 4 checkpoints (1-4)

Browse files
.gitattributes CHANGED
@@ -65,3 +65,5 @@ paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-fina
65
  paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec01_slide_a.pdf filter=lfs diff=lfs merge=lfs -text
66
  paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/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
67
  paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/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
 
 
 
65
  paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec01_slide_a.pdf filter=lfs diff=lfs merge=lfs -text
66
  paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/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
67
  paper-releases/pbisc-diffusion/updates/20260930T090852Z-summary-deck-final-path-story/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
68
+ paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/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
69
+ paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/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/20261001T023742Z-deck-calibration-giroux-sexgenes/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:dfcbd1f60941a714a8083949316e98ba7afc26a20600cd1c2ebe0b9e832ffd54
3
+ size 4609204
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/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:4ac766b8d690aa8ac883bd2090625ca70c7d1db54bbd6a3171f14782f278459a
3
+ size 5196206
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/README.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # PBISC-Diffusion paper summary deck (2026-09-30, r00)
2
+
3
+ 28-slide English summary of the PBISC-Diffusion (Model 8) paper experiments: title,
4
+ outline, 10 sections (23 content slides), then a Backup divider and 3 backup slides.
5
+ Short keyword lines only; the figures carry the results. Section 10 is planned work.
6
+
7
+ - `PBISC-Diffusion_paper_summary_20260930.pptx`: the deck
8
+ - `PBISC-Diffusion_paper_summary_20260930.pdf`: LibreOffice PDF of the deck
9
+ - `data/slides_spec.json`: slide order, titles, keywords, footnotes, speaker-note text
10
+ - `generate_deck.py`: builds the pptx from `data/slides_spec.json` only (python-pptx)
11
+ - `figures/`: all slide figures (PNG + PDF), made by `tools/sec*.py`
12
+ - `data/sec*.csv`, `data/sec09_slide_text.json`: every plotted or quoted number with its source path
13
+ - `render/`: PDF and 70-dpi slide JPGs for checking
14
+
15
+ ## Rebuild
16
+
17
+ Everything is CPU only; no GPU or checkpoint is touched.
18
+
19
+ ```bash
20
+ cd /home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/2026-09-30--paper-summary--r00
21
+ # figures + data tables (sec03_common.py and style.py are shared helpers, not run directly)
22
+ for f in sec01_overview sec02_backbone sec03_width_loss sec03_width_bench sec03_panel \
23
+ sec04_sle_benchmark sec05_condition_space sec05_cells_offmanifold \
24
+ sec05_behcet_direction sec05_shift_cohorts sec06_finetune_method sec07_ft_modes \
25
+ sec07_k_aug sec08_pairs_needed sec09_paired_validation sec10_paired_subset_cohorts; do
26
+ python3 "tools/$f.py" || break
27
+ done
28
+ python3 tools/sync_sec09_text.py # copy regenerated section 9 text into data/slides_spec.json
29
+ python3 generate_deck.py # -> PBISC-Diffusion_paper_summary_20260930.pptx
30
+ soffice --headless --convert-to pdf --outdir render PBISC-Diffusion_paper_summary_20260930.pptx
31
+ pdftoppm -jpeg -r 70 render/PBISC-Diffusion_paper_summary_20260930.pdf render/slide
32
+ cp render/PBISC-Diffusion_paper_summary_20260930.pdf .
33
+ ```
34
+
35
+ `generate_deck.py` stops with an error if a figure is missing, a title does not fit on one
36
+ line, a footnote needs more than 2 lines, or any text contains Korean or placeholder words.
37
+
38
+ ## Notes
39
+
40
+ - Section 9 (few-pair scSemiProfiler comparison) uses all 25 scSemiProfiler draws
41
+ (5 cohorts x 5 draws). If scores change, rerun `tools/sec09_paired_validation.py`, then
42
+ `tools/sync_sec09_text.py`, then check the short footnotes it lists and rebuild.
43
+ - Section 9 update (user decisions 2026-10-01): (1) the gene-wise calibration comparator is back,
44
+ named "Zero-shot + calibration" (few-pair `zs_cal`, alpha from the same 5 donors; 5-fold `zs__cal`)
45
+ and the sc-only control is "sc-only fine-tune (+ calibration)" (`pseudo_full__cal`); (2) Giroux's
46
+ disease metrics (logFC r, partial r, top-50 DEG, broadcast) exclude 196 sex-linked genes because its
47
+ severity is confounded with sex, read from `plans/paired_finetune_intradataset_20260927/scores_nosex/`
48
+ (see its README). Both are stated in the slide footnotes.
49
+ - On-slide footnotes are one short line; the full source and method text is in the speaker
50
+ notes (`footnote_full` in the spec).
51
+ - `DRAFT_1150_*`: frozen copy shown at the 2026-09-30 12:00 meeting (23/25 scSemiProfiler
52
+ draws, long footnotes). Superseded by the files above.
53
+ - Story rule (user decision 2026-09-30): the deck and paper do not mention PBISC-VAE, reference
54
+ calibration (refcal), the TPM input variant or any calibration arm (calibration arm reinstated
55
+ 2026-10-01 as "Zero-shot + calibration"; never "refcal"). The no-fine-tune baseline is
56
+ zero-shot on real bulk as measured; the sc-only control is the sc-only fine-tune fed raw bulk.
57
+ `tools/sec04_immicro.py` (refcal vs scSemiProfiler on ImMicro) is kept but no longer in the deck.
58
+ The pre-revision deck, scripts and figures are in `_archive/2026-09-30_before_no_vae_refcal/`.
59
+
60
+ ## Sources
61
+
62
+ Final model: `runs/f01_6k_1x_seed20260627` (epoch 16, EMA). Scores and receipts come from
63
+ `plans/utility_studies_final6k_20260925/`, `plans/paired_finetune_intradataset_20260927/`,
64
+ `plans/immicro_scsemi_comparison_20260927/`, `plans/floor01_campaign_20260923/`,
65
+ `analysis/scsemi_benchmark_diffusion_20260913/` and the run folders named in each
66
+ `data/sec*.csv`. Manuscript: `/home/sj_server_1/PBISC/paper-release-20260928/manuscript/`.
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_ft_modes.py ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Section 7, slide (a): full FT vs LoRA vs condition-encoder-only vs sc-only FT vs zero-shot + calibration vs
2
+ zero-shot, plus the compute cost (trainable parameters, wall-clock time per training step).
3
+
4
+ The fine-tuned arms (full, LoRA, condition-encoder-only) are fed the real bulk as measured (*__raw). Two zero-shot
5
+ rows bracket them: the pretrained model fed real bulk as measured (zs__raw) and fed gene-wise calibrated bulk
6
+ (zs__cal). Calibration (user decision 2026-10-01: back as a comparator): alpha_g = mean CPM(pseudobulk_g) /
7
+ mean CPM(bulk_g) over the fold's paired training donors (train + inner-val, prepare_dataset.py `fit = fold != f`),
8
+ applied as bulk CPM x alpha, then renormalised. The sc-only fine-tune never saw real bulk, so it is fed the
9
+ calibrated bulk (pseudo_full__cal, "sc-only FT (+ cal.)"). The condition-encoder-only arm exists only as
10
+ real_condenc__raw (fold-0 call). The point under test: is cond.-encoder-only about what a gene-wise calibration
11
+ does (fold-0 call: cond.-enc. vs zs__cal), while LoRA beats both?
12
+ Accuracy: ImMicro and sepsis, 5-fold cross-fitted, pooled scoring (one call over all donors).
13
+ The condition-encoder-only arm exists only in the fold-0 pilot, so the L1 and coverage panels also show
14
+ every arm from the fold-0 scoring call (open diamonds). Metrics are only comparable within one scoring call,
15
+ so filled circles (pooled call) and open diamonds (fold-0 call) are never compared with each other.
16
+ The sepsis-vs-control logFC r is shown for the pooled call only: the fold-0 contrast rests on 5 controls
17
+ and the source README calls the per-fold contrast too noisy to use.
18
+
19
+ Compute: time per training step (median over runs), not minutes per run, because runs early-stop at
20
+ different steps (sepsis full 5.75k-20k, LoRA 5.75k-15k). All three modes use batch 256 and validate every
21
+ 250 steps (asserted from RUN.json), so wall seconds / steps_run is a like-for-like per-step cost.
22
+
23
+ Every number is read from the score summaries / RUN.json receipts below. CPU only.
24
+ """
25
+ import json
26
+ import sys
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ import pandas as pd
31
+ from scipy.stats import wilcoxon
32
+
33
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
34
+ "2026-09-30--paper-summary--r00")
35
+ sys.path.insert(0, str(DECK / "tools"))
36
+ import style # noqa: E402
37
+ import matplotlib.pyplot as plt # noqa: E402
38
+ from matplotlib.lines import Line2D # noqa: E402
39
+
40
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
41
+ "paired_finetune_intradataset_20260927")
42
+ FIGDIR, DATADIR = DECK / "figures", DECK / "data"
43
+ DATASETS = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis"}
44
+ CELLTYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
45
+
46
+ # rows top -> bottom: (score arm key, run dir name or None, label, colour)
47
+ ARMS = [
48
+ ("real_full__raw", "real_full", "full FT", style.ARM["full_ft"]),
49
+ ("real_lora__raw", "real_lora", "LoRA FT (r 16)", style.ARM["lora"]),
50
+ ("real_condenc__raw", "real_condenc", "cond.-encoder-only FT", style.ARM["other"]),
51
+ ("pseudo_full__cal", None, "sc-only FT (+ cal.)", style.ARM["sconly"]),
52
+ ("zs__cal", None, "zero-shot + calibration", style.ARM["zs_cal"]),
53
+ ("zs__raw", None, "zero-shot, real bulk", style.ARM["zs_raw"]),
54
+ ]
55
+ COMPUTE_ARMS = ARMS[:3]
56
+ ZS = "zs__raw"
57
+ ZS_CAL = "zs__cal"
58
+ CAL_ARMS = {"pseudo_full__cal", ZS_CAL} # the only arms fed calibrated bulk; every other arm is fed raw real bulk
59
+ RAW_EDGE = "#5E8FB5" # edge of the pale raw zero-shot marker (same as sec05 RAW_EDGE)
60
+ EDGE = {"zs__raw": RAW_EDGE}
61
+
62
+
63
+ def fit_lim(vals, lo, hi, step, pad_frac=0.05):
64
+ """Default axis limits, widened (to a multiple of step) only when a value would sit on or past an edge."""
65
+ vals = np.asarray(vals, float)
66
+ pad = pad_frac * (hi - lo)
67
+ if vals.min() - pad < lo:
68
+ lo = round(float(np.floor((vals.min() - pad) / step) * step), 10)
69
+ if vals.max() + pad > hi:
70
+ hi = round(float(np.ceil((vals.max() + pad) / step) * step), 10)
71
+ return lo, hi
72
+
73
+
74
+ def load_call(ds, call):
75
+ root = PLAN / "scores" / ds / call
76
+ summ = json.loads((root / "summary.json").read_text())
77
+ con = pd.read_csv(root / "contrast.csv") if (root / "contrast.csv").exists() else None
78
+ per = pd.read_csv(root / "per_donor.csv")
79
+ return root, summ, con, per
80
+
81
+
82
+ def arm_metrics(ds, call):
83
+ root, summ, con, per = load_call(ds, call)
84
+ rows = []
85
+ for arm, _, label, _ in ARMS:
86
+ if arm not in summ["arms"]:
87
+ continue
88
+ h = summ["headline"][arm]
89
+ r = {"dataset": ds, "call": call, "arm": arm, "label": label, "n_donors": summ["n_donors"],
90
+ "comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
91
+ "source_summary": str(root / "summary.json")}
92
+ if con is not None:
93
+ c = con[(con["arm"] == arm) & (con["statistic"] == "mean_cp10k") & con["celltype"].isin(CELLTYPES)]
94
+ assert set(c["celltype"]) == set(CELLTYPES), (ds, call, arm)
95
+ r["logfc_r"] = float(c["r_generated"].mean())
96
+ assert abs(r["logfc_r"] - h["contrast_mean_cp10k_r_gen"]) < 1e-9
97
+ r["n_case"] = int(c["n_case_donors_obs"].iloc[0])
98
+ r["n_control"] = int(c["n_control_donors_obs"].iloc[0])
99
+ r["source_contrast"] = str(root / "contrast.csv")
100
+ rows.append(r)
101
+ return pd.DataFrame(rows), per
102
+
103
+
104
+ def compute_receipts():
105
+ rows = []
106
+ for ds in DATASETS:
107
+ for arm, run, label, _ in COMPUTE_ARMS:
108
+ for f in sorted((PLAN / "runs" / ds).glob(f"fold[0-9]/{run}/RUN.json")):
109
+ d = json.loads(f.read_text())
110
+ rows.append({"dataset": ds, "arm": arm, "label": label, "fold": d["fold"], "mode": d["mode"],
111
+ "lr": d["lr"], "batch_size": d["batch_size"], "eval_every": d["eval_every"],
112
+ "n_trainable": d["trainable"]["n_trainable"],
113
+ "n_total_base": d["trainable"]["n_total_base"],
114
+ "wall_seconds": d["wall_seconds"], "steps_run": d["steps_run"],
115
+ "sec_per_step": d["wall_seconds"] / d["steps_run"],
116
+ "selected_step": d["selected_step"],
117
+ "selected_inner_val_loss": d["selected_inner_val_loss"],
118
+ "pretrained_inner_val_loss": d["pretrained_inner_val_loss"],
119
+ "source_checkpoint": d["source_checkpoint"], "run_json": str(f)})
120
+ return pd.DataFrame(rows)
121
+
122
+
123
+ def main():
124
+ acc, pers = [], {}
125
+ for ds in DATASETS:
126
+ for call in ("pooled", "fold0"):
127
+ df, per = arm_metrics(ds, call)
128
+ acc.append(df)
129
+ pers[(ds, call)] = per
130
+ acc = pd.concat(acc, ignore_index=True)
131
+ # sanity: the condition-encoder arm is only in the fold-0 call; every arm except the two calibrated ones is fed
132
+ # raw real bulk
133
+ assert not ((acc["call"] == "pooled") & (acc["arm"] == "real_condenc__raw")).any()
134
+ assert (acc["arm"].str.endswith("__raw") | acc["arm"].isin(CAL_ARMS)).all()
135
+ assert acc[acc["arm"].isin(CAL_ARMS)]["arm"].str.endswith("__cal").all()
136
+ # every plotted arm is present in both calls (except cond.-encoder-only, fold-0 call only)
137
+ for (ds, call), g in acc.groupby(["dataset", "call"]):
138
+ want = {a[0] for a in ARMS} - ({"real_condenc__raw"} if call == "pooled" else set())
139
+ assert set(g["arm"]) == want, (ds, call, set(g["arm"]))
140
+
141
+ # paired Wilcoxon of donor-level L1 (uncorrected): full vs LoRA and each fine-tune vs zero-shot (pooled call);
142
+ # cond.-encoder-only vs LoRA / zero-shot (fold-0 call, the only call with that arm). The rows after the first five
143
+ # compare with zero-shot + calibration (zs__cal): full / LoRA (pooled), cond.-encoder-only and LoRA (fold 0), and the
144
+ # raw -> calibrated zero-shot gap; the comparisons with zs__cal are also run on donor coverage.
145
+ wil = []
146
+ tests = [("pooled", "real_full__raw", "real_lora__raw", "full - LoRA", ("comp_l1",)),
147
+ ("pooled", "real_full__raw", ZS, "full - zero-shot", ("comp_l1",)),
148
+ ("pooled", "real_lora__raw", ZS, "LoRA - zero-shot", ("comp_l1",)),
149
+ ("fold0", "real_condenc__raw", "real_lora__raw", "cond.-encoder-only - LoRA", ("comp_l1", "coverage")),
150
+ ("fold0", "real_condenc__raw", ZS, "cond.-encoder-only - zero-shot", ("comp_l1",)),
151
+ ("pooled", "real_full__raw", ZS_CAL, "full - zero-shot + cal", ("comp_l1", "coverage")),
152
+ ("pooled", "real_lora__raw", ZS_CAL, "LoRA - zero-shot + cal", ("comp_l1", "coverage")),
153
+ ("fold0", "real_condenc__raw", ZS_CAL, "cond.-encoder-only - zero-shot + cal", ("comp_l1", "coverage")),
154
+ ("fold0", "real_lora__raw", ZS_CAL, "LoRA - zero-shot + cal", ("comp_l1", "coverage")),
155
+ ("pooled", ZS_CAL, ZS, "zero-shot + cal - zero-shot", ("comp_l1", "coverage"))]
156
+ for ds in DATASETS:
157
+ for call, a, b, name, metrics in tests:
158
+ per = pers[(ds, call)]
159
+ for arm in (a, b): # donor mean must reproduce the headline L1
160
+ h = float(acc[(acc["dataset"] == ds) & (acc["call"] == call) & (acc["arm"] == arm)]["comp_l1"].iloc[0])
161
+ assert abs(per.loc[per["arm"] == arm, "comp_l1"].mean() - h) < 1e-9, (ds, call, arm)
162
+ for met in metrics:
163
+ p = per.pivot(index="donor", columns="arm", values=met)
164
+ x = (p[a] - p[b]).dropna()
165
+ better = (x < 0) if met == "comp_l1" else (x > 0) # L1: lower is better; coverage: higher
166
+ wil.append({"dataset": ds, "call": call, "comparison": f"{name} {met}", "arm_a": a, "arm_b": b,
167
+ "metric": met, "mean_diff": float(x.mean()), "frac_donors_a_lower": float((x < 0).mean()),
168
+ "frac_donors_a_better": float(better.mean()),
169
+ "wilcoxon_p": float(wilcoxon(x).pvalue), "n": int(len(x)),
170
+ "source": str(PLAN / "scores" / ds / call / "per_donor.csv")})
171
+ wil = pd.DataFrame(wil)
172
+
173
+ rec = compute_receipts()
174
+ # per-step cost is like-for-like only if batch size and validation cadence match across modes
175
+ assert rec["batch_size"].nunique() == 1 and rec["eval_every"].nunique() == 1
176
+ agg = dict(n_runs=("fold", "size"), folds=("fold", lambda s: ",".join(map(str, sorted(s)))),
177
+ n_trainable=("n_trainable", "first"), n_trainable_nunique=("n_trainable", "nunique"),
178
+ lr=("lr", "first"),
179
+ wall_min_median=("wall_seconds", lambda s: float(np.median(s)) / 60.0),
180
+ wall_min_min=("wall_seconds", lambda s: float(np.min(s)) / 60.0),
181
+ wall_min_max=("wall_seconds", lambda s: float(np.max(s)) / 60.0),
182
+ steps_run_median=("steps_run", "median"), steps_run_min=("steps_run", "min"),
183
+ steps_run_max=("steps_run", "max"),
184
+ sec_per_step_median=("sec_per_step", "median"))
185
+ comp = rec.groupby(["dataset", "arm", "label"]).agg(**agg).reset_index()
186
+ comp_all = rec.groupby(["arm", "label"]).agg(**agg).reset_index().assign(dataset="both")
187
+ comp = pd.concat([comp, comp_all], ignore_index=True)
188
+ assert (comp["n_trainable_nunique"] == 1).all()
189
+ n_full = int(rec.loc[rec["arm"] == "real_full__raw", "n_trainable"].iloc[0])
190
+ n_lora = int(rec.loc[rec["arm"] == "real_lora__raw", "n_trainable"].iloc[0])
191
+ ratio = n_full / n_lora
192
+ sps = comp[comp["dataset"] == "both"].set_index("arm")["sec_per_step_median"]
193
+ step_ratio = float(sps["real_full__raw"] / sps["real_lora__raw"])
194
+
195
+ acc.to_csv(DATADIR / "sec07_ft_modes_accuracy.csv", index=False)
196
+ rec.to_csv(DATADIR / "sec07_ft_modes_compute_runs.csv", index=False)
197
+ comp.to_csv(DATADIR / "sec07_ft_modes_compute.csv", index=False)
198
+ wil.to_csv(DATADIR / "sec07_ft_modes_wilcoxon.csv", index=False)
199
+
200
+ # ------------------------------------------------------------------ figure
201
+ W, H = 12.2, 4.95
202
+ fig = plt.figure(figsize=(W, H))
203
+
204
+ def ax_in(x, y, w, h):
205
+ return fig.add_axes([x / W, y / H, w / W, h / H])
206
+
207
+ ny = len(ARMS)
208
+ ypos = {a[0]: ny - 1 - i for i, a in enumerate(ARMS)}
209
+ x0, gap, ggap = 2.3, 0.36, 0.62
210
+ pw = (W - x0 - ggap - 3 * gap) / 5
211
+ top_y, top_h = 2.3, 2.1
212
+ # (dataset, metric, x label, xlim, ticks, show fold-0 diamonds)
213
+ # last tick sits inside the axis so it never touches the next panel's "0" (logFC r is the last panel).
214
+ # Default limits are widened from the data (fit_lim) so the zero-shot real-bulk point is never clipped;
215
+ # the L1 limit is shared by both cohorts so the two L1 panels stay comparable.
216
+ def vals(ds_list, met, calls):
217
+ s = acc[acc["dataset"].isin(ds_list) & acc["call"].isin(calls)][met]
218
+ return s.dropna().to_numpy(float)
219
+ l1_lim = fit_lim(vals(list(DATASETS), "comp_l1", ["pooled", "fold0"]), 0, 0.5, 0.1)
220
+ cov_lim = fit_lim(vals(list(DATASETS), "coverage", ["pooled", "fold0"]), 0, 1.0, 0.1)
221
+ r_lim = fit_lim(vals(["ye2026_sepsis"], "logfc_r", ["pooled"]), 0, 0.65, 0.05)
222
+ panels = [("immicro", "comp_l1", "L1 ↓", l1_lim, [0, 0.2, 0.4], True),
223
+ ("immicro", "coverage", "coverage ↑", cov_lim, [0, 0.4, 0.8], True),
224
+ ("ye2026_sepsis", "comp_l1", "L1 ↓", l1_lim, [0, 0.2, 0.4], True),
225
+ ("ye2026_sepsis", "coverage", "coverage ↑", cov_lim, [0, 0.4, 0.8], True),
226
+ ("ye2026_sepsis", "logfc_r", "logFC r ↑", r_lim, [0, 0.2, 0.4, 0.6], False)]
227
+ for _, _, _, lim, ticks, _ in panels:
228
+ assert lim[0] <= min(ticks) and max(ticks) < lim[1], (lim, ticks)
229
+ xs = []
230
+ x = x0
231
+ for i in range(len(panels)):
232
+ xs.append(x)
233
+ x += pw + (ggap if i == 1 else gap)
234
+ for i, (ds, met, xlabel, xlim, ticks, show_f0) in enumerate(panels):
235
+ ax = ax_in(xs[i], top_y, pw, top_h)
236
+ for arm, _, label, col in ARMS:
237
+ y = ypos[arm]
238
+ ax.axhline(y, color="#E6E6E6", lw=0.8, zorder=0)
239
+ calls = (("pooled", 0.14, "o", True), ("fold0", -0.14, "D", False)) if show_f0 else \
240
+ (("pooled", 0.0, "o", True),)
241
+ drawn = False
242
+ for call, dy, mk, fill in calls:
243
+ s = acc[(acc["dataset"] == ds) & (acc["call"] == call) & (acc["arm"] == arm)]
244
+ if len(s) == 0:
245
+ continue
246
+ v = float(s[met].iloc[0])
247
+ assert xlim[0] <= v <= xlim[1], (ds, call, arm, met, v, xlim) # no point outside the axis
248
+ ax.plot([v], [y + dy], marker=mk, ms=9 if mk == "o" else 7.5, mec=EDGE.get(arm, col),
249
+ mfc=col if fill else "white", mew=1.8, ls="none", zorder=3)
250
+ drawn = True
251
+ if not drawn:
252
+ x_txt = max(0.0, (0 - xlim[0]) / (xlim[1] - xlim[0])) + 0.02 # right of the r = 0 line
253
+ ax.text(x_txt, y, "no pooled contrast", ha="left", va="center", fontsize=style.FS - 3,
254
+ color="#6E6E6E", transform=ax.get_yaxis_transform())
255
+ if xlim[0] < 0: # the axis extends below 0 (zero-shot logFC r); mark r = 0
256
+ ax.axvline(0, color="#BDBDBD", lw=0.8, zorder=1)
257
+ ax.set_xlim(*xlim)
258
+ ax.set_xticks(ticks)
259
+ ax.set_xticklabels([f"{t:g}" for t in ticks])
260
+ ax.set_ylim(-0.6, ny - 0.4)
261
+ ax.set_yticks([ypos[a[0]] for a in ARMS])
262
+ if i == 0:
263
+ ax.set_yticklabels([a[2] for a in ARMS], fontsize=style.FS - 1)
264
+ else:
265
+ ax.set_yticklabels([])
266
+ ax.tick_params(axis="y", length=0)
267
+ ax.spines["left"].set_visible(False)
268
+ ax.set_xlabel(xlabel, labelpad=3)
269
+ # dataset headers (group labels, not figure titles)
270
+ im_n = int(acc[(acc["dataset"] == "immicro") & (acc["call"] == "pooled")]["n_donors"].iloc[0])
271
+ im_n0 = int(acc[(acc["dataset"] == "immicro") & (acc["call"] == "fold0")]["n_donors"].iloc[0])
272
+ se = acc[(acc["dataset"] == "ye2026_sepsis") & (acc["call"] == "pooled")].iloc[0]
273
+ se_n0 = int(acc[(acc["dataset"] == "ye2026_sepsis") & (acc["call"] == "fold0")]["n_donors"].iloc[0])
274
+ hy = (top_y + top_h + 0.12) / H
275
+ fig.text((xs[0] + (xs[1] + pw)) / 2 / W, hy, f"ImMicro, healthy (n {im_n})", ha="center", va="bottom",
276
+ fontsize=style.FS, color=style.INK)
277
+ fig.text((xs[2] + (xs[4] + pw)) / 2 / W, hy,
278
+ f"Sepsis {int(se['n_case'])} vs control {int(se['n_control'])} (n {int(se['n_donors'])})",
279
+ ha="center", va="bottom", fontsize=style.FS, color=style.INK)
280
+ for xa, xb in ((xs[0], xs[1] + pw), (xs[2], xs[4] + pw)):
281
+ fig.add_artist(Line2D([xa / W, xb / W], [hy - 0.005, hy - 0.005], color=style.GREY, lw=0.8))
282
+
283
+ # ------------------------------------------------------------------ compute row
284
+ cy, ch = 0.45, 1.0
285
+ carms = COMPUTE_ARMS
286
+ cpos = {a[0]: len(carms) - 1 - i for i, a in enumerate(carms)}
287
+ bx = [x0, x0 + 2.75]
288
+ bw = [2.15, 2.0]
289
+ # trainable params (log)
290
+ ax = ax_in(bx[0], cy, bw[0], ch)
291
+ for arm, _, label, col in carms:
292
+ n = int(comp.loc[comp["arm"] == arm, "n_trainable"].iloc[0])
293
+ ax.barh(cpos[arm], n / 1e6, height=0.62, color=col, lw=0)
294
+ ax.text(n / 1e6 * 1.12, cpos[arm], f"{n / 1e6:.1f} M", va="center", ha="left", fontsize=style.FS - 2)
295
+ ax.set_xscale("log")
296
+ ax.set_xlim(0.5, 400)
297
+ ax.set_xticks([1, 10, 100])
298
+ ax.set_xticklabels(["1 M", "10 M", "100 M"])
299
+ ax.minorticks_off()
300
+ ax.set_yticks([cpos[a[0]] for a in carms])
301
+ ax.set_yticklabels([a[2] for a in carms], fontsize=style.FS - 1)
302
+ ax.tick_params(axis="y", length=0)
303
+ ax.spines["left"].set_visible(False)
304
+ ax.set_ylim(-0.6, len(carms) - 0.4)
305
+ ax.set_xlabel("trainable params (log)", labelpad=3)
306
+ # wall-clock ms per training step, median over all runs of both cohorts
307
+ ax = ax_in(bx[1], cy, bw[1], ch)
308
+ both = comp[comp["dataset"] == "both"].set_index("arm")
309
+ for arm, _, label, col in carms:
310
+ s = both.loc[arm]
311
+ v = 1000.0 * s["sec_per_step_median"]
312
+ ax.barh(cpos[arm], v, height=0.62, color=col, lw=0)
313
+ txt = f"{v:.0f} ms" if s["n_runs"] > 2 else f"{v:.0f} ms (fold 0)"
314
+ ax.text(v + 1.2, cpos[arm], txt, va="center", ha="left", fontsize=style.FS - 2)
315
+ ax.set_xlim(0, 80)
316
+ ax.set_xticks([0, 25, 50])
317
+ ax.set_yticks([cpos[a[0]] for a in carms])
318
+ ax.set_yticklabels([])
319
+ ax.tick_params(axis="y", length=0)
320
+ ax.spines["left"].set_visible(False)
321
+ ax.set_ylim(-0.6, len(carms) - 0.4)
322
+ ax.set_xlabel("wall ms / step", labelpad=3)
323
+
324
+ # legend for the two scoring calls (bottom right)
325
+ lx = (bx[1] + bw[1] + 0.75) / W
326
+ handles = [Line2D([], [], marker="o", ms=9, mfc=style.INK, mec=style.INK, ls="none",
327
+ label=f"5-fold pooled (n {im_n} / {int(se['n_donors'])})"),
328
+ Line2D([], [], marker="D", ms=7.5, mfc="white", mec=style.INK, mew=1.8, ls="none",
329
+ label=f"fold-0 pilot (n {im_n0} / {se_n0})")]
330
+ fig.legend(handles=handles, loc="lower left", bbox_to_anchor=(lx, (cy + 0.42) / H), frameon=False,
331
+ fontsize=style.FS - 2, handletextpad=0.4, labelspacing=0.5)
332
+ fig.text(lx + 0.004, (cy - 0.40) / H, # 4 lines; sits below the legend (bottom at cy + 0.42)
333
+ "compare same marker only\ncond.-encoder-only: fold 0 only\nlogFC r: pooled only\n"
334
+ "cal.: α from the fold's training pairs",
335
+ ha="left", va="bottom", fontsize=style.FS - 3, color="#4D4D4D", linespacing=1.3)
336
+
337
+ style.save(fig, "sec07_ft_modes", FIGDIR)
338
+
339
+ # print the numbers used on the slide
340
+ print(f"trainable full {n_full} lora {n_lora} ratio {ratio:.2f}; per-step full/LoRA {step_ratio:.2f}")
341
+ print(comp[["dataset", "label", "n_runs", "folds", "lr", "n_trainable", "wall_min_median", "wall_min_min",
342
+ "wall_min_max", "steps_run_min", "steps_run_max", "sec_per_step_median"]]
343
+ .round(4).to_string(index=False))
344
+ print(acc[["dataset", "call", "label", "n_donors", "comp_l1", "coverage", "precision", "logfc_r",
345
+ "n_case", "n_control"]].round(3).to_string(index=False))
346
+ print(f"x limits: L1 {l1_lim}, coverage {cov_lim}, logFC r {r_lim}")
347
+ print(wil.drop(columns=["source"]).to_string(index=False))
348
+
349
+
350
+ if __name__ == "__main__":
351
+ main()