junidude14 commited on
Commit
9d27d80
·
verified ·
1 Parent(s): cd1c064

Archive 3 checkpoints (1-3)

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/legacy_adapters/plans/paired_finetune_intradataset_20260927/scsemi/tools/export_npz.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 strict_export_arguments(man: dict, work: Path, out: Path) -> list[str] | None:
70
+ """Opt-in dispatch only; existing fewshot/CV/budget export semantics stay unchanged."""
71
+ if man.get("mode") != "strict":
72
+ return None
73
+ plan = M8 / "plans/paper_figures_strictpairs_20261012"
74
+ condition = Path(man["condition_npz"]).resolve()
75
+ if not condition.is_relative_to(plan / "data"):
76
+ raise ValueError("strict export condition is outside the versioned strict-pairs plan")
77
+ relative = condition.relative_to(plan / "data").parent
78
+ support = plan / "protocol/splits" / relative / "support.json"
79
+ return ["--work", str(work), "--out", str(out), "--support-manifest", str(support)]
80
+
81
+
82
+ def main(argv=None) -> int:
83
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
84
+ ap.add_argument("--work", type=Path, required=True)
85
+ ap.add_argument("--out", type=Path, required=True, help="generated NPZ path (receipt = same stem .log)")
86
+ a = ap.parse_args(argv)
87
+ work, out = a.work.resolve(), a.out.resolve()
88
+ man = json.loads((work / "inputs/inputs_manifest.json").read_text())
89
+ strict_args = strict_export_arguments(man, work, out)
90
+ if strict_args is not None:
91
+ import importlib.util
92
+ plan_tools = M8 / "plans/paper_figures_strictpairs_20261012/tools"
93
+ sys.path.insert(0, str(plan_tools))
94
+ spec = importlib.util.spec_from_file_location("strict_support_exporter", plan_tools / "export_scsemi_strict.py")
95
+ module = importlib.util.module_from_spec(spec)
96
+ spec.loader.exec_module(module)
97
+ return module.main(strict_args)
98
+ run = json.loads((work / "run_manifest.json").read_text())
99
+ smoke = bool(man.get("smoke"))
100
+ if smoke and "/scsemi/smoke/" not in str(out):
101
+ raise SystemExit("smoke outputs never go to the benchmark's generated/ tree")
102
+ if out.exists() or out.with_suffix(".log").exists():
103
+ raise SystemExit(f"{out} or its receipt exists; never overwrite (preserve and inspect)")
104
+ signature = run["run_signature"]
105
+ genes = man["modeled_genes"]["gene_ids"]
106
+ pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
107
+ panel = pd.read_csv(PANEL)
108
+ panel_ids = np.asarray(panel.gene_id.astype(str).tolist(), dtype=str) # fixed-width unicode: loads with allow_pickle=False
109
+ panel_symbols = np.asarray(panel.gene_symbol.astype(str).tolist(), dtype=str)
110
+ if not np.array_equal(panel_ids[pidx], np.asarray(genes)):
111
+ raise SystemExit("modeled genes do not sit at the recorded panel columns")
112
+ depth = float(man["depth"]["value"])
113
+ if not (np.isfinite(depth) and depth > 0):
114
+ raise SystemExit("invalid depth")
115
+ targets = man["condition_sample_order"] if not smoke else [t for t in man["condition_sample_order"]
116
+ if t in set(man["target_order_test_samples"])]
117
+ if sorted(targets) != sorted(man["target_order_test_samples"]):
118
+ raise SystemExit("targets differ from the condition NPZ order")
119
+ per, src_rows = [], []
120
+ G = np.zeros((len(targets) * N_CELLS, panel_ids.size), dtype=np.float32)
121
+ for i, t in enumerate(targets):
122
+ rec = json.loads((work / "shards" / f"{t}.json").read_text())
123
+ shard = work / "shards" / f"{t}.npz"
124
+ if not rec.get("complete") or rec["run_signature"] != signature or rec["shard_sha256"] != sha(shard):
125
+ raise SystemExit(f"{t}: shard incomplete or receipt mismatch")
126
+ C = sp.load_npz(shard).tocsr()
127
+ if C.shape[1] != len(genes):
128
+ raise SystemExit(f"{t}: shard has {C.shape[1]} genes")
129
+ rows = pick_rows(C.shape[0], t)
130
+ X = C[rows].toarray().astype(np.float64)
131
+ if not np.isfinite(X).all() or (X < 0).any():
132
+ raise SystemExit(f"{t}: non-finite or negative values")
133
+ E, n_zero = to_expected_counts(X, depth)
134
+ G[i * N_CELLS:(i + 1) * N_CELLS, pidx] = E
135
+ src_rows.append(rows.astype(np.int32))
136
+ mult = np.bincount(rows, minlength=C.shape[0])
137
+ per.append({"sample_id": t, "representative": rec["representative"], "n_upstream_cells": int(C.shape[0]),
138
+ "with_replacement": bool(C.shape[0] < N_CELLS), "max_multiplicity": int(mult.max()),
139
+ "zero_library_cells": n_zero, "elapsed_seconds": rec["elapsed_seconds"],
140
+ "median_nonzero_genes": float(np.median((E > 0).sum(1)))})
141
+ lib = G.sum(1, dtype=np.float64)
142
+ nz = lib > 0
143
+ checks = {"finite": bool(np.isfinite(G).all()), "nonnegative": bool((G >= 0).all()),
144
+ "zero_outside_modeled_genes": bool(not G[:, np.setdiff1d(np.arange(panel_ids.size), pidx)].any()),
145
+ "nonzero_cells_sum_to_depth": bool(np.allclose(lib[nz], depth, rtol=1e-4)),
146
+ "gene_order_equals_panel": True, "cells_per_target": N_CELLS}
147
+ if not all(v for k, v in checks.items() if isinstance(v, bool)):
148
+ raise SystemExit(f"output checks failed: {checks}")
149
+ n_t = len(targets)
150
+ avail = np.zeros((n_t, panel_ids.size), dtype=bool)
151
+ avail[:, pidx] = True
152
+ arm = {"fewshot": "scsemi5", "cv": "scsemi"}.get(man["mode"])
153
+ if arm is None: # budget split (added 2026-10-02): the equal-pair-budget arm of LoRA lora_n<n>
154
+ arm = f"scsemi_n{int(man['budget']['n'])}"
155
+ meta = {"method": "scSemiProfiler", "arm": arm,
156
+ "setting": run["protocol"]["setting"], "dataset": man["dataset"], "mode": man["mode"], "split": man["split"],
157
+ "input_condition_path": man["condition_npz"], "input_condition_sha256": man["condition_sha256"],
158
+ "seed": SEED, "run_signature": signature, "upstream_commit": run["protocol"]["upstream_commit"],
159
+ "protocol": run["protocol"], "representatives": [r["sample_id"] for r in man["representatives"]],
160
+ "train_donors": man["train_donors"], "n_modeled_genes": len(genes),
161
+ "unit": "expected_counts (Poisson rates)", "depth_rule": man["depth"]["rule"], "depth": depth,
162
+ "cell_rule": "1500 per target from the n_rep upstream cells: without replacement if n_rep >= 1500, else "
163
+ "whole permutations concatenated to 1500; default_rng([20260927, uint64 LE sha256(target)[:8]]); "
164
+ "kept rows sorted (source_row)",
165
+ "support_readout": "upstream (values <= 10 normalized units zeroed by fast_semi)", "smoke": smoke,
166
+ "code_migrations": [{"at": m["at"], "transitions": m["transitions"], "to_code_signature": m["to_code_signature"]}
167
+ for m in run.get("migrations", [])],
168
+ "work": str(work)}
169
+ if "budget" in man:
170
+ meta["budget"] = man["budget"]
171
+ if "reuse" in run: # pretraining / hvset reused from another run (run_scsemi_paired.py --reuse-from)
172
+ meta["reuse"] = run["reuse"]
173
+ out.parent.mkdir(parents=True, exist_ok=True)
174
+ tmp = out.with_name(out.stem + ".tmp.npz")
175
+ np.savez_compressed(tmp, generated_counts=G, gene_ids=panel_ids, gene_symbols=panel_symbols,
176
+ sample_ids=np.asarray(targets), bulk_index=np.repeat(np.arange(n_t, dtype=np.int64), N_CELLS),
177
+ cells_per_bulk=np.full(n_t, N_CELLS, dtype=np.int64), output_availability_mask=avail,
178
+ source_row=np.concatenate(src_rows), metadata_json=np.asarray(json.dumps(meta)))
179
+ with np.load(tmp, allow_pickle=False) as chk: # the scorer opens NPZs with allow_pickle=False
180
+ for key in chk.files:
181
+ chk[key]
182
+ os.replace(tmp, out)
183
+ receipt = {"output": str(out), "output_sha256": sha(out), "written_utc": datetime.now(timezone.utc).isoformat(),
184
+ "condition_npz": man["condition_npz"], "condition_sha256": man["condition_sha256"], "seed": SEED,
185
+ "bulks": n_t, "cells": int(G.shape[0]), "genes": int(panel_ids.size), "modeled_genes": len(genes),
186
+ "depth": depth, "checks": checks, "per_target": per,
187
+ "total_target_seconds": float(sum(p["elapsed_seconds"] for p in per)),
188
+ "median_target_seconds": float(np.median([p["elapsed_seconds"] for p in per])),
189
+ "run_signature": signature, "code_migrations": meta["code_migrations"],
190
+ "exporter_sha256": sha(Path(__file__)), "smoke": smoke}
191
+ rtmp = out.with_name(out.stem + ".log.tmp")
192
+ rtmp.write_text(json.dumps(receipt, indent=1) + "\n")
193
+ os.replace(rtmp, out.with_suffix(".log"))
194
+ print(json.dumps({k: receipt[k] for k in ("output", "bulks", "cells", "modeled_genes", "depth",
195
+ "median_target_seconds")}))
196
+ return 0
197
+
198
+
199
+ if __name__ == "__main__":
200
+ 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/legacy_adapters/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
65
+ n: int | None = None, support_manifest: Path | None = None) -> dict:
66
+ data = TASK / "data" / ds
67
+ usable = folds["fold"].to_numpy() >= 0
68
+ donors = folds["donor_id"].astype(str).to_numpy()
69
+ extra = {}
70
+ if support_manifest is not None:
71
+ strict_tools = TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/tools"
72
+ sys.path.insert(0, str(strict_tools))
73
+ from support_manifest import load_manifest, select_rows
74
+ m = load_manifest(support_manifest, folds)
75
+ if m["cohort"] != ds:
76
+ raise SystemExit("support cohort differs from dataset")
77
+ rep, tgt = select_rows(m, folds)
78
+ rel = support_manifest.resolve().parent.relative_to(
79
+ TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/protocol/splits")
80
+ cond = TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/data" / rel / "test_raw.npz"
81
+ return {"rep": rep, "tgt": tgt, "train_donors": m["train_donor_ids"],
82
+ "test": m["test_sample_ids"], "condition": cond,
83
+ "sources": {"support.json": support_manifest},
84
+ "support_sha256": m["sha256"], "target_donors": m["test_donor_ids"]}
85
+ if mode == "fewshot":
86
+ dd = data / "fewshot_n5" / f"draw{j}"
87
+ train_donors = [x.strip() for x in (dd / "train_donors.txt").read_text().splitlines() if x.strip()]
88
+ test = [x.strip() for x in (dd / "test_samples.txt").read_text().splitlines() if x.strip()]
89
+ cond = dd / "test_raw.npz"
90
+ sources = {"train_donors.txt": dd / "train_donors.txt", "test_samples.txt": dd / "test_samples.txt"}
91
+ rep = np.flatnonzero(np.isin(donors, train_donors) & usable)
92
+ elif mode == "cv":
93
+ fold = folds["fold"].to_numpy()
94
+ test = sample_ids[fold == j].tolist()
95
+ rep = np.flatnonzero(usable & (fold != j))
96
+ train_donors = sorted(set(donors[rep]))
97
+ cond = data / f"fold{j}" / "test_raw.npz"
98
+ sources = {}
99
+ elif mode == "budget":
100
+ fold = folds["fold"].to_numpy()
101
+ rj = TASK / "runs" / ds / f"fold{j}" / f"lora_n{n}" / "RUN.json"
102
+ run = json.loads(rj.read_text())
103
+ if run["fold"] != j or (run.get("train_subset") or {}).get("train_n") != n:
104
+ raise SystemExit(f"{rj}: not the fold {j} n={n} learning-curve run")
105
+ fit = list(run["train_rows"]) + list(run["inner_val_rows"])
106
+ test = sample_ids[fold == j].tolist()
107
+ if sorted(run["test_rows_never_loaded_for_training"]) != sorted(test):
108
+ raise SystemExit(f"{rj}: its test rows differ from fold {j}'s rows")
109
+ pos = {s: i for i, s in enumerate(sample_ids)}
110
+ if len(set(fit)) != len(fit) or any(s not in pos for s in fit):
111
+ raise SystemExit(f"{rj}: duplicate or unknown fit rows")
112
+ rep = np.asarray(sorted(pos[s] for s in fit), dtype=np.int64)
113
+ if not (usable[rep] & (fold[rep] != j)).all():
114
+ raise SystemExit(f"{rj}: a fit row is unusable or in fold {j}")
115
+ cb = data / "CAL_BUDGET.json"
116
+ if cb.exists():
117
+ e = json.loads(cb.read_text())["folds"][str(j)]["n"][str(n)]
118
+ if sorted(e["fit_sample_ids"]) != sorted(fit) or e["lora_checkpoint_sha256"] != run["checkpoint_sha256"]:
119
+ raise SystemExit(f"{cb}: fold {j} n={n} fit rows / LoRA checkpoint differ from {rj}")
120
+ train_donors = sorted(set(donors[rep]))
121
+ cond = data / f"fold{j}" / "test_raw.npz"
122
+ sources = {"lora_RUN.json": rj, **({"CAL_BUDGET.json": cb} if cb.exists() else {})}
123
+ extra = {"budget": {"n": int(n), "fold": int(j), "lora_run": str(rj), "lora_checkpoint_sha256": run["checkpoint_sha256"],
124
+ "n_train_rows": len(run["train_rows"]), "n_inner_val_rows": len(run["inner_val_rows"]),
125
+ "train_rows": list(run["train_rows"]), "inner_val_rows": list(run["inner_val_rows"])}}
126
+ else:
127
+ raise SystemExit(f"unknown mode {mode}")
128
+ pos = {s: i for i, s in enumerate(sample_ids)}
129
+ miss = [s for s in test if s not in pos]
130
+ if miss:
131
+ raise SystemExit(f"test samples not in features.npz: {miss[:5]}")
132
+ tgt = np.asarray([pos[s] for s in test], dtype=np.int64)
133
+ if not usable[tgt].all():
134
+ raise SystemExit("a test row is not usable (fold -1)")
135
+ if set(donors[rep]) & set(donors[tgt]):
136
+ raise SystemExit("a donor is both representative and target")
137
+ if len(set(test)) != len(test):
138
+ raise SystemExit("duplicate test samples")
139
+ return {"rep": rep, "tgt": tgt, "train_donors": train_donors, "test": test, "condition": cond, "sources": sources,
140
+ **extra}
141
+
142
+
143
+ def main(argv=None) -> int:
144
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
145
+ ap.add_argument("--dataset", required=True)
146
+ ap.add_argument("--mode", choices=["fewshot", "cv", "budget"], default="fewshot")
147
+ ap.add_argument("--draw", type=int, help="fewshot draw index")
148
+ ap.add_argument("--fold", type=int, help="cv / budget fold index")
149
+ ap.add_argument("--n", type=int, help="budget: the LoRA learning-curve n (runs/<ds>/fold<k>/lora_n<n>)")
150
+ ap.add_argument("--work", type=Path, required=True)
151
+ ap.add_argument("--smoke-reps", type=int, default=0, help="SMOKE ONLY: keep the first N representative rows")
152
+ ap.add_argument("--smoke-cells", type=int, default=0, help="SMOKE ONLY: at most N cells per representative")
153
+ ap.add_argument("--smoke-targets", default="", help="SMOKE ONLY: comma list of target sample ids")
154
+ ap.add_argument("--smoke-rep-ids", default="", help="SMOKE ONLY: comma list of representative sample ids to keep")
155
+ ap.add_argument("--check-only", action="store_true", help="dry run: check everything, write nothing under --work")
156
+ ap.add_argument("--check-out", type=Path, default=None, help="--check-only: write the split summary JSON here")
157
+ ap.add_argument("--support-manifest", type=Path, default=None,
158
+ help="strict support.json; representatives are its exact n sample IDs")
159
+ a = ap.parse_args(argv)
160
+ if a.support_manifest is not None:
161
+ if a.draw is not None or a.fold is not None or a.n is not None:
162
+ raise SystemExit("--support-manifest cannot be combined with --draw/--fold/--n")
163
+ a.mode = "strict"
164
+ j = 0
165
+ else:
166
+ j = a.draw if a.mode == "fewshot" else a.fold
167
+ if j is None:
168
+ raise SystemExit("--draw (fewshot) or --fold (cv, budget) required")
169
+ if (a.mode == "budget") != (a.n is not None):
170
+ raise SystemExit("--n is required with --mode budget and only valid there")
171
+ smoke = bool(a.smoke_reps or a.smoke_cells or a.smoke_targets or a.smoke_rep_ids)
172
+ if a.support_manifest is not None and smoke:
173
+ raise SystemExit("strict support forbids smoke subsetting")
174
+ work = a.work.resolve()
175
+ if smoke and "/scsemi/smoke/" not in str(work) + "/":
176
+ raise SystemExit("smoke subsetting only under scsemi/smoke/")
177
+ out = work / "inputs"
178
+ if not a.check_only:
179
+ if (out / "inputs_manifest.json").exists():
180
+ raise SystemExit(f"{out}/inputs_manifest.json exists; inputs are immutable (preserve and inspect)")
181
+ out.mkdir(parents=True, exist_ok=True)
182
+ data = TASK / "data" / a.dataset
183
+ d = PD.load(data)
184
+ folds = pd.read_csv(data / "folds.csv")
185
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
186
+ raise SystemExit("folds.csv rows differ from features.npz")
187
+ s = split_rows(a.dataset, a.mode, j, d["sample_ids"], folds, n=a.n,
188
+ support_manifest=a.support_manifest)
189
+ rep, tgt = s["rep"], s["tgt"]
190
+ if a.smoke_rep_ids:
191
+ keep_r = set(a.smoke_rep_ids.split(","))
192
+ rep = np.asarray([r for r in rep if d["sample_ids"][r] in keep_r], dtype=np.int64)
193
+ if a.smoke_reps:
194
+ rep = rep[: a.smoke_reps]
195
+ if a.smoke_targets:
196
+ keep = set(a.smoke_targets.split(","))
197
+ tgt = np.asarray([t for t in tgt if d["sample_ids"][t] in keep], dtype=np.int64)
198
+ s["test"] = [x for x in s["test"] if x in keep]
199
+ if a.mode == "fewshot" and not smoke:
200
+ usable = np.flatnonzero(folds["fold"].to_numpy() >= 0)
201
+ if set(rep.tolist()) | set(tgt.tolist()) != set(usable.tolist()):
202
+ raise SystemExit("representatives + targets do not cover the usable rows")
203
+ # modeled genes
204
+ z = np.load(data / "cells_panel6k.npz", allow_pickle=False)
205
+ panel = z["panel_gene_ids"].astype(str)
206
+ gpos = {g: i for i, g in enumerate(d["gene_ids"])}
207
+ pcanon = np.asarray([gpos[g] for g in panel], dtype=np.int64)
208
+ rows = np.sort(np.concatenate([rep, tgt]))
209
+ bulk_ok = d["bulk_valid"][rows][:, pcanon].all(0)
210
+ sc_ok = d["sc_valid"][rep][:, pcanon].all(0)
211
+ model_pidx = np.flatnonzero(bulk_ok & sc_ok)
212
+ genes = panel[model_pidx]
213
+ if genes.size < 1000:
214
+ raise SystemExit(f"only {genes.size} modeled genes")
215
+ # scorer's scoring genes (all rows of the dataset) for the record
216
+ score_mask = d["bulk_valid"][:, pcanon].all(0) & d["sc_valid"][:, pcanon].all(0)
217
+ # bulk
218
+ import anndata as ad
219
+ B = d["bulk"][rows][:, pcanon[model_pidx]].astype(np.float64)
220
+ if not np.isfinite(B).all() or (B < 0).any():
221
+ raise SystemExit("non-finite or negative bulk on the modeled genes")
222
+ if (B.sum(1) <= 0).any():
223
+ raise SystemExit("a bulk row has no counts on the modeled genes")
224
+ sym = pd.read_csv(TASK.parents[1] / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv")
225
+ sym = sym.set_index("gene_id").gene_symbol.astype(str)
226
+ var = pd.DataFrame({"gene_symbol": sym.reindex(genes).to_numpy()}, index=pd.Index(genes, name="gene_id"))
227
+ obs_b = pd.DataFrame({"sample_ids": d["sample_ids"][rows], "donor_id": d["donor_ids"][rows],
228
+ "group": d["groups"][rows], "role": np.where(np.isin(rows, rep), "representative", "target")},
229
+ index=pd.Index(d["sample_ids"][rows], name="obs"))
230
+ if not a.check_only:
231
+ ad.AnnData(X=B, obs=obs_b, var=var).write_h5ad(out / "bulk.h5ad")
232
+ # representative cells
233
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
234
+ rs = np.asarray(z["row_sample"], dtype=np.int64)
235
+ blocks, obs_rows, per_rep = [], [], []
236
+ rng = np.random.default_rng(SEED)
237
+ for r in rep:
238
+ cells = np.flatnonzero(rs == r)
239
+ if a.smoke_cells and cells.size > a.smoke_cells:
240
+ cells = np.sort(rng.choice(cells, a.smoke_cells, replace=False))
241
+ Xr = X[cells][:, model_pidx].tocsr().astype(np.float32)
242
+ lib = np.asarray(Xr.sum(1)).ravel()
243
+ if (lib <= 0).any():
244
+ raise SystemExit(f"{d['sample_ids'][r]}: {int((lib <= 0).sum())} cells without counts on the modeled genes")
245
+ blocks.append(Xr)
246
+ obs_rows.append(pd.DataFrame({"sample_ids": d["sample_ids"][r], "donor_id": d["donor_ids"][r],
247
+ "source_cell_row": cells}))
248
+ per_rep.append({"sample_id": str(d["sample_ids"][r]), "donor_id": str(d["donor_ids"][r]),
249
+ "group": str(d["groups"][r]), "n_cells": int(cells.size),
250
+ "median_umi_modeled_genes": float(np.median(lib))})
251
+ Xs = sp.vstack(blocks, format="csr")
252
+ obs_s = pd.concat(obs_rows, ignore_index=True)
253
+ obs_s.index = pd.Index([f"{a_}|{b_}" for a_, b_ in zip(obs_s.sample_ids, obs_s.source_cell_row)], name="cell")
254
+ if not a.check_only:
255
+ ad.AnnData(X=Xs, obs=obs_s, var=var.copy()).write_h5ad(out / "rep_sc.h5ad")
256
+ lib_all = np.asarray(Xs.sum(1)).ravel()
257
+ depth = float(np.median(lib_all))
258
+ cond = s["condition"]
259
+ man = {
260
+ "schema": "scsemi_paired.inputs.v1", "written_utc": datetime.now(timezone.utc).isoformat(),
261
+ "dataset": a.dataset, "mode": a.mode, "split": j, "smoke": smoke,
262
+ "smoke_settings": {"reps": a.smoke_reps, "cells": a.smoke_cells, "targets": a.smoke_targets,
263
+ "rep_ids": a.smoke_rep_ids} if smoke else None,
264
+ "train_donors": s["train_donors"],
265
+ "representatives": per_rep, "targets": [str(x) for x in d["sample_ids"][tgt]],
266
+ "target_order_test_samples": s["test"],
267
+ "bulk_row_order": [str(x) for x in d["sample_ids"][rows]],
268
+ "n_representatives": int(rep.size), "n_targets": int(tgt.size), "n_rep_cells": int(Xs.shape[0]),
269
+ "modeled_genes": {"n": int(genes.size), "gene_ids": genes.tolist(), "panel_index": model_pidx.tolist(),
270
+ "rule": "6k panel genes with bulk_valid in every rep+target row and sc_valid in every rep row",
271
+ "equals_scorer_scoring_genes": bool(np.array_equal(model_pidx, np.flatnonzero(score_mask))),
272
+ "n_scorer_scoring_genes": int(score_mask.sum())},
273
+ "depth": {"value": depth, "rule": "median over all representative cells (all rows of the training donors) of the "
274
+ "per-cell UMI sum on the modeled genes; every generated cell is scaled to this expected library",
275
+ "n_cells": int(lib_all.size)},
276
+ "condition_npz": str(cond), "condition_sha256": sha(cond),
277
+ "sources": {"features.npz": sha(data / "features.npz"), "folds.csv": sha(data / "folds.csv"),
278
+ "cells_panel6k.npz": sha(data / "cells_panel6k.npz"),
279
+ **{k: sha(v) for k, v in s["sources"].items()}},
280
+ "files": ({"bulk.h5ad": sha(out / "bulk.h5ad"), "rep_sc.h5ad": sha(out / "rep_sc.h5ad")}
281
+ if not a.check_only else None),
282
+ "builder_sha256": sha(Path(__file__)),
283
+ }
284
+ if a.mode == "strict":
285
+ man["support_sha256"] = s["support_sha256"]
286
+ man["target_donors"] = s["target_donors"]
287
+ if a.mode == "budget":
288
+ man["target_donors"] = sorted({str(x) for x in d["donor_ids"][tgt]})
289
+ man["budget"] = s["budget"]
290
+ with np.load(cond, allow_pickle=False) as cz:
291
+ cond_ids = cz["sample_ids"].astype(str).tolist()
292
+ if not smoke and sorted(cond_ids) != sorted(man["targets"]):
293
+ raise SystemExit("condition NPZ sample_ids differ from the targets")
294
+ man["condition_sample_order"] = cond_ids
295
+ if a.check_only:
296
+ summary = {"dataset": a.dataset, "mode": a.mode, "split": j, "n": a.n, "work": str(work),
297
+ "reps": [r["sample_id"] for r in per_rep], "targets": man["targets"],
298
+ "rep_cells": {r["sample_id"]: r["n_cells"] for r in per_rep}, "n_rep_cells": int(Xs.shape[0]),
299
+ "modeled_genes": int(genes.size), "modeled_panel_index": model_pidx.tolist(),
300
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"],
301
+ "depth": depth, "condition_npz": str(cond), "condition_matches_targets": True,
302
+ "train_donors": s["train_donors"], **({"budget": s["budget"]} if a.mode == "budget" else {})}
303
+ if a.check_out is not None:
304
+ a.check_out.parent.mkdir(parents=True, exist_ok=True)
305
+ a.check_out.write_text(json.dumps(summary, indent=1) + "\n")
306
+ print(json.dumps({k: summary[k] for k in ("dataset", "mode", "split", "n", "n_rep_cells", "modeled_genes",
307
+ "equals_scorer_genes", "depth")} | {"reps": len(summary["reps"]),
308
+ "targets": len(summary["targets"])}))
309
+ return 0
310
+ tmp = out / "inputs_manifest.json.tmp"
311
+ tmp.write_text(json.dumps(man, indent=1) + "\n")
312
+ tmp.replace(out / "inputs_manifest.json")
313
+ print(json.dumps({"dataset": a.dataset, "mode": a.mode, "split": j, "reps": int(rep.size), "targets": int(tgt.size),
314
+ "rep_cells": int(Xs.shape[0]), "modeled_genes": int(genes.size),
315
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"], "depth": depth}))
316
+ return 0
317
+
318
+
319
+ if __name__ == "__main__":
320
+ 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/runs/immicro/healthy/fold0/n5/lora/RUN.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "pbisc_sdd.ft_intradataset.run.v1",
3
+ "source_checkpoint": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt",
4
+ "source_checkpoint_sha256": "8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633",
5
+ "dataset_dir": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/immicro",
6
+ "condition_npz": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/immicro/conditions_raw_fixed.npz",
7
+ "condition_npz_sha256": "2be5717d19e86bdf38e4838d4bd2886a211ba78bfbfe749c458305a3e0ac2dcc",
8
+ "fold": 0,
9
+ "mode": "lora",
10
+ "trainable": {
11
+ "mode": "lora",
12
+ "lora_layers": [
13
+ "time_encoder.0",
14
+ "time_encoder.2",
15
+ "condition_encoder.0",
16
+ "condition_encoder.3",
17
+ "context_mixer.2",
18
+ "down_blocks.0.input_projection",
19
+ "down_blocks.0.context_projection.1",
20
+ "down_blocks.1.input_projection",
21
+ "down_blocks.1.context_projection.1",
22
+ "down_blocks.2.input_projection",
23
+ "down_blocks.2.context_projection.1",
24
+ "down_blocks.3.input_projection",
25
+ "down_blocks.3.context_projection.1",
26
+ "up_blocks.0.input_projection",
27
+ "up_blocks.0.context_projection.1",
28
+ "up_blocks.1.input_projection",
29
+ "up_blocks.1.context_projection.1",
30
+ "up_blocks.2.input_projection",
31
+ "up_blocks.2.context_projection.1",
32
+ "output_trunk.0",
33
+ "value_head",
34
+ "active_head"
35
+ ],
36
+ "lora_rank": 16,
37
+ "lora_alpha": 16.0,
38
+ "n_trainable": 1296224,
39
+ "n_total_base": 54185184,
40
+ "trainable_tensors": 44
41
+ },
42
+ "lr": 0.0005,
43
+ "warmup": 200,
44
+ "batch_size": 256,
45
+ "ema_decay": 0.999,
46
+ "max_steps": 3000,
47
+ "steps_run": 3000,
48
+ "eval_every": 250,
49
+ "patience": 8,
50
+ "train_subset": null,
51
+ "train_donors_file": null,
52
+ "support_manifest": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/protocol/splits/immicro/healthy/fold0/n5/support.json",
53
+ "support_sha256": "85c04462a9c768c205fc0adfcb0a40e5f94f504a93d6d822944387bc055b65d4",
54
+ "train_donor_ids": [
55
+ "HS40",
56
+ "HS30",
57
+ "HS53",
58
+ "HS39",
59
+ "HS109"
60
+ ],
61
+ "excluded_selected_donor_visits": [],
62
+ "fixed_steps": 3000,
63
+ "selected_step": 3000,
64
+ "selected_inner_val_loss": NaN,
65
+ "pretrained_inner_val_loss": NaN,
66
+ "train_rows": [
67
+ "HS30",
68
+ "HS39",
69
+ "HS40",
70
+ "HS53",
71
+ "HS109"
72
+ ],
73
+ "inner_val_rows": [],
74
+ "test_rows_never_loaded_for_training": [
75
+ "HS3",
76
+ "HS6",
77
+ "HS7",
78
+ "HS13",
79
+ "HS18",
80
+ "HS31",
81
+ "HS34",
82
+ "HS37",
83
+ "HS38",
84
+ "HS52",
85
+ "HS58",
86
+ "HS60",
87
+ "HS66",
88
+ "HS81",
89
+ "HS82",
90
+ "HS83",
91
+ "HS85",
92
+ "HS86",
93
+ "HS95",
94
+ "HS98",
95
+ "HS101",
96
+ "HS107"
97
+ ],
98
+ "max_abs_weight_change": 0.5038369297981262,
99
+ "n_tensors_changed": 22,
100
+ "seed": 20260927,
101
+ "wall_seconds": 113.0,
102
+ "written_utc": "2026-10-12T10:58:15.169906+00:00",
103
+ "checkpoint_sha256": "51eb269bf13e9ead76da3fdd3bb9ca6400c2de7014f85286ecc0e0c11ad9df11",
104
+ "reload_forward_max_abs_diff": 0.0
105
+ }