junidude14 commited on
Commit
3dc9974
·
verified ·
1 Parent(s): 5c47f7b

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/make_queues.sh ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ {
11
+ echo "# scSemiProfiler paired few-pair baseline (5 representatives' donors), server_1; order fixed by the coordinator"
12
+ for ds in ji2025_chili giroux2022 ye2026_sepsis immicro; do
13
+ opt="|clean_sample_sc" # server_1 disk: dense cell graphs 2-24 GB per draw, re-derivable (bit-identical), sha kept
14
+ for j in 0 1 2 3 4; do echo "fewshot|$ds|$j$opt"; done
15
+ done
16
+ } > "$S/queues/server1_fewshot.txt"
17
+ {
18
+ echo "# scSemiProfiler paired few-pair baseline, server_2 (Imperial data + outputs live on server_2)"
19
+ for j in 0 1 2 3 4; do echo "fewshot|imperial_eskd|$j"; done
20
+ } > "$S/queues/server2_fewshot.txt"
21
+ {
22
+ echo "# OPTIONAL scSemiProfiler 5-fold CV variant (all training donors of fold k are representatives). Expensive."
23
+ for ds in ji2025_chili giroux2022 ye2026_sepsis immicro; do
24
+ opt="|clean_sample_sc"
25
+ for k in 0 1 2 3 4; do echo "cv|$ds|$k$opt"; done
26
+ done
27
+ } > "$S/queues/server1_cv.txt"
28
+ wc -l "$S"/queues/*.txt
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
12
+ Modeled genes = final 6k panel genes measured in the bulk of every representative and target row AND in the
13
+ single cells of every representative row (features.npz bulk_valid / sc_valid). No target single-cell mask,
14
+ depth or cell count enters.
15
+
16
+ Writes <work>/inputs/:
17
+ bulk.h5ad raw bulk counts (float64) of reps + targets on the modeled genes, obs['sample_ids'],
18
+ rows in features.npz order; upstream initsetup(normed=False) library-normalises + log1p's it
19
+ rep_sc.h5ad raw UMI counts (float32 CSR) of every representative cell on the modeled genes,
20
+ obs['sample_ids'] = the representative row's sample id; upstream scprocess(normed=False)
21
+ inputs_manifest.json rows, genes, depth rule, source hashes
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import argparse
26
+ import hashlib
27
+ import json
28
+ import os
29
+ import sys
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
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
41
+ HERE = TASK / "scsemi"
42
+ sys.path.insert(0, str(TASK / "tools"))
43
+ import prepare_dataset as PD # noqa: E402 (the benchmark's own loader: bulk_raw with unmeasured NaN -> 0, masks, use)
44
+
45
+ SEED = 20260927
46
+
47
+
48
+ def sha(path: Path) -> str:
49
+ h = hashlib.sha256()
50
+ with open(path, "rb") as f:
51
+ for block in iter(lambda: f.read(1 << 24), b""):
52
+ h.update(block)
53
+ return h.hexdigest()
54
+
55
+
56
+ def split_rows(ds: str, mode: str, j: int, sample_ids: np.ndarray, folds: pd.DataFrame) -> dict:
57
+ data = TASK / "data" / ds
58
+ usable = folds["fold"].to_numpy() >= 0
59
+ donors = folds["donor_id"].astype(str).to_numpy()
60
+ if mode == "fewshot":
61
+ dd = data / "fewshot_n5" / f"draw{j}"
62
+ train_donors = [x.strip() for x in (dd / "train_donors.txt").read_text().splitlines() if x.strip()]
63
+ test = [x.strip() for x in (dd / "test_samples.txt").read_text().splitlines() if x.strip()]
64
+ cond = dd / "test_raw.npz"
65
+ sources = {"train_donors.txt": dd / "train_donors.txt", "test_samples.txt": dd / "test_samples.txt"}
66
+ rep = np.flatnonzero(np.isin(donors, train_donors) & usable)
67
+ elif mode == "cv":
68
+ fold = folds["fold"].to_numpy()
69
+ test = sample_ids[fold == j].tolist()
70
+ rep = np.flatnonzero(usable & (fold != j))
71
+ train_donors = sorted(set(donors[rep]))
72
+ cond = data / f"fold{j}" / "test_raw.npz"
73
+ sources = {}
74
+ else:
75
+ raise SystemExit(f"unknown mode {mode}")
76
+ pos = {s: i for i, s in enumerate(sample_ids)}
77
+ miss = [s for s in test if s not in pos]
78
+ if miss:
79
+ raise SystemExit(f"test samples not in features.npz: {miss[:5]}")
80
+ tgt = np.asarray([pos[s] for s in test], dtype=np.int64)
81
+ if not usable[tgt].all():
82
+ raise SystemExit("a test row is not usable (fold -1)")
83
+ if set(donors[rep]) & set(donors[tgt]):
84
+ raise SystemExit("a donor is both representative and target")
85
+ if len(set(test)) != len(test):
86
+ raise SystemExit("duplicate test samples")
87
+ return {"rep": rep, "tgt": tgt, "train_donors": train_donors, "test": test, "condition": cond, "sources": sources}
88
+
89
+
90
+ def main(argv=None) -> int:
91
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
92
+ ap.add_argument("--dataset", required=True)
93
+ ap.add_argument("--mode", choices=["fewshot", "cv"], default="fewshot")
94
+ ap.add_argument("--draw", type=int, help="fewshot draw index")
95
+ ap.add_argument("--fold", type=int, help="cv fold index")
96
+ ap.add_argument("--work", type=Path, required=True)
97
+ ap.add_argument("--smoke-reps", type=int, default=0, help="SMOKE ONLY: keep the first N representative rows")
98
+ ap.add_argument("--smoke-cells", type=int, default=0, help="SMOKE ONLY: at most N cells per representative")
99
+ ap.add_argument("--smoke-targets", default="", help="SMOKE ONLY: comma list of target sample ids")
100
+ ap.add_argument("--smoke-rep-ids", default="", help="SMOKE ONLY: comma list of representative sample ids to keep")
101
+ a = ap.parse_args(argv)
102
+ j = a.draw if a.mode == "fewshot" else a.fold
103
+ if j is None:
104
+ raise SystemExit("--draw (fewshot) or --fold (cv) required")
105
+ smoke = bool(a.smoke_reps or a.smoke_cells or a.smoke_targets or a.smoke_rep_ids)
106
+ work = a.work.resolve()
107
+ if smoke and "/scsemi/smoke/" not in str(work) + "/":
108
+ raise SystemExit("smoke subsetting only under scsemi/smoke/")
109
+ out = work / "inputs"
110
+ if (out / "inputs_manifest.json").exists():
111
+ raise SystemExit(f"{out}/inputs_manifest.json exists; inputs are immutable (preserve and inspect)")
112
+ out.mkdir(parents=True, exist_ok=True)
113
+ data = TASK / "data" / a.dataset
114
+ d = PD.load(data)
115
+ folds = pd.read_csv(data / "folds.csv")
116
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
117
+ raise SystemExit("folds.csv rows differ from features.npz")
118
+ s = split_rows(a.dataset, a.mode, j, d["sample_ids"], folds)
119
+ rep, tgt = s["rep"], s["tgt"]
120
+ if a.smoke_rep_ids:
121
+ keep_r = set(a.smoke_rep_ids.split(","))
122
+ rep = np.asarray([r for r in rep if d["sample_ids"][r] in keep_r], dtype=np.int64)
123
+ if a.smoke_reps:
124
+ rep = rep[: a.smoke_reps]
125
+ if a.smoke_targets:
126
+ keep = set(a.smoke_targets.split(","))
127
+ tgt = np.asarray([t for t in tgt if d["sample_ids"][t] in keep], dtype=np.int64)
128
+ s["test"] = [x for x in s["test"] if x in keep]
129
+ if a.mode == "fewshot" and not smoke:
130
+ usable = np.flatnonzero(folds["fold"].to_numpy() >= 0)
131
+ if set(rep.tolist()) | set(tgt.tolist()) != set(usable.tolist()):
132
+ raise SystemExit("representatives + targets do not cover the usable rows")
133
+ # modeled genes
134
+ z = np.load(data / "cells_panel6k.npz", allow_pickle=False)
135
+ panel = z["panel_gene_ids"].astype(str)
136
+ gpos = {g: i for i, g in enumerate(d["gene_ids"])}
137
+ pcanon = np.asarray([gpos[g] for g in panel], dtype=np.int64)
138
+ rows = np.sort(np.concatenate([rep, tgt]))
139
+ bulk_ok = d["bulk_valid"][rows][:, pcanon].all(0)
140
+ sc_ok = d["sc_valid"][rep][:, pcanon].all(0)
141
+ model_pidx = np.flatnonzero(bulk_ok & sc_ok)
142
+ genes = panel[model_pidx]
143
+ if genes.size < 1000:
144
+ raise SystemExit(f"only {genes.size} modeled genes")
145
+ # scorer's scoring genes (all rows of the dataset) for the record
146
+ score_mask = d["bulk_valid"][:, pcanon].all(0) & d["sc_valid"][:, pcanon].all(0)
147
+ # bulk
148
+ import anndata as ad
149
+ B = d["bulk"][rows][:, pcanon[model_pidx]].astype(np.float64)
150
+ if not np.isfinite(B).all() or (B < 0).any():
151
+ raise SystemExit("non-finite or negative bulk on the modeled genes")
152
+ if (B.sum(1) <= 0).any():
153
+ raise SystemExit("a bulk row has no counts on the modeled genes")
154
+ sym = pd.read_csv(TASK.parents[1] / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv")
155
+ sym = sym.set_index("gene_id").gene_symbol.astype(str)
156
+ var = pd.DataFrame({"gene_symbol": sym.reindex(genes).to_numpy()}, index=pd.Index(genes, name="gene_id"))
157
+ obs_b = pd.DataFrame({"sample_ids": d["sample_ids"][rows], "donor_id": d["donor_ids"][rows],
158
+ "group": d["groups"][rows], "role": np.where(np.isin(rows, rep), "representative", "target")},
159
+ index=pd.Index(d["sample_ids"][rows], name="obs"))
160
+ ad.AnnData(X=B, obs=obs_b, var=var).write_h5ad(out / "bulk.h5ad")
161
+ # representative cells
162
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
163
+ rs = np.asarray(z["row_sample"], dtype=np.int64)
164
+ blocks, obs_rows, per_rep = [], [], []
165
+ rng = np.random.default_rng(SEED)
166
+ for r in rep:
167
+ cells = np.flatnonzero(rs == r)
168
+ if a.smoke_cells and cells.size > a.smoke_cells:
169
+ cells = np.sort(rng.choice(cells, a.smoke_cells, replace=False))
170
+ Xr = X[cells][:, model_pidx].tocsr().astype(np.float32)
171
+ lib = np.asarray(Xr.sum(1)).ravel()
172
+ if (lib <= 0).any():
173
+ raise SystemExit(f"{d['sample_ids'][r]}: {int((lib <= 0).sum())} cells without counts on the modeled genes")
174
+ blocks.append(Xr)
175
+ obs_rows.append(pd.DataFrame({"sample_ids": d["sample_ids"][r], "donor_id": d["donor_ids"][r],
176
+ "source_cell_row": cells}))
177
+ per_rep.append({"sample_id": str(d["sample_ids"][r]), "donor_id": str(d["donor_ids"][r]),
178
+ "group": str(d["groups"][r]), "n_cells": int(cells.size),
179
+ "median_umi_modeled_genes": float(np.median(lib))})
180
+ Xs = sp.vstack(blocks, format="csr")
181
+ obs_s = pd.concat(obs_rows, ignore_index=True)
182
+ obs_s.index = pd.Index([f"{a_}|{b_}" for a_, b_ in zip(obs_s.sample_ids, obs_s.source_cell_row)], name="cell")
183
+ ad.AnnData(X=Xs, obs=obs_s, var=var.copy()).write_h5ad(out / "rep_sc.h5ad")
184
+ lib_all = np.asarray(Xs.sum(1)).ravel()
185
+ depth = float(np.median(lib_all))
186
+ cond = s["condition"]
187
+ man = {
188
+ "schema": "scsemi_paired.inputs.v1", "written_utc": datetime.now(timezone.utc).isoformat(),
189
+ "dataset": a.dataset, "mode": a.mode, "split": j, "smoke": smoke,
190
+ "smoke_settings": {"reps": a.smoke_reps, "cells": a.smoke_cells, "targets": a.smoke_targets,
191
+ "rep_ids": a.smoke_rep_ids} if smoke else None,
192
+ "train_donors": s["train_donors"],
193
+ "representatives": per_rep, "targets": [str(x) for x in d["sample_ids"][tgt]],
194
+ "target_order_test_samples": s["test"],
195
+ "bulk_row_order": [str(x) for x in d["sample_ids"][rows]],
196
+ "n_representatives": int(rep.size), "n_targets": int(tgt.size), "n_rep_cells": int(Xs.shape[0]),
197
+ "modeled_genes": {"n": int(genes.size), "gene_ids": genes.tolist(), "panel_index": model_pidx.tolist(),
198
+ "rule": "6k panel genes with bulk_valid in every rep+target row and sc_valid in every rep row",
199
+ "equals_scorer_scoring_genes": bool(np.array_equal(model_pidx, np.flatnonzero(score_mask))),
200
+ "n_scorer_scoring_genes": int(score_mask.sum())},
201
+ "depth": {"value": depth, "rule": "median over all representative cells (all rows of the training donors) of the "
202
+ "per-cell UMI sum on the modeled genes; every generated cell is scaled to this expected library",
203
+ "n_cells": int(lib_all.size)},
204
+ "condition_npz": str(cond), "condition_sha256": sha(cond),
205
+ "sources": {"features.npz": sha(data / "features.npz"), "folds.csv": sha(data / "folds.csv"),
206
+ "cells_panel6k.npz": sha(data / "cells_panel6k.npz"),
207
+ **{k: sha(v) for k, v in s["sources"].items()}},
208
+ "files": {"bulk.h5ad": sha(out / "bulk.h5ad"), "rep_sc.h5ad": sha(out / "rep_sc.h5ad")},
209
+ "builder_sha256": sha(Path(__file__)),
210
+ }
211
+ with np.load(cond, allow_pickle=False) as cz:
212
+ cond_ids = cz["sample_ids"].astype(str).tolist()
213
+ if not smoke and sorted(cond_ids) != sorted(man["targets"]):
214
+ raise SystemExit("condition NPZ sample_ids differ from the targets")
215
+ man["condition_sample_order"] = cond_ids
216
+ tmp = out / "inputs_manifest.json.tmp"
217
+ tmp.write_text(json.dumps(man, indent=1) + "\n")
218
+ tmp.replace(out / "inputs_manifest.json")
219
+ print(json.dumps({"dataset": a.dataset, "mode": a.mode, "split": j, "reps": int(rep.size), "targets": int(tgt.size),
220
+ "rep_cells": int(Xs.shape[0]), "modeled_genes": int(genes.size),
221
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"], "depth": depth}))
222
+ return 0
223
+
224
+
225
+ if __name__ == "__main__":
226
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_env_server2.sh ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Build the server_2 scSemiProfiler venv equivalent to server_1's frozen runtime_env (CPU-side install only).
3
+ # base: /home/sj_server_1/miniforge3/envs/scanvi (same path and versions on both hosts)
4
+ # venv: scsemi/runtime_env (--system-site-packages), + the frozen env's pip set with the same pins; certifi and
5
+ # charset-normalizer (+ the optional regex, defusedxml) are pinned INTO the venv (on server_1 they come from ~/.local), so server_2 runs with
6
+ # PYTHONNOUSERSITE=1 and nothing from the user site. Records scsemi_environment.json. Run as a CPU unit.
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
+ BASE=/home/sj_server_1/miniforge3/envs/scanvi
10
+ ENV=$S/runtime_env
11
+ export PYTHONNOUSERSITE=1 CUDA_VISIBLE_DEVICES=
12
+ [[ -x $ENV/bin/python ]] || "$BASE/bin/python" -m venv --system-site-packages "$ENV"
13
+ "$ENV/bin/python" -m pip install --no-deps --no-input \
14
+ faiss-cpu==1.12.0 gseapy==1.3.0 igraph==0.11.9 texttable==1.7.0 \
15
+ requests==2.32.5 urllib3==2.8.0 certifi==2026.1.4 charset-normalizer==3.4.4 regex==2026.1.15 defusedxml==0.7.1
16
+ "$ENV/bin/python" - <<'PY'
17
+ import importlib.metadata as m, json, os, sys
18
+ from pathlib import Path
19
+ names = ["torch", "anndata", "scanpy", "scvi-tools", "lightning", "pytorch-lightning", "numpy", "scipy", "scikit-learn",
20
+ "pandas", "h5py", "faiss-cpu", "gseapy", "igraph", "texttable", "requests", "urllib3", "certifi",
21
+ "charset-normalizer", "idna", "regex", "defusedxml"]
22
+ sys.path.insert(0, os.environ.get("VENDOR", "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi/vendor/scSemiProfiler"))
23
+ import scSemiProfiler, scvi, torch # noqa: F401 (CUDA hidden: import only)
24
+ user = [n for n, mod in list(sys.modules.items()) if getattr(mod, "__file__", None) and "/.local/" in str(mod.__file__)]
25
+ rec = {"python": sys.executable, "versions": {n: m.version(n) for n in names}, "user_site_modules_loaded": user,
26
+ "cuda_visible_devices": os.environ.get("CUDA_VISIBLE_DEVICES")}
27
+ Path(sys.prefix, "scsemi_environment.json").write_text(json.dumps(rec, indent=2) + "\n")
28
+ print(json.dumps(rec, indent=2))
29
+ if user:
30
+ raise SystemExit(f"modules imported from the user site: {user}")
31
+ PY
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_queue_scsemi.sh ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # scSemiProfiler paired-baseline queue for this host, one split at a time (style of ../tools/run_queue.sh).
3
+ # queue line: MODE|DATASET|SPLIT[|OPTIONS] MODE fewshot (SPLIT = draw) or cv (SPLIT = fold)
4
+ # OPTIONS (comma list): clean_sample_sc = after the split's NPZ is exported AND validated, delete
5
+ # scsemi_project/sample_sc/*.h5ad (dense upstream cell graphs, ~1.5 GB per Giroux representative;
6
+ # their sha256 stay in prepared.json)
7
+ # Per split:
8
+ # 1. done check: generated NPZ + receipt + passing <npz>.validation.json -> skipped
9
+ # 2. CPU units (tools/cpu_unit.sh, ml.slice, <= 6 threads, MemoryMax <= 16G): input build, upstream prepare
10
+ # 3. GPU steps, each after the thermal gate and gpu_usable.sh, each through $HOME/.local/bin/ml-run (ml.slice,
11
+ # shared GPU lock): pretrain CHUNK_REPS representatives per call, then CHUNK_TARGETS targets per call, until
12
+ # status.json says complete. Per-target runtime is in work/.../shards/<target>.json and events.jsonl.
13
+ # 4. CPU units: export (adapter) + independent validation; optional scoring (SCORE=1, benchmark scorer)
14
+ # A failure is logged, the split's partial outputs are preserved (no retry, no cleanup) and the queue moves on.
15
+ # env: QUEUE (required), MAX_WAIT_H (24), CHUNK_REPS (2), CHUNK_TARGETS (12), SCORE (0), SCSEMI_PY (host default)
16
+ # SMOKE_CPU=1: queue-logic test on "smoke|DATASET|DRAW|OPTIONS|T1,T2,.." lines only (2 reps x 300 cells, 1-2 epochs,
17
+ # CPU units instead of ml-run, outputs under scsemi/smoke/queue/); never touches the GPU
18
+ # PREP_ONLY=1: CPU steps only (input build + upstream prepare), no GPU, no export. Safe to run while the GPU
19
+ # queue runs: every split is processed under an exclusive lock (work/.../.split.lock, waits up to MAX_WAIT_H).
20
+ # PREP_MEM (16): MemoryMax GiB of the upstream-prepare CPU unit (cpu_unit.sh caps it; see README memory note)
21
+ set -uo pipefail
22
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
23
+ export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
24
+ M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
25
+ T=$M8/plans/paired_finetune_intradataset_20260927
26
+ S=$T/scsemi
27
+ case "$(hostname -s)" in
28
+ spark-fa6b) PYD=$M8/plans/immicro_scsemi_comparison_20260927/runtime_env/bin/python; USERSITE=1 ;; # server_1: frozen env
29
+ spark-0110) PYD=$S/runtime_env/bin/python; USERSITE=0 ;; # server_2: equivalent venv
30
+ *) echo "unknown host $(hostname -s)" >&2; exit 2 ;;
31
+ esac
32
+ PY=${SCSEMI_PY:-$PYD}
33
+ SPY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python # benchmark scorer env (both hosts)
34
+ QUEUE="${QUEUE:?QUEUE}"; MAX_WAIT_H="${MAX_WAIT_H:-24}"; CHUNK_REPS="${CHUNK_REPS:-2}"; CHUNK_TARGETS="${CHUNK_TARGETS:-12}"
35
+ SCORE="${SCORE:-0}"; SMOKE_CPU="${SMOKE_CPU:-0}"; PREP_ONLY="${PREP_ONLY:-0}"; PREP_MEM="${PREP_MEM:-16}"
36
+ mkdir -p "$S/logs"
37
+ LOG=$S/logs/queue_$(basename "$QUEUE" .txt)_$(hostname -s)_$(date +%Y%m%dT%H%M%S).log
38
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
39
+ start=$(date +%s)
40
+ gate() {
41
+ local verdict usable
42
+ if [[ $SMOKE_CPU == 1 ]]; then echo "smoke: CPU only, no GPU gate"; return; fi
43
+ until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh") \
44
+ && usable=$(bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh" 2>/dev/null); do
45
+ (( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
46
+ sleep 120
47
+ done
48
+ echo "$verdict; GPU $usable"
49
+ }
50
+ cpu() { # cpu NAME THREADS MEMMAX CMD... (waits for the memory floor instead of failing on it)
51
+ local mem=$3
52
+ until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 32 + mem )); do
53
+ (( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: memory floor not met within ${MAX_WAIT_H} h"; exit 1; }
54
+ sleep 120
55
+ done
56
+ ALLOW_USER_SITE=${US:-$USERSITE} bash "$S/tools/cpu_unit.sh" "$@" >> "$LOG" 2>&1 < /dev/null
57
+ }
58
+ st() { python3 -c "import json,sys;print(json.load(open(sys.argv[1]))[sys.argv[2]])" "$1/status.json" "$2" 2>/dev/null; }
59
+ gpu() { # gpu WORK PHASE EXTRA...
60
+ local W=$1 phase=$2; shift 2
61
+ if [[ $SMOKE_CPU == 1 ]]; then # queue-logic test: same wrapper, CPU, reduced epochs, never ml-run
62
+ cpu "smk-$phase" 4 8 "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase "$phase" --device cpu --smoke --threads 4 "$@"
63
+ return
64
+ fi
65
+ local ns=
66
+ [[ $USERSITE == 1 ]] || ns=PYTHONNOUSERSITE=1
67
+ "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
68
+ OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 $ns \
69
+ "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase "$phase" --device cuda:0 --threads 4 "$@" \
70
+ >> "$W/gpu.log" 2>&1 < /dev/null
71
+ }
72
+ n_fail=0
73
+ fail() { n_fail=$((n_fail+1)); log "WARN: $*"; }
74
+ log "queue $QUEUE on $(hostname -s); python $PY; chunks reps=$CHUNK_REPS targets=$CHUNK_TARGETS; score=$SCORE; smoke_cpu=$SMOKE_CPU"
75
+ while IFS= read -r line; do
76
+ [[ -z "${line// }" || "$line" == \#* ]] && continue
77
+ IFS='|' read -r mode ds j opts extra <<< "$line"
78
+ SMK=()
79
+ case $mode in
80
+ fewshot) W=$S/work/$ds/fewshot_n5/draw$j; OUT=$T/generated/$ds/fewshot_n5/draw$j/scsemi5__raw.npz; ARM=scsemi5
81
+ SC=$T/scores/$ds/fewshot_n5/draw${j}_scsemi5; DON=$T/data/$ds/fewshot_n5/draw$j/test_samples.txt
82
+ imode=fewshot; sflag=(--draw "$j") ;;
83
+ cv) W=$S/work/$ds/cv/fold$j; OUT=$T/generated/$ds/fold$j/scsemi__raw.npz; ARM=scsemi
84
+ SC=$T/scores/$ds/fold${j}_scsemi; DON=; imode=cv; sflag=(--fold "$j") ;;
85
+ smoke) [[ $SMOKE_CPU == 1 ]] || { fail "smoke line needs SMOKE_CPU=1: $line"; continue; }
86
+ W=$S/smoke/queue/${ds}_draw$j; OUT=$W/generated/scsemi5__raw.npz; ARM=scsemi5; SC=$W/score
87
+ DON=$W/targets.txt; imode=fewshot; SMK=(--smoke)
88
+ sflag=(--draw "$j" --smoke-reps 2 --smoke-cells 300 --smoke-targets "$extra")
89
+ mkdir -p "$W"; tr ',' '\n' <<< "$extra" > "$DON" ;;
90
+ *) fail "unknown line: $line"; continue ;;
91
+ esac
92
+ [[ $SMOKE_CPU == 1 && $mode != smoke ]] && { fail "SMOKE_CPU=1 runs smoke lines only: $line"; continue; }
93
+ tag="$ds/$mode$j"
94
+ mkdir -p "$W"
95
+ exec 9>"$W/.split.lock" # re-opening fd 9 releases the previous split's lock
96
+ flock -w $((MAX_WAIT_H * 3600)) 9 || { fail "$tag: split lock held by another queue for ${MAX_WAIT_H} h"; continue; }
97
+ VAL=${OUT%.npz}.validation.json
98
+ if [[ -s $VAL ]] && python3 -c "import json,sys;sys.exit(0 if json.load(open(sys.argv[1]))['passed'] else 1)" "$VAL"; then
99
+ log "$tag: exported + validated already; skipped"
100
+ else
101
+ mkdir -p "$W"
102
+ if [[ ! -s $W/inputs/inputs_manifest.json ]]; then
103
+ log "$tag: building inputs (CPU unit)"
104
+ cpu "in-${ds:0:3}-$mode$j" 4 12 "$PY" -u "$S/tools/prepare_draw_inputs.py" --dataset "$ds" --mode "$imode" "${sflag[@]}" --work "$W" \
105
+ || { fail "$tag: input build failed"; continue; }
106
+ fi
107
+ if [[ ! -s $W/prepared.json ]]; then
108
+ log "$tag: upstream prepare (initsetup + assignment + scprocess, CPU unit)"
109
+ cpu "prep-${ds:0:3}-$mode$j" 6 "$PREP_MEM" "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase prepare --device cpu --threads 6 "${SMK[@]}" \
110
+ || { fail "$tag: prepare failed (see $W/events.jsonl)"; continue; }
111
+ fi
112
+ if [[ $PREP_ONLY == 1 ]]; then log "$tag: CPU-prepared (PREP_ONLY; GPU steps left to the GPU queue)"; continue; fi
113
+ ok=1
114
+ while [[ "$(st "$W" pretrain_complete)" != True ]]; do
115
+ before=$(st "$W" reps_pretrained)
116
+ g=$(gate) || { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
117
+ log "$tag: pretrain ${before}/$(st "$W" n_reps) reps; next $CHUNK_REPS ($g)"
118
+ gpu "$W" pretrain --max-reps "$CHUNK_REPS" || { fail "$tag: pretrain step failed (see $W/gpu.log, $W/events.jsonl)"; ok=0; break; }
119
+ [[ "$(st "$W" reps_pretrained)" != "$before" ]] || { fail "$tag: pretrain made no progress"; ok=0; break; }
120
+ done
121
+ (( ok )) || continue
122
+ while [[ "$(st "$W" infer_complete)" != True ]]; do
123
+ before=$(st "$W" targets_done)
124
+ g=$(gate) || { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
125
+ log "$tag: infer ${before}/$(st "$W" n_targets) targets; next $CHUNK_TARGETS ($g)"
126
+ gpu "$W" infer --max-targets "$CHUNK_TARGETS" || { fail "$tag: infer step failed (see $W/gpu.log, $W/events.jsonl)"; ok=0; break; }
127
+ [[ "$(st "$W" targets_done)" != "$before" ]] || { fail "$tag: infer made no progress"; ok=0; break; }
128
+ done
129
+ (( ok )) || continue
130
+ if [[ ! -s $OUT ]]; then
131
+ cpu "exp-${ds:0:3}-$mode$j" 2 16 "$PY" -u "$S/tools/export_npz.py" --work "$W" --out "$OUT" || { fail "$tag: export failed"; continue; }
132
+ fi
133
+ cpu "val-${ds:0:3}-$mode$j" 2 16 "$PY" -u "$S/tools/validate_export.py" --work "$W" --npz "$OUT" || { fail "$tag: validation failed ($VAL)"; continue; }
134
+ log "$tag: exported + validated: $(python3 -c "import json,sys;d=json.load(open(sys.argv[1]));print('targets',d['bulks'],'median target s %.1f'%d['median_target_seconds'],'total target s %.0f'%d['total_target_seconds'])" "${OUT%.npz}.log")"
135
+ if [[ ",$opts," == *",clean_sample_sc,"* ]]; then
136
+ rm -f "$W"/scsemi_project/sample_sc/*.h5ad && log "$tag: removed sample_sc/*.h5ad (sha256 kept in prepared.json)"
137
+ fi
138
+ fi
139
+ if [[ $SCORE == 1 && $PREP_ONLY != 1 && $mode != cv && -s $VAL && ! -s $SC/summary.json ]]; then
140
+ read -r -a cargs <<< "$(bash "$T/tools/contrast_args.sh" "$ds")"
141
+ log "$tag: scoring arm $ARM -> $SC"
142
+ mkdir -p "$SC"
143
+ US=0 cpu "sc-${ds:0:3}-$mode$j" 6 16 "$SPY" -u "$T/tools/score_ft.py" --dataset "$ds" --out "$SC" --threads 6 \
144
+ --donors "$DON" "${cargs[@]}" --arm "$ARM=$OUT" || fail "$tag: scoring failed"
145
+ fi
146
+ done < "$QUEUE"
147
+ exec 9>&-
148
+ log "queue finished: failed=$n_fail"
149
+ (( n_fail == 0 ))