junidude14 commited on
Commit
34f59d9
·
verified ·
1 Parent(s): 901d892

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/aggregate_rankcal.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Line up the 2026-10-01 arms with their existing counterparts (CPU only; reads scores, writes one md + json).
3
+
4
+ Rank sweep (alpha = r): n = 5 / 20 / all x r = 4 (new) / 16 (lora_n5, lora_n20, real_lora) / 64 (new)
5
+ Equal-budget calibration: n = 5 / 10 / 20 / 40 / all x zs__cal_n<n> (new; all = zs__cal) vs lora_n<n> (all = real_lora)
6
+ Per arm: fold mean ± SD (scores/<ds>/fold<k> or scores/<ds>/<exp>/fold<k>), pooled values (scores/<ds>/pooled_deg, else
7
+ pooled, or scores/<ds>/<exp>/pooled), with a contrast the pooled mean_cp10k logFC r / partial r over T, B, Monocyte, NK
8
+ and the top-50 DEG sum, the training runs' selected step and inner-val loss (RUN.json, where present on this host),
9
+ and a paired Wilcoxon over pooled per-donor composition L1 against the comparator.
10
+ Writes scores/<ds>/rankcal_20261001.md and .json. usage: aggregate_rankcal.py DATASET
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ from scipy.stats import wilcoxon
21
+
22
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
23
+ RANK, CAL = "lora_rank_20261001", "cal_budget_20261001"
24
+ TYPES = ["T cell", "B cell", "Monocyte", "NK cell"]
25
+
26
+
27
+ def rank_arm(r: int, n: str) -> str:
28
+ if r == 16:
29
+ return "real_lora__raw" if n == "all" else f"lora_n{n}__raw"
30
+ return f"lora_r{r}__raw" if n == "all" else f"lora_r{r}_n{n}__raw"
31
+
32
+
33
+ def main(ds: str) -> int:
34
+ S = TASK / "scores" / ds
35
+ old_pooled = S / "pooled_deg" if (S / "pooled_deg/summary.json").exists() else S / "pooled"
36
+ src = {} # arm -> (fold dirs, pooled dir)
37
+ for r in (4, 16, 64):
38
+ for n in ("5", "20", "all"):
39
+ a = rank_arm(r, n)
40
+ src[a] = ([S / f"fold{k}" for k in range(5)], old_pooled) if r == 16 else \
41
+ ([S / RANK / f"fold{k}" for k in range(5)], S / RANK / "pooled")
42
+ for n in ("5", "10", "20", "40"):
43
+ src[f"lora_n{n}__raw"] = ([S / f"fold{k}" for k in range(5)], old_pooled)
44
+ src[f"zs__cal_n{n}"] = ([S / CAL / f"fold{k}" for k in range(5)], S / CAL / "pooled")
45
+ src["zs__cal"] = ([S / f"fold{k}" for k in range(5)], old_pooled)
46
+ cache: dict[Path, tuple] = {}
47
+
48
+ def load(d: Path):
49
+ if d not in cache:
50
+ if not (d / "summary.json").exists():
51
+ cache[d] = None
52
+ else:
53
+ s = json.loads((d / "summary.json").read_text())
54
+ pdn = pd.read_csv(d / "per_donor.csv")
55
+ c = pd.read_csv(d / "contrast.csv") if (d / "contrast.csv").exists() else None
56
+ cache[d] = (s, pdn, c)
57
+ return cache[d]
58
+
59
+ stats = {}
60
+ for arm, (fdirs, pdir) in src.items():
61
+ rec = {"fold": {}, "pooled": None}
62
+ rows = [load(d)[0]["headline"][arm] for d in fdirs if load(d) and arm in load(d)[0]["headline"]]
63
+ if rows:
64
+ df = pd.DataFrame(rows)
65
+ for m in ("comp_l1", "precision", "coverage", "pb_r_median"):
66
+ rec["fold"][m] = (float(df[m].mean()), float(df[m].std(ddof=1)) if len(df) > 1 else float("nan"), len(df))
67
+ p = load(pdir)
68
+ if p and arm in p[0]["headline"]:
69
+ h = p[0]["headline"][arm]
70
+ rec["pooled"] = {m: h.get(m) for m in ("comp_l1", "precision", "coverage", "pb_r_median", "deg_top50_sum")}
71
+ if p[2] is not None:
72
+ c = p[2][(p[2]["arm"] == arm) & (p[2]["statistic"] == "mean_cp10k") & p[2]["celltype"].isin(TYPES)]
73
+ rec["pooled"]["logfc_r"] = float(c["r_generated"].mean())
74
+ rec["pooled"]["partial_r"] = float(c["partial_r_generated_given_broadcast"].mean())
75
+ rec["per_donor_l1"] = p[1][p[1]["arm"] == arm].set_index("donor")["comp_l1"]
76
+ run = arm.removesuffix("__raw")
77
+ rj = [TASK / "runs" / ds / f"fold{k}" / run / "RUN.json" for k in range(5)]
78
+ rj = [json.loads(x.read_text()) for x in rj if x.exists()]
79
+ if rj:
80
+ rec["train"] = {"selected_steps": [x["selected_step"] for x in rj],
81
+ "inner_val": float(np.mean([x["selected_inner_val_loss"] for x in rj])),
82
+ "pretrained_inner_val": float(np.mean([x["pretrained_inner_val_loss"] for x in rj])),
83
+ "n_trainable": rj[0]["trainable"].get("n_trainable"), "n_runs": len(rj)}
84
+ stats[arm] = rec
85
+
86
+ def wil(a: str, b: str) -> str:
87
+ x, y = stats[a].get("per_donor_l1"), stats[b].get("per_donor_l1")
88
+ if x is None or y is None:
89
+ return "—"
90
+ j = x.to_frame("a").join(y.to_frame("b"), how="inner")
91
+ if len(j) < 5:
92
+ return "—"
93
+ d = j["a"] - j["b"]
94
+ return f"{d.mean():+.3f} ({(d < 0).mean():.0%} better, p {wilcoxon(j['a'], j['b']).pvalue:.2g})"
95
+
96
+ def cells(arm: str) -> list[str]:
97
+ s = stats[arm]
98
+ f, p = s["fold"], s["pooled"]
99
+ out = [f"{f['comp_l1'][0]:.3f} ± {f['comp_l1'][1]:.3f} ({f['comp_l1'][2]})" if f else "pending",
100
+ f"{f['coverage'][0]:.3f}" if f else "", f"{p['comp_l1']:.3f}" if p else "pending",
101
+ f"{p['precision']:.3f} / {p['coverage']:.3f}" if p else ""]
102
+ if p and "logfc_r" in p:
103
+ out += [f"{p['logfc_r']:.2f}", f"{p['partial_r']:.2f}", f"{p['deg_top50_sum']}" if p.get("deg_top50_sum") is not None else "—"]
104
+ elif p is None and any(stats[a]["pooled"] and "logfc_r" in stats[a]["pooled"] for a in stats):
105
+ out += ["", "", ""]
106
+ t = s.get("train")
107
+ out.append(f"{min(t['selected_steps'])}–{max(t['selected_steps'])}; {t['inner_val']:.5f}" if t else "")
108
+ return out
109
+
110
+ contrast = any(stats[a]["pooled"] and "logfc_r" in stats[a]["pooled"] for a in stats)
111
+ head = ["comp L1 fold mean ± SD (folds)", "coverage (fold mean)", "pooled comp L1", "pooled precision / coverage"]
112
+ head += ["pooled logFC r (T/B/Mono/NK)", "partial r", "top-50 DEG"] if contrast else []
113
+ head += ["selected step; inner-val loss", "pooled per-donor L1 vs comparator (Δ, better in, Wilcoxon p)"]
114
+ L = [f"# {ds}: LoRA rank sweep and equal-budget calibration (2026-10-01)", "",
115
+ f"Existing arms: scores/{ds}/fold<k>, {old_pooled.relative_to(TASK)}; new: scores/{ds}/{RANK}, scores/{ds}/{CAL}.", "",
116
+ "## LoRA rank (alpha = r; comparator = r 16 at the same n)", "",
117
+ "| n | r | " + " | ".join(head) + " |", "|" + "---|" * (len(head) + 2)]
118
+ for n in ("5", "20", "all"):
119
+ for r in (4, 16, 64):
120
+ a = rank_arm(r, n)
121
+ L.append(f"| {n} | {r} | " + " | ".join(cells(a)) + f" | {wil(a, rank_arm(16, n)) if r != 16 else '(comparator)'} |")
122
+ L += ["", "## Zero-shot paired calibration at the LoRA pair budget (comparator = zs__cal_n<n>)", "",
123
+ "| n | arm | " + " | ".join(head) + " |", "|" + "---|" * (len(head) + 2)]
124
+ for n in ("5", "10", "20", "40", "all"):
125
+ zs, lo = ("zs__cal", "real_lora__raw") if n == "all" else (f"zs__cal_n{n}", f"lora_n{n}__raw")
126
+ L.append(f"| {n} | {zs} | " + " | ".join(cells(zs)) + " | (comparator) |")
127
+ L.append(f"| {n} | {lo} | " + " | ".join(cells(lo)) + f" | {wil(lo, zs)} |")
128
+ L += ["", "Fold scores use each fold's test donors as reference; pooled scores use all donors (cross-fitted). "
129
+ "n = training pairs; every run also saw the fold's inner-validation pairs, which zs__cal_n<n> uses for alpha."]
130
+ (S / "rankcal_20261001.md").write_text("\n".join(L) + "\n")
131
+ js = {a: {k: v for k, v in s.items() if k != "per_donor_l1"} for a, s in stats.items()}
132
+ (S / "rankcal_20261001.json").write_text(json.dumps(js, indent=1, default=float))
133
+ print("\n".join(L))
134
+ return 0
135
+
136
+
137
+ if __name__ == "__main__":
138
+ sys.exit(main(sys.argv[1]))
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_archive_request.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Archive-maintenance request for the paired fine-tuning benchmark (PBISC-Diffusion paper, pbisc-diffusion).
3
+
4
+ Follows paper-release-20260928/maintenance/POLICY.md: every payload is listed explicitly (host, exact path, kind,
5
+ state); generated arrays are not payloads but inference locations with their receipts; work that is still running
6
+ (the scSemiProfiler baseline) is registered as running/planned locations only.
7
+
8
+ Payloads (completed): code, documents, figures and their source CSVs, score tables, paired-data manifests and
9
+ small data (features, pairs, folds, splits, cell metadata), the condition NPZs every sampler read, run receipts
10
+ (RUN.json / history.json, which carry every fine-tuned checkpoint's sha256), queues, and the recommended-protocol
11
+ LoRA checkpoints (all-training-donor LoRA per fold, and the 5-pair LoRA per draw) on both hosts.
12
+ Not uploaded (location/provenance only): other fine-tuned checkpoints (sha256 in their RUN.json), the per-cell
13
+ count arrays cells_panel6k.npz / cells_full.npz (sha256 in BUILD.json / MANIFEST.json; rebuilt from the datalake
14
+ processing outputs), generated NPZs.
15
+ usage: build_archive_request.py OUT.json
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import glob
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
27
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
28
+
29
+
30
+ def files(patterns, root=T):
31
+ out = []
32
+ for p in patterns:
33
+ for f in sorted(glob.glob(str(root / p), recursive=True)):
34
+ q = Path(f)
35
+ if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and not q.name.endswith((".bak", ".pyc")) \
36
+ and ".bak_" not in q.name:
37
+ out.append(str(q))
38
+ return sorted(set(out))
39
+
40
+
41
+ def remote_files(patterns):
42
+ cmd = "cd %s && for p in %s; do ls -1d $p 2>/dev/null; done; true" % (T, " ".join(patterns))
43
+ res = subprocess.run(["ssh", "-n", "spark-0110", cmd], capture_output=True, text=True, check=True)
44
+ return sorted({str(T / l.strip()) for l in res.stdout.splitlines() if l.strip()})
45
+
46
+
47
+ def remote_json(path):
48
+ res = subprocess.run(["ssh", "-n", "spark-0110", f"cat '{path}'"], capture_output=True, text=True)
49
+ return json.loads(res.stdout) if res.returncode == 0 and res.stdout.strip() else None
50
+
51
+
52
+ def main(out: str) -> int:
53
+ assets = []
54
+
55
+ def add(paths, kind, host="server_1", state="completed"):
56
+ for p in paths:
57
+ assets.append({"host": host, "source": p, "kind": kind, "state": state})
58
+
59
+ add(files(["tools/*.py", "tools/*.sh", "tests/*.py", "figures/make_figures.py",
60
+ "scsemi/tools/*.py", "scsemi/tools/*.sh", "scsemi/tests/*.py"]), "code")
61
+ add(files(["README.md", "FEASIBILITY.md", "figures/FIGURES.md", "scsemi/README.md",
62
+ "data/*/QC_REPORT.md"]), "document")
63
+ add(files(["figures/*.png", "figures/*.pdf"]), "figure")
64
+ add(files(["figures/source_data/**/*.csv"]), "table")
65
+ add(files(["scores/*/*/summary.json", "scores/*/*/per_donor.csv", "scores/*/*/contrast.csv", "scores/*/*/README.md",
66
+ "scores/*/fewshot_n5/*/summary.json", "scores/*/fewshot_n5/*/per_donor.csv",
67
+ "scores/*/fewshot_n5/*/contrast.csv", "scores/*/fewshot_n5/*/README.md",
68
+ "scores/*/AGGREGATE.md", "scores/*/aggregate.json",
69
+ "scores/*/fewshot_n5/AGGREGATE.md", "scores/*/fewshot_n5/aggregate.json"]), "table")
70
+ # 2026-10-01: Giroux sex-linked-gene rescoring (scores_nosex, chrY-only sensitivity scores_nochrY) and its gene list
71
+ add(files([f"{d}/{p}" for d in ("scores_nosex", "scores_nochrY")
72
+ for p in ("README.md", "**/summary.json", "**/per_donor.csv", "**/contrast.csv", "**/README.md")]), "table")
73
+ add(files(["data/sex_linked_genes/*.csv", "data/sex_linked_genes/*.md", # BUILD.json is caught by data/*/BUILD.json
74
+ "data/sex_linked_genes/sources/*.txt", "data/sex_linked_genes/sources/README*"]), "metadata")
75
+ # equal-pair-budget calibration (alpha fitted on each lora_n<n> run's own pairs)
76
+ add(files(["data/*/fold*/alpha_n*.npy"]), "data")
77
+ add(files(["data/*/CAL_BUDGET.json"]), "metadata")
78
+ add(files(["data/*/features.npz", "data/*/cells_obs.parquet", "data/*/fold*/alpha.npy",
79
+ "data/*/fewshot_n5/draw*/alpha.npy"]), "data")
80
+ add(files(["data/*/pairs.csv", "data/*/folds.csv", "data/*/samples.csv", "data/*/identity_*.csv",
81
+ "data/*/pairs_sensitivity_offday.csv", "data/*/MANIFEST.json", "data/*/PREPARE.json",
82
+ "data/*/BUILD.json", "data/*/cells_full.BUILD.json", "data/*/fewshot_n5/DRAWS.json",
83
+ "data/*/fewshot_n5/draw*/*.txt"]), "metadata")
84
+ add(files(["data/*/conditions_*.npz", "data/*/fold*/*.npz", "data/*/fewshot_n5/*.npz",
85
+ "data/*/fewshot_n5/draw*/*.npz"]), "condition")
86
+ add(files(["runs/**/RUN.json", "runs/**/history.json"]), "log")
87
+ # server_2 ran its own copies of the scSemiProfiler queues (some exist only there): keep them as the as-run record
88
+ subprocess.run(["rsync", "-a", f"spark-0110:{T}/scsemi/queues/", f"{T}/scsemi/queues/as_run_server2/",
89
+ "--include=server2_*.txt", "--exclude=*"], check=True)
90
+ add(files(["queues/*.txt", "scsemi/queues/*.txt", "scsemi/queues/as_run_server2/*.txt",
91
+ "scsemi/vendor/compatibility.patch",
92
+ "scsemi/vendor/source_manifest.json"]), "config")
93
+ # recommended protocol weights (LoRA merged into the base weights): server_1 datasets here, Imperial on server_2
94
+ add(files(["runs/*/fold*/real_lora/checkpoint_ft.pt", "runs/*/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint")
95
+ add(remote_files(["runs/imperial_eskd/fold*/real_lora/checkpoint_ft.pt",
96
+ "runs/imperial_eskd/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint", host="server_2")
97
+ add(remote_files(["runs/imperial_eskd/*/*/RUN.json", "runs/imperial_eskd/*/*/history.json",
98
+ "runs/imperial_eskd/fewshot_n5/*/*/RUN.json", "runs/imperial_eskd/fewshot_n5/*/*/history.json"]),
99
+ "log", host="server_2")
100
+
101
+ # ---- inference locations (not payloads) ------------------------------------------------------------------------
102
+ locs = []
103
+
104
+ def receipt_fields(rec: dict | None) -> dict:
105
+ if not rec:
106
+ return {}
107
+ keep = {}
108
+ for k in ("output_sha256", "checkpoint", "checkpoint_sha256", "input_condition_path", "input_condition_sha256",
109
+ "condition_npz", "condition_sha256", "seed", "steps", "generated_counts_rows"):
110
+ if k in rec and not isinstance(rec[k], (dict, list)):
111
+ keep[k] = rec[k]
112
+ if "output_sha256" in keep:
113
+ keep["sha256"] = keep["output_sha256"]
114
+ return keep
115
+
116
+ def loc(host, npz, experiment, cohort, rec=None, state="completed"):
117
+ rpath = npz[:-4] + ".log"
118
+ item = {"host": host, "path": npz, "state": state, "experiment": experiment, "cohort": cohort,
119
+ "artifact_role": "inference_output"}
120
+ if state in ("completed", "final"):
121
+ item["receipt"] = rpath
122
+ item.update(receipt_fields(rec))
123
+ locs.append(item)
124
+
125
+ for ds in DATASETS:
126
+ # present on server_1
127
+ for npz in files([f"generated/{ds}/**/*.npz"]):
128
+ rel = Path(npz).relative_to(T / "generated" / ds)
129
+ rp = Path(npz[:-4] + ".log")
130
+ rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
131
+ if rec is None:
132
+ continue
133
+ loc("server_1", npz, f"paired_finetune_{rel.parts[0]}", ds, rec)
134
+ # moved to server_2 (sha-verified move; .moved marker kept on server_1)
135
+ for mk in files([f"generated/{ds}/**/*.moved"]):
136
+ npz = mk[:-6] + ".npz"
137
+ rp = Path(mk[:-6] + ".log")
138
+ rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
139
+ rel = Path(npz).relative_to(T / "generated" / ds)
140
+ item_state = "completed" if rec else "presence_only"
141
+ loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", ds, rec, state=item_state)
142
+ locs[-1]["move_marker_server_1"] = mk
143
+ # Imperial outputs live on server_2
144
+ for npz in remote_files(["generated/imperial_eskd/*/*.npz", "generated/imperial_eskd/fewshot_n5/*/*.npz",
145
+ "generated/imperial_eskd/pooled/*.npz"]):
146
+ rec = remote_json(npz[:-4] + ".log")
147
+ if rec is None:
148
+ continue
149
+ rel = Path(npz).relative_to(T / "generated" / "imperial_eskd")
150
+ loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", "imperial_eskd", rec)
151
+ # scSemiProfiler draws of the other datasets that ran on server_2 (queues server2_*.txt)
152
+ for npz in remote_files([f"generated/{ds}/fewshot_n5/draw*/scsemi5__raw.npz" for ds in DATASETS
153
+ if ds != "imperial_eskd"]):
154
+ rec = remote_json(npz[:-4] + ".log")
155
+ if rec is None:
156
+ continue
157
+ rel = Path(npz).relative_to(T / "generated")
158
+ loc("server_2", npz, "paired_finetune_fewshot_n5", rel.parts[0], rec)
159
+ # scSemiProfiler baseline still running: register in-progress / planned draws by their future output path
160
+ done = {l["path"] for l in locs}
161
+ run_queues = [T / "scsemi" / "queues" / "server1_fewshot_d0first.txt"] + \
162
+ sorted((T / "scsemi" / "queues" / "as_run_server2").glob("server2_*.txt"))
163
+ for qf in run_queues:
164
+ host = "server_1" if qf.name.startswith("server1_") else "server_2"
165
+ for line in qf.read_text().splitlines():
166
+ if not line.startswith("fewshot|"):
167
+ continue
168
+ _, ds, j = line.split("|")[:3]
169
+ npz = str(T / "generated" / ds / "fewshot_n5" / f"draw{j}" / "scsemi5__raw.npz")
170
+ if npz in done:
171
+ continue
172
+ state = "planned"
173
+ locs.append({"host": host, "path": npz, "state": state, "experiment": "paired_finetune_fewshot_n5_scsemiprofiler",
174
+ "cohort": ds, "artifact_role": "inference_output",
175
+ "note": "scSemiProfiler 5-pair baseline queued or running on this host at request time"})
176
+ done.add(npz)
177
+ req = {
178
+ "project_id": "pbisc-diffusion",
179
+ "summary": (
180
+ "Within-dataset paired fine-tuning benchmark of the final 6k 1x E16 model (plans/paired_finetune_intradataset_20260927): "
181
+ "LoRA (recommended protocol), full and condition-encoder fine-tuning, sc-only control, LoRA learning curve, "
182
+ "K-augmentation null, 5-pair deployment scenario, on ImMicro, Ye 2026 sepsis, Imperial ESKD COVID, Giroux 2022 and "
183
+ "Ji 2025 (whole-blood bulk); scores (scANVI composition, precision/coverage, contrast logFC r, top-50 DEG), figures, "
184
+ "paired-data manifests, conditions, run receipts and the recommended-protocol LoRA checkpoints. The scSemiProfiler "
185
+ "5-pair baseline: every finished draw is included as score tables and a completed location; draws not yet "
186
+ "finished at request time (none on 2026-09-30: 25/25 done) are planned locations. Not uploaded: per-cell count "
187
+ "arrays and non-recommended fine-tuned checkpoints (sha256 recorded in BUILD/MANIFEST and RUN.json)."),
188
+ "assets": assets,
189
+ "inference_locations": locs,
190
+ }
191
+ Path(out).write_text(json.dumps(req, indent=1))
192
+ kinds = {}
193
+ for a in assets:
194
+ kinds[(a["host"], a["kind"])] = kinds.get((a["host"], a["kind"]), 0) + 1
195
+ print(json.dumps({"assets": len(assets), "by_host_kind": {f"{h}/{k}": v for (h, k), v in sorted(kinds.items())},
196
+ "locations": len(locs), "location_states": {s: sum(l["state"] == s for l in locs) for s in {l["state"] for l in locs}}},
197
+ indent=1))
198
+ return 0
199
+
200
+
201
+ if __name__ == "__main__":
202
+ sys.exit(main(sys.argv[1]))
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_sex_gene_list.py ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Sex-chromosome-linked genes to drop from the disease-signal scores (user decision 2026-10-01, Giroux cohort).
3
+
4
+ CPU only, no network. Every gene comes from a source file; nothing is typed in by hand.
5
+
6
+ Definition (on the 20,097-gene protein-coding axis of data/<cohort>/features.npz):
7
+ 1. chrY non-PAR: every axis gene that GENCODE v50 places on chrY and that does not lie entirely inside a chrY
8
+ pseudo-autosomal region (PAR1 / PAR2 of GRCh38, read from the NCBI GRCh38.p14 assembly-regions report).
9
+ 2. chrX XCI escape: every X gene of Tukiainen et al. 2017 (Nature 550:244, Supplementary Table 13) whose
10
+ "Reported XCI status" is Escape or Variable (variable escape), plus the genes the paper flags as a possible new
11
+ escape call; mapped to the axis by Ensembl gene id (version stripped), else by a unique chrX symbol in GENCODE
12
+ v50. Genes lying entirely inside a chrX PAR are dropped (they are expressed from X and Y alike).
13
+ PAR = the gene's GENCODE v50 interval lies entirely inside a PAR interval of its chromosome. GENCODE v50 gives the
14
+ chrY PAR copies their own ids (ENSG00000292xxx) and no "PAR" tag, so coordinates are the only rule; Tukiainen's
15
+ own Region column is reported next to it as a cross-check.
16
+
17
+ Outputs (data/sex_linked_genes/):
18
+ sex_linked_genes_exclude.csv gene_id, symbol, chromosome, reason, start, end, tukiainen_* columns (full list)
19
+ chrY_nonPAR_genes.csv the chrY part only (chrY-only sensitivity run)
20
+ tukiainen2017_mapping.csv every Tukiainen escape / variable / new-call row and what happened to it
21
+ par_genes_on_axis.csv axis genes inside a PAR (kept in the scores)
22
+ BUILD.json input sha256s and counts
23
+
24
+ usage: python3 tools/build_sex_gene_list.py
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import gzip
29
+ import hashlib
30
+ import json
31
+ import re
32
+ from datetime import datetime, timezone
33
+ from pathlib import Path
34
+
35
+ import numpy as np
36
+ import pandas as pd
37
+
38
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
39
+ OUT = T / "data" / "sex_linked_genes"
40
+ SRC = OUT / "sources"
41
+ GTF = Path("/home/sj_server_1/gblee/ablations_data_repro_20260802/fixed_assets/gencode.v50.annotation.gtf.gz")
42
+ TUK = SRC / "Tukiainen2017_Suppl.Table.13.xlsx"
43
+ REGIONS = SRC / "GCF_000001405.40_GRCh38.p14_assembly_regions.txt"
44
+ COHORTS = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
45
+ ESCAPE_STATUS = ("Escape", "Variable") # Tukiainen "Reported XCI status" values counted as escape
46
+ NEW_CALL_COL = "Possible new call for escape (support from several analyses)"
47
+
48
+
49
+ def sha(p: Path) -> str:
50
+ h = hashlib.sha256()
51
+ with open(p, "rb") as fh:
52
+ for b in iter(lambda: fh.read(1 << 20), b""):
53
+ h.update(b)
54
+ return h.hexdigest()
55
+
56
+
57
+ def axis() -> np.ndarray:
58
+ ids = None
59
+ for ds in COHORTS:
60
+ g = np.load(T / "data" / ds / "features.npz", allow_pickle=False)["gene_ids"].astype(str)
61
+ if ids is None:
62
+ ids = g
63
+ elif not np.array_equal(ids, g):
64
+ raise SystemExit(f"{ds}: gene axis differs from {COHORTS[0]}")
65
+ return ids
66
+
67
+
68
+ def gtf_genes() -> pd.DataFrame:
69
+ rows = []
70
+ with gzip.open(GTF, "rt") as fh:
71
+ for line in fh:
72
+ if line.startswith("#"):
73
+ continue
74
+ p = line.split("\t", 9)
75
+ if p[2] != "gene":
76
+ continue
77
+ a = p[8]
78
+ rows.append((re.search(r'gene_id "([^"]+)"', a).group(1), re.search(r'gene_name "([^"]+)"', a).group(1),
79
+ re.search(r'gene_type "([^"]+)"', a).group(1), p[0], int(p[3]), int(p[4])))
80
+ g = pd.DataFrame(rows, columns=["gene_id_versioned", "symbol", "gene_type", "chromosome", "start", "end"])
81
+ g["gene_id"] = g.gene_id_versioned.str.replace(r"\.\d+(_PAR_Y)?$", "", regex=True)
82
+ if g.gene_id.duplicated().any():
83
+ raise SystemExit(f"duplicate unversioned gene ids in {GTF}")
84
+ return g
85
+
86
+
87
+ def par_regions() -> pd.DataFrame:
88
+ """PAR rows of the NCBI region report: region name, chromosome, start, stop (1-based, inclusive)."""
89
+ rows = []
90
+ for line in REGIONS.read_text().splitlines():
91
+ if line.startswith("#") or not line.strip():
92
+ continue
93
+ f = line.split("\t")
94
+ if f[4] == "PAR":
95
+ rows.append({"region": f[0], "chromosome": f"chr{f[1]}", "start": int(f[2]), "end": int(f[3])})
96
+ par = pd.DataFrame(rows)
97
+ if sorted(par.chromosome.value_counts().items()) != [("chrX", 2), ("chrY", 2)]:
98
+ raise SystemExit(f"expected PAR1 and PAR2 on chrX and chrY in {REGIONS}, got {rows}")
99
+ return par
100
+
101
+
102
+ def inside_par(chrom: str, start: int, end: int, par: pd.DataFrame) -> str:
103
+ """'PAR#1' / 'PAR#2' when [start, end] lies entirely inside one; 'boundary' when it only overlaps one; ''."""
104
+ for r in par[par.chromosome == chrom].itertuples():
105
+ if start >= r.start and end <= r.end:
106
+ return r.region
107
+ if start <= r.end and end >= r.start:
108
+ return "boundary"
109
+ return ""
110
+
111
+
112
+ def tukiainen() -> pd.DataFrame:
113
+ t = pd.read_excel(TUK, header=0)
114
+ t = t[t["Gene ID"].astype(str).str.startswith("ENSG")].copy() # drops the footnote row
115
+ if set(t["Chr"].astype(str)) != {"X"}:
116
+ raise SystemExit("Tukiainen table: non-X rows")
117
+ t["gene_id"] = t["Gene ID"].astype(str).str.replace(r"\.\d+$", "", regex=True)
118
+ t["new_call"] = t[NEW_CALL_COL].astype(str).str.strip().str.lower().eq("x")
119
+ return t.rename(columns={"Gene ID": "tuk_id", "Gene name": "tuk_symbol", "Reported XCI status": "status"})
120
+
121
+
122
+ def main() -> int:
123
+ ids = axis()
124
+ g = gtf_genes().set_index("gene_id")
125
+ miss = [x for x in ids if x not in g.index]
126
+ if miss:
127
+ raise SystemExit(f"{len(miss)} axis genes not in GENCODE v50 (e.g. {miss[:3]})")
128
+ ax = g.loc[ids].reset_index()
129
+ par = par_regions()
130
+ ax["par"] = [inside_par(c, s, e, par) if c in ("chrX", "chrY") else ""
131
+ for c, s, e in zip(ax.chromosome, ax.start, ax.end)]
132
+
133
+ # 1. chrY non-PAR
134
+ y = ax[ax.chromosome == "chrY"]
135
+ if (y.par == "boundary").any():
136
+ raise SystemExit(f"chrY genes crossing a PAR boundary: {y[y.par == 'boundary'].symbol.tolist()}")
137
+ ynp = y[y.par == ""].assign(reason="chrY non-PAR")
138
+
139
+ # 2. chrX XCI escape (Tukiainen 2017)
140
+ t = tukiainen()
141
+ sel = t[t.status.isin(ESCAPE_STATUS) | t.new_call].copy()
142
+ pos = {x: i for i, x in enumerate(ax.gene_id)}
143
+ xsym = ax[ax.chromosome == "chrX"].symbol.value_counts()
144
+ xsym_row = {s: i for i, s in zip(ax.index, ax.symbol) if ax.at[i, "chromosome"] == "chrX" and xsym[s] == 1}
145
+ maps = []
146
+ for r in sel.itertuples():
147
+ if r.gene_id in pos:
148
+ i, how = pos[r.gene_id], "ensembl id"
149
+ elif r.tuk_symbol in xsym_row:
150
+ i, how = xsym_row[r.tuk_symbol], "unique chrX symbol (GENCODE v50)"
151
+ else:
152
+ maps.append({"tukiainen_id": r.tuk_id, "tukiainen_symbol": r.tuk_symbol, "tukiainen_region": r.Region,
153
+ "tukiainen_status": r.status, "tukiainen_new_call": bool(r.new_call), "mapped_by": "",
154
+ "gene_id": "", "symbol": "", "chromosome": "", "par": "", "outcome": "not on the axis"})
155
+ continue
156
+ a = ax.loc[i]
157
+ if a.chromosome != "chrX":
158
+ raise SystemExit(f"Tukiainen {r.tuk_symbol} maps to {a.gene_id} on {a.chromosome}")
159
+ status = r.status if r.status in ESCAPE_STATUS else "new call"
160
+ outcome = "PAR: kept" if a.par.startswith("PAR") else "excluded"
161
+ maps.append({"tukiainen_id": r.tuk_id, "tukiainen_symbol": r.tuk_symbol, "tukiainen_region": r.Region,
162
+ "tukiainen_status": r.status, "tukiainen_new_call": bool(r.new_call), "mapped_by": how,
163
+ "gene_id": a.gene_id, "symbol": a.symbol, "chromosome": a.chromosome, "par": a.par,
164
+ "outcome": outcome, "reason": f"chrX XCI escape (Tukiainen 2017: {status})"})
165
+ mp = pd.DataFrame(maps)
166
+ disagree = mp[(mp.outcome != "not on the axis") & ((mp.par.str.startswith("PAR")) != (mp.tukiainen_region == "PAR"))]
167
+ xe = mp[mp.outcome == "excluded"]
168
+ if xe.gene_id.duplicated().any():
169
+ raise SystemExit(f"two Tukiainen rows map to one axis gene: {xe[xe.gene_id.duplicated()].gene_id.tolist()}")
170
+ xe = xe.merge(ax[["gene_id", "start", "end"]], on="gene_id")
171
+
172
+ cols = ["gene_id", "symbol", "chromosome", "reason", "start", "end"]
173
+ full = pd.concat([ynp[cols].assign(tukiainen_status="", tukiainen_region="", tukiainen_mapped_by=""),
174
+ xe[cols + ["tukiainen_status", "tukiainen_region", "mapped_by"]]
175
+ .rename(columns={"mapped_by": "tukiainen_mapped_by"})], ignore_index=True)
176
+ full = full.sort_values(["chromosome", "start"], kind="stable").reset_index(drop=True)
177
+ if full.gene_id.duplicated().any():
178
+ raise SystemExit("duplicate gene in the exclusion list")
179
+ OUT.mkdir(parents=True, exist_ok=True)
180
+ full.to_csv(OUT / "sex_linked_genes_exclude.csv", index=False)
181
+ full[full.reason == "chrY non-PAR"].to_csv(OUT / "chrY_nonPAR_genes.csv", index=False)
182
+ mp.to_csv(OUT / "tukiainen2017_mapping.csv", index=False)
183
+ pg = ax[ax.par.str.startswith("PAR") | (ax.par == "boundary")][["gene_id", "symbol", "chromosome", "start", "end", "par"]]
184
+ pg.to_csv(OUT / "par_genes_on_axis.csv", index=False)
185
+ build = {"written_utc": datetime.now(timezone.utc).isoformat(), "script": str(Path(__file__).resolve()),
186
+ "script_sha256": sha(Path(__file__).resolve()),
187
+ "inputs": {str(p): sha(p) for p in (GTF, TUK, REGIONS)},
188
+ "axis": {"source": f"{T}/data/<cohort>/features.npz gene_ids (identical in {len(COHORTS)} cohorts)",
189
+ "n_genes": int(ids.size), "n_chrX": int((ax.chromosome == "chrX").sum()),
190
+ "n_chrY": int((ax.chromosome == "chrY").sum())},
191
+ "par_regions": par.to_dict(orient="records"),
192
+ "counts": {"chrY_on_axis": int(len(y)), "chrY_PAR_kept": int((y.par != "").sum()),
193
+ "chrY_nonPAR_excluded": int(len(ynp)),
194
+ "tukiainen_rows_selected": int(len(sel)),
195
+ "tukiainen_selected_by_status": sel.status.value_counts().to_dict(),
196
+ "tukiainen_new_calls": int(sel.new_call.sum()),
197
+ "tukiainen_not_on_axis": int((mp.outcome == "not on the axis").sum()),
198
+ "tukiainen_PAR_kept": int((mp.outcome == "PAR: kept").sum()),
199
+ "chrX_escape_excluded": int(len(xe)),
200
+ "chrX_escape_by_reason": xe.reason.value_counts().to_dict(),
201
+ "mapped_by_symbol": int((xe.mapped_by != "ensembl id").sum()),
202
+ "par_status_disagrees_with_tukiainen_region": disagree[["symbol", "par", "tukiainen_region"]]
203
+ .to_dict(orient="records"),
204
+ "axis_genes_crossing_a_PAR_boundary": ax[ax.par == "boundary"].symbol.tolist(),
205
+ "total_excluded": int(len(full))}}
206
+ (OUT / "BUILD.json").write_text(json.dumps(build, indent=1) + "\n")
207
+ print(json.dumps(build["counts"], indent=1))
208
+ return 0
209
+
210
+
211
+ if __name__ == "__main__":
212
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/check_rankcal.py ADDED
@@ -0,0 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Dry-run check of the 2026-10-01 rank-sweep / equal-budget-calibration queues (CPU only; never imports torch).
3
+
4
+ For every queue line (run_queue.sh format):
5
+ train the reference r 16 run of the same dataset / fold / n (lora_n<n>, or real_lora for all pairs) is read; its
6
+ lr, warmup, batch, EMA, eval interval, patience, cap, seed, base checkpoint sha, condition NPZ (path + current
7
+ sha) and update scale alpha/r must equal what this line will use (ft_sdd.py defaults read with ast + the
8
+ line's flags); the line's --train-n / --subset-seed / --strata-regex must equal the reference's train_subset;
9
+ the training / inner-validation / test rows are recomputed from folds.csv with ft_sdd.py's selection code
10
+ and must equal the reference RUN.json lists. The run dir must not hold RUN.json / checkpoint_ft.pt yet.
11
+ sample checkpoint = base or a run trained earlier in the same queue; condition NPZ resolves with the sampler's keys
12
+ and the fold's test rows; seed / steps / weights equal the reference arm's generation receipt; for zs__cal_n<n>
13
+ the CAL_BUDGET.json fit rows equal lora_n<n>'s train + inner-val rows and exclude every test donor; the output
14
+ NPZ / receipt / .moved marker must not exist, and no arm name collides with an existing one.
15
+ Also: base checkpoint sha, input shas (for comparing hosts), disk need vs free space, runner/env paths.
16
+ --no-ref skips the reference comparisons (for server_2, whose runs/ holds no ImMicro/sepsis runs).
17
+ usage: check_rankcal.py QUEUE [QUEUE ...] [--no-ref] [--json OUT]
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import argparse
22
+ import ast
23
+ import hashlib
24
+ import json
25
+ import os
26
+ import re
27
+ import shutil
28
+ import socket
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import pandas as pd
34
+
35
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
36
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
37
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
38
+ TASK = M8 / "plans/paired_finetune_intradataset_20260927"
39
+ BASE_CKPT = M8 / "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
40
+ BASE_SHA = "8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633"
41
+ SAMPLER_KEYS = {"bulk_counts", "bulk_measurement_fraction", "output_availability_mask", "recipe_k", "cells_per_bulk",
42
+ "sample_ids", "gene_ids"}
43
+ CKPT_BYTES = 217_981_000 # merged FT checkpoint (existing runs: 217.98 MB)
44
+ GENES, CELLS = 6000, 1500 # generated NPZ: float32 [donors x 1500, 6000]
45
+ _sha_cache: dict[str, str] = {}
46
+
47
+
48
+ def sha(p: Path) -> str:
49
+ k = str(Path(p).resolve())
50
+ if k not in _sha_cache:
51
+ h = hashlib.sha256()
52
+ with open(p, "rb") as f:
53
+ for b in iter(lambda: f.read(1 << 24), b""):
54
+ h.update(b)
55
+ _sha_cache[k] = h.hexdigest()
56
+ return _sha_cache[k]
57
+
58
+
59
+ def ft_defaults() -> dict:
60
+ """argparse defaults of ft_sdd.py, read from its source (no torch import)."""
61
+ tree = ast.parse((TASK / "tools/ft_sdd.py").read_text())
62
+ out = {}
63
+ for node in ast.walk(tree):
64
+ if isinstance(node, ast.Call) and getattr(node.func, "attr", "") == "add_argument" and node.args:
65
+ name = ast.literal_eval(node.args[0])
66
+ kw = {k.arg: k.value for k in node.keywords}
67
+ if "default" in kw:
68
+ out[name.lstrip("-").replace("-", "_")] = ast.literal_eval(kw["default"])
69
+ return out
70
+
71
+
72
+ def parse_extra(tokens: list[str]) -> dict:
73
+ out, i = {}, 0
74
+ while i < len(tokens):
75
+ k = tokens[i]
76
+ if not k.startswith("--"):
77
+ raise ValueError(f"unexpected token {k!r}")
78
+ out[k[2:].replace("-", "_")] = tokens[i + 1]
79
+ i += 2
80
+ return out
81
+
82
+
83
+ def select_rows(folds: pd.DataFrame, fold: int, train_n: int, subset_seed: int, strata_regex: str):
84
+ """ft_sdd.py's row selection (fold mode, optional --train-n learning-curve subset), verbatim logic."""
85
+ inner_col = f"inner_val_f{fold}"
86
+ test_rows = folds.index[folds["fold"] == fold].to_numpy()
87
+ inner_rows = folds.index[folds[inner_col]].to_numpy()
88
+ train_rows = folds.index[(folds["fold"] != fold) & (folds["fold"] >= 0) & ~folds[inner_col]].to_numpy()
89
+ if train_n:
90
+ grp = folds.loc[train_rows, "group"].astype(str)
91
+ strata = (grp.str.contains(strata_regex, regex=True) if strata_regex
92
+ else pd.Series(True, index=grp.index)).to_numpy()
93
+ srng = np.random.default_rng(subset_seed)
94
+ labels = sorted(set(strata.tolist()))
95
+ perm = {s: train_rows[strata == s][srng.permutation(int((strata == s).sum()))] for s in labels}
96
+ n = min(int(train_n), len(train_rows))
97
+ sizes = {s: len(perm[s]) for s in labels}
98
+ alloc = {s: max(1, int(np.floor(n * sizes[s] / len(train_rows)))) for s in labels}
99
+ while sum(alloc.values()) < n:
100
+ s = max(labels, key=lambda s: n * sizes[s] / len(train_rows) - alloc[s])
101
+ alloc[s] += 1
102
+ while sum(alloc.values()) > n:
103
+ s = max((s for s in labels if alloc[s] > 1), key=lambda s: alloc[s])
104
+ alloc[s] -= 1
105
+ train_rows = np.sort(np.concatenate([perm[s][:alloc[s]] for s in labels]))
106
+ return train_rows, inner_rows, test_rows
107
+
108
+
109
+ def main(argv=None) -> int:
110
+ ap = argparse.ArgumentParser()
111
+ ap.add_argument("queues", nargs="+", type=Path)
112
+ ap.add_argument("--no-ref", action="store_true")
113
+ ap.add_argument("--json", type=Path, default=None)
114
+ a = ap.parse_args(argv)
115
+ errors, notes = [], []
116
+ err = errors.append
117
+ defaults = ft_defaults()
118
+ host = socket.gethostname().split(".")[0]
119
+ inputs: dict[str, str] = {}
120
+
121
+ def need(p: Path, what: str) -> bool:
122
+ if not Path(p).exists():
123
+ err(f"missing {what}: {p}")
124
+ return False
125
+ return True
126
+
127
+ if need(BASE_CKPT, "base checkpoint"):
128
+ inputs[str(BASE_CKPT)] = sha(BASE_CKPT)
129
+ if inputs[str(BASE_CKPT)] != BASE_SHA:
130
+ err(f"base checkpoint sha {inputs[str(BASE_CKPT)][:12]} != {BASE_SHA[:12]}")
131
+ trained, tags, outputs = set(), set(), set()
132
+ n_train = n_sample = 0
133
+ need_bytes = 0
134
+ per_queue = {}
135
+ folds_cache: dict[str, pd.DataFrame] = {}
136
+ for q in a.queues:
137
+ nq = {"train": 0, "sample": 0}
138
+ for ln, line in enumerate(q.read_text().splitlines(), 1):
139
+ if not line.strip() or line.startswith("#"):
140
+ continue
141
+ parts = line.split("|")
142
+ where = f"{q.name}:{ln}"
143
+ if parts[0] == "train":
144
+ n_train += 1; nq["train"] += 1
145
+ run, cond, fold, mode, lr = Path(parts[1]), Path(parts[2]), int(parts[3]), parts[4], parts[5]
146
+ extra = parse_extra(parts[6:])
147
+ ds = run.parent.parent.name
148
+ dsdir = TASK / "data" / ds
149
+ if mode != "lora":
150
+ err(f"{where}: mode {mode}")
151
+ rank, alpha = int(extra.get("lora_rank", defaults["lora_rank"])), float(extra.get("lora_alpha", defaults["lora_alpha"]))
152
+ if alpha / rank != 1.0:
153
+ err(f"{where}: alpha/r = {alpha / rank}")
154
+ unknown = set(extra) - {"lora_rank", "lora_alpha", "train_n", "subset_seed", "strata_regex"}
155
+ if unknown:
156
+ err(f"{where}: unexpected flags {sorted(unknown)} (would differ from the r 16 arms)")
157
+ if (run / "RUN.json").exists() or (run / "checkpoint_ft.pt").exists():
158
+ err(f"{where}: {run} already holds RUN.json/checkpoint_ft.pt (would be skipped / clash)")
159
+ if run.name in {"real_lora", "real_full", "real_condenc", "pseudo_full", "lora_multik", "lora_recipe"} \
160
+ or re.fullmatch(r"lora_n\d+", run.name):
161
+ err(f"{where}: run dir name {run.name} is an existing arm")
162
+ for p, w in ((cond, "condition"), (dsdir / "cells_panel6k.npz", "cells"), (dsdir / "folds.csv", "folds")):
163
+ if need(p, w):
164
+ inputs[str(p)] = sha(p)
165
+ trained.add(str(run / "checkpoint_ft.pt"))
166
+ need_bytes += CKPT_BYTES
167
+ if a.no_ref:
168
+ continue
169
+ n = int(extra.get("train_n", 0))
170
+ ref_dir = run.parent / (f"lora_n{n}" if n else "real_lora")
171
+ rj = ref_dir / "RUN.json"
172
+ if not need(rj, "reference RUN.json"):
173
+ continue
174
+ ref = json.loads(rj.read_text())
175
+ checks = {
176
+ "fold": (ref["fold"], fold), "mode": (ref["mode"], mode), "lr": (ref["lr"], float(lr)),
177
+ "warmup": (ref["warmup"], defaults["warmup"]), "batch_size": (ref["batch_size"], defaults["batch_size"]),
178
+ "ema_decay": (ref["ema_decay"], defaults["ema_decay"]), "max_steps": (ref["max_steps"], defaults["max_steps"]),
179
+ "eval_every": (ref["eval_every"], defaults["eval_every"]), "patience": (ref["patience"], defaults["patience"]),
180
+ "seed": (ref["seed"], defaults["seed"]), "source_checkpoint_sha256": (ref["source_checkpoint_sha256"], BASE_SHA),
181
+ "condition_npz": (ref["condition_npz"], str(cond)), "condition_npz_sha256": (ref["condition_npz_sha256"], inputs.get(str(cond))),
182
+ "scale alpha/r": (ref["trainable"]["lora_alpha"] / ref["trainable"]["lora_rank"], alpha / rank),
183
+ "fixed_steps": (ref.get("fixed_steps"), None), "train_donors_file": (ref.get("train_donors_file"), None),
184
+ }
185
+ ts = ref.get("train_subset") or {}
186
+ if n:
187
+ checks.update({"train_n": (ts.get("train_n"), n), "subset_seed": (ts.get("subset_seed"), int(extra["subset_seed"])),
188
+ "strata_regex": (ts.get("strata_regex"), extra.get("strata_regex", ""))})
189
+ elif ts:
190
+ err(f"{where}: reference {rj} is a subset run")
191
+ for k, (want, got) in checks.items():
192
+ if want != got:
193
+ err(f"{where}: {k}: reference {want!r} vs this line {got!r}")
194
+ if ds not in folds_cache:
195
+ folds_cache[ds] = pd.read_csv(dsdir / "folds.csv")
196
+ folds = folds_cache[ds]
197
+ tr, iv, te = select_rows(folds, fold, n, int(extra.get("subset_seed", 0)), extra.get("strata_regex", ""))
198
+ sid = folds["sample_id"].astype(str).to_numpy()
199
+ for name, mine, theirs in (("train_rows", sid[tr], ref["train_rows"]), ("inner_val_rows", sid[iv], ref["inner_val_rows"]),
200
+ ("test_rows", sid[te], ref["test_rows_never_loaded_for_training"])):
201
+ if list(mine) != list(theirs):
202
+ err(f"{where}: {name} differ from {rj} ({len(mine)} vs {len(theirs)})")
203
+ elif parts[0] == "sample":
204
+ n_sample += 1; nq["sample"] += 1
205
+ tag, ckpt, cond, seed, out = parts[1], parts[2], Path(parts[3]), int(parts[4]), Path(parts[5])
206
+ if tag in tags:
207
+ err(f"{where}: duplicate tag {tag}")
208
+ tags.add(tag)
209
+ if str(out) in outputs:
210
+ err(f"{where}: duplicate output {out}")
211
+ outputs.add(str(out))
212
+ if ckpt != "base" and ckpt not in trained:
213
+ err(f"{where}: checkpoint {ckpt} is not trained earlier in the queues")
214
+ for suffix in (".npz", ".log", ".moved", ".err"):
215
+ if out.with_suffix(suffix).exists():
216
+ err(f"{where}: {out.with_suffix(suffix)} already exists")
217
+ arm = out.stem
218
+ fold = int(out.parent.name.removeprefix("fold"))
219
+ ds = out.parent.parent.name
220
+ if not need(cond, "condition"):
221
+ continue
222
+ inputs[str(cond)] = sha(cond)
223
+ z = np.load(cond, allow_pickle=True)
224
+ if not SAMPLER_KEYS <= set(z.files):
225
+ err(f"{where}: {cond.name} lacks {sorted(SAMPLER_KEYS - set(z.files))}")
226
+ test_raw = np.load(TASK / "data" / ds / f"fold{fold}" / "test_raw.npz", allow_pickle=True)
227
+ if not np.array_equal(z["sample_ids"].astype(str), test_raw["sample_ids"].astype(str)):
228
+ err(f"{where}: {cond.name} rows differ from fold{fold}/test_raw.npz")
229
+ need_bytes += int(z["sample_ids"].size) * CELLS * GENES * 4 * 2 # fold NPZ + its pooled copy
230
+ if a.no_ref:
231
+ continue
232
+ # generation settings of the reference arm (receipt is kept even after the NPZ moved to server_2)
233
+ if arm.startswith("zs__cal_n"):
234
+ ref_arm, n = "zs__cal", int(arm.removeprefix("zs__cal_n"))
235
+ cb = json.loads((TASK / "data" / ds / "CAL_BUDGET.json").read_text())["folds"][str(fold)]["n"][str(n)]
236
+ if cb["sha256"] != inputs[str(cond)] or Path(cb["file"]) != cond:
237
+ err(f"{where}: CAL_BUDGET.json entry does not describe {cond}")
238
+ lr_ = json.loads((TASK / "runs" / ds / f"fold{fold}" / f"lora_n{n}" / "RUN.json").read_text())
239
+ if sorted(cb["fit_sample_ids"]) != sorted(lr_["train_rows"] + lr_["inner_val_rows"]):
240
+ err(f"{where}: calibration rows differ from lora_n{n} train + inner-val rows")
241
+ if set(cb["fit_sample_ids"]) & set(z["sample_ids"].astype(str)):
242
+ err(f"{where}: a test row is among the calibration rows")
243
+ else:
244
+ m = re.fullmatch(r"lora_r(\d+)(?:_n(\d+))?__raw", arm)
245
+ if not m:
246
+ err(f"{where}: unexpected arm name {arm}")
247
+ continue
248
+ ref_arm = f"lora_n{m.group(2)}__raw" if m.group(2) else "real_lora__raw"
249
+ rec_p = out.parent / f"{ref_arm}.log"
250
+ if not need(rec_p, "reference generation receipt"):
251
+ continue
252
+ rec = json.loads(rec_p.read_text())
253
+ if rec["seed"] != seed or rec["steps"] != 50 or rec["weights"] != "ema":
254
+ err(f"{where}: seed/steps/weights differ from {rec_p.name}")
255
+ if not ref_arm.startswith("zs__") and (rec["condition_npz"] != str(cond) or rec["condition_sha256"] != inputs[str(cond)]):
256
+ err(f"{where}: condition differs from {rec_p.name}'s ({rec['condition_npz']})")
257
+ else:
258
+ err(f"{where}: unknown line kind {parts[0]}")
259
+ per_queue[q.name] = nq
260
+ # arm-name collisions with anything already in generated/<ds>/fold*/ on this host
261
+ for o in outputs:
262
+ p = Path(o)
263
+ same = [x for x in p.parent.glob(p.stem + ".*")]
264
+ if same:
265
+ err(f"existing files for new arm {p.stem} in {p.parent}: {[x.name for x in same]}")
266
+ for py in ("/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python", "/home/sj_server_2/miniforge3/envs/b2sc-infer/bin/python",
267
+ "/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python"):
268
+ notes.append(f"{py}: {'present' if Path(py).exists() else 'absent'}")
269
+ for p in (Path.home() / ".local/bin/ml-run", M8 / "plans/arch_ablation_6k_20260913/tools/gpu_usable.sh",
270
+ M8 / "plans/floor01_campaign_20260923/tools/thermal_guard.sh", M8 / "plans/utility_studies_final6k_20260925/tools/sample_queue.sh",
271
+ M8 / "scripts/sample_sdd_standalone.py"):
272
+ if not p.exists():
273
+ err(f"missing runner piece {p}")
274
+ free = shutil.disk_usage(TASK).free
275
+ rep = {"host": host, "queues": per_queue, "train_steps": n_train, "sample_steps": n_sample, "errors": errors,
276
+ "notes": notes, "disk_need_gib": round(need_bytes / 2**30, 1), "disk_free_gib": round(free / 2**30, 1),
277
+ "inputs_sha256": inputs, "reference_checks": not a.no_ref}
278
+ if need_bytes > free:
279
+ errors.append(f"disk: need ~{need_bytes / 2**30:.0f} GiB, free {free / 2**30:.0f} GiB")
280
+ if a.json:
281
+ a.json.write_text(json.dumps(rep, indent=1))
282
+ print(json.dumps({k: rep[k] for k in ("host", "queues", "train_steps", "sample_steps", "disk_need_gib", "disk_free_gib",
283
+ "reference_checks")}, indent=1))
284
+ print("\n".join(notes))
285
+ print(f"{len(inputs)} input files hashed; {len(errors)} error(s)")
286
+ for e in errors:
287
+ print("ERROR", e)
288
+ return 1 if errors else 0
289
+
290
+
291
+ if __name__ == "__main__":
292
+ sys.exit(main())