junidude14 commited on
Commit
64be060
·
verified ·
1 Parent(s): b764098

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261003T174003Z-scsemi-readout-sensitivity/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/compare_output_variants.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """scSemiProfiler read-out sensitivity: official output (scsemi5) vs no output threshold (scsemi5nt) vs the re-read
3
+ control (scsemi5rt), next to LoRA-5 (lora5) and the copy-the-representative composition baseline (CPU only).
4
+
5
+ Metrics exactly as the deck reads them (figures/make_figures.py Call / arm_metrics, unchanged): composition L1,
6
+ precision, coverage; disease logFC r (mean over T / B / Mono / NK of the mean-CP10K contrast r) and top-50 DEG overlap
7
+ sum for the four cohorts with a disease contrast. Giroux disease metrics come from scores_nosex/ (sex-linked genes
8
+ excluded, labels reused), as in the deck; its non-disease metrics must be identical in both trees.
9
+ Per draw every call must share the donor set and the reference sha with the draw's main call (lora5), and the new
10
+ arms' receipts must be verified by the scorer. Copy = composition L1 of the representative's observed cells
11
+ (deck data/sec09_scsemi_representative.csv, panel a, series copy).
12
+ Outputs: scsemi/analysis/output_variants_20261003/{per_draw.csv, summary.csv, SUMMARY.md}. Draws not yet scored for
13
+ every arm are listed as pending and left out.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import importlib.util
18
+ import json
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import pandas as pd
23
+
24
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
25
+ T = M8 / "plans/paired_finetune_intradataset_20260927"
26
+ SCORES, NOSEX_ROOT = T / "scores", T / "scores_nosex"
27
+ OUT = T / "scsemi/analysis/output_variants_20261003"
28
+ DECK_COPY = M8 / "presentations/2026-09-30--paper-summary--r00/data/sec09_scsemi_representative.csv"
29
+ _spec = importlib.util.spec_from_file_location("pf_make_figures", T / "figures" / "make_figures.py")
30
+ mf = importlib.util.module_from_spec(_spec)
31
+ _spec.loader.exec_module(mf)
32
+ NOSEX = ("giroux2022",)
33
+ ARMS = {"lora5": "", "scsemi5": "_scsemi5", "scsemi5nt": "_scsemi5nt", "scsemi5rt": "_scsemi5rt"}
34
+ CELL = ("comp_l1", "precision", "coverage")
35
+ DIS = ("contrast_r", "deg")
36
+ LOWER_BETTER = {"comp_l1"}
37
+
38
+
39
+ def metrics(root: Path, ds: str, j: int):
40
+ base = mf.Call(root / ds / "fewshot_n5" / f"draw{j}")
41
+ out = {}
42
+ for arm, suf in ARMS.items():
43
+ call = base if not suf else mf.Call(root / ds / "fewshot_n5" / f"draw{j}{suf}")
44
+ if arm not in call.arms:
45
+ raise ValueError(f"{call.path}: arm {arm} missing")
46
+ if set(call.donors) != set(base.donors):
47
+ raise ValueError(f"{call.path}: donor set differs from draw{j}")
48
+ if call.summary["reference"]["reference_sha256"] != base.summary["reference"]["reference_sha256"]:
49
+ raise ValueError(f"{call.path}: reference sha differs from draw{j}")
50
+ if suf and not call.summary["per_arm"][arm].get("receipt_verified", False):
51
+ raise ValueError(f"{call.path}: receipt not verified")
52
+ out[arm] = mf.arm_metrics(call, arm)
53
+ return out
54
+
55
+
56
+ def main() -> int:
57
+ OUT.mkdir(parents=True, exist_ok=True)
58
+ rows, pending = [], []
59
+ for ds in mf.DATASETS:
60
+ for j in range(5):
61
+ dirs = [SCORES / ds / "fewshot_n5" / f"draw{j}{s}" / "summary.json" for s in ARMS.values()]
62
+ if ds in NOSEX:
63
+ dirs += [NOSEX_ROOT / ds / "fewshot_n5" / f"draw{j}{s}" / "summary.json" for s in ARMS.values()]
64
+ if not all(p.exists() for p in dirs):
65
+ pending.append(f"{ds} draw{j}")
66
+ continue
67
+ m = metrics(SCORES, ds, j)
68
+ if ds in NOSEX:
69
+ n = metrics(NOSEX_ROOT, ds, j)
70
+ for arm in ARMS:
71
+ for k in ("comp_l1", "null", "precision", "coverage", "n_scored"):
72
+ if m[arm][k] != n[arm][k]:
73
+ raise ValueError(f"{ds} draw{j} {arm}: {k} differs between scores/ and scores_nosex/")
74
+ for k in DIS:
75
+ m[arm][k] = n[arm][k]
76
+ for arm in ARMS:
77
+ rows.append({"dataset": ds, "draw": j, "arm": arm, **{k: m[arm][k] for k in CELL + DIS}})
78
+ df = pd.DataFrame(rows)
79
+ copy = pd.read_csv(DECK_COPY)
80
+ copy = copy[(copy.panel == "a") & (copy.series == "copy")].rename(columns={"cohort": "dataset", "value": "comp_l1"})
81
+ copy = copy.assign(draw=copy.draw.astype(int), arm="copy")[["dataset", "draw", "arm", "comp_l1"]]
82
+ if len(df):
83
+ copy = copy.merge(df[["dataset", "draw"]].drop_duplicates(), on=["dataset", "draw"])
84
+ df = pd.concat([df, copy], ignore_index=True)
85
+ df.to_csv(OUT / "per_draw.csv", index=False)
86
+ if not rows:
87
+ print("nothing scored yet; pending:", pending)
88
+ return 0
89
+ s = df.groupby(["dataset", "arm"])[list(CELL + DIS)].mean().reset_index()
90
+ s["n_draws"] = df.groupby(["dataset", "arm"]).size().values
91
+ s.to_csv(OUT / "summary.csv", index=False)
92
+ # control check: rt vs official, per draw (should be ~0)
93
+ w = df[df.arm.isin(["scsemi5", "scsemi5rt"])].pivot_table(index=["dataset", "draw"], columns="arm",
94
+ values=list(CELL + DIS))
95
+ ctrl = {k: float(np.nanmax(np.abs(w[(k, "scsemi5rt")] - w[(k, "scsemi5")]))) for k in CELL + DIS}
96
+ lines = ["# scSemiProfiler read-out sensitivity (few-pair, 5 donors)", "",
97
+ "Arms: `scsemi5` official output (values <= 10 zeroed by upstream), `scsemi5nt` same trained models without "
98
+ "the output threshold, `scsemi5rt` re-read control with the threshold, `lora5` LoRA-5, `copy` = the "
99
+ "representative's own cells (composition only). Mean over scored draws; Giroux disease metrics without "
100
+ "sex-linked genes.", "",
101
+ f"Scored draws: {df[df.arm == 'lora5'].groupby('dataset').size().to_dict()}; pending: {pending or 'none'}", "",
102
+ f"Control (max |rt - official| over draws): " + ", ".join(f"{k} {v:.3g}" for k, v in ctrl.items()), ""]
103
+ for k in CELL + DIS:
104
+ p = s.pivot(index="dataset", columns="arm", values=k).reindex([d for d in mf.DATASETS if d in set(s.dataset)])
105
+ p = p[[a for a in ("lora5", "scsemi5", "scsemi5nt", "scsemi5rt", "copy") if a in p.columns]]
106
+ lines += [f"## {k} ({'lower' if k in LOWER_BETTER else 'higher'} = better)", "",
107
+ "| cohort | " + " | ".join(p.columns) + " |", "|---" * (len(p.columns) + 1) + "|"]
108
+ for ds, r in p.iterrows():
109
+ lines.append(f"| {ds} | " + " | ".join("" if pd.isna(v) else f"{v:.3f}" for v in r.values) + " |")
110
+ lines.append("")
111
+ (OUT / "SUMMARY.md").write_text("\n".join(lines) + "\n")
112
+ print("\n".join(lines))
113
+ return 0
114
+
115
+
116
+ if __name__ == "__main__":
117
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261003T174003Z-scsemi-readout-sensitivity/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/export_variant_npz.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Adapter for read-out variants (tools/resample_output_variants.py) -> the benchmark's generated NPZ + receipt (CPU).
3
+
4
+ Same NPZ layout, keys, cell rule, depth rule and receipt fields as tools/export_npz.py (its pick_rows /
5
+ to_expected_counts / panel are imported, not copied); export_npz.py itself is not modified (the live queue runs it).
6
+ Differences: shard receipts and shards come from <work>/variants/<v>/ (only the 1,500 kept rows are stored; their
7
+ source rows must equal export_npz.pick_rows(n_upstream_cells, target)); the arm and support_readout come from
8
+ <work>/variants/<v>/VARIANT.json; metadata_json carries "variant".
9
+ usage: export_variant_npz.py --work W --variant {nt,rt} --out OUT.npz
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import sys
17
+ from datetime import datetime, timezone
18
+ from pathlib import Path
19
+
20
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
21
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+ import scipy.sparse as sp
26
+
27
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
28
+ import export_npz as E # noqa: E402 (PANEL, SEED, N_CELLS, pick_rows, to_expected_counts, sha)
29
+
30
+
31
+ def main(argv=None) -> int:
32
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
33
+ ap.add_argument("--work", type=Path, required=True)
34
+ ap.add_argument("--variant", choices=["nt", "rt"], required=True)
35
+ ap.add_argument("--out", type=Path, required=True)
36
+ a = ap.parse_args(argv)
37
+ work, out = a.work.resolve(), a.out.resolve()
38
+ vdir = work / "variants" / a.variant
39
+ var = json.loads((vdir / "VARIANT.json").read_text())
40
+ man = json.loads((work / "inputs/inputs_manifest.json").read_text())
41
+ run = json.loads((work / "run_manifest.json").read_text())
42
+ if man.get("smoke"):
43
+ raise SystemExit("smoke work dirs are not benchmark splits")
44
+ if out.exists() or out.with_suffix(".log").exists():
45
+ raise SystemExit(f"{out} or its receipt exists; never overwrite (preserve and inspect)")
46
+ signature = run["run_signature"]
47
+ if var["run_signature"] != signature:
48
+ raise SystemExit("VARIANT.json belongs to another run signature")
49
+ genes = man["modeled_genes"]["gene_ids"]
50
+ pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
51
+ panel = pd.read_csv(E.PANEL)
52
+ panel_ids = np.asarray(panel.gene_id.astype(str).tolist(), dtype=str)
53
+ panel_symbols = np.asarray(panel.gene_symbol.astype(str).tolist(), dtype=str)
54
+ if not np.array_equal(panel_ids[pidx], np.asarray(genes)):
55
+ raise SystemExit("modeled genes do not sit at the recorded panel columns")
56
+ depth = float(man["depth"]["value"])
57
+ if not (np.isfinite(depth) and depth > 0):
58
+ raise SystemExit("invalid depth")
59
+ targets = man["condition_sample_order"]
60
+ if sorted(targets) != sorted(man["target_order_test_samples"]):
61
+ raise SystemExit("targets differ from the condition NPZ order")
62
+ N = E.N_CELLS
63
+ per, src_rows = [], []
64
+ G = np.zeros((len(targets) * N, panel_ids.size), dtype=np.float32)
65
+ for i, t in enumerate(targets):
66
+ rec = json.loads((vdir / f"{t}.json").read_text())
67
+ shard = vdir / f"{t}.npz"
68
+ if (not rec.get("complete") or rec["run_signature"] != signature or rec["variant"] != a.variant
69
+ or rec["shard_sha256"] != E.sha(shard)):
70
+ raise SystemExit(f"{t}: variant shard incomplete or receipt mismatch")
71
+ rows = np.asarray(rec["source_rows"], dtype=np.int64)
72
+ if not np.array_equal(rows, E.pick_rows(int(rec["n_upstream_cells"]), t)):
73
+ raise SystemExit(f"{t}: stored rows differ from export_npz.pick_rows")
74
+ C = sp.load_npz(shard).tocsr()
75
+ if C.shape != (N, len(genes)):
76
+ raise SystemExit(f"{t}: variant shard shape {C.shape}")
77
+ X = C.toarray().astype(np.float64)
78
+ if not np.isfinite(X).all() or (X < 0).any():
79
+ raise SystemExit(f"{t}: non-finite or negative values")
80
+ Ec, n_zero = E.to_expected_counts(X, depth)
81
+ G[i * N:(i + 1) * N, pidx] = Ec
82
+ src_rows.append(rows.astype(np.int32))
83
+ mult = np.bincount(rows, minlength=int(rec["n_upstream_cells"]))
84
+ per.append({"sample_id": t, "representative": rec["representative"], "n_upstream_cells": int(rec["n_upstream_cells"]),
85
+ "with_replacement": bool(rec["n_upstream_cells"] < N), "max_multiplicity": int(mult.max()),
86
+ "zero_library_cells": n_zero, "elapsed_seconds": rec["elapsed_seconds"],
87
+ "readout_seconds": rec["readout_seconds"],
88
+ "median_nonzero_genes": float(np.median((Ec > 0).sum(1)))})
89
+ lib = G.sum(1, dtype=np.float64)
90
+ nz = lib > 0
91
+ checks = {"finite": bool(np.isfinite(G).all()), "nonnegative": bool((G >= 0).all()),
92
+ "zero_outside_modeled_genes": bool(not G[:, np.setdiff1d(np.arange(panel_ids.size), pidx)].any()),
93
+ "nonzero_cells_sum_to_depth": bool(np.allclose(lib[nz], depth, rtol=1e-4)),
94
+ "gene_order_equals_panel": True, "cells_per_target": N}
95
+ if not all(v for v in checks.values() if isinstance(v, bool)):
96
+ raise SystemExit(f"output checks failed: {checks}")
97
+ n_t = len(targets)
98
+ avail = np.zeros((n_t, panel_ids.size), dtype=bool)
99
+ avail[:, pidx] = True
100
+ meta = {"method": "scSemiProfiler", "arm": var["arm"], "variant": {k: var[k] for k in (
101
+ "variant", "base_arm", "output_threshold", "tool", "tool_sha256", "device", "seed_rule", "origin_host",
102
+ "origin_work")},
103
+ "setting": run["protocol"]["setting"], "dataset": man["dataset"], "mode": man["mode"], "split": man["split"],
104
+ "input_condition_path": man["condition_npz"], "input_condition_sha256": man["condition_sha256"],
105
+ "seed": E.SEED, "run_signature": signature, "upstream_commit": run["protocol"]["upstream_commit"],
106
+ "protocol": run["protocol"], "representatives": [r["sample_id"] for r in man["representatives"]],
107
+ "train_donors": man["train_donors"], "n_modeled_genes": len(genes),
108
+ "unit": "expected_counts (Poisson rates)", "depth_rule": man["depth"]["rule"], "depth": depth,
109
+ "cell_rule": "1500 per target from the n_rep upstream cells: export_npz.pick_rows (rows stored by "
110
+ "resample_output_variants.py); kept rows sorted (source_row)",
111
+ "support_readout": var["support_readout"], "smoke": False, "work": str(work)}
112
+ if "budget" in man:
113
+ meta["budget"] = man["budget"]
114
+ if "reuse" in run:
115
+ meta["reuse"] = run["reuse"]
116
+ out.parent.mkdir(parents=True, exist_ok=True)
117
+ tmp = out.with_name(out.stem + ".tmp.npz")
118
+ np.savez_compressed(tmp, generated_counts=G, gene_ids=panel_ids, gene_symbols=panel_symbols,
119
+ sample_ids=np.asarray(targets), bulk_index=np.repeat(np.arange(n_t, dtype=np.int64), N),
120
+ cells_per_bulk=np.full(n_t, N, dtype=np.int64), output_availability_mask=avail,
121
+ source_row=np.concatenate(src_rows), metadata_json=np.asarray(json.dumps(meta)))
122
+ with np.load(tmp, allow_pickle=False) as chk: # the scorer opens NPZs with allow_pickle=False
123
+ for key in chk.files:
124
+ chk[key]
125
+ os.replace(tmp, out)
126
+ receipt = {"output": str(out), "output_sha256": E.sha(out), "written_utc": datetime.now(timezone.utc).isoformat(),
127
+ "condition_npz": man["condition_npz"], "condition_sha256": man["condition_sha256"], "seed": E.SEED,
128
+ "bulks": n_t, "cells": int(G.shape[0]), "genes": int(panel_ids.size), "modeled_genes": len(genes),
129
+ "depth": depth, "checks": checks, "per_target": per, "arm": var["arm"], "variant": a.variant,
130
+ "total_target_seconds": float(sum(p["elapsed_seconds"] for p in per)),
131
+ "median_target_seconds": float(np.median([p["elapsed_seconds"] for p in per])),
132
+ "run_signature": signature, "exporter_sha256": E.sha(Path(__file__)),
133
+ "export_npz_sha256": E.sha(Path(E.__file__)), "smoke": False}
134
+ rtmp = out.with_name(out.stem + ".log.tmp")
135
+ rtmp.write_text(json.dumps(receipt, indent=1) + "\n")
136
+ os.replace(rtmp, out.with_suffix(".log"))
137
+ print(json.dumps({k: receipt[k] for k in ("output", "arm", "bulks", "cells", "modeled_genes", "depth")}))
138
+ return 0
139
+
140
+
141
+ if __name__ == "__main__":
142
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261003T174003Z-scsemi-readout-sensitivity/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/index_variant_receipts.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """One table of every read-out-variant receipt (tools/resample_output_variants.py), CPU only.
3
+
4
+ The per-target receipts live in each draw's work dir: <work>/variants/{nt,rt}/<target>.json on server_1, and for the
5
+ draws whose work dir is on server_2 (Imperial 0-4, ImMicro 2-3) in the same path there (copied back by
6
+ run_output_variants.sh). This collects them (server_2 over ssh) into
7
+ scsemi/analysis/output_variants_20261003/receipts_index.csv (one row per draw x target x variant: representative,
8
+ seed, rows, model / shard / official shard sha256, read-out seconds and the control numbers) and variants.json
9
+ (each draw's VARIANT.json pair). Exit 1 when a queued draw lacks a complete receipt set.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ import pandas as pd
19
+
20
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
21
+ S = T / "scsemi"
22
+ OUT = S / "analysis/output_variants_20261003"
23
+ QUEUE = S / "queues/output_variants_20261003.txt"
24
+ R2 = "spark-0110"
25
+ PULL = r'''
26
+ import glob, json, os, sys
27
+ w = sys.argv[1]
28
+ out = {"variants": {}, "receipts": []}
29
+ for v in ("nt", "rt"):
30
+ d = os.path.join(w, "variants", v)
31
+ p = os.path.join(d, "VARIANT.json")
32
+ out["variants"][v] = json.load(open(p)) if os.path.isfile(p) else None
33
+ for f in sorted(glob.glob(os.path.join(d, "*.json"))):
34
+ if os.path.basename(f) != "VARIANT.json":
35
+ out["receipts"].append(json.load(open(f)))
36
+ print(json.dumps(out))
37
+ '''
38
+
39
+
40
+ def pull(host: str, work: Path) -> dict:
41
+ cmd = ["python3", "-", str(work)] if host == "server_1" else ["ssh", R2, "python3", "-", str(work)]
42
+ return json.loads(subprocess.run(cmd, input=PULL, capture_output=True, text=True, check=True).stdout)
43
+
44
+
45
+ def main() -> int:
46
+ rows, variants, bad = [], [], []
47
+ for line in QUEUE.read_text().splitlines():
48
+ if not line.strip() or line.startswith("#"):
49
+ continue
50
+ ds, j, host = line.split("|")
51
+ work = S / "work" / ds / "fewshot_n5" / f"draw{j}"
52
+ got = pull(host, work)
53
+ man = json.loads(subprocess.run(
54
+ ["cat", str(work / "inputs/inputs_manifest.json")] if host == "server_1"
55
+ else ["ssh", R2, "cat", str(work / "inputs/inputs_manifest.json")], capture_output=True, text=True,
56
+ check=True).stdout)
57
+ targets = set(man["target_order_test_samples"])
58
+ for v in ("nt", "rt"):
59
+ have = {r["sample_id"] for r in got["receipts"] if r["variant"] == v and r.get("complete")}
60
+ if got["variants"][v] is None or have != targets:
61
+ bad.append(f"{ds} draw{j} {v}: {len(have)}/{len(targets)} receipts")
62
+ variants.append({"dataset": ds, "draw": int(j), "host": host, "work": str(work), "variant": v,
63
+ "VARIANT": got["variants"][v]})
64
+ for r in got["receipts"]:
65
+ c = r.get("control", {})
66
+ rows.append({"dataset": ds, "draw": int(j), "host": host, "variant": r["variant"], "arm": r["arm"],
67
+ "sample_id": r["sample_id"], "representative": r["representative"], "seed": r["seed"],
68
+ "n_upstream_cells": r["n_upstream_cells"], "rows_kept": len(r["source_rows"]),
69
+ "nonzero_fraction_kept": 1 - r["zero_fraction"], "model_sha256": r["model_sha256"],
70
+ "shard_sha256": r["shard_sha256"], "official_shard_sha256": r["official_shard_sha256"],
71
+ "training_seconds": r["elapsed_seconds"], "readout_seconds": r["readout_seconds"],
72
+ "tool_sha256": r["tool_sha256"], **{f"control_{k}": v for k, v in c.items()}})
73
+ OUT.mkdir(parents=True, exist_ok=True)
74
+ df = pd.DataFrame(rows).sort_values(["dataset", "draw", "variant", "sample_id"])
75
+ df.to_csv(OUT / "receipts_index.csv", index=False)
76
+ (OUT / "variants.json").write_text(json.dumps(variants, indent=1) + "\n")
77
+ rt = df[df.variant == "rt"]
78
+ print(json.dumps({"rows": len(df), "draws": int(df[["dataset", "draw"]].drop_duplicates().shape[0]),
79
+ "rt_vs_official_log_pseudobulk_r_min": float(rt.control_rt_vs_official_log_pseudobulk_r.min()),
80
+ "rt_vs_official_pseudobulk_rel_l1_max": float(rt.control_rt_vs_official_pseudobulk_rel_l1.max()),
81
+ "tool_versions": sorted(df.tool_sha256.str[:12].unique().tolist()), "incomplete": bad}, indent=1))
82
+ return 1 if bad else 0
83
+
84
+
85
+ if __name__ == "__main__":
86
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261003T174003Z-scsemi-readout-sensitivity/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/resample_output_variants.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Read-out sensitivity of scSemiProfiler, CPU only, no retraining (added 2026-10-03, user decision: run now as reviewer
3
+ insurance). Without this tool's outputs every existing scSemiProfiler arm is unchanged.
4
+
5
+ What upstream does at the end of fast_semi (vendor inference.py 438-457, vaegan.py myVAE.sample):
6
+ model = fastgenerator(..., countbulkweight=512, ..., upperbound=upperbounds[3]); load tmp/model<ministages-1>
7
+ xsemi = cat(model.module.sample(batch, n_samples=1))[:, :genelen]
8
+ sample(): ZINB mean of the decoder, then exprs * (exprs > bound), bound = library_size / 1e3 = 10 by default
9
+ save models/semi_<rep>_to_<tgt> (that same state), then xsemi = xsemi * (xsemi > 10) and np.save(inferreddata/...)
10
+ The threshold is not an API parameter, so the official output (arms scsemi5 / scsemi / scsemi_n<n>) carries it.
11
+
12
+ This tool rebuilds that final model from models/semi_<rep>_to_<tgt> on the same representative input (upstream
13
+ setdata), repeats the read-out once per target with the target's own seed (scvi.settings.seed = 20260927 + target bulk
14
+ row, the wrapper's infer rule) and keeps two variants of that single draw:
15
+ nt sample(bound=0), no xsemi > 10 step: the model's ZINB mean on every modeled gene (arm <base>nt)
16
+ rt the same draw zeroed at <= 10 exactly as upstream: control of the re-run (arm <base>rt)
17
+ It equals the official output up to the encoder's z sampling noise; per target it is compared with the official
18
+ shard (pseudobulk correlation, relative L1, non-zero fraction) and the numbers go into the receipt.
19
+ The module is left in the state upstream leaves it in: a freshly built model with the state loaded, not .eval()
20
+ (BatchNorm uses the read-out batch's statistics), batch = min(n_rep, 9000) cells; sample() itself runs under no_grad.
21
+
22
+ Representative inputs: sample_sc/<rep>.h5ad is deleted after an export (clean_sample_sc). If missing it is re-derived
23
+ with the wrapper's own prepare steps (the rep's rows of inputs/rep_sc.h5ad -> upstream scprocess with the run's
24
+ scprocess protocol, the lean cell graph, the run's hvset.npy / hvgenes.npy) in <work>/variants/_scratch and must match
25
+ prepared.json's sha256 (geneset scores too); a mismatch stops the tool. The scratch project is removed at the end.
26
+ Each representative (re-derivation + read-out of its targets) runs in its own child process (--rep REP), and its rows
27
+ are read from rep_sc.h5ad in backed mode. Added 2026-10-03 after the first Giroux runs were OOM-killed at the 16 GiB
28
+ cap: scvi keeps every set-up AnnData (with its dense n x n cell graph) in a class-level registry, so one process
29
+ accumulated the representatives' inputs.
30
+
31
+ Output per variant v in {nt, rt}: <work>/variants/<v>/VARIANT.json, <tgt>.npz (CSR, compressed; only the rows
32
+ export_npz.pick_rows keeps, in that order) and <tgt>.json (receipt: source_rows, n_upstream_cells, sha256, model sha256,
33
+ control numbers, and elapsed_seconds = the official target's training seconds, since the model is the same).
34
+ tools/export_variant_npz.py and tools/validate_variant_export.py read them. Targets already done are skipped.
35
+ usage: resample_output_variants.py --work W [--threads N] [--origin-host H --origin-work PATH]
36
+ """
37
+ from __future__ import annotations
38
+
39
+ import argparse
40
+ import gc
41
+ import hashlib
42
+ import importlib.metadata
43
+ import json
44
+ import os
45
+ import shutil
46
+ import subprocess
47
+ import sys
48
+ import time
49
+ from datetime import datetime, timezone
50
+ from pathlib import Path
51
+
52
+ HERE = Path(__file__).resolve().parents[1]
53
+ SEED = 20260927
54
+ VARIANTS = {
55
+ "nt": {"suffix": "nt", "bound": 0.0, "post_threshold": False,
56
+ "support_readout": "no output threshold: the upstream model's ZINB mean on every modeled gene "
57
+ "(sample(bound=0), no xsemi > 10 step); read-out sensitivity variant, not the official output"},
58
+ "rt": {"suffix": "rt", "bound": 0.0, "post_threshold": True,
59
+ "support_readout": "upstream (values <= 10 normalized units zeroed), re-read from the saved per-target model; "
60
+ "control of the read-out re-run (equals the official output up to z sampling noise)"},
61
+ }
62
+ ENV_KEYS = ["torch", "scvi-tools", "scanpy", "anndata", "lightning", "numpy", "scikit-learn"]
63
+
64
+
65
+ def sha256(path: Path) -> str:
66
+ h = hashlib.sha256()
67
+ with open(path, "rb") as f:
68
+ for block in iter(lambda: f.read(1 << 24), b""):
69
+ h.update(block)
70
+ return h.hexdigest()
71
+
72
+
73
+ def write_json(path: Path, value: dict) -> None:
74
+ tmp = path.with_name(path.name + ".tmp")
75
+ tmp.write_text(json.dumps(value, indent=1, default=str) + "\n")
76
+ tmp.replace(path)
77
+
78
+
79
+ def main(argv=None) -> int:
80
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
81
+ ap.add_argument("--work", type=Path, required=True)
82
+ ap.add_argument("--threads", type=int, default=4)
83
+ ap.add_argument("--origin-host", default=None, help="host the work dir was copied from (recorded only)")
84
+ ap.add_argument("--origin-work", default=None, help="the work dir's path on that host (recorded only)")
85
+ ap.add_argument("--rep", default=None, metavar="REP",
86
+ help="internal: process only REP's targets (the parent runs one child per representative)")
87
+ a = ap.parse_args(argv)
88
+ if not 1 <= a.threads <= 6:
89
+ ap.error("--threads must be 1..6")
90
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
91
+ raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
92
+ for name in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
93
+ os.environ[name] = str(a.threads)
94
+ work = a.work.resolve()
95
+ project = work / "scsemi_project"
96
+ man = json.loads((work / "inputs/inputs_manifest.json").read_text())
97
+ run = json.loads((work / "run_manifest.json").read_text())
98
+ prepared = json.loads((work / "prepared.json").read_text())
99
+ signature = run["run_signature"]
100
+ binding = run["migrations"][-1]["to_binding"] if run.get("migrations") else run
101
+ protocol = binding["protocol"]
102
+ if prepared["run_signature"] != signature:
103
+ raise SystemExit("prepared.json belongs to another run signature")
104
+ if man.get("smoke"):
105
+ raise SystemExit("smoke work dirs are not benchmark splits")
106
+ base_arm = {"fewshot": "scsemi5", "cv": "scsemi"}.get(man["mode"]) or f"scsemi_n{int(man['budget']['n'])}"
107
+ for name, digest in man["files"].items():
108
+ if sha256(work / "inputs" / name) != digest:
109
+ raise SystemExit(f"input {name} differs from its manifest")
110
+ for name in ("processed_bulkdata.h5ad", "hvgenes.npy", "sids.txt", "hvset.npy"):
111
+ if sha256(project / name) != prepared["files"][name]:
112
+ raise SystemExit(f"prepared file changed: {name}")
113
+ if sha256(work / "genesets/c2.cp.v7.4.symbols.gmt") != prepared["genesets_gmt_sha256"]:
114
+ raise SystemExit("work genesets/ GMT differs from prepared.json")
115
+ vendor = HERE / "vendor/scSemiProfiler"
116
+ source = json.loads((vendor.parent / "source_manifest.json").read_text())
117
+ if source != binding["source"]:
118
+ raise SystemExit("vendor source manifest differs from the run's binding")
119
+ for name, expected in source["files"].items():
120
+ if sha256(vendor / name) != expected:
121
+ raise SystemExit(f"vendor source hash mismatch: {name}")
122
+ env = {k: importlib.metadata.version(k) for k in ENV_KEYS}
123
+ bad_env = {k: (env[k], binding["environment"].get(k)) for k in ENV_KEYS if env[k] != binding["environment"].get(k)}
124
+ if bad_env:
125
+ raise SystemExit(f"environment differs from the run's binding: {bad_env}")
126
+ if sha256(HERE / "tools/lean_cellgraph.py") != binding["lean_cellgraph_sha256"]:
127
+ raise SystemExit("tools/lean_cellgraph.py differs from the run's binding")
128
+
129
+ import numpy as np
130
+ import anndata
131
+ import scipy.sparse as sp
132
+ sys.path.insert(0, str(vendor))
133
+ sys.path.insert(0, str(HERE / "tools"))
134
+ import torch
135
+ import scvi
136
+ import scSemiProfiler
137
+ import scSemiProfiler.singlecell_process as upstream_sp
138
+ from scSemiProfiler.inference import setdata, fastgenerator
139
+ from lean_cellgraph import fast_cellgraph_lean
140
+ from export_npz import pick_rows
141
+ upstream_sp.fast_cellgraph = fast_cellgraph_lean # as the wrapper's prepare phase (resolved inside scprocess)
142
+ torch.set_num_threads(a.threads)
143
+
144
+ sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
145
+ assign = json.loads((work / "assignment.json").read_text())["targets"]
146
+ targets = list(man["target_order_test_samples"])
147
+ reps = [r["sample_id"] for r in man["representatives"]]
148
+ genelen = len(man["modeled_genes"]["gene_ids"])
149
+ I = protocol["infer"]
150
+ S = protocol["scprocess"]
151
+ scratch = work / "variants" / "_scratch"
152
+ sproj = scratch / "project"
153
+ if a.rep is not None and a.rep not in reps:
154
+ raise SystemExit(f"--rep {a.rep}: not a representative of this split")
155
+ tool_sha = sha256(Path(__file__))
156
+ out = {}
157
+ for v, spec in VARIANTS.items():
158
+ d = work / "variants" / v
159
+ d.mkdir(parents=True, exist_ok=True)
160
+ meta = {"variant": v, "arm": base_arm + spec["suffix"], "base_arm": base_arm,
161
+ "support_readout": spec["support_readout"], "output_threshold": "none" if v == "nt" else "values <= 10 zeroed",
162
+ "run_signature": signature, "upstream_commit": protocol["upstream_commit"], "work": str(work),
163
+ "origin_host": a.origin_host or os.uname().nodename, "origin_work": a.origin_work or str(work),
164
+ "tool": str(Path(__file__).resolve()), "tool_sha256": tool_sha, "environment": env,
165
+ "device": "cpu", "seed_rule": "scvi.settings.seed = 20260927 + target bulk row (the wrapper's infer rule)"}
166
+ if (d / "VARIANT.json").exists():
167
+ old = json.loads((d / "VARIANT.json").read_text())
168
+ if {k: old.get(k) for k in ("arm", "run_signature", "tool_sha256", "environment")} != \
169
+ {k: meta[k] for k in ("arm", "run_signature", "tool_sha256", "environment")}:
170
+ raise SystemExit(f"{d}/VARIANT.json was written by another tool version / run; use a fresh variants dir")
171
+ else:
172
+ meta["created_utc"] = datetime.now(timezone.utc).isoformat()
173
+ write_json(d / "VARIANT.json", meta)
174
+ out[v] = d
175
+
176
+ def done(t: str) -> bool:
177
+ ok = []
178
+ for v, d in out.items():
179
+ rp, sh = d / f"{t}.json", d / f"{t}.npz"
180
+ if rp.exists():
181
+ rec = json.loads(rp.read_text())
182
+ if not rec.get("complete") or rec["shard_sha256"] != sha256(sh):
183
+ raise SystemExit(f"{rp}: incomplete or sha mismatch; preserve and inspect")
184
+ ok.append(True)
185
+ else:
186
+ if sh.exists():
187
+ raise SystemExit(f"{sh} without receipt; preserve and inspect")
188
+ ok.append(False)
189
+ if any(ok) and not all(ok):
190
+ raise SystemExit(f"{t}: only some variants written; preserve and inspect")
191
+ return all(ok)
192
+
193
+ pending = [t for t in targets if not done(t)]
194
+ print(json.dumps({"work": str(work), "targets": len(targets), "pending": len(pending)}), flush=True)
195
+ if not pending:
196
+ return 0
197
+ bulk = anndata.read_h5ad(project / "processed_bulkdata.h5ad")
198
+ t_start = time.monotonic()
199
+ try:
200
+ for r in reps:
201
+ mine = [t for t in pending if assign[t]["representative"] == r]
202
+ if not mine:
203
+ continue
204
+ if a.rep is None: # parent: one child process per representative (all its memory is returned)
205
+ cmd = [sys.executable, "-u", str(Path(__file__).resolve()), "--work", str(work),
206
+ "--threads", str(a.threads), "--rep", r]
207
+ for flag, val in (("--origin-host", a.origin_host), ("--origin-work", a.origin_work)):
208
+ if val:
209
+ cmd += [flag, val]
210
+ rc = subprocess.run(cmd).returncode
211
+ if rc != 0:
212
+ raise SystemExit(f"{r}: child process exited {rc}")
213
+ continue
214
+ if r != a.rep:
215
+ continue
216
+ # representative input in a scratch project (never written into the run's own project)
217
+ if sproj.exists():
218
+ shutil.rmtree(sproj)
219
+ (sproj / "sample_sc").mkdir(parents=True)
220
+ (sproj / "geneset_scores").mkdir()
221
+ for name in ("hvgenes.npy", "hvset.npy"):
222
+ shutil.copyfile(project / name, sproj / name)
223
+ f_sc, f_gs = project / "sample_sc" / f"{r}.h5ad", project / "geneset_scores" / f"{r}.npy"
224
+ if f_sc.exists() and f_gs.exists():
225
+ os.link(f_sc, sproj / "sample_sc" / f"{r}.h5ad")
226
+ os.link(f_gs, sproj / "geneset_scores" / f"{r}.npy")
227
+ how = "existing prepared files"
228
+ else:
229
+ os.chdir(work) # upstream scprocess reads "genesets/" relative to the cwd
230
+ R = anndata.read_h5ad(work / "inputs/rep_sc.h5ad", backed="r")
231
+ f_r = scratch / f"{r}.h5ad"
232
+ R[(R.obs["sample_ids"] == r).to_numpy()].to_memory().write_h5ad(f_r)
233
+ R.file.close()
234
+ del R
235
+ gc.collect()
236
+ scSemiProfiler.scprocess(str(sproj), str(f_r), logged=S["logged"], normed=S["normed"],
237
+ cellfilter=S["cellfilter"], threshold=S["threshold"], geneset=S["geneset"],
238
+ weight=S["weight"], k=S["k"])
239
+ f_r.unlink()
240
+ gc.collect()
241
+ how = "re-derived with upstream scprocess (lean cell graph)"
242
+ for name in (f"sample_sc/{r}.h5ad", f"geneset_scores/{r}.npy"):
243
+ if sha256(sproj / name) != prepared["files"][name]:
244
+ raise SystemExit(f"{r}: {name} ({how}) differs from prepared.json; stop and inspect")
245
+ print(json.dumps({"representative": r, "input": how, "sha_ok": True, "targets": len(mine)}), flush=True)
246
+ adata, adj, variances, _, geneset_len = setdata(str(sproj), r, device="cpu", k=I["k"], diagw=I["diagw"])
247
+ maxexpr = adata.X.max()
248
+ upperbounds = [maxexpr / 2, maxexpr / 4, maxexpr / 8, maxexpr / (8 * np.sqrt(2)), maxexpr / 16,
249
+ maxexpr / 32, maxexpr / 64] # fast_semi's list; [3] is the final model's
250
+ batch_size = int(np.min([adata.X.shape[0], 9000]))
251
+ n_rep = adata.X.shape[0]
252
+ rid = sids.index(r)
253
+ for t in mine:
254
+ tid = sids.index(t)
255
+ orec = json.loads((work / "shards" / f"{t}.json").read_text())
256
+ oshard = work / "shards" / f"{t}.npz"
257
+ if (not orec.get("complete") or orec["run_signature"] != signature or orec["representative"] != r
258
+ or orec["shard_sha256"] != sha256(oshard)):
259
+ raise SystemExit(f"{t}: official shard receipt mismatch")
260
+ # fast_semi's bulk vector for bulktype 'real' (inference.py 349-362), same arithmetic
261
+ tgtbulk = np.exp(bulk.X[tid]) - 1
262
+ repbulk = np.exp(bulk.X[rid]) - 1
263
+ pseudobulk = (np.array(adata.X)).mean(axis=0).reshape((1, -1))
264
+ ratio = np.array((np.array(tgtbulk).reshape((1, -1)) + I["pseudocount"]) /
265
+ (np.array(repbulk).reshape((1, -1)) + I["pseudocount"]))
266
+ ratio = np.concatenate([ratio, np.ones((1, pseudobulk.shape[1] - ratio.shape[1]))], axis=1)
267
+ bvec = torch.tensor(pseudobulk * ratio)
268
+ model = fastgenerator(adata=adata, variances=variances, geneset_len=geneset_len, bulk=bvec,
269
+ n_hidden=256, n_latent=32, dropout_rate=0, countbulkweight=512, logbulkweight=0,
270
+ absbulkweight=0, abslogbulkweight=0, corrbulkweight=0, power=2,
271
+ upperbound=upperbounds[3])
272
+ mpath = project / "models" / f"semi_{r}_to_{t}"
273
+ model.module.load_state_dict(torch.load(mpath, map_location="cpu", weights_only=True))
274
+ scvi.settings.seed = SEED + tid
275
+ t0 = time.monotonic()
276
+ xs = []
277
+ for tensors in model._make_data_loader(adata=adata, batch_size=batch_size):
278
+ xs.append(model.module.sample(tensors, n_samples=1, bound=VARIANTS["nt"]["bound"]))
279
+ X = np.array(torch.cat(xs))[:, :genelen]
280
+ el = time.monotonic() - t0
281
+ if X.shape != (n_rep, genelen) or not np.isfinite(X).all() or (X < 0).any():
282
+ raise SystemExit(f"{t}: invalid read-out {X.shape}")
283
+ Xrt = X * (X > 10)
284
+ Off = sp.load_npz(oshard).tocsr()
285
+ if Off.shape != X.shape:
286
+ raise SystemExit(f"{t}: official shard shape {Off.shape} != read-out {X.shape}")
287
+ pb_off = np.asarray(Off.mean(0)).ravel()
288
+ pb_rt, pb_nt = Xrt.mean(0), X.mean(0)
289
+ k = pb_off > 0
290
+ control = {"genes_compared": int(k.sum()),
291
+ "rt_vs_official_log_pseudobulk_r": float(np.corrcoef(np.log(pb_rt[k] + 0.1), np.log(pb_off[k] + 0.1))[0, 1]),
292
+ "rt_vs_official_pseudobulk_rel_l1": float(np.abs(pb_rt - pb_off).sum() / pb_off.sum()),
293
+ "nonzero_fraction_official": float(Off.nnz / (Off.shape[0] * Off.shape[1])),
294
+ "nonzero_fraction_rt": float((Xrt > 0).mean()),
295
+ "nonzero_fraction_nt": float((X > 0).mean()),
296
+ "library_mean_nt": float(X.sum(1).mean()), "library_mean_rt": float(Xrt.sum(1).mean()),
297
+ "library_mean_official": float(np.asarray(Off.sum(1)).mean()),
298
+ "nt_vs_official_log_pseudobulk_r": float(np.corrcoef(np.log(pb_nt[k] + 0.1), np.log(pb_off[k] + 0.1))[0, 1])}
299
+ rows = pick_rows(n_rep, t)
300
+ for v, M in (("nt", X), ("rt", Xrt)):
301
+ d = out[v]
302
+ C = sp.csr_matrix(M[rows])
303
+ tmp = d / f"{t}.tmp.npz"
304
+ sp.save_npz(tmp, C, compressed=True)
305
+ back = sp.load_npz(tmp).toarray()
306
+ if back.dtype != M.dtype or not np.array_equal(back, M[rows]):
307
+ raise SystemExit(f"{t}/{v}: CSR re-encoding is not lossless")
308
+ tmp.replace(d / f"{t}.npz")
309
+ write_json(d / f"{t}.json", {
310
+ "sample_id": t, "representative": r, "rep_bulk_index": rid, "target_bulk_index": tid,
311
+ "variant": v, "arm": base_arm + VARIANTS[v]["suffix"], "seed": SEED + tid,
312
+ "n_upstream_cells": int(n_rep), "source_rows": rows.astype(int).tolist(),
313
+ "rows_rule": "export_npz.pick_rows(n_upstream_cells, target)",
314
+ "shape": list(C.shape), "dtype": str(M.dtype), "nnz": int(C.nnz),
315
+ "zero_fraction": float(1 - C.nnz / (C.shape[0] * C.shape[1])),
316
+ "zero_rows": int((np.asarray(C.sum(1)).ravel() == 0).sum()),
317
+ "matrix_unit": "normalized_expression",
318
+ "model": str(mpath), "model_sha256": sha256(mpath),
319
+ "official_shard": str(oshard), "official_shard_sha256": orec["shard_sha256"],
320
+ "elapsed_seconds": orec["elapsed_seconds"],
321
+ "elapsed_note": "the official target's training seconds (same model); this tool only re-reads",
322
+ "readout_seconds": el, "device": "cpu", "run_signature": signature, "tool_sha256": tool_sha,
323
+ "control": control, "shard": str(d / f"{t}.npz"), "shard_sha256": sha256(d / f"{t}.npz"),
324
+ "created_at": datetime.now(timezone.utc).isoformat(), "complete": True})
325
+ print(json.dumps({"target": t, "rep": r, "readout_s": round(el, 2), **{k2: round(v2, 4) for k2, v2 in control.items()}}), flush=True)
326
+ del model, X, Xrt, Off
327
+ gc.collect()
328
+ del adata, adj, variances
329
+ shutil.rmtree(sproj)
330
+ gc.collect()
331
+ finally:
332
+ if scratch.exists():
333
+ shutil.rmtree(scratch)
334
+ print(json.dumps({"work": str(work), "done": len(pending), "seconds": round(time.monotonic() - t_start, 1)}), flush=True)
335
+ return 0
336
+
337
+
338
+ if __name__ == "__main__":
339
+ sys.exit(main())