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/offload_work.sh +44 -0
- paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py +290 -0
- paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/reuse_gpu_check.sh +50 -0
- paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_queue_scsemi.sh +233 -0
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/offload_work.sh
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Move a finished scSemiProfiler split's bulky, no-longer-read files to spark-0110 at the SAME ABSOLUTE PATH (2026-10-02):
|
| 3 |
+
# scsemi_project/models/* (pretrain checkpoints and per-target models; their .receipt.json files stay here) and
|
| 4 |
+
# inputs/rep_sc.h5ad (its sha256 stays in inputs/inputs_manifest.json).
|
| 5 |
+
# A local file is deleted only after spark-0110's sha256 of the copy equals the local sha256; the files and shas are
|
| 6 |
+
# appended to <work>/offloaded_to_server2.tsv. Refuses a split whose generated NPZ is not exported and validated, and
|
| 7 |
+
# refuses relative paths (a relative path once put files under the remote $HOME; see tools/move_generated.sh).
|
| 8 |
+
# Do not offload a CV run before every budget split that reuses it (--reuse-from) has finished: its 'link' phase reads
|
| 9 |
+
# the CV checkpoints. To resume a split later, rsync the files back first (same paths).
|
| 10 |
+
# usage: offload_work.sh VALIDATION_JSON WORK [VALIDATION_JSON WORK ...] (absolute paths)
|
| 11 |
+
set -uo pipefail
|
| 12 |
+
REMOTE=spark-0110
|
| 13 |
+
n_ok=0; n_fail=0
|
| 14 |
+
while (( $# >= 2 )); do
|
| 15 |
+
val=$1; work=$2; shift 2
|
| 16 |
+
[[ $work == /* && $val == /* ]] || { echo "FAIL relative path: $work $val"; n_fail=$((n_fail+1)); continue; }
|
| 17 |
+
W=$(realpath -e "$work") || { echo "FAIL no such dir $work"; n_fail=$((n_fail+1)); continue; }
|
| 18 |
+
python3 -c "import json,sys;sys.exit(0 if json.load(open(sys.argv[1]))['passed'] else 1)" "$val" 2>/dev/null \
|
| 19 |
+
|| { echo "SKIP $W: $val missing or not passed"; n_fail=$((n_fail+1)); continue; }
|
| 20 |
+
M=$W/scsemi_project/models
|
| 21 |
+
names=$(mktemp); shas=$(mktemp)
|
| 22 |
+
find "$M" -maxdepth 1 -type f ! -name '*.receipt.json' -printf '%f\n' 2>/dev/null | sort > "$names"
|
| 23 |
+
have_in=0; [[ -f $W/inputs/rep_sc.h5ad ]] && have_in=1
|
| 24 |
+
if [[ ! -s $names ]] && (( ! have_in )); then echo "nothing to move in $W"; rm -f "$names" "$shas"; continue; fi
|
| 25 |
+
{ sed "s|^|$M/|" "$names"; (( have_in )) && echo "$W/inputs/rep_sc.h5ad"; } | xargs -r -d '\n' sha256sum > "$shas"
|
| 26 |
+
ok=1
|
| 27 |
+
ssh -n "$REMOTE" "mkdir -p '$M' '$W/inputs'" || ok=0
|
| 28 |
+
if (( ok )) && [[ -s $names ]]; then
|
| 29 |
+
ionice -c3 rsync -a --bwlimit=200000 --files-from="$names" "$M/" "$REMOTE:$M/" || ok=0
|
| 30 |
+
fi
|
| 31 |
+
if (( ok && have_in )); then
|
| 32 |
+
ionice -c3 rsync -a --bwlimit=200000 "$W/inputs/rep_sc.h5ad" "$REMOTE:$W/inputs/" || ok=0
|
| 33 |
+
fi
|
| 34 |
+
if (( ok )) && ssh "$REMOTE" "sha256sum -c --quiet -" < "$shas"; then
|
| 35 |
+
awk '{print $2}' "$shas" | xargs -r -d '\n' rm -f
|
| 36 |
+
awk -v t="$(date -Is)" -v r="$REMOTE" '{print t "\t" r "\t" $2 "\t" $1}' "$shas" >> "$W/offloaded_to_server2.tsv"
|
| 37 |
+
echo "moved $(wc -l < "$shas") files of $W to $REMOTE (same paths, sha-verified)"; n_ok=$((n_ok+1))
|
| 38 |
+
else
|
| 39 |
+
echo "FAIL transfer or remote sha256 mismatch for $W; local files kept"; n_fail=$((n_fail+1))
|
| 40 |
+
fi
|
| 41 |
+
rm -f "$names" "$shas"
|
| 42 |
+
done
|
| 43 |
+
echo "offloaded=$n_ok failed=$n_fail"
|
| 44 |
+
(( n_fail == 0 ))
|
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Build scSemiProfiler inputs for one paired split (CPU only).
|
| 3 |
+
|
| 4 |
+
Representatives = every usable row of the split's training donors (paired sc + real bulk).
|
| 5 |
+
Targets = the split's test rows (real bulk only; their cells are never read here).
|
| 6 |
+
|
| 7 |
+
--mode fewshot --draw j : training donors = data/<ds>/fewshot_n5/draw<j>/train_donors.txt,
|
| 8 |
+
targets = draw<j>/test_samples.txt, condition = draw<j>/test_raw.npz
|
| 9 |
+
--mode cv --fold k : training donors = every usable donor not in fold k (inner-val donors included),
|
| 10 |
+
targets = fold k's rows, condition = data/<ds>/fold<k>/test_raw.npz
|
| 11 |
+
--mode budget --fold k --n N (added 2026-10-02): representatives = exactly the rows LoRA lora_n<N> of fold k saw,
|
| 12 |
+
runs/<ds>/fold<k>/lora_n<N>/RUN.json train_rows + inner_val_rows (checked against
|
| 13 |
+
data/<ds>/CAL_BUDGET.json fit_sample_ids when present); targets = fold k's rows (checked
|
| 14 |
+
against the run's test_rows_never_loaded_for_training); condition = fold<k>/test_raw.npz.
|
| 15 |
+
The manifest also records target_donors (used by run_scsemi_paired.py --reuse-from).
|
| 16 |
+
--check-only (added 2026-10-02): build and check everything (split, genes, cells, depth, condition), write
|
| 17 |
+
nothing under --work; print the summary (and the representative / target lists to
|
| 18 |
+
--check-out if given). Without it the builder behaves exactly as before.
|
| 19 |
+
|
| 20 |
+
Modeled genes = final 6k panel genes measured in the bulk of every representative and target row AND in the
|
| 21 |
+
single cells of every representative row (features.npz bulk_valid / sc_valid). No target single-cell mask,
|
| 22 |
+
depth or cell count enters.
|
| 23 |
+
|
| 24 |
+
Writes <work>/inputs/:
|
| 25 |
+
bulk.h5ad raw bulk counts (float64) of reps + targets on the modeled genes, obs['sample_ids'],
|
| 26 |
+
rows in features.npz order; upstream initsetup(normed=False) library-normalises + log1p's it
|
| 27 |
+
rep_sc.h5ad raw UMI counts (float32 CSR) of every representative cell on the modeled genes,
|
| 28 |
+
obs['sample_ids'] = the representative row's sample id; upstream scprocess(normed=False)
|
| 29 |
+
inputs_manifest.json rows, genes, depth rule, source hashes
|
| 30 |
+
"""
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import argparse
|
| 34 |
+
import hashlib
|
| 35 |
+
import json
|
| 36 |
+
import os
|
| 37 |
+
import sys
|
| 38 |
+
from datetime import datetime, timezone
|
| 39 |
+
from pathlib import Path
|
| 40 |
+
|
| 41 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 42 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 43 |
+
|
| 44 |
+
import numpy as np
|
| 45 |
+
import pandas as pd
|
| 46 |
+
import scipy.sparse as sp
|
| 47 |
+
|
| 48 |
+
TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 49 |
+
HERE = TASK / "scsemi"
|
| 50 |
+
sys.path.insert(0, str(TASK / "tools"))
|
| 51 |
+
import prepare_dataset as PD # noqa: E402 (the benchmark's own loader: bulk_raw with unmeasured NaN -> 0, masks, use)
|
| 52 |
+
|
| 53 |
+
SEED = 20260927
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def sha(path: Path) -> str:
|
| 57 |
+
h = hashlib.sha256()
|
| 58 |
+
with open(path, "rb") as f:
|
| 59 |
+
for block in iter(lambda: f.read(1 << 24), b""):
|
| 60 |
+
h.update(block)
|
| 61 |
+
return h.hexdigest()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def split_rows(ds: str, mode: str, j: int, sample_ids: np.ndarray, folds: pd.DataFrame, n: int | None = None) -> dict:
|
| 65 |
+
data = TASK / "data" / ds
|
| 66 |
+
usable = folds["fold"].to_numpy() >= 0
|
| 67 |
+
donors = folds["donor_id"].astype(str).to_numpy()
|
| 68 |
+
extra = {}
|
| 69 |
+
if mode == "fewshot":
|
| 70 |
+
dd = data / "fewshot_n5" / f"draw{j}"
|
| 71 |
+
train_donors = [x.strip() for x in (dd / "train_donors.txt").read_text().splitlines() if x.strip()]
|
| 72 |
+
test = [x.strip() for x in (dd / "test_samples.txt").read_text().splitlines() if x.strip()]
|
| 73 |
+
cond = dd / "test_raw.npz"
|
| 74 |
+
sources = {"train_donors.txt": dd / "train_donors.txt", "test_samples.txt": dd / "test_samples.txt"}
|
| 75 |
+
rep = np.flatnonzero(np.isin(donors, train_donors) & usable)
|
| 76 |
+
elif mode == "cv":
|
| 77 |
+
fold = folds["fold"].to_numpy()
|
| 78 |
+
test = sample_ids[fold == j].tolist()
|
| 79 |
+
rep = np.flatnonzero(usable & (fold != j))
|
| 80 |
+
train_donors = sorted(set(donors[rep]))
|
| 81 |
+
cond = data / f"fold{j}" / "test_raw.npz"
|
| 82 |
+
sources = {}
|
| 83 |
+
elif mode == "budget":
|
| 84 |
+
fold = folds["fold"].to_numpy()
|
| 85 |
+
rj = TASK / "runs" / ds / f"fold{j}" / f"lora_n{n}" / "RUN.json"
|
| 86 |
+
run = json.loads(rj.read_text())
|
| 87 |
+
if run["fold"] != j or (run.get("train_subset") or {}).get("train_n") != n:
|
| 88 |
+
raise SystemExit(f"{rj}: not the fold {j} n={n} learning-curve run")
|
| 89 |
+
fit = list(run["train_rows"]) + list(run["inner_val_rows"])
|
| 90 |
+
test = sample_ids[fold == j].tolist()
|
| 91 |
+
if sorted(run["test_rows_never_loaded_for_training"]) != sorted(test):
|
| 92 |
+
raise SystemExit(f"{rj}: its test rows differ from fold {j}'s rows")
|
| 93 |
+
pos = {s: i for i, s in enumerate(sample_ids)}
|
| 94 |
+
if len(set(fit)) != len(fit) or any(s not in pos for s in fit):
|
| 95 |
+
raise SystemExit(f"{rj}: duplicate or unknown fit rows")
|
| 96 |
+
rep = np.asarray(sorted(pos[s] for s in fit), dtype=np.int64)
|
| 97 |
+
if not (usable[rep] & (fold[rep] != j)).all():
|
| 98 |
+
raise SystemExit(f"{rj}: a fit row is unusable or in fold {j}")
|
| 99 |
+
cb = data / "CAL_BUDGET.json"
|
| 100 |
+
if cb.exists():
|
| 101 |
+
e = json.loads(cb.read_text())["folds"][str(j)]["n"][str(n)]
|
| 102 |
+
if sorted(e["fit_sample_ids"]) != sorted(fit) or e["lora_checkpoint_sha256"] != run["checkpoint_sha256"]:
|
| 103 |
+
raise SystemExit(f"{cb}: fold {j} n={n} fit rows / LoRA checkpoint differ from {rj}")
|
| 104 |
+
train_donors = sorted(set(donors[rep]))
|
| 105 |
+
cond = data / f"fold{j}" / "test_raw.npz"
|
| 106 |
+
sources = {"lora_RUN.json": rj, **({"CAL_BUDGET.json": cb} if cb.exists() else {})}
|
| 107 |
+
extra = {"budget": {"n": int(n), "fold": int(j), "lora_run": str(rj), "lora_checkpoint_sha256": run["checkpoint_sha256"],
|
| 108 |
+
"n_train_rows": len(run["train_rows"]), "n_inner_val_rows": len(run["inner_val_rows"]),
|
| 109 |
+
"train_rows": list(run["train_rows"]), "inner_val_rows": list(run["inner_val_rows"])}}
|
| 110 |
+
else:
|
| 111 |
+
raise SystemExit(f"unknown mode {mode}")
|
| 112 |
+
pos = {s: i for i, s in enumerate(sample_ids)}
|
| 113 |
+
miss = [s for s in test if s not in pos]
|
| 114 |
+
if miss:
|
| 115 |
+
raise SystemExit(f"test samples not in features.npz: {miss[:5]}")
|
| 116 |
+
tgt = np.asarray([pos[s] for s in test], dtype=np.int64)
|
| 117 |
+
if not usable[tgt].all():
|
| 118 |
+
raise SystemExit("a test row is not usable (fold -1)")
|
| 119 |
+
if set(donors[rep]) & set(donors[tgt]):
|
| 120 |
+
raise SystemExit("a donor is both representative and target")
|
| 121 |
+
if len(set(test)) != len(test):
|
| 122 |
+
raise SystemExit("duplicate test samples")
|
| 123 |
+
return {"rep": rep, "tgt": tgt, "train_donors": train_donors, "test": test, "condition": cond, "sources": sources,
|
| 124 |
+
**extra}
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def main(argv=None) -> int:
|
| 128 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 129 |
+
ap.add_argument("--dataset", required=True)
|
| 130 |
+
ap.add_argument("--mode", choices=["fewshot", "cv", "budget"], default="fewshot")
|
| 131 |
+
ap.add_argument("--draw", type=int, help="fewshot draw index")
|
| 132 |
+
ap.add_argument("--fold", type=int, help="cv / budget fold index")
|
| 133 |
+
ap.add_argument("--n", type=int, help="budget: the LoRA learning-curve n (runs/<ds>/fold<k>/lora_n<n>)")
|
| 134 |
+
ap.add_argument("--work", type=Path, required=True)
|
| 135 |
+
ap.add_argument("--smoke-reps", type=int, default=0, help="SMOKE ONLY: keep the first N representative rows")
|
| 136 |
+
ap.add_argument("--smoke-cells", type=int, default=0, help="SMOKE ONLY: at most N cells per representative")
|
| 137 |
+
ap.add_argument("--smoke-targets", default="", help="SMOKE ONLY: comma list of target sample ids")
|
| 138 |
+
ap.add_argument("--smoke-rep-ids", default="", help="SMOKE ONLY: comma list of representative sample ids to keep")
|
| 139 |
+
ap.add_argument("--check-only", action="store_true", help="dry run: check everything, write nothing under --work")
|
| 140 |
+
ap.add_argument("--check-out", type=Path, default=None, help="--check-only: write the split summary JSON here")
|
| 141 |
+
a = ap.parse_args(argv)
|
| 142 |
+
j = a.draw if a.mode == "fewshot" else a.fold
|
| 143 |
+
if j is None:
|
| 144 |
+
raise SystemExit("--draw (fewshot) or --fold (cv, budget) required")
|
| 145 |
+
if (a.mode == "budget") != (a.n is not None):
|
| 146 |
+
raise SystemExit("--n is required with --mode budget and only valid there")
|
| 147 |
+
smoke = bool(a.smoke_reps or a.smoke_cells or a.smoke_targets or a.smoke_rep_ids)
|
| 148 |
+
work = a.work.resolve()
|
| 149 |
+
if smoke and "/scsemi/smoke/" not in str(work) + "/":
|
| 150 |
+
raise SystemExit("smoke subsetting only under scsemi/smoke/")
|
| 151 |
+
out = work / "inputs"
|
| 152 |
+
if not a.check_only:
|
| 153 |
+
if (out / "inputs_manifest.json").exists():
|
| 154 |
+
raise SystemExit(f"{out}/inputs_manifest.json exists; inputs are immutable (preserve and inspect)")
|
| 155 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 156 |
+
data = TASK / "data" / a.dataset
|
| 157 |
+
d = PD.load(data)
|
| 158 |
+
folds = pd.read_csv(data / "folds.csv")
|
| 159 |
+
if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
|
| 160 |
+
raise SystemExit("folds.csv rows differ from features.npz")
|
| 161 |
+
s = split_rows(a.dataset, a.mode, j, d["sample_ids"], folds, n=a.n)
|
| 162 |
+
rep, tgt = s["rep"], s["tgt"]
|
| 163 |
+
if a.smoke_rep_ids:
|
| 164 |
+
keep_r = set(a.smoke_rep_ids.split(","))
|
| 165 |
+
rep = np.asarray([r for r in rep if d["sample_ids"][r] in keep_r], dtype=np.int64)
|
| 166 |
+
if a.smoke_reps:
|
| 167 |
+
rep = rep[: a.smoke_reps]
|
| 168 |
+
if a.smoke_targets:
|
| 169 |
+
keep = set(a.smoke_targets.split(","))
|
| 170 |
+
tgt = np.asarray([t for t in tgt if d["sample_ids"][t] in keep], dtype=np.int64)
|
| 171 |
+
s["test"] = [x for x in s["test"] if x in keep]
|
| 172 |
+
if a.mode == "fewshot" and not smoke:
|
| 173 |
+
usable = np.flatnonzero(folds["fold"].to_numpy() >= 0)
|
| 174 |
+
if set(rep.tolist()) | set(tgt.tolist()) != set(usable.tolist()):
|
| 175 |
+
raise SystemExit("representatives + targets do not cover the usable rows")
|
| 176 |
+
# modeled genes
|
| 177 |
+
z = np.load(data / "cells_panel6k.npz", allow_pickle=False)
|
| 178 |
+
panel = z["panel_gene_ids"].astype(str)
|
| 179 |
+
gpos = {g: i for i, g in enumerate(d["gene_ids"])}
|
| 180 |
+
pcanon = np.asarray([gpos[g] for g in panel], dtype=np.int64)
|
| 181 |
+
rows = np.sort(np.concatenate([rep, tgt]))
|
| 182 |
+
bulk_ok = d["bulk_valid"][rows][:, pcanon].all(0)
|
| 183 |
+
sc_ok = d["sc_valid"][rep][:, pcanon].all(0)
|
| 184 |
+
model_pidx = np.flatnonzero(bulk_ok & sc_ok)
|
| 185 |
+
genes = panel[model_pidx]
|
| 186 |
+
if genes.size < 1000:
|
| 187 |
+
raise SystemExit(f"only {genes.size} modeled genes")
|
| 188 |
+
# scorer's scoring genes (all rows of the dataset) for the record
|
| 189 |
+
score_mask = d["bulk_valid"][:, pcanon].all(0) & d["sc_valid"][:, pcanon].all(0)
|
| 190 |
+
# bulk
|
| 191 |
+
import anndata as ad
|
| 192 |
+
B = d["bulk"][rows][:, pcanon[model_pidx]].astype(np.float64)
|
| 193 |
+
if not np.isfinite(B).all() or (B < 0).any():
|
| 194 |
+
raise SystemExit("non-finite or negative bulk on the modeled genes")
|
| 195 |
+
if (B.sum(1) <= 0).any():
|
| 196 |
+
raise SystemExit("a bulk row has no counts on the modeled genes")
|
| 197 |
+
sym = pd.read_csv(TASK.parents[1] / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv")
|
| 198 |
+
sym = sym.set_index("gene_id").gene_symbol.astype(str)
|
| 199 |
+
var = pd.DataFrame({"gene_symbol": sym.reindex(genes).to_numpy()}, index=pd.Index(genes, name="gene_id"))
|
| 200 |
+
obs_b = pd.DataFrame({"sample_ids": d["sample_ids"][rows], "donor_id": d["donor_ids"][rows],
|
| 201 |
+
"group": d["groups"][rows], "role": np.where(np.isin(rows, rep), "representative", "target")},
|
| 202 |
+
index=pd.Index(d["sample_ids"][rows], name="obs"))
|
| 203 |
+
if not a.check_only:
|
| 204 |
+
ad.AnnData(X=B, obs=obs_b, var=var).write_h5ad(out / "bulk.h5ad")
|
| 205 |
+
# representative cells
|
| 206 |
+
X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
|
| 207 |
+
rs = np.asarray(z["row_sample"], dtype=np.int64)
|
| 208 |
+
blocks, obs_rows, per_rep = [], [], []
|
| 209 |
+
rng = np.random.default_rng(SEED)
|
| 210 |
+
for r in rep:
|
| 211 |
+
cells = np.flatnonzero(rs == r)
|
| 212 |
+
if a.smoke_cells and cells.size > a.smoke_cells:
|
| 213 |
+
cells = np.sort(rng.choice(cells, a.smoke_cells, replace=False))
|
| 214 |
+
Xr = X[cells][:, model_pidx].tocsr().astype(np.float32)
|
| 215 |
+
lib = np.asarray(Xr.sum(1)).ravel()
|
| 216 |
+
if (lib <= 0).any():
|
| 217 |
+
raise SystemExit(f"{d['sample_ids'][r]}: {int((lib <= 0).sum())} cells without counts on the modeled genes")
|
| 218 |
+
blocks.append(Xr)
|
| 219 |
+
obs_rows.append(pd.DataFrame({"sample_ids": d["sample_ids"][r], "donor_id": d["donor_ids"][r],
|
| 220 |
+
"source_cell_row": cells}))
|
| 221 |
+
per_rep.append({"sample_id": str(d["sample_ids"][r]), "donor_id": str(d["donor_ids"][r]),
|
| 222 |
+
"group": str(d["groups"][r]), "n_cells": int(cells.size),
|
| 223 |
+
"median_umi_modeled_genes": float(np.median(lib))})
|
| 224 |
+
Xs = sp.vstack(blocks, format="csr")
|
| 225 |
+
obs_s = pd.concat(obs_rows, ignore_index=True)
|
| 226 |
+
obs_s.index = pd.Index([f"{a_}|{b_}" for a_, b_ in zip(obs_s.sample_ids, obs_s.source_cell_row)], name="cell")
|
| 227 |
+
if not a.check_only:
|
| 228 |
+
ad.AnnData(X=Xs, obs=obs_s, var=var.copy()).write_h5ad(out / "rep_sc.h5ad")
|
| 229 |
+
lib_all = np.asarray(Xs.sum(1)).ravel()
|
| 230 |
+
depth = float(np.median(lib_all))
|
| 231 |
+
cond = s["condition"]
|
| 232 |
+
man = {
|
| 233 |
+
"schema": "scsemi_paired.inputs.v1", "written_utc": datetime.now(timezone.utc).isoformat(),
|
| 234 |
+
"dataset": a.dataset, "mode": a.mode, "split": j, "smoke": smoke,
|
| 235 |
+
"smoke_settings": {"reps": a.smoke_reps, "cells": a.smoke_cells, "targets": a.smoke_targets,
|
| 236 |
+
"rep_ids": a.smoke_rep_ids} if smoke else None,
|
| 237 |
+
"train_donors": s["train_donors"],
|
| 238 |
+
"representatives": per_rep, "targets": [str(x) for x in d["sample_ids"][tgt]],
|
| 239 |
+
"target_order_test_samples": s["test"],
|
| 240 |
+
"bulk_row_order": [str(x) for x in d["sample_ids"][rows]],
|
| 241 |
+
"n_representatives": int(rep.size), "n_targets": int(tgt.size), "n_rep_cells": int(Xs.shape[0]),
|
| 242 |
+
"modeled_genes": {"n": int(genes.size), "gene_ids": genes.tolist(), "panel_index": model_pidx.tolist(),
|
| 243 |
+
"rule": "6k panel genes with bulk_valid in every rep+target row and sc_valid in every rep row",
|
| 244 |
+
"equals_scorer_scoring_genes": bool(np.array_equal(model_pidx, np.flatnonzero(score_mask))),
|
| 245 |
+
"n_scorer_scoring_genes": int(score_mask.sum())},
|
| 246 |
+
"depth": {"value": depth, "rule": "median over all representative cells (all rows of the training donors) of the "
|
| 247 |
+
"per-cell UMI sum on the modeled genes; every generated cell is scaled to this expected library",
|
| 248 |
+
"n_cells": int(lib_all.size)},
|
| 249 |
+
"condition_npz": str(cond), "condition_sha256": sha(cond),
|
| 250 |
+
"sources": {"features.npz": sha(data / "features.npz"), "folds.csv": sha(data / "folds.csv"),
|
| 251 |
+
"cells_panel6k.npz": sha(data / "cells_panel6k.npz"),
|
| 252 |
+
**{k: sha(v) for k, v in s["sources"].items()}},
|
| 253 |
+
"files": ({"bulk.h5ad": sha(out / "bulk.h5ad"), "rep_sc.h5ad": sha(out / "rep_sc.h5ad")}
|
| 254 |
+
if not a.check_only else None),
|
| 255 |
+
"builder_sha256": sha(Path(__file__)),
|
| 256 |
+
}
|
| 257 |
+
if a.mode == "budget":
|
| 258 |
+
man["target_donors"] = sorted({str(x) for x in d["donor_ids"][tgt]})
|
| 259 |
+
man["budget"] = s["budget"]
|
| 260 |
+
with np.load(cond, allow_pickle=False) as cz:
|
| 261 |
+
cond_ids = cz["sample_ids"].astype(str).tolist()
|
| 262 |
+
if not smoke and sorted(cond_ids) != sorted(man["targets"]):
|
| 263 |
+
raise SystemExit("condition NPZ sample_ids differ from the targets")
|
| 264 |
+
man["condition_sample_order"] = cond_ids
|
| 265 |
+
if a.check_only:
|
| 266 |
+
summary = {"dataset": a.dataset, "mode": a.mode, "split": j, "n": a.n, "work": str(work),
|
| 267 |
+
"reps": [r["sample_id"] for r in per_rep], "targets": man["targets"],
|
| 268 |
+
"rep_cells": {r["sample_id"]: r["n_cells"] for r in per_rep}, "n_rep_cells": int(Xs.shape[0]),
|
| 269 |
+
"modeled_genes": int(genes.size), "modeled_panel_index": model_pidx.tolist(),
|
| 270 |
+
"equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"],
|
| 271 |
+
"depth": depth, "condition_npz": str(cond), "condition_matches_targets": True,
|
| 272 |
+
"train_donors": s["train_donors"], **({"budget": s["budget"]} if a.mode == "budget" else {})}
|
| 273 |
+
if a.check_out is not None:
|
| 274 |
+
a.check_out.parent.mkdir(parents=True, exist_ok=True)
|
| 275 |
+
a.check_out.write_text(json.dumps(summary, indent=1) + "\n")
|
| 276 |
+
print(json.dumps({k: summary[k] for k in ("dataset", "mode", "split", "n", "n_rep_cells", "modeled_genes",
|
| 277 |
+
"equals_scorer_genes", "depth")} | {"reps": len(summary["reps"]),
|
| 278 |
+
"targets": len(summary["targets"])}))
|
| 279 |
+
return 0
|
| 280 |
+
tmp = out / "inputs_manifest.json.tmp"
|
| 281 |
+
tmp.write_text(json.dumps(man, indent=1) + "\n")
|
| 282 |
+
tmp.replace(out / "inputs_manifest.json")
|
| 283 |
+
print(json.dumps({"dataset": a.dataset, "mode": a.mode, "split": j, "reps": int(rep.size), "targets": int(tgt.size),
|
| 284 |
+
"rep_cells": int(Xs.shape[0]), "modeled_genes": int(genes.size),
|
| 285 |
+
"equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"], "depth": depth}))
|
| 286 |
+
return 0
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/reuse_gpu_check.sh
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Minimal GPU confirmation that a reused pretraining equals a fresh one (coordinating agent only; one GPU call, ~3-6 min).
|
| 3 |
+
# Run once after work/<ds>/cv/fold<k> has pretrained (its prepared.json and receipted checkpoints exist), before the
|
| 4 |
+
# budget lines that reuse it. Nothing under work/ or generated/ is written.
|
| 5 |
+
# 1. CPU units: build the budget split (fold k, n) in validation/reuse_gpu_check_20261002/<ds>_fold<k>_n<n>/ and prepare
|
| 6 |
+
# it with --reuse-from the CV run (hvset copied; every representative's sample_sc / geneset_scores must be
|
| 7 |
+
# byte-identical to the CV run's, else prepare refuses);
|
| 8 |
+
# 2. GPU (thermal gate + gpu_usable.sh, then ml-run, as run_queue_scsemi.sh): phase pretrain --max-reps 1 with
|
| 9 |
+
# --reuse-from, i.e. the first representative pretrained FROM SCRATCH with the CV run's seeds (no link);
|
| 10 |
+
# 3. CPU unit: tools/compare_runs.py fresh vs CV checkpoints (torch.equal on every tensor) ->
|
| 11 |
+
# validation/reuse_gpu_check_20261002_<ds>_fold<k>_n<n>.json; the check dir's prepared cell graphs are then deleted.
|
| 12 |
+
# usage: reuse_gpu_check.sh [DATASET (immicro)] [FOLD (0)] [N (5)]
|
| 13 |
+
set -uo pipefail
|
| 14 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 15 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 16 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 17 |
+
S=$M8/plans/paired_finetune_intradataset_20260927/scsemi
|
| 18 |
+
[[ "$(hostname -s)" == spark-fa6b ]] || { echo "server_1 only (frozen runtime_env)" >&2; exit 2; }
|
| 19 |
+
PY=$M8/plans/immicro_scsemi_comparison_20260927/runtime_env/bin/python
|
| 20 |
+
ds=${1:-immicro}; k=${2:-0}; n=${3:-5}
|
| 21 |
+
A=$S/work/$ds/cv/fold$k
|
| 22 |
+
W=$S/validation/reuse_gpu_check_20261002/${ds}_fold${k}_n$n
|
| 23 |
+
OUT=$S/validation/reuse_gpu_check_20261002_${ds}_fold${k}_n$n.json
|
| 24 |
+
[[ -s $A/prepared.json ]] || { echo "CV run $A is not prepared" >&2; exit 1; }
|
| 25 |
+
ls "$A"/scsemi_project/models/fastreconst2_*.receipt.json >/dev/null 2>&1 || { echo "CV run $A has no pretrain-2 checkpoints yet" >&2; exit 1; }
|
| 26 |
+
mkdir -p "$W"
|
| 27 |
+
if [[ ! -s $W/inputs/inputs_manifest.json ]]; then
|
| 28 |
+
ALLOW_USER_SITE=1 bash "$S/tools/cpu_unit.sh" "rgc-in-${ds:0:3}$k" 4 12 "$PY" -u "$S/tools/prepare_draw_inputs.py" \
|
| 29 |
+
--dataset "$ds" --mode budget --fold "$k" --n "$n" --work "$W" || exit 1
|
| 30 |
+
fi
|
| 31 |
+
if [[ ! -s $W/prepared.json ]]; then
|
| 32 |
+
ALLOW_USER_SITE=1 bash "$S/tools/cpu_unit.sh" "rgc-prep-${ds:0:3}$k" 6 16 "$PY" -u "$S/tools/run_scsemi_paired.py" \
|
| 33 |
+
--work "$W" --phase prepare --device cpu --threads 6 --reuse-from "$A" || exit 1
|
| 34 |
+
fi
|
| 35 |
+
r=$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['representatives'][0]['sample_id'])" "$W/inputs/inputs_manifest.json")
|
| 36 |
+
[[ -s $A/scsemi_project/models/fastreconst2_$r.receipt.json ]] || { echo "CV run lacks the checkpoints of $r" >&2; exit 1; }
|
| 37 |
+
if [[ ! -s $W/scsemi_project/models/fastreconst2_$r.receipt.json ]]; then
|
| 38 |
+
until bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh" && bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh"; do
|
| 39 |
+
sleep 120
|
| 40 |
+
done
|
| 41 |
+
"$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 42 |
+
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 \
|
| 43 |
+
"$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase pretrain --device cuda:0 --threads 4 --max-reps 1 \
|
| 44 |
+
--reuse-from "$A" >> "$W/gpu.log" 2>&1 < /dev/null || { echo "GPU pretrain failed (see $W/gpu.log)" >&2; exit 1; }
|
| 45 |
+
fi
|
| 46 |
+
ALLOW_USER_SITE=1 bash "$S/tools/cpu_unit.sh" "rgc-cmp-${ds:0:3}$k" 2 8 "$PY" -u "$S/tools/compare_runs.py" "$OUT" "$W" "$A"
|
| 47 |
+
rc=$?
|
| 48 |
+
rm -f "$W"/scsemi_project/sample_sc/*.h5ad "$W"/scsemi_project/geneset_scores/*.npy
|
| 49 |
+
python3 -c "import json,sys;d=json.load(open(sys.argv[1]));print('reuse == fresh:', d['all_identical'], d['items'])" "$OUT"
|
| 50 |
+
exit $rc
|
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_queue_scsemi.sh
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# Added 2026-10-02 (opt-in; lines and env without them behave exactly as before):
|
| 22 |
+
# budget|DATASET|FOLD|OPTIONS|N : equal-pair-budget split (representatives = runs/<ds>/fold<k>/lora_n<N>/RUN.json
|
| 23 |
+
# train + inner-val rows; targets = fold k's rows) -> generated/<ds>/fold<k>/scsemi_n<N>__raw.npz
|
| 24 |
+
# OPTIONS lean_hvset : prepare selects hvset with tools/lean_hvset.py (output-identical, one representative in
|
| 25 |
+
# memory; needed for CV folds). Passed to every wrapper call of the split (run binding).
|
| 26 |
+
# reuse_cv : (budget lines) reuse the hvset and pretraining of work/<ds>/cv/fold<k> (--reuse-from); a CPU
|
| 27 |
+
# 'link' unit hard-links its checkpoints; GPU pretraining then runs only for a representative
|
| 28 |
+
# whose source checkpoint is missing, and only with REUSE_ALLOW_PRETRAIN=1 (source seeds)
|
| 29 |
+
# clean_prepared: like clean_sample_sc, and also delete scsemi_project/geneset_scores/*.npy (cells x 2,922
|
| 30 |
+
# float64, 11 GB per sepsis CV fold; sha256 kept in prepared.json, re-derivable)
|
| 31 |
+
# offload : after export + validation, move scsemi_project/models/* and inputs/rep_sc.h5ad to spark-0110
|
| 32 |
+
# (tools/offload_work.sh: same absolute paths, sha-verified; receipts and manifests stay)
|
| 33 |
+
# offload|DATASET|cv : move work/<ds>/cv/fold* models + inputs to spark-0110 once every budget split of <ds> is done
|
| 34 |
+
# MIN_FREE_GIB (0 = off): before a split's input build and CPU prepare (where its prepared cell graphs and
|
| 35 |
+
# gene-set scores are written), wait (MAX_WAIT_H) until $S's filesystem has this many GiB free
|
| 36 |
+
set -uo pipefail
|
| 37 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 38 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 39 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 40 |
+
T=$M8/plans/paired_finetune_intradataset_20260927
|
| 41 |
+
S=$T/scsemi
|
| 42 |
+
case "$(hostname -s)" in
|
| 43 |
+
spark-fa6b) PYD=$M8/plans/immicro_scsemi_comparison_20260927/runtime_env/bin/python; USERSITE=1 ;; # server_1: frozen env
|
| 44 |
+
spark-0110) PYD=$S/runtime_env/bin/python; USERSITE=0 ;; # server_2: equivalent venv
|
| 45 |
+
*) echo "unknown host $(hostname -s)" >&2; exit 2 ;;
|
| 46 |
+
esac
|
| 47 |
+
PY=${SCSEMI_PY:-$PYD}
|
| 48 |
+
SPY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python # benchmark scorer env (both hosts)
|
| 49 |
+
QUEUE="${QUEUE:?QUEUE}"; MAX_WAIT_H="${MAX_WAIT_H:-24}"; CHUNK_REPS="${CHUNK_REPS:-2}"; CHUNK_TARGETS="${CHUNK_TARGETS:-12}"
|
| 50 |
+
SCORE="${SCORE:-0}"; SMOKE_CPU="${SMOKE_CPU:-0}"; PREP_ONLY="${PREP_ONLY:-0}"; PREP_MEM="${PREP_MEM:-16}"
|
| 51 |
+
MIN_FREE_GIB="${MIN_FREE_GIB:-0}"; REUSE_ALLOW_PRETRAIN="${REUSE_ALLOW_PRETRAIN:-0}"
|
| 52 |
+
mkdir -p "$S/logs"
|
| 53 |
+
LOG=$S/logs/queue_$(basename "$QUEUE" .txt)_$(hostname -s)_$(date +%Y%m%dT%H%M%S).log
|
| 54 |
+
log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
|
| 55 |
+
start=$(date +%s)
|
| 56 |
+
gate() {
|
| 57 |
+
local verdict usable
|
| 58 |
+
if [[ $SMOKE_CPU == 1 ]]; then echo "smoke: CPU only, no GPU gate"; return; fi
|
| 59 |
+
until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh") \
|
| 60 |
+
&& usable=$(bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh" 2>/dev/null); do
|
| 61 |
+
(( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
|
| 62 |
+
sleep 120
|
| 63 |
+
done
|
| 64 |
+
echo "$verdict; GPU $usable"
|
| 65 |
+
}
|
| 66 |
+
cpu() { # cpu NAME THREADS MEMMAX CMD... (waits for the memory floor instead of failing on it)
|
| 67 |
+
local mem=$3
|
| 68 |
+
until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 32 + mem )); do
|
| 69 |
+
(( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: memory floor not met within ${MAX_WAIT_H} h"; exit 1; }
|
| 70 |
+
sleep 120
|
| 71 |
+
done
|
| 72 |
+
ALLOW_USER_SITE=${US:-$USERSITE} bash "$S/tools/cpu_unit.sh" "$@" >> "$LOG" 2>&1 < /dev/null
|
| 73 |
+
}
|
| 74 |
+
st() { python3 -c "import json,sys;print(json.load(open(sys.argv[1]))[sys.argv[2]])" "$1/status.json" "$2" 2>/dev/null; }
|
| 75 |
+
disk() { # disk NOTE : wait until MIN_FREE_GIB GiB are free on $S (no-op when MIN_FREE_GIB is 0)
|
| 76 |
+
(( MIN_FREE_GIB > 0 )) || return 0
|
| 77 |
+
local free warned=0
|
| 78 |
+
while free=$(df -B1G --output=avail "$S" | tail -1 | tr -dc '0-9'); (( free < MIN_FREE_GIB )); do
|
| 79 |
+
(( warned )) || { log "disk: ${free} GiB free < MIN_FREE_GIB ${MIN_FREE_GIB} before $1; waiting"; warned=1; }
|
| 80 |
+
(( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: disk below ${MIN_FREE_GIB} GiB within ${MAX_WAIT_H} h"; exit 1; }
|
| 81 |
+
sleep 300
|
| 82 |
+
done
|
| 83 |
+
(( warned )) && log "disk: ${free} GiB free; continuing"
|
| 84 |
+
return 0
|
| 85 |
+
}
|
| 86 |
+
gpu() { # gpu WORK PHASE EXTRA...
|
| 87 |
+
local W=$1 phase=$2; shift 2
|
| 88 |
+
if [[ $SMOKE_CPU == 1 ]]; then # queue-logic test: same wrapper, CPU, reduced epochs, never ml-run
|
| 89 |
+
cpu "smk-$phase" 4 8 "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase "$phase" --device cpu --smoke --threads 4 "$@"
|
| 90 |
+
return
|
| 91 |
+
fi
|
| 92 |
+
local ns=
|
| 93 |
+
[[ $USERSITE == 1 ]] || ns=PYTHONNOUSERSITE=1
|
| 94 |
+
"$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 95 |
+
OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 $ns \
|
| 96 |
+
"$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase "$phase" --device cuda:0 --threads 4 "$@" \
|
| 97 |
+
>> "$W/gpu.log" 2>&1 < /dev/null
|
| 98 |
+
}
|
| 99 |
+
n_fail=0
|
| 100 |
+
fail() { n_fail=$((n_fail+1)); log "WARN: $*"; }
|
| 101 |
+
log "queue $QUEUE on $(hostname -s); python $PY; chunks reps=$CHUNK_REPS targets=$CHUNK_TARGETS; score=$SCORE; smoke_cpu=$SMOKE_CPU"
|
| 102 |
+
while IFS= read -r line; do
|
| 103 |
+
[[ -z "${line// }" || "$line" == \#* ]] && continue
|
| 104 |
+
IFS='|' read -r mode ds j opts extra <<< "$line"
|
| 105 |
+
SMK=()
|
| 106 |
+
case $mode in
|
| 107 |
+
fewshot) W=$S/work/$ds/fewshot_n5/draw$j; OUT=$T/generated/$ds/fewshot_n5/draw$j/scsemi5__raw.npz; ARM=scsemi5
|
| 108 |
+
SC=$T/scores/$ds/fewshot_n5/draw${j}_scsemi5; DON=$T/data/$ds/fewshot_n5/draw$j/test_samples.txt
|
| 109 |
+
imode=fewshot; sflag=(--draw "$j") ;;
|
| 110 |
+
cv) W=$S/work/$ds/cv/fold$j; OUT=$T/generated/$ds/fold$j/scsemi__raw.npz; ARM=scsemi
|
| 111 |
+
SC=$T/scores/$ds/fold${j}_scsemi; DON=; imode=cv; sflag=(--fold "$j") ;;
|
| 112 |
+
budget) [[ $extra =~ ^[0-9]+$ ]] || { fail "budget line needs N in field 5: $line"; continue; }
|
| 113 |
+
W=$S/work/$ds/budget/fold$j/n$extra; OUT=$T/generated/$ds/fold$j/scsemi_n${extra}__raw.npz
|
| 114 |
+
ARM=scsemi_n$extra; SC=; DON=; imode=budget; sflag=(--fold "$j" --n "$extra") ;;
|
| 115 |
+
offload) # offload|DATASET|cv : after the budget lines that reuse them, move the CV runs' models + rep_sc.h5ad to
|
| 116 |
+
# spark-0110 (tools/offload_work.sh; same absolute paths, sha-verified). Refused while any budget output
|
| 117 |
+
# of the dataset is missing or unvalidated (their link phase reads the CV checkpoints).
|
| 118 |
+
[[ $SMOKE_CPU != 1 && $j == cv ]] || { fail "offload line not run: $line"; continue; }
|
| 119 |
+
pend=0; args=()
|
| 120 |
+
for k in 0 1 2 3 4; do
|
| 121 |
+
for b in "$T"/generated/"$ds"/fold$k/scsemi_n*__raw.npz; do
|
| 122 |
+
[[ -e $b ]] || continue
|
| 123 |
+
python3 -c "import json,sys;sys.exit(0 if json.load(open(sys.argv[1]))['passed'] else 1)" "${b%.npz}.validation.json" 2>/dev/null || pend=1
|
| 124 |
+
done
|
| 125 |
+
for n in 5 10 20 40; do
|
| 126 |
+
[[ -d $S/work/$ds/budget/fold$k/n$n ]] && [[ ! -s $T/generated/$ds/fold$k/scsemi_n${n}__raw.validation.json ]] && pend=1
|
| 127 |
+
done
|
| 128 |
+
args+=("$T/generated/$ds/fold$k/scsemi__raw.validation.json" "$S/work/$ds/cv/fold$k")
|
| 129 |
+
done
|
| 130 |
+
(( pend )) && { fail "$ds: a budget split is unfinished; CV runs kept for its link phase ($line)"; continue; }
|
| 131 |
+
log "$ds: offloading the CV runs' models and inputs to spark-0110"
|
| 132 |
+
bash "$S/tools/offload_work.sh" "${args[@]}" >> "$LOG" 2>&1 || fail "$ds: offload incomplete (local files kept where unverified)"
|
| 133 |
+
continue ;;
|
| 134 |
+
smoke) [[ $SMOKE_CPU == 1 ]] || { fail "smoke line needs SMOKE_CPU=1: $line"; continue; }
|
| 135 |
+
# smoke|DS|SPLIT|OPTS|T1,T2[|MODE|N|REP_IDS]: MODE fewshot (default, as before), cv or budget
|
| 136 |
+
IFS='|' read -r stg smode sn sreps <<< "$extra"
|
| 137 |
+
smode=${smode:-fewshot}; SMK=(--smoke)
|
| 138 |
+
if [[ $smode == fewshot ]]; then
|
| 139 |
+
W=$S/smoke/queue/${ds}_draw$j; OUT=$W/generated/scsemi5__raw.npz; ARM=scsemi5
|
| 140 |
+
sflag=(--draw "$j" --smoke-reps 2 --smoke-cells 300 --smoke-targets "$stg")
|
| 141 |
+
else
|
| 142 |
+
W=$S/smoke/queue/${ds}_${smode}$j${sn:+_n$sn}; OUT=$W/generated/scsemi__raw.npz; ARM=scsemi
|
| 143 |
+
sflag=(--fold "$j" ${sn:+--n "$sn"} --smoke-cells 300 --smoke-targets "$stg")
|
| 144 |
+
if [[ -n $sreps ]]; then sflag+=(--smoke-rep-ids "$sreps"); else sflag+=(--smoke-reps 2); fi
|
| 145 |
+
fi
|
| 146 |
+
SC=$W/score; DON=$W/targets.txt; imode=$smode
|
| 147 |
+
mkdir -p "$W"; tr ',' '\n' <<< "$stg" > "$DON" ;;
|
| 148 |
+
*) fail "unknown line: $line"; continue ;;
|
| 149 |
+
esac
|
| 150 |
+
[[ $SMOKE_CPU == 1 && $mode != smoke ]] && { fail "SMOKE_CPU=1 runs smoke lines only: $line"; continue; }
|
| 151 |
+
tag="$ds/$mode$j"; uid="${ds:0:3}-$mode$j"
|
| 152 |
+
[[ $mode == budget ]] && { tag="$ds/budget${j}_n$extra"; uid="${ds:0:3}-b${j}n$extra"; }
|
| 153 |
+
WARGS=(); REUSE=0
|
| 154 |
+
[[ ",$opts," == *",lean_hvset,"* ]] && WARGS+=(--lean-hvset)
|
| 155 |
+
if [[ ",$opts," == *",reuse_cv,"* ]]; then
|
| 156 |
+
[[ $mode == budget || ( $mode == smoke && $imode == budget ) ]] || { fail "reuse_cv is for budget lines: $line"; continue; }
|
| 157 |
+
if [[ $mode == smoke ]]; then WARGS+=(--reuse-from "$S/smoke/queue/${ds}_cv$j"); else WARGS+=(--reuse-from "$S/work/$ds/cv/fold$j"); fi
|
| 158 |
+
REUSE=1
|
| 159 |
+
fi
|
| 160 |
+
mkdir -p "$W"
|
| 161 |
+
exec 9>"$W/.split.lock" # re-opening fd 9 releases the previous split's lock
|
| 162 |
+
flock -w $((MAX_WAIT_H * 3600)) 9 || { fail "$tag: split lock held by another queue for ${MAX_WAIT_H} h"; continue; }
|
| 163 |
+
VAL=${OUT%.npz}.validation.json
|
| 164 |
+
if [[ -s $VAL ]] && python3 -c "import json,sys;sys.exit(0 if json.load(open(sys.argv[1]))['passed'] else 1)" "$VAL"; then
|
| 165 |
+
log "$tag: exported + validated already; skipped"
|
| 166 |
+
else
|
| 167 |
+
mkdir -p "$W"
|
| 168 |
+
if [[ ! -s $W/inputs/inputs_manifest.json ]]; then
|
| 169 |
+
disk "$tag input build"
|
| 170 |
+
log "$tag: building inputs (CPU unit)"
|
| 171 |
+
cpu "in-$uid" 4 12 "$PY" -u "$S/tools/prepare_draw_inputs.py" --dataset "$ds" --mode "$imode" "${sflag[@]}" --work "$W" \
|
| 172 |
+
|| { fail "$tag: input build failed"; continue; }
|
| 173 |
+
fi
|
| 174 |
+
if [[ ! -s $W/prepared.json ]]; then
|
| 175 |
+
disk "$tag prepare"
|
| 176 |
+
log "$tag: upstream prepare (initsetup + assignment + scprocess, CPU unit)${WARGS[*]:+ [${WARGS[*]}]}"
|
| 177 |
+
cpu "prep-$uid" 6 "$PREP_MEM" "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase prepare --device cpu --threads 6 "${SMK[@]}" "${WARGS[@]}" \
|
| 178 |
+
|| { fail "$tag: prepare failed (see $W/events.jsonl)"; continue; }
|
| 179 |
+
fi
|
| 180 |
+
if [[ $PREP_ONLY == 1 ]]; then log "$tag: CPU-prepared (PREP_ONLY; GPU steps left to the GPU queue)"; continue; fi
|
| 181 |
+
if (( REUSE )) && [[ "$(st "$W" pretrain_complete)" != True ]]; then
|
| 182 |
+
log "$tag: linking the source run's pretrain checkpoints (CPU unit)"
|
| 183 |
+
cpu "lnk-$uid" 2 4 "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase link --device cpu --threads 2 "${SMK[@]}" "${WARGS[@]}" \
|
| 184 |
+
|| { fail "$tag: link failed (see $W/events.jsonl)"; continue; }
|
| 185 |
+
log "$tag: pretrain checkpoints after link: $(st "$W" reps_pretrained)/$(st "$W" n_reps)"
|
| 186 |
+
if [[ "$(st "$W" pretrain_complete)" != True && $REUSE_ALLOW_PRETRAIN != 1 ]]; then
|
| 187 |
+
fail "$tag: source run lacks pretrain checkpoints; REUSE_ALLOW_PRETRAIN=1 pretrains them with the source seeds"; continue
|
| 188 |
+
fi
|
| 189 |
+
fi
|
| 190 |
+
ok=1
|
| 191 |
+
while [[ "$(st "$W" pretrain_complete)" != True ]]; do
|
| 192 |
+
before=$(st "$W" reps_pretrained)
|
| 193 |
+
g=$(gate) || { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
|
| 194 |
+
log "$tag: pretrain ${before}/$(st "$W" n_reps) reps; next $CHUNK_REPS ($g)"
|
| 195 |
+
gpu "$W" pretrain --max-reps "$CHUNK_REPS" "${WARGS[@]}" || { fail "$tag: pretrain step failed (see $W/gpu.log, $W/events.jsonl)"; ok=0; break; }
|
| 196 |
+
[[ "$(st "$W" reps_pretrained)" != "$before" ]] || { fail "$tag: pretrain made no progress"; ok=0; break; }
|
| 197 |
+
done
|
| 198 |
+
(( ok )) || continue
|
| 199 |
+
while [[ "$(st "$W" infer_complete)" != True ]]; do
|
| 200 |
+
before=$(st "$W" targets_done)
|
| 201 |
+
g=$(gate) || { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
|
| 202 |
+
log "$tag: infer ${before}/$(st "$W" n_targets) targets; next $CHUNK_TARGETS ($g)"
|
| 203 |
+
gpu "$W" infer --max-targets "$CHUNK_TARGETS" "${WARGS[@]}" || { fail "$tag: infer step failed (see $W/gpu.log, $W/events.jsonl)"; ok=0; break; }
|
| 204 |
+
[[ "$(st "$W" targets_done)" != "$before" ]] || { fail "$tag: infer made no progress"; ok=0; break; }
|
| 205 |
+
done
|
| 206 |
+
(( ok )) || continue
|
| 207 |
+
if [[ ! -s $OUT ]]; then
|
| 208 |
+
cpu "exp-$uid" 2 16 "$PY" -u "$S/tools/export_npz.py" --work "$W" --out "$OUT" || { fail "$tag: export failed"; continue; }
|
| 209 |
+
fi
|
| 210 |
+
cpu "val-$uid" 2 16 "$PY" -u "$S/tools/validate_export.py" --work "$W" --npz "$OUT" || { fail "$tag: validation failed ($VAL)"; continue; }
|
| 211 |
+
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")"
|
| 212 |
+
if [[ ",$opts," == *",clean_sample_sc,"* || ",$opts," == *",clean_prepared,"* ]]; then
|
| 213 |
+
rm -f "$W"/scsemi_project/sample_sc/*.h5ad && log "$tag: removed sample_sc/*.h5ad (sha256 kept in prepared.json)"
|
| 214 |
+
fi
|
| 215 |
+
if [[ ",$opts," == *",clean_prepared,"* ]]; then
|
| 216 |
+
rm -f "$W"/scsemi_project/geneset_scores/*.npy && log "$tag: removed geneset_scores/*.npy (sha256 kept in prepared.json)"
|
| 217 |
+
fi
|
| 218 |
+
if [[ ",$opts," == *",offload,"* && $SMOKE_CPU != 1 ]]; then
|
| 219 |
+
bash "$S/tools/offload_work.sh" "$VAL" "$W" >> "$LOG" 2>&1 && log "$tag: models + rep_sc.h5ad moved to spark-0110" \
|
| 220 |
+
|| fail "$tag: offload incomplete (local files kept where unverified)"
|
| 221 |
+
fi
|
| 222 |
+
fi
|
| 223 |
+
if [[ $SCORE == 1 && $PREP_ONLY != 1 && $mode != cv && $mode != budget && -s $VAL && ! -s $SC/summary.json ]]; then
|
| 224 |
+
read -r -a cargs <<< "$(bash "$T/tools/contrast_args.sh" "$ds")"
|
| 225 |
+
log "$tag: scoring arm $ARM -> $SC"
|
| 226 |
+
mkdir -p "$SC"
|
| 227 |
+
US=0 cpu "sc-$uid" 6 16 "$SPY" -u "$T/tools/score_ft.py" --dataset "$ds" --out "$SC" --threads 6 \
|
| 228 |
+
--donors "$DON" "${cargs[@]}" --arm "$ARM=$OUT" || fail "$tag: scoring failed"
|
| 229 |
+
fi
|
| 230 |
+
done < "$QUEUE"
|
| 231 |
+
exec 9>&-
|
| 232 |
+
log "queue finished: failed=$n_fail"
|
| 233 |
+
(( n_fail == 0 ))
|