junidude14 commited on
Commit
61ebfff
·
verified ·
1 Parent(s): 8d13f84

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/backups/plans/paired_finetune_intradataset_20260927/scsemi/tools/export_npz.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Adapter: completed scSemiProfiler target shards -> the benchmark's generated NPZ + JSON receipt (CPU only).
3
+
4
+ Per target (condition-NPZ order):
5
+ cells upstream output has one generated cell per cell of the assigned representative (n_rep cells).
6
+ Keep 1,500: n_rep >= 1500 -> 1,500 drawn without replacement; n_rep < 1500 -> whole permutations of the
7
+ n_rep cells concatenated until 1,500 (each cell used floor/ceil(1500/n_rep) times). Stream
8
+ default_rng([20260927, uint64(sha256(target)[:8])]) (the scorer's donor-keyed stream form); kept rows sorted.
9
+ depth upstream values are normalized expression (library-normalised ZINB means, values <= 10 zeroed). Each kept
10
+ cell is rescaled to sum to D = the median per-cell UMI on the modeled genes of the representatives'
11
+ observed cells (inputs_manifest depth.value; label-free, from the training pairs only). All-zero cells stay
12
+ zero (counted). Result = expected counts (Poisson rates), what score_ft.py reads out.
13
+ genes modeled genes placed at their 6k-panel columns; every other panel column is 0.
14
+ metadata_json.input_condition_path = the split's test_raw.npz, so the scorer's bulk-broadcast baseline works.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import argparse
19
+ import hashlib
20
+ import json
21
+ import math
22
+ import os
23
+ import sys
24
+ from datetime import datetime, timezone
25
+ from pathlib import Path
26
+
27
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
28
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
29
+
30
+ import numpy as np
31
+ import pandas as pd
32
+ import scipy.sparse as sp
33
+
34
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
35
+ PANEL = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv"
36
+ SEED = 20260927
37
+ N_CELLS = 1500
38
+
39
+
40
+ def sha(path: Path) -> str:
41
+ h = hashlib.sha256()
42
+ with open(path, "rb") as f:
43
+ for block in iter(lambda: f.read(1 << 24), b""):
44
+ h.update(block)
45
+ return h.hexdigest()
46
+
47
+
48
+ def target_rng(target: str) -> np.random.Generator:
49
+ key = int.from_bytes(hashlib.sha256(str(target).encode()).digest()[:8], "little")
50
+ return np.random.default_rng([SEED, key])
51
+
52
+
53
+ def pick_rows(n_src: int, target: str, n_out: int = N_CELLS) -> np.ndarray:
54
+ if n_src < 1:
55
+ raise ValueError(f"{target}: no generated cells")
56
+ rng = target_rng(target)
57
+ if n_src >= n_out:
58
+ return np.sort(rng.choice(n_src, size=n_out, replace=False))
59
+ reps = math.ceil(n_out / n_src)
60
+ return np.sort(np.concatenate([rng.permutation(n_src) for _ in range(reps)])[:n_out])
61
+
62
+
63
+ def to_expected_counts(X: np.ndarray, depth: float) -> tuple[np.ndarray, int]:
64
+ lib = X.sum(1, dtype=np.float64)
65
+ scale = np.divide(depth, lib, out=np.zeros_like(lib), where=lib > 0)
66
+ return (X * scale[:, None]).astype(np.float32), int((lib <= 0).sum())
67
+
68
+
69
+ def main(argv=None) -> int:
70
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
71
+ ap.add_argument("--work", type=Path, required=True)
72
+ ap.add_argument("--out", type=Path, required=True, help="generated NPZ path (receipt = same stem .log)")
73
+ a = ap.parse_args(argv)
74
+ work, out = a.work.resolve(), a.out.resolve()
75
+ man = json.loads((work / "inputs/inputs_manifest.json").read_text())
76
+ run = json.loads((work / "run_manifest.json").read_text())
77
+ smoke = bool(man.get("smoke"))
78
+ if smoke and "/scsemi/smoke/" not in str(out):
79
+ raise SystemExit("smoke outputs never go to the benchmark's generated/ tree")
80
+ if out.exists() or out.with_suffix(".log").exists():
81
+ raise SystemExit(f"{out} or its receipt exists; never overwrite (preserve and inspect)")
82
+ signature = run["run_signature"]
83
+ genes = man["modeled_genes"]["gene_ids"]
84
+ pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
85
+ panel = pd.read_csv(PANEL)
86
+ panel_ids = np.asarray(panel.gene_id.astype(str).tolist(), dtype=str) # fixed-width unicode: loads with allow_pickle=False
87
+ panel_symbols = np.asarray(panel.gene_symbol.astype(str).tolist(), dtype=str)
88
+ if not np.array_equal(panel_ids[pidx], np.asarray(genes)):
89
+ raise SystemExit("modeled genes do not sit at the recorded panel columns")
90
+ depth = float(man["depth"]["value"])
91
+ if not (np.isfinite(depth) and depth > 0):
92
+ raise SystemExit("invalid depth")
93
+ targets = man["condition_sample_order"] if not smoke else [t for t in man["condition_sample_order"]
94
+ if t in set(man["target_order_test_samples"])]
95
+ if sorted(targets) != sorted(man["target_order_test_samples"]):
96
+ raise SystemExit("targets differ from the condition NPZ order")
97
+ per, src_rows = [], []
98
+ G = np.zeros((len(targets) * N_CELLS, panel_ids.size), dtype=np.float32)
99
+ for i, t in enumerate(targets):
100
+ rec = json.loads((work / "shards" / f"{t}.json").read_text())
101
+ shard = work / "shards" / f"{t}.npz"
102
+ if not rec.get("complete") or rec["run_signature"] != signature or rec["shard_sha256"] != sha(shard):
103
+ raise SystemExit(f"{t}: shard incomplete or receipt mismatch")
104
+ C = sp.load_npz(shard).tocsr()
105
+ if C.shape[1] != len(genes):
106
+ raise SystemExit(f"{t}: shard has {C.shape[1]} genes")
107
+ rows = pick_rows(C.shape[0], t)
108
+ X = C[rows].toarray().astype(np.float64)
109
+ if not np.isfinite(X).all() or (X < 0).any():
110
+ raise SystemExit(f"{t}: non-finite or negative values")
111
+ E, n_zero = to_expected_counts(X, depth)
112
+ G[i * N_CELLS:(i + 1) * N_CELLS, pidx] = E
113
+ src_rows.append(rows.astype(np.int32))
114
+ mult = np.bincount(rows, minlength=C.shape[0])
115
+ per.append({"sample_id": t, "representative": rec["representative"], "n_upstream_cells": int(C.shape[0]),
116
+ "with_replacement": bool(C.shape[0] < N_CELLS), "max_multiplicity": int(mult.max()),
117
+ "zero_library_cells": n_zero, "elapsed_seconds": rec["elapsed_seconds"],
118
+ "median_nonzero_genes": float(np.median((E > 0).sum(1)))})
119
+ lib = G.sum(1, dtype=np.float64)
120
+ nz = lib > 0
121
+ checks = {"finite": bool(np.isfinite(G).all()), "nonnegative": bool((G >= 0).all()),
122
+ "zero_outside_modeled_genes": bool(not G[:, np.setdiff1d(np.arange(panel_ids.size), pidx)].any()),
123
+ "nonzero_cells_sum_to_depth": bool(np.allclose(lib[nz], depth, rtol=1e-4)),
124
+ "gene_order_equals_panel": True, "cells_per_target": N_CELLS}
125
+ if not all(v for k, v in checks.items() if isinstance(v, bool)):
126
+ raise SystemExit(f"output checks failed: {checks}")
127
+ n_t = len(targets)
128
+ avail = np.zeros((n_t, panel_ids.size), dtype=bool)
129
+ avail[:, pidx] = True
130
+ arm = {"fewshot": "scsemi5", "cv": "scsemi"}.get(man["mode"])
131
+ if arm is None: # budget split (added 2026-10-02): the equal-pair-budget arm of LoRA lora_n<n>
132
+ arm = f"scsemi_n{int(man['budget']['n'])}"
133
+ meta = {"method": "scSemiProfiler", "arm": arm,
134
+ "setting": run["protocol"]["setting"], "dataset": man["dataset"], "mode": man["mode"], "split": man["split"],
135
+ "input_condition_path": man["condition_npz"], "input_condition_sha256": man["condition_sha256"],
136
+ "seed": SEED, "run_signature": signature, "upstream_commit": run["protocol"]["upstream_commit"],
137
+ "protocol": run["protocol"], "representatives": [r["sample_id"] for r in man["representatives"]],
138
+ "train_donors": man["train_donors"], "n_modeled_genes": len(genes),
139
+ "unit": "expected_counts (Poisson rates)", "depth_rule": man["depth"]["rule"], "depth": depth,
140
+ "cell_rule": "1500 per target from the n_rep upstream cells: without replacement if n_rep >= 1500, else "
141
+ "whole permutations concatenated to 1500; default_rng([20260927, uint64 LE sha256(target)[:8]]); "
142
+ "kept rows sorted (source_row)",
143
+ "support_readout": "upstream (values <= 10 normalized units zeroed by fast_semi)", "smoke": smoke,
144
+ "code_migrations": [{"at": m["at"], "transitions": m["transitions"], "to_code_signature": m["to_code_signature"]}
145
+ for m in run.get("migrations", [])],
146
+ "work": str(work)}
147
+ if "budget" in man:
148
+ meta["budget"] = man["budget"]
149
+ if "reuse" in run: # pretraining / hvset reused from another run (run_scsemi_paired.py --reuse-from)
150
+ meta["reuse"] = run["reuse"]
151
+ out.parent.mkdir(parents=True, exist_ok=True)
152
+ tmp = out.with_name(out.stem + ".tmp.npz")
153
+ np.savez_compressed(tmp, generated_counts=G, gene_ids=panel_ids, gene_symbols=panel_symbols,
154
+ sample_ids=np.asarray(targets), bulk_index=np.repeat(np.arange(n_t, dtype=np.int64), N_CELLS),
155
+ cells_per_bulk=np.full(n_t, N_CELLS, dtype=np.int64), output_availability_mask=avail,
156
+ source_row=np.concatenate(src_rows), metadata_json=np.asarray(json.dumps(meta)))
157
+ with np.load(tmp, allow_pickle=False) as chk: # the scorer opens NPZs with allow_pickle=False
158
+ for key in chk.files:
159
+ chk[key]
160
+ os.replace(tmp, out)
161
+ receipt = {"output": str(out), "output_sha256": sha(out), "written_utc": datetime.now(timezone.utc).isoformat(),
162
+ "condition_npz": man["condition_npz"], "condition_sha256": man["condition_sha256"], "seed": SEED,
163
+ "bulks": n_t, "cells": int(G.shape[0]), "genes": int(panel_ids.size), "modeled_genes": len(genes),
164
+ "depth": depth, "checks": checks, "per_target": per,
165
+ "total_target_seconds": float(sum(p["elapsed_seconds"] for p in per)),
166
+ "median_target_seconds": float(np.median([p["elapsed_seconds"] for p in per])),
167
+ "run_signature": signature, "code_migrations": meta["code_migrations"],
168
+ "exporter_sha256": sha(Path(__file__)), "smoke": smoke}
169
+ rtmp = out.with_name(out.stem + ".log.tmp")
170
+ rtmp.write_text(json.dumps(receipt, indent=1) + "\n")
171
+ os.replace(rtmp, out.with_suffix(".log"))
172
+ print(json.dumps({k: receipt[k] for k in ("output", "bulks", "cells", "modeled_genes", "depth",
173
+ "median_target_seconds")}))
174
+ return 0
175
+
176
+
177
+ if __name__ == "__main__":
178
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/backups/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Build scSemiProfiler inputs for one paired split (CPU only).
3
+
4
+ Representatives = every usable row of the split's training donors (paired sc + real bulk).
5
+ Targets = the split's test rows (real bulk only; their cells are never read here).
6
+
7
+ --mode fewshot --draw j : training donors = data/<ds>/fewshot_n5/draw<j>/train_donors.txt,
8
+ targets = draw<j>/test_samples.txt, condition = draw<j>/test_raw.npz
9
+ --mode cv --fold k : training donors = every usable donor not in fold k (inner-val donors included),
10
+ targets = fold k's rows, condition = data/<ds>/fold<k>/test_raw.npz
11
+ --mode budget --fold k --n N (added 2026-10-02): representatives = exactly the rows LoRA lora_n<N> of fold k saw,
12
+ runs/<ds>/fold<k>/lora_n<N>/RUN.json train_rows + inner_val_rows (checked against
13
+ data/<ds>/CAL_BUDGET.json fit_sample_ids when present); targets = fold k's rows (checked
14
+ against the run's test_rows_never_loaded_for_training); condition = fold<k>/test_raw.npz.
15
+ The manifest also records target_donors (used by run_scsemi_paired.py --reuse-from).
16
+ --check-only (added 2026-10-02): build and check everything (split, genes, cells, depth, condition), write
17
+ nothing under --work; print the summary (and the representative / target lists to
18
+ --check-out if given). Without it the builder behaves exactly as before.
19
+
20
+ Modeled genes = final 6k panel genes measured in the bulk of every representative and target row AND in the
21
+ single cells of every representative row (features.npz bulk_valid / sc_valid). No target single-cell mask,
22
+ depth or cell count enters.
23
+
24
+ Writes <work>/inputs/:
25
+ bulk.h5ad raw bulk counts (float64) of reps + targets on the modeled genes, obs['sample_ids'],
26
+ rows in features.npz order; upstream initsetup(normed=False) library-normalises + log1p's it
27
+ rep_sc.h5ad raw UMI counts (float32 CSR) of every representative cell on the modeled genes,
28
+ obs['sample_ids'] = the representative row's sample id; upstream scprocess(normed=False)
29
+ inputs_manifest.json rows, genes, depth rule, source hashes
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import hashlib
35
+ import json
36
+ import os
37
+ import sys
38
+ from datetime import datetime, timezone
39
+ from pathlib import Path
40
+
41
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
42
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
43
+
44
+ import numpy as np
45
+ import pandas as pd
46
+ import scipy.sparse as sp
47
+
48
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
49
+ HERE = TASK / "scsemi"
50
+ sys.path.insert(0, str(TASK / "tools"))
51
+ import prepare_dataset as PD # noqa: E402 (the benchmark's own loader: bulk_raw with unmeasured NaN -> 0, masks, use)
52
+
53
+ SEED = 20260927
54
+
55
+
56
+ def sha(path: Path) -> str:
57
+ h = hashlib.sha256()
58
+ with open(path, "rb") as f:
59
+ for block in iter(lambda: f.read(1 << 24), b""):
60
+ h.update(block)
61
+ return h.hexdigest()
62
+
63
+
64
+ def split_rows(ds: str, mode: str, j: int, sample_ids: np.ndarray, folds: pd.DataFrame, n: int | None = None) -> dict:
65
+ data = TASK / "data" / ds
66
+ usable = folds["fold"].to_numpy() >= 0
67
+ donors = folds["donor_id"].astype(str).to_numpy()
68
+ extra = {}
69
+ if mode == "fewshot":
70
+ dd = data / "fewshot_n5" / f"draw{j}"
71
+ train_donors = [x.strip() for x in (dd / "train_donors.txt").read_text().splitlines() if x.strip()]
72
+ test = [x.strip() for x in (dd / "test_samples.txt").read_text().splitlines() if x.strip()]
73
+ cond = dd / "test_raw.npz"
74
+ sources = {"train_donors.txt": dd / "train_donors.txt", "test_samples.txt": dd / "test_samples.txt"}
75
+ rep = np.flatnonzero(np.isin(donors, train_donors) & usable)
76
+ elif mode == "cv":
77
+ fold = folds["fold"].to_numpy()
78
+ test = sample_ids[fold == j].tolist()
79
+ rep = np.flatnonzero(usable & (fold != j))
80
+ train_donors = sorted(set(donors[rep]))
81
+ cond = data / f"fold{j}" / "test_raw.npz"
82
+ sources = {}
83
+ elif mode == "budget":
84
+ fold = folds["fold"].to_numpy()
85
+ rj = TASK / "runs" / ds / f"fold{j}" / f"lora_n{n}" / "RUN.json"
86
+ run = json.loads(rj.read_text())
87
+ if run["fold"] != j or (run.get("train_subset") or {}).get("train_n") != n:
88
+ raise SystemExit(f"{rj}: not the fold {j} n={n} learning-curve run")
89
+ fit = list(run["train_rows"]) + list(run["inner_val_rows"])
90
+ test = sample_ids[fold == j].tolist()
91
+ if sorted(run["test_rows_never_loaded_for_training"]) != sorted(test):
92
+ raise SystemExit(f"{rj}: its test rows differ from fold {j}'s rows")
93
+ pos = {s: i for i, s in enumerate(sample_ids)}
94
+ if len(set(fit)) != len(fit) or any(s not in pos for s in fit):
95
+ raise SystemExit(f"{rj}: duplicate or unknown fit rows")
96
+ rep = np.asarray(sorted(pos[s] for s in fit), dtype=np.int64)
97
+ if not (usable[rep] & (fold[rep] != j)).all():
98
+ raise SystemExit(f"{rj}: a fit row is unusable or in fold {j}")
99
+ cb = data / "CAL_BUDGET.json"
100
+ if cb.exists():
101
+ e = json.loads(cb.read_text())["folds"][str(j)]["n"][str(n)]
102
+ if sorted(e["fit_sample_ids"]) != sorted(fit) or e["lora_checkpoint_sha256"] != run["checkpoint_sha256"]:
103
+ raise SystemExit(f"{cb}: fold {j} n={n} fit rows / LoRA checkpoint differ from {rj}")
104
+ train_donors = sorted(set(donors[rep]))
105
+ cond = data / f"fold{j}" / "test_raw.npz"
106
+ sources = {"lora_RUN.json": rj, **({"CAL_BUDGET.json": cb} if cb.exists() else {})}
107
+ extra = {"budget": {"n": int(n), "fold": int(j), "lora_run": str(rj), "lora_checkpoint_sha256": run["checkpoint_sha256"],
108
+ "n_train_rows": len(run["train_rows"]), "n_inner_val_rows": len(run["inner_val_rows"]),
109
+ "train_rows": list(run["train_rows"]), "inner_val_rows": list(run["inner_val_rows"])}}
110
+ else:
111
+ raise SystemExit(f"unknown mode {mode}")
112
+ pos = {s: i for i, s in enumerate(sample_ids)}
113
+ miss = [s for s in test if s not in pos]
114
+ if miss:
115
+ raise SystemExit(f"test samples not in features.npz: {miss[:5]}")
116
+ tgt = np.asarray([pos[s] for s in test], dtype=np.int64)
117
+ if not usable[tgt].all():
118
+ raise SystemExit("a test row is not usable (fold -1)")
119
+ if set(donors[rep]) & set(donors[tgt]):
120
+ raise SystemExit("a donor is both representative and target")
121
+ if len(set(test)) != len(test):
122
+ raise SystemExit("duplicate test samples")
123
+ return {"rep": rep, "tgt": tgt, "train_donors": train_donors, "test": test, "condition": cond, "sources": sources,
124
+ **extra}
125
+
126
+
127
+ def main(argv=None) -> int:
128
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
129
+ ap.add_argument("--dataset", required=True)
130
+ ap.add_argument("--mode", choices=["fewshot", "cv", "budget"], default="fewshot")
131
+ ap.add_argument("--draw", type=int, help="fewshot draw index")
132
+ ap.add_argument("--fold", type=int, help="cv / budget fold index")
133
+ ap.add_argument("--n", type=int, help="budget: the LoRA learning-curve n (runs/<ds>/fold<k>/lora_n<n>)")
134
+ ap.add_argument("--work", type=Path, required=True)
135
+ ap.add_argument("--smoke-reps", type=int, default=0, help="SMOKE ONLY: keep the first N representative rows")
136
+ ap.add_argument("--smoke-cells", type=int, default=0, help="SMOKE ONLY: at most N cells per representative")
137
+ ap.add_argument("--smoke-targets", default="", help="SMOKE ONLY: comma list of target sample ids")
138
+ ap.add_argument("--smoke-rep-ids", default="", help="SMOKE ONLY: comma list of representative sample ids to keep")
139
+ ap.add_argument("--check-only", action="store_true", help="dry run: check everything, write nothing under --work")
140
+ ap.add_argument("--check-out", type=Path, default=None, help="--check-only: write the split summary JSON here")
141
+ a = ap.parse_args(argv)
142
+ j = a.draw if a.mode == "fewshot" else a.fold
143
+ if j is None:
144
+ raise SystemExit("--draw (fewshot) or --fold (cv, budget) required")
145
+ if (a.mode == "budget") != (a.n is not None):
146
+ raise SystemExit("--n is required with --mode budget and only valid there")
147
+ smoke = bool(a.smoke_reps or a.smoke_cells or a.smoke_targets or a.smoke_rep_ids)
148
+ work = a.work.resolve()
149
+ if smoke and "/scsemi/smoke/" not in str(work) + "/":
150
+ raise SystemExit("smoke subsetting only under scsemi/smoke/")
151
+ out = work / "inputs"
152
+ if not a.check_only:
153
+ if (out / "inputs_manifest.json").exists():
154
+ raise SystemExit(f"{out}/inputs_manifest.json exists; inputs are immutable (preserve and inspect)")
155
+ out.mkdir(parents=True, exist_ok=True)
156
+ data = TASK / "data" / a.dataset
157
+ d = PD.load(data)
158
+ folds = pd.read_csv(data / "folds.csv")
159
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
160
+ raise SystemExit("folds.csv rows differ from features.npz")
161
+ s = split_rows(a.dataset, a.mode, j, d["sample_ids"], folds, n=a.n)
162
+ rep, tgt = s["rep"], s["tgt"]
163
+ if a.smoke_rep_ids:
164
+ keep_r = set(a.smoke_rep_ids.split(","))
165
+ rep = np.asarray([r for r in rep if d["sample_ids"][r] in keep_r], dtype=np.int64)
166
+ if a.smoke_reps:
167
+ rep = rep[: a.smoke_reps]
168
+ if a.smoke_targets:
169
+ keep = set(a.smoke_targets.split(","))
170
+ tgt = np.asarray([t for t in tgt if d["sample_ids"][t] in keep], dtype=np.int64)
171
+ s["test"] = [x for x in s["test"] if x in keep]
172
+ if a.mode == "fewshot" and not smoke:
173
+ usable = np.flatnonzero(folds["fold"].to_numpy() >= 0)
174
+ if set(rep.tolist()) | set(tgt.tolist()) != set(usable.tolist()):
175
+ raise SystemExit("representatives + targets do not cover the usable rows")
176
+ # modeled genes
177
+ z = np.load(data / "cells_panel6k.npz", allow_pickle=False)
178
+ panel = z["panel_gene_ids"].astype(str)
179
+ gpos = {g: i for i, g in enumerate(d["gene_ids"])}
180
+ pcanon = np.asarray([gpos[g] for g in panel], dtype=np.int64)
181
+ rows = np.sort(np.concatenate([rep, tgt]))
182
+ bulk_ok = d["bulk_valid"][rows][:, pcanon].all(0)
183
+ sc_ok = d["sc_valid"][rep][:, pcanon].all(0)
184
+ model_pidx = np.flatnonzero(bulk_ok & sc_ok)
185
+ genes = panel[model_pidx]
186
+ if genes.size < 1000:
187
+ raise SystemExit(f"only {genes.size} modeled genes")
188
+ # scorer's scoring genes (all rows of the dataset) for the record
189
+ score_mask = d["bulk_valid"][:, pcanon].all(0) & d["sc_valid"][:, pcanon].all(0)
190
+ # bulk
191
+ import anndata as ad
192
+ B = d["bulk"][rows][:, pcanon[model_pidx]].astype(np.float64)
193
+ if not np.isfinite(B).all() or (B < 0).any():
194
+ raise SystemExit("non-finite or negative bulk on the modeled genes")
195
+ if (B.sum(1) <= 0).any():
196
+ raise SystemExit("a bulk row has no counts on the modeled genes")
197
+ sym = pd.read_csv(TASK.parents[1] / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv")
198
+ sym = sym.set_index("gene_id").gene_symbol.astype(str)
199
+ var = pd.DataFrame({"gene_symbol": sym.reindex(genes).to_numpy()}, index=pd.Index(genes, name="gene_id"))
200
+ obs_b = pd.DataFrame({"sample_ids": d["sample_ids"][rows], "donor_id": d["donor_ids"][rows],
201
+ "group": d["groups"][rows], "role": np.where(np.isin(rows, rep), "representative", "target")},
202
+ index=pd.Index(d["sample_ids"][rows], name="obs"))
203
+ if not a.check_only:
204
+ ad.AnnData(X=B, obs=obs_b, var=var).write_h5ad(out / "bulk.h5ad")
205
+ # representative cells
206
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
207
+ rs = np.asarray(z["row_sample"], dtype=np.int64)
208
+ blocks, obs_rows, per_rep = [], [], []
209
+ rng = np.random.default_rng(SEED)
210
+ for r in rep:
211
+ cells = np.flatnonzero(rs == r)
212
+ if a.smoke_cells and cells.size > a.smoke_cells:
213
+ cells = np.sort(rng.choice(cells, a.smoke_cells, replace=False))
214
+ Xr = X[cells][:, model_pidx].tocsr().astype(np.float32)
215
+ lib = np.asarray(Xr.sum(1)).ravel()
216
+ if (lib <= 0).any():
217
+ raise SystemExit(f"{d['sample_ids'][r]}: {int((lib <= 0).sum())} cells without counts on the modeled genes")
218
+ blocks.append(Xr)
219
+ obs_rows.append(pd.DataFrame({"sample_ids": d["sample_ids"][r], "donor_id": d["donor_ids"][r],
220
+ "source_cell_row": cells}))
221
+ per_rep.append({"sample_id": str(d["sample_ids"][r]), "donor_id": str(d["donor_ids"][r]),
222
+ "group": str(d["groups"][r]), "n_cells": int(cells.size),
223
+ "median_umi_modeled_genes": float(np.median(lib))})
224
+ Xs = sp.vstack(blocks, format="csr")
225
+ obs_s = pd.concat(obs_rows, ignore_index=True)
226
+ obs_s.index = pd.Index([f"{a_}|{b_}" for a_, b_ in zip(obs_s.sample_ids, obs_s.source_cell_row)], name="cell")
227
+ if not a.check_only:
228
+ ad.AnnData(X=Xs, obs=obs_s, var=var.copy()).write_h5ad(out / "rep_sc.h5ad")
229
+ lib_all = np.asarray(Xs.sum(1)).ravel()
230
+ depth = float(np.median(lib_all))
231
+ cond = s["condition"]
232
+ man = {
233
+ "schema": "scsemi_paired.inputs.v1", "written_utc": datetime.now(timezone.utc).isoformat(),
234
+ "dataset": a.dataset, "mode": a.mode, "split": j, "smoke": smoke,
235
+ "smoke_settings": {"reps": a.smoke_reps, "cells": a.smoke_cells, "targets": a.smoke_targets,
236
+ "rep_ids": a.smoke_rep_ids} if smoke else None,
237
+ "train_donors": s["train_donors"],
238
+ "representatives": per_rep, "targets": [str(x) for x in d["sample_ids"][tgt]],
239
+ "target_order_test_samples": s["test"],
240
+ "bulk_row_order": [str(x) for x in d["sample_ids"][rows]],
241
+ "n_representatives": int(rep.size), "n_targets": int(tgt.size), "n_rep_cells": int(Xs.shape[0]),
242
+ "modeled_genes": {"n": int(genes.size), "gene_ids": genes.tolist(), "panel_index": model_pidx.tolist(),
243
+ "rule": "6k panel genes with bulk_valid in every rep+target row and sc_valid in every rep row",
244
+ "equals_scorer_scoring_genes": bool(np.array_equal(model_pidx, np.flatnonzero(score_mask))),
245
+ "n_scorer_scoring_genes": int(score_mask.sum())},
246
+ "depth": {"value": depth, "rule": "median over all representative cells (all rows of the training donors) of the "
247
+ "per-cell UMI sum on the modeled genes; every generated cell is scaled to this expected library",
248
+ "n_cells": int(lib_all.size)},
249
+ "condition_npz": str(cond), "condition_sha256": sha(cond),
250
+ "sources": {"features.npz": sha(data / "features.npz"), "folds.csv": sha(data / "folds.csv"),
251
+ "cells_panel6k.npz": sha(data / "cells_panel6k.npz"),
252
+ **{k: sha(v) for k, v in s["sources"].items()}},
253
+ "files": ({"bulk.h5ad": sha(out / "bulk.h5ad"), "rep_sc.h5ad": sha(out / "rep_sc.h5ad")}
254
+ if not a.check_only else None),
255
+ "builder_sha256": sha(Path(__file__)),
256
+ }
257
+ if a.mode == "budget":
258
+ man["target_donors"] = sorted({str(x) for x in d["donor_ids"][tgt]})
259
+ man["budget"] = s["budget"]
260
+ with np.load(cond, allow_pickle=False) as cz:
261
+ cond_ids = cz["sample_ids"].astype(str).tolist()
262
+ if not smoke and sorted(cond_ids) != sorted(man["targets"]):
263
+ raise SystemExit("condition NPZ sample_ids differ from the targets")
264
+ man["condition_sample_order"] = cond_ids
265
+ if a.check_only:
266
+ summary = {"dataset": a.dataset, "mode": a.mode, "split": j, "n": a.n, "work": str(work),
267
+ "reps": [r["sample_id"] for r in per_rep], "targets": man["targets"],
268
+ "rep_cells": {r["sample_id"]: r["n_cells"] for r in per_rep}, "n_rep_cells": int(Xs.shape[0]),
269
+ "modeled_genes": int(genes.size), "modeled_panel_index": model_pidx.tolist(),
270
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"],
271
+ "depth": depth, "condition_npz": str(cond), "condition_matches_targets": True,
272
+ "train_donors": s["train_donors"], **({"budget": s["budget"]} if a.mode == "budget" else {})}
273
+ if a.check_out is not None:
274
+ a.check_out.parent.mkdir(parents=True, exist_ok=True)
275
+ a.check_out.write_text(json.dumps(summary, indent=1) + "\n")
276
+ print(json.dumps({k: summary[k] for k in ("dataset", "mode", "split", "n", "n_rep_cells", "modeled_genes",
277
+ "equals_scorer_genes", "depth")} | {"reps": len(summary["reps"]),
278
+ "targets": len(summary["targets"])}))
279
+ return 0
280
+ tmp = out / "inputs_manifest.json.tmp"
281
+ tmp.write_text(json.dumps(man, indent=1) + "\n")
282
+ tmp.replace(out / "inputs_manifest.json")
283
+ print(json.dumps({"dataset": a.dataset, "mode": a.mode, "split": j, "reps": int(rep.size), "targets": int(tgt.size),
284
+ "rep_cells": int(Xs.shape[0]), "modeled_genes": int(genes.size),
285
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"], "depth": depth}))
286
+ return 0
287
+
288
+
289
+ if __name__ == "__main__":
290
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/backups/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_scsemi_paired.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Pinned scSemiProfiler in its native paired-representative mode, real bulk, gene sets on (resumable).
3
+
4
+ Phases (each invocation does a bounded amount of work and exits; receipts make every step skippable):
5
+ prepare CPU. upstream initsetup(bulk, normed=False) + fixed representatives + upstream nearest-representative
6
+ assignment (representative_selection.update_membership on processed_bulkdata.obsm['X_pca']) +
7
+ upstream scprocess(rep cells, normed=False, threshold 1e-3, geneset=True, k=15).
8
+ pretrain GPU (via ml-run only). Per representative: fastrecon (VAE100/GAN100, lr 1e-3) then reconst_pretrain2
9
+ (VAE50/GAN50, lr 1e-4), exactly the calls upstream scinfer() makes. --max-reps bounds one call.
10
+ infer GPU (via ml-run only). Per target: fast_semi(rep, target, rep's pretrain-2 model, bulktype='real',
11
+ pseudocount 0.1, lr 2e-4, 150 epochs x 5 ministages), the call upstream scinfer() makes.
12
+ The upstream dense output is re-encoded losslessly as CSR (verified equal) with a receipt holding the
13
+ per-target runtime. --max-targets bounds one call.
14
+
15
+ CUDA work belongs to the coordinating agent and must run through ml-run. No automatic retries. Partial
16
+ outputs are preserved; an unreceipted upstream artefact stops the run for inspection.
17
+ --smoke (only under scsemi/smoke/, CPU) shrinks the epoch budget to exercise the plumbing.
18
+
19
+ Opt-in additions 2026-10-02 (without these flags every phase behaves and signs exactly as before):
20
+ --lean-hvset prepare computes hvset.npy with tools/lean_hvset.cohort_hvset_lean (one representative in memory;
21
+ output-identical to cohort_hvset, validation/hvset_dependence_20261002.json). Needed for CV folds,
22
+ whose dense cohort hvset needs ~70 KiB per representative cell (above the 16 GiB CPU cap). Recorded
23
+ in the run binding, so pass it on every phase of that work dir.
24
+ --reuse-from W (equal-budget splits) the split's representatives are a subset of the prepared run W of the same
25
+ fold (its CV run). prepare copies W's hvset.npy instead of selecting one, then runs upstream
26
+ scprocess per representative and refuses unless every sample_sc/<r>.h5ad and geneset_scores/<r>.npy
27
+ is byte-identical to W's (prepared.json); pretraining seeds are W's (base + 1000/2000 + row index in
28
+ W's bulk order). Phase 'link' (CPU) then hard-links W's receipted pretrain checkpoints with receipts
29
+ naming their source; a representative without one is pretrained by phase 'pretrain' with W's seed,
30
+ which gives the same bytes (GPU pretraining is bit-reproducible: README "Reuse of pretraining").
31
+ Refuses when W's representatives include any of this split's targets. Recorded in the binding.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ from datetime import datetime, timezone
37
+ import fcntl
38
+ import gc
39
+ import hashlib
40
+ import importlib.metadata
41
+ import json
42
+ import os
43
+ from pathlib import Path
44
+ import re
45
+ import resource
46
+ import shutil
47
+ import sys
48
+ import time
49
+ import types
50
+
51
+ HERE = Path(__file__).resolve().parents[1]
52
+ SEED = 20260927
53
+ MIGRATIONS = HERE / "compat_migrations.json" # approved code transitions a run may migrate across
54
+ MIGRATABLE = {"source", "wrapper_sha256"} # binding components an approved transition may change
55
+ PROTOCOL = {
56
+ "method": "scSemiProfiler", "setting": "paired_fixed_representatives_realbulk_genesets",
57
+ "upstream_commit": "c2aea021188759e56ecf14578915c0237aaa75d2",
58
+ "initsetup": {"logged": False, "normed": False, "geneselection": False, "batch": 1},
59
+ "scprocess": {"logged": False, "normed": False, "cellfilter": False, "threshold": 0.001, "geneset": True,
60
+ "weight": 0.5, "k": 15},
61
+ "representatives": "fixed: every usable row of the split's training donors (no active learning)",
62
+ "assignment": "upstream representative_selection.update_membership: nearest representative by Euclidean "
63
+ "distance in processed_bulkdata.obsm['X_pca'] (initsetup PCA of log1p CP10K real bulk)",
64
+ "pretrain1": {"vaesteps": 100, "gansteps": 100, "lr": 1e-3, "k": 15, "diagw": 1},
65
+ "pretrain2": {"vaesteps": 50, "gansteps": 50, "lr": 1e-4, "k": 15, "diagw": 1.0},
66
+ "infer": {"bulktype": "real", "pseudocount": 0.1, "lr": 2e-4, "epochs": 150, "ministages": 5, "k": 15,
67
+ "diagw": 1.0},
68
+ "seeds": {"base": SEED, "pretrain1": "base + 1000 + bulk row index", "pretrain2": "base + 2000 + bulk row index",
69
+ "target": "base + bulk row index (frozen campaign rule)"},
70
+ "output_unit": "normalized_expression (upstream fast_semi output: ZINB mean, rep-cell library, values <= 10 zeroed)",
71
+ "cellgraph_impl": "tools/lean_cellgraph.fast_cellgraph_lean replaces upstream singlecell_process.fast_cellgraph "
72
+ "inside scprocess: same arithmetic, chunked (16 GiB CPU cap); bit-identical outputs verified "
73
+ "(validation/lean_cellgraph_*.json)",
74
+ "scprocess_orchestration": "cohort hvset first (upstream scprocess's own steps: sorted sample_ids, normalize_total "
75
+ "1e4, dense, X*(X>10), getGeneSetMatrix score formula, concatenate, log1p, "
76
+ "highly_variable_genes) -> hvset.npy; then upstream scprocess once per representative "
77
+ "(it skips hvset when hvset.npy exists). Bit-identical to one scprocess call over all "
78
+ "representatives (validation/prepared_*.json); peak memory is one representative",
79
+ }
80
+
81
+
82
+ def cohort_hvset(project: Path, rep_sc: Path, threshold: float) -> "np.ndarray":
83
+ """Upstream scprocess's hvset block, run representative by representative (same order, same arithmetic)."""
84
+ import numpy as np
85
+ import anndata
86
+ import scanpy as sc
87
+ from scSemiProfiler.singlecell_process import getGeneSetMatrix
88
+ R = anndata.read_h5ad(rep_sc)
89
+ sids = np.unique(R.obs["sample_ids"])
90
+ zps = []
91
+ for sid in sids:
92
+ a = R[(R.obs["sample_ids"] == sid).to_numpy()].copy()
93
+ sc.pp.normalize_total(a, target_sum=1e4)
94
+ X = np.array(a.X.todense())
95
+ X = X * np.array(X > 1e4 * threshold)
96
+ genes_upper = [g.upper() for g in list(a.var.index)]
97
+ gene_set_matrix, _ = getGeneSetMatrix("c2.cp.v7.4.symbols.gmt", genes_upper, "genesets/")
98
+ zp = X.dot(np.array(gene_set_matrix).T)
99
+ eps = 1e-6
100
+ den = (np.array(gene_set_matrix.sum(axis=1)) + eps)
101
+ zp = (zp + eps) / den
102
+ zp = zp - eps / den
103
+ zps.append(zp)
104
+ del a, X
105
+ zps = np.concatenate(zps, axis=0)
106
+ zdata = anndata.AnnData(zps)
107
+ sc.pp.log1p(zdata)
108
+ sc.pp.highly_variable_genes(zdata)
109
+ hvset = zdata.var.highly_variable
110
+ np.save(str(project) + "/hvset.npy", hvset)
111
+ return np.asarray(hvset)
112
+ SMOKE_BUDGET = {"pretrain1": {"vaesteps": 1, "gansteps": 1}, "pretrain2": {"vaesteps": 1, "gansteps": 1},
113
+ "infer": {"epochs": 2}}
114
+
115
+
116
+ def sha256(path: Path) -> str:
117
+ digest = hashlib.sha256()
118
+ with Path(path).open("rb") as stream:
119
+ for chunk in iter(lambda: stream.read(16 * 1024 * 1024), b""):
120
+ digest.update(chunk)
121
+ return digest.hexdigest()
122
+
123
+
124
+ def write_json(path: Path, value: dict) -> None:
125
+ path.parent.mkdir(parents=True, exist_ok=True)
126
+ tmp = path.with_name(path.name + ".tmp")
127
+ with tmp.open("w") as stream:
128
+ json.dump(value, stream, indent=1, default=str)
129
+ stream.write("\n")
130
+ stream.flush()
131
+ os.fsync(stream.fileno())
132
+ tmp.replace(path)
133
+
134
+
135
+ def canonical_sha(value) -> str:
136
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
137
+
138
+
139
+ def resolve_run_identity(run_file: Path, binding: dict, code_signature: str) -> tuple[str, list]:
140
+ """The run's identity is the signature it was created with (every receipt is signed with it). A later code
141
+ version may continue the run only if its binding differs from the run's latest binding in MIGRATABLE components
142
+ alone and each change is an approved transition in compat_migrations.json; the migration is appended to
143
+ run_manifest.json. Anything else refuses, as before."""
144
+ rec = json.loads(run_file.read_text())
145
+ identity = rec["run_signature"]
146
+ migrations = rec.get("migrations", [])
147
+ if migrations:
148
+ last, last_sig = migrations[-1]["to_binding"], migrations[-1]["to_code_signature"]
149
+ else:
150
+ last, last_sig = {k: rec.get(k) for k in binding}, identity
151
+ if canonical_sha(last) != identity:
152
+ raise SystemExit("run_manifest.json binding does not hash to its run_signature; inspect")
153
+ if last == binding:
154
+ return identity, migrations
155
+ changed = sorted(k for k in set(last) | set(binding) if last.get(k) != binding.get(k))
156
+ if set(changed) - MIGRATABLE:
157
+ raise SystemExit(f"work dir belongs to different inputs/code/environment ({changed}); use a fresh work dir")
158
+ approved = json.loads(MIGRATIONS.read_text())["transitions"] if MIGRATIONS.exists() else []
159
+ used = []
160
+ for k in changed:
161
+ frm = canonical_sha(last[k]) if k == "source" else last[k]
162
+ to = canonical_sha(binding[k]) if k == "source" else binding[k]
163
+ hit = [x for x in approved if x["component"] == k and x["from"] == frm and x["to"] == to]
164
+ if not hit:
165
+ raise SystemExit(f"code change in {k} ({str(frm)[:12]} -> {str(to)[:12]}) is not an approved migration "
166
+ f"in {MIGRATIONS.name}; use a fresh work dir")
167
+ used.append(hit[0]["id"])
168
+ migrations = migrations + [{"at": datetime.now(timezone.utc).isoformat(), "host": os.uname().nodename,
169
+ "from_code_signature": last_sig, "to_code_signature": code_signature,
170
+ "changed": changed, "transitions": used, "to_binding": binding}]
171
+ rec["migrations"] = migrations
172
+ write_json(run_file, rec)
173
+ return identity, migrations
174
+
175
+
176
+ REUSE_PROTOCOL_KEYS = ("upstream_commit", "scprocess", "pretrain1", "pretrain2", "seeds", "cellgraph_impl",
177
+ "scprocess_orchestration")
178
+ REUSE_BINDING_KEYS = ("source", "environment", "wrapper_sha256", "lean_cellgraph_sha256", "geneset_mapped_gmt_sha256")
179
+
180
+
181
+ def load_reuse_source(src: Path, work: Path, man: dict, protocol: dict, binding: dict) -> dict:
182
+ """--reuse-from: the source run W whose hvset and pretraining this split reuses. Everything a representative's
183
+ pretraining depends on besides its own cells must be W's: hvset (copied), gene axis, scprocess / pretrain protocol,
184
+ vendor source, environment, wrapper, cell-graph code, gene-set asset; the seeds are W's. W's representatives must
185
+ be a superset of this split's and must not contain any of its targets (W's hvset was selected on W's cells)."""
186
+ if src == work:
187
+ raise SystemExit("--reuse-from points at this work dir")
188
+ for f in ("run_manifest.json", "prepared.json", "inputs/inputs_manifest.json"):
189
+ if not (src / f).exists():
190
+ raise SystemExit(f"--reuse-from {src}: {f} missing (prepare the source run first)")
191
+ srun = json.loads((src / "run_manifest.json").read_text())
192
+ sprep = json.loads((src / "prepared.json").read_text())
193
+ sman = json.loads((src / "inputs/inputs_manifest.json").read_text())
194
+ if sprep["run_signature"] != srun["run_signature"]:
195
+ raise SystemExit(f"--reuse-from {src}: prepared.json belongs to another run signature")
196
+ sb = srun["migrations"][-1]["to_binding"] if srun.get("migrations") else srun
197
+ why = []
198
+ if sman["dataset"] != man["dataset"] or bool(sman.get("smoke")) != bool(man.get("smoke")):
199
+ why.append("dataset / smoke flag")
200
+ if sman["modeled_genes"]["gene_ids"] != man["modeled_genes"]["gene_ids"]:
201
+ why.append("modeled gene axis")
202
+ why += [f"protocol.{k}" for k in REUSE_PROTOCOL_KEYS if sb["protocol"].get(k) != protocol.get(k)]
203
+ why += [k for k in REUSE_BINDING_KEYS if sb.get(k) != binding.get(k)]
204
+ s_reps = {r["sample_id"] for r in sman["representatives"]}
205
+ reps = [r["sample_id"] for r in man["representatives"]]
206
+ if not set(reps) <= s_reps:
207
+ why.append(f"representatives not in the source run: {sorted(set(reps) - s_reps)[:5]}")
208
+ if "target_donors" not in man:
209
+ why.append("inputs manifest has no target_donors (build the split with --mode budget)")
210
+ else:
211
+ s_donors = {r["donor_id"] for r in sman["representatives"]}
212
+ if set(man["targets"]) & s_reps or set(man["target_donors"]) & s_donors:
213
+ why.append("a target (row or donor) is a representative of the source run")
214
+ if why:
215
+ raise SystemExit(f"--reuse-from {src} refused: {why}")
216
+ order = sman["bulk_row_order"]
217
+ return {"binding": {"work": str(src), "run_signature": srun["run_signature"],
218
+ "hvset_sha256": sprep["files"]["hvset.npy"],
219
+ "seed_rule": "pretrain seeds = the source run's: base + 1000/2000 + row index in its bulk_row_order"},
220
+ "src": src, "prep": sprep, "signature": srun["run_signature"],
221
+ "seed_index": {r: order.index(r) for r in reps}}
222
+
223
+
224
+ def main(argv=None) -> int:
225
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
226
+ ap.add_argument("--work", type=Path, required=True)
227
+ ap.add_argument("--phase", choices=["prepare", "pretrain", "infer", "status", "link"], required=True)
228
+ ap.add_argument("--device", default="cuda:0")
229
+ ap.add_argument("--threads", type=int, default=4)
230
+ ap.add_argument("--max-reps", type=int, default=0, help="pretrain: at most N representatives this call (0 = all)")
231
+ ap.add_argument("--max-targets", type=int, default=0, help="infer: at most N targets this call (0 = all)")
232
+ ap.add_argument("--smoke", action="store_true")
233
+ ap.add_argument("--lean-hvset", action="store_true", help="prepare: streamed, output-identical hvset (see docstring)")
234
+ ap.add_argument("--reuse-from", type=Path, default=None, help="prepared source run whose hvset / pretraining is reused")
235
+ a = ap.parse_args(argv)
236
+ if not 1 <= a.threads <= 6:
237
+ ap.error("--threads must be 1..6")
238
+ if a.phase == "link" and a.reuse_from is None:
239
+ ap.error("--phase link needs --reuse-from")
240
+ for name in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
241
+ os.environ[name] = str(a.threads)
242
+ work = a.work.resolve()
243
+ if a.smoke and "/scsemi/smoke/" not in str(work) + "/":
244
+ raise SystemExit("--smoke only under scsemi/smoke/")
245
+ if a.phase in ("prepare", "status", "link") and a.device != "cpu":
246
+ a.device = "cpu"
247
+ if a.device == "cpu" and os.environ.get("CUDA_VISIBLE_DEVICES") != "":
248
+ raise SystemExit("CPU phases require CUDA_VISIBLE_DEVICES=''")
249
+ if a.device.startswith("cuda") and a.smoke:
250
+ raise SystemExit("smoke runs are CPU only")
251
+ inputs = work / "inputs"
252
+ project = work / "scsemi_project"
253
+ events = work / "events.jsonl"
254
+ protocol = json.loads(json.dumps(PROTOCOL))
255
+ if a.smoke:
256
+ for k, v in SMOKE_BUDGET.items():
257
+ protocol[k].update(v)
258
+ protocol["SMOKE"] = "reduced epoch budget; plumbing test only, never a benchmark output"
259
+ if a.lean_hvset and a.reuse_from is None:
260
+ protocol["hvset_impl"] = ("tools/lean_hvset.cohort_hvset_lean: streamed, one representative in memory; "
261
+ "output-identical to cohort_hvset (validation/hvset_dependence_20261002.json)")
262
+
263
+ def event(kind: str, **values) -> None:
264
+ v = {"at": datetime.now(timezone.utc).isoformat(), "event": kind, "phase": a.phase, **values,
265
+ "max_rss_gib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**20, 2)}
266
+ with events.open("a") as s:
267
+ s.write(json.dumps(v, default=str) + "\n")
268
+ s.flush()
269
+ os.fsync(s.fileno())
270
+ print(json.dumps(v, default=str), flush=True)
271
+
272
+ # shared code lock: tools/compat_patch_*.py replaces vendor files under the exclusive lock, so this call never
273
+ # verifies or imports a half-updated vendor; released once the vendor modules are imported
274
+ code_lock = open(HERE / ".code_update.lock", "a")
275
+ fcntl.flock(code_lock, fcntl.LOCK_SH)
276
+ man = json.loads((inputs / "inputs_manifest.json").read_text())
277
+ if bool(man.get("smoke")) != a.smoke:
278
+ raise SystemExit("smoke flag differs from the inputs' smoke flag")
279
+ for name, digest in man["files"].items():
280
+ if sha256(inputs / name) != digest:
281
+ raise SystemExit(f"input {name} differs from its manifest")
282
+ vendor = HERE / "vendor/scSemiProfiler"
283
+ source = json.loads((vendor.parent / "source_manifest.json").read_text())
284
+ for name, expected in source["files"].items():
285
+ if sha256(vendor / name) != expected:
286
+ raise SystemExit(f"vendor source hash mismatch: {name}")
287
+ assets = json.loads((HERE / "genesets/geneset_assets.json").read_text())
288
+ gmt_src = HERE / "genesets/c2.cp.v7.4.symbols.gmt"
289
+ if sha256(gmt_src) != assets["mapped_gmt_sha256"] or sha256(vendor / "genesets/c2.cp.v7.4.symbols.gmt") != assets["original_gmt_sha256"]:
290
+ raise SystemExit("gene-set asset hash mismatch")
291
+ versions = {n: importlib.metadata.version(n) for n in ["torch", "scvi-tools", "scanpy", "anndata", "lightning",
292
+ "numpy", "scikit-learn", "faiss-cpu", "gseapy"]}
293
+ binding = {"protocol": protocol, "inputs": man["files"], "source": source, "environment": versions,
294
+ "wrapper_sha256": sha256(Path(__file__)), "lean_cellgraph_sha256": sha256(HERE / "tools/lean_cellgraph.py"),
295
+ "geneset_mapped_gmt_sha256": assets["mapped_gmt_sha256"]}
296
+ if a.lean_hvset and a.reuse_from is None:
297
+ binding["lean_hvset_sha256"] = sha256(HERE / "tools/lean_hvset.py")
298
+ reuse = None
299
+ if a.reuse_from is not None:
300
+ reuse = load_reuse_source(a.reuse_from.resolve(), work, man, protocol, binding)
301
+ binding["reuse"] = reuse["binding"]
302
+ code_signature = canonical_sha(binding)
303
+ run_file = work / "run_manifest.json"
304
+ migrations: list = []
305
+ if run_file.exists():
306
+ signature, migrations = resolve_run_identity(run_file, binding, code_signature)
307
+ else:
308
+ signature = code_signature
309
+ reps = [r["sample_id"] for r in man["representatives"]]
310
+ targets = list(man["target_order_test_samples"])
311
+ sids_expected = man["bulk_row_order"]
312
+ for s_ in sids_expected:
313
+ if not re.fullmatch(r"[A-Za-z0-9_.+-]+", s_):
314
+ raise SystemExit(f"unsafe sample id {s_!r}")
315
+ if not run_file.exists():
316
+ write_json(run_file, {"run_signature": signature, **binding, "work": str(work), "hostname": os.uname().nodename})
317
+
318
+ def status() -> dict:
319
+ pre = json.loads((work / "prepared.json").read_text()) if (work / "prepared.json").exists() else None
320
+ done_r = [r for r in reps if all((project / "models" / f"{b}{r}.receipt.json").exists()
321
+ for b in ("fast_reconst1_", "fastreconst2_"))]
322
+ done_t = [t for t in targets if (work / "shards" / f"{t}.json").exists()]
323
+ st = {"prepared": pre is not None, "n_reps": len(reps), "reps_pretrained": len(done_r),
324
+ "n_targets": len(targets), "targets_done": len(done_t),
325
+ "pretrain_complete": len(done_r) == len(reps), "infer_complete": len(done_t) == len(targets),
326
+ "run_signature": signature, "updated": datetime.now(timezone.utc).isoformat()}
327
+ write_json(work / "status.json", st)
328
+ return st
329
+
330
+ if a.phase == "status":
331
+ fcntl.flock(code_lock, fcntl.LOCK_UN)
332
+ print(json.dumps(status()))
333
+ return 0
334
+
335
+ import numpy as np
336
+ import anndata
337
+ import scipy.sparse as sp
338
+ sys.path.insert(0, str(vendor))
339
+ import torch
340
+ import scvi
341
+ import scSemiProfiler
342
+ from scSemiProfiler.inference import fastrecon, reconst_pretrain2, fast_semi
343
+ from scSemiProfiler.representative_selection import update_membership
344
+ fcntl.flock(code_lock, fcntl.LOCK_UN)
345
+ torch.set_num_threads(a.threads)
346
+ os.chdir(work) # upstream reads "genesets/" and writes vaegan_train.txt relative to the cwd
347
+ event("start", run_signature=signature, code_signature=code_signature,
348
+ migrations=[m["transitions"] for m in migrations], device=a.device, host=os.uname().nodename)
349
+ try:
350
+ # ------------------------------------------------------------------ prepare (CPU)
351
+ prep = work / "prepared.json"
352
+ if a.phase == "prepare":
353
+ if prep.exists():
354
+ event("prepare_already_done")
355
+ status()
356
+ return 0
357
+ if project.exists():
358
+ raise SystemExit("partial upstream project without prepared.json; preserve and inspect")
359
+ gdir = work / "genesets"
360
+ gdir.mkdir(exist_ok=True)
361
+ shutil.copyfile(gmt_src, gdir / "c2.cp.v7.4.symbols.gmt")
362
+ t0 = time.monotonic()
363
+ P = protocol["initsetup"]
364
+ scSemiProfiler.initsetup(str(project), str(inputs / "bulk.h5ad"), logged=P["logged"], normed=P["normed"],
365
+ geneselection=P["geneselection"], batch=P["batch"])
366
+ if not (project / "processed_bulkdata.h5ad").exists():
367
+ raise SystemExit("upstream initsetup did not write processed_bulkdata.h5ad")
368
+ sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
369
+ if sids != sids_expected:
370
+ raise SystemExit("upstream sids.txt differs from the input bulk order")
371
+ rep_idx = [sids.index(r) for r in reps]
372
+ scSemiProfiler.set_representatives(str(project), rep_idx)
373
+ bulk = anndata.read_h5ad(project / "processed_bulkdata.h5ad")
374
+ pca = np.asarray(bulk.obsm["X_pca"], dtype=np.float64)
375
+ labels = update_membership(reduced_bulk=pca, representatives=rep_idx)
376
+ (project / "status/init_cluster_labels.txt").write_text("".join(f"{int(x)}\n" for x in labels))
377
+ dist = np.sqrt(((pca[:, None, :] - pca[rep_idx][None, :, :]) ** 2).sum(-1))
378
+ assign = {t: {"representative": reps[int(labels[sids.index(t)])],
379
+ "distances": {reps[i]: float(dist[sids.index(t), i]) for i in range(len(reps))}} for t in targets}
380
+ for i, r in enumerate(reps):
381
+ if int(labels[sids.index(r)]) != i:
382
+ raise SystemExit(f"representative {r} not assigned to itself")
383
+ write_json(work / "assignment.json", {"rule": protocol["assignment"], "n_pca_components": int(pca.shape[1]),
384
+ "bulk_row_order": sids, "representative_indices": rep_idx,
385
+ "targets": assign,
386
+ "targets_per_representative": {r: sum(v["representative"] == r for v in assign.values()) for r in reps}})
387
+ del bulk
388
+ S = protocol["scprocess"]
389
+ import scSemiProfiler.singlecell_process as upstream_sp
390
+ sys.path.insert(0, str(HERE / "tools"))
391
+ from lean_cellgraph import fast_cellgraph_lean
392
+ upstream_sp.fast_cellgraph = fast_cellgraph_lean # resolved from module globals inside scprocess
393
+ if S["logged"] or S["normed"] or S["cellfilter"] or S["geneset"] is not True:
394
+ raise SystemExit("cohort_hvset replicates the logged=False, normed=False, cellfilter=False, geneset=True path only")
395
+ (project / "geneset_scores").mkdir(exist_ok=True)
396
+ if reuse is not None: # the source run's hvset (byte copy, sha-checked); upstream scprocess skips hvset
397
+ src_hv = reuse["src"] / "scsemi_project/hvset.npy"
398
+ if sha256(src_hv) != reuse["binding"]["hvset_sha256"]:
399
+ raise SystemExit(f"{src_hv} differs from the source run's prepared.json")
400
+ shutil.copyfile(src_hv, project / "hvset.npy")
401
+ event("hvset_copied_from_source", source=str(reuse["src"]))
402
+ elif a.lean_hvset:
403
+ from lean_hvset import cohort_hvset_lean
404
+ cohort_hvset_lean(project, inputs / "rep_sc.h5ad", S["threshold"])
405
+ event("cohort_hvset_done", impl="lean_hvset")
406
+ else:
407
+ cohort_hvset(project, inputs / "rep_sc.h5ad", S["threshold"])
408
+ event("cohort_hvset_done")
409
+ R = anndata.read_h5ad(inputs / "rep_sc.h5ad")
410
+ per_rep = work / "inputs_per_rep"
411
+ per_rep.mkdir(exist_ok=True)
412
+ for r in reps:
413
+ f_r = per_rep / f"{r}.h5ad"
414
+ R[(R.obs["sample_ids"] == r).to_numpy()].copy().write_h5ad(f_r)
415
+ scSemiProfiler.scprocess(str(project), str(f_r), logged=S["logged"], normed=S["normed"],
416
+ cellfilter=S["cellfilter"], threshold=S["threshold"], geneset=S["geneset"],
417
+ weight=S["weight"], k=S["k"])
418
+ f_r.unlink()
419
+ gc.collect()
420
+ per_rep.rmdir()
421
+ del R
422
+ genes = man["modeled_genes"]["gene_ids"]
423
+ if np.load(project / "hvgenes.npy", allow_pickle=True).astype(str).tolist() != genes:
424
+ raise SystemExit("upstream altered the modeled gene axis")
425
+ hvset = np.load(project / "hvset.npy", allow_pickle=False).astype(bool)
426
+ if hvset.shape != (2922,) or not hvset.any():
427
+ raise SystemExit("no variable gene-set features selected; refuse silent no-geneset fallback")
428
+ qc = {"selected_gene_sets": int(hvset.sum()), "reps": {}}
429
+ for r in reps:
430
+ f_sc, f_gs = project / "sample_sc" / f"{r}.h5ad", project / "geneset_scores" / f"{r}.npy"
431
+ if not f_sc.exists() or not f_gs.exists():
432
+ raise SystemExit(f"upstream scprocess did not write {r}")
433
+ g = np.load(f_gs, allow_pickle=False)
434
+ if not np.isfinite(g).all() or (g < 0).any():
435
+ raise SystemExit(f"{r}: non-finite / negative gene-set scores")
436
+ h = anndata.read_h5ad(f_sc, backed="r")
437
+ X = np.asarray(h.X[:])
438
+ n_feat = len(h.uns["feature_var"])
439
+ if h.var_names.astype(str).tolist() != genes or n_feat != len(genes) + int(hvset.sum()):
440
+ raise SystemExit(f"{r}: prepared axis / feature variance length mismatch")
441
+ glib = X.sum(1)
442
+ slib = g[:, hvset].sum(1)
443
+ h.file.close()
444
+ if g.shape[0] != X.shape[0]:
445
+ raise SystemExit(f"{r}: gene-set score rows differ from cells")
446
+ if (glib <= 0).any() or (slib <= 0).any():
447
+ raise SystemExit(f"{r}: {int((glib <= 0).sum())} cells with empty thresholded gene library, "
448
+ f"{int((slib <= 0).sum())} with empty selected gene-set library (log would be -inf)")
449
+ qc["reps"][r] = {"n_cells": int(X.shape[0]), "median_thresholded_gene_library": float(np.median(glib)),
450
+ "median_nonzero_genes": float(np.median((X > 0).sum(1))),
451
+ "zero_score_pathways": int(np.all(g == 0, axis=0).sum())}
452
+ del X, g
453
+ files = ["processed_bulkdata.h5ad", "hvgenes.npy", "sids.txt", "hvset.npy", "hvmask.npy",
454
+ "status/init_representatives.txt", "status/init_cluster_labels.txt"]
455
+ files += [f"sample_sc/{r}.h5ad" for r in reps] + [f"geneset_scores/{r}.npy" for r in reps]
456
+ write_json(work / "geneset_feature_qc.json", {"run_signature": signature, **qc})
457
+ file_sha = {f: sha256(project / f) for f in files}
458
+ extra = {}
459
+ if reuse is not None: # every pretraining input of every representative must be the source run's bytes
460
+ keys = ["hvset.npy"] + [f"sample_sc/{r}.h5ad" for r in reps] + [f"geneset_scores/{r}.npy" for r in reps]
461
+ bad = [k for k in keys if file_sha[k] != reuse["prep"]["files"].get(k)]
462
+ if bad:
463
+ raise SystemExit(f"prepared files differ from the source run {reuse['src']}: {bad[:6]}")
464
+ extra["reuse_check"] = {"source_work": str(reuse["src"]), "source_run_signature": reuse["signature"],
465
+ "identical_files": keys, "all_identical": True}
466
+ event("reuse_check_passed", n_files=len(keys))
467
+ write_json(prep, {"run_signature": signature, "seconds": round(time.monotonic() - t0, 1),
468
+ "files": file_sha,
469
+ "genesets_gmt_sha256": sha256(gdir / "c2.cp.v7.4.symbols.gmt"), **extra})
470
+ event("prepared", seconds=round(time.monotonic() - t0, 1), selected_gene_sets=int(hvset.sum()))
471
+ status()
472
+ return 0
473
+
474
+ # ------------------------------------------------------------------ GPU phases
475
+ if not prep.exists():
476
+ raise SystemExit("run --phase prepare first")
477
+ prepared = json.loads(prep.read_text())
478
+ if prepared["run_signature"] != signature:
479
+ raise SystemExit("prepared.json belongs to another run signature")
480
+ for name, digest in prepared["files"].items():
481
+ if name.startswith("sample_sc/"):
482
+ continue # large; verified per representative when used
483
+ if sha256(project / name) != digest:
484
+ raise SystemExit(f"prepared file changed: {name}")
485
+ sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
486
+ assign = json.loads((work / "assignment.json").read_text())["targets"]
487
+ for sub in ("models", "history", "tmp", "inferreddata"):
488
+ (project / sub).mkdir(exist_ok=True)
489
+ verified_sc: set[str] = set()
490
+
491
+ def verify_sc(r: str) -> None:
492
+ if r not in verified_sc:
493
+ if sha256(project / f"sample_sc/{r}.h5ad") != prepared["files"][f"sample_sc/{r}.h5ad"]:
494
+ raise SystemExit(f"prepared sample_sc/{r}.h5ad changed")
495
+ verified_sc.add(r)
496
+
497
+ def ckpt_ok(path: Path) -> bool:
498
+ rp = path.with_name(path.name + ".receipt.json")
499
+ if not path.exists():
500
+ if rp.exists():
501
+ raise SystemExit(f"receipt without checkpoint: {rp}")
502
+ return False
503
+ if not rp.exists():
504
+ raise SystemExit(f"unreceipted checkpoint {path}; preserve and inspect")
505
+ rec = json.loads(rp.read_text())
506
+ if rec["run_signature"] != signature or rec["sha256"] != sha256(path):
507
+ raise SystemExit(f"checkpoint receipt mismatch: {path}")
508
+ return True
509
+
510
+ def shim(state_path: Path):
511
+ sd = torch.load(state_path, map_location=a.device, weights_only=True)
512
+ return types.SimpleNamespace(module=types.SimpleNamespace(state_dict=lambda: sd))
513
+
514
+ if a.phase == "link": # CPU: reuse the source run's receipted pretrain checkpoints (hard link, sha-checked)
515
+ smodels = reuse["src"] / "scsemi_project/models"
516
+ n_link = n_missing = 0
517
+ for r in reps:
518
+ for stage, base in ((1, "fast_reconst1_"), (2, "fastreconst2_")):
519
+ dst = project / "models" / f"{base}{r}"
520
+ if ckpt_ok(dst):
521
+ continue
522
+ src = smodels / f"{base}{r}"
523
+ srp = src.with_name(src.name + ".receipt.json")
524
+ if not (src.exists() and srp.exists()):
525
+ n_missing += 1
526
+ event("link_source_missing", representative=r, stage=stage)
527
+ continue
528
+ srec = json.loads(srp.read_text())
529
+ want_seed = SEED + 1000 * stage + reuse["seed_index"][r]
530
+ if not (srec.get("complete") and srec["run_signature"] == reuse["signature"] and srec["stage"] == stage
531
+ and srec["representative"] == r and srec["seed"] == want_seed and srec["sha256"] == sha256(src)):
532
+ raise SystemExit(f"source checkpoint {src} does not match its receipt, the source run or the seed")
533
+ try:
534
+ os.link(src, dst)
535
+ except OSError:
536
+ shutil.copy2(src, dst)
537
+ if sha256(dst) != srec["sha256"]:
538
+ raise SystemExit(f"linked checkpoint {dst} differs from its source")
539
+ write_json(dst.with_name(dst.name + ".receipt.json"), {
540
+ "run_signature": signature, "sha256": srec["sha256"], "stage": stage, "representative": r,
541
+ "seed": want_seed, "elapsed_seconds": 0.0, "code_signature": code_signature,
542
+ "device": srec.get("device"), "complete": True,
543
+ "reused_from": {"path": str(src), "run_signature": reuse["signature"], "receipt": srec}})
544
+ n_link += 1
545
+ st = status()
546
+ event("link_done", linked=n_link, source_missing=n_missing,
547
+ **{k: st[k] for k in ("reps_pretrained", "n_reps")})
548
+ return 0
549
+
550
+ if a.phase == "pretrain":
551
+ P1, P2 = protocol["pretrain1"], protocol["pretrain2"]
552
+ n_done = 0
553
+ for r in reps:
554
+ c1 = project / "models" / f"fast_reconst1_{r}"
555
+ c2 = project / "models" / f"fastreconst2_{r}"
556
+ ok1, ok2 = ckpt_ok(c1), ckpt_ok(c2)
557
+ if ok1 and ok2:
558
+ continue
559
+ if a.max_reps and n_done >= a.max_reps:
560
+ break
561
+ verify_sc(r)
562
+ idx = reuse["seed_index"][r] if reuse is not None else sids.index(r)
563
+ model1 = None
564
+ if not ok1:
565
+ scvi.settings.seed = SEED + 1000 + idx
566
+ event("pretrain_start", stage=1, representative=r, seed=SEED + 1000 + idx)
567
+ t0 = time.monotonic()
568
+ model1 = fastrecon(str(project), r, device=a.device, k=P1["k"], diagw=P1["diagw"],
569
+ vaesteps=P1["vaesteps"], gansteps=P1["gansteps"], lr=P1["lr"])
570
+ el = time.monotonic() - t0
571
+ write_json(c1.with_name(c1.name + ".receipt.json"), {"run_signature": signature, "sha256": sha256(c1),
572
+ "stage": 1, "representative": r, "seed": SEED + 1000 + idx, "elapsed_seconds": el,
573
+ "code_signature": code_signature,
574
+ "device": a.device, "complete": True})
575
+ event("pretrain_complete", stage=1, representative=r, elapsed_seconds=round(el, 1))
576
+ if not ok2:
577
+ pre = model1 if model1 is not None else shim(c1)
578
+ scvi.settings.seed = SEED + 2000 + idx
579
+ event("pretrain_start", stage=2, representative=r, seed=SEED + 2000 + idx)
580
+ t0 = time.monotonic()
581
+ model2 = reconst_pretrain2(str(project), r, pre, device=a.device, k=P2["k"], diagw=P2["diagw"],
582
+ vaesteps=P2["vaesteps"], gansteps=P2["gansteps"], lr=P2["lr"])
583
+ el = time.monotonic() - t0
584
+ write_json(c2.with_name(c2.name + ".receipt.json"), {"run_signature": signature, "sha256": sha256(c2),
585
+ "stage": 2, "representative": r, "seed": SEED + 2000 + idx, "elapsed_seconds": el,
586
+ "code_signature": code_signature,
587
+ "device": a.device, "complete": True})
588
+ event("pretrain_complete", stage=2, representative=r, elapsed_seconds=round(el, 1))
589
+ del model2
590
+ del model1
591
+ gc.collect()
592
+ if a.device.startswith("cuda"):
593
+ torch.cuda.empty_cache()
594
+ n_done += 1
595
+ st = status()
596
+ event("pretrain_call_done", reps_this_call=n_done, **{k: st[k] for k in ("reps_pretrained", "n_reps")})
597
+ return 0
598
+
599
+ if a.phase == "infer":
600
+ I = protocol["infer"]
601
+ missing = [r for r in reps if not (ckpt_ok(project / "models" / f"fast_reconst1_{r}")
602
+ and ckpt_ok(project / "models" / f"fastreconst2_{r}"))]
603
+ if missing:
604
+ raise SystemExit(f"pretraining incomplete for {missing}")
605
+ shards = work / "shards"
606
+ shards.mkdir(exist_ok=True)
607
+ genelen = len(man["modeled_genes"]["gene_ids"])
608
+ n_done = 0
609
+ for t in targets:
610
+ rec_path = shards / f"{t}.json"
611
+ shard = shards / f"{t}.npz"
612
+ if rec_path.exists():
613
+ rec = json.loads(rec_path.read_text())
614
+ if rec["run_signature"] != signature or rec["shard_sha256"] != sha256(shard):
615
+ raise SystemExit(f"target shard receipt mismatch: {t}")
616
+ continue
617
+ if shard.exists():
618
+ raise SystemExit(f"shard without receipt: {shard}; preserve and inspect")
619
+ if a.max_targets and n_done >= a.max_targets:
620
+ break
621
+ r = assign[t]["representative"]
622
+ verify_sc(r)
623
+ upstream = project / "inferreddata" / f"{r}_to_{t}.npy"
624
+ if upstream.exists():
625
+ raise SystemExit(f"unreceipted upstream output {upstream}; preserve and inspect")
626
+ rid, tid = sids.index(r), sids.index(t)
627
+ scvi.settings.seed = SEED + tid
628
+ event("target_start", sample_id=t, representative=r, seed=SEED + tid)
629
+ t0 = time.monotonic()
630
+ fast_semi(str(project), rid, tid, str(project / "models" / f"fastreconst2_{r}"), device=a.device,
631
+ k=I["k"], diagw=I["diagw"], bulktype=I["bulktype"], pseudocount=I["pseudocount"], lr=I["lr"],
632
+ epochs=I["epochs"], ministages=I["ministages"])
633
+ elapsed = time.monotonic() - t0
634
+ M = np.load(upstream, allow_pickle=False)
635
+ n_rep_cells = json.loads((work / "geneset_feature_qc.json").read_text())["reps"][r]["n_cells"]
636
+ if M.shape != (n_rep_cells, genelen) or not np.isfinite(M).all() or (M < 0).any():
637
+ raise SystemExit(f"{t}: invalid upstream output {M.shape} (expected {(n_rep_cells, genelen)})")
638
+ C = sp.csr_matrix(M)
639
+ tmp = shards / f"{t}.tmp.npz"
640
+ sp.save_npz(tmp, C, compressed=False)
641
+ back = sp.load_npz(tmp).toarray()
642
+ if back.dtype != M.dtype or not np.array_equal(back, M):
643
+ raise SystemExit(f"{t}: CSR re-encoding is not lossless")
644
+ tmp.replace(shard)
645
+ lib = M.sum(1)
646
+ rec = {"sample_id": t, "representative": r, "rep_bulk_index": rid, "target_bulk_index": tid,
647
+ "seed": SEED + tid, "elapsed_seconds": elapsed, "device": a.device, "run_signature": signature,
648
+ "code_signature": code_signature,
649
+ "shape": list(M.shape), "dtype": str(M.dtype), "nnz": int(C.nnz),
650
+ "zero_fraction": float(1 - C.nnz / M.size), "zero_rows": int((lib == 0).sum()),
651
+ "mean_library_normalized": float(lib.mean()), "matrix_unit": "normalized_expression",
652
+ "upstream_npy": str(upstream), "upstream_npy_sha256": sha256(upstream),
653
+ "shard": str(shard), "shard_sha256": sha256(shard), "lossless_csr_verified": True,
654
+ "upstream_npy_removed": True, "created_at": datetime.now(timezone.utc).isoformat(), "complete": True}
655
+ write_json(rec_path, rec)
656
+ upstream.unlink() # dense copy of a verified lossless shard (disk)
657
+ del M, C, back
658
+ gc.collect()
659
+ n_done += 1
660
+ event("target_complete", sample_id=t, representative=r, elapsed_seconds=round(elapsed, 2),
661
+ zero_rows=rec["zero_rows"], zero_fraction=round(rec["zero_fraction"], 4))
662
+ st = status()
663
+ event("infer_call_done", targets_this_call=n_done, **{k: st[k] for k in ("targets_done", "n_targets")})
664
+ return 0
665
+ except BaseException as exc:
666
+ event("failed", error_type=type(exc).__name__, message=str(exc)[:2000])
667
+ raise
668
+ return 0
669
+
670
+
671
+ if __name__ == "__main__":
672
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/backups/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fine-tune the final PBISC-SDD model inside one paired dataset fold.
3
+
4
+ Training pairs are (condition of row r, one retained cell of row r). The condition comes from a condition NPZ
5
+ written by prepare_dataset.py (real bulk or pseudobulk, fixed-depth policy) and goes through the checkpoint's own
6
+ conditioner exactly as the standalone sampler does (sample_sdd_standalone.load_conditions), then
7
+ condition_with_measurement_context(base, bulk_measurement_fraction, output_availability_mask). The loss is the
8
+ pretraining loss (SparseDataDiffusion.training_loss: measured-only value L2 + support BCE, self-conditioning),
9
+ with bf16 autocast, AdamW and gradient clipping as in pretraining.
10
+
11
+ Rows: fold k's test rows are never loaded. Training rows = the other folds minus the inner-validation rows;
12
+ inner-validation rows give a fixed-draw diffusion loss every --eval-every steps, and the EMA state with the lowest
13
+ inner-validation loss is kept (early stopping with --patience evaluations).
14
+
15
+ Modes (what is trainable):
16
+ full every denoiser parameter
17
+ condenc only denoiser.condition_encoder (the bulk -> context map)
18
+ lora low-rank updates W = W0 + (alpha/r) B A on every nn.Linear of the denoiser (B starts at zero);
19
+ merged into the weights before saving
20
+
21
+ Batches are donor-balanced: a row is drawn uniformly, then one of its cells uniformly.
22
+
23
+ The output checkpoint keeps the input checkpoint's schema and self-contained keys, with model_state and
24
+ ema_state.model_state set to the selected weights, so scripts/sample_sdd_standalone.py samples it unchanged.
25
+ src/pbisc_sdd is sealed and is only imported.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import hashlib
31
+ import json
32
+ import math
33
+ import os
34
+ import sys
35
+ import time
36
+ from datetime import datetime, timezone
37
+ from pathlib import Path
38
+
39
+ import numpy as np
40
+ import pandas as pd
41
+ import torch
42
+ from torch import nn
43
+ import torch.nn.utils.parametrize as parametrize
44
+
45
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
46
+ for p in (M8 / "src", M8 / "scripts"):
47
+ if str(p) not in sys.path:
48
+ sys.path.insert(0, str(p))
49
+ import sample_sdd_standalone as SS # noqa: E402
50
+ from pbisc_sdd.data import condition_with_measurement_context # noqa: E402
51
+
52
+ SCHEMA = "pbisc_sdd.ft_intradataset.run.v1"
53
+ KEEP_KEYS = ("schema_version", "model_config", "diffusion_config", "value_scaler", "conditioner_state",
54
+ "gene_positions", "gene_ids", "gene_symbols", "gene_measurement_coverage",
55
+ "full_gene_measurement_coverage", "corpus_fingerprint", "experiment_config", "proportion_hint",
56
+ "training_contract")
57
+
58
+
59
+ def sha256_file(path: Path) -> str:
60
+ h = hashlib.sha256()
61
+ with open(path, "rb") as f:
62
+ for block in iter(lambda: f.read(1 << 24), b""):
63
+ h.update(block)
64
+ return h.hexdigest()
65
+
66
+
67
+ def log(msg: str) -> None:
68
+ print(f"{datetime.now().isoformat(timespec='seconds')} {msg}", flush=True)
69
+
70
+
71
+ # ----------------------------------------------------------------------------------------------- LoRA
72
+ class LoRADelta(nn.Module):
73
+ """Parametrization W -> W + scale * B @ A (B zero-initialised, so the start equals the pretrained W)."""
74
+
75
+ def __init__(self, out_features: int, in_features: int, rank: int, alpha: float) -> None:
76
+ super().__init__()
77
+ self.A = nn.Parameter(torch.empty(rank, in_features))
78
+ self.B = nn.Parameter(torch.zeros(out_features, rank))
79
+ nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
80
+ self.scale = float(alpha) / float(rank)
81
+
82
+ def forward(self, weight: torch.Tensor) -> torch.Tensor:
83
+ return weight + self.scale * (self.B @ self.A).to(dtype=weight.dtype)
84
+
85
+
86
+ def add_lora(model: nn.Module, rank: int, alpha: float) -> list[str]:
87
+ names = []
88
+ for name, module in model.named_modules():
89
+ if isinstance(module, nn.Linear):
90
+ delta = LoRADelta(module.out_features, module.in_features, rank, alpha).to(
91
+ device=module.weight.device, dtype=module.weight.dtype)
92
+ parametrize.register_parametrization(module, "weight", delta)
93
+ names.append(name)
94
+ return names
95
+
96
+
97
+ def merge_lora(model: nn.Module) -> None:
98
+ for module in model.modules():
99
+ if isinstance(module, nn.Linear) and parametrize.is_parametrized(module, "weight"):
100
+ parametrize.remove_parametrizations(module, "weight", leave_parametrized=True)
101
+
102
+
103
+ def set_trainable(denoiser: nn.Module, mode: str, rank: int, alpha: float) -> dict:
104
+ for p in denoiser.parameters():
105
+ p.requires_grad_(False)
106
+ info: dict = {"mode": mode}
107
+ if mode == "full":
108
+ for p in denoiser.parameters():
109
+ p.requires_grad_(True)
110
+ elif mode == "condenc":
111
+ for p in denoiser.condition_encoder.parameters():
112
+ p.requires_grad_(True)
113
+ elif mode == "lora":
114
+ info["lora_layers"] = add_lora(denoiser, rank, alpha)
115
+ info["lora_rank"], info["lora_alpha"] = rank, alpha
116
+ for name, p in denoiser.named_parameters():
117
+ p.requires_grad_(name.endswith(".A") or name.endswith(".B"))
118
+ else:
119
+ raise SystemExit(f"unknown mode {mode}")
120
+ trainable = [n for n, p in denoiser.named_parameters() if p.requires_grad]
121
+ info["n_trainable"] = int(sum(p.numel() for p in denoiser.parameters() if p.requires_grad))
122
+ info["n_total_base"] = int(sum(p.numel() for n, p in denoiser.named_parameters()
123
+ if not (n.endswith(".A") or n.endswith(".B"))))
124
+ info["trainable_tensors"] = len(trainable)
125
+ return info
126
+
127
+
128
+ # ----------------------------------------------------------------------------------------------- data
129
+ class Cells:
130
+ """Retained cells on the 6k panel (CSR, rows sorted by dataset row)."""
131
+
132
+ def __init__(self, path: Path, panel_gene_ids: np.ndarray) -> None:
133
+ z = np.load(path, allow_pickle=False)
134
+ self.indptr = z["indptr"].astype(np.int64)
135
+ self.indices = z["indices"].astype(np.int64)
136
+ self.data = z["data"].astype(np.float32)
137
+ self.row_sample = z["row_sample"].astype(np.int64)
138
+ self.n_genes = int(z["shape"][1])
139
+ if not np.array_equal(z["panel_gene_ids"].astype(str), panel_gene_ids.astype(str)):
140
+ raise SystemExit("cells_panel6k columns differ from the checkpoint gene panel")
141
+ if bool((np.diff(self.row_sample) < 0).any()):
142
+ raise SystemExit("cells are not sorted by dataset row")
143
+ n_rows = int(self.row_sample.max()) + 1
144
+ self.start = np.searchsorted(self.row_sample, np.arange(n_rows), side="left")
145
+ self.count = np.searchsorted(self.row_sample, np.arange(n_rows), side="right") - self.start
146
+
147
+ def dense(self, cells: np.ndarray) -> np.ndarray:
148
+ s, e = self.indptr[cells], self.indptr[cells + 1]
149
+ lens = e - s
150
+ idx = np.concatenate([np.arange(a, b) for a, b in zip(s, e)]) if len(cells) else np.zeros(0, np.int64)
151
+ out = np.zeros((len(cells), self.n_genes), dtype=np.float32)
152
+ out[np.repeat(np.arange(len(cells)), lens), self.indices[idx]] = self.data[idx]
153
+ return out
154
+
155
+
156
+ def draw_batch(cells: Cells, rows: np.ndarray, batch: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
157
+ r = rows[rng.integers(0, len(rows), size=batch)]
158
+ c = cells.start[r] + np.floor(rng.random(batch) * cells.count[r]).astype(np.int64)
159
+ return r, c
160
+
161
+
162
+ # ----------------------------------------------------------------------------------------------- main
163
+ def main(argv=None) -> int:
164
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
165
+ ap.add_argument("--checkpoint", type=Path, required=True)
166
+ ap.add_argument("--checkpoint-sha", required=True)
167
+ ap.add_argument("--dataset-dir", type=Path, required=True)
168
+ ap.add_argument("--condition-npz", type=Path, required=True, help="all-row condition NPZ used for training")
169
+ ap.add_argument("--fold", type=int, required=True)
170
+ ap.add_argument("--mode", choices=("full", "condenc", "lora"), required=True)
171
+ ap.add_argument("--lora-rank", type=int, default=16)
172
+ ap.add_argument("--lora-alpha", type=float, default=16.0)
173
+ ap.add_argument("--lr", type=float, required=True)
174
+ ap.add_argument("--warmup", type=int, default=200)
175
+ ap.add_argument("--batch-size", type=int, default=256)
176
+ ap.add_argument("--max-steps", type=int, default=20000)
177
+ ap.add_argument("--eval-every", type=int, default=250)
178
+ ap.add_argument("--patience", type=int, default=8)
179
+ ap.add_argument("--ema-decay", type=float, default=0.999)
180
+ ap.add_argument("--val-cells-per-row", type=int, default=256)
181
+ ap.add_argument("--val-repeats", type=int, default=2)
182
+ ap.add_argument("--seed", type=int, default=20260927)
183
+ ap.add_argument("--out-dir", type=Path, required=True)
184
+ ap.add_argument("--device", default="cuda")
185
+ ap.add_argument("--max-cuda-gib", type=float, default=8.0)
186
+ ap.add_argument("--min-system-gib", type=float, default=32.0)
187
+ ap.add_argument("--smoke", action="store_true", help="tiny run for tests (few steps, CPU allowed)")
188
+ ap.add_argument("--train-n", type=int, default=0, help="learning curve: number of training donors to keep")
189
+ ap.add_argument("--train-donors-file", default="", help="few-pair scenario: train on these donor_ids (one per "
190
+ "line), no inner validation, every other usable row is test; --fold is ignored")
191
+ ap.add_argument("--fixed-steps", type=int, default=0, help="train exactly this many steps without inner "
192
+ "validation and keep the final EMA state (for when no pairs can be spared for early stopping)")
193
+ ap.add_argument("--subset-seed", type=int, default=0)
194
+ ap.add_argument("--strata-regex", default="", help="groups matching this regex form one stratum, the rest another")
195
+ a = ap.parse_args(argv)
196
+
197
+ a.out_dir.mkdir(parents=True, exist_ok=True)
198
+ done = a.out_dir / "checkpoint_ft.pt"
199
+ if done.exists() and (a.out_dir / "RUN.json").exists():
200
+ log(f"{done} exists; nothing to do")
201
+ return 0
202
+ avail = int(open("/proc/meminfo").read().split("MemAvailable:")[1].split()[0]) / 1048576
203
+ if avail < a.min_system_gib:
204
+ raise SystemExit(f"MemAvailable {avail:.1f} GiB < floor {a.min_system_gib}")
205
+ got = sha256_file(a.checkpoint)
206
+ if got != a.checkpoint_sha:
207
+ raise SystemExit(f"checkpoint sha {got[:12]} != {a.checkpoint_sha[:12]}")
208
+ device = torch.device(a.device)
209
+ if device.type == "cuda" and device.index is None:
210
+ device = torch.device("cuda", 0)
211
+ if device.type == "cuda":
212
+ total = torch.cuda.get_device_properties(device).total_memory
213
+ torch.cuda.set_per_process_memory_fraction(min(1.0, a.max_cuda_gib * 2**30 / total), device)
214
+ torch.manual_seed(a.seed)
215
+ rng = np.random.default_rng(a.seed)
216
+
217
+ bundle = SS.restore_standalone(a.checkpoint, device=device, weights="ema", conditioner_source="embedded")
218
+ diffusion, scaler = bundle.diffusion, bundle.scaler
219
+ ext = SS.load_conditions(a.condition_npz, bundle, default_cells_per_bulk=1)
220
+ folds = pd.read_csv(a.dataset_dir / "folds.csv")
221
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), ext.sample_ids.astype(str)):
222
+ raise SystemExit("condition NPZ rows differ from folds.csv")
223
+ if a.train_donors_file:
224
+ # few-pair deployment scenario: train on the listed donors only, no inner validation, and treat every other
225
+ # usable row (fold >= 0) as test; --fold is ignored
226
+ want = {l.strip() for l in Path(a.train_donors_file).read_text().splitlines() if l.strip()}
227
+ is_train = folds["donor_id"].astype(str).isin(want) & (folds["fold"] >= 0)
228
+ if int(folds.loc[is_train, "donor_id"].nunique()) != len(want):
229
+ raise SystemExit("some listed training donors are missing or excluded")
230
+ folds = folds.assign(fold=np.where(folds["fold"] < 0, -1, np.where(is_train, 1, 0)))
231
+ folds["inner_val_custom"] = False
232
+ a.fold = 0
233
+ inner_col = "inner_val_custom"
234
+ else:
235
+ inner_col = f"inner_val_f{a.fold}"
236
+ test_rows = folds.index[folds["fold"] == a.fold].to_numpy()
237
+ inner_rows = folds.index[folds[inner_col]].to_numpy()
238
+ # fold -1 marks rows excluded by the pairing identity checks: never trained on, never tested
239
+ train_rows = folds.index[(folds["fold"] != a.fold) & (folds["fold"] >= 0)
240
+ & ~folds[inner_col]].to_numpy()
241
+ subset_info = None
242
+ if a.train_n:
243
+ # learning curve: keep a stratified, nested subset of the training donors (inner-validation and test
244
+ # rows unchanged). Each stratum is permuted once by --subset-seed, so smaller subsets are prefixes of
245
+ # larger ones; allocation is proportional to stratum size with at least one donor per stratum.
246
+ grp = folds.loc[train_rows, "group"].astype(str)
247
+ strata = (grp.str.contains(a.strata_regex, regex=True) if a.strata_regex
248
+ else pd.Series(True, index=grp.index)).to_numpy()
249
+ srng = np.random.default_rng(a.subset_seed)
250
+ labels = sorted(set(strata.tolist()))
251
+ perm = {s: train_rows[strata == s][srng.permutation(int((strata == s).sum()))] for s in labels}
252
+ n = min(int(a.train_n), len(train_rows))
253
+ sizes = {s: len(perm[s]) for s in labels}
254
+ alloc = {s: max(1, int(np.floor(n * sizes[s] / len(train_rows)))) for s in labels}
255
+ while sum(alloc.values()) < n:
256
+ s = max(labels, key=lambda s: n * sizes[s] / len(train_rows) - alloc[s])
257
+ alloc[s] += 1
258
+ while sum(alloc.values()) > n:
259
+ s = max((s for s in labels if alloc[s] > 1), key=lambda s: alloc[s])
260
+ alloc[s] -= 1
261
+ train_rows = np.sort(np.concatenate([perm[s][:alloc[s]] for s in labels]))
262
+ subset_info = {"train_n": int(n), "subset_seed": a.subset_seed, "strata_regex": a.strata_regex,
263
+ "allocation": {str(k): int(v) for k, v in alloc.items()}}
264
+ if set(test_rows) & (set(inner_rows) | set(train_rows)):
265
+ raise SystemExit("test rows overlap training rows")
266
+ if set(folds.loc[test_rows, "donor_id"]) & set(folds.loc[np.r_[train_rows, inner_rows], "donor_id"]):
267
+ raise SystemExit("a test donor also appears in training")
268
+
269
+ cells = Cells(a.dataset_dir / "cells_panel6k.npz", bundle.gene_ids)
270
+ z = np.load(a.dataset_dir / "cells_panel6k.npz", allow_pickle=False)
271
+ panel_measured = z["panel_measured"].astype(bool)
272
+ if not np.array_equal(panel_measured, ext.output_availability_mask.astype(bool)):
273
+ raise SystemExit("cells' measured panel differs from the condition NPZ output_availability_mask")
274
+
275
+ base = torch.from_numpy(ext.base_conditions.astype(np.float32)).to(device)
276
+ bulk_frac = torch.from_numpy(ext.bulk_measurement_fraction.astype(np.float32)).to(device)
277
+ avail_rows = torch.from_numpy(ext.output_availability_mask.astype(bool)).to(device)
278
+ cond_rows = condition_with_measurement_context(base, bulk_frac, avail_rows) # [rows, condition_dim]
279
+
280
+ denoiser = diffusion.denoiser
281
+ info = set_trainable(denoiser, a.mode, a.lora_rank, a.lora_alpha)
282
+ params = [p for p in denoiser.parameters() if p.requires_grad]
283
+ named = [(n, p) for n, p in denoiser.named_parameters() if p.requires_grad]
284
+ opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
285
+ ema = {n: p.detach().clone() for n, p in named}
286
+ log(f"mode={a.mode} trainable={info['n_trainable']:,} rows train/inner/test="
287
+ f"{len(train_rows)}/{len(inner_rows)}/{len(test_rows)} cells(train)={int(cells.count[train_rows].sum()):,}")
288
+
289
+ # fixed inner-validation draws
290
+ vrng = np.random.default_rng(a.seed + 1)
291
+ val_cells, val_rows = [], []
292
+ for r in inner_rows:
293
+ n = int(cells.count[r])
294
+ take = min(a.val_cells_per_row, n)
295
+ pick = cells.start[r] + np.sort(vrng.choice(n, size=take, replace=False))
296
+ val_cells.append(pick)
297
+ val_rows.append(np.full(take, r))
298
+ val_cells = np.concatenate(val_cells) if val_cells else np.zeros(0, np.int64)
299
+ val_rows = np.concatenate(val_rows) if val_rows else np.zeros(0, np.int64)
300
+
301
+ def to_batch(r: np.ndarray, c: np.ndarray):
302
+ x_log = torch.from_numpy(np.log1p(cells.dense(c))).to(device)
303
+ rr = torch.from_numpy(r).to(device)
304
+ availability = avail_rows[rr]
305
+ return scaler.to_unit_tensor(x_log), cond_rows[rr], availability, x_log > 0
306
+
307
+ def swap_in_ema() -> dict:
308
+ backup = {n: p.detach().clone() for n, p in named}
309
+ with torch.no_grad():
310
+ for n, p in named:
311
+ p.copy_(ema[n])
312
+ return backup
313
+
314
+ def restore(backup: dict) -> None:
315
+ with torch.no_grad():
316
+ for n, p in named:
317
+ p.copy_(backup[n])
318
+
319
+ @torch.no_grad()
320
+ def val_loss() -> float:
321
+ if len(val_cells) == 0:
322
+ return float("nan")
323
+ diffusion.eval()
324
+ tot, n = 0.0, 0
325
+ for rep in range(a.val_repeats):
326
+ for i in range(0, len(val_cells), a.batch_size):
327
+ g = torch.Generator(device=device).manual_seed(a.seed + 1_000_003 * rep + i)
328
+ v, c, m, act = to_batch(val_rows[i:i + a.batch_size], val_cells[i:i + a.batch_size])
329
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
330
+ res = diffusion.training_loss(v, c, availability_mask=m, active_target=act, generator=g)
331
+ tot += float(res.loss) * v.shape[0]
332
+ n += v.shape[0]
333
+ diffusion.train()
334
+ return tot / max(n, 1)
335
+
336
+ history = []
337
+ best = {"loss": val_loss(), "step": 0}
338
+ best_state = {n: t.detach().cpu().clone() for n, t in ema.items()}
339
+ history.append({"step": 0, "inner_val_loss": best["loss"], "train_loss": None})
340
+ log(f"step 0 inner-val loss {best['loss']:.5f} (pretrained)")
341
+ gen = torch.Generator(device=device).manual_seed(a.seed + 7)
342
+ diffusion.train()
343
+ t0 = time.time()
344
+ run_loss, run_n, bad = 0.0, 0, 0
345
+ max_steps = 20 if a.smoke else (a.fixed_steps or a.max_steps)
346
+ eval_every = 5 if a.smoke else a.eval_every
347
+ step = 0
348
+ for step in range(1, max_steps + 1):
349
+ for gparam in opt.param_groups:
350
+ gparam["lr"] = a.lr * min(1.0, step / max(1, a.warmup))
351
+ r, c = draw_batch(cells, train_rows, a.batch_size, rng)
352
+ v, cond, m, act = to_batch(r, c)
353
+ opt.zero_grad(set_to_none=True)
354
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
355
+ res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=gen)
356
+ if not bool(torch.isfinite(res.loss)):
357
+ raise FloatingPointError(f"non-finite loss at step {step}")
358
+ res.loss.backward()
359
+ norm = nn.utils.clip_grad_norm_(params, 5.0)
360
+ if not bool(torch.isfinite(norm)):
361
+ raise FloatingPointError(f"non-finite grad norm at step {step}")
362
+ opt.step()
363
+ with torch.no_grad():
364
+ for n_, p in named:
365
+ ema[n_].lerp_(p.detach(), 1.0 - a.ema_decay)
366
+ run_loss += float(res.loss.detach())
367
+ run_n += 1
368
+ if a.fixed_steps and step == max_steps:
369
+ best = {"loss": float("nan"), "step": step}
370
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
371
+ if step % eval_every == 0 and not a.fixed_steps:
372
+ backup = swap_in_ema()
373
+ vl = val_loss()
374
+ restore(backup)
375
+ rec = {"step": step, "inner_val_loss": vl, "train_loss": run_loss / run_n,
376
+ "sec": round(time.time() - t0, 1)}
377
+ history.append(rec)
378
+ run_loss, run_n = 0.0, 0
379
+ if vl < best["loss"] - 1e-6:
380
+ best = {"loss": vl, "step": step}
381
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
382
+ bad = 0
383
+ else:
384
+ bad += 1
385
+ log(f"step {step} train {rec['train_loss']:.5f} inner-val {vl:.5f} best {best['loss']:.5f}@{best['step']} "
386
+ f"({rec['sec']:.0f}s)")
387
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
388
+ if bad >= a.patience:
389
+ log(f"early stop: no improvement in {a.patience} evaluations")
390
+ break
391
+
392
+ # load the selected EMA state, merge LoRA, save a self-contained checkpoint
393
+ with torch.no_grad():
394
+ for n_, p in named:
395
+ p.copy_(best_state[n_].to(device))
396
+ if a.mode == "lora":
397
+ merge_lora(denoiser)
398
+ state = {k: v.detach().cpu().clone() for k, v in denoiser.state_dict().items()}
399
+ payload_in = SS._load_checkpoint_cpu(a.checkpoint)
400
+ ref_state = payload_in["ema_state"]["model_state"]
401
+ if set(ref_state.keys()) != set(state.keys()):
402
+ raise SystemExit("fine-tuned state keys differ from the checkpoint's")
403
+ changed = {k: float((state[k].float() - ref_state[k].float()).abs().max()) for k in state}
404
+ out = {k: payload_in[k] for k in KEEP_KEYS if k in payload_in}
405
+ out["model_state"] = state
406
+ out["ema_state"] = {"model_state": state}
407
+ ft_meta = {
408
+ "schema": SCHEMA, "source_checkpoint": str(a.checkpoint), "source_checkpoint_sha256": got,
409
+ "dataset_dir": str(a.dataset_dir), "condition_npz": str(a.condition_npz),
410
+ "condition_npz_sha256": ext.input_sha256, "fold": a.fold, "mode": a.mode, "trainable": info,
411
+ "lr": a.lr, "warmup": a.warmup, "batch_size": a.batch_size, "ema_decay": a.ema_decay,
412
+ "max_steps": max_steps, "steps_run": step, "eval_every": eval_every, "patience": a.patience,
413
+ "train_subset": subset_info, "train_donors_file": a.train_donors_file or None,
414
+ "fixed_steps": a.fixed_steps or None,
415
+ "selected_step": best["step"], "selected_inner_val_loss": best["loss"],
416
+ "pretrained_inner_val_loss": history[0]["inner_val_loss"],
417
+ "train_rows": [str(x) for x in folds.loc[train_rows, "sample_id"]],
418
+ "inner_val_rows": [str(x) for x in folds.loc[inner_rows, "sample_id"]],
419
+ "test_rows_never_loaded_for_training": [str(x) for x in folds.loc[test_rows, "sample_id"]],
420
+ "max_abs_weight_change": max(changed.values()),
421
+ "n_tensors_changed": int(sum(v > 0 for v in changed.values())),
422
+ "seed": a.seed, "wall_seconds": round(time.time() - t0, 1),
423
+ "written_utc": datetime.now(timezone.utc).isoformat(),
424
+ }
425
+ out["finetune"] = ft_meta
426
+ tmp = a.out_dir / "checkpoint_ft.pt.tmp"
427
+ torch.save(out, tmp)
428
+ os.replace(tmp, done)
429
+ ft_meta["checkpoint_sha256"] = sha256_file(done)
430
+ # reload through the sampler's own restore path and compare one forward pass
431
+ check = SS.restore_standalone(done, device=torch.device("cpu"), weights="ema", conditioner_source="embedded")
432
+ ref = SS.restore_standalone(done, device=torch.device("cpu"), weights="raw", conditioner_source="embedded")
433
+ xs = torch.randn(4, check.diffusion.state_dim, generator=torch.Generator().manual_seed(0))
434
+ tt = torch.full((4,), 0.5)
435
+ cc = cond_rows[torch.from_numpy(train_rows[:1]).to(device)].repeat(4, 1).float().cpu()
436
+ denoiser_cpu = denoiser.to("cpu").float().eval()
437
+ with torch.no_grad():
438
+ o1 = check.diffusion.denoiser(xs, tt, cc).value_prediction
439
+ o2 = denoiser_cpu(xs, tt, cc).value_prediction
440
+ o3 = ref.diffusion.denoiser(xs, tt, cc).value_prediction
441
+ ft_meta["reload_forward_max_abs_diff"] = float(max((o1 - o2).abs().max(), (o1 - o3).abs().max()))
442
+ if ft_meta["reload_forward_max_abs_diff"] > 1e-4:
443
+ raise SystemExit(f"reloaded checkpoint differs: {ft_meta['reload_forward_max_abs_diff']}")
444
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
445
+ (a.out_dir / "RUN.json").write_text(json.dumps(ft_meta, indent=1))
446
+ log(f"saved {done} (selected step {best['step']}, inner-val {best['loss']:.5f} vs pretrained "
447
+ f"{history[0]['inner_val_loss']:.5f}); sha {ft_meta['checkpoint_sha256'][:12]}")
448
+ return 0
449
+
450
+
451
+ if __name__ == "__main__":
452
+ sys.exit(main())