Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_no_pretraining.py +155 -0
- paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_cross_scratch.py +180 -0
- paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py +0 -0
- paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py +265 -0
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec07_no_pretraining.py
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 7 slide of the 2026-09-30 paper-summary deck: no pretraining, same cohort (sepsis fold 0 pilot, 2026-10-05).
|
| 3 |
+
|
| 4 |
+
CPU only. The same denoiser trained from random initialisation on the cohort's own pairs (tools/ft_sdd_aug.py
|
| 5 |
+
--init random, full training, lr 2e-4, inner-val selection, cap 100k steps) vs the pretrained model + LoRA r16, on the
|
| 6 |
+
same training pairs, real-bulk conditions (K = 1,000), test donors (fold 0: 12 sepsis, 5 controls) and sampling seed.
|
| 7 |
+
Reads one score_ft.py call over every arm (plans/paired_finetune_intradataset_20260927/scores/ye2026_sepsis/
|
| 8 |
+
fold0_scratch_20261005/{summary.json, per_donor.csv, contrast.csv}) and the runs' RUN.json:
|
| 9 |
+
composition L1, coverage, disease logFC r (mean over T/B/Mono/NK of the mean-CP10K contrast r) = summary.json headline
|
| 10 |
+
across-donor composition r = per cell type (T, B, Mono, NK), Pearson r over the 17 test donors of generated vs
|
| 11 |
+
observed fraction (per_donor.csv), mean of the four types (reproduces ablation_extra_donor.csv comp_r_mean4)
|
| 12 |
+
training time = RUN.json wall_seconds (GB10; selected step and steps run in the slide data)
|
| 13 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders):
|
| 14 |
+
figures/sec07_no_pretraining.{png,pdf}, data/sec07_no_pretraining.csv, data/sec07_no_pretraining_slide_text.json
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
|
| 29 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 30 |
+
"2026-09-30--paper-summary--r00")
|
| 31 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 32 |
+
import sec09_paired_validation as S9 # noqa: E402 (deck rcParams and shared names)
|
| 33 |
+
import style # noqa: E402
|
| 34 |
+
from grouped_bars import grouped_bars # noqa: E402
|
| 35 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 36 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 37 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 38 |
+
|
| 39 |
+
T = S9.T
|
| 40 |
+
SC = T / "scores" / "ye2026_sepsis" / "fold0_scratch_20261005"
|
| 41 |
+
RUNS = T / "runs" / "ye2026_sepsis" / "fold0"
|
| 42 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 43 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 44 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 45 |
+
SCRATCH = "#882255"
|
| 46 |
+
GROUPS = ["5", "58", "58 +\nrecipes"]
|
| 47 |
+
ARMS = [("pre", "Pretrained + LoRA", style.ARM["lora"], None),
|
| 48 |
+
("scratch", "From scratch (no pretraining)", SCRATCH, None)]
|
| 49 |
+
RUN = {("pre", 0): "lora_n5", ("pre", 1): "real_lora", ("pre", 2): "lora_recipe",
|
| 50 |
+
("scratch", 0): "scratch_n5", ("scratch", 1): "scratch_full", ("scratch", 2): "scratch_recipe"}
|
| 51 |
+
TYPES = ("T cell", "B cell", "Monocyte", "NK cell")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main() -> int:
|
| 55 |
+
s = json.loads((SC / "summary.json").read_text())
|
| 56 |
+
pd_ = pd.read_csv(SC / "per_donor.csv")
|
| 57 |
+
need = {f"{r}__raw" for r in RUN.values()} | {"zs__raw"}
|
| 58 |
+
if not need <= set(s["arms"]):
|
| 59 |
+
raise SystemExit(f"{SC}: arms missing {need - set(s['arms'])}")
|
| 60 |
+
if s["n_donors"] != 17:
|
| 61 |
+
raise SystemExit(f"{SC}: expected 17 scored donors, got {s['n_donors']}")
|
| 62 |
+
|
| 63 |
+
def comp_r(arm):
|
| 64 |
+
g = pd_[pd_.arm == arm]
|
| 65 |
+
return float(np.mean([np.corrcoef(g["gen_" + t], g["obs_" + t])[0, 1] for t in TYPES]))
|
| 66 |
+
|
| 67 |
+
vals, rows = {}, []
|
| 68 |
+
for (a, i), run in RUN.items():
|
| 69 |
+
arm = f"{run}__raw"
|
| 70 |
+
h = s["headline"][arm]
|
| 71 |
+
rj = json.loads((RUNS / run / "RUN.json").read_text())
|
| 72 |
+
if (rj.get("init") == "random") != (a == "scratch"):
|
| 73 |
+
raise SystemExit(f"{run}: init {rj.get('init')} does not match {a}")
|
| 74 |
+
v = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "logfc_r": h["contrast_mean_cp10k_r_gen"],
|
| 75 |
+
"comp_r": comp_r(arm), "minutes": rj["wall_seconds"] / 60, "selected_step": rj["selected_step"],
|
| 76 |
+
"steps_run": rj["steps_run"], "train_rows": len(rj["train_rows"])}
|
| 77 |
+
vals[(a, i)] = v
|
| 78 |
+
rows.append({"group": GROUPS[i].replace("\n", " ") + " pairs", "arm": a, "score_arm": arm, **v,
|
| 79 |
+
"source": f"{SC}/summary.json; per_donor.csv; {RUNS / run / 'RUN.json'}"})
|
| 80 |
+
zs = s["headline"]["zs__raw"]
|
| 81 |
+
zsv = {"comp_l1": zs["comp_l1"], "coverage": zs["coverage"], "logfc_r": zs["contrast_mean_cp10k_r_gen"],
|
| 82 |
+
"comp_r": comp_r("zs__raw")}
|
| 83 |
+
rows.append({"group": "0 pairs", "arm": "zero-shot", "score_arm": "zs__raw", **zsv, "source": f"{SC}/summary.json"})
|
| 84 |
+
|
| 85 |
+
panels = [("comp_l1", "Composition L1 ↓", False, None), ("coverage", "Coverage ↑", False, None),
|
| 86 |
+
("logfc_r", "Disease logFC r ↑", False, None), ("comp_r", "Donor comp. r ↑", False, None),
|
| 87 |
+
("minutes", "Train time (min)", True, lambda v: f"{v:.0f}" if v >= 10 else f"{v:.1f}")]
|
| 88 |
+
fig, axes = plt.subplots(1, len(panels), figsize=(12.3, 4.1), gridspec_kw={"wspace": 0.38})
|
| 89 |
+
for ax, (mk, lab, log, fmt) in zip(axes, panels):
|
| 90 |
+
grouped_bars(ax, GROUPS, ARMS, lambda i, a: vals[(a, i)][mk], FS, EDGE, SUB, fmt=fmt, log=log)
|
| 91 |
+
ax.set_title(lab, fontsize=FS - 1)
|
| 92 |
+
if mk in zsv:
|
| 93 |
+
ax.axhline(zsv[mk], color=style.ARM["zs"], ls=(0, (4, 2)), lw=1.4, zorder=3)
|
| 94 |
+
if mk in ("coverage", "comp_r"):
|
| 95 |
+
ax.set_ylim(0, 1.0)
|
| 96 |
+
if mk == "minutes":
|
| 97 |
+
ax.set_ylim(1, 300)
|
| 98 |
+
ax.set_yticks([1, 10, 100], ["1", "10", "100"])
|
| 99 |
+
ax.minorticks_off()
|
| 100 |
+
for t in ax.get_xticklabels():
|
| 101 |
+
t.set_fontsize(FS - 4)
|
| 102 |
+
ax.set_xlabel("Training pairs", fontsize=FS - 4)
|
| 103 |
+
handles = [Patch(color=c, label=l) for _, l, c, _ in ARMS] + \
|
| 104 |
+
[Line2D([0], [0], color=style.ARM["zs"], ls=(0, (4, 2)), lw=1.4, label="Zero-shot (pretrained, no pairs)")]
|
| 105 |
+
fig.legend(handles=handles, loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.12), fontsize=FS - 2)
|
| 106 |
+
style.save(fig, "sec07_no_pretraining", FIGDIR)
|
| 107 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 108 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec07_no_pretraining.csv", index=False, float_format="%.6g")
|
| 109 |
+
|
| 110 |
+
p5, s5, p58, s58 = vals[("pre", 0)], vals[("scratch", 0)], vals[("pre", 1)], vals[("scratch", 1)]
|
| 111 |
+
sm = [vals[("scratch", i)]["minutes"] for i in range(3)]
|
| 112 |
+
pm = [vals[("pre", i)]["minutes"] for i in range(3)]
|
| 113 |
+
kw = [f"Same realism; 5 pairs: donor r {p5['comp_r']:.2f} vs {s5['comp_r']:.2f}",
|
| 114 |
+
f"58 pairs: scratch logFC r {s58['logfc_r']:.2f} vs {p58['logfc_r']:.2f}",
|
| 115 |
+
f"Scratch {min(sm):.0f}–{max(sm):.0f} min, LoRA {min(pm):.0f}–{max(pm):.0f} min"]
|
| 116 |
+
for k in kw:
|
| 117 |
+
if len(k) > 45:
|
| 118 |
+
raise SystemExit(f"keyword too long: {k}")
|
| 119 |
+
numbers = [{"value": f"{g.replace(chr(10), ' ')} pairs: pretrained+LoRA L1 {vals[('pre', i)]['comp_l1']:.3f} / scratch "
|
| 120 |
+
f"{vals[('scratch', i)]['comp_l1']:.3f}; coverage {vals[('pre', i)]['coverage']:.2f} / "
|
| 121 |
+
f"{vals[('scratch', i)]['coverage']:.2f}; logFC r {vals[('pre', i)]['logfc_r']:.2f} / "
|
| 122 |
+
f"{vals[('scratch', i)]['logfc_r']:.2f}; donor composition r {vals[('pre', i)]['comp_r']:.2f} / "
|
| 123 |
+
f"{vals[('scratch', i)]['comp_r']:.2f}; time {vals[('pre', i)]['minutes']:.1f} / "
|
| 124 |
+
f"{vals[('scratch', i)]['minutes']:.0f} min; steps (selected/run) "
|
| 125 |
+
f"{vals[('pre', i)]['selected_step']}/{vals[('pre', i)]['steps_run']} vs "
|
| 126 |
+
f"{vals[('scratch', i)]['selected_step']}/{vals[('scratch', i)]['steps_run']}",
|
| 127 |
+
"source": f"data/sec07_no_pretraining.csv"} for i, g in enumerate(GROUPS)]
|
| 128 |
+
full = ("Pilot on one fold: sepsis fold 0, 17 test donors (12 sepsis, 5 controls); folds 1-4 not run, so no claim "
|
| 129 |
+
"yet. From scratch = the same denoiser (54.2 M weights) re-initialised at random (tools/ft_sdd_aug.py --init "
|
| 130 |
+
"random; seed 20260627) and trained in full on the cohort's own pairs at the pretraining lr 2e-4, batch 256, "
|
| 131 |
+
"EMA 0.999, inner-val selection every 1,000 steps, patience 10, cap 100k steps; the checkpoint supplies only "
|
| 132 |
+
"the architecture, 6k panel, value scaler and bulk z-score constants. Pretrained + LoRA = f01 6k 1x E16 + "
|
| 133 |
+
"LoRA r16 (lr 5e-4). Same training pairs (5 or 58, + 7-8 inner-val), real-bulk conditions K = 1,000, test "
|
| 134 |
+
"donors and sampling seed; recipes = K-diversified pseudobulk augmentation. The 58-pair scratch arms were "
|
| 135 |
+
"still improving at the 100k cap. Coverage = PCA-50 k = 10 balls (precision, C2ST, MMD, E_N agree; "
|
| 136 |
+
"scores_extra/ye2026_sepsis/fold0_scratch_20261005/). Donor composition r = per cell type (T, B, Mono, NK) "
|
| 137 |
+
"Pearson r over the 17 donors of generated vs observed fraction, mean of the four. Dashed = zero-shot. "
|
| 138 |
+
"Training time = RUN.json wall seconds on one GB10 (LoRA also needs the one-time 15.9 h pretraining, which "
|
| 139 |
+
"every cohort reuses). Source: plans/paired_finetune_intradataset_20260927/scores/ye2026_sepsis/"
|
| 140 |
+
"fold0_scratch_20261005/ and README 'No-pretraining ablation'.")
|
| 141 |
+
txt = {"title": "No pretraining: same cohort, from scratch", "layout": "full",
|
| 142 |
+
"figures": [str(FIGDIR / "sec07_no_pretraining.png")], "keywords": kw,
|
| 143 |
+
"footnote_short": "Pilot: sepsis fold 0, 17 test donors (12 sepsis, 5 controls). Folds 1–4 not run yet.",
|
| 144 |
+
"footnote": full, "numbers": numbers}
|
| 145 |
+
out = {"section": "07-no-pretraining", "scripts": [str(Path(__file__).resolve())],
|
| 146 |
+
"generated_from": "tools/sec07_no_pretraining.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
|
| 147 |
+
(OUTDATA / "sec07_no_pretraining_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 148 |
+
print("\n".join(kw))
|
| 149 |
+
for n in numbers:
|
| 150 |
+
print(n["value"])
|
| 151 |
+
return 0
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
if __name__ == "__main__":
|
| 155 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec08_cross_scratch.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 8 slide of the 2026-09-30 paper-summary deck: no pretraining, other cohorts (held-out sepsis pilot, 2026-10-05).
|
| 3 |
+
|
| 4 |
+
CPU only. Held-out sepsis (82 usable samples), training pool = ImMicro + Imperial + Giroux + Liu 2021 (split
|
| 5 |
+
hoL_ye2026_sepsis), K = 1,000. Arms: zero-shot + cross-cohort calibration, pretrained + LoRA r16 / r64 / full FT at step
|
| 6 |
+
saturation (as slides 25-26), the same denoiser trained from random initialisation on the pool (--init random, full,
|
| 7 |
+
lr 2e-4, milestones every 50k steps to 162k), and the cohort's own-pair LoRA (5-fold, reference).
|
| 8 |
+
|
| 9 |
+
All arms are read from plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis/<arm>/summary.json
|
| 10 |
+
(tools/mask_rescore.py): the 46 panel genes measured in sepsis but in no training cohort are zeroed in the generated
|
| 11 |
+
cells of EVERY arm before scoring. Reason: a model trained from scratch never gets a loss on those genes and puts ~91 %
|
| 12 |
+
of its UMI there (observed sepsis cells: 0.014 %), so unmasked scores would measure that artefact. The pretrained arms
|
| 13 |
+
change little with the mask (checked against scores/ and printed). Training time = RUN.json wall_seconds (GB10); the own-
|
| 14 |
+
cohort LoRA time is the mean of its five fold runs (paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold*/real_lora).
|
| 15 |
+
Outputs: figures/sec08_cross_scratch.{png,pdf}, data/sec08_cross_scratch.csv, data/sec08_cross_scratch_slide_text.json
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import os
|
| 20 |
+
|
| 21 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 22 |
+
|
| 23 |
+
import glob
|
| 24 |
+
import json
|
| 25 |
+
import sys
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
|
| 31 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 32 |
+
"2026-09-30--paper-summary--r00")
|
| 33 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 34 |
+
import sec09_paired_validation as S9 # noqa: E402
|
| 35 |
+
import style # noqa: E402
|
| 36 |
+
from grouped_bars import grouped_bars # noqa: E402
|
| 37 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 38 |
+
|
| 39 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 40 |
+
P = M8 / "plans" / "paired_crosscohort_20261002"
|
| 41 |
+
TI = M8 / "plans" / "paired_finetune_intradataset_20260927"
|
| 42 |
+
MS, UM = P / "scores_masked" / "ye2026_sepsis", P / "scores" / "ye2026_sepsis"
|
| 43 |
+
RUNS = P / "runs" / "hoL_ye2026_sepsis" / "K1000"
|
| 44 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 45 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 46 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 47 |
+
# key, label, scored arm, run dir (None = no training), colour, hatch (colours as in tools/sec08_cross_cohort.py)
|
| 48 |
+
ARMS = [("cal", "Calibration", "xcalL_K1000", None, "#0072B2", None),
|
| 49 |
+
("r16", "LoRA r16", "locoL_lora16sat_s26750_K1000", "lora16sat", "#44AA99", None),
|
| 50 |
+
("r64", "LoRA r64", "locoL_lora64sat_s59000_K1000", "lora64sat", "#117733", None),
|
| 51 |
+
("full", "Full FT", "locoL_fullsat_s108500_K1000", "fullsat", "#332288", None),
|
| 52 |
+
("scratch", "From scratch", "locoL_scratchsat_s162000_K1000", "scratchsat", "#882255", None),
|
| 53 |
+
("own", "Own-cohort LoRA", "within_real_lora__raw", "own", "#D55E00", "///")]
|
| 54 |
+
MILESTONES = ["locoL_scratchsat_s50000_K1000", "locoL_scratchsat_s100000_K1000", "locoL_scratchsat_s150000_K1000",
|
| 55 |
+
"locoL_scratchsat_s162000_K1000"]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def head(root, arm):
|
| 59 |
+
s = json.loads((root / arm / "summary.json").read_text())
|
| 60 |
+
h = s["headline"][arm]
|
| 61 |
+
return s, {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "logfc_r": h["contrast_mean_cp10k_r_gen"],
|
| 62 |
+
"deg": h.get("deg_top50_sum")}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def main() -> int:
|
| 66 |
+
vals, rows, ref = {}, [], None
|
| 67 |
+
for key, lab, arm, run, *_ in ARMS:
|
| 68 |
+
s, v = head(MS, arm)
|
| 69 |
+
sig = (tuple(sorted(s["donors"])), s["reference"]["reference_sha256"])
|
| 70 |
+
if ref is None:
|
| 71 |
+
ref = sig
|
| 72 |
+
elif sig != ref:
|
| 73 |
+
raise SystemExit(f"{arm}: donors or reference differ from the other masked calls")
|
| 74 |
+
if run is None:
|
| 75 |
+
v["minutes"], v["steps"] = np.nan, 0
|
| 76 |
+
elif run == "own":
|
| 77 |
+
w = [json.loads(Path(f).read_text())["wall_seconds"] for f in
|
| 78 |
+
sorted(glob.glob(str(TI / "runs" / "ye2026_sepsis" / "fold*" / "real_lora" / "RUN.json")))]
|
| 79 |
+
if len(w) != 5:
|
| 80 |
+
raise SystemExit("own-cohort LoRA: expected five fold runs")
|
| 81 |
+
v["minutes"], v["steps"] = float(np.mean(w)) / 60, None
|
| 82 |
+
else:
|
| 83 |
+
rj = json.loads((RUNS / run / "RUN.json").read_text())
|
| 84 |
+
if (rj.get("init") == "random") != (key == "scratch"):
|
| 85 |
+
raise SystemExit(f"{run}: init {rj.get('init')}")
|
| 86 |
+
v["minutes"], v["steps"] = rj["wall_seconds"] / 60, rj["steps_run"]
|
| 87 |
+
um = UM / arm / "summary.json"
|
| 88 |
+
if um.exists() and key not in ("scratch",):
|
| 89 |
+
_, u = head(UM, arm)
|
| 90 |
+
v["unmasked_comp_l1"], v["unmasked_coverage"], v["unmasked_logfc_r"] = u["comp_l1"], u["coverage"], u["logfc_r"]
|
| 91 |
+
vals[key] = v
|
| 92 |
+
rows.append({"arm": key, "label": lab.replace("\n", " "), "scored_arm": arm, **v,
|
| 93 |
+
"source": str(MS / arm / "summary.json")})
|
| 94 |
+
if len(ref[0]) != 82:
|
| 95 |
+
raise SystemExit(f"expected 82 scored samples, got {len(ref[0])}")
|
| 96 |
+
ms = {a: head(MS, a)[1] for a in MILESTONES}
|
| 97 |
+
for a in MILESTONES:
|
| 98 |
+
rows.append({"arm": "scratch_milestone", "label": a, "scored_arm": a, **ms[a], "source": str(MS / a / "summary.json")})
|
| 99 |
+
for k, v in vals.items():
|
| 100 |
+
if "unmasked_comp_l1" in v:
|
| 101 |
+
print(f"{k}: masked vs unmasked L1 {v['comp_l1']:.3f}/{v['unmasked_comp_l1']:.3f}, coverage "
|
| 102 |
+
f"{v['coverage']:.3f}/{v['unmasked_coverage']:.3f}, logFC r {v['logfc_r']:.3f}/{v['unmasked_logfc_r']:.3f}")
|
| 103 |
+
|
| 104 |
+
groups = [lab for _, lab, *_ in ARMS]
|
| 105 |
+
panels = [("comp_l1", "Composition L1 ↓", False, lambda v: f"{v:.2f}"),
|
| 106 |
+
("coverage", "Coverage ↑", False, lambda v: f"{v:.2f}"),
|
| 107 |
+
("logfc_r", "Disease logFC r ↑", False, lambda v: f"{v:.2f}"),
|
| 108 |
+
("minutes", "Train time (min)", True, lambda v: f"{v:.0f}")]
|
| 109 |
+
fig, axes = plt.subplots(1, len(panels), figsize=(12.3, 4.0), gridspec_kw={"wspace": 0.30})
|
| 110 |
+
for ax, (mk, lab, log, fmt) in zip(axes, panels):
|
| 111 |
+
x = np.arange(len(ARMS))
|
| 112 |
+
for i, (key, _l, _a, _r, col, hatch) in enumerate(ARMS):
|
| 113 |
+
v = vals[key][mk]
|
| 114 |
+
if np.isnan(v):
|
| 115 |
+
ax.text(i, 0.10, "none", transform=ax.get_xaxis_transform(), ha="center", va="bottom",
|
| 116 |
+
fontsize=FS - 5, color=SUB)
|
| 117 |
+
continue
|
| 118 |
+
ax.bar(i, v, 0.75, color=col, edgecolor=EDGE if hatch else "none", linewidth=0.6, hatch=hatch, zorder=2)
|
| 119 |
+
ax.text(i, v * (1.08 if log else 1.0) + (0 if log else 0.008), fmt(v), ha="center", va="bottom",
|
| 120 |
+
fontsize=FS - 6, color=SUB)
|
| 121 |
+
ax.set_xticks(x, [g for g in groups], rotation=55, ha="right", fontsize=FS - 5)
|
| 122 |
+
ax.set_title(lab, fontsize=FS - 1)
|
| 123 |
+
ax.tick_params(axis="y", labelsize=FS - 4)
|
| 124 |
+
ax.grid(axis="y", color="#E3E3E3", linewidth=0.8, zorder=0)
|
| 125 |
+
ax.set_axisbelow(True)
|
| 126 |
+
ax.axvline(len(ARMS) - 1.5, color="#BBBBBB", lw=0.8, ls=":")
|
| 127 |
+
if mk == "coverage":
|
| 128 |
+
ax.set_ylim(0, 1.0)
|
| 129 |
+
if log:
|
| 130 |
+
ax.set_yscale("log")
|
| 131 |
+
ax.set_ylim(1, 400)
|
| 132 |
+
ax.set_yticks([1, 10, 100], ["1", "10", "100"])
|
| 133 |
+
ax.minorticks_off()
|
| 134 |
+
if mk == "comp_l1":
|
| 135 |
+
ax.set_ylim(0, max(v["comp_l1"] for v in vals.values()) * 1.18)
|
| 136 |
+
style.save(fig, "sec08_cross_scratch", FIGDIR)
|
| 137 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 138 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec08_cross_scratch.csv", index=False, float_format="%.6g")
|
| 139 |
+
|
| 140 |
+
sc, r16, own, cal = vals["scratch"], vals["r16"], vals["own"], vals["cal"]
|
| 141 |
+
kw = [f"Scratch ≈ LoRA r16: coverage {sc['coverage']:.2f} vs {r16['coverage']:.2f}",
|
| 142 |
+
f"Own-cohort pairs far ahead: coverage {own['coverage']:.2f}",
|
| 143 |
+
f"Scratch {sc['minutes']:.0f} min vs LoRA r16 {r16['minutes']:.0f} min"]
|
| 144 |
+
for k in kw:
|
| 145 |
+
if len(k) > 45:
|
| 146 |
+
raise SystemExit(f"keyword too long: {k}")
|
| 147 |
+
numbers = [{"value": f"{lab.replace(chr(10), ' ')}: L1 {vals[k]['comp_l1']:.3f}, coverage {vals[k]['coverage']:.3f}, "
|
| 148 |
+
f"logFC r {vals[k]['logfc_r']:.3f}, top-50 DEG {vals[k]['deg']}, time "
|
| 149 |
+
+ ("none" if np.isnan(vals[k]["minutes"]) else f"{vals[k]['minutes']:.0f} min"),
|
| 150 |
+
"source": "data/sec08_cross_scratch.csv"} for k, lab, *_ in ARMS]
|
| 151 |
+
numbers.append({"value": "Scratch milestones (masked) 50k / 100k / 150k / 162k steps: L1 " +
|
| 152 |
+
" / ".join(f"{ms[a]['comp_l1']:.3f}" for a in MILESTONES) + "; coverage " +
|
| 153 |
+
" / ".join(f"{ms[a]['coverage']:.3f}" for a in MILESTONES) + "; logFC r " +
|
| 154 |
+
" / ".join(f"{ms[a]['logfc_r']:.3f}" for a in MILESTONES),
|
| 155 |
+
"source": "data/sec08_cross_scratch.csv"})
|
| 156 |
+
full = ("Pilot, one held-out cohort: sepsis (82 samples), training pool ImMicro + Imperial + Giroux + Liu 2021, "
|
| 157 |
+
"K = 1,000, same inner-val selection and sampling as slides 25-26. From scratch = the same denoiser at random "
|
| 158 |
+
"initialisation (--init random), full training at lr 2e-4, milestones every 50k steps, stopped at 162k "
|
| 159 |
+
"(selected 152k; 127 min on one GB10). Every arm is scored with the 46 panel genes that no training cohort "
|
| 160 |
+
"measured set to 0 in the generated cells (tools/mask_rescore.py): the scratch model never gets a loss on "
|
| 161 |
+
"them and puts ~91 % of its UMI there (observed sepsis cells 0.014 %); the pretrained arms barely change "
|
| 162 |
+
f"(e.g. LoRA r16 coverage {r16['coverage']:.2f} masked vs {r16.get('unmasked_coverage', float('nan')):.2f} unmasked). "
|
| 163 |
+
f"Calibration needs no training. Own-cohort LoRA = 5-fold LoRA on sepsis pairs (mean {own['minutes']:.1f} min "
|
| 164 |
+
"per fold). Scratch milestones: " + numbers[-1]["value"].split(": ", 1)[1] + ". "
|
| 165 |
+
"Source: plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis/ (table_masked.py), runs/hoL_ye2026_sepsis/K1000/.")
|
| 166 |
+
txt = {"title": "No pretraining: other cohorts, from scratch", "layout": "full",
|
| 167 |
+
"figures": [str(FIGDIR / "sec08_cross_scratch.png")], "keywords": kw,
|
| 168 |
+
"footnote_short": "Pilot: held-out sepsis, 82 samples. Genes no training cohort measured are zeroed in every arm.",
|
| 169 |
+
"footnote": full, "numbers": numbers}
|
| 170 |
+
out = {"section": "08-cross-scratch", "scripts": [str(Path(__file__).resolve())],
|
| 171 |
+
"generated_from": "tools/sec08_cross_scratch.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
|
| 172 |
+
(OUTDATA / "sec08_cross_scratch_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 173 |
+
print("\n".join(kw))
|
| 174 |
+
for n in numbers:
|
| 175 |
+
print(n["value"])
|
| 176 |
+
return 0
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_paired_validation.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py
ADDED
|
@@ -0,0 +1,265 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 9 slide of the 2026-09-30 paper-summary deck: scSemiProfiler and LoRA given the SAME training pairs
|
| 3 |
+
(5-fold CV, 2026-10-05; cohorts still running are shown as "in progress").
|
| 4 |
+
|
| 5 |
+
CPU only. Per cohort, both methods use exactly the pairs of the other four folds (LoRA's training + inner-val rows =
|
| 6 |
+
scSemiProfiler's representatives; checked for every fold by scsemi/tools/check_units.py) and are scored on all usable
|
| 7 |
+
samples, each by the fold model that never saw it (one pooled score_ft.py call per method, same donors and reference):
|
| 8 |
+
LoRA scores/<ds>/pooled/summary.json arm real_lora__raw
|
| 9 |
+
scSemiProfiler scores/<ds>/scsemi_cv_20261002/pooled/summary.json arm scsemi__raw
|
| 10 |
+
Giroux disease metrics from scores_nosex/ (sex-linked genes excluded), as in the deck.
|
| 11 |
+
GPU time per fold (one GB10, every step alone on the GPU; data preparation and scoring not counted on either side):
|
| 12 |
+
LoRA runs/<ds>/fold<k>/real_lora/RUN.json wall_seconds + the sampling job's wall clock in logs/run_queue_*.log
|
| 13 |
+
scSemiProfiler scsemi/work/<ds>/cv/fold<k>/scsemi_project/models/*.receipt.json elapsed_seconds (stage 1 + 2 of every
|
| 14 |
+
representative, complete, same run signature as the export) + the export's total_target_seconds
|
| 15 |
+
Read on the host that holds each fold's records (server_1 or spark-0110).
|
| 16 |
+
The equal-pair-budget runs (n = 5..40, ImMicro and sepsis) are drawn on the "Pairs needed" slide; quoted here.
|
| 17 |
+
Outputs: figures/sec09_same_pairs.{png,pdf}, data/sec09_same_pairs.csv, data/sec09_same_pairs_slide_text.json
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import os
|
| 22 |
+
|
| 23 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import subprocess
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pandas as pd
|
| 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 sec09_paired_validation as S9 # noqa: E402
|
| 37 |
+
import style # noqa: E402
|
| 38 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 39 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 40 |
+
|
| 41 |
+
T = S9.T
|
| 42 |
+
ORDER, ROWNAME = S9.ORDER, S9.ROWNAME
|
| 43 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 44 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 45 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 46 |
+
CV = "scsemi_cv_20261002"
|
| 47 |
+
BUDGET = "scsemi_budget_20261002"
|
| 48 |
+
ARMS = [("scsemi", "scSemiProfiler, same pairs", style.ARM["scsemi"]), ("lora", "LoRA, same pairs", style.ARM["lora"])]
|
| 49 |
+
TAG = {"immicro": "imm", "ye2026_sepsis": "ye2", "imperial_eskd": "imp", "giroux2022": "gir", "ji2025_chili": "ji2"}
|
| 50 |
+
|
| 51 |
+
COLLECT = r'''
|
| 52 |
+
import glob, json, os, re, sys
|
| 53 |
+
T = sys.argv[1]; TAG = json.loads(sys.argv[2])
|
| 54 |
+
def jl(p):
|
| 55 |
+
try:
|
| 56 |
+
return json.load(open(p))
|
| 57 |
+
except Exception:
|
| 58 |
+
return None
|
| 59 |
+
st, en = {}, {}
|
| 60 |
+
for lg in sorted(glob.glob(os.path.join(T, "logs", "run_queue_*.log"))):
|
| 61 |
+
for line in open(lg, errors="replace"):
|
| 62 |
+
m = re.match(r"^(\S+) --- ([a-z0-9]+_f\d_real_lora_raw) seed=", line)
|
| 63 |
+
if m: st.setdefault(m.group(2), []).append(m.group(1))
|
| 64 |
+
m = re.match(r"^(\S+) ([a-z0-9]+_f\d_real_lora_raw) done:", line)
|
| 65 |
+
if m: en.setdefault(m.group(2), []).append(m.group(1))
|
| 66 |
+
out = {}
|
| 67 |
+
for ds, p in TAG.items():
|
| 68 |
+
for k in range(5):
|
| 69 |
+
r = {}
|
| 70 |
+
run = jl(os.path.join(T, "runs", ds, f"fold{k}", "real_lora", "RUN.json"))
|
| 71 |
+
tag = f"{p}_f{k}_real_lora_raw"
|
| 72 |
+
if run and len(st.get(tag, [])) >= 1 and len(en.get(tag, [])) >= 1:
|
| 73 |
+
r["lora"] = {"train_s": run["wall_seconds"], "start": st[tag][-1], "end": en[tag][-1]}
|
| 74 |
+
ex = jl(os.path.join(T, "generated", ds, f"fold{k}", "scsemi__raw.log"))
|
| 75 |
+
w = os.path.join(T, "scsemi", "work", ds, "cv", f"fold{k}")
|
| 76 |
+
asg = jl(os.path.join(w, "assignment.json"))
|
| 77 |
+
if ex and asg:
|
| 78 |
+
rec = [jl(f) for f in glob.glob(os.path.join(w, "scsemi_project", "models", "*.receipt.json"))]
|
| 79 |
+
rec = [x for x in rec if x and x.get("complete") and x.get("run_signature") == ex["run_signature"]]
|
| 80 |
+
r["scsemi"] = {"n_reps": len(asg["representative_indices"]), "n_rec": len(rec),
|
| 81 |
+
"pretrain_s": sum(x["elapsed_seconds"] for x in rec), "target_s": ex["total_target_seconds"],
|
| 82 |
+
"bulks": ex["bulks"]}
|
| 83 |
+
out[f"{ds}|{k}"] = r
|
| 84 |
+
print(json.dumps(out))
|
| 85 |
+
'''
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def collect(host):
|
| 89 |
+
cmd = ["python3", "-", str(T), json.dumps(TAG)]
|
| 90 |
+
if host != "server_1":
|
| 91 |
+
cmd = ["ssh", "spark-0110"] + ["python3", "-", str(T), "'" + json.dumps(TAG) + "'"]
|
| 92 |
+
res = subprocess.run(cmd, input=COLLECT, capture_output=True, text=True, check=True)
|
| 93 |
+
return json.loads(res.stdout)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def load(p):
|
| 97 |
+
f = p / "summary.json"
|
| 98 |
+
return json.loads(f.read_text()) if f.exists() else None
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def main() -> int:
|
| 102 |
+
got = {h: collect(h) for h in ("server_1", "server_2")}
|
| 103 |
+
vals, rows, done = {}, [], []
|
| 104 |
+
for ds in ORDER:
|
| 105 |
+
lo, sc = load(T / "scores" / ds / "pooled"), load(T / "scores" / ds / CV / "pooled")
|
| 106 |
+
if sc is None or "scsemi__raw" not in sc["arms"]:
|
| 107 |
+
continue
|
| 108 |
+
if set(lo["donors"]) != set(sc["donors"]) or lo["reference"]["reference_sha256"] != sc["reference"]["reference_sha256"]:
|
| 109 |
+
raise SystemExit(f"{ds}: LoRA and scSemiProfiler pooled calls differ in donors or reference")
|
| 110 |
+
hl, hs = dict(lo["headline"]["real_lora__raw"]), dict(sc["headline"]["scsemi__raw"])
|
| 111 |
+
if ds == "giroux2022":
|
| 112 |
+
nl, ns = load(T / "scores_nosex" / ds / "pooled"), load(T / "scores_nosex" / ds / CV / "pooled")
|
| 113 |
+
if ns is None:
|
| 114 |
+
hs["contrast_mean_cp10k_r_gen"] = np.nan
|
| 115 |
+
for h, n, a in ((hl, nl, "real_lora__raw"), (hs, ns, "scsemi__raw")):
|
| 116 |
+
if n is not None:
|
| 117 |
+
h["contrast_mean_cp10k_r_gen"] = n["headline"][a]["contrast_mean_cp10k_r_gen"]
|
| 118 |
+
t = {"lora": [], "scsemi": []}
|
| 119 |
+
for k in range(5):
|
| 120 |
+
for m in ("lora", "scsemi"):
|
| 121 |
+
rec = [g[f"{ds}|{k}"][m] for g in got.values() if m in g.get(f"{ds}|{k}", {})
|
| 122 |
+
and (m == "lora" or g[f"{ds}|{k}"][m]["n_rec"] == 2 * g[f"{ds}|{k}"][m]["n_reps"])]
|
| 123 |
+
if len(rec) != 1:
|
| 124 |
+
raise SystemExit(f"{ds} fold {k} {m}: {len(rec)} complete timing records across hosts")
|
| 125 |
+
r = rec[0]
|
| 126 |
+
if m == "lora":
|
| 127 |
+
gen = (pd.Timestamp(r["end"]) - pd.Timestamp(r["start"])).total_seconds()
|
| 128 |
+
t[m].append((r["train_s"] + gen) / 3600)
|
| 129 |
+
else:
|
| 130 |
+
t[m].append((r["pretrain_s"] + r["target_s"]) / 3600)
|
| 131 |
+
for m, h in (("lora", hl), ("scsemi", hs)):
|
| 132 |
+
vals[(ds, m)] = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
|
| 133 |
+
"logfc_r": h.get("contrast_mean_cp10k_r_gen", np.nan), "deg": h.get("deg_top50_sum"),
|
| 134 |
+
"hours": float(np.mean(t[m])), "hours_min": min(t[m]), "hours_max": max(t[m])}
|
| 135 |
+
rows.append({"dataset": ds, "arm": m, **vals[(ds, m)], "n_scored": lo["n_donors"],
|
| 136 |
+
"source": str(T / "scores" / ds / (CV + "/pooled" if m == "scsemi" else "pooled") / "summary.json")})
|
| 137 |
+
done.append(ds)
|
| 138 |
+
if not done:
|
| 139 |
+
raise SystemExit("no cohort has a scored scSemiProfiler 5-fold CV yet")
|
| 140 |
+
# equal pair budget (quoted only)
|
| 141 |
+
bud = []
|
| 142 |
+
for ds in ORDER:
|
| 143 |
+
sb, lo = load(T / "scores" / ds / BUDGET / "pooled"), load(T / "scores" / ds / "pooled")
|
| 144 |
+
if sb is None:
|
| 145 |
+
continue
|
| 146 |
+
for n in (5, 10, 20, 40):
|
| 147 |
+
a, b = f"scsemi_n{n}__raw", f"lora_n{n}__raw"
|
| 148 |
+
if a in sb["arms"] and b in lo["arms"]:
|
| 149 |
+
bud.append({"dataset": ds, "n": n, "scsemi_l1": sb["headline"][a]["comp_l1"],
|
| 150 |
+
"lora_l1": lo["headline"][b]["comp_l1"], "scsemi_cov": sb["headline"][a]["coverage"],
|
| 151 |
+
"lora_cov": lo["headline"][b]["coverage"]})
|
| 152 |
+
bud = pd.DataFrame(bud)
|
| 153 |
+
|
| 154 |
+
panels = [("comp_l1", "Composition L1 ↓", None), ("coverage", "Coverage ↑", (0, 1)),
|
| 155 |
+
("logfc_r", "Disease logFC r ↑", (0, 1)), ("hours", "GPU hours per fold", None)]
|
| 156 |
+
fig, axes = plt.subplots(1, 4, figsize=(12.3, 4.2), gridspec_kw={"wspace": 0.12})
|
| 157 |
+
h = 0.36
|
| 158 |
+
y = np.arange(len(ORDER)) * 1.0
|
| 159 |
+
for ax, (mk, lab, lim) in zip(axes, panels):
|
| 160 |
+
for i, ds in enumerate(ORDER):
|
| 161 |
+
if ds == "immicro" and mk == "logfc_r" and ds in done:
|
| 162 |
+
ax.text(0.03, y[i], "healthy cohort: no contrast", transform=ax.get_yaxis_transform(), va="center",
|
| 163 |
+
fontsize=FS - 4, color=SUB)
|
| 164 |
+
continue
|
| 165 |
+
if ds not in done:
|
| 166 |
+
ax.text(0.03, y[i], "in progress", transform=ax.get_yaxis_transform(), va="center", fontsize=FS - 4,
|
| 167 |
+
color=SUB)
|
| 168 |
+
continue
|
| 169 |
+
for k, (m, _l, col) in enumerate(ARMS):
|
| 170 |
+
v = vals[(ds, m)][mk]
|
| 171 |
+
yy = y[i] + (k - 0.5) * h
|
| 172 |
+
if v is None or np.isnan(v):
|
| 173 |
+
ax.text(0.03, yy, "no contrast" if ds == "immicro" else "n/a", transform=ax.get_yaxis_transform(),
|
| 174 |
+
va="center", fontsize=FS - 5, color=SUB)
|
| 175 |
+
continue
|
| 176 |
+
ax.barh(yy, v, h * 0.9, color=col, edgecolor="none")
|
| 177 |
+
if mk == "hours":
|
| 178 |
+
vv = vals[(ds, m)]
|
| 179 |
+
s = (f"{vv['hours_min'] * 60:.0f}–{vv['hours_max'] * 60:.0f} min" if m == "lora"
|
| 180 |
+
else f"{vv['hours_min']:.1f}–{vv['hours_max']:.1f} h")
|
| 181 |
+
else:
|
| 182 |
+
s = f"{v:.2f}"
|
| 183 |
+
ax.text(v * (1.12 if mk == "hours" else 1.0) + (0 if mk == "hours" else 0.015), yy, s, va="center",
|
| 184 |
+
fontsize=FS - 5, color=SUB)
|
| 185 |
+
ax.set_title(lab, fontsize=FS - 1)
|
| 186 |
+
ax.set_yticks(y, [ROWNAME[d] for d in ORDER] if ax is axes[0] else [""] * len(ORDER), fontsize=FS - 3)
|
| 187 |
+
ax.set_ylim(len(ORDER) - 0.5, -0.5)
|
| 188 |
+
ax.tick_params(axis="y", length=0)
|
| 189 |
+
ax.tick_params(axis="x", labelsize=FS - 4)
|
| 190 |
+
if lim:
|
| 191 |
+
ax.set_xlim(*lim)
|
| 192 |
+
if mk == "comp_l1":
|
| 193 |
+
ax.set_xlim(0, 0.75)
|
| 194 |
+
if mk == "hours":
|
| 195 |
+
ax.set_xscale("log")
|
| 196 |
+
ax.set_xlim(0.03, 40)
|
| 197 |
+
ax.set_xticks([0.1, 1, 10], ["0.1", "1", "10"])
|
| 198 |
+
ax.minorticks_off()
|
| 199 |
+
ax.grid(axis="x", color="#E3E3E3", linewidth=0.8)
|
| 200 |
+
ax.set_axisbelow(True)
|
| 201 |
+
fig.legend(handles=[Patch(color=c, label=l) for _, l, c in ARMS], loc="lower center", ncol=2,
|
| 202 |
+
bbox_to_anchor=(0.5, -0.08), fontsize=FS - 2)
|
| 203 |
+
style.save(fig, "sec09_same_pairs", FIGDIR)
|
| 204 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 205 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec09_same_pairs.csv", index=False, float_format="%.6g")
|
| 206 |
+
if len(bud):
|
| 207 |
+
bud.to_csv(OUTDATA / "sec09_same_pairs_budget.csv", index=False, float_format="%.6g")
|
| 208 |
+
|
| 209 |
+
names = [S9.NAME[d] for d in done]
|
| 210 |
+
lw = {k: sum((vals[(d, 'lora')][k] < vals[(d, 'scsemi')][k]) if k == "comp_l1"
|
| 211 |
+
else (vals[(d, 'lora')][k] > vals[(d, 'scsemi')][k]) for d in done
|
| 212 |
+
if not np.isnan(vals[(d, 'lora')][k]) and not np.isnan(vals[(d, 'scsemi')][k]))
|
| 213 |
+
for k in ("comp_l1", "coverage", "precision", "logfc_r")}
|
| 214 |
+
ratio = [vals[(d, "scsemi")]["hours"] / vals[(d, "lora")]["hours"] for d in done]
|
| 215 |
+
kw = [f"Same pairs: LoRA ahead on every metric",
|
| 216 |
+
f"Coverage {vals[(done[0], 'lora')]['coverage']:.2f} vs {vals[(done[0], 'scsemi')]['coverage']:.2f} ({S9.NAME[done[0]]})",
|
| 217 |
+
f"{min(ratio):.0f}–{max(ratio):.0f}× less GPU time per fold"]
|
| 218 |
+
if not all(lw[k] == sum(1 for d in done if not np.isnan(vals[(d, 'lora')][k])) for k in lw):
|
| 219 |
+
kw[0] = "Same pairs: " + ", ".join(f"{k} {v}/{len(done)}" for k, v in lw.items())
|
| 220 |
+
for k in kw:
|
| 221 |
+
if len(k) > 45:
|
| 222 |
+
raise SystemExit(f"keyword too long: {k}")
|
| 223 |
+
numbers = [{"value": f"{S9.NAME[d]}: L1 LoRA {vals[(d, 'lora')]['comp_l1']:.3f} / scSemi {vals[(d, 'scsemi')]['comp_l1']:.3f}; "
|
| 224 |
+
f"coverage {vals[(d, 'lora')]['coverage']:.3f} / {vals[(d, 'scsemi')]['coverage']:.3f}; precision "
|
| 225 |
+
f"{vals[(d, 'lora')]['precision']:.3f} / {vals[(d, 'scsemi')]['precision']:.3f}; logFC r "
|
| 226 |
+
f"{vals[(d, 'lora')]['logfc_r']:.3f} / {vals[(d, 'scsemi')]['logfc_r']:.3f}; top-50 DEG "
|
| 227 |
+
f"{vals[(d, 'lora')]['deg']} / {vals[(d, 'scsemi')]['deg']}; GPU per fold LoRA "
|
| 228 |
+
f"{vals[(d, 'lora')]['hours'] * 60:.1f} min / scSemi {vals[(d, 'scsemi')]['hours']:.2f} h",
|
| 229 |
+
"source": "data/sec09_same_pairs.csv"} for d in done]
|
| 230 |
+
btxt = ""
|
| 231 |
+
if len(bud):
|
| 232 |
+
for d, g in bud.groupby("dataset"):
|
| 233 |
+
btxt += (f" Equal pair budget, {S9.NAME[d]} (n = 5, 10, 20, 40 pairs): scSemiProfiler L1 "
|
| 234 |
+
f"{g.scsemi_l1.min():.3f}–{g.scsemi_l1.max():.3f} and coverage {g.scsemi_cov.min():.2f}–"
|
| 235 |
+
f"{g.scsemi_cov.max():.2f} at every n; LoRA L1 {g.lora_l1.min():.3f}–{g.lora_l1.max():.3f}, coverage "
|
| 236 |
+
f"{g.lora_cov.min():.2f}–{g.lora_cov.max():.2f} (drawn on the 'Pairs needed' slide).")
|
| 237 |
+
numbers.append({"value": btxt.strip(), "source": "data/sec09_same_pairs_budget.csv"})
|
| 238 |
+
pending = [S9.NAME[d] for d in ORDER if d not in done]
|
| 239 |
+
full = ("5-fold CV: for every fold, scSemiProfiler's representatives are exactly LoRA's training + inner-val pairs "
|
| 240 |
+
"(the other four folds; checked per fold), test = the fold's samples from their real bulk only. Pooled = one "
|
| 241 |
+
"scoring call per method over every usable sample, same donors and reference (sha-checked). scSemiProfiler = "
|
| 242 |
+
"upstream c2aea02, default settings, official output. GPU time per fold on one GB10: LoRA = fine-tune + "
|
| 243 |
+
"sampling 1,500 cells per test sample; scSemiProfiler = pretraining of every representative + one model per "
|
| 244 |
+
"test sample (receipts); data preparation and scoring not counted on either side. "
|
| 245 |
+
+ ("Still running (server_1 / server_2): " + ", ".join(pending) + "." if pending else "")
|
| 246 |
+
+ btxt + " Source: plans/paired_finetune_intradataset_20260927/scores/<cohort>/{pooled,scsemi_cv_20261002/pooled}/ "
|
| 247 |
+
"and scsemi/analysis/cv_budget_20261005/.")
|
| 248 |
+
txt = {"title": "Same training pairs: LoRA vs scSemiProfiler", "layout": "full",
|
| 249 |
+
"figures": [str(FIGDIR / "sec09_same_pairs.png")], "keywords": kw,
|
| 250 |
+
"footnote_short": ("5-fold CV; scSemiProfiler representatives = LoRA's training pairs. "
|
| 251 |
+
+ (f"{', '.join(pending)}: running." if pending else "")),
|
| 252 |
+
"footnote": full, "numbers": numbers}
|
| 253 |
+
if len(txt["footnote_short"]) > 110:
|
| 254 |
+
raise SystemExit("short footnote too long")
|
| 255 |
+
out = {"section": "09-same-pairs", "scripts": [str(Path(__file__).resolve())],
|
| 256 |
+
"generated_from": "tools/sec09_same_pairs.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
|
| 257 |
+
(OUTDATA / "sec09_same_pairs_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 258 |
+
print("\n".join(kw))
|
| 259 |
+
for n in numbers:
|
| 260 |
+
print(n["value"])
|
| 261 |
+
return 0
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
if __name__ == "__main__":
|
| 265 |
+
sys.exit(main())
|