junidude14 commited on
Commit
f8a2e7d
·
verified ·
1 Parent(s): 418fbe1

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T022002Z-deck-time-to-apply-scsemi-reps/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec09_scsemi_representative.pdf ADDED
Binary file (30.1 kB). View file
 
paper-releases/pbisc-diffusion/updates/20261002T022002Z-deck-time-to-apply-scsemi-reps/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec09_scsemi_representative.png ADDED

Git LFS Details

  • SHA256: 1398427288f000e7823a437e3adff0fe2be89a1375ea6c984b4be9398d069a9e
  • Pointer size: 131 Bytes
  • Size of remote file: 190 kB
paper-releases/pbisc-diffusion/updates/20261002T022002Z-deck-time-to-apply-scsemi-reps/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/sec09_time_to_apply.pdf ADDED
Binary file (43.9 kB). View file
 
paper-releases/pbisc-diffusion/updates/20261002T022002Z-deck-time-to-apply-scsemi-reps/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/sec09_time_to_apply.py ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 (15.9 h, slide 15).
14
+ Each draw is read on the host that holds its export (Imperial LoRA and scSemiProfiler, and scSemiProfiler ImMicro 2-3,
15
+ ran on server_2; scSemiProfiler sepsis 4 was pretrained on server_2 and finished on server_1, whose receipts hold both
16
+ parts); a step without a complete record stops the script. Work lost to interruptions (memory-guard stops) is not
17
+ counted, which can only favour scSemiProfiler.
18
+
19
+ Outputs (deck folder; DECK_FIGDIR / DECK_OUTDATA override the folders):
20
+ figures/sec09_time_to_apply.{png,pdf}
21
+ data/sec09_time_to_apply_runs.csv one row per cohort x draw x method with every time and its source
22
+ data/sec09_time_to_apply.csv per cohort and method: mean / SD / min / max over the 5 draws
23
+ data/sec09_time_to_apply_slide_text.json title, keywords, footnotes and quoted numbers (synced into the spec by
24
+ tools/sync_sec09_text.py through text_source)
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import os
29
+
30
+ os.environ["CUDA_VISIBLE_DEVICES"] = "" # plotting only
31
+
32
+ import json
33
+ import subprocess
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+ import pandas as pd
39
+
40
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
41
+ "2026-09-30--paper-summary--r00")
42
+ sys.path.insert(0, str(DECK / "tools"))
43
+ import sec09_paired_validation as S9 # noqa: E402 (shared section 9 names and colours; sets the deck rcParams)
44
+ import style # noqa: E402
45
+ import matplotlib.pyplot as plt # noqa: E402
46
+ from matplotlib.patches import Patch # noqa: E402
47
+
48
+ T = S9.T
49
+ FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
50
+ OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
51
+ ORDER, NAME, ROWNAME = S9.ORDER, S9.NAME, S9.ROWNAME
52
+ FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
53
+ DRAWS = range(5)
54
+ SERVER2 = "spark-0110"
55
+ COL = {"lora": style.ARM["lora"], "scsemi": style.ARM["scsemi"]}
56
+ PALE = {"lora": "#F2B48C", "scsemi": "#F5D08A"} # second segment (generation / per-target inference)
57
+ LAB = {"lora": "LoRA, 5 donors", "scsemi": "scSemiProfiler, 5 donors"}
58
+
59
+ # Runs on each host (python3 -, argv: plan root). Prints one JSON object: every record the deck needs, per cohort/draw.
60
+ COLLECT = r'''
61
+ import glob, json, os, re, sys
62
+ T = sys.argv[1]
63
+ TAG = {"immicro": "imm", "ye2026_sepsis": "ye2", "imperial_eskd": "imp", "giroux2022": "gir", "ji2025_chili": "ji2"}
64
+ def jload(p):
65
+ try:
66
+ with open(p) as f:
67
+ return json.load(f)
68
+ except Exception:
69
+ return None
70
+ starts, ends = {}, {}
71
+ pat_s = re.compile(r"^(\S+) --- ([a-z0-9]+_fs_d[0-9]_lora) seed=")
72
+ pat_e = re.compile(r"^(\S+) ([a-z0-9]+_fs_d[0-9]_lora) done:")
73
+ for lg in sorted(glob.glob(os.path.join(T, "logs", "run_queue_*.log"))):
74
+ for line in open(lg, errors="replace"):
75
+ m = pat_s.match(line)
76
+ if m:
77
+ starts.setdefault(m.group(2), []).append((m.group(1), lg))
78
+ m = pat_e.match(line)
79
+ if m:
80
+ ends.setdefault(m.group(2), []).append((m.group(1), lg))
81
+ out = {}
82
+ for ds, p in TAG.items():
83
+ for j in range(5):
84
+ k = f"{ds}|{j}"
85
+ r = {}
86
+ run = jload(os.path.join(T, "runs", ds, "fewshot_n5", f"draw{j}", "lora", "RUN.json"))
87
+ if run:
88
+ r["lora_train"] = {"wall_seconds": run.get("wall_seconds"), "steps_run": run.get("steps_run"),
89
+ "src": os.path.join(T, "runs", ds, "fewshot_n5", f"draw{j}", "lora", "RUN.json")}
90
+ g = os.path.join(T, "generated", ds, "fewshot_n5", f"draw{j}")
91
+ lr = jload(os.path.join(g, "lora__raw.log"))
92
+ if lr and os.path.isfile(os.path.join(g, "lora__raw.npz")):
93
+ r["lora_out"] = {"bulks": lr.get("bulks"), "cells": lr.get("cells"), "sha256": lr.get("output_sha256")}
94
+ tag = f"{p}_fs_d{j}_lora"
95
+ if tag in starts or tag in ends:
96
+ r["lora_sample_log"] = {"starts": starts.get(tag, []), "ends": ends.get(tag, [])}
97
+ ex = jload(os.path.join(g, "scsemi5__raw.log"))
98
+ if ex and os.path.isfile(os.path.join(g, "scsemi5__raw.npz")):
99
+ r["scsemi_export"] = {k2: ex.get(k2) for k2 in ("bulks", "cells", "total_target_seconds",
100
+ "median_target_seconds", "run_signature", "output_sha256")}
101
+ r["scsemi_export"]["src"] = os.path.join(g, "scsemi5__raw.log")
102
+ md = os.path.join(T, "scsemi", "work", ds, "fewshot_n5", f"draw{j}", "scsemi_project", "models")
103
+ rec = []
104
+ for f in sorted(glob.glob(os.path.join(md, "*.receipt.json"))):
105
+ x = jload(f) or {}
106
+ rec.append({"file": f, "stage": x.get("stage"), "representative": x.get("representative"),
107
+ "elapsed_seconds": x.get("elapsed_seconds"), "complete": x.get("complete"),
108
+ "run_signature": x.get("run_signature")})
109
+ r["scsemi_pretrain"] = rec
110
+ asg = jload(os.path.join(T, "scsemi", "work", ds, "fewshot_n5", f"draw{j}", "assignment.json"))
111
+ if asg:
112
+ r["scsemi_n_reps"] = len(asg.get("representative_indices", []))
113
+ out[k] = r
114
+ print(json.dumps(out))
115
+ '''
116
+
117
+
118
+ def collect(host: str) -> dict:
119
+ cmd = ["python3", "-", str(T)] if host == "server_1" else ["ssh", SERVER2, "python3", "-", str(T)]
120
+ res = subprocess.run(cmd, input=COLLECT, capture_output=True, text=True, check=True)
121
+ return json.loads(res.stdout)
122
+
123
+
124
+ def ts(s: str) -> pd.Timestamp:
125
+ return pd.Timestamp(s)
126
+
127
+
128
+ def build_runs() -> pd.DataFrame:
129
+ got = {h: collect(h) for h in ("server_1", "server_2")}
130
+ rows = []
131
+ for ds in ORDER:
132
+ for j in DRAWS:
133
+ k = f"{ds}|{j}"
134
+ # LoRA: the host that holds both the trained adapter and the generated cells
135
+ lh = [h for h in got if "lora_train" in got[h].get(k, {}) and "lora_out" in got[h].get(k, {})]
136
+ if len(lh) != 1:
137
+ raise SystemExit(f"{k}: LoRA-5 run found on {lh or 'no host'}")
138
+ r = got[lh[0]][k]
139
+ log = r.get("lora_sample_log") or {}
140
+ if len(log.get("starts", [])) != 1 or len(log.get("ends", [])) != 1:
141
+ raise SystemExit(f"{k}: expected one sampling start and end in {lh[0]} queue logs, got {log}")
142
+ (t0, src0), (t1, src1) = log["starts"][0], log["ends"][0]
143
+ gen_s = (ts(t1) - ts(t0)).total_seconds()
144
+ train_s = float(r["lora_train"]["wall_seconds"])
145
+ if r["lora_train"]["steps_run"] != 3000 or not (0 < gen_s < 6 * 3600):
146
+ raise SystemExit(f"{k}: unexpected LoRA record {r['lora_train']} / sampling {gen_s} s")
147
+ nb = int(r["lora_out"]["bulks"])
148
+ rows.append(dict(cohort=ds, draw=j, method="lora", host=lh[0], n_test=nb, step1_s=train_s, step2_s=gen_s,
149
+ step1="fine-tune (3,000 steps)", step2="generate 1,500 cells per test sample",
150
+ src1=r["lora_train"]["src"], src2=f"{src0} [{t0} -> {t1}]"))
151
+ # scSemiProfiler: the host with the validated export; train time from that host's final model receipts
152
+ sh = [h for h in got if "scsemi_export" in got[h].get(k, {})]
153
+ if len(sh) != 1:
154
+ raise SystemExit(f"{k}: scSemiProfiler export found on {sh or 'no host'}")
155
+ r = got[sh[0]][k]
156
+ ex = r["scsemi_export"]
157
+ rec = [x for x in r["scsemi_pretrain"] if x["complete"] and x["run_signature"] == ex["run_signature"]]
158
+ n_reps = int(r["scsemi_n_reps"])
159
+ stages = sorted((x["stage"], x["representative"]) for x in rec)
160
+ if len(rec) != 2 * n_reps or len(set(stages)) != len(stages):
161
+ raise SystemExit(f"{k}: {len(rec)} complete pretrain receipts on {sh[0]}, expected 2 x {n_reps}")
162
+ if int(ex["bulks"]) != nb:
163
+ raise SystemExit(f"{k}: scSemiProfiler scored {ex['bulks']} test samples, LoRA {nb}")
164
+ rows.append(dict(cohort=ds, draw=j, method="scsemi", host=sh[0], n_test=int(ex["bulks"]),
165
+ step1_s=float(sum(x["elapsed_seconds"] for x in rec)),
166
+ step2_s=float(ex["total_target_seconds"]),
167
+ step1=f"train on {n_reps} representatives (2 stages each)",
168
+ step2="one model per test sample",
169
+ src1=str(Path(rec[0]["file"]).parent) + "/*.receipt.json", src2=ex["src"]))
170
+ d = pd.DataFrame(rows)
171
+ d["total_s"] = d.step1_s + d.step2_s
172
+ d["per_test_s"] = d.total_s / d.n_test
173
+ return d
174
+
175
+
176
+ def summarise(d: pd.DataFrame) -> pd.DataFrame:
177
+ g = d.groupby(["cohort", "method"], sort=False)
178
+ s = g.agg(n_draws=("draw", "size"), n_test_min=("n_test", "min"), n_test_max=("n_test", "max"),
179
+ step1_min_mean=("step1_s", lambda x: x.mean() / 60), step2_min_mean=("step2_s", lambda x: x.mean() / 60),
180
+ total_min_mean=("total_s", lambda x: x.mean() / 60), total_min_sd=("total_s", lambda x: x.std(ddof=1) / 60),
181
+ total_min_min=("total_s", lambda x: x.min() / 60), total_min_max=("total_s", lambda x: x.max() / 60),
182
+ per_test_s_mean=("per_test_s", "mean")).reset_index()
183
+ w = d.pivot_table(index=["cohort", "draw"], columns="method", values="total_s")
184
+ ratio = (w["scsemi"] / w["lora"]).groupby(level=0)
185
+ s["speedup_mean"] = s.cohort.map(ratio.mean())
186
+ s["speedup_min"] = s.cohort.map(ratio.min())
187
+ s["speedup_max"] = s.cohort.map(ratio.max())
188
+ return s
189
+
190
+
191
+ def fmt_t(minutes: float) -> str:
192
+ return f"{minutes:.0f} min" if minutes < 90 else f"{minutes / 60:.1f} h"
193
+
194
+
195
+ def draw(d: pd.DataFrame, s: pd.DataFrame) -> None:
196
+ fig, (ax, bx) = plt.subplots(1, 2, figsize=(12.3, 4.6), gridspec_kw={"width_ratios": [2.1, 1.0], "wspace": 0.12})
197
+ h, gap = 0.36, 0.42
198
+ yt, ylab = [], []
199
+ for i, ds in enumerate(ORDER):
200
+ y0 = i * (2 * h + gap)
201
+ for k, m in enumerate(("scsemi", "lora")):
202
+ y = y0 + k * h
203
+ r = s[(s.cohort == ds) & (s.method == m)].iloc[0]
204
+ a, b = r.step1_min_mean / 60, r.step2_min_mean / 60
205
+ ax.barh(y, a, h * 0.9, color=COL[m], edgecolor="none")
206
+ ax.barh(y, b, h * 0.9, left=a, color=PALE[m], edgecolor="none")
207
+ tot = d[(d.cohort == ds) & (d.method == m)].total_s.to_numpy() / 3600
208
+ ax.errorbar(tot.mean(), y, xerr=tot.std(ddof=1), fmt="none", ecolor=EDGE, elinewidth=1, capsize=2.5)
209
+ ax.scatter(tot, np.full(tot.size, y), s=13, facecolor="white", edgecolor=EDGE, linewidth=0.8, zorder=3)
210
+ label = fmt_t(r.total_min_mean)
211
+ if m == "lora":
212
+ label += f" ({r.speedup_mean:.0f}× less)"
213
+ ax.text(max(tot.max(), a + b) + 0.06, y, label, va="center", ha="left", fontsize=FS - 2,
214
+ color=INK if m == "lora" else SUB, fontweight="bold" if m == "lora" else "normal")
215
+ yt.append(y0 + h / 2)
216
+ r = s[(s.cohort == ds) & (s.method == "lora")].iloc[0]
217
+ 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}"
218
+ ylab.append(f"{ROWNAME[ds]}\n{nt} test samples")
219
+ ax.set_yticks(yt, ylab, fontsize=FS - 2)
220
+ ax.invert_yaxis()
221
+ ax.set_xlabel("GPU time per draw (h)")
222
+ ax.set_xlim(0, None)
223
+ ax.tick_params(axis="y", length=0)
224
+ # per test sample, log scale
225
+ for i, ds in enumerate(ORDER):
226
+ y0 = i * (2 * h + gap)
227
+ for k, m in enumerate(("scsemi", "lora")):
228
+ v = d[(d.cohort == ds) & (d.method == m)].per_test_s.to_numpy()
229
+ bx.scatter(v, np.full(v.size, y0 + k * h), s=26, color=COL[m], edgecolor=EDGE, linewidth=0.6, zorder=3)
230
+ bx.set_xscale("log")
231
+ bx.set_yticks(yt, [""] * len(yt))
232
+ bx.tick_params(axis="y", length=0)
233
+ bx.invert_yaxis()
234
+ bx.set_xlabel("GPU seconds per test sample")
235
+ bx.grid(axis="x", which="major", color="#E3E3E3", linewidth=0.8)
236
+ bx.set_axisbelow(True)
237
+ handles = [Patch(color=COL["scsemi"], label="scSemiProfiler: train on representatives"),
238
+ Patch(color=PALE["scsemi"], label="scSemiProfiler: one model per test sample"),
239
+ Patch(color=COL["lora"], label="LoRA: fine-tune once"),
240
+ Patch(color=PALE["lora"], label="LoRA: generate cells")]
241
+ fig.legend(handles=handles, loc="lower center", ncol=2, bbox_to_anchor=(0.42, -0.13), fontsize=FS - 2,
242
+ handlelength=1.2, columnspacing=1.6)
243
+ style.save(fig, "sec09_time_to_apply", FIGDIR)
244
+
245
+
246
+ INK = style.INK
247
+
248
+
249
+ def slide_text(d: pd.DataFrame, s: pd.DataFrame) -> dict:
250
+ lo, sc = s[s.method == "lora"], s[s.method == "scsemi"]
251
+ w = d.pivot_table(index=["cohort", "draw"], columns="method", values="total_s")
252
+ rat = w["scsemi"] / w["lora"]
253
+ per_lo = d[d.method == "lora"].groupby("cohort").per_test_s.mean()
254
+ per_sc = d[d.method == "scsemi"].groupby("cohort").per_test_s.mean()
255
+ kw = [f"LoRA-5: {lo.total_min_mean.min():.0f}–{lo.total_min_mean.max():.0f} min per draw, every test sample",
256
+ f"scSemiProfiler-5: {sc.total_min_mean.min() / 60:.1f}–{sc.total_min_mean.max() / 60:.1f} h per draw",
257
+ f"{rat.min():.0f}–{rat.max():.0f}× less GPU time, same 5 donors"]
258
+ numbers = []
259
+ for ds in ORDER:
260
+ a = lo[lo.cohort == ds].iloc[0]
261
+ b = sc[sc.cohort == ds].iloc[0]
262
+ numbers.append({"value": f"{NAME[ds]}: LoRA-5 {a.total_min_mean:.1f} min (fine-tune {a.step1_min_mean:.1f} + "
263
+ f"generate {a.step2_min_mean:.1f}), scSemiProfiler-5 {b.total_min_mean:.0f} min "
264
+ f"(representatives {b.step1_min_mean:.0f} + per-sample models {b.step2_min_mean:.0f}); "
265
+ f"{a.speedup_min:.0f}–{a.speedup_max:.0f}× per draw; per test sample "
266
+ f"{per_lo[ds]:.1f} s vs {per_sc[ds]:.0f} s",
267
+ "source": "data/sec09_time_to_apply.csv"})
268
+ full = ("Same 25 draws as the previous slides (5 cohorts x 5 draws; same 5 training donors and test samples for "
269
+ "both methods). GPU time on one GB10, every step alone on the GPU (shared lock). LoRA-5: fine-tune = "
270
+ "RUN.json wall_seconds of the 3,000-step LoRA; generate = wall clock of the sampling job in the queue log "
271
+ "(model load + DDIM 50, 1,500 cells per test sample). scSemiProfiler-5 (upstream c2aea02, default "
272
+ "budget): stage 1 + stage 2 pretraining of every representative (model receipts) + its per-target "
273
+ "inference (5 ministages x 150 epochs, export receipt total_target_seconds). Not counted on either side: "
274
+ "CPU data preparation, scoring, work lost to interruptions, and PBISC's one-time pretraining (15.9 h, slide "
275
+ "15), which every cohort reuses. scSemiProfiler time grows with the number of test samples because it trains one model per "
276
+ "sample. Per-draw ratio scSemiProfiler / LoRA: " +
277
+ "; ".join(f"{NAME[ds]} {rat.loc[ds].min():.0f}–{rat.loc[ds].max():.0f}×" for ds in ORDER) + ".")
278
+ return {"title": "5 donors: time to apply", "layout": "full",
279
+ "figures": [str(FIGDIR / "sec09_time_to_apply.png")], "keywords": kw,
280
+ "footnote_short": "One GB10 GPU; mean of 5 draws. Data prep and scoring not counted. "
281
+ "PBISC pretraining (15.9 h) is done once.",
282
+ "footnote": full, "numbers": numbers}
283
+
284
+
285
+ def main() -> int:
286
+ d = build_runs()
287
+ s = summarise(d)
288
+ OUTDATA.mkdir(exist_ok=True)
289
+ d.to_csv(OUTDATA / "sec09_time_to_apply_runs.csv", index=False)
290
+ s.to_csv(OUTDATA / "sec09_time_to_apply.csv", index=False)
291
+ draw(d, s)
292
+ txt = slide_text(d, s)
293
+ out = {"section": "09-time", "scripts": [str(Path(__file__).resolve())],
294
+ "generated_from": "tools/sec09_time_to_apply.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
295
+ (OUTDATA / "sec09_time_to_apply_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
296
+ with pd.option_context("display.width", 200):
297
+ print(s.round(2).to_string(index=False))
298
+ print("\n".join(txt["keywords"]))
299
+ return 0
300
+
301
+
302
+ if __name__ == "__main__":
303
+ sys.exit(main())