junidude14 commited on
Commit
419684e
·
verified ·
1 Parent(s): 836e2f8

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/fig1b_overview_nature.png ADDED

Git LFS Details

  • SHA256: e50ff68c0a08b0c4730c7a5abf2700cd1b994afc8ca2e69de60d33ff99f8c9e1
  • Pointer size: 131 Bytes
  • Size of remote file: 323 kB
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/figure_plan.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Six-figure plan slides for the paper-summary deck (2026-10-06, Nature-style manuscript order).
3
+
4
+ Reads data/figure_plan.json (the hand-written plan: figures, panels, evidence slides, status) and the current spec.
5
+ Checks that every evidence title is a slide of the deck (or one of the two slides made here) and that every content
6
+ slide of the deck is placed exactly once (a panel, a figure's details, Supplementary or Appendix).
7
+ Writes:
8
+ figures/figplan_overview.png, figures/figplan_fig{1..6}.png plan tables (no data)
9
+ figures/fig1b_overview_nature.png, figures/fig1d_corpus.png copies of the manuscript candidates
10
+ data/figure_plan_slide_text.json slide text (synced into the spec)
11
+ CPU only.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import shutil
17
+ import sys
18
+ import textwrap
19
+ from pathlib import Path
20
+
21
+ import matplotlib
22
+
23
+ matplotlib.use("Agg")
24
+ import matplotlib.pyplot as plt # noqa: E402
25
+ from matplotlib.patches import FancyBboxPatch # noqa: E402
26
+
27
+ DECK = Path(__file__).resolve().parents[1]
28
+ MS = Path("/home/sj_server_1/PBISC/paper-release-20260928/manuscript")
29
+ PLAN = DECK / "data" / "figure_plan.json"
30
+ SPEC = DECK / "data" / "slides_spec.json"
31
+ FIG = DECK / "figures"
32
+ NEW = {"Overview draft (Nature style)": MS / "figures" / "fig01_architecture_nature.png",
33
+ "Pretraining corpus": MS / "figures" / "fig01_corpus_nature.png"}
34
+ STATUS_COLOR = {"Ready": "#5E8C6A", "Adapt": "#C98A4B", "Draft": "#8E6C9E", "Build": "#3F6E9E", "Run": "#B5544F",
35
+ "Decide": "#5F5F5F"}
36
+ INK, SUB = "#1A1A1A", "#5A5A5A"
37
+ plt.rcParams.update({"font.family": "Arial", "font.size": 11})
38
+
39
+
40
+ def chip(ax, x, y, s, w=0.085, h=0.05, color=None):
41
+ ax.add_patch(FancyBboxPatch((x, y - h / 2), w, h, boxstyle="round,pad=0.004,rounding_size=0.012",
42
+ fc=color or STATUS_COLOR[s], ec="none", transform=ax.transAxes))
43
+ ax.text(x + w / 2, y, s, ha="center", va="center", color="white", fontsize=10, fontweight="bold",
44
+ transform=ax.transAxes)
45
+
46
+
47
+ def plan_table(fig_plan, out):
48
+ rows = fig_plan["panels"]
49
+ cols = {"p": 0.012, "c": 0.045, "e": 0.355, "s": 0.695, "n": 0.79}
50
+ wrapped = []
51
+ for r in rows:
52
+ ev = "; ".join(f"\u201c{e}\u201d" for e in r["evidence"]) if r["evidence"] else "\u2014"
53
+ wrapped.append((textwrap.wrap(r["content"], 40), textwrap.wrap(ev, 46) or ["\u2014"],
54
+ textwrap.wrap(r.get("note", ""), 30)))
55
+ nlines = [max(len(c), len(e), len(n), 1) for c, e, n in wrapped]
56
+ line_in, pad_in = 0.235, 0.09
57
+ fig_h = 0.45 + sum(nl * line_in + 2 * pad_in for nl in nlines)
58
+ fig = plt.figure(figsize=(12.3, fig_h))
59
+ ax = fig.add_axes([0, 0, 1, 1])
60
+ ax.axis("off")
61
+ f = lambda inch: inch / fig_h # inches -> axes fraction (vertical)
62
+ y = 1 - f(0.2)
63
+ for k, h in zip(cols, ["", "Panel content", "Evidence in this deck (slide title)", "Status", "Note"]):
64
+ ax.text(cols[k], y, h, fontsize=10.5, color=SUB, fontweight="bold", va="center", transform=ax.transAxes)
65
+ y -= f(0.25)
66
+ for k, (r, (c, e, n), nl) in enumerate(zip(rows, wrapped, nlines)):
67
+ hgt = f(nl * line_in + 2 * pad_in)
68
+ if k % 2 == 0:
69
+ ax.add_patch(plt.Rectangle((0, y - hgt), 1, hgt, color="#F4F4F4", transform=ax.transAxes, zorder=0))
70
+ y0 = y - f(pad_in + line_in / 2)
71
+ ax.text(cols["p"] + 0.008, y0, r["p"], fontsize=12, fontweight="bold", va="center", transform=ax.transAxes)
72
+ for x, lines, col in ((cols["c"], c, INK), (cols["e"], e, SUB), (cols["n"], n, SUB)):
73
+ for j, ln in enumerate(lines):
74
+ ax.text(x, y0 - f(j * line_in), ln, fontsize=10.5, color=col, va="center", transform=ax.transAxes)
75
+ chip(ax, cols["s"], y0, r["status"], w=0.075, h=f(0.2))
76
+ y -= hgt
77
+ fig.savefig(out, dpi=200)
78
+ plt.close(fig)
79
+
80
+
81
+ def overview_table(plan, out):
82
+ figs = plan["figures"]
83
+ fig = plt.figure(figsize=(12.3, 5.0))
84
+ ax = fig.add_axes([0, 0, 1, 1])
85
+ ax.axis("off")
86
+ for x, h in ((0.012, "Main figure"), (0.40, "What the figure shows"), (0.755, "Panels by status")):
87
+ ax.text(x, 0.95, h, fontsize=11, color=SUB, fontweight="bold", transform=ax.transAxes)
88
+ step = 0.145
89
+ for k, fg in enumerate(figs):
90
+ y = 0.85 - k * step
91
+ if k % 2 == 0:
92
+ ax.add_patch(plt.Rectangle((0, y - step / 2), 1, step, color="#F4F4F4", transform=ax.transAxes, zorder=0))
93
+ ax.text(0.012, y, f"Fig. {fg['n']}", fontsize=12, fontweight="bold", va="center", transform=ax.transAxes)
94
+ ax.text(0.075, y, fg["title"], fontsize=11.5, va="center", transform=ax.transAxes)
95
+ lines = textwrap.wrap(fg["claim"], 50)
96
+ for j, ln in enumerate(lines):
97
+ ax.text(0.40, y + 0.022 * (len(lines) - 1) - j * 0.044, ln, fontsize=10.5, color=SUB, va="center",
98
+ transform=ax.transAxes)
99
+ counts = {}
100
+ for pnl in fg["panels"]:
101
+ counts[pnl["status"]] = counts.get(pnl["status"], 0) + 1
102
+ x = 0.755
103
+ for st in STATUS_COLOR:
104
+ if st in counts:
105
+ chip(ax, x, y, f"{st} {counts[st]}", w=0.072, h=0.06, color=STATUS_COLOR[st])
106
+ x += 0.086
107
+ fig.savefig(out, dpi=200)
108
+ plt.close(fig)
109
+
110
+
111
+ def main() -> int:
112
+ plan = json.loads(PLAN.read_text())
113
+ spec = json.loads(SPEC.read_text())
114
+ have = [s["title"] for s in spec["slides"] if s.get("kind") == "content"]
115
+ have = [t for t in have if t not in NEW and not t.startswith(("Figure ", "Manuscript plan"))]
116
+ placed = []
117
+ for f in plan["figures"]:
118
+ for p in f["panels"]:
119
+ placed += p["evidence"]
120
+ placed += f["details"]
121
+ placed += plan["supplementary"] + plan["appendix"]
122
+ unknown = [t for t in placed if t not in have and t not in NEW]
123
+ missing = [t for t in have if t not in placed]
124
+ twice = sorted({t for t in placed if placed.count(t) > 1})
125
+ if unknown or missing or twice:
126
+ raise SystemExit(f"plan does not match the deck: unknown {unknown}, unplaced {missing}, twice {twice}")
127
+ for title, src in NEW.items():
128
+ if not src.is_file():
129
+ raise SystemExit(f"missing manuscript figure {src}")
130
+ shutil.copyfile(NEW["Overview draft (Nature style)"], FIG / "fig1b_overview_nature.png")
131
+ shutil.copyfile(NEW["Pretraining corpus"], FIG / "fig1d_corpus.png")
132
+ overview_table(plan, FIG / "figplan_overview.png")
133
+ for f in plan["figures"]:
134
+ plan_table(f, FIG / f"figplan_fig{f['n']}.png")
135
+
136
+ summ = json.loads((MS / "source_data/corpus/corpus_summary.json").read_text())
137
+ tot = summ["cells"]
138
+ healthy = summ["family_cells"]["Healthy"] / tot
139
+ vitro = summ["handling_cells"]["in vitro"] / tot
140
+ slides = [{
141
+ "title": "Manuscript plan: six main figures", "layout": "full",
142
+ "figures": [str(FIG / "figplan_overview.png")], "keywords": [],
143
+ "footnote_short": "Nature style: short abstract and introduction, descriptive results, short discussion, "
144
+ "detailed methods; up to 17 supplementary figures.",
145
+ "footnote": plan["source"] + " Status: " + "; ".join(f"{k} = {v}" for k, v in plan["status_legend"].items()) + ".",
146
+ "numbers": []}]
147
+ for f in plan["figures"]:
148
+ n_ok = sum(p["status"] == "Ready" for p in f["panels"])
149
+ slides.append({
150
+ "title": f"Figure {f['n']} plan: {f['title']}", "layout": "full",
151
+ "figures": [str(FIG / f"figplan_fig{f['n']}.png")], "keywords": [],
152
+ "footnote_short": f"{f['claim']} {n_ok} of {len(f['panels'])} panels ready.",
153
+ "footnote": "Panels: " + " ".join(f"{p['p']}) {p['content']} [{p['status']}"
154
+ + (f"; {p['note']}" if p.get("note") else "") + "]." for p in f["panels"])
155
+ + (" Details in this section: " + "; ".join(f["details"]) + "." if f["details"] else ""),
156
+ "numbers": []})
157
+ slides.append({
158
+ "title": "Overview draft (Nature style)", "layout": "full",
159
+ "figures": [str(FIG / "fig1b_overview_nature.png")],
160
+ "keywords": ["Each cell is learned with its own bulk", "Diffusion on each gene's value and detection",
161
+ "One bulk in, K cells out; optional LoRA"],
162
+ "footnote_short": "Draft for Fig. 1b; schematic, no data. Plan: manuscript editorial/fig1_nature_redesign_plan.",
163
+ "footnote": "Candidate replacement for the engineering diagram (kept in this section as details and for Methods). "
164
+ "Source: paper-release-20260928/manuscript/figures/fig01_architecture_nature.svg "
165
+ "(scripts/build_figure1_architecture_nature.py).",
166
+ "numbers": []})
167
+ slides.append({
168
+ "title": "Pretraining corpus", "layout": "full",
169
+ "figures": [str(FIG / "fig1d_corpus.png")],
170
+ "keywords": [f"{tot / 1e6:.1f} M cells, {summ['datasets']} datasets, {summ['donors']:,} donors",
171
+ f"{100 * healthy:.1f}% healthy donors; {100 * vitro:.1f}% cultured in vitro",
172
+ "Labels describe the corpus; never model input"],
173
+ "footnote_short": "Detailed version: Supplementary Fig. S1 of the manuscript.",
174
+ "footnote": "Source: paper-release-20260928/manuscript/source_data/corpus/ (build_corpus_tables.py) and "
175
+ "figures/fig01_corpus_nature.png (build_figure1_corpus.py).",
176
+ "numbers": [{"value": f"{tot:,} cells; {summ['datasets']} datasets; {summ['donors']:,} donors; "
177
+ f"healthy {100 * healthy:.1f}%; in vitro {100 * vitro:.1f}%",
178
+ "source": "manuscript/source_data/corpus/corpus_summary.json"}]})
179
+ out = {"section": "figure-plan", "scripts": [str(Path(__file__).resolve())],
180
+ "generated_from": "tools/figure_plan.py (rerun to refresh; do not edit by hand)", "slides": slides}
181
+ (DECK / "data" / "figure_plan_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
182
+ print("placed", len(placed), "slides; plan slides", len(slides))
183
+ return 0
184
+
185
+
186
+ if __name__ == "__main__":
187
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/restructure_figure_order_20261006.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """One-off spec change of 2026-10-06: order the deck by the six main figures of the Nature-style manuscript plan.
3
+
4
+ Reads data/figure_plan.json (written by hand) and data/figure_plan_slide_text.json (tools/figure_plan.py). New order:
5
+ title, agenda (6 figures + Supplementary + Appendix), the manuscript plan, then for each figure a divider, its plan
6
+ slide, its panel slides in panel order (section label "Fig. 1a" ...) and its details; then Supplementary and
7
+ Appendix as before. No slide is dropped or rewritten; only order, section labels and the agenda change. The text
8
+ of the new slides is filled by tools/sync_sec09_text.py. Refuses to run twice.
9
+ """
10
+ import json
11
+ from pathlib import Path
12
+
13
+ DECK = Path(__file__).resolve().parents[1]
14
+ SPEC = DECK / "data" / "slides_spec.json"
15
+ PLAN = DECK / "data" / "figure_plan.json"
16
+ TEXT = "data/figure_plan_slide_text.json"
17
+
18
+
19
+ def main() -> None:
20
+ spec = json.loads(SPEC.read_text())
21
+ if any(s.get("text_source", {}).get("file") == TEXT for s in spec["slides"]):
22
+ raise SystemExit("already restructured (figure-plan slides exist)")
23
+ plan = json.loads(PLAN.read_text())
24
+ gen = json.loads((DECK / TEXT).read_text())["slides"]
25
+ old = {s["title"]: s for s in spec["slides"] if s.get("kind") == "content"}
26
+ title = next(s for s in spec["slides"] if s.get("kind") == "title")
27
+ agenda = next(s for s in spec["slides"] if s.get("kind") == "agenda")
28
+
29
+ def new_slide(i, label):
30
+ g = gen[i]
31
+ return {"kind": "content", "section": "plan", "section_label": label,
32
+ "text_source": {"file": TEXT, "index": i}, "title": g["title"], "layout": g["layout"],
33
+ "figures": [str(Path(f).relative_to(DECK)) for f in g["figures"]], "keywords": [], "footnote": "",
34
+ "sources": "tools/figure_plan.py; data/figure_plan.json"}
35
+ made = {g["title"]: i for i, g in enumerate(gen)}
36
+ title["subtitle"] = "Paper figure plan (Nature style) · updated 2026-10-06"
37
+ agenda["items"] = [f"Fig. {f['n']} {f['title']}" for f in plan["figures"]] + ["Supplementary", "Appendix"]
38
+ out = [title, agenda, new_slide(made["Manuscript plan: six main figures"], "Plan")]
39
+ used = set()
40
+ for f in plan["figures"]:
41
+ out.append({"kind": "divider", "title": f"Figure {f['n']}. {f['title']}"})
42
+ out.append(new_slide(made[f"Figure {f['n']} plan: {f['title']}"], f"Fig. {f['n']} plan"))
43
+ for p in f["panels"]:
44
+ for t in p["evidence"]:
45
+ if t in made:
46
+ s = new_slide(made[t], f"Fig. {f['n']}{p['p']}")
47
+ s["sources"] = ("tools/figure_plan.py; manuscript figures/" +
48
+ ("fig01_architecture_nature.svg" if "Overview" in t else "fig01_corpus_nature.png"))
49
+ else:
50
+ s = old[t]
51
+ s["section"], s["section_label"] = str(f["n"]), f"Fig. {f['n']}{p['p']}"
52
+ used.add(t)
53
+ out.append(s)
54
+ for t in f["details"]:
55
+ s = old[t]
56
+ s["section"], s["section_label"] = str(f["n"]), f"Fig. {f['n']} details"
57
+ used.add(t)
58
+ out.append(s)
59
+ for block, titles in (("Supplementary", plan["supplementary"]), ("Appendix", plan["appendix"])):
60
+ out.append({"kind": "divider", "title": block})
61
+ for t in titles:
62
+ s = old[t]
63
+ s["section_label"] = block
64
+ used.add(t)
65
+ out.append(s)
66
+ left = set(old) - used
67
+ if left:
68
+ raise SystemExit(f"slides not placed: {sorted(left)}")
69
+ spec["slides"] = out
70
+ SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
71
+ for i, s in enumerate(out, 1):
72
+ print(i, s.get("kind"), s.get("section_label", ""), "|", s.get("title"))
73
+
74
+
75
+ if __name__ == "__main__":
76
+ main()
paper-releases/pbisc-diffusion/updates/20261006T145850Z-deck-six-figure-order/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 '5 donors' 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())