junidude14 commited on
Commit
452cabb
·
verified ·
1 Parent(s): 0a5cdc7

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/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/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/hvset_dependence.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Does a representative's pretraining input depend on the split? Gene axis and hvset per split (CPU only; 2026-10-02).
3
+
4
+ A representative r's pretraining reads sample_sc/<r>.h5ad, geneset_scores/<r>.npy and hvset.npy (vendor
5
+ inference.setdata) and is seeded with base + 1000/2000 + r's bulk row index. geneset_scores/<r> depends only on r's
6
+ cells and the modeled gene axis; sample_sc/<r> also stores feature_var over [genes, gene-set scores[:, hvset]]; and
7
+ hvset.npy is selected on the POOLED gene-set scores of all representatives of the split (upstream scprocess). So r's
8
+ pretraining is reusable across splits only where the gene axis, hvset and seed index coincide. This tool measures,
9
+ per cohort, the modeled gene axis and the exact hvset (tools/lean_hvset.py arithmetic, streamed) of
10
+ cv<k> representatives = every usable row not in fold k (design A)
11
+ b<k>_n<n> representatives = runs/<ds>/fold<k>/lora_n<n>/RUN.json train_rows + inner_val_rows (design B)
12
+ cohort every usable row (the 'cohort-fixed' alternative; it includes each fold's test donors' cells)
13
+ and validates the streamed hvset on every prepared few-pair draw it can see (exact equality with its hvset.npy, whose
14
+ sha256 is in prepared.json; Imperial draws from --fewshot-extra copies of server_2's inputs_manifest/hvset).
15
+ --lean-check WORK [...]: additionally runs tools/lean_hvset.cohort_hvset_lean on WORK/inputs/rep_sc.h5ad and the
16
+ original dense cohort_hvset, and compares means, variances (bitwise) and hvset.npy bytes with prepared.json.
17
+ usage (cwd = scsemi/, CUDA hidden, through tools/cpu_unit.sh):
18
+ hvset_dependence.py --out validation/hvset_dependence_20261002.json [--datasets a,b] [--fewshot-extra DIR]
19
+ [--lean-check WORK ...]
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import hashlib
25
+ import itertools
26
+ import json
27
+ import os
28
+ import sys
29
+ import time
30
+ from datetime import datetime, timezone
31
+ from pathlib import Path
32
+
33
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
34
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
35
+
36
+ import numpy as np
37
+ import pandas as pd
38
+ import scipy.sparse as sp
39
+
40
+ HERE = Path(__file__).resolve().parents[1]
41
+ TASK = HERE.parent
42
+ sys.path.insert(0, str(HERE / "vendor/scSemiProfiler"))
43
+ sys.path.insert(0, str(HERE / "tools"))
44
+ sys.path.insert(0, str(TASK / "tools"))
45
+ import lean_hvset as L # noqa: E402
46
+ import prepare_dataset as PD # noqa: E402
47
+
48
+ DATASETS = ("ji2025_chili", "giroux2022", "ye2026_sepsis", "immicro", "imperial_eskd")
49
+ NS = (5, 10, 20, 40)
50
+ THRESHOLD = 1e-3
51
+
52
+
53
+ def sha_bytes(b: bytes) -> str:
54
+ return hashlib.sha256(b).hexdigest()
55
+
56
+
57
+ def hvset_npy_sha(h: np.ndarray) -> str:
58
+ import io
59
+ buf = io.BytesIO()
60
+ np.save(buf, np.asarray(h, dtype=bool))
61
+ return sha_bytes(buf.getvalue())
62
+
63
+
64
+ class Cohort:
65
+ def __init__(self, ds: str):
66
+ import anndata # noqa: F401 (scanpy import order as the wrapper)
67
+ self.ds = ds
68
+ data = TASK / "data" / ds
69
+ self.d = PD.load(data)
70
+ self.folds = pd.read_csv(data / "folds.csv")
71
+ if not np.array_equal(self.folds["sample_id"].astype(str).to_numpy(), self.d["sample_ids"]):
72
+ raise SystemExit("folds.csv rows differ from features.npz")
73
+ z = np.load(data / "cells_panel6k.npz", allow_pickle=False)
74
+ self.panel = z["panel_gene_ids"].astype(str)
75
+ self.X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
76
+ self.rs = np.asarray(z["row_sample"], dtype=np.int64)
77
+ gpos = {g: i for i, g in enumerate(self.d["gene_ids"])}
78
+ self.pcanon = np.asarray([gpos[g] for g in self.panel], dtype=np.int64)
79
+ self.sid = self.d["sample_ids"]
80
+ self.pos = {s: i for i, s in enumerate(self.sid)}
81
+ self.fold = self.folds["fold"].to_numpy()
82
+ self.usable = self.fold >= 0
83
+ self.n_cells = np.bincount(self.rs, minlength=self.sid.size)
84
+ self._gsm = {}
85
+
86
+ def axis(self, rep: np.ndarray, tgt: np.ndarray) -> np.ndarray:
87
+ """prepare_draw_inputs rule: bulk_valid in every rep+target row, sc_valid in every rep row (panel indices)."""
88
+ rows = np.sort(np.concatenate([rep, tgt]))
89
+ bulk_ok = self.d["bulk_valid"][rows][:, self.pcanon].all(0)
90
+ sc_ok = self.d["sc_valid"][rep][:, self.pcanon].all(0)
91
+ return np.flatnonzero(bulk_ok & sc_ok)
92
+
93
+ def gsm(self, pidx: np.ndarray) -> np.ndarray:
94
+ key = pidx.tobytes()
95
+ if key not in self._gsm:
96
+ self._gsm[key] = L.gene_set_matrix([g.upper() for g in self.panel[pidx]])
97
+ return self._gsm[key]
98
+
99
+ def hvset(self, rep: np.ndarray, pidx: np.ndarray) -> np.ndarray:
100
+ """Streamed hvset of a representative set, representatives in sorted sample-id order (np.unique, as upstream),
101
+ each one's cells built exactly as prepare_draw_inputs writes rep_sc.h5ad."""
102
+ import anndata
103
+ gsm = self.gsm(pidx)
104
+ var = pd.DataFrame(index=pd.Index(self.panel[pidx], name="gene_id"))
105
+ mom = L.Moments()
106
+ for s in np.unique(self.sid[rep]):
107
+ r = self.pos[s]
108
+ cells = np.flatnonzero(self.rs == r)
109
+ Xr = self.X[cells][:, pidx].tocsr().astype(np.float32)
110
+ a = anndata.AnnData(X=Xr, var=var.copy())
111
+ mom.add_scores(L.sample_scores(a, gsm, THRESHOLD))
112
+ del a, Xr
113
+ return L.hvset_from_moments(mom)
114
+
115
+
116
+ def lora_rows(ds: str, k: int, run: str, extra: Path | None) -> dict | None:
117
+ p = TASK / "runs" / ds / f"fold{k}" / run / "RUN.json"
118
+ if not p.exists() and extra is not None:
119
+ p = extra / f"fold{k}" / run / "RUN.json"
120
+ if not p.exists():
121
+ return None
122
+ j = json.loads(p.read_text())
123
+ return {"path": str(p), "fit": list(j["train_rows"]) + list(j["inner_val_rows"]),
124
+ "test": list(j["test_rows_never_loaded_for_training"]), "n_train": len(j["train_rows"]),
125
+ "n_inner_val": len(j["inner_val_rows"])}
126
+
127
+
128
+ def compare(a: np.ndarray, b: np.ndarray) -> dict:
129
+ inter, union = int((a & b).sum()), int((a | b).sum())
130
+ return {"n_a": int(a.sum()), "n_b": int(b.sum()), "sym_diff": int((a ^ b).sum()), "only_a": int((a & ~b).sum()),
131
+ "only_b": int((b & ~a).sum()), "jaccard": round(inter / union, 4) if union else 1.0}
132
+
133
+
134
+ def lean_check(work: Path) -> dict:
135
+ """Dense cohort_hvset (the wrapper's own function) vs lean_hvset on one prepared split: bitwise means/vars + bytes."""
136
+ import shutil
137
+ import tempfile
138
+ import run_scsemi_paired as RSP
139
+ import scanpy.preprocessing._highly_variable_genes as H
140
+ rec, cap = {}, {}
141
+ tmp = Path(tempfile.mkdtemp(prefix="leanchk_", dir=os.environ.get("TMPDIR", "/tmp")))
142
+ (tmp / "dense").mkdir()
143
+ (tmp / "lean").mkdir()
144
+ orig = H._get_mean_var
145
+
146
+ def spy(x, *a, **k):
147
+ m, v = orig(x, *a, **k)
148
+ rec["mv"] = (m.copy(), v.copy())
149
+ return m, v
150
+ H._get_mean_var = spy
151
+ try:
152
+ t0 = time.monotonic()
153
+ hd = np.asarray(RSP.cohort_hvset(tmp / "dense", work / "inputs/rep_sc.h5ad", THRESHOLD))
154
+ td = time.monotonic() - t0
155
+ finally:
156
+ H._get_mean_var = orig
157
+ orig_hfm = L.hvset_from_moments
158
+
159
+ def hfm(mom):
160
+ cap["mv"] = mom.mean_var()
161
+ return orig_hfm(mom)
162
+ L.hvset_from_moments = hfm
163
+ try:
164
+ t0 = time.monotonic()
165
+ hl = L.cohort_hvset_lean(tmp / "lean", work / "inputs/rep_sc.h5ad", THRESHOLD)
166
+ tl = time.monotonic() - t0
167
+ finally:
168
+ L.hvset_from_moments = orig_hfm
169
+ sd = sha_bytes((tmp / "dense/hvset.npy").read_bytes())
170
+ sl = sha_bytes((tmp / "lean/hvset.npy").read_bytes())
171
+ sp_ = json.loads((work / "prepared.json").read_text())["files"]["hvset.npy"]
172
+ shutil.rmtree(tmp)
173
+ out = {"work": str(work), "mean_bitwise": bool(np.array_equal(rec["mv"][0], cap["mv"][0])),
174
+ "var_bitwise": bool(np.array_equal(rec["mv"][1], cap["mv"][1])), "hvset_equal": bool(np.array_equal(hd, hl)),
175
+ "sha_dense": sd, "sha_lean": sl, "sha_prepared": sp_, "seconds_dense": round(td, 1),
176
+ "seconds_lean": round(tl, 1), "n_rep_cells": json.loads((work / "inputs/inputs_manifest.json").read_text())["n_rep_cells"]}
177
+ out["identical"] = out["mean_bitwise"] and out["var_bitwise"] and out["hvset_equal"] and sd == sl == sp_
178
+ print(json.dumps(out), flush=True)
179
+ return out
180
+
181
+
182
+ def main(argv=None) -> int:
183
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
184
+ ap.add_argument("--out", type=Path, required=True)
185
+ ap.add_argument("--datasets", default=",".join(DATASETS))
186
+ ap.add_argument("--fewshot-extra", type=Path, default=None,
187
+ help="dir with <ds>/draw<j>/{inputs_manifest.json,hvset.npy,prepared.json} copied from another host")
188
+ ap.add_argument("--runs-extra", type=Path, default=None,
189
+ help="dir with <ds>/fold<k>/<run>/RUN.json copied from another host (Imperial lives on server_2)")
190
+ ap.add_argument("--lean-check", nargs="*", type=Path, default=[])
191
+ ap.add_argument("--skip-budget", action="store_true")
192
+ a = ap.parse_args(argv)
193
+ os.chdir(HERE) # upstream getGeneSetMatrix reads genesets/ relative to the cwd (the mapped GMT)
194
+ assets = json.loads((HERE / "genesets/geneset_assets.json").read_text())
195
+ if sha_bytes((HERE / "genesets/c2.cp.v7.4.symbols.gmt").read_bytes()) != assets["mapped_gmt_sha256"]:
196
+ raise SystemExit("mapped GMT hash mismatch")
197
+ res = {"written_utc": None, "host": os.uname().nodename, "tool_sha256": sha_bytes(Path(__file__).read_bytes()),
198
+ "lean_hvset_sha256": sha_bytes((HERE / "tools/lean_hvset.py").read_bytes()), "lean_check": [], "datasets": {}}
199
+ for w in a.lean_check:
200
+ res["lean_check"].append(lean_check(w.resolve()))
201
+ for ds in [x for x in a.datasets.split(",") if x]:
202
+ t_ds = time.monotonic()
203
+ C = Cohort(ds)
204
+ usable = np.flatnonzero(C.usable)
205
+ R = {"n_rows": int(C.sid.size), "n_usable": int(usable.size), "n_cells_usable": int(C.n_cells[usable].sum()),
206
+ "axes": {}, "hvsets": {}, "fewshot_validation": [], "splits": {}}
207
+ # ---- splits
208
+ splits = {}
209
+ for k in range(5):
210
+ rep = np.flatnonzero(C.usable & (C.fold != k))
211
+ tgt = np.flatnonzero(C.fold == k)
212
+ lr = lora_rows(ds, k, "real_lora", a.runs_extra / ds if a.runs_extra else None)
213
+ chk = None
214
+ if lr is not None:
215
+ chk = {"lora_run": lr["path"], "reps_equal_lora_fit_rows": sorted(C.sid[rep].tolist()) == sorted(lr["fit"]),
216
+ "targets_equal_lora_test_rows": sorted(C.sid[tgt].tolist()) == sorted(lr["test"]),
217
+ "n_lora_train": lr["n_train"], "n_lora_inner_val": lr["n_inner_val"]}
218
+ splits[f"cv{k}"] = (rep, tgt, chk)
219
+ if not a.skip_budget:
220
+ for n in NS:
221
+ lr = lora_rows(ds, k, f"lora_n{n}", None)
222
+ if lr is None:
223
+ continue
224
+ rep_b = np.asarray(sorted(C.pos[s] for s in lr["fit"]), dtype=np.int64)
225
+ chk = {"lora_run": lr["path"], "n_train": lr["n_train"], "n_inner_val": lr["n_inner_val"],
226
+ "targets_equal_lora_test_rows": sorted(C.sid[tgt].tolist()) == sorted(lr["test"]),
227
+ "reps_subset_of_cv_reps": bool(set(rep_b.tolist()) <= set(rep.tolist()))}
228
+ cb = TASK / "data" / ds / "CAL_BUDGET.json"
229
+ if cb.exists():
230
+ e = json.loads(cb.read_text())["folds"][str(k)]["n"][str(n)]
231
+ chk["reps_equal_cal_budget_fit"] = sorted(e["fit_sample_ids"]) == sorted(C.sid[rep_b].tolist())
232
+ splits[f"b{k}_n{n}"] = (rep_b, tgt, chk)
233
+ splits["cohort"] = (usable, np.zeros(0, dtype=np.int64), None)
234
+ cohort_axis = C.axis(usable, np.zeros(0, dtype=np.int64))
235
+ all_rows = np.arange(C.sid.size)
236
+ scorer_axis = np.flatnonzero(C.d["bulk_valid"][:, C.pcanon].all(0) & C.d["sc_valid"][:, C.pcanon].all(0))
237
+ R["axes"]["cohort_usable"] = {"n": int(cohort_axis.size)}
238
+ R["axes"]["scorer_all_rows"] = {"n": int(scorer_axis.size),
239
+ "equals_cohort_usable": bool(np.array_equal(scorer_axis, cohort_axis))}
240
+ del all_rows
241
+ axes = {}
242
+ for name, (rep, tgt, chk) in splits.items():
243
+ ax = C.axis(rep, tgt)
244
+ axes[name] = ax
245
+ R["splits"][name] = {"n_reps": int(rep.size), "n_targets": int(tgt.size), "n_rep_cells": int(C.n_cells[rep].sum()),
246
+ "n_modeled_genes": int(ax.size),
247
+ "axis_equals_cohort_fixed": bool(np.array_equal(ax, cohort_axis)),
248
+ "axis_only_split": int(np.setdiff1d(ax, cohort_axis).size),
249
+ "axis_only_cohort": int(np.setdiff1d(cohort_axis, ax).size), "lora_check": chk}
250
+ # ---- few-pair validation (exactness of the streamed hvset)
251
+ draws = []
252
+ for W in sorted((HERE / "work" / ds / "fewshot_n5").glob("draw*")):
253
+ if (W / "prepared.json").exists():
254
+ draws.append((W.name, json.loads((W / "inputs/inputs_manifest.json").read_text()),
255
+ json.loads((W / "prepared.json").read_text())["files"]["hvset.npy"], str(W)))
256
+ if a.fewshot_extra is not None:
257
+ for W in sorted((a.fewshot_extra / ds).glob("draw*")):
258
+ if (W / "prepared.json").exists() and W.name not in {x[0] for x in draws}:
259
+ draws.append((W.name, json.loads((W / "inputs_manifest.json").read_text()),
260
+ json.loads((W / "prepared.json").read_text())["files"]["hvset.npy"], str(W)))
261
+ for name, man, want, src in draws:
262
+ rep = np.asarray(sorted(C.pos[r["sample_id"]] for r in man["representatives"]), dtype=np.int64)
263
+ pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
264
+ t0 = time.monotonic()
265
+ h = C.hvset(rep, pidx)
266
+ got = hvset_npy_sha(h)
267
+ R["fewshot_validation"].append({"draw": name, "source": src, "n_reps": int(rep.size),
268
+ "n_selected": int(h.sum()), "hvset_sha_equals_prepared": got == want,
269
+ "seconds": round(time.monotonic() - t0, 1)})
270
+ print(ds, name, "streamed hvset == prepared:", got == want, flush=True)
271
+ # ---- hvsets of the planned splits
272
+ H = {}
273
+ for name, (rep, tgt, chk) in splits.items():
274
+ t0 = time.monotonic()
275
+ H[name] = C.hvset(rep, axes[name])
276
+ R["splits"][name]["n_selected_gene_sets"] = int(H[name].sum())
277
+ R["splits"][name]["hvset_sha256"] = hvset_npy_sha(H[name])
278
+ R["splits"][name]["hvset_seconds"] = round(time.monotonic() - t0, 1)
279
+ print(ds, name, "reps", rep.size, "selected", int(H[name].sum()), f"{time.monotonic() - t0:.0f}s", flush=True)
280
+ cv = [f"cv{k}" for k in range(5)]
281
+ R["hvsets"]["cv_pairwise"] = {f"{x}_vs_{y}": compare(H[x], H[y]) for x, y in itertools.combinations(cv, 2)}
282
+ R["hvsets"]["cv_vs_cohort"] = {x: compare(H[x], H["cohort"]) for x in cv}
283
+ R["hvsets"]["cv_all_identical"] = all(np.array_equal(H[cv[0]], H[x]) for x in cv[1:])
284
+ R["hvsets"]["cv_union"] = int(np.any([H[x] for x in cv], axis=0).sum())
285
+ R["hvsets"]["cv_intersection"] = int(np.all([H[x] for x in cv], axis=0).sum())
286
+ bud = [x for x in H if x.startswith("b")]
287
+ R["hvsets"]["budget_vs_cv_same_fold"] = {x: compare(H[x], H["cv" + x[1]]) for x in bud}
288
+ R["seconds"] = round(time.monotonic() - t_ds, 1)
289
+ res["datasets"][ds] = R
290
+ del C
291
+ res["written_utc"] = datetime.now(timezone.utc).isoformat()
292
+ a.out.parent.mkdir(parents=True, exist_ok=True)
293
+ a.out.write_text(json.dumps(res, indent=1) + "\n")
294
+ ok_val = all(v["hvset_sha_equals_prepared"] for R in res["datasets"].values() for v in R["fewshot_validation"])
295
+ ok_lean = all(x["identical"] for x in res["lean_check"])
296
+ print(json.dumps({"out": str(a.out), "fewshot_streamed_equal_prepared": ok_val, "lean_check_identical": ok_lean}))
297
+ return 0 if (ok_val and ok_lean) else 1
298
+
299
+
300
+ if __name__ == "__main__":
301
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/lean_hvset.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Memory-lean, output-identical replacement for run_scsemi_paired.cohort_hvset (CPU only). Added 2026-10-02.
2
+
3
+ cohort_hvset (upstream scprocess's hvset block) concatenates every representative cell's gene-set scores (cells x 2,922
4
+ float64, 23 KiB per cell) and runs scanpy's seurat highly_variable_genes on the log1p'd matrix, which holds three dense
5
+ copies at once (log1p'd matrix, its expm1 copy, the squared copy): ~70 KiB per representative cell. That fits the
6
+ 16 GiB CPU cap for a few-pair draw (<= 156k cells) but not for a CV fold (sepsis ~490k cells -> ~34 GiB).
7
+
8
+ This version produces the same bits with one representative in memory at a time:
9
+ * scores: the same code as cohort_hvset, representative by representative in the same order (sorted sample ids);
10
+ * the same elementwise steps: log1p (scanpy log1p on the AnnData, in place), then expm1 of a copy (scanpy seurat);
11
+ * scanpy's dense _get_mean_var takes x.mean(axis=0, dtype=float64) and (x*x).mean(axis=0, dtype=float64). numpy's
12
+ axis-0 add.reduce on a C-contiguous array accumulates row by row in order, so continuing the reduction from the
13
+ running sum (add.reduce over [running_sum; next block]) gives the same sums bit for bit; mean = sum / n as np.mean;
14
+ * the mean / variance are handed to the installed scanpy's own _highly_variable_genes_single_batch (only its
15
+ _get_mean_var call is substituted for this one call), so binning, dispersion normalisation and cutoffs are scanpy's.
16
+ Bit-identity is checked, not assumed: tools/hvset_dependence.py --validate compares means, variances and hvset with the
17
+ dense path and with every prepared few-pair draw's hvset.npy (validation/lean_hvset_*.json).
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import numpy as np
22
+
23
+ GMT = "c2.cp.v7.4.symbols.gmt"
24
+ N_PATHWAYS = 2922
25
+
26
+
27
+ def gene_set_matrix(genes_upper: list[str], gene_sets_path: str = "genesets/") -> np.ndarray:
28
+ """Upstream getGeneSetMatrix (cohort_hvset calls it once per representative with the same genes; it is a pure
29
+ function of the genes and the GMT, so it is evaluated once here)."""
30
+ from scSemiProfiler.singlecell_process import getGeneSetMatrix
31
+ gsm, _ = getGeneSetMatrix(GMT, genes_upper, gene_sets_path)
32
+ return np.array(gsm)
33
+
34
+
35
+ def sample_scores(a, gsm: np.ndarray, threshold: float) -> np.ndarray:
36
+ """cohort_hvset's per-representative block, verbatim: a = that representative's cells (AnnData copy, raw counts)."""
37
+ import scanpy as sc
38
+ sc.pp.normalize_total(a, target_sum=1e4)
39
+ X = np.array(a.X.todense())
40
+ X = X * np.array(X > 1e4 * threshold)
41
+ zp = X.dot(np.array(gsm).T)
42
+ eps = 1e-6
43
+ den = (np.array(gsm.sum(axis=1)) + eps)
44
+ zp = (zp + eps) / den
45
+ zp = zp - eps / den
46
+ return zp
47
+
48
+
49
+ class Moments:
50
+ """Running column sums of x and x*x in row order (numpy axis-0 reduction continued block by block)."""
51
+
52
+ def __init__(self) -> None:
53
+ self.n = 0
54
+ self.s1 = None
55
+ self.s2 = None
56
+
57
+ def add_scores(self, zp: np.ndarray) -> None:
58
+ x = np.log1p(zp) # scanpy log1p_array: np.log1p(x, out=x)
59
+ np.expm1(x, out=x) # scanpy seurat: x = x.copy(); np.expm1(x, out=x)
60
+ x2 = x * x # scanpy elem_mul(x, x)
61
+ if self.s1 is None:
62
+ self.s1 = np.add.reduce(x, axis=0, dtype=np.float64)
63
+ self.s2 = np.add.reduce(x2, axis=0, dtype=np.float64)
64
+ else:
65
+ self.s1 = np.add.reduce(np.concatenate([self.s1[None, :], x]), axis=0, dtype=np.float64)
66
+ self.s2 = np.add.reduce(np.concatenate([self.s2[None, :], x2]), axis=0, dtype=np.float64)
67
+ self.n += x.shape[0]
68
+
69
+ def mean_var(self) -> tuple[np.ndarray, np.ndarray]:
70
+ """scanpy _get_mean_var (dense branch) from the running sums."""
71
+ n = self.n
72
+ mean = np.true_divide(self.s1, n)
73
+ mean_sq = np.true_divide(self.s2, n)
74
+ var = mean_sq - mean ** 2
75
+ if n != 1:
76
+ var *= n / (n - 1)
77
+ return mean, var
78
+
79
+
80
+ def hvset_from_moments(mom: Moments) -> np.ndarray:
81
+ """scanpy.pp.highly_variable_genes(zdata) defaults (flavor seurat, min_mean 0.0125, max_mean 3, min_disp 0.5,
82
+ n_bins 20) on the pooled scores, through scanpy's own single-batch function with _get_mean_var substituted."""
83
+ import anndata
84
+ import scanpy as sc
85
+ import scanpy.preprocessing._highly_variable_genes as H
86
+ mean, var = mom.mean_var()
87
+ p = mean.shape[0]
88
+ dummy = anndata.AnnData(np.zeros((2, p))) # never read: _get_mean_var below ignores its argument
89
+ sc.pp.log1p(dummy) # same uns['log1p'] (base None) as zdata
90
+ orig = H._get_mean_var
91
+ H._get_mean_var = lambda _x, *args, **kw: (mean.copy(), var.copy())
92
+ try:
93
+ sc.pp.highly_variable_genes(dummy)
94
+ finally:
95
+ H._get_mean_var = orig
96
+ return np.asarray(dummy.var.highly_variable)
97
+
98
+
99
+ def cohort_hvset_lean(project, rep_sc, threshold: float) -> np.ndarray:
100
+ """Drop-in for run_scsemi_paired.cohort_hvset: same inputs, same hvset.npy (np.save of a bool array)."""
101
+ import anndata
102
+ R = anndata.read_h5ad(rep_sc)
103
+ sids = np.unique(R.obs["sample_ids"])
104
+ genes_upper = [g.upper() for g in list(R.var.index)]
105
+ gsm = gene_set_matrix(genes_upper)
106
+ mom = Moments()
107
+ for sid in sids:
108
+ a = R[(R.obs["sample_ids"] == sid).to_numpy()].copy()
109
+ mom.add_scores(sample_scores(a, gsm, threshold))
110
+ del a
111
+ hvset = hvset_from_moments(mom)
112
+ np.save(str(project) + "/hvset.npy", hvset)
113
+ return hvset
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/make_queues.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Write the scSemiProfiler baseline queues.
3
+ # queues/server1_fewshot.txt : ji2025_chili, giroux2022, ye2026_sepsis, immicro (draws 0-4), run on server_1
4
+ # queues/server2_fewshot.txt : imperial_eskd (draws 0-4), run on server_2 (its data and outputs live there)
5
+ # queues/server1_cv.txt : OPTIONAL 5-fold CV variant (representatives = all training donors of fold k);
6
+ # expensive, see README "CV variant cost"; not started by default
7
+ set -euo pipefail
8
+ S=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi
9
+ mkdir -p "$S/queues"
10
+ # ---- 2026-10-02: 5-fold CV (A) + equal pair budget (B), server_1 only. Written only with the argument cv_budget_20261002
11
+ # (then nothing else is written; without it this script writes exactly the three queues below, as before).
12
+ # server1_cv_budget_20261002.txt recommended order: Ji (canary) -> ImMicro A -> ImMicro B (n 5,10,20,40) ->
13
+ # sepsis A -> sepsis B -> Giroux A -> Imperial A; B reuses A's fold pretraining
14
+ # server1_cv_budget_20261002_userorder.txt the requested order: Ji, Giroux A -> sepsis, ImMicro A -> B (n-major) -> Imperial A
15
+ # server1_budget_plain_20261002.txt OPTIONAL plain B (own hvset + own pretraining per split; ~3 extra GPU days)
16
+ if [[ "${1:-}" == cv_budget_20261002 ]]; then
17
+ # cv lines of cohorts without budget lines offload right away; ImMicro / sepsis CV runs stay until their budget lines ran
18
+ cvl() { for k in 0 1 2 3 4; do echo "cv|$1|$k|lean_hvset,clean_prepared${2:-}"; done; }
19
+ bl() { for n in 5 10 20 40; do for k in 0 1 2 3 4; do echo "budget|$1|$k|reuse_cv,clean_prepared,offload|$n"; done; done; }
20
+ {
21
+ echo "# scSemiProfiler A (5-fold CV, representatives = LoRA real_lora train + inner-val rows) and B (equal pair budget,"
22
+ echo "# representatives = lora_n<n> train + inner-val rows, pretraining reused from A of the same fold), server_1, 2026-10-02"
23
+ cvl ji2025_chili ,offload; cvl immicro; bl immicro; echo "offload|immicro|cv"
24
+ cvl ye2026_sepsis; bl ye2026_sepsis; echo "offload|ye2026_sepsis|cv"; cvl giroux2022 ,offload; cvl imperial_eskd ,offload
25
+ } > "$S/queues/server1_cv_budget_20261002.txt"
26
+ {
27
+ echo "# same units as server1_cv_budget_20261002.txt in the order first requested (B n-major across both cohorts)"
28
+ cvl ji2025_chili ,offload; cvl giroux2022 ,offload; cvl ye2026_sepsis; cvl immicro
29
+ for n in 5 10 20 40; do for ds in immicro ye2026_sepsis; do for k in 0 1 2 3 4; do
30
+ echo "budget|$ds|$k|reuse_cv,clean_prepared,offload|$n"; done; done; done
31
+ echo "offload|immicro|cv"; echo "offload|ye2026_sepsis|cv"
32
+ cvl imperial_eskd ,offload
33
+ } > "$S/queues/server1_cv_budget_20261002_userorder.txt"
34
+ {
35
+ echo "# OPTIONAL plain equal-budget B: each split selects its own hvset and pretrains its own representatives (no reuse)"
36
+ for ds in immicro ye2026_sepsis; do for n in 5 10 20 40; do for k in 0 1 2 3 4; do
37
+ echo "budget|$ds|$k|lean_hvset,clean_prepared,offload|$n"; done; done; done
38
+ } > "$S/queues/server1_budget_plain_20261002.txt"
39
+ wc -l "$S"/queues/server1_cv_budget_20261002*.txt "$S"/queues/server1_budget_plain_20261002.txt
40
+ exit 0
41
+ fi
42
+ {
43
+ echo "# scSemiProfiler paired few-pair baseline (5 representatives' donors), server_1; order fixed by the coordinator"
44
+ for ds in ji2025_chili giroux2022 ye2026_sepsis immicro; do
45
+ opt="|clean_sample_sc" # server_1 disk: dense cell graphs 2-24 GB per draw, re-derivable (bit-identical), sha kept
46
+ for j in 0 1 2 3 4; do echo "fewshot|$ds|$j$opt"; done
47
+ done
48
+ } > "$S/queues/server1_fewshot.txt"
49
+ {
50
+ echo "# scSemiProfiler paired few-pair baseline, server_2 (Imperial data + outputs live on server_2)"
51
+ for j in 0 1 2 3 4; do echo "fewshot|imperial_eskd|$j"; done
52
+ } > "$S/queues/server2_fewshot.txt"
53
+ {
54
+ echo "# OPTIONAL scSemiProfiler 5-fold CV variant (all training donors of fold k are representatives). Expensive."
55
+ for ds in ji2025_chili giroux2022 ye2026_sepsis immicro; do
56
+ opt="|clean_sample_sc"
57
+ for k in 0 1 2 3 4; do echo "cv|$ds|$k$opt"; done
58
+ done
59
+ } > "$S/queues/server1_cv.txt"
60
+ wc -l "$S"/queues/*.txt