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/restructure_20261006.py +73 -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/sec08_cross_cohort.py +285 -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/sec08_cross_scratch.py +214 -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_paired_validation.py +0 -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/restructure_20261006.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""One-off spec change of 2026-10-06 (user decision: the from-scratch results go to the paper's Supplementary, and the
|
| 3 |
+
Discussion presents them as a route to other tissues). Refuses to run twice.
|
| 4 |
+
|
| 5 |
+
- moves "No pretraining: same cohort, from scratch" (section 7) and "No pretraining: other cohorts, from scratch"
|
| 6 |
+
(section 8) into a new "Supplementary" block (divider + slides) placed before the existing Appendix block;
|
| 7 |
+
- adds "Rare states: from scratch vs pretrained" (tools/secS_scratch_rare_states.py) to that block;
|
| 8 |
+
- adds "Next: other tissues from a few dozen pairs" (tools/sec10_other_tissues.py) after the section 10 slide, and
|
| 9 |
+
relabels section 10 "10 Next steps";
|
| 10 |
+
- agenda: item 7 back to its wording before the scratch slides, item 10 names the new slide.
|
| 11 |
+
Text fields of the new slides are filled by tools/sync_sec09_text.py from their text_source files.
|
| 12 |
+
"""
|
| 13 |
+
import json
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
DECK = Path(__file__).resolve().parents[1]
|
| 17 |
+
SPEC = DECK / "data" / "slides_spec.json"
|
| 18 |
+
T_SAME = "No pretraining: same cohort, from scratch"
|
| 19 |
+
T_OTHER = "No pretraining: other cohorts, from scratch"
|
| 20 |
+
T_NEXT = "Next: cohorts with a paired subset (planned)"
|
| 21 |
+
LABEL_S, LABEL_10 = "Supplementary", "10 Next steps"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def main() -> None:
|
| 25 |
+
spec = json.loads(SPEC.read_text())
|
| 26 |
+
slides = spec["slides"]
|
| 27 |
+
if any(s.get("kind") == "divider" and s.get("title") == "Supplementary" for s in slides):
|
| 28 |
+
raise SystemExit("already restructured (a Supplementary divider exists)")
|
| 29 |
+
idx = {s.get("title"): i for i, s in enumerate(slides)}
|
| 30 |
+
for t in (T_SAME, T_OTHER, T_NEXT, "Appendix"):
|
| 31 |
+
if t not in idx:
|
| 32 |
+
raise SystemExit(f"slide not found: {t}")
|
| 33 |
+
same, other = slides[idx[T_SAME]], slides[idx[T_OTHER]]
|
| 34 |
+
rest = [s for s in slides if s.get("title") not in (T_SAME, T_OTHER)]
|
| 35 |
+
for s in (same, other):
|
| 36 |
+
s["section"], s["section_label"] = "S", LABEL_S
|
| 37 |
+
rare = {"kind": "content", "section": "S", "section_label": LABEL_S,
|
| 38 |
+
"text_source": {"file": "data/secS_scratch_rare_states_slide_text.json", "index": 0},
|
| 39 |
+
"title": "Rare states: from scratch vs pretrained", "layout": "full",
|
| 40 |
+
"figures": ["figures/secS_scratch_rare_states.png"], "keywords": [], "footnote": "",
|
| 41 |
+
"say": ("Supplementary. With the same pairs, the model trained from scratch makes rare cell states about as "
|
| 42 |
+
"well as the pretrained model on average, but pretraining keeps the cycling and interferon T and NK "
|
| 43 |
+
"states. C1Q-high monocytes appear only when the cohort's own pairs are used, whatever the "
|
| 44 |
+
"initialisation."),
|
| 45 |
+
"sources": ("plans/rare_states_screen_20261004/out/{sepsis_fold0,sepsis_loco_masked}_*.csv; "
|
| 46 |
+
"tools/secS_scratch_rare_states.py; data/secS_scratch_rare_states{,_bootstrap}.csv")}
|
| 47 |
+
nxt_txt = json.loads((DECK / "data" / "sec10_other_tissues_slide_text.json").read_text())["slides"][0]
|
| 48 |
+
nxt = {"kind": "content", "section": "10", "section_label": LABEL_10,
|
| 49 |
+
"text_source": {"file": "data/sec10_other_tissues_slide_text.json", "index": 0},
|
| 50 |
+
"title": nxt_txt["title"], "layout": "full", "figures": ["figures/sec10_other_tissues.png"],
|
| 51 |
+
"keywords": [], "footnote": "", "say": nxt_txt["say"],
|
| 52 |
+
"sources": ("tools/sec10_other_tissues.py; data/sec10_other_tissues.csv (from sec07_no_pretraining.csv, "
|
| 53 |
+
"sec08_cross_scratch.csv, secS_scratch_rare_states_bootstrap.csv, sec06_ft_method.csv, "
|
| 54 |
+
"sec01_model_numbers.csv)")}
|
| 55 |
+
out = []
|
| 56 |
+
for s in rest:
|
| 57 |
+
if s.get("kind") == "divider" and s.get("title") == "Appendix":
|
| 58 |
+
out += [{"kind": "divider", "title": "Supplementary"}, same, other, rare]
|
| 59 |
+
out.append(s)
|
| 60 |
+
if s.get("title") == T_NEXT:
|
| 61 |
+
s["section_label"] = LABEL_10
|
| 62 |
+
out.append(nxt)
|
| 63 |
+
agenda = next(s for s in out if s.get("kind") == "agenda")
|
| 64 |
+
agenda["items"][6] = "LoRA: compute, rank and K ablations"
|
| 65 |
+
agenda["items"][9] = "Next: paired-subset cohorts, other tissues"
|
| 66 |
+
spec["slides"] = out
|
| 67 |
+
SPEC.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n")
|
| 68 |
+
for i, s in enumerate(out, 1):
|
| 69 |
+
print(i, s.get("kind"), s.get("section_label", ""), "|", s.get("title"))
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
if __name__ == "__main__":
|
| 73 |
+
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/sec08_cross_cohort.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 8 of the 2026-09-30 paper-summary deck: do bulk-sc pairs from OTHER cohorts transfer? (added 2026-10-03)
|
| 3 |
+
|
| 4 |
+
The leave-one-cohort-out (LOCO) benchmark of plans/paired_crosscohort_20261002 (user decision 2026-10-03: report
|
| 5 |
+
K = 1000 only and use it to explain why PBISC fits LoRA on a few pairs of each cohort instead of one cross-cohort
|
| 6 |
+
model). CPU only; reads score summaries and run receipts, draws two slide figures:
|
| 7 |
+
figures/sec08_cross_cohort.{png,pdf} FULL: composition L1, coverage, disease logFC r per held-out cohort
|
| 8 |
+
figures/sec08_cross_cohort_steps.{png,pdf} FULL: the same test metrics against training steps (block milestones)
|
| 9 |
+
data/sec08_cross_cohort.csv, data/sec08_cross_cohort_steps.csv every plotted value with its source file
|
| 10 |
+
data/sec08_cross_cohort_slide_text.json titles, keywords, footnotes, quoted numbers (synced into the spec)
|
| 11 |
+
|
| 12 |
+
Arms (every one scores the held-out cohort's usable samples against the same frozen reference; checked):
|
| 13 |
+
zero-shot base model, real bulk (zs_K1000)
|
| 14 |
+
calibration (other) base model, bulk x alpha fitted on the OTHER cohorts' pairs (xcalL_K1000) 0 target pairs
|
| 15 |
+
LoRA r16 / r64 / full fine-tuned on the other PBMC cohorts + Liu 2021 (Liu: training only), step-saturation
|
| 16 |
+
protocol (20k blocks, stop below 1 % block improvement); value = last milestone 0 target pairs
|
| 17 |
+
own-cohort LoRA LoRA r16 on the cohort's own pairs, 5-fold pooled (plans/paired_finetune_intradataset_20260927)
|
| 18 |
+
Giroux's logFC r excludes the 196 sex-linked genes (scores_nosex/), as everywhere else in the deck.
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 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 style # noqa: E402
|
| 34 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 35 |
+
from matplotlib.patches import Patch # noqa: E402
|
| 36 |
+
from matplotlib.lines import Line2D # noqa: E402
|
| 37 |
+
|
| 38 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 39 |
+
LOCO = M8 / "plans/paired_crosscohort_20261002"
|
| 40 |
+
SRC = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 41 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 42 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 43 |
+
ORDER = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
|
| 44 |
+
NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
|
| 45 |
+
"ji2025_chili": "Ji (whole blood)"}
|
| 46 |
+
MODES = [("lora16sat", "LoRA r16"), ("lora64sat", "LoRA r64"), ("fullsat", "Full fine-tune")]
|
| 47 |
+
COL = {"zs": style.ARM["zs_raw"], "xcal": style.ARM["zs_cal"], "lora16sat": "#44AA99", "lora64sat": "#117733",
|
| 48 |
+
"fullsat": "#332288", "own": style.ARM["lora"]}
|
| 49 |
+
LAB = {"zs": "Zero-shot", "xcal": "Calibration from other cohorts", "lora16sat": "LoRA r16, other cohorts",
|
| 50 |
+
"lora64sat": "LoRA r64, other cohorts", "fullsat": "Full fine-tune, other cohorts",
|
| 51 |
+
"own": "LoRA on the cohort's own pairs"}
|
| 52 |
+
ARMS = ["zs", "xcal", "lora16sat", "lora64sat", "fullsat", "own"]
|
| 53 |
+
METRICS = [("comp_l1", "Composition L1\nlower = better"), ("coverage", "Coverage\nhigher = better"),
|
| 54 |
+
("logfc_r", "Disease logFC r\nhigher = better")]
|
| 55 |
+
EDGE, SUB, FS = "#333333", "#595959", style.FS
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def summary_metrics(summary_path: Path, arm: str, disease_path: Path | None) -> dict:
|
| 59 |
+
s = json.loads(summary_path.read_text())
|
| 60 |
+
h = s["headline"][arm]
|
| 61 |
+
out = {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "precision": h["precision"],
|
| 62 |
+
"logfc_r": h.get("contrast_mean_cp10k_r_gen"), "reference_sha256": s["reference"]["reference_sha256"],
|
| 63 |
+
"donors": sorted(s["donors"]), "source": str(summary_path), "source_disease": None}
|
| 64 |
+
if disease_path is not None and disease_path.is_file():
|
| 65 |
+
d = json.loads(disease_path.read_text())
|
| 66 |
+
out["logfc_r"] = d["headline"][arm].get("contrast_mean_cp10k_r_gen")
|
| 67 |
+
out["source_disease"] = str(disease_path)
|
| 68 |
+
return out
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def final_arm(cohort: str, tag: str) -> tuple[str, int, dict]:
|
| 72 |
+
run = json.loads((LOCO / "runs" / f"hoL_{cohort}" / "K1000" / tag / "RUN.json").read_text())
|
| 73 |
+
st = run["milestones"][-1]["milestone_step"]
|
| 74 |
+
return f"locoL_{tag}_s{st}_K1000", st, run
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def loco_paths(cohort: str, arm: str) -> tuple[Path, Path | None]:
|
| 78 |
+
main = LOCO / "scores" / cohort / arm / "summary.json"
|
| 79 |
+
dis = LOCO / "scores_nosex" / cohort / arm / "summary.json" if cohort == "giroux2022" else None
|
| 80 |
+
return main, dis
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def collect() -> tuple[pd.DataFrame, pd.DataFrame, dict]:
|
| 84 |
+
rows, steps, runs = [], [], {}
|
| 85 |
+
for c in ORDER:
|
| 86 |
+
refs = set()
|
| 87 |
+
for a, arm in (("zs", "zs_K1000"), ("xcal", "xcalL_K1000")):
|
| 88 |
+
m = summary_metrics(*loco_paths(c, arm)[:1], arm, loco_paths(c, arm)[1])
|
| 89 |
+
rows.append({"cohort": c, "arm": a, "score_arm": arm, "steps": None, **m})
|
| 90 |
+
refs.add(m["reference_sha256"])
|
| 91 |
+
for tag, _ in MODES:
|
| 92 |
+
arm, st, run = final_arm(c, tag)
|
| 93 |
+
runs[(c, tag)] = run
|
| 94 |
+
m = summary_metrics(*loco_paths(c, arm)[:1], arm, loco_paths(c, arm)[1])
|
| 95 |
+
rows.append({"cohort": c, "arm": tag, "score_arm": arm, "steps": st, **m,
|
| 96 |
+
"wall_seconds": run["wall_seconds"], "minutes": run["wall_seconds"] / 60,
|
| 97 |
+
"run_receipt": str(LOCO / "runs" / f"hoL_{c}" / "K1000" / tag / "RUN.json")})
|
| 98 |
+
refs.add(m["reference_sha256"])
|
| 99 |
+
for ms in run["milestones"]:
|
| 100 |
+
a2 = f"locoL_{tag}_s{ms['milestone_step']}_K1000"
|
| 101 |
+
m2 = summary_metrics(*loco_paths(c, a2)[:1], a2, loco_paths(c, a2)[1])
|
| 102 |
+
steps.append({"cohort": c, "mode": tag, "step": ms["milestone_step"],
|
| 103 |
+
"inner_val_loss": ms["selected_inner_val_loss"], "score_arm": a2,
|
| 104 |
+
**{k: m2[k] for k in ("comp_l1", "coverage", "precision", "logfc_r", "source",
|
| 105 |
+
"source_disease")}})
|
| 106 |
+
refs.add(m2["reference_sha256"])
|
| 107 |
+
own = summary_metrics(SRC / "scores" / c / "pooled" / "summary.json", "real_lora__raw",
|
| 108 |
+
SRC / "scores_nosex" / c / "pooled" / "summary.json" if c == "giroux2022" else None)
|
| 109 |
+
rows.append({"cohort": c, "arm": "own", "score_arm": "real_lora__raw", "steps": None, **own})
|
| 110 |
+
refs.add(own["reference_sha256"])
|
| 111 |
+
donors = {tuple(r["donors"]) for r in rows if r["cohort"] == c}
|
| 112 |
+
if len(refs) != 1 or len(donors) != 1:
|
| 113 |
+
raise SystemExit(f"{c}: scoring calls differ in reference or samples")
|
| 114 |
+
t = pd.DataFrame(rows).drop(columns=["donors", "reference_sha256"])
|
| 115 |
+
return t, pd.DataFrame(steps), runs
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def draw_main(t: pd.DataFrame) -> None:
|
| 119 |
+
fig, axs = plt.subplots(len(METRICS), len(ORDER), figsize=(12.3, 5.0), sharey="row",
|
| 120 |
+
gridspec_kw={"hspace": 0.32, "wspace": 0.08})
|
| 121 |
+
x = np.arange(len(ARMS))
|
| 122 |
+
for j, c in enumerate(ORDER):
|
| 123 |
+
sub = t[t.cohort == c].set_index("arm").loc[ARMS]
|
| 124 |
+
for i, (key, label) in enumerate(METRICS):
|
| 125 |
+
ax = axs[i, j]
|
| 126 |
+
v = sub[key].astype(float).to_numpy()
|
| 127 |
+
if np.isnan(v).all():
|
| 128 |
+
ax.text(0.5, 0.5, "no case–control groups", ha="center", va="center", fontsize=FS - 3, color=SUB,
|
| 129 |
+
transform=ax.transAxes)
|
| 130 |
+
else:
|
| 131 |
+
ax.bar(x, np.nan_to_num(v), 0.78, color=[COL[a] for a in ARMS], edgecolor="none")
|
| 132 |
+
for xi, a in zip(x, ARMS):
|
| 133 |
+
if a in ("lora16sat", "lora64sat", "fullsat"):
|
| 134 |
+
st = sub.loc[a, "steps"]
|
| 135 |
+
if i == 0:
|
| 136 |
+
ax.text(xi, 0.012, f"{int(st) // 1000}k", ha="center", va="bottom", rotation=90,
|
| 137 |
+
fontsize=FS - 6, color="white")
|
| 138 |
+
ax.set_xticks([])
|
| 139 |
+
if j == 0:
|
| 140 |
+
ax.set_ylabel(label, fontsize=FS - 3)
|
| 141 |
+
if i == 0:
|
| 142 |
+
ax.set_title(NAME[c], fontsize=FS - 1)
|
| 143 |
+
ax.tick_params(axis="y", labelsize=FS - 4)
|
| 144 |
+
ax.axhline(0, color=EDGE, lw=0.8)
|
| 145 |
+
handles = [Patch(color=COL[a], label=LAB[a]) for a in ARMS]
|
| 146 |
+
fig.legend(handles=handles, loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.08), fontsize=FS - 3,
|
| 147 |
+
handlelength=1.1, columnspacing=1.4)
|
| 148 |
+
style.save(fig, "sec08_cross_cohort", FIGDIR)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def draw_steps(t: pd.DataFrame, st: pd.DataFrame) -> None:
|
| 152 |
+
mets = METRICS[:2] + [METRICS[2]]
|
| 153 |
+
fig, axs = plt.subplots(len(mets), len(ORDER), figsize=(12.3, 5.0), sharex=True, sharey="row",
|
| 154 |
+
gridspec_kw={"hspace": 0.3, "wspace": 0.08})
|
| 155 |
+
for j, c in enumerate(ORDER):
|
| 156 |
+
ref = t[t.cohort == c].set_index("arm")
|
| 157 |
+
for i, (key, label) in enumerate(mets):
|
| 158 |
+
ax = axs[i, j]
|
| 159 |
+
if ref[key].isna().all():
|
| 160 |
+
ax.text(0.5, 0.5, "no case–control groups", ha="center", va="center", fontsize=FS - 3, color=SUB,
|
| 161 |
+
transform=ax.transAxes)
|
| 162 |
+
else:
|
| 163 |
+
for tag, _ in MODES:
|
| 164 |
+
s = st[(st.cohort == c) & (st["mode"] == tag)].sort_values("step")
|
| 165 |
+
ax.plot(s.step / 1000, s[key], "-o", color=COL[tag], ms=3.5, lw=1.6)
|
| 166 |
+
for a, ls in (("xcal", "--"), ("own", ":")):
|
| 167 |
+
ax.axhline(ref.loc[a, key], color=COL[a], ls=ls, lw=1.4)
|
| 168 |
+
if j == 0:
|
| 169 |
+
ax.set_ylabel(label, fontsize=FS - 3)
|
| 170 |
+
if i == 0:
|
| 171 |
+
ax.set_title(NAME[c], fontsize=FS - 1)
|
| 172 |
+
if i == len(mets) - 1:
|
| 173 |
+
ax.set_xlabel("training steps (k)", fontsize=FS - 3)
|
| 174 |
+
ax.tick_params(labelsize=FS - 4)
|
| 175 |
+
handles = [Line2D([0], [0], color=COL[t_], marker="o", ms=4, lw=1.6, label=LAB[t_]) for t_, _ in MODES]
|
| 176 |
+
handles += [Line2D([0], [0], color=COL["xcal"], ls="--", lw=1.4, label=LAB["xcal"]),
|
| 177 |
+
Line2D([0], [0], color=COL["own"], ls=":", lw=1.4, label=LAB["own"])]
|
| 178 |
+
fig.legend(handles=handles, loc="lower center", ncol=3, bbox_to_anchor=(0.5, -0.09), fontsize=FS - 3,
|
| 179 |
+
handlelength=1.8, columnspacing=1.4)
|
| 180 |
+
style.save(fig, "sec08_cross_cohort_steps", FIGDIR)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def slide_text(t: pd.DataFrame, st: pd.DataFrame, runs: dict) -> dict:
|
| 184 |
+
piv = {k: t.pivot(index="cohort", columns="arm", values=k).loc[ORDER] for k, _ in METRICS}
|
| 185 |
+
loco = ["lora16sat", "lora64sat", "fullsat"]
|
| 186 |
+
best_l1 = piv["comp_l1"][["xcal"] + loco].idxmin(axis=1)
|
| 187 |
+
n_cal_l1 = int((piv["comp_l1"]["xcal"] <= piv["comp_l1"][loco].min(axis=1) + 0.01).sum())
|
| 188 |
+
own_cov = piv["coverage"]["own"]
|
| 189 |
+
zero_cov = piv["coverage"][["xcal"] + loco].max(axis=1)
|
| 190 |
+
dis = [c for c in ORDER if not np.isnan(piv["logfc_r"].loc[c, "own"])]
|
| 191 |
+
own_r = piv["logfc_r"].loc[dis, "own"]
|
| 192 |
+
zero_r = piv["logfc_r"].loc[dis, ["zs", "xcal"] + loco].max(axis=1)
|
| 193 |
+
n_own_cov = int((own_cov > zero_cov).sum())
|
| 194 |
+
n_own_r = int((own_r > zero_r).sum())
|
| 195 |
+
sat = {tag: [r["milestones"][-1]["milestone_step"] for (c, tg), r in runs.items() if tg == tag] for tag in loco}
|
| 196 |
+
ji = st[(st.cohort == "ji2025_chili") & (st["mode"] == "fullsat")].sort_values("step")
|
| 197 |
+
ji_first, ji_last = ji.comp_l1.iloc[0], ji.comp_l1.iloc[-1]
|
| 198 |
+
# full fine-tune: cohorts whose composition L1 rose (drift) or fell by >= 0.05 from the first to the last milestone
|
| 199 |
+
d_full = {c: g.sort_values("step").comp_l1.iloc[-1] - g.sort_values("step").comp_l1.iloc[0]
|
| 200 |
+
for c, g in st[st["mode"] == "fullsat"].groupby("cohort")}
|
| 201 |
+
drift = [NAME[c].split(" ")[0] for c in ORDER if d_full[c] >= 0.05]
|
| 202 |
+
gain = [NAME[c].split(" ")[0] for c in ORDER if d_full[c] <= -0.05]
|
| 203 |
+
# gap: no milestone of any mode reaches the own-cohort LoRA's coverage
|
| 204 |
+
gap = all(st[st.cohort == c].coverage.max() < piv["coverage"].loc[c, "own"] for c in ORDER)
|
| 205 |
+
# training time to saturation (RUN.json wall_seconds, one GB10; added 2026-10-06, user request: times in the deck)
|
| 206 |
+
mins = {tag: [runs[(c, tag)]["wall_seconds"] / 60 for c in ORDER] for tag in loco}
|
| 207 |
+
rng = {tag: (min(v), max(v)) for tag, v in mins.items()}
|
| 208 |
+
s1 = {"title": "Pairs from other cohorts do not transfer", "layout": "full",
|
| 209 |
+
"figures": [str(FIGDIR / "sec08_cross_cohort.png")],
|
| 210 |
+
"keywords": ["Train on the other cohorts, test the held-out one",
|
| 211 |
+
f"Calibration ties or beats them on composition in {n_cal_l1}/5",
|
| 212 |
+
f"Own-cohort pairs best on coverage {n_own_cov}/5, disease r {n_own_r}/{len(dis)}"],
|
| 213 |
+
"footnote_short": "Leave-one-cohort-out, K = 1000; train on the other cohorts (+ Liu 2021), test the held-out one.",
|
| 214 |
+
"footnote": ("Each held-out cohort is scored on all its usable samples against the same frozen reference as "
|
| 215 |
+
"its within-cohort benchmark. Zero-shot = base model on real bulk. Calibration from other cohorts = "
|
| 216 |
+
"gene-wise alpha (mean pseudobulk CPM / mean bulk CPM) fitted on the training cohorts' pairs, "
|
| 217 |
+
"cohort-balanced; 0 target pairs. LoRA r16 / r64 / full fine-tune = trained on the other PBMC "
|
| 218 |
+
"cohorts' pairs plus Liu 2021 (training only: its cells are in the pretraining corpus; 44 pairs "
|
| 219 |
+
"after excluding 14 hashtag-negative-heavy rows), cohort-balanced batches, inner-validation on "
|
| 220 |
+
"10 % of each training cohort's donors, step-saturation protocol (20k-step blocks, stop when a "
|
| 221 |
+
"block lowers the inner-validation loss by < 1 % of the total), value at the last milestone "
|
| 222 |
+
"(number in the bar = steps). Ji's bulk is whole blood and is never trained on. Own-cohort LoRA = "
|
| 223 |
+
"LoRA r16 on the cohort's own pairs, 5-fold pooled. Giroux's logFC r excludes 196 sex-linked "
|
| 224 |
+
"genes. Best on composition among zero-target-pair arms: " +
|
| 225 |
+
", ".join(f"{NAME[c]} {LAB[best_l1[c]]}" for c in ORDER) + "."),
|
| 226 |
+
"numbers": [{"value": f"{NAME[c]}: L1 " + " / ".join(f"{a} {piv['comp_l1'].loc[c, a]:.3f}" for a in ARMS)
|
| 227 |
+
+ "; coverage " + " / ".join(f"{a} {piv['coverage'].loc[c, a]:.2f}" for a in ARMS)
|
| 228 |
+
+ ("; logFC r " + " / ".join(f"{a} {piv['logfc_r'].loc[c, a]:.2f}" for a in ARMS)
|
| 229 |
+
if c in dis else ""), "source": "data/sec08_cross_cohort.csv"} for c in ORDER]}
|
| 230 |
+
s2 = {"title": "Longer training on other cohorts" + (": gap stays" if gap else ""), "layout": "full",
|
| 231 |
+
"figures": [str(FIGDIR / "sec08_cross_cohort_steps.png")],
|
| 232 |
+
"keywords": [f"To saturation: r16 {rng['lora16sat'][0]:.0f}–{rng['lora16sat'][1]:.0f} min, "
|
| 233 |
+
f"full {rng['fullsat'][0]:.0f}–{rng['fullsat'][1]:.0f} min",
|
| 234 |
+
f"Full fine-tune drifts in {' and '.join(drift)} (Ji L1 {ji_first:.2f} → {ji_last:.2f})"
|
| 235 |
+
if "Ji" in drift else f"Full fine-tune drifts in {' and '.join(drift) or 'no cohort'}",
|
| 236 |
+
"So PBISC fits LoRA on a few pairs per cohort"],
|
| 237 |
+
"footnote_short": "Test metrics at every 20k-step milestone (best inner-validation state so far). K = 1000.",
|
| 238 |
+
"footnote": ("Same runs as the previous slide. Each point = the milestone checkpoint at the end of a 20k-step "
|
| 239 |
+
"block (or at the early stop), sampled and scored on the held-out cohort. Dashed = calibration "
|
| 240 |
+
"from other cohorts; dotted = LoRA on the cohort's own pairs. Training stopped (steps): " +
|
| 241 |
+
"; ".join(f"{dict(MODES)[tg]} " + ", ".join(f"{NAME[c].split(' ')[0]} {runs[(c, tg)]['milestones'][-1]['milestone_step'] // 1000}k"
|
| 242 |
+
for c in ORDER) for tg in loco) +
|
| 243 |
+
f". Saturation steps across cohorts: r16 up to {max(sat['lora16sat']) // 1000}k, r64 up to "
|
| 244 |
+
f"{max(sat['lora64sat']) // 1000}k, full up to {max(sat['fullsat']) // 1000}k. Training time to "
|
| 245 |
+
"saturation (RUN.json wall seconds, one GB10): " +
|
| 246 |
+
"; ".join(f"{dict(MODES)[tg]} " + ", ".join(f"{NAME[c].split(' ')[0]} {m:.0f} min"
|
| 247 |
+
for c, m in zip(ORDER, mins[tg])) for tg in loco) +
|
| 248 |
+
". Gap = no milestone of any mode reaches the own-cohort LoRA's coverage" +
|
| 249 |
+
(" (true in all five cohorts)" if gap else "") + "; full fine-tune composition L1 from the first "
|
| 250 |
+
"to the last milestone: " + ", ".join(f"{NAME[c].split(' ')[0]} {d_full[c]:+.3f}" for c in ORDER) +
|
| 251 |
+
(f" (drift >= 0.05 in {' and '.join(drift)}" if drift else " (no drift >= 0.05") +
|
| 252 |
+
(f"; improved by >= 0.05 in {' and '.join(gain)})." if gain else ").")),
|
| 253 |
+
"numbers": [{"value": f"{NAME[c]} {dict(MODES)[tg]}: " + ", ".join(
|
| 254 |
+
f"{int(r.step) // 1000}k L1 {r.comp_l1:.3f} cov {r.coverage:.2f}" for r in
|
| 255 |
+
st[(st.cohort == c) & (st["mode"] == tg)].sort_values("step").itertuples()),
|
| 256 |
+
"source": "data/sec08_cross_cohort_steps.csv"} for c in ORDER for tg in loco] +
|
| 257 |
+
[{"value": f"Training time to saturation, {dict(MODES)[tg]}: " + ", ".join(
|
| 258 |
+
f"{NAME[c].split(' ')[0]} {m:.0f} min" for c, m in zip(ORDER, mins[tg])),
|
| 259 |
+
"source": "data/sec08_cross_cohort.csv (minutes = RUN.json wall_seconds / 60)"} for tg in loco]}
|
| 260 |
+
return {"section": "08-cross-cohort", "scripts": [str(Path(__file__).resolve())],
|
| 261 |
+
"generated_from": "tools/sec08_cross_cohort.py (rerun to refresh; do not edit by hand)",
|
| 262 |
+
"slides": [s1, s2]}
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def main() -> int:
|
| 266 |
+
t, st, runs = collect()
|
| 267 |
+
agg = pd.read_csv(LOCO / "scores" / "aggregate.csv")
|
| 268 |
+
for r in t[t.arm.isin(["zs", "xcal", "lora16sat", "lora64sat", "fullsat"])].itertuples():
|
| 269 |
+
g = agg[(agg.cohort == r.cohort) & (agg.arm == r.score_arm)]
|
| 270 |
+
if len(g) != 1 or abs(float(g.comp_l1.iloc[0]) - r.comp_l1) > 1e-9:
|
| 271 |
+
raise SystemExit(f"{r.cohort} {r.score_arm}: differs from scores/aggregate.csv")
|
| 272 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 273 |
+
t.to_csv(OUTDATA / "sec08_cross_cohort.csv", index=False)
|
| 274 |
+
st.to_csv(OUTDATA / "sec08_cross_cohort_steps.csv", index=False)
|
| 275 |
+
draw_main(t)
|
| 276 |
+
draw_steps(t, st)
|
| 277 |
+
txt = slide_text(t, st, runs)
|
| 278 |
+
(OUTDATA / "sec08_cross_cohort_slide_text.json").write_text(json.dumps(txt, indent=1, ensure_ascii=False))
|
| 279 |
+
for s in txt["slides"]:
|
| 280 |
+
print(s["title"]); print(" " + "\n ".join(s["keywords"]))
|
| 281 |
+
return 0
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
if __name__ == "__main__":
|
| 285 |
+
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/sec08_cross_scratch.py
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Section 8 slide of the 2026-09-30 paper-summary deck: no pretraining, other cohorts (held-out sepsis pilot, 2026-10-05).
|
| 3 |
+
|
| 4 |
+
CPU only. Held-out sepsis (82 usable samples), training pool = ImMicro + Imperial + Giroux + Liu 2021 (split
|
| 5 |
+
hoL_ye2026_sepsis), K = 1,000. Arms: zero-shot + cross-cohort calibration, pretrained + LoRA r16 / r64 / full FT at step
|
| 6 |
+
saturation (as the 'Pairs from other cohorts do not transfer' and 'Longer training on other cohorts' slides), the same denoiser trained from random initialisation on the pool (--init random, full,
|
| 7 |
+
lr 2e-4, milestones every 50k steps to 162k), and the cohort's own-pair LoRA (5-fold, reference).
|
| 8 |
+
|
| 9 |
+
All arms are read from plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis/<arm>/summary.json
|
| 10 |
+
(tools/mask_rescore.py): the 46 panel genes measured in sepsis but in no training cohort are zeroed in the generated
|
| 11 |
+
cells of EVERY arm before scoring. Reason: a model trained from scratch never gets a loss on those genes and puts most
|
| 12 |
+
of its UMI there (share read from the generated_masked/<arm>.log receipts; observed share from cells_panel6k.npz), so unmasked
|
| 13 |
+
scores would measure that artefact. The pretrained arms change little with the mask (checked against scores/ and
|
| 14 |
+
printed). Training time and stopping settings = RUN.json (GB10); the own-cohort LoRA time is the mean of its five fold
|
| 15 |
+
runs (paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold*/real_lora).
|
| 16 |
+
Outputs: figures/sec08_cross_scratch.{png,pdf}, data/sec08_cross_scratch.csv, data/sec08_cross_scratch_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 glob
|
| 25 |
+
import json
|
| 26 |
+
import sys
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
import pandas as pd
|
| 31 |
+
|
| 32 |
+
DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
|
| 33 |
+
"2026-09-30--paper-summary--r00")
|
| 34 |
+
sys.path.insert(0, str(DECK / "tools"))
|
| 35 |
+
import sec09_paired_validation as S9 # noqa: E402
|
| 36 |
+
import style # noqa: E402
|
| 37 |
+
from grouped_bars import grouped_bars # noqa: E402
|
| 38 |
+
import matplotlib.pyplot as plt # noqa: E402
|
| 39 |
+
|
| 40 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 41 |
+
P = M8 / "plans" / "paired_crosscohort_20261002"
|
| 42 |
+
TI = M8 / "plans" / "paired_finetune_intradataset_20260927"
|
| 43 |
+
MS, UM = P / "scores_masked" / "ye2026_sepsis", P / "scores" / "ye2026_sepsis"
|
| 44 |
+
GM = P / "generated_masked" / "ye2026_sepsis" / "hoL_ye2026_sepsis"
|
| 45 |
+
RUNS = P / "runs" / "hoL_ye2026_sepsis" / "K1000"
|
| 46 |
+
FIGDIR = Path(os.environ.get("DECK_FIGDIR", str(DECK / "figures")))
|
| 47 |
+
OUTDATA = Path(os.environ.get("DECK_OUTDATA", str(DECK / "data")))
|
| 48 |
+
FS, SUB, EDGE = S9.FS, S9.SUB, S9.EDGE
|
| 49 |
+
# key, label, scored arm, run dir (None = no training), colour, hatch (colours as in tools/sec08_cross_cohort.py)
|
| 50 |
+
ARMS = [("cal", "Calibration", "xcalL_K1000", None, "#0072B2", None),
|
| 51 |
+
("r16", "LoRA r16", "locoL_lora16sat_s26750_K1000", "lora16sat", "#44AA99", None),
|
| 52 |
+
("r64", "LoRA r64", "locoL_lora64sat_s59000_K1000", "lora64sat", "#117733", None),
|
| 53 |
+
("full", "Full FT", "locoL_fullsat_s108500_K1000", "fullsat", "#332288", None),
|
| 54 |
+
("scratch", "From scratch", "locoL_scratchsat_s162000_K1000", "scratchsat", "#882255", None),
|
| 55 |
+
("own", "Own-cohort LoRA", "within_real_lora__raw", "own", "#D55E00", "///")]
|
| 56 |
+
MILESTONES = ["locoL_scratchsat_s50000_K1000", "locoL_scratchsat_s100000_K1000", "locoL_scratchsat_s150000_K1000",
|
| 57 |
+
"locoL_scratchsat_s162000_K1000"]
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def observed_share(gene_ids) -> float:
|
| 61 |
+
"""UMI share of the observed sepsis cells on the masked genes (all cells of the cohort's panel matrix)."""
|
| 62 |
+
z = np.load(TI / "data" / "ye2026_sepsis" / "cells_panel6k.npz", allow_pickle=False)
|
| 63 |
+
ids = z["panel_gene_ids"].astype(str)
|
| 64 |
+
col = np.isin(ids, np.asarray(gene_ids, dtype=str))
|
| 65 |
+
if col.sum() != len(set(gene_ids)):
|
| 66 |
+
raise SystemExit("masked genes missing from the sepsis panel")
|
| 67 |
+
per_gene = np.bincount(z["indices"], weights=z["data"], minlength=len(ids))
|
| 68 |
+
return float(per_gene[col].sum() / per_gene.sum())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def head(root, arm):
|
| 72 |
+
s = json.loads((root / arm / "summary.json").read_text())
|
| 73 |
+
h = s["headline"][arm]
|
| 74 |
+
return s, {"comp_l1": h["comp_l1"], "coverage": h["coverage"], "logfc_r": h["contrast_mean_cp10k_r_gen"],
|
| 75 |
+
"deg": h.get("deg_top50_sum")}
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main() -> int:
|
| 79 |
+
vals, rows, ref = {}, [], None
|
| 80 |
+
for key, lab, arm, run, *_ in ARMS:
|
| 81 |
+
s, v = head(MS, arm)
|
| 82 |
+
sig = (tuple(sorted(s["donors"])), s["reference"]["reference_sha256"])
|
| 83 |
+
if ref is None:
|
| 84 |
+
ref = sig
|
| 85 |
+
elif sig != ref:
|
| 86 |
+
raise SystemExit(f"{arm}: donors or reference differ from the other masked calls")
|
| 87 |
+
if run is None:
|
| 88 |
+
v["minutes"], v["steps"] = np.nan, 0
|
| 89 |
+
elif run == "own":
|
| 90 |
+
w = [json.loads(Path(f).read_text())["wall_seconds"] for f in
|
| 91 |
+
sorted(glob.glob(str(TI / "runs" / "ye2026_sepsis" / "fold*" / "real_lora" / "RUN.json")))]
|
| 92 |
+
if len(w) != 5:
|
| 93 |
+
raise SystemExit("own-cohort LoRA: expected five fold runs")
|
| 94 |
+
v["minutes"], v["steps"] = float(np.mean(w)) / 60, None
|
| 95 |
+
else:
|
| 96 |
+
rj = json.loads((RUNS / run / "RUN.json").read_text())
|
| 97 |
+
if (rj.get("init") == "random") != (key == "scratch"):
|
| 98 |
+
raise SystemExit(f"{run}: init {rj.get('init')}")
|
| 99 |
+
v["minutes"], v["steps"] = rj["wall_seconds"] / 60, rj["steps_run"]
|
| 100 |
+
um = UM / arm / "summary.json"
|
| 101 |
+
if um.exists() and key not in ("scratch",):
|
| 102 |
+
_, u = head(UM, arm)
|
| 103 |
+
v["unmasked_comp_l1"], v["unmasked_coverage"], v["unmasked_logfc_r"] = u["comp_l1"], u["coverage"], u["logfc_r"]
|
| 104 |
+
vals[key] = v
|
| 105 |
+
rows.append({"arm": key, "label": lab.replace("\n", " "), "scored_arm": arm, **v,
|
| 106 |
+
"source": str(MS / arm / "summary.json")})
|
| 107 |
+
if len(ref[0]) != 82:
|
| 108 |
+
raise SystemExit(f"expected 82 scored samples, got {len(ref[0])}")
|
| 109 |
+
ms = {a: head(MS, a)[1] for a in MILESTONES}
|
| 110 |
+
for a in MILESTONES:
|
| 111 |
+
rows.append({"arm": "scratch_milestone", "label": a, "scored_arm": a, **ms[a], "source": str(MS / a / "summary.json")})
|
| 112 |
+
for k, v in vals.items():
|
| 113 |
+
if "unmasked_comp_l1" in v:
|
| 114 |
+
print(f"{k}: masked vs unmasked L1 {v['comp_l1']:.3f}/{v['unmasked_comp_l1']:.3f}, coverage "
|
| 115 |
+
f"{v['coverage']:.3f}/{v['unmasked_coverage']:.3f}, logFC r {v['logfc_r']:.3f}/{v['unmasked_logfc_r']:.3f}")
|
| 116 |
+
|
| 117 |
+
groups = [lab for _, lab, *_ in ARMS]
|
| 118 |
+
panels = [("comp_l1", "Composition L1 ↓", False, lambda v: f"{v:.2f}"),
|
| 119 |
+
("coverage", "Coverage ↑", False, lambda v: f"{v:.2f}"),
|
| 120 |
+
("logfc_r", "Disease logFC r ↑", False, lambda v: f"{v:.2f}"),
|
| 121 |
+
("minutes", "Train time (min)", True, lambda v: f"{v:.0f}")]
|
| 122 |
+
fig, axes = plt.subplots(1, len(panels), figsize=(12.3, 4.0), gridspec_kw={"wspace": 0.30})
|
| 123 |
+
for ax, (mk, lab, log, fmt) in zip(axes, panels):
|
| 124 |
+
x = np.arange(len(ARMS))
|
| 125 |
+
for i, (key, _l, _a, _r, col, hatch) in enumerate(ARMS):
|
| 126 |
+
v = vals[key][mk]
|
| 127 |
+
if np.isnan(v):
|
| 128 |
+
ax.text(i, 0.10, "none", transform=ax.get_xaxis_transform(), ha="center", va="bottom",
|
| 129 |
+
fontsize=FS - 5, color=SUB)
|
| 130 |
+
continue
|
| 131 |
+
ax.bar(i, v, 0.75, color=col, edgecolor=EDGE if hatch else "none", linewidth=0.6, hatch=hatch, zorder=2)
|
| 132 |
+
ax.text(i, v * (1.08 if log else 1.0) + (0 if log else 0.008), fmt(v), ha="center", va="bottom",
|
| 133 |
+
fontsize=FS - 6, color=SUB)
|
| 134 |
+
ax.set_xticks(x, [g for g in groups], rotation=55, ha="right", fontsize=FS - 5)
|
| 135 |
+
ax.set_xlim(-0.6, len(ARMS) - 0.4) # keep the "none" label of the first arm inside the axes
|
| 136 |
+
ax.set_title(lab, fontsize=FS - 1)
|
| 137 |
+
ax.tick_params(axis="y", labelsize=FS - 4)
|
| 138 |
+
ax.grid(axis="y", color="#E3E3E3", linewidth=0.8, zorder=0)
|
| 139 |
+
ax.set_axisbelow(True)
|
| 140 |
+
ax.axvline(len(ARMS) - 1.5, color="#BBBBBB", lw=0.8, ls=":")
|
| 141 |
+
if mk == "coverage":
|
| 142 |
+
ax.set_ylim(0, 1.0)
|
| 143 |
+
if log:
|
| 144 |
+
ax.set_yscale("log")
|
| 145 |
+
ax.set_ylim(1, 400)
|
| 146 |
+
ax.set_yticks([1, 10, 100], ["1", "10", "100"])
|
| 147 |
+
ax.minorticks_off()
|
| 148 |
+
if mk == "comp_l1":
|
| 149 |
+
ax.set_ylim(0, max(v["comp_l1"] for v in vals.values()) * 1.18)
|
| 150 |
+
style.save(fig, "sec08_cross_scratch", FIGDIR)
|
| 151 |
+
OUTDATA.mkdir(exist_ok=True)
|
| 152 |
+
pd.DataFrame(rows).to_csv(OUTDATA / "sec08_cross_scratch.csv", index=False, float_format="%.6g")
|
| 153 |
+
|
| 154 |
+
sc, r16, own, cal = vals["scratch"], vals["r16"], vals["own"], vals["cal"]
|
| 155 |
+
kw = [f"Scratch ≈ LoRA r16: coverage {sc['coverage']:.2f} vs {r16['coverage']:.2f}",
|
| 156 |
+
f"Own-cohort pairs far ahead: coverage {own['coverage']:.2f}",
|
| 157 |
+
f"Scratch {sc['minutes']:.0f} min vs LoRA r16 {r16['minutes']:.0f} min"]
|
| 158 |
+
for k in kw:
|
| 159 |
+
if len(k) > 45:
|
| 160 |
+
raise SystemExit(f"keyword too long: {k}")
|
| 161 |
+
numbers = [{"value": f"{lab.replace(chr(10), ' ')}: L1 {vals[k]['comp_l1']:.3f}, coverage {vals[k]['coverage']:.3f}, "
|
| 162 |
+
f"logFC r {vals[k]['logfc_r']:.3f}, top-50 DEG {vals[k]['deg']}, time "
|
| 163 |
+
+ ("none" if np.isnan(vals[k]["minutes"]) else f"{vals[k]['minutes']:.0f} min"),
|
| 164 |
+
"source": "data/sec08_cross_scratch.csv"} for k, lab, *_ in ARMS]
|
| 165 |
+
numbers.append({"value": "Scratch milestones (masked) 50k / 100k / 150k / 162k steps: L1 " +
|
| 166 |
+
" / ".join(f"{ms[a]['comp_l1']:.3f}" for a in MILESTONES) + "; coverage " +
|
| 167 |
+
" / ".join(f"{ms[a]['coverage']:.3f}" for a in MILESTONES) + "; logFC r " +
|
| 168 |
+
" / ".join(f"{ms[a]['logfc_r']:.3f}" for a in MILESTONES),
|
| 169 |
+
"source": "data/sec08_cross_scratch.csv"})
|
| 170 |
+
rj = {k: json.loads((RUNS / run / "RUN.json").read_text()) for k, _l, _a, run, *_ in ARMS if run not in (None, "own")}
|
| 171 |
+
sj, pre_rj = rj["scratch"], [rj[k] for k in ("r16", "r64", "full")]
|
| 172 |
+
if len({(r["eval_every"], r["patience"], r["block"], r["saturation_frac"]) for r in pre_rj}) != 1:
|
| 173 |
+
raise SystemExit("pretrained saturation arms differ in their stopping settings")
|
| 174 |
+
pj = pre_rj[0]
|
| 175 |
+
stops = sorted({r["stop_reason"] for r in rj.values()})
|
| 176 |
+
shares = {a: json.loads((GM / f"{a}.log").read_text())["generated_umi_share_masked_before"] for a in MILESTONES}
|
| 177 |
+
masked = {tuple(json.loads((GM / f"{a}.log").read_text())["masked_gene_ids"]) for a in MILESTONES}
|
| 178 |
+
if len(masked) != 1:
|
| 179 |
+
raise SystemExit("milestones masked different genes")
|
| 180 |
+
masked = masked.pop()
|
| 181 |
+
n_mask, obs_share = len(masked), observed_share(masked)
|
| 182 |
+
sel = dict((k, a) for k, _l, a, *_ in ARMS)["scratch"]
|
| 183 |
+
full = ("Pilot, one held-out cohort: sepsis (82 samples), training pool ImMicro + Imperial + Giroux + Liu 2021, "
|
| 184 |
+
"K = 1,000, same inner-val selection and sampling as the 'Pairs from other cohorts do not transfer' and "
|
| 185 |
+
"'Longer training on other cohorts' slides. From scratch = the same denoiser at random initialisation "
|
| 186 |
+
f"(--init random), full training at lr {sj['lr']:.0e}".replace("e-0", "e-") + f", inner validation every {sj['eval_every']:,} steps "
|
| 187 |
+
f"(patience {sj['patience']}), milestones every {sj['block'] // 1000}k steps without the "
|
| 188 |
+
f"{pj['saturation_frac']:.0%} saturation rule; stopped at {sj['steps_run'] // 1000}k (selected "
|
| 189 |
+
f"{sj['selected_step'] // 1000}k; {sj['wall_seconds'] / 60:.0f} min on one GB10). The pretrained arms: inner "
|
| 190 |
+
f"validation every {pj['eval_every']} steps (patience {pj['patience']}), {pj['block'] // 1000}k-step blocks "
|
| 191 |
+
f"with the {pj['saturation_frac']:.0%} rule; " + ("all four runs ended by patience early stopping" if stops == ["early_stop"] else f"stop reasons: {', '.join(stops)}") + ". Every arm is "
|
| 192 |
+
f"scored with the {n_mask} panel genes that no training cohort measured set to 0 in the generated cells "
|
| 193 |
+
"(tools/mask_rescore.py): the scratch model never gets a loss on them and puts "
|
| 194 |
+
f"~{shares[sel]:.0%} of its UMI there ({100 * min(shares.values()):.0f}–{100 * max(shares.values()):.0f}% across "
|
| 195 |
+
f"milestones; observed sepsis cells {100 * obs_share:.3f}%); the pretrained arms barely change "
|
| 196 |
+
f"(e.g. LoRA r16 coverage {r16['coverage']:.2f} masked vs {r16.get('unmasked_coverage', float('nan')):.2f} unmasked). "
|
| 197 |
+
f"Calibration needs no training. Own-cohort LoRA = 5-fold LoRA on sepsis pairs (mean {own['minutes']:.1f} min "
|
| 198 |
+
"per fold). Scratch milestones: " + numbers[-1]["value"].split(": ", 1)[1] + ". "
|
| 199 |
+
"Source: plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis/ (table_masked.py), runs/hoL_ye2026_sepsis/K1000/.")
|
| 200 |
+
txt = {"title": "No pretraining: other cohorts, from scratch", "layout": "full",
|
| 201 |
+
"figures": [str(FIGDIR / "sec08_cross_scratch.png")], "keywords": kw,
|
| 202 |
+
"footnote_short": "Pilot: held-out sepsis, 82 samples. Genes no training cohort measured are zeroed in every arm.",
|
| 203 |
+
"footnote": full, "numbers": numbers}
|
| 204 |
+
out = {"section": "08-cross-scratch", "scripts": [str(Path(__file__).resolve())],
|
| 205 |
+
"generated_from": "tools/sec08_cross_scratch.py (rerun to refresh; do not edit by hand)", "slides": [txt]}
|
| 206 |
+
(OUTDATA / "sec08_cross_scratch_slide_text.json").write_text(json.dumps(out, indent=1, ensure_ascii=False))
|
| 207 |
+
print("\n".join(kw))
|
| 208 |
+
for n in numbers:
|
| 209 |
+
print(n["value"])
|
| 210 |
+
return 0
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
if __name__ == "__main__":
|
| 214 |
+
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_paired_validation.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|