Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_same_pairs.py +265 -0
- paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_time_to_apply.py +311 -0
- paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec10_other_tissues.py +202 -0
- paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/secS_scratch_rare_states.py +342 -0
paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/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: composition, coverage, training steps" 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: composition, coverage, training steps' 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())
|
paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_time_to_apply.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 9 of the 2026-09-30 paper-summary deck: time to apply, LoRA-5 vs scSemiProfiler-5 (same 5-donor draws).
|
| 3 |
+
|
| 4 |
+
CPU only, reads receipts and queue logs; no torch, no CUDA. GPU time per draw on one GB10 (the GPU lock makes every
|
| 5 |
+
step run alone on the GPU):
|
| 6 |
+
LoRA-5 fine-tune runs/<ds>/fewshot_n5/draw<j>/lora/RUN.json wall_seconds (3,000 steps)
|
| 7 |
+
generate logs/run_queue_*.log: '--- <p>_fs_d<j>_lora seed=' -> '<p>_fs_d<j>_lora done:' (wall clock
|
| 8 |
+
of the sampling job: model load + DDIM 50 for 1,500 cells per test sample)
|
| 9 |
+
scSemiProfiler train scsemi/work/<ds>/fewshot_n5/draw<j>/scsemi_project/models/*.receipt.json elapsed_seconds,
|
| 10 |
+
stage 1 + stage 2 for every representative (complete, same run_signature as the export)
|
| 11 |
+
infer generated/<ds>/fewshot_n5/draw<j>/scsemi5__raw.log total_target_seconds (one model per
|
| 12 |
+
test sample)
|
| 13 |
+
Not counted on either side: data preparation (CPU), scoring, the base model's one-time pretraining (data/sec06_ft_method.csv
|
| 14 |
+
pretrain_wall_hours, shown on the 'Fine-tuning with paired bulk + sc' slide).
|
| 15 |
+
Each draw is read on the host that holds its export (Imperial LoRA and scSemiProfiler, and scSemiProfiler ImMicro 2-3,
|
| 16 |
+
ran on server_2; scSemiProfiler sepsis 4 was pretrained on server_2 and finished on server_1, whose receipts hold both
|
| 17 |
+
parts); a step without a complete record stops the script. Work lost to interruptions (memory-guard stops) is not
|
| 18 |
+
counted, which can only favour scSemiProfiler.
|
| 19 |
+
|
| 20 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders):
|
| 21 |
+
figures/sec09_time_to_apply.{png,pdf}
|
| 22 |
+
data/sec09_time_to_apply_runs.csv one row per cohort x draw x method with every time and its source
|
| 23 |
+
data/sec09_time_to_apply.csv per cohort and method: mean / SD / min / max over the 5 draws
|
| 24 |
+
data/sec09_time_to_apply_slide_text.json title, keywords, footnotes and quoted numbers (synced into the spec by
|
| 25 |
+
tools/sync_sec09_text.py through text_source)
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import os
|
| 30 |
+
|
| 31 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 32 |
+
|
| 33 |
+
import json
|
| 34 |
+
import subprocess
|
| 35 |
+
import sys
|
| 36 |
+
from pathlib import Path
|
| 37 |
+
|
| 38 |
+
import numpy as np
|
| 39 |
+
import pandas as pd
|
| 40 |
+
|
| 41 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 42 |
+
"2026-09-30--paper-summary--r00")
|
| 43 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 44 |
+
import sec09_paired_validation as S9 # noqa: E402 (shared section 9 names and colours; sets the deck rcParams)
|
| 45 |
+
import style # noqa: E402
|
| 46 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 47 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 48 |
+
|
| 49 |
+
T = S9.T
|
| 50 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 51 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 52 |
+
ORDER, NAME, ROWNAME = S9.ORDER, S9.NAME, S9.ROWNAME
|
| 53 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 54 |
+
DRAWS = range(5)
|
| 55 |
+
SERVER2 = "spark-0110"
|
| 56 |
+
COL = {"lora": style.ARM["lora"], "scsemi": style.ARM["scsemi"]}
|
| 57 |
+
PALE = {"lora": "#F2B48C", "scsemi": "#F5D08A"} # second segment (generation / per-target inference)
|
| 58 |
+
LAB = {"lora": "LoRA, 5 donors", "scsemi": "scSemiProfiler, 5 donors"}
|
| 59 |
+
|
| 60 |
+
# Runs on each host (python3 -, argv: plan root). Prints one JSON object: every record the deck needs, per cohort/draw.
|
| 61 |
+
COLLECT = r'''
|
| 62 |
+
import glob, json, os, re, sys
|
| 63 |
+
T = sys.argv[1]
|
| 64 |
+
TAG = {"immicro": "imm", "ye2026_sepsis": "ye2", "imperial_eskd": "imp", "giroux2022": "gir", "ji2025_chili": "ji2"}
|
| 65 |
+
def jload(p):
|
| 66 |
+
try:
|
| 67 |
+
with open(p) as f:
|
| 68 |
+
return json.load(f)
|
| 69 |
+
except Exception:
|
| 70 |
+
return None
|
| 71 |
+
starts, ends = {}, {}
|
| 72 |
+
pat_s = re.compile(r"^(\S+) --- ([a-z0-9]+_fs_d[0-9]_lora) seed=")
|
| 73 |
+
pat_e = re.compile(r"^(\S+) ([a-z0-9]+_fs_d[0-9]_lora) done:")
|
| 74 |
+
for lg in sorted(glob.glob(os.path.join(T, "logs", "run_queue_*.log"))):
|
| 75 |
+
for line in open(lg, errors="replace"):
|
| 76 |
+
m = pat_s.match(line)
|
| 77 |
+
if m:
|
| 78 |
+
starts.setdefault(m.group(2), []).append((m.group(1), lg))
|
| 79 |
+
m = pat_e.match(line)
|
| 80 |
+
if m:
|
| 81 |
+
ends.setdefault(m.group(2), []).append((m.group(1), lg))
|
| 82 |
+
out = {}
|
| 83 |
+
for ds, p in TAG.items():
|
| 84 |
+
for j in range(5):
|
| 85 |
+
k = f"{ds}|{j}"
|
| 86 |
+
r = {}
|
| 87 |
+
run = jload(os.path.join(T, "runs", ds, "fewshot_n5", f"draw{j}", "lora", "RUN.json"))
|
| 88 |
+
if run:
|
| 89 |
+
r["lora_train"] = {"wall_seconds": run.get("wall_seconds"), "steps_run": run.get("steps_run"),
|
| 90 |
+
"src": os.path.join(T, "runs", ds, "fewshot_n5", f"draw{j}", "lora", "RUN.json")}
|
| 91 |
+
g = os.path.join(T, "generated", ds, "fewshot_n5", f"draw{j}")
|
| 92 |
+
lr = jload(os.path.join(g, "lora__raw.log"))
|
| 93 |
+
if lr and os.path.isfile(os.path.join(g, "lora__raw.npz")):
|
| 94 |
+
r["lora_out"] = {"bulks": lr.get("bulks"), "cells": lr.get("cells"), "sha256": lr.get("output_sha256")}
|
| 95 |
+
tag = f"{p}_fs_d{j}_lora"
|
| 96 |
+
if tag in starts or tag in ends:
|
| 97 |
+
r["lora_sample_log"] = {"starts": starts.get(tag, []), "ends": ends.get(tag, [])}
|
| 98 |
+
ex = jload(os.path.join(g, "scsemi5__raw.log"))
|
| 99 |
+
if ex and os.path.isfile(os.path.join(g, "scsemi5__raw.npz")):
|
| 100 |
+
r["scsemi_export"] = {k2: ex.get(k2) for k2 in ("bulks", "cells", "total_target_seconds",
|
| 101 |
+
"median_target_seconds", "run_signature", "output_sha256")}
|
| 102 |
+
r["scsemi_export"]["src"] = os.path.join(g, "scsemi5__raw.log")
|
| 103 |
+
md = os.path.join(T, "scsemi", "work", ds, "fewshot_n5", f"draw{j}", "scsemi_project", "models")
|
| 104 |
+
rec = []
|
| 105 |
+
for f in sorted(glob.glob(os.path.join(md, "*.receipt.json"))):
|
| 106 |
+
x = jload(f) or {}
|
| 107 |
+
rec.append({"file": f, "stage": x.get("stage"), "representative": x.get("representative"),
|
| 108 |
+
"elapsed_seconds": x.get("elapsed_seconds"), "complete": x.get("complete"),
|
| 109 |
+
"run_signature": x.get("run_signature")})
|
| 110 |
+
r["scsemi_pretrain"] = rec
|
| 111 |
+
asg = jload(os.path.join(T, "scsemi", "work", ds, "fewshot_n5", f"draw{j}", "assignment.json"))
|
| 112 |
+
if asg:
|
| 113 |
+
r["scsemi_n_reps"] = len(asg.get("representative_indices", []))
|
| 114 |
+
out[k] = r
|
| 115 |
+
print(json.dumps(out))
|
| 116 |
+
'''
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def collect(host: str) -> dict:
|
| 120 |
+
cmd = ["python3", "-", str(T)] if host == "server_1" else ["ssh", SERVER2, "python3", "-", str(T)]
|
| 121 |
+
res = subprocess.run(cmd, input=COLLECT, capture_output=True, text=True, check=True)
|
| 122 |
+
return json.loads(res.stdout)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def ts(s: str) -> pd.Timestamp:
|
| 126 |
+
return pd.Timestamp(s)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def build_runs() -> pd.DataFrame:
|
| 130 |
+
got = {h: collect(h) for h in ("server_1", "server_2")}
|
| 131 |
+
rows = []
|
| 132 |
+
for ds in ORDER:
|
| 133 |
+
for j in DRAWS:
|
| 134 |
+
k = f"{ds}|{j}"
|
| 135 |
+
# LoRA: the host that holds both the trained adapter and the generated cells
|
| 136 |
+
lh = [h for h in got if "lora_train" in got[h].get(k, {}) and "lora_out" in got[h].get(k, {})]
|
| 137 |
+
if len(lh) != 1:
|
| 138 |
+
raise SystemExit(f"{k}: LoRA-5 run found on {lh or 'no host'}")
|
| 139 |
+
r = got[lh[0]][k]
|
| 140 |
+
log = r.get("lora_sample_log") or {}
|
| 141 |
+
if len(log.get("starts", [])) != 1 or len(log.get("ends", [])) != 1:
|
| 142 |
+
raise SystemExit(f"{k}: expected one sampling start and end in {lh[0]} queue logs, got {log}")
|
| 143 |
+
(t0, src0), (t1, src1) = log["starts"][0], log["ends"][0]
|
| 144 |
+
gen_s = (ts(t1) - ts(t0)).total_seconds()
|
| 145 |
+
train_s = float(r["lora_train"]["wall_seconds"])
|
| 146 |
+
if r["lora_train"]["steps_run"] != 3000 or not (0 < gen_s < 6 * 3600):
|
| 147 |
+
raise SystemExit(f"{k}: unexpected LoRA record {r['lora_train']} / sampling {gen_s} s")
|
| 148 |
+
nb = int(r["lora_out"]["bulks"])
|
| 149 |
+
rows.append(dict(cohort=ds, draw=j, method="lora", host=lh[0], n_test=nb, step1_s=train_s, step2_s=gen_s,
|
| 150 |
+
step1="fine-tune (3,000 steps)", step2="generate 1,500 cells per test sample",
|
| 151 |
+
src1=r["lora_train"]["src"], src2=f"{src0} [{t0} -> {t1}]"))
|
| 152 |
+
# scSemiProfiler: the host with the validated export; train time from that host's final model receipts
|
| 153 |
+
sh = [h for h in got if "scsemi_export" in got[h].get(k, {})]
|
| 154 |
+
if len(sh) != 1:
|
| 155 |
+
raise SystemExit(f"{k}: scSemiProfiler export found on {sh or 'no host'}")
|
| 156 |
+
r = got[sh[0]][k]
|
| 157 |
+
ex = r["scsemi_export"]
|
| 158 |
+
rec = [x for x in r["scsemi_pretrain"] if x["complete"] and x["run_signature"] == ex["run_signature"]]
|
| 159 |
+
n_reps = int(r["scsemi_n_reps"])
|
| 160 |
+
stages = sorted((x["stage"], x["representative"]) for x in rec)
|
| 161 |
+
if len(rec) != 2 * n_reps or len(set(stages)) != len(stages):
|
| 162 |
+
raise SystemExit(f"{k}: {len(rec)} complete pretrain receipts on {sh[0]}, expected 2 x {n_reps}")
|
| 163 |
+
if int(ex["bulks"]) != nb:
|
| 164 |
+
raise SystemExit(f"{k}: scSemiProfiler scored {ex['bulks']} test samples, LoRA {nb}")
|
| 165 |
+
rows.append(dict(cohort=ds, draw=j, method="scsemi", host=sh[0], n_test=int(ex["bulks"]),
|
| 166 |
+
step1_s=float(sum(x["elapsed_seconds"] for x in rec)),
|
| 167 |
+
step2_s=float(ex["total_target_seconds"]),
|
| 168 |
+
step1=f"train on {n_reps} representatives (2 stages each)",
|
| 169 |
+
step2="one model per test sample",
|
| 170 |
+
src1=str(Path(rec[0]["file"]).parent) + "/*.receipt.json", src2=ex["src"]))
|
| 171 |
+
d = pd.DataFrame(rows)
|
| 172 |
+
d["total_s"] = d.step1_s + d.step2_s
|
| 173 |
+
d["per_test_s"] = d.total_s / d.n_test
|
| 174 |
+
return d
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def summarise(d: pd.DataFrame) -> pd.DataFrame:
|
| 178 |
+
g = d.groupby(["cohort", "method"], sort=False)
|
| 179 |
+
s = g.agg(n_draws=("draw", "size"), n_test_min=("n_test", "min"), n_test_max=("n_test", "max"),
|
| 180 |
+
step1_min_mean=("step1_s", lambda x: x.mean() / 60), step2_min_mean=("step2_s", lambda x: x.mean() / 60),
|
| 181 |
+
total_min_mean=("total_s", lambda x: x.mean() / 60), total_min_sd=("total_s", lambda x: x.std(ddof=1) / 60),
|
| 182 |
+
total_min_min=("total_s", lambda x: x.min() / 60), total_min_max=("total_s", lambda x: x.max() / 60),
|
| 183 |
+
per_test_s_mean=("per_test_s", "mean")).reset_index()
|
| 184 |
+
w = d.pivot_table(index=["cohort", "draw"], columns="method", values="total_s")
|
| 185 |
+
ratio = (w["scsemi"] / w["lora"]).groupby(level=0)
|
| 186 |
+
s["speedup_mean"] = s.cohort.map(ratio.mean())
|
| 187 |
+
s["speedup_min"] = s.cohort.map(ratio.min())
|
| 188 |
+
s["speedup_max"] = s.cohort.map(ratio.max())
|
| 189 |
+
return s
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def fmt_t(minutes: float) -> str:
|
| 193 |
+
return f"{minutes:.0f} min" if minutes < 90 else f"{minutes / 60:.1f} h"
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def draw(d: pd.DataFrame, s: pd.DataFrame) -> None:
|
| 197 |
+
fig, (ax, bx) = plt.subplots(1, 2, figsize=(12.3, 4.6), gridspec_kw={"width_ratios": [2.1, 1.0], "wspace": 0.12})
|
| 198 |
+
h, gap = 0.36, 0.42
|
| 199 |
+
yt, ylab = [], []
|
| 200 |
+
for i, ds in enumerate(ORDER):
|
| 201 |
+
y0 = i * (2 * h + gap)
|
| 202 |
+
for k, m in enumerate(("scsemi", "lora")):
|
| 203 |
+
y = y0 + k * h
|
| 204 |
+
r = s[(s.cohort == ds) & (s.method == m)].iloc[0]
|
| 205 |
+
a, b = r.step1_min_mean / 60, r.step2_min_mean / 60
|
| 206 |
+
ax.barh(y, a, h * 0.9, color=COL[m], edgecolor="none")
|
| 207 |
+
ax.barh(y, b, h * 0.9, left=a, color=PALE[m], edgecolor="none")
|
| 208 |
+
tot = d[(d.cohort == ds) & (d.method == m)].total_s.to_numpy() / 3600
|
| 209 |
+
ax.errorbar(tot.mean(), y, xerr=tot.std(ddof=1), fmt="none", ecolor=EDGE, elinewidth=1, capsize=2.5)
|
| 210 |
+
ax.scatter(tot, np.full(tot.size, y), s=13, facecolor="white", edgecolor=EDGE, linewidth=0.8, zorder=3)
|
| 211 |
+
label = fmt_t(r.total_min_mean)
|
| 212 |
+
if m == "lora":
|
| 213 |
+
label += f" ({r.speedup_mean:.0f}× less)"
|
| 214 |
+
ax.text(max(tot.max(), a + b) + 0.06, y, label, va="center", ha="left", fontsize=FS - 2,
|
| 215 |
+
color=INK if m == "lora" else SUB, fontweight="bold" if m == "lora" else "normal")
|
| 216 |
+
yt.append(y0 + h / 2)
|
| 217 |
+
r = s[(s.cohort == ds) & (s.method == "lora")].iloc[0]
|
| 218 |
+
nt = f"{r.n_test_min}" if r.n_test_min == r.n_test_max else f"{r.n_test_min}–{r.n_test_max}"
|
| 219 |
+
ylab.append(f"{ROWNAME[ds]}\n{nt} test samples")
|
| 220 |
+
ax.set_yticks(yt, ylab, fontsize=FS - 2)
|
| 221 |
+
ax.invert_yaxis()
|
| 222 |
+
ax.set_xlabel("GPU time per draw (h)")
|
| 223 |
+
ax.set_xlim(0, None)
|
| 224 |
+
ax.tick_params(axis="y", length=0)
|
| 225 |
+
# per test sample, log scale
|
| 226 |
+
for i, ds in enumerate(ORDER):
|
| 227 |
+
y0 = i * (2 * h + gap)
|
| 228 |
+
for k, m in enumerate(("scsemi", "lora")):
|
| 229 |
+
v = d[(d.cohort == ds) & (d.method == m)].per_test_s.to_numpy()
|
| 230 |
+
bx.scatter(v, np.full(v.size, y0 + k * h), s=26, color=COL[m], edgecolor=EDGE, linewidth=0.6, zorder=3)
|
| 231 |
+
bx.set_xscale("log")
|
| 232 |
+
bx.set_yticks(yt, [""] * len(yt))
|
| 233 |
+
bx.tick_params(axis="y", length=0)
|
| 234 |
+
bx.set_ylim(ax.get_ylim()) # same rows as the bars (ax is already inverted)
|
| 235 |
+
bx.set_title("Per test sample (dots = draws)", fontsize=FS - 2)
|
| 236 |
+
bx.set_xlabel("GPU seconds per test sample")
|
| 237 |
+
bx.grid(axis="x", which="major", color="#E3E3E3", linewidth=0.8)
|
| 238 |
+
bx.set_axisbelow(True)
|
| 239 |
+
handles = [Patch(color=COL["scsemi"], label="scSemiProfiler: train on representatives"),
|
| 240 |
+
Patch(color=PALE["scsemi"], label="scSemiProfiler: one model per test sample"),
|
| 241 |
+
Patch(color=COL["lora"], label="LoRA: fine-tune once"),
|
| 242 |
+
Patch(color=PALE["lora"], label="LoRA: generate cells")]
|
| 243 |
+
fig.legend(handles=handles, loc="lower center", ncol=2, bbox_to_anchor=(0.42, -0.13), fontsize=FS - 2,
|
| 244 |
+
handlelength=1.2, columnspacing=1.6)
|
| 245 |
+
style.save(fig, "sec09_time_to_apply", FIGDIR)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
INK = style.INK
|
| 249 |
+
# one-time pretraining wall hours, from the section 6 source table (no hard-coded value; 2026-10-06)
|
| 250 |
+
_ft = pd.read_csv(OUTDATA / "sec06_ft_method.csv").set_index("key")
|
| 251 |
+
PRETRAIN_H = float(_ft.loc["pretrain_wall_hours", "value"])
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def slide_text(d: pd.DataFrame, s: pd.DataFrame) -> dict:
|
| 255 |
+
lo, sc = s[s.method == "lora"], s[s.method == "scsemi"]
|
| 256 |
+
w = d.pivot_table(index=["cohort", "draw"], columns="method", values="total_s")
|
| 257 |
+
rat = w["scsemi"] / w["lora"]
|
| 258 |
+
per_lo = d[d.method == "lora"].groupby("cohort").per_test_s.mean()
|
| 259 |
+
per_sc = d[d.method == "scsemi"].groupby("cohort").per_test_s.mean()
|
| 260 |
+
kw = [f"LoRA-5: {lo.total_min_mean.min():.0f}–{lo.total_min_mean.max():.0f} min per draw, every test sample",
|
| 261 |
+
f"scSemiProfiler-5: {fmt_t(sc.total_min_mean.min())}–{fmt_t(sc.total_min_mean.max())} per draw",
|
| 262 |
+
f"{lo.speedup_mean.min():.0f}–{lo.speedup_mean.max():.0f}× less GPU time, same 5 donors"] # cohort means, as the figure
|
| 263 |
+
numbers = []
|
| 264 |
+
for ds in ORDER:
|
| 265 |
+
a = lo[lo.cohort == ds].iloc[0]
|
| 266 |
+
b = sc[sc.cohort == ds].iloc[0]
|
| 267 |
+
numbers.append({"value": f"{NAME[ds]}: LoRA-5 {a.total_min_mean:.1f} min (fine-tune {a.step1_min_mean:.1f} + "
|
| 268 |
+
f"generate {a.step2_min_mean:.1f}), scSemiProfiler-5 {b.total_min_mean:.0f} min "
|
| 269 |
+
f"(representatives {b.step1_min_mean:.0f} + per-sample models {b.step2_min_mean:.0f}); "
|
| 270 |
+
f"{a.speedup_min:.0f}–{a.speedup_max:.0f}× per draw; per test sample "
|
| 271 |
+
f"{per_lo[ds]:.1f} s vs {per_sc[ds]:.0f} s",
|
| 272 |
+
"source": "data/sec09_time_to_apply.csv"})
|
| 273 |
+
numbers.append({"value": f"PBISC one-time pretraining {PRETRAIN_H:.1f} h (not counted per draw)",
|
| 274 |
+
"source": "data/sec06_ft_method.csv (pretrain_wall_hours)"})
|
| 275 |
+
full = ("Same 25 draws as the previous slides (5 cohorts x 5 draws; same 5 training donors and test samples for "
|
| 276 |
+
"both methods). GPU time on one GB10, every step alone on the GPU (shared lock). LoRA-5: fine-tune = "
|
| 277 |
+
"RUN.json wall_seconds of the 3,000-step LoRA; generate = wall clock of the sampling job in the queue log "
|
| 278 |
+
"(model load + DDIM 50, 1,500 cells per test sample). scSemiProfiler-5 (upstream c2aea02, default "
|
| 279 |
+
"budget): stage 1 + stage 2 pretraining of every representative (model receipts) + its per-target "
|
| 280 |
+
"inference (5 ministages x 150 epochs, export receipt total_target_seconds). Not counted on either side: "
|
| 281 |
+
"CPU data preparation, scoring, work lost to interruptions, and PBISC's one-time pretraining "
|
| 282 |
+
f"({PRETRAIN_H:.1f} h; 'Fine-tuning with paired bulk + sc' slide), which every cohort reuses. scSemiProfiler time grows with the number of test samples because it trains one model per "
|
| 283 |
+
"sample. Per-draw ratio scSemiProfiler / LoRA: " +
|
| 284 |
+
"; ".join(f"{NAME[ds]} {rat.loc[ds].min():.0f}–{rat.loc[ds].max():.0f}×" for ds in ORDER) +
|
| 285 |
+
f" (all 25 draws {rat.min():.0f}–{rat.max():.0f}×; keyword and figure = mean of each cohort's 5 draws).")
|
| 286 |
+
return {"title": "5 donors: time to apply", "layout": "full",
|
| 287 |
+
"figures": [str(FIGDIR / "sec09_time_to_apply.png")], "keywords": kw,
|
| 288 |
+
"footnote_short": "One GB10 GPU; mean of 5 draws. Data prep and scoring not counted. "
|
| 289 |
+
f"PBISC pretraining ({PRETRAIN_H:.1f} h) is done once.",
|
| 290 |
+
"footnote": full, "numbers": numbers}
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def main() -> int:
|
| 294 |
+
d = build_runs()
|
| 295 |
+
s = summarise(d)
|
| 296 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 297 |
+
d.to_csv(OUTDATA / "sec09_time_to_apply_runs.csv", index=False)
|
| 298 |
+
s.to_csv(OUTDATA / "sec09_time_to_apply.csv", index=False)
|
| 299 |
+
draw(d, s)
|
| 300 |
+
txt = slide_text(d, s)
|
| 301 |
+
out = {"section": "09-time", "scripts": [str(Path(__file__).resolve())],
|
| 302 |
+
"generated_from": "tools/sec09_time_to_apply.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
|
| 303 |
+
(OUTDATA / "sec09_time_to_apply_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 304 |
+
with pd.option_context("display.width", 200):
|
| 305 |
+
print(s.round(2).to_string(index=False))
|
| 306 |
+
print("\n".join(txt["keywords"]))
|
| 307 |
+
return 0
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
if __name__ == "__main__":
|
| 311 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec10_other_tissues.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 10 slide of the 2026-09-30 paper-summary deck: other tissues from a few dozen pairs (2026-10-06).
|
| 3 |
+
|
| 4 |
+
User framing (2026-10-06), for the paper's Discussion: with pretraining, a LoRA of a few minutes gives a working PBISC
|
| 5 |
+
model; with enough compute, a few dozen paired bulk-sc samples plus pseudobulk recipes approach the same results
|
| 6 |
+
without a corpus (protocol-dependent). This does not weaken the pretraining result: it is a route to bulk-to-sc models
|
| 7 |
+
for other organs and tissues, the planned next step. The from-scratch evidence itself sits in the Supplementary.
|
| 8 |
+
|
| 9 |
+
CPU only; a comparison table drawn from the deck's own source tables (no new numbers):
|
| 10 |
+
data/sec07_no_pretraining.csv same cohort, same pairs (sepsis fold 0, 17 donors): composition, coverage,
|
| 11 |
+
disease logFC r, donor composition r, training minutes (RUN.json)
|
| 12 |
+
data/sec08_cross_scratch.csv pairs from other cohorts only (held-out sepsis, masked): coverage
|
| 13 |
+
data/secS_scratch_rare_states_bootstrap.csv rare states, mean of 13, donor bootstrap (tools/secS_scratch_rare_states.py)
|
| 14 |
+
data/sec06_ft_method.csv pretraining wall hours; data/sec01_model_numbers.csv corpus cells
|
| 15 |
+
plans/paired_crosscohort_20261002/generated_masked/.../<scratch arm>.log UMI share on never-measured genes
|
| 16 |
+
Outputs: figures/sec10_other_tissues.{png,pdf}, data/sec10_other_tissues.csv, data/sec10_other_tissues_slide_text.json
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
|
| 22 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 23 |
+
|
| 24 |
+
import json
|
| 25 |
+
import sys
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 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 sec09_paired_validation as S9 # noqa: E402 (deck rcParams and shared names)
|
| 34 |
+
import style # noqa: E402
|
| 35 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 36 |
+
from matplotlib.patches import Rectangle # noqa: E402
|
| 37 |
+
|
| 38 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 39 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 40 |
+
GM = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002/"
|
| 41 |
+
"generated_masked/ye2026_sepsis/hoL_ye2026_sepsis")
|
| 42 |
+
FS, SUB, EDGE, INK = S9.FS, S9.SUB, S9.EDGE, style.INK
|
| 43 |
+
SCRATCH = "#882255"
|
| 44 |
+
RUNS0 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 45 |
+
"paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0")
|
| 46 |
+
PRE = style.ARM["lora"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def main() -> int:
|
| 50 |
+
p7 = pd.read_csv(OUTDATA / "sec07_no_pretraining.csv")
|
| 51 |
+
pre, scr = p7[p7.arm == "pre"].set_index("group"), p7[p7.arm == "scratch"].set_index("group")
|
| 52 |
+
g5, gr = "5 pairs", "58 + recipes pairs"
|
| 53 |
+
if not {g5, gr} <= set(pre.index) or not {g5, gr} <= set(scr.index):
|
| 54 |
+
raise SystemExit("sec07_no_pretraining.csv lacks the 5-pair or recipe rows")
|
| 55 |
+
n_rec = int(pre.loc[gr, "train_rows"])
|
| 56 |
+
summ = {json.loads(Path(x.split(";")[0].strip()).read_text())["n_donors"] for x in p7.source}
|
| 57 |
+
if len(summ) != 1:
|
| 58 |
+
raise SystemExit("same-cohort arms scored on different donor sets")
|
| 59 |
+
n_held = summ.pop()
|
| 60 |
+
if int(scr.loc[gr, "train_rows"]) != n_rec:
|
| 61 |
+
raise SystemExit("recipe arms differ in training pairs")
|
| 62 |
+
# run receipts of the same-cohort arms: inner-validation pairs, scratch settings, recipe augmentation
|
| 63 |
+
rj = {a: json.loads((RUNS0 / a.replace("__raw", "") / "RUN.json").read_text()) for a in p7.score_arm.dropna()
|
| 64 |
+
if a != "zs__raw"}
|
| 65 |
+
ivs = {tuple(r["inner_val_rows"]) for r in rj.values()}
|
| 66 |
+
if len(ivs) != 1:
|
| 67 |
+
raise SystemExit("same-cohort runs differ in inner-validation pairs")
|
| 68 |
+
n_iv = len(ivs.pop())
|
| 69 |
+
sr = [rj[a] for a in scr.score_arm]
|
| 70 |
+
if len({(r["lr"], r["max_steps"], tuple(r["kept_from_checkpoint"])) for r in sr}) != 1:
|
| 71 |
+
raise SystemExit("scratch runs differ in lr / step cap / kept checkpoint parts")
|
| 72 |
+
at_cap = [g for g, a in zip(scr.index, scr.score_arm) if rj[a]["selected_step"] == rj[a]["steps_run"] == rj[a]["max_steps"]]
|
| 73 |
+
aug = rj[pre.loc[gr, "score_arm"]]["augmentation"]
|
| 74 |
+
if aug != rj[scr.loc[gr, "score_arm"]]["augmentation"]:
|
| 75 |
+
raise SystemExit("recipe arms differ in augmentation")
|
| 76 |
+
x8 = pd.read_csv(OUTDATA / "sec08_cross_scratch.csv").set_index("arm")
|
| 77 |
+
n_x8 = {len(json.loads(Path(x).read_text())["donors"]) for x in x8.source}
|
| 78 |
+
if len(n_x8) != 1:
|
| 79 |
+
raise SystemExit("cross-cohort arms scored on different donor sets")
|
| 80 |
+
n_x8 = n_x8.pop()
|
| 81 |
+
bt = pd.read_csv(OUTDATA / "secS_scratch_rare_states_bootstrap.csv")
|
| 82 |
+
rc = bt[bt.comparison == "58 pairs + recipes: scratch vs pretrained"]
|
| 83 |
+
agg = rc[rc.state.str.startswith("MEAN")].iloc[0]
|
| 84 |
+
# per-state calls that count: significant, marker states (not scANVI labels), and not a state both arms miss
|
| 85 |
+
calls = rc[~rc.state.str.startswith("MEAN") & ~rc.state.str.endswith("(label)") & ~rc.both_fail.astype(bool)]
|
| 86 |
+
short = lambda st: st.split(" (")[0].replace("DN2 / ABC B", "DN2 B")
|
| 87 |
+
closer = {side: ", ".join(short(x) for x in calls[calls.verdict == f"{side} closer"].state) or "none"
|
| 88 |
+
for side in ("pretrained", "scratch")}
|
| 89 |
+
ft = pd.read_csv(OUTDATA / "sec06_ft_method.csv").set_index("key")
|
| 90 |
+
mn = pd.read_csv(OUTDATA / "sec01_model_numbers.csv").set_index("key")
|
| 91 |
+
pre_h = float(ft.loc["pretrain_wall_hours", "value"])
|
| 92 |
+
cells, corpus = float(mn.loc["train_split_cells", "value"]), float(mn.loc["corpus_cells", "value"])
|
| 93 |
+
logs = sorted(GM.glob("locoL_scratchsat_*.log"))
|
| 94 |
+
shares = [json.loads(f.read_text())["generated_umi_share_masked_before"] for f in logs]
|
| 95 |
+
n_mask = {json.loads(f.read_text())["n_masked"] for f in logs}
|
| 96 |
+
if len(n_mask) != 1:
|
| 97 |
+
raise SystemExit("scratch milestones masked different gene counts")
|
| 98 |
+
n_mask = n_mask.pop()
|
| 99 |
+
|
| 100 |
+
# rows: label, pretrained, scratch, which side is better (None = similar / not scored), source
|
| 101 |
+
def b(a, c, hi=True, tol=0.05):
|
| 102 |
+
return None if abs(a - c) < tol else ("pre" if (a > c) == hi else "scr")
|
| 103 |
+
rows = [
|
| 104 |
+
("Corpus pretraining", f"{cells / 1e6:.1f} M train cells, {pre_h:.1f} h, once", "none", None,
|
| 105 |
+
"sec01_model_numbers.csv train_split_cells; sec06_ft_method.csv pretrain_wall_hours"),
|
| 106 |
+
("Training, sepsis fold 0 (one GPU)", f"{pre.minutes.min():.0f}–{pre.minutes.max():.0f} min",
|
| 107 |
+
f"{scr.minutes.min():.0f}–{scr.minutes.max():.0f} min", "pre", "sec07_no_pretraining.csv minutes"),
|
| 108 |
+
("5 pairs: donor composition r", f"{pre.loc[g5, 'comp_r']:.2f}", f"{scr.loc[g5, 'comp_r']:.2f}",
|
| 109 |
+
b(pre.loc[g5, "comp_r"], scr.loc[g5, "comp_r"]), "sec07_no_pretraining.csv comp_r"),
|
| 110 |
+
(f"{n_rec} pairs + recipes: donor composition r", f"{pre.loc[gr, 'comp_r']:.2f}", f"{scr.loc[gr, 'comp_r']:.2f}",
|
| 111 |
+
b(pre.loc[gr, "comp_r"], scr.loc[gr, "comp_r"]), "sec07_no_pretraining.csv comp_r"),
|
| 112 |
+
(f"{n_rec} pairs + recipes: coverage", f"{pre.loc[gr, 'coverage']:.2f}", f"{scr.loc[gr, 'coverage']:.2f}",
|
| 113 |
+
b(pre.loc[gr, "coverage"], scr.loc[gr, "coverage"]), "sec07_no_pretraining.csv coverage"),
|
| 114 |
+
(f"{n_rec} pairs + recipes: disease logFC r", f"{pre.loc[gr, 'logfc_r']:.2f}", f"{scr.loc[gr, 'logfc_r']:.2f}",
|
| 115 |
+
b(pre.loc[gr, "logfc_r"], scr.loc[gr, "logfc_r"]), "sec07_no_pretraining.csv logfc_r"),
|
| 116 |
+
(f"{n_rec} pairs + recipes: 13 rare states, " + ("n.s. on average" if agg.verdict == "n.s." else agg.verdict),
|
| 117 |
+
f"closer on {closer['pretrained']}", f"closer on {closer['scratch']}", None,
|
| 118 |
+
"secS_scratch_rare_states_bootstrap.csv"),
|
| 119 |
+
("Other cohorts' pairs only (sepsis held out): coverage", f"{x8.loc['r16', 'coverage']:.2f} (LoRA r16)",
|
| 120 |
+
f"{x8.loc['scratch', 'coverage']:.2f}", b(x8.loc["r16", "coverage"], x8.loc["scratch", "coverage"]),
|
| 121 |
+
"sec08_cross_scratch.csv coverage (masked)"),
|
| 122 |
+
]
|
| 123 |
+
pd.DataFrame(rows, columns=["row", "pretrained_lora", "from_scratch", "better", "source"]).to_csv(
|
| 124 |
+
OUTDATA / "sec10_other_tissues.csv", index=False)
|
| 125 |
+
|
| 126 |
+
# ---- table figure
|
| 127 |
+
fig = plt.figure(figsize=(12.3, 4.5))
|
| 128 |
+
ax = fig.add_axes([0, 0, 1, 1])
|
| 129 |
+
ax.set_xlim(0, 12.3)
|
| 130 |
+
ax.set_ylim(0, 4.5)
|
| 131 |
+
ax.axis("off")
|
| 132 |
+
x_lab, x_pre, x_scr, w_col = 0.15, 6.15, 9.2, 3.0
|
| 133 |
+
top, rh = 4.05, 0.47
|
| 134 |
+
for x, lab, col in ((x_pre, "Pretrained + LoRA", PRE), (x_scr, "From scratch", SCRATCH)):
|
| 135 |
+
ax.add_patch(Rectangle((x - 0.05, top), w_col - 0.1, 0.4, color=col, lw=0))
|
| 136 |
+
ax.text(x + (w_col - 0.2) / 2, top + 0.2, lab, ha="center", va="center", color="white", fontsize=FS,
|
| 137 |
+
fontweight="bold")
|
| 138 |
+
for i, (lab, a, c, better, _) in enumerate(rows):
|
| 139 |
+
y = top - (i + 1) * rh
|
| 140 |
+
if i % 2 == 0:
|
| 141 |
+
ax.add_patch(Rectangle((0.05, y), 12.2, rh, color="#F4F4F4", lw=0, zorder=0))
|
| 142 |
+
ax.text(x_lab, y + rh / 2, lab, ha="left", va="center", fontsize=FS - 2, color=INK)
|
| 143 |
+
for x, v, side in ((x_pre, a, "pre"), (x_scr, c, "scr")):
|
| 144 |
+
ax.text(x + (w_col - 0.2) / 2, y + rh / 2, v, ha="center", va="center", fontsize=FS - 2,
|
| 145 |
+
color=INK, fontweight="bold" if better == side else "normal")
|
| 146 |
+
style.save(fig, "sec10_other_tissues", FIGDIR)
|
| 147 |
+
|
| 148 |
+
# ---- slide text
|
| 149 |
+
close = all(scr.loc[gr, m] >= pre.loc[gr, m] - 0.05 for m in ("comp_r", "coverage", "logfc_r"))
|
| 150 |
+
kw = [f"Pretrained: a {pre.loc[g5, 'minutes']:.0f}-min LoRA works from 5 pairs",
|
| 151 |
+
f"Scratch: {n_rec} pairs + recipes come close ({scr.loc[gr, 'minutes']:.0f} min)" if close
|
| 152 |
+
else f"Scratch: {n_rec} pairs + recipes, {scr.loc[gr, 'minutes']:.0f} min",
|
| 153 |
+
"Next: test this route on other tissues"]
|
| 154 |
+
say = ("Pretraining is what makes PBISC practical: a LoRA of a few minutes on as few as five pairs. In a one-fold "
|
| 155 |
+
"sepsis pilot, though, with enough compute, a few dozen paired bulk and single-cell samples plus pseudobulk "
|
| 156 |
+
"recipes came close to the same results without corpus pretraining, and the outcome depends on the training "
|
| 157 |
+
"protocol. This does not weaken the pretraining result. It suggests that a PBISC-like bulk-to-single-cell "
|
| 158 |
+
"model could be built for other organs and tissues that have no large single-cell corpus yet. Folds 1 to 4 "
|
| 159 |
+
"and a second cohort will test this first.")
|
| 160 |
+
names = {"model_config": "the architecture", "diffusion_config": "the diffusion settings",
|
| 161 |
+
"gene panel": "the 6k gene panel", "value_scaler": "the value scaler",
|
| 162 |
+
"conditioner z-score constants": "the bulk z-score constants"}
|
| 163 |
+
kept = [names.get(k, k) for k in sr[0]["kept_from_checkpoint"]]
|
| 164 |
+
kept = ", ".join(kept[:-1]) + " and " + kept[-1]
|
| 165 |
+
kgrid = aug["recipe_k_grid"]
|
| 166 |
+
full = (f"Discussion point; the from-scratch evidence is in the Supplementary. Same cohort, same pairs: sepsis "
|
| 167 |
+
f"fold 0, {n_held} held-out donors; every run also early-stops on the same "
|
| 168 |
+
f"{n_iv} inner-validation pairs. From scratch = the same denoiser at random initialisation, full training "
|
| 169 |
+
f"(lr {sr[0]['lr']:.0e}".replace("e-0", "e-") + f", inner-val selection, cap {sr[0]['max_steps'] // 1000}k "
|
| 170 |
+
f"steps" + (f"; the {' and '.join(g.replace(' + recipes pairs', '-pair + recipes').replace(' pairs', '-pair') for g in at_cap)} "
|
| 171 |
+
f"runs were still improving at the cap" if at_cap else "") +
|
| 172 |
+
f"). It still took {kept} from the PBMC checkpoint, so a corpus-free setup (panel and scalers built from the "
|
| 173 |
+
f"pairs alone) is untested. Recipes = {aug['recipe_frac']:.0%} of each batch is pseudobulk built from the "
|
| 174 |
+
f"training donors' own cells, K from the pretraining grid ({kgrid[0]:,}–{kgrid[-1]:,}). Bold = higher by "
|
| 175 |
+
f"0.05 or more (one fold, no interval), or less training time per cohort; the pretraining row is not scored. "
|
| 176 |
+
f"Rare states: mean |log2 gen/obs| over 13 states, scratch minus pretrained {agg.D:+.2f} [{agg.lo:+.2f}, "
|
| 177 |
+
f"{agg.hi:+.2f}] (donor bootstrap, {agg.verdict}); per-state calls = significant, marker states only, "
|
| 178 |
+
f"excluding states that both arms miss by more than 4-fold. Protocol dependence: recipes, the step budget, "
|
| 179 |
+
f"and the gene space - a scratch model learns only genes measured in its training pairs (trained on other "
|
| 180 |
+
f"cohorts, it put {100 * min(shares):.0f}–{100 * max(shares):.0f}% of its UMI on the {n_mask} genes that "
|
| 181 |
+
f"none of those cohorts measured). Pairs from other cohorts do not replace the target cohort's own: "
|
| 182 |
+
f"own-cohort LoRA coverage {x8.loc['own', 'coverage']:.2f} on held-out sepsis. Pilot only: folds 1–4 and a "
|
| 183 |
+
f"second cohort are needed before the claim. Pretraining ({pre_h:.1f} h on {cells / 1e6:.1f} M train cells "
|
| 184 |
+
f"of the {corpus / 1e6:.1f} M-cell corpus) is done once and reused by every cohort.")
|
| 185 |
+
txt = {"title": "Next: other tissues from a few dozen pairs", "layout": "full",
|
| 186 |
+
"figures": [str(FIGDIR / "sec10_other_tissues.png")], "keywords": kw,
|
| 187 |
+
"footnote_short": f"Pilots: sepsis fold 0 ({n_held} donors); last row held-out sepsis ({n_x8}). Folds 1–4 "
|
| 188 |
+
"and a second cohort pending.",
|
| 189 |
+
"footnote": full, "say": say,
|
| 190 |
+
"numbers": [{"value": f"{r[0]}: pretrained {r[1]} / scratch {r[2]}", "source": f"data/{r[4]}"} for r in rows]}
|
| 191 |
+
out = {"section": "10-other-tissues", "scripts": [str(Path(__file__).resolve())],
|
| 192 |
+
"generated_from": "tools/sec10_other_tissues.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
|
| 193 |
+
(OUTDATA / "sec10_other_tissues_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 194 |
+
print("\n".join(kw))
|
| 195 |
+
for r in rows:
|
| 196 |
+
print(f" {r[0]}: {r[1]} | {r[2]} | better={r[3]}")
|
| 197 |
+
print(full)
|
| 198 |
+
return 0
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
if __name__ == "__main__":
|
| 202 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261005T175437Z-deck-supplementary-other-tissues-review/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/secS_scratch_rare_states.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Supplementary slide of the 2026-09-30 paper-summary deck: rare cell states, from scratch vs pretrained (2026-10-06).
|
| 3 |
+
|
| 4 |
+
User decision 2026-10-06: the from-scratch results go to the paper's Supplementary (Discussion: a route to other
|
| 5 |
+
tissues). CPU only. Reads the rare-state screen of plans/rare_states_screen_20261004 (tools/sepsis_states.py; rules
|
| 6 |
+
tools/states.json; observed cells binomially thinned to each arm's generated depth; label states unthinned):
|
| 7 |
+
same cohort out/sepsis_fold0_{summary,per_donor}.csv sepsis fold 0, 17 held-out donors, same training
|
| 8 |
+
pairs for both initialisations: LoRA-5 vs scratch-5, LoRA-58 / full FT-58 vs scratch-58,
|
| 9 |
+
LoRA+recipes vs scratch+recipes (58 pairs)
|
| 10 |
+
other cohorts out/sepsis_loco_masked_{summary,per_donor}.csv all 82 sepsis donors held out, trained on ImMicro +
|
| 11 |
+
Imperial + Giroux + Liu pairs; the 46 genes no training cohort measured are zeroed in every arm (the
|
| 12 |
+
scratch model is never trained on them), as in the cross-cohort benchmark's scores_masked/
|
| 13 |
+
gen/obs = generated state % of parent / observed % (1 = same rate). The donor bootstrap (2,000 resamples, seed
|
| 14 |
+
20261005) of D = |log2 gen/obs| scratch - |log2 gen/obs| pretrained uses pooled counts + 0.5, the estimator of
|
| 15 |
+
out/scratch_vs_lora_20261005/ (whose REPORT.md has the full analysis and its two verification passes); D > 0 =
|
| 16 |
+
pretrained closer. The summary CSVs' gen_over_obs must equal the pooled per-donor counts (checked).
|
| 17 |
+
Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders):
|
| 18 |
+
figures/secS_scratch_rare_states.{png,pdf}
|
| 19 |
+
data/secS_scratch_rare_states.csv every plotted value with its source
|
| 20 |
+
data/secS_scratch_rare_states_bootstrap.csv aggregate and per-state D with 95 % CIs
|
| 21 |
+
data/secS_scratch_rare_states_slide_text.json
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import os
|
| 26 |
+
|
| 27 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
|
| 28 |
+
|
| 29 |
+
import json
|
| 30 |
+
import sys
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import pandas as pd
|
| 35 |
+
|
| 36 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 37 |
+
"2026-09-30--paper-summary--r00")
|
| 38 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 39 |
+
import sec09_paired_validation as S9 # noqa: E402 (deck rcParams and shared names)
|
| 40 |
+
import style # noqa: E402
|
| 41 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 42 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 43 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 44 |
+
|
| 45 |
+
RS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 46 |
+
M8P = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans")
|
| 47 |
+
TI_RUNS = M8P / "paired_finetune_intradataset_20260927" / "runs" / "ye2026_sepsis" / "fold0"
|
| 48 |
+
GM = M8P / "paired_crosscohort_20261002" / "generated_masked" / "ye2026_sepsis" / "hoL_ye2026_sepsis"
|
| 49 |
+
FOLDS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
|
| 50 |
+
"paired_finetune_intradataset_20260927/data/ye2026_sepsis/folds.csv")
|
| 51 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 52 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 53 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 54 |
+
SCRATCH = "#882255" # as tools/sec07_no_pretraining.py and tools/sec08_cross_scratch.py
|
| 55 |
+
CONTROLS = {"ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"}
|
| 56 |
+
SHOW = [("C1Q-high monocyte (reference)", "C1Q-high mono"), ("MS1 monocyte (IL1R2+)", "MS1 mono"),
|
| 57 |
+
("Cycling monocyte (Ye 2026)", "Cycling mono"), ("Cycling T/NK", "Cycling T/NK"),
|
| 58 |
+
("ISG-high T", "ISG-high T"), ("Plasmablast (label)", "Plasmablast (label)"), ("DN2 / ABC B", "DN2 B"),
|
| 59 |
+
("Granulocyte-like (LDG)", "Granulocyte-like")]
|
| 60 |
+
WITHIN = {"scope": "fold0", "prefix": "sepsis_fold0", "n_donors": 17,
|
| 61 |
+
"settings": [("5 pairs", "lora_n5__raw", "scratch_n5__raw"),
|
| 62 |
+
("58 pairs", "real_lora__raw", "scratch_full__raw"),
|
| 63 |
+
("58 pairs, full FT", "real_full__raw", "scratch_full__raw"),
|
| 64 |
+
("58 pairs + recipes", "lora_recipe__raw", "scratch_recipe__raw")],
|
| 65 |
+
"plot": [("5 pairs", "o"), ("58 pairs + recipes", "D")]}
|
| 66 |
+
CROSS = {"prefix": "sepsis_loco_masked", "n_donors": 82, "scratch": "locoL_scratchsat_s162000_K1000",
|
| 67 |
+
"scratch50": "locoL_scratchsat_s50000_K1000",
|
| 68 |
+
"comps": [("LoRA r16", "locoL_lora16sat_s26750_K1000"), ("LoRA r64", "locoL_lora64sat_s59000_K1000"),
|
| 69 |
+
("Full FT", "locoL_fullsat_s108500_K1000"), ("Calibration", "xcalL_K1000")],
|
| 70 |
+
"own": "within_real_lora__raw",
|
| 71 |
+
"plot": [("Own-cohort LoRA (reference)", "within_real_lora__raw", style.ARM["lora"], "o", True),
|
| 72 |
+
("Calibration", "xcalL_K1000", "#0072B2", "s", False),
|
| 73 |
+
("LoRA r16", "locoL_lora16sat_s26750_K1000", "#44AA99", "^", False),
|
| 74 |
+
("Full FT", "locoL_fullsat_s108500_K1000", "#332288", "v", False),
|
| 75 |
+
("From scratch", "locoL_scratchsat_s162000_K1000", SCRATCH, "D", False)]}
|
| 76 |
+
B, SEED = 2000, 20261005
|
| 77 |
+
FAIL = 2.0 # |log2 gen/obs| above this (more than 4-fold off) in both arms = both fail; such a call is no win
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load(prefix: str):
|
| 81 |
+
s = pd.read_csv(RS / "out" / f"{prefix}_summary.csv")
|
| 82 |
+
p = pd.read_csv(RS / "out" / f"{prefix}_per_donor.csv")
|
| 83 |
+
for r in s.itertuples(): # the plotted ratio must be the pooled per-donor counts
|
| 84 |
+
t = p[(p.arm == r.arm) & (p.state == r.state)]
|
| 85 |
+
ro = t.obsthin_state.sum() / max(t.obs_parent.sum(), 1)
|
| 86 |
+
rg = t.gen_state.sum() / max(t.gen_parent.sum(), 1)
|
| 87 |
+
if ro > 0 and not np.isclose(rg / ro, r.gen_over_obs, rtol=1e-9):
|
| 88 |
+
raise SystemExit(f"{prefix} {r.arm} {r.state}: summary ratio differs from the per-donor counts")
|
| 89 |
+
return s, p
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class Boot:
|
| 93 |
+
"""Donor bootstrap of pooled (+0.5) gen/obs ratios, one shared resample matrix per scope."""
|
| 94 |
+
|
| 95 |
+
def __init__(self, per: pd.DataFrame):
|
| 96 |
+
self.per = per
|
| 97 |
+
self.donors = sorted(per.donor.unique())
|
| 98 |
+
self.idx = np.random.default_rng(SEED).integers(0, len(self.donors), size=(B, len(self.donors)))
|
| 99 |
+
self.cache = {}
|
| 100 |
+
|
| 101 |
+
def counts(self, arm, st):
|
| 102 |
+
if (arm, st) not in self.cache:
|
| 103 |
+
t = self.per[(self.per.arm == arm) & (self.per.state == st)].set_index("donor").reindex(self.donors)
|
| 104 |
+
if t.gen_parent.isna().any():
|
| 105 |
+
raise SystemExit(f"{arm} {st}: donors missing")
|
| 106 |
+
self.cache[(arm, st)] = [t[c].to_numpy(float) for c in ("gen_state", "gen_parent", "obsthin_state",
|
| 107 |
+
"obs_parent")]
|
| 108 |
+
return self.cache[(arm, st)]
|
| 109 |
+
|
| 110 |
+
def ratio(self, arm, st, boot=False):
|
| 111 |
+
gs, gp, os_, op = self.counts(arm, st)
|
| 112 |
+
if not boot:
|
| 113 |
+
return ((gs.sum() + .5) / gp.sum()) / ((os_.sum() + .5) / op.sum())
|
| 114 |
+
i = self.idx
|
| 115 |
+
return ((gs[i].sum(1) + .5) / gp[i].sum(1)) / ((os_[i].sum(1) + .5) / op[i].sum(1))
|
| 116 |
+
|
| 117 |
+
def D(self, scr, pre, states):
|
| 118 |
+
"""point and 95 % CI of mean over states of |log2| scratch - |log2| pretrained"""
|
| 119 |
+
pt = np.mean([abs(np.log2(self.ratio(scr, s))) - abs(np.log2(self.ratio(pre, s))) for s in states])
|
| 120 |
+
bs = np.mean([np.abs(np.log2(self.ratio(scr, s, True))) - np.abs(np.log2(self.ratio(pre, s, True)))
|
| 121 |
+
for s in states], axis=0)
|
| 122 |
+
lo, hi = np.percentile(bs, [2.5, 97.5])
|
| 123 |
+
return float(pt), float(lo), float(hi)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def verdict(lo, hi):
|
| 127 |
+
return "pretrained closer" if lo > 0 else "scratch closer" if hi < 0 else "n.s."
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def main() -> int:
|
| 131 |
+
ws, wp = load(WITHIN["prefix"])
|
| 132 |
+
cs, cp = load(CROSS["prefix"])
|
| 133 |
+
if wp.donor.nunique() != WITHIN["n_donors"] or cp.donor.nunique() != CROSS["n_donors"]:
|
| 134 |
+
raise SystemExit("unexpected donor counts")
|
| 135 |
+
rare = [s for s in ws.state.unique() if s not in CONTROLS]
|
| 136 |
+
if sorted(rare) != sorted(s for s in cs.state.unique() if s not in CONTROLS) or len(rare) != 13:
|
| 137 |
+
raise SystemExit("state sets differ between the two scopes")
|
| 138 |
+
wb, cb = Boot(wp), Boot(cp)
|
| 139 |
+
W = ws.pivot(index="state", columns="arm", values="gen_over_obs")
|
| 140 |
+
C = cs.pivot(index="state", columns="arm", values="gen_over_obs")
|
| 141 |
+
|
| 142 |
+
# ---- bootstrap table
|
| 143 |
+
rows = []
|
| 144 |
+
for lab, pre, scr in WITHIN["settings"]:
|
| 145 |
+
for st in rare + ["MEAN of 13 rare states"]:
|
| 146 |
+
sts = rare if st.startswith("MEAN") else [st]
|
| 147 |
+
pt, lo, hi = wb.D(scr, pre, sts)
|
| 148 |
+
one = not st.startswith("MEAN")
|
| 149 |
+
rows.append({"scope": "same cohort (fold 0)", "comparison": f"{lab}: scratch vs pretrained", "state": st,
|
| 150 |
+
"D": pt, "lo": lo, "hi": hi, "verdict": verdict(lo, hi),
|
| 151 |
+
"gen_obs_scratch": W.loc[st, scr] if one else np.nan,
|
| 152 |
+
"gen_obs_pretrained": W.loc[st, pre] if one else np.nan})
|
| 153 |
+
for lab, arm in CROSS["comps"]:
|
| 154 |
+
for scr_lab, scr in (("scratch final", CROSS["scratch"]), ("scratch 50k", CROSS["scratch50"])):
|
| 155 |
+
for st in rare + ["MEAN of 13 rare states"]:
|
| 156 |
+
sts = rare if st.startswith("MEAN") else [st]
|
| 157 |
+
pt, lo, hi = cb.D(scr, arm, sts)
|
| 158 |
+
one = not st.startswith("MEAN")
|
| 159 |
+
rows.append({"scope": "other cohorts (masked)", "comparison": f"{scr_lab} vs {lab}", "state": st,
|
| 160 |
+
"D": pt, "lo": lo, "hi": hi, "verdict": verdict(lo, hi),
|
| 161 |
+
"gen_obs_scratch": C.loc[st, scr] if one else np.nan,
|
| 162 |
+
"gen_obs_pretrained": C.loc[st, arm] if one else np.nan})
|
| 163 |
+
BT = pd.DataFrame(rows)
|
| 164 |
+
BT["both_fail"] = (np.abs(np.log2(BT.gen_obs_scratch)) > FAIL) & (np.abs(np.log2(BT.gen_obs_pretrained)) > FAIL)
|
| 165 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 166 |
+
BT.to_csv(OUTDATA / "secS_scratch_rare_states_bootstrap.csv", index=False)
|
| 167 |
+
|
| 168 |
+
# ---- figure: two dot plots on a log axis
|
| 169 |
+
fig, (ax, bx) = plt.subplots(1, 2, figsize=(12.3, 4.7), sharey=True, gridspec_kw={"wspace": 0.06})
|
| 170 |
+
ylab = [s for _, s in SHOW]
|
| 171 |
+
yy = np.arange(len(SHOW))[::-1]
|
| 172 |
+
data_rows = []
|
| 173 |
+
for a in (ax, bx):
|
| 174 |
+
a.axvspan(0.5, 2.0, color="#EEEEEE", zorder=0)
|
| 175 |
+
a.axvline(1.0, color="#777777", lw=1.0, zorder=1)
|
| 176 |
+
a.set_xscale("log")
|
| 177 |
+
a.set_xlim(0.008, 8)
|
| 178 |
+
a.set_xticks([0.01, 0.1, 1, 5], ["0.01", "0.1", "1", "5"])
|
| 179 |
+
a.tick_params(axis="x", labelsize=FS - 3)
|
| 180 |
+
a.grid(axis="y", color="#F2F2F2", lw=0.8)
|
| 181 |
+
a.set_axisbelow(True)
|
| 182 |
+
off = {"5 pairs": 0.17, "58 pairs + recipes": -0.17}
|
| 183 |
+
for lab, mk in WITHIN["plot"]:
|
| 184 |
+
_, pre, scr = next(x for x in WITHIN["settings"] if x[0] == lab)
|
| 185 |
+
for y, (st, short) in zip(yy, SHOW):
|
| 186 |
+
vp, vs = W.loc[st, pre], W.loc[st, scr]
|
| 187 |
+
ax.plot([vp, vs], [y + off[lab]] * 2, color="#BBBBBB", lw=1.2, zorder=2)
|
| 188 |
+
ax.scatter([vp], [y + off[lab]], marker=mk, s=46, color=style.ARM["lora"], edgecolor=EDGE, lw=0.5, zorder=3)
|
| 189 |
+
ax.scatter([vs], [y + off[lab]], marker=mk, s=46, color=SCRATCH, edgecolor=EDGE, lw=0.5, zorder=3)
|
| 190 |
+
for arm, v, init in ((pre, vp, "pretrained + LoRA"), (scr, vs, "from scratch")):
|
| 191 |
+
data_rows.append({"panel": "same cohort", "setting": lab, "init": init, "arm": arm, "state": st,
|
| 192 |
+
"gen_over_obs": v, "source": str(RS / "out" / f"{WITHIN['prefix']}_summary.csv")})
|
| 193 |
+
ax.set_yticks(yy, ylab, fontsize=FS - 2)
|
| 194 |
+
ax.set_ylim(-0.6, len(SHOW) - 0.4)
|
| 195 |
+
ax.set_title(f"Same cohort, same pairs (sepsis, {WITHIN['n_donors']} donors)", fontsize=FS - 1)
|
| 196 |
+
ax.set_xlabel("Generated / observed rate (log)", fontsize=FS - 2)
|
| 197 |
+
k = len(CROSS["plot"])
|
| 198 |
+
for j, (lab, arm, col, mk, ref) in enumerate(CROSS["plot"]):
|
| 199 |
+
dy = 0.3 - j * 0.6 / (k - 1)
|
| 200 |
+
for y, (st, short) in zip(yy, SHOW):
|
| 201 |
+
v = C.loc[st, arm]
|
| 202 |
+
bx.scatter([v], [y + dy], marker=mk, s=40, color=col, edgecolor="black" if ref else EDGE,
|
| 203 |
+
lw=1.1 if ref else 0.5, zorder=3)
|
| 204 |
+
data_rows.append({"panel": "other cohorts", "setting": "held-out sepsis, masked", "init": lab, "arm": arm,
|
| 205 |
+
"state": st, "gen_over_obs": v,
|
| 206 |
+
"source": str(RS / "out" / f"{CROSS['prefix']}_summary.csv")})
|
| 207 |
+
bx.set_title(f"Other cohorts' pairs (held-out sepsis, {CROSS['n_donors']} donors)", fontsize=FS - 1)
|
| 208 |
+
bx.set_xlabel("Generated / observed rate (log)", fontsize=FS - 2)
|
| 209 |
+
h_a = [Patch(facecolor=style.ARM["lora"], edgecolor=EDGE, lw=0.5, label="Pretrained + LoRA"),
|
| 210 |
+
Patch(facecolor=SCRATCH, edgecolor=EDGE, lw=0.5, label="From scratch"),
|
| 211 |
+
Line2D([], [], ls="", marker="o", ms=7, color="white", mec=EDGE, label="5 pairs"),
|
| 212 |
+
Line2D([], [], ls="", marker="D", ms=6, color="white", mec=EDGE, label="58 pairs + recipes")]
|
| 213 |
+
h_b = [Line2D([], [], ls="", marker=mk, ms=7, color=col, mec="black" if ref else EDGE, label=lab)
|
| 214 |
+
for lab, _, col, mk, ref in CROSS["plot"]]
|
| 215 |
+
ax.legend(handles=h_a, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=2, fontsize=FS - 4,
|
| 216 |
+
frameon=False, handletextpad=0.3, columnspacing=1.0)
|
| 217 |
+
bx.legend(handles=h_b, loc="upper center", bbox_to_anchor=(0.5, -0.17), ncol=3, fontsize=FS - 4,
|
| 218 |
+
frameon=False, handletextpad=0.3, columnspacing=1.0)
|
| 219 |
+
style.save(fig, "secS_scratch_rare_states", FIGDIR)
|
| 220 |
+
pd.DataFrame(data_rows).to_csv(OUTDATA / "secS_scratch_rare_states.csv", index=False)
|
| 221 |
+
|
| 222 |
+
# ---- slide text, every count from the data
|
| 223 |
+
agg_w = BT[(BT.scope.str.startswith("same")) & (BT.state.str.startswith("MEAN"))]
|
| 224 |
+
agg_c = BT[(BT.scope.str.startswith("other")) & (BT.state.str.startswith("MEAN"))]
|
| 225 |
+
tie_w = bool((agg_w.verdict == "n.s.").all())
|
| 226 |
+
tie_lora = all(agg_c[agg_c.comparison == f"scratch final vs {x}"].verdict.iloc[0] == "n.s."
|
| 227 |
+
for x in ("LoRA r16", "LoRA r64"))
|
| 228 |
+
same = BT[BT.scope.str.startswith("same") & ~BT.state.str.startswith("MEAN")]
|
| 229 |
+
other = BT[BT.scope.str.startswith("other") & ~BT.state.str.startswith("MEAN")
|
| 230 |
+
& BT.comparison.str.startswith("scratch final")]
|
| 231 |
+
sig = lambda t, side: int((t.verdict == f"{side} closer").sum())
|
| 232 |
+
cyc_w, cyc_c = same[same.state == "Cycling T/NK"], other[other.state == "Cycling T/NK"]
|
| 233 |
+
isg_w, isg_c = same[same.state == "ISG-high T"], other[other.state == "ISG-high T"]
|
| 234 |
+
n_cyc, pos_cyc = len(cyc_w) + len(cyc_c), int((cyc_w.D > 0).sum() + (cyc_c.D > 0).sum())
|
| 235 |
+
# same-cohort state-level calls (13 states x 4 settings): where each side is significantly closer
|
| 236 |
+
scr_calls = same[same.verdict == "scratch closer"]
|
| 237 |
+
lab_calls = scr_calls[scr_calls.state.str.endswith("(label)")]
|
| 238 |
+
fail_calls = scr_calls[~scr_calls.state.str.endswith("(label)") & scr_calls.both_fail]
|
| 239 |
+
rest_calls = scr_calls[~scr_calls.state.str.endswith("(label)") & ~scr_calls.both_fail]
|
| 240 |
+
pre_calls = same[same.verdict == "pretrained closer"]
|
| 241 |
+
c1q = "C1Q-high monocyte (reference)"
|
| 242 |
+
own_arms = [a for _, p, s in WITHIN["settings"] for a in (p, s)]
|
| 243 |
+
c1q_own_min = float(W.loc[c1q, own_arms].min())
|
| 244 |
+
c1q_other_max = float(C.loc[c1q, [a for _, a in CROSS["comps"]] + [CROSS["scratch"], CROSS["scratch50"]]].max())
|
| 245 |
+
# fold 0 vs folds 1-4 for the own-pair LoRA (all 82 donors are scored in the masked cross-cohort scope)
|
| 246 |
+
folds = pd.read_csv(FOLDS)[["sample_id", "fold"]].rename(columns={"sample_id": "donor"})
|
| 247 |
+
if set(wp.donor) != set(folds[folds.fold == 0].donor):
|
| 248 |
+
raise SystemExit("fold-0 donors differ from folds.csv")
|
| 249 |
+
per_fold = {}
|
| 250 |
+
for st in (c1q, "Cycling T/NK"):
|
| 251 |
+
t = cp[(cp.arm == CROSS["own"]) & (cp.state == st)].merge(folds, on="donor", how="left")
|
| 252 |
+
if t.fold.isna().any() or len(t) != CROSS["n_donors"]:
|
| 253 |
+
raise SystemExit(f"{st}: donors without a fold")
|
| 254 |
+
g = t.groupby("fold")[["gen_state", "gen_parent", "obsthin_state", "obs_parent"]].sum()
|
| 255 |
+
per_fold[st] = (g.gen_state / g.gen_parent) / (g.obsthin_state / g.obs_parent)
|
| 256 |
+
best0 = all(per_fold[st].idxmax() == 0 for st in per_fold)
|
| 257 |
+
rest = lambda st: (per_fold[st].drop(0).min(), per_fold[st].drop(0).max())
|
| 258 |
+
# training settings of the same-cohort scratch runs and the masked gene count, from the receipts
|
| 259 |
+
sr = [json.loads((TI_RUNS / scr.replace("__raw", "") / "RUN.json").read_text()) for _, _, scr in WITHIN["settings"]]
|
| 260 |
+
if len({(r["lr"], r["max_steps"]) for r in sr}) != 1 or any(r.get("init") != "random" for r in sr):
|
| 261 |
+
raise SystemExit("same-cohort scratch runs differ in lr / step cap / init")
|
| 262 |
+
n_mask = json.loads((GM / f"{CROSS['scratch']}.log").read_text())["n_masked"]
|
| 263 |
+
kw = ["Same pairs: no significant difference on average" if tie_w else "Same pairs: average differs (see notes)",
|
| 264 |
+
f"Cycling T/NK: pretrained closer, {pos_cyc} of {n_cyc}" if pos_cyc == n_cyc
|
| 265 |
+
else f"Cycling T/NK: pretrained closer in {pos_cyc} of {n_cyc}",
|
| 266 |
+
"C1Q-high needs the cohort's own pairs" if c1q_own_min >= 0.4 and c1q_other_max <= 0.15
|
| 267 |
+
else "C1Q-high: see notes"]
|
| 268 |
+
fmt = lambda r: f"{r.D:+.2f} [{r.lo:+.2f}, {r.hi:+.2f}]"
|
| 269 |
+
short = lambda st: dict(SHOW).get(st, st).replace(" (label)", "")
|
| 270 |
+
row = lambda comp, st: BT[(BT.comparison == comp) & (BT.state == st)].iloc[0]
|
| 271 |
+
dn2, ms1 = row("58 pairs + recipes: scratch vs pretrained", "DN2 / ABC B"), row("58 pairs: scratch vs pretrained",
|
| 272 |
+
"MS1 monocyte (IL1R2+)")
|
| 273 |
+
isg_pre = C.loc["ISG-high T", [a for _, a in CROSS["comps"]]]
|
| 274 |
+
lab_word = ("label over-calls by the pretrained arms" if bool((lab_calls.gen_obs_pretrained > 1).all())
|
| 275 |
+
else "label states")
|
| 276 |
+
full = (f"Supplementary. Rare-state screen (plans/rare_states_screen_20261004): 13 rare states plus two controls, "
|
| 277 |
+
f"marker rules from the literature (tools/states.json) or scANVI labels; per arm, generated state % of its "
|
| 278 |
+
f"parent / observed % (1 = same rate; grey band = within 2-fold). For marker states the observed cells are "
|
| 279 |
+
f"thinned to the arm's generated depth; the two label states (plasmablast, proliferating T) are not thinned. "
|
| 280 |
+
f"The figure shows {len(SHOW)} of the 13 states; every average uses all 13 "
|
| 281 |
+
f"(data/secS_scratch_rare_states_bootstrap.csv). Same cohort: sepsis fold 0, {WITHIN['n_donors']} held-out "
|
| 282 |
+
f"donors, the same training pairs, conditions and sampling seed for both initialisations; from scratch = "
|
| 283 |
+
f"random initialisation, full training (lr {sr[0]['lr']:.0e}, cap {sr[0]['max_steps'] // 1000}k steps)."
|
| 284 |
+
.replace("e-0", "e-") + f" Other cohorts: all {CROSS['n_donors']} sepsis donors held out, trained on "
|
| 285 |
+
f"ImMicro + Imperial + Giroux + Liu pairs; the {n_mask} genes that no training cohort measured are zeroed in "
|
| 286 |
+
f"every arm (the scratch model is never trained on them). Donor bootstrap of D = |log2| scratch - |log2| "
|
| 287 |
+
f"pretrained, mean of the 13 rare states (D > 0 = pretrained closer): same cohort "
|
| 288 |
+
+ "; ".join(f"{r.comparison.split(':')[0]} {fmt(r)}" for r in agg_w.itertuples()) +
|
| 289 |
+
"; other cohorts, scratch final vs " + "; ".join(f"{r.comparison.split(' vs ')[1]} {fmt(r)}"
|
| 290 |
+
for r in agg_c[agg_c.comparison.str.startswith('scratch final')].itertuples()) +
|
| 291 |
+
"; scratch 50k vs " + "; ".join(f"{r.comparison.split(' vs ')[1]} {fmt(r)}"
|
| 292 |
+
for r in agg_c[agg_c.comparison.str.startswith('scratch 50k')].itertuples()) +
|
| 293 |
+
f". A non-significant average is not a shown equivalence (intervals about +/-0.3 log2). "
|
| 294 |
+
f"Cycling T/NK: pretrained closer in {int((cyc_w.D > 0).sum())} of {len(cyc_w)} same-cohort settings "
|
| 295 |
+
f"({sig(cyc_w, 'pretrained')} significant) and {int((cyc_c.D > 0).sum())} of {len(cyc_c)} other-cohort "
|
| 296 |
+
f"comparisons ({sig(cyc_c, 'pretrained')} significant; scratch {C.loc['Cycling T/NK', CROSS['scratch']]:.2f}x). "
|
| 297 |
+
f"ISG-high T: pretrained closer in {int((isg_w.D > 0).sum())} of {len(isg_w)} same-cohort settings "
|
| 298 |
+
f"({sig(isg_w, 'pretrained')} significant) but scratch closer in {int((isg_c.D < 0).sum())} of {len(isg_c)} "
|
| 299 |
+
f"other-cohort comparisons ({sig(isg_c, 'scratch')} significant; scratch "
|
| 300 |
+
f"{C.loc['ISG-high T', CROSS['scratch']]:.2f}x vs pretrained {isg_pre.min():.2f}–{isg_pre.max():.2f}x). "
|
| 301 |
+
f"Same-cohort state-level calls (13 states x {len(WITHIN['settings'])} settings): pretrained closer "
|
| 302 |
+
f"{len(pre_calls)}, scratch closer {len(scr_calls)} of {len(same)}; of the scratch calls {len(lab_calls)} are "
|
| 303 |
+
f"{lab_word} ({', '.join(sorted({short(x) for x in lab_calls.state}))}), {len(fail_calls)} are "
|
| 304 |
+
f"states where both arms are more than 4-fold off ({', '.join(sorted({short(x) for x in fail_calls.state}))}), and "
|
| 305 |
+
f"{len(rest_calls)} {'is' if len(rest_calls) == 1 else 'are'} "
|
| 306 |
+
+ ", ".join(f"{short(r.state)} ({r.comparison.split(':')[0]} {fmt(r)})" for r in rest_calls.itertuples()) +
|
| 307 |
+
f"; scratch is also closer on MS1 at 58 pairs ({fmt(ms1)}, {ms1.verdict}). "
|
| 308 |
+
f"C1Q-high: {c1q_own_min:.2f}x or more with the cohort's own pairs (both initialisations), "
|
| 309 |
+
f"{c1q_other_max:.2f}x or less without them. "
|
| 310 |
+
+ (f"Fold 0 is the own-pair LoRA's best fold for C1Q-high and cycling T/NK (58 pairs: "
|
| 311 |
+
f"{per_fold[c1q][0]:.2f}x and {per_fold['Cycling T/NK'][0]:.2f}x vs {rest(c1q)[0]:.2f}–{rest(c1q)[1]:.2f}x "
|
| 312 |
+
f"and {rest('Cycling T/NK')[0]:.2f}–{rest('Cycling T/NK')[1]:.2f}x in folds 1–4); scratch has not been "
|
| 313 |
+
f"run on folds 1–4. " if best0 else "") +
|
| 314 |
+
"One fold, one held-out cohort, one seed; no multiplicity correction. Full analysis: "
|
| 315 |
+
"plans/rare_states_screen_20261004/README.md and out/scratch_vs_lora_20261005/REPORT.md (two verification "
|
| 316 |
+
"passes on the same-cohort and unmasked analyses); the masked cross-cohort numbers here come from the "
|
| 317 |
+
"REPORT addendum and masked_cross_bootstrap.csv, which supersede the unmasked cross-cohort readings in the "
|
| 318 |
+
"REPORT body.")
|
| 319 |
+
numbers = [{"value": f"{short}: same cohort " + ", ".join(
|
| 320 |
+
f"{lab} LoRA {W.loc[st, pre]:.2f} / scratch {W.loc[st, scr]:.2f}" for lab, pre, scr in WITHIN["settings"]
|
| 321 |
+
if lab != "58 pairs, full FT") + "; other cohorts " + ", ".join(
|
| 322 |
+
f"{lab} {C.loc[st, arm]:.2f}" for lab, arm, *_ in CROSS["plot"]),
|
| 323 |
+
"source": "data/secS_scratch_rare_states.csv"} for st, short in SHOW]
|
| 324 |
+
txt = {"title": "Rare states: from scratch vs pretrained", "layout": "full",
|
| 325 |
+
"figures": [str(FIGDIR / "secS_scratch_rare_states.png")], "keywords": kw,
|
| 326 |
+
"footnote_short": f"Pilot, one seed: sepsis fold 0 ({WITHIN['n_donors']} donors), held-out sepsis "
|
| 327 |
+
f"({CROSS['n_donors']}, masked). 1 = observed rate; grey = within 2-fold.",
|
| 328 |
+
"footnote": full, "numbers": numbers}
|
| 329 |
+
out = {"section": "S-scratch-rare-states", "scripts": [str(Path(__file__).resolve())],
|
| 330 |
+
"generated_from": "tools/secS_scratch_rare_states.py (rerun to refresh; do not edit by hand)",
|
| 331 |
+
"slides": [txt]}
|
| 332 |
+
(OUTDATA / "secS_scratch_rare_states_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 333 |
+
print("\n".join(kw))
|
| 334 |
+
print(BT[BT.state.str.startswith("MEAN")].round(3).to_string(index=False))
|
| 335 |
+
print(f"tie same cohort {tie_w}; tie vs LoRA other cohorts {tie_lora}; C1Q own min {c1q_own_min:.2f}, "
|
| 336 |
+
f"other max {c1q_other_max:.2f}; fold 0 best for the own LoRA {best0}")
|
| 337 |
+
print(full)
|
| 338 |
+
return 0
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
if __name__ == "__main__":
|
| 342 |
+
sys.exit(main())
|