junidude14 commited on
Commit
9aefea2
·
verified ·
1 Parent(s): e7a1524

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/queues/loco_scratch_sepsis_20261005.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # No-pretraining ablation, cross-cohort pilot (user decision 2026-10-05): held-out sepsis (split hoL_ye2026_sepsis =
2
+ # ImMicro + Imperial + Giroux + Liu), K = 1000, every denoiser weight randomly initialised (--init random), full
3
+ # training at the pretraining lr 2e-4, milestones every 50k steps up to 200k (each sampled and scored), saturation stop
4
+ # disabled (frac 0: stop only if a whole block does not improve), patience 10 evaluations of 1,000 steps.
5
+ loco|hoL_ye2026_sepsis|1000|scratchsat|full|2e-4|--init|random|--block|50000|--max-steps|200000|--saturation-frac|0|--eval-every|1000|--patience|10
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/mask_rescore.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """No-pretraining LOCO pilot (2026-10-05): rescore held-out arms with the genes that NO training cohort measured set to
3
+ zero in the generated cells (CPU only).
4
+
5
+ Why: a model trained from scratch on the training cohorts never receives a loss for a gene none of them measured, so its
6
+ output there is untrained. For held-out sepsis (split hoL_ye2026_sepsis) 46 panel genes are measured in sepsis but in
7
+ none of ImMicro / Imperial / Giroux / Liu; the scratch arm puts ~91 % of its generated UMI there, while the observed
8
+ sepsis cells carry 0.014 % of their UMI on them. Zeroing those genes in EVERY arm (scratch and pretrained alike) and
9
+ rescoring compares the arms on the genes the scratch model could learn. The unmasked scores stay the primary record.
10
+
11
+ mask_rescore.py ARM NPZ_PATH_OR_- [--held ye2026_sepsis] [--split hoL_ye2026_sepsis]
12
+ NPZ "-" = read the NPZ bytes from stdin (ssh spark-0110 cat ... | mask_rescore.py ARM -); its sha256 must equal the
13
+ receipt's output_sha256 (the receipt <npz>.log is read from the server_1 path given by --receipt).
14
+ The masked NPZ (+ a derived receipt with the source sha and the masked gene ids) is written to
15
+ generated_masked/<held>/<split>/<ARM>.npz, scored with score_ft.py exactly as score_pending.sh scores (usable samples,
16
+ per-cohort contrast) into scores_masked/<held>/<ARM>/, then deleted (receipt kept).
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import argparse
21
+ import hashlib
22
+ import io
23
+ import json
24
+ import subprocess
25
+ import sys
26
+ from datetime import datetime
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+
31
+ P = Path(__file__).resolve().parents[1]
32
+ SRC = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
33
+ PY = "/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python"
34
+
35
+
36
+ def never_trained_mask(split: str, held: str, gene_ids: np.ndarray) -> np.ndarray:
37
+ s = json.loads((P / f"splits/{split}.json").read_text())
38
+ tr = None
39
+ for c in s["training_cohorts"]:
40
+ z = np.load(Path(c["dataset_dir"]) / "cells_panel6k.npz", allow_pickle=False)
41
+ if not np.array_equal(z["panel_gene_ids"].astype(str), gene_ids):
42
+ raise SystemExit(f"{c['cohort']}: panel differs")
43
+ m = z["panel_measured"].any(0)
44
+ tr = m if tr is None else (tr | m)
45
+ z = np.load(SRC / f"data/{held}/cells_panel6k.npz", allow_pickle=False)
46
+ return z["panel_measured"].any(0) & ~tr
47
+
48
+
49
+ def main() -> int:
50
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
51
+ ap.add_argument("arm")
52
+ ap.add_argument("npz")
53
+ ap.add_argument("--receipt", required=True, help="generation receipt (.log JSON with output_sha256)")
54
+ ap.add_argument("--held", default="ye2026_sepsis")
55
+ ap.add_argument("--split", default="hoL_ye2026_sepsis")
56
+ ap.add_argument("--condition", default=None, help="local copy of the arm's condition NPZ when the receipt's path "
57
+ "is not on this host (bulk-broadcast baseline); passed to score_ft.py as --condition ARM=PATH")
58
+ a = ap.parse_args()
59
+ raw = sys.stdin.buffer.read() if a.npz == "-" else Path(a.npz).read_bytes()
60
+ sha = hashlib.sha256(raw).hexdigest()
61
+ rec = json.loads(Path(a.receipt).read_text())
62
+ if rec.get("output_sha256") != sha:
63
+ raise SystemExit(f"{a.arm}: NPZ sha {sha[:12]} != receipt {str(rec.get('output_sha256'))[:12]}")
64
+ d = dict(np.load(io.BytesIO(raw), allow_pickle=False))
65
+ del raw
66
+ ids = d["gene_ids"].astype(str)
67
+ m = never_trained_mask(a.split, a.held, ids)
68
+ before = float(d["generated_counts"][:, m].sum() / d["generated_counts"].sum())
69
+ d["generated_counts"][:, m] = 0
70
+ out = P / f"generated_masked/{a.held}/{a.split}/{a.arm}.npz"
71
+ out.parent.mkdir(parents=True, exist_ok=True)
72
+ np.savez(out, **d)
73
+ osha = hashlib.sha256(out.read_bytes()).hexdigest()
74
+ derived = {"output_sha256": osha, "derived_from": a.npz if a.npz != "-" else a.receipt.replace(".log", ".npz"),
75
+ "source_sha256": sha, "source_receipt": a.receipt, "masked_rule": "panel genes measured in the held-out "
76
+ "cohort but in none of the split's training cohorts set to 0 in generated_counts",
77
+ "masked_gene_ids": ids[m].tolist(), "n_masked": int(m.sum()),
78
+ "generated_umi_share_masked_before": before, "written": datetime.now().isoformat(timespec="seconds"),
79
+ **{k: rec.get(k) for k in ("condition_npz", "condition_sha256", "checkpoint", "checkpoint_sha256", "seed",
80
+ "steps", "support_readout", "weights") if k in rec}}
81
+ out.with_suffix(".log").write_text(json.dumps(derived, indent=1) + "\n")
82
+ cargs = subprocess.run(["bash", str(SRC / "tools/contrast_args.sh"), a.held], capture_output=True,
83
+ text=True).stdout.split()
84
+ so = P / f"scores_masked/{a.held}/{a.arm}"
85
+ so.mkdir(parents=True, exist_ok=True)
86
+ r = subprocess.run([PY, str(SRC / "tools/score_ft.py"), "--dataset", a.held, "--threads", "8", "--donors",
87
+ str(P / f"data/{a.held}/usable_samples.txt"), "--arm", f"{a.arm}={out}", *cargs, "--out", str(so),
88
+ *(["--condition", f"{a.arm}={a.condition}"] if a.condition else [])],
89
+ capture_output=True, text=True)
90
+ (so / "score.log").write_text(r.stdout + r.stderr)
91
+ out.unlink()
92
+ print(json.dumps({"arm": a.arm, "masked_genes": int(m.sum()), "generated_umi_share_masked_before": round(before, 4),
93
+ "score_rc": r.returncode}))
94
+ return r.returncode
95
+
96
+
97
+ if __name__ == "__main__":
98
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/run_loco_queue.sh ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Cross-cohort (LOCO) queue: the same queue file runs on server_1 and server_2; each line is one unit that a host
3
+ # claims before it starts (atomic mkdir in claims/ on server_1, so a unit never runs on both hosts).
4
+ # zs|COHORT|K base model on data/<cohort>/test_raw_K<K>.npz -> generated/<cohort>/zs_K<K>.npz
5
+ # xcal|SPLIT|K base model on splits/<split>/test_xcal_K<K>.npz -> generated/<held>/<split>/xcal_K<K>.npz
6
+ # loco|SPLIT|K|TAG|MODE|LR[|extra] fine-tune (ft_sdd_multi.py) -> runs/<split>/K<K>/<TAG>/, then sample the held-out
7
+ # cohort's test_raw_K<K>.npz -> generated/<held>/<split>/K<K>_<TAG>.npz; with --block
8
+ # (step saturation) every milestone checkpoint -> .../K<K>_<TAG>_s<step>.npz
9
+ # Every GPU step goes through ml-run (ml.slice, shared GPU lock) after the thermal gate and gpu_usable.sh (shared with
10
+ # the scSemiProfiler queue: when only this user's ml.slice job holds the GPU, ml-run waits on the lock, so the two
11
+ # queues alternate and never overlap). Sampling: the sampler call of utility_studies sample_queue.sh (DDIM 50,
12
+ # Bernoulli read-out, seed 20260927, 1,500 cells per bulk), behind this queue's gate.
13
+ # On server_2 every finished unit is copied back to the same absolute paths on server_1 (sha-checked).
14
+ # A host claims a unit only after its GPU gate passes. A failed unit is marked FAILED in its claim and not retried;
15
+ # two failures in a row stop the queue.
16
+ # env: QUEUE (required), REVERSE (0; 1 = walk the queue from the end), MAX_WAIT_H (480)
17
+ set -uo pipefail
18
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
19
+ export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
20
+ M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
21
+ P=$M8/plans/paired_crosscohort_20261002
22
+ SQ=$M8/plans/utility_studies_final6k_20260925/tools/sample_queue.sh
23
+ BASE_CKPT=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
24
+ BASE_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
25
+ SEED=20260927
26
+ COORD=spark-fa6b
27
+ case "$(hostname -s)" in
28
+ spark-fa6b) HOST=server_1; PY=/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python ;;
29
+ spark-0110) HOST=server_2; PY=/home/sj_server_2/miniforge3/envs/b2sc-infer/bin/python ;;
30
+ *) echo "unknown host" >&2; exit 2 ;;
31
+ esac
32
+ QUEUE="${QUEUE:?QUEUE}"; REVERSE="${REVERSE:-0}"; MAX_WAIT_H="${MAX_WAIT_H:-480}"
33
+ mkdir -p "$P/logs"
34
+ LOG=$P/logs/loco_queue_$(basename "$QUEUE" .txt)_${HOST}_$(date +%Y%m%dT%H%M%S).log
35
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
36
+ start=$(date +%s)
37
+
38
+ on_coord() { if [[ $HOST == server_1 ]]; then bash -c "$1"; else ssh -n "$COORD" "$1"; fi; }
39
+ claim() { # claim KEY -> 0 if this host now owns the unit
40
+ on_coord "mkdir -p '$P/claims' && mkdir '$P/claims/$1' 2>/dev/null && echo '$HOST $(date -Is)' > '$P/claims/$1/OWNER'"
41
+ }
42
+ mark() { on_coord "echo '$HOST $(date -Is) ${3:-}' > '$P/claims/$1/$2'"; }
43
+ usable_or_own() {
44
+ # gpu_usable.sh (free GPU, or a foreign process idle at <= 5 %), or else: every compute process on the GPU is this
45
+ # user's own job inside ml.slice (the scSemiProfiler queue holding the shared lock). In that case ml-run below blocks
46
+ # on the shared lock and the two queues take turns, never overlapping. Anything else (another user's process at
47
+ # work, memory below 32 GiB, guard inactive) waits.
48
+ local r; r=$(bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh" 2>/dev/null) && { echo "$r"; return 0; }
49
+ systemctl --user is-active --quiet ml-memory-guard.service || return 1
50
+ local avail; avail=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo); (( avail >= 32 )) || return 1
51
+ local pids p; pids=$(nvidia-smi --query-compute-apps=pid --format=csv,noheader | tr -d ' ')
52
+ [[ -n $pids ]] || return 1
53
+ for p in $pids; do
54
+ [[ "$(stat -c %U "/proc/$p" 2>/dev/null)" == "$(id -un)" ]] && grep -q '/ml.slice/' "/proc/$p/cgroup" 2>/dev/null || return 1
55
+ done
56
+ echo "own ml.slice job on the GPU; waiting on the shared lock"
57
+ }
58
+ gate() {
59
+ until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh") && usable=$(usable_or_own); do
60
+ (( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
61
+ sleep 60
62
+ done
63
+ echo "$verdict; GPU $usable"
64
+ }
65
+ copy_back() { # server_2 -> server_1, same absolute paths; NPZ checked against its receipt's sha256
66
+ [[ $HOST == server_1 ]] && return 0
67
+ local f
68
+ for f in "$@"; do
69
+ [[ -e $f ]] || continue
70
+ ssh -n "$COORD" "mkdir -p '$(dirname "$f")'" && rsync -a "$f" "$COORD:$(dirname "$f")/" || return 1
71
+ done
72
+ return 0
73
+ }
74
+ yield_gpu() { # after each GPU step: if another of this user's GPU queues is active, pause longer than its 120 s gate
75
+ # poll so that it gets the next turn on the shared lock (the queues alternate instead of one starving the other)
76
+ local u
77
+ for u in $(systemctl --user list-units --type=service --state=active --no-legend 2>/dev/null | awk '{print $1}' \
78
+ | grep -E '^scsemi-queue'); do
79
+ log "yield: $u is active; pausing 150 s"; sleep 150; return 0
80
+ done
81
+ }
82
+ sample() { # sample TAG CKPT CKPT_SHA COND OUT -- the sampler call of sample_queue.sh ($SQ), with this queue's gate
83
+ local tag=$1 ck=$2 sha=$3 cond=$4 out=$5 rec=${5%.npz}.log err=${5%.npz}.err
84
+ if [[ -s $rec && ( -s $out || -e ${out%.npz}.moved ) ]]; then log "$tag already sampled; skipped"; return 0; fi
85
+ [[ -s $cond ]] || { log "WARN: $tag condition missing: $cond"; return 1; }
86
+ [[ "$(sha256sum "$ck" | cut -d' ' -f1)" == "$sha" ]] || { log "WARN: $tag checkpoint sha differs"; return 1; }
87
+ mkdir -p "$(dirname "$out")"
88
+ log "--- sample $tag seed=$SEED ($(gate))"
89
+ if "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
90
+ PYTHONPATH="$M8/src" OMP_NUM_THREADS=4 "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
91
+ --checkpoint "$ck" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 \
92
+ --steps 50 --seed "$SEED" --device cuda --conditioner-source embedded \
93
+ --active-logit-threshold 0.0 --support-readout bernoulli > "$rec" 2> "$err"; then
94
+ log "$tag sampled: $(python3 -c "import json;d=json.load(open('$rec'));print('zero_frac %.4f' % d.get('generated_zero_fraction',-1), d.get('output_sha256','')[:12])" 2>/dev/null)"
95
+ else
96
+ log "WARN: $tag sampling failed (see $err)"; rm -f "$rec"; yield_gpu; return 1
97
+ fi
98
+ yield_gpu
99
+ # (2026-10-05) score_pending.sh may score and offload the NPZ to server_2 during the yield pause; a .moved marker
100
+ # (written only after the remote sha matched) counts as present
101
+ [[ -s $rec && ( -s $out || -e ${out%.npz}.moved ) ]]
102
+ }
103
+ held_of() { python3 -c "import json;print(json.load(open('$P/splits/$1.json'))['held_out'])"; }
104
+
105
+ mapfile -t LINES < <(grep -v -e '^\s*$' -e '^#' "$QUEUE")
106
+ [[ $REVERSE == 1 ]] && mapfile -t LINES < <(printf '%s\n' "${LINES[@]}" | tac)
107
+ log "queue=$QUEUE host=$HOST units=${#LINES[@]} reverse=$REVERSE py=$PY"
108
+ fails=0; n_done=0
109
+ for line in "${LINES[@]}"; do
110
+ IFS='|' read -r kind a1 a2 a3 a4 a5 extra <<< "$line"
111
+ case $kind in
112
+ zs) key="zs_${a1}_K${a2}" ;;
113
+ xcal) key="xcal_${a1}_K${a2}" ;;
114
+ loco) key="loco_${a1}_K${a2}_${a3}" ;;
115
+ *) log "WARN: unknown line: $line"; continue ;;
116
+ esac
117
+ # wait for a usable GPU before claiming, so a host that cannot run now never holds a unit the other host could run
118
+ on_coord "test -d '$P/claims/$key'" && continue
119
+ gate > /dev/null
120
+ claim "$key" || continue
121
+ unit_t0=$(date +%s)
122
+ log "=== $key claimed"
123
+ ok=0
124
+ if [[ $kind == zs ]]; then
125
+ out=$P/generated/$a1/zs_K$a2.npz
126
+ sample "$key" "$BASE_CKPT" "$BASE_SHA" "$P/data/$a1/test_raw_K$a2.npz" "$out" && ok=1
127
+ files=("$out" "${out%.npz}.log" "${out%.npz}.err")
128
+ elif [[ $kind == xcal ]]; then
129
+ held=$(held_of "$a1"); out=$P/generated/$held/$a1/xcal_K$a2.npz
130
+ sample "$key" "$BASE_CKPT" "$BASE_SHA" "$P/splits/$a1/test_xcal_K$a2.npz" "$out" && ok=1
131
+ files=("$out" "${out%.npz}.log" "${out%.npz}.err")
132
+ else
133
+ split=$a1 K=$a2 tag=$a3 mode=$a4 lr=$a5
134
+ held=$(held_of "$split"); run=$P/runs/$split/K$K/$tag; out=$P/generated/$held/$split/K${K}_$tag.npz
135
+ mkdir -p "$run"
136
+ if [[ ! -s $run/RUN.json ]]; then
137
+ log "--- train $split K=$K $tag mode=$mode lr=$lr ($(gate))"
138
+ # shellcheck disable=SC2086
139
+ "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
140
+ OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$P/tools/ft_sdd_multi.py" --checkpoint "$BASE_CKPT" \
141
+ --checkpoint-sha "$BASE_SHA" --split "$P/splits/$split.json" --k "$K" --mode "$mode" --lr "$lr" \
142
+ --out-dir "$run" ${extra//|/ } >> "$run/train.log" 2>&1
143
+ yield_gpu
144
+ fi
145
+ files=("$run/RUN.json" "$run/history.json" "$run/train.log" "$run/checkpoint_ft.pt")
146
+ if [[ -s $run/RUN.json ]]; then
147
+ sha=$(python3 -c "import json;print(json.load(open('$run/RUN.json'))['checkpoint_sha256'])")
148
+ log "train $key: $(python3 -c "import json;d=json.load(open('$run/RUN.json'));print('selected step',d['selected_step'],'of',d['steps_run'],'stop',d.get('stop_reason'),'inner-val %.5f (pre %.5f)'%(d['selected_inner_val_loss'],d['pretrained_inner_val_loss']),'%.0f s'%d['wall_seconds'])")"
149
+ ms=$(python3 -c "import json;d=json.load(open('$run/RUN.json'));print(' '.join('%d:%s' % (m['milestone_step'], m['checkpoint_sha256']) for m in d.get('milestones') or []))")
150
+ if [[ -n $ms ]]; then
151
+ # step-saturation runs: sample every milestone checkpoint (best-so-far at each block end) -> K<K>_<tag>_s<step>
152
+ ok=1; files+=("$run/milestones.json")
153
+ for x in $ms; do
154
+ st=${x%%:*}; msha=${x#*:}; out=$P/generated/$held/$split/K${K}_${tag}_s${st}.npz
155
+ sample "${key}_s${st}" "$run/checkpoint_ft_s${st}.pt" "$msha" "$P/data/$held/test_raw_K$K.npz" "$out" || ok=0
156
+ files+=("$run/checkpoint_ft_s${st}.pt" "$out" "${out%.npz}.log" "${out%.npz}.err")
157
+ done
158
+ else
159
+ sample "$key" "$run/checkpoint_ft.pt" "$sha" "$P/data/$held/test_raw_K$K.npz" "$out" && ok=1
160
+ files+=("$out" "${out%.npz}.log" "${out%.npz}.err")
161
+ fi
162
+ else
163
+ log "WARN: train $key failed (see $run/train.log)"
164
+ fi
165
+ fi
166
+ if (( ok )); then
167
+ copy_back "${files[@]}" || { log "WARN: $key copy to server_1 failed; outputs kept on $HOST"; ok=0; }
168
+ fi
169
+ if (( ok )); then
170
+ mark "$key" DONE "$(python3 -c "import json;print(json.load(open('${out%.npz}.log'))['output_sha256'])")"
171
+ log "=== $key done"; fails=0; n_done=$((n_done+1))
172
+ else
173
+ mark "$key" FAILED; log "=== $key FAILED"; fails=$((fails+1))
174
+ # host policy: after a memory-guard stop, inspect before any further GPU work -> never move on to the next unit
175
+ if journalctl -t ml-memory-guard --since "@$unit_t0" --no-pager 2>/dev/null | grep -q "stopping ml.slice"; then
176
+ log "ABORT: the memory guard stopped ml.slice during $key; queue stopped for inspection (no further units)"
177
+ exit 1
178
+ fi
179
+ (( fails >= 2 )) && { log "ABORT: two failed units in a row"; exit 1; }
180
+ fi
181
+ done
182
+ log "queue finished on $HOST: units done here=$n_done"
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/table_masked.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Table of the held-out arms scored after zeroing never-trained genes (scores_masked/<held>/<arm>/), next to the
3
+ unmasked scores (scores/<held>/<arm>/). usage: table_masked.py [HELD] -> prints; writes scores_masked/<held>/table.csv"""
4
+ import glob, json, os, sys
5
+ import pandas as pd
6
+ P = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
7
+ held = sys.argv[1] if len(sys.argv) > 1 else "ye2026_sepsis"
8
+ rows = []
9
+ for kind, root in (("masked", f"{P}/scores_masked/{held}"), ("unmasked", f"{P}/scores/{held}")):
10
+ for d in sorted(glob.glob(f"{root}/*/summary.json")):
11
+ arm = d.split("/")[-2]
12
+ if kind == "unmasked" and not os.path.exists(f"{P}/scores_masked/{held}/{arm}/summary.json"):
13
+ continue
14
+ s = json.load(open(d)); h = s["headline"][list(s["headline"])[0]]
15
+ c = pd.read_csv(os.path.dirname(d) + "/contrast.csv")
16
+ c = c[(c.statistic == "mean_cp10k") & c.celltype.isin(["T cell", "B cell", "Monocyte", "NK cell"])]
17
+ rows.append({"arm": arm, "scores": kind, "comp_l1": h["comp_l1"], "precision": h["precision"],
18
+ "coverage": h["coverage"], "coverage_dm": h["coverage_dm"], "pb_r": h["pb_r_median"],
19
+ "pb_top1": h["pb_top1"], "mono_pct": h["mono_pct_gen"], "median_umi": h["median_umi_gen"],
20
+ "logfc_r": h["contrast_mean_cp10k_r_gen"], "partial_r": c.partial_r_generated_given_broadcast.mean(),
21
+ "deg_top50_4type": h.get("deg_top50_sum_4type")})
22
+ t = pd.DataFrame(rows).sort_values(["scores", "arm"])
23
+ t.to_csv(f"{P}/scores_masked/{held}/table.csv", index=False)
24
+ with pd.option_context("display.width", 250, "display.max_columns", 20):
25
+ print(t.round(3).to_string(index=False))
26
+ h = s["headline"][list(s["headline"])[0]]
27
+ print("observed: mono %.1f%%, median UMI %.0f, broadcast logFC r %.3f, comp L1 LOO null %.3f" % (
28
+ h["mono_pct_obs"], h["median_umi_obs"], h["contrast_mean_cp10k_r_broadcast"], h["comp_l1_obs_loo_null"]))