junidude14 commited on
Commit
03f10e5
·
verified ·
1 Parent(s): 348488b

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261005T121346Z-scsemi-cv-budget-interim/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/restart_cvb_s1_20261004.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One-off (2026-10-04, user decision: use server_2): stop scsemi-queue-cvb-s1 at a clean point (no scSemiProfiler GPU
3
+ # step and no scsemi-* CPU unit running) and restart it on queues/server1_cv_budget_20261004_no_giroux_imperial.txt with
4
+ # the original settings (MAX_WAIT_H=480, MIN_FREE_GIB=80). The runner resumes split by split from its receipts.
5
+ set -uo pipefail
6
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
7
+ S=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi
8
+ log() { echo "$(date -Is) $*"; }
9
+ busy() {
10
+ local u
11
+ for u in $(systemctl --user list-units --type=service --state=running --no-legend | awk '{print $1}'); do
12
+ case $u in
13
+ mljob*) systemctl --user show "$u" -p ExecStart --value | grep -q 'run_scsemi' && return 0 ;;
14
+ scsemi-queue*) ;;
15
+ scsemi-*) return 0 ;;
16
+ esac
17
+ done
18
+ return 1
19
+ }
20
+ log "waiting for the current scSemiProfiler step to end"
21
+ while busy; do sleep 2; done
22
+ systemctl --user stop scsemi-queue-cvb-s1
23
+ log "scsemi-queue-cvb-s1 stopped; last queue log lines:"
24
+ grep -v '^unit' "$(ls -t "$S"/logs/queue_server1_cv_budget*.log | head -1)" | tail -2
25
+ sleep 5
26
+ busy && log "WARN: a step started just before the stop; it finishes on its own (its receipt is written)"
27
+ systemctl --user reset-failed scsemi-queue-cvb-s1 2>/dev/null
28
+ systemd-run --user --unit=scsemi-queue-cvb-s1 --setenv=QUEUE="$S/queues/server1_cv_budget_20261004_no_giroux_imperial.txt" \
29
+ --setenv=MAX_WAIT_H=480 --setenv=MIN_FREE_GIB=80 /bin/bash "$S/tools/run_queue_scsemi.sh"
30
+ log "scsemi-queue-cvb-s1 restarted on the server_1 queue without Giroux / Imperial"
paper-releases/pbisc-diffusion/updates/20261005T121346Z-scsemi-cv-budget-interim/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/restart_queue_clean.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Stop a scSemiProfiler queue unit at a clean point (no scSemiProfiler GPU step and no scsemi-* CPU unit running) and
3
+ # start it again with QUEUE / MAX_WAIT_H=480 / MIN_FREE_GIB=80, so it runs the current tools/run_queue_scsemi.sh.
4
+ # The runner resumes split by split from its receipts. Run it under a unit name that does not start with "scsemi-".
5
+ # usage: restart_queue_clean.sh UNIT QUEUE_FILE (2026-10-04: pick up the memory-guard abort in the runner)
6
+ set -uo pipefail
7
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
8
+ S=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi
9
+ unit=$1; queue=$2
10
+ [[ -f $queue ]] || { echo "no queue file $queue" >&2; exit 2; }
11
+ log() { echo "$(date -Is) $*"; }
12
+ busy() {
13
+ local u
14
+ for u in $(systemctl --user list-units --type=service --state=running --no-legend | awk '{print $1}'); do
15
+ case $u in
16
+ mljob*) systemctl --user show "$u" -p ExecStart --value | grep -q 'run_scsemi' && return 0 ;;
17
+ scsemi-queue*) ;;
18
+ scsemi-*) return 0 ;;
19
+ esac
20
+ done
21
+ return 1
22
+ }
23
+ log "waiting for the current scSemiProfiler step of $unit to end"
24
+ while busy; do sleep 2; done
25
+ systemctl --user stop "$unit"
26
+ log "$unit stopped"
27
+ sleep 5
28
+ busy && log "WARN: a step started just before the stop; it finishes on its own (its receipt is written)"
29
+ systemctl --user reset-failed "$unit" 2>/dev/null
30
+ systemd-run --user --unit="$unit" --setenv=QUEUE="$queue" --setenv=MAX_WAIT_H=480 --setenv=MIN_FREE_GIB=80 \
31
+ /bin/bash "$S/tools/run_queue_scsemi.sh"
32
+ log "$unit restarted on $queue ($(sha256sum "$S/tools/run_queue_scsemi.sh" | cut -c1-12))"
paper-releases/pbisc-diffusion/updates/20261005T121346Z-scsemi-cv-budget-interim/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_queue_scsemi.sh ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ guard_abort() { # host policy (2026-10-04): after a memory-guard stop of ml.slice, inspect before any further step
57
+ if journalctl -t ml-memory-guard --since "@$start" --no-pager 2>/dev/null | grep -q "stopping ml.slice"; then
58
+ log "ABORT: the memory guard stopped ml.slice since this queue started; no further steps (inspect, then restart)"
59
+ exit 1
60
+ fi
61
+ }
62
+ gate() {
63
+ local verdict usable
64
+ guard_abort
65
+ if [[ $SMOKE_CPU == 1 ]]; then echo "smoke: CPU only, no GPU gate"; return; fi
66
+ until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh") \
67
+ && usable=$(bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh" 2>/dev/null); do
68
+ (( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
69
+ sleep 120
70
+ done
71
+ echo "$verdict; GPU $usable"
72
+ }
73
+ cpu() { # cpu NAME THREADS MEMMAX CMD... (waits for the memory floor instead of failing on it)
74
+ local mem=$3
75
+ guard_abort
76
+ until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 32 + mem )); do
77
+ (( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: memory floor not met within ${MAX_WAIT_H} h"; exit 1; }
78
+ sleep 120
79
+ done
80
+ ALLOW_USER_SITE=${US:-$USERSITE} bash "$S/tools/cpu_unit.sh" "$@" >> "$LOG" 2>&1 < /dev/null
81
+ }
82
+ st() { python3 -c "import json,sys;print(json.load(open(sys.argv[1]))[sys.argv[2]])" "$1/status.json" "$2" 2>/dev/null; }
83
+ disk() { # disk NOTE : wait until MIN_FREE_GIB GiB are free on $S (no-op when MIN_FREE_GIB is 0)
84
+ (( MIN_FREE_GIB > 0 )) || return 0
85
+ local free warned=0
86
+ while free=$(df -B1G --output=avail "$S" | tail -1 | tr -dc '0-9'); (( free < MIN_FREE_GIB )); do
87
+ (( warned )) || { log "disk: ${free} GiB free < MIN_FREE_GIB ${MIN_FREE_GIB} before $1; waiting"; warned=1; }
88
+ (( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: disk below ${MIN_FREE_GIB} GiB within ${MAX_WAIT_H} h"; exit 1; }
89
+ sleep 300
90
+ done
91
+ (( warned )) && log "disk: ${free} GiB free; continuing"
92
+ return 0
93
+ }
94
+ gpu() { # gpu WORK PHASE EXTRA...
95
+ local W=$1 phase=$2; shift 2
96
+ if [[ $SMOKE_CPU == 1 ]]; then # queue-logic test: same wrapper, CPU, reduced epochs, never ml-run
97
+ cpu "smk-$phase" 4 8 "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase "$phase" --device cpu --smoke --threads 4 "$@"
98
+ return
99
+ fi
100
+ local ns=
101
+ [[ $USERSITE == 1 ]] || ns=PYTHONNOUSERSITE=1
102
+ "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
103
+ OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4 PYTHONUNBUFFERED=1 PYTHONDONTWRITEBYTECODE=1 $ns \
104
+ "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase "$phase" --device cuda:0 --threads 4 "$@" \
105
+ >> "$W/gpu.log" 2>&1 < /dev/null
106
+ }
107
+ n_fail=0
108
+ fail() { n_fail=$((n_fail+1)); log "WARN: $*"; }
109
+ log "queue $QUEUE on $(hostname -s); python $PY; chunks reps=$CHUNK_REPS targets=$CHUNK_TARGETS; score=$SCORE; smoke_cpu=$SMOKE_CPU"
110
+ while IFS= read -r line; do
111
+ guard_abort
112
+ [[ -z "${line// }" || "$line" == \#* ]] && continue
113
+ IFS='|' read -r mode ds j opts extra <<< "$line"
114
+ SMK=()
115
+ case $mode in
116
+ fewshot) W=$S/work/$ds/fewshot_n5/draw$j; OUT=$T/generated/$ds/fewshot_n5/draw$j/scsemi5__raw.npz; ARM=scsemi5
117
+ SC=$T/scores/$ds/fewshot_n5/draw${j}_scsemi5; DON=$T/data/$ds/fewshot_n5/draw$j/test_samples.txt
118
+ imode=fewshot; sflag=(--draw "$j") ;;
119
+ cv) W=$S/work/$ds/cv/fold$j; OUT=$T/generated/$ds/fold$j/scsemi__raw.npz; ARM=scsemi
120
+ SC=$T/scores/$ds/fold${j}_scsemi; DON=; imode=cv; sflag=(--fold "$j") ;;
121
+ budget) [[ $extra =~ ^[0-9]+$ ]] || { fail "budget line needs N in field 5: $line"; continue; }
122
+ W=$S/work/$ds/budget/fold$j/n$extra; OUT=$T/generated/$ds/fold$j/scsemi_n${extra}__raw.npz
123
+ ARM=scsemi_n$extra; SC=; DON=; imode=budget; sflag=(--fold "$j" --n "$extra") ;;
124
+ offload) # offload|DATASET|cv : after the budget lines that reuse them, move the CV runs' models + rep_sc.h5ad to
125
+ # spark-0110 (tools/offload_work.sh; same absolute paths, sha-verified). Refused while any budget output
126
+ # of the dataset is missing or unvalidated (their link phase reads the CV checkpoints).
127
+ [[ $SMOKE_CPU != 1 && $j == cv ]] || { fail "offload line not run: $line"; continue; }
128
+ pend=0; args=()
129
+ for k in 0 1 2 3 4; do
130
+ for b in "$T"/generated/"$ds"/fold$k/scsemi_n*__raw.npz; do
131
+ [[ -e $b ]] || continue
132
+ 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
133
+ done
134
+ for n in 5 10 20 40; do
135
+ [[ -d $S/work/$ds/budget/fold$k/n$n ]] && [[ ! -s $T/generated/$ds/fold$k/scsemi_n${n}__raw.validation.json ]] && pend=1
136
+ done
137
+ args+=("$T/generated/$ds/fold$k/scsemi__raw.validation.json" "$S/work/$ds/cv/fold$k")
138
+ done
139
+ (( pend )) && { fail "$ds: a budget split is unfinished; CV runs kept for its link phase ($line)"; continue; }
140
+ log "$ds: offloading the CV runs' models and inputs to spark-0110"
141
+ bash "$S/tools/offload_work.sh" "${args[@]}" >> "$LOG" 2>&1 || fail "$ds: offload incomplete (local files kept where unverified)"
142
+ continue ;;
143
+ smoke) [[ $SMOKE_CPU == 1 ]] || { fail "smoke line needs SMOKE_CPU=1: $line"; continue; }
144
+ # smoke|DS|SPLIT|OPTS|T1,T2[|MODE|N|REP_IDS]: MODE fewshot (default, as before), cv or budget
145
+ IFS='|' read -r stg smode sn sreps <<< "$extra"
146
+ smode=${smode:-fewshot}; SMK=(--smoke)
147
+ if [[ $smode == fewshot ]]; then
148
+ W=$S/smoke/queue/${ds}_draw$j; OUT=$W/generated/scsemi5__raw.npz; ARM=scsemi5
149
+ sflag=(--draw "$j" --smoke-reps 2 --smoke-cells 300 --smoke-targets "$stg")
150
+ else
151
+ W=$S/smoke/queue/${ds}_${smode}$j${sn:+_n$sn}; OUT=$W/generated/scsemi__raw.npz; ARM=scsemi
152
+ sflag=(--fold "$j" ${sn:+--n "$sn"} --smoke-cells 300 --smoke-targets "$stg")
153
+ if [[ -n $sreps ]]; then sflag+=(--smoke-rep-ids "$sreps"); else sflag+=(--smoke-reps 2); fi
154
+ fi
155
+ SC=$W/score; DON=$W/targets.txt; imode=$smode
156
+ mkdir -p "$W"; tr ',' '\n' <<< "$stg" > "$DON" ;;
157
+ *) fail "unknown line: $line"; continue ;;
158
+ esac
159
+ [[ $SMOKE_CPU == 1 && $mode != smoke ]] && { fail "SMOKE_CPU=1 runs smoke lines only: $line"; continue; }
160
+ tag="$ds/$mode$j"; uid="${ds:0:3}-$mode$j"
161
+ [[ $mode == budget ]] && { tag="$ds/budget${j}_n$extra"; uid="${ds:0:3}-b${j}n$extra"; }
162
+ WARGS=(); REUSE=0
163
+ [[ ",$opts," == *",lean_hvset,"* ]] && WARGS+=(--lean-hvset)
164
+ if [[ ",$opts," == *",reuse_cv,"* ]]; then
165
+ [[ $mode == budget || ( $mode == smoke && $imode == budget ) ]] || { fail "reuse_cv is for budget lines: $line"; continue; }
166
+ if [[ $mode == smoke ]]; then WARGS+=(--reuse-from "$S/smoke/queue/${ds}_cv$j"); else WARGS+=(--reuse-from "$S/work/$ds/cv/fold$j"); fi
167
+ REUSE=1
168
+ fi
169
+ mkdir -p "$W"
170
+ exec 9>"$W/.split.lock" # re-opening fd 9 releases the previous split's lock
171
+ flock -w $((MAX_WAIT_H * 3600)) 9 || { fail "$tag: split lock held by another queue for ${MAX_WAIT_H} h"; continue; }
172
+ VAL=${OUT%.npz}.validation.json
173
+ if [[ -s $VAL ]] && python3 -c "import json,sys;sys.exit(0 if json.load(open(sys.argv[1]))['passed'] else 1)" "$VAL"; then
174
+ log "$tag: exported + validated already; skipped"
175
+ else
176
+ mkdir -p "$W"
177
+ if [[ ! -s $W/inputs/inputs_manifest.json ]]; then
178
+ disk "$tag input build"
179
+ log "$tag: building inputs (CPU unit)"
180
+ cpu "in-$uid" 4 12 "$PY" -u "$S/tools/prepare_draw_inputs.py" --dataset "$ds" --mode "$imode" "${sflag[@]}" --work "$W" \
181
+ || { fail "$tag: input build failed"; continue; }
182
+ fi
183
+ if [[ ! -s $W/prepared.json ]]; then
184
+ disk "$tag prepare"
185
+ log "$tag: upstream prepare (initsetup + assignment + scprocess, CPU unit)${WARGS[*]:+ [${WARGS[*]}]}"
186
+ cpu "prep-$uid" 6 "$PREP_MEM" "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase prepare --device cpu --threads 6 "${SMK[@]}" "${WARGS[@]}" \
187
+ || { fail "$tag: prepare failed (see $W/events.jsonl)"; continue; }
188
+ fi
189
+ if [[ $PREP_ONLY == 1 ]]; then log "$tag: CPU-prepared (PREP_ONLY; GPU steps left to the GPU queue)"; continue; fi
190
+ if (( REUSE )) && [[ "$(st "$W" pretrain_complete)" != True ]]; then
191
+ log "$tag: linking the source run's pretrain checkpoints (CPU unit)"
192
+ cpu "lnk-$uid" 2 4 "$PY" -u "$S/tools/run_scsemi_paired.py" --work "$W" --phase link --device cpu --threads 2 "${SMK[@]}" "${WARGS[@]}" \
193
+ || { fail "$tag: link failed (see $W/events.jsonl)"; continue; }
194
+ log "$tag: pretrain checkpoints after link: $(st "$W" reps_pretrained)/$(st "$W" n_reps)"
195
+ if [[ "$(st "$W" pretrain_complete)" != True && $REUSE_ALLOW_PRETRAIN != 1 ]]; then
196
+ fail "$tag: source run lacks pretrain checkpoints; REUSE_ALLOW_PRETRAIN=1 pretrains them with the source seeds"; continue
197
+ fi
198
+ fi
199
+ ok=1
200
+ while [[ "$(st "$W" pretrain_complete)" != True ]]; do
201
+ before=$(st "$W" reps_pretrained)
202
+ g=$(gate) || { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
203
+ log "$tag: pretrain ${before}/$(st "$W" n_reps) reps; next $CHUNK_REPS ($g)"
204
+ gpu "$W" pretrain --max-reps "$CHUNK_REPS" "${WARGS[@]}" || { fail "$tag: pretrain step failed (see $W/gpu.log, $W/events.jsonl)"; ok=0; break; }
205
+ [[ "$(st "$W" reps_pretrained)" != "$before" ]] || { fail "$tag: pretrain made no progress"; ok=0; break; }
206
+ done
207
+ (( ok )) || continue
208
+ while [[ "$(st "$W" infer_complete)" != True ]]; do
209
+ before=$(st "$W" targets_done)
210
+ g=$(gate) || { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
211
+ log "$tag: infer ${before}/$(st "$W" n_targets) targets; next $CHUNK_TARGETS ($g)"
212
+ gpu "$W" infer --max-targets "$CHUNK_TARGETS" "${WARGS[@]}" || { fail "$tag: infer step failed (see $W/gpu.log, $W/events.jsonl)"; ok=0; break; }
213
+ [[ "$(st "$W" targets_done)" != "$before" ]] || { fail "$tag: infer made no progress"; ok=0; break; }
214
+ done
215
+ (( ok )) || continue
216
+ if [[ ! -s $OUT ]]; then
217
+ cpu "exp-$uid" 2 16 "$PY" -u "$S/tools/export_npz.py" --work "$W" --out "$OUT" || { fail "$tag: export failed"; continue; }
218
+ fi
219
+ cpu "val-$uid" 2 16 "$PY" -u "$S/tools/validate_export.py" --work "$W" --npz "$OUT" || { fail "$tag: validation failed ($VAL)"; continue; }
220
+ 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")"
221
+ if [[ ",$opts," == *",clean_sample_sc,"* || ",$opts," == *",clean_prepared,"* ]]; then
222
+ rm -f "$W"/scsemi_project/sample_sc/*.h5ad && log "$tag: removed sample_sc/*.h5ad (sha256 kept in prepared.json)"
223
+ fi
224
+ if [[ ",$opts," == *",clean_prepared,"* ]]; then
225
+ rm -f "$W"/scsemi_project/geneset_scores/*.npy && log "$tag: removed geneset_scores/*.npy (sha256 kept in prepared.json)"
226
+ fi
227
+ if [[ ",$opts," == *",offload,"* && $SMOKE_CPU != 1 ]]; then
228
+ bash "$S/tools/offload_work.sh" "$VAL" "$W" >> "$LOG" 2>&1 && log "$tag: models + rep_sc.h5ad moved to spark-0110" \
229
+ || fail "$tag: offload incomplete (local files kept where unverified)"
230
+ fi
231
+ fi
232
+ if [[ $SCORE == 1 && $PREP_ONLY != 1 && $mode != cv && $mode != budget && -s $VAL && ! -s $SC/summary.json ]]; then
233
+ read -r -a cargs <<< "$(bash "$T/tools/contrast_args.sh" "$ds")"
234
+ log "$tag: scoring arm $ARM -> $SC"
235
+ mkdir -p "$SC"
236
+ US=0 cpu "sc-$uid" 6 16 "$SPY" -u "$T/tools/score_ft.py" --dataset "$ds" --out "$SC" --threads 6 \
237
+ --donors "$DON" "${cargs[@]}" --arm "$ARM=$OUT" || fail "$tag: scoring failed"
238
+ fi
239
+ done < "$QUEUE"
240
+ exec 9>&-
241
+ log "queue finished: failed=$n_fail"
242
+ (( n_fail == 0 ))
paper-releases/pbisc-diffusion/updates/20261005T121346Z-scsemi-cv-budget-interim/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/summarize_cv_budget.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """scSemiProfiler 5-fold CV (A) and equal pair budget (B) vs LoRA, from the scored calls (CPU only; reruns as more
3
+ cohorts finish).
4
+
5
+ A: scores/<ds>/scsemi_cv_20261002/{pooled,fold<k>} arm scsemi__raw vs scores/<ds>/{pooled,fold<k>} arm real_lora__raw
6
+ (representatives = exactly LoRA's training + inner-val rows of the fold)
7
+ B: scores/<ds>/scsemi_budget_20261002/{pooled,fold<k>} arms scsemi_n<n>__raw vs lora_n<n>__raw, n = 5/10/20/40
8
+ (representatives = exactly lora_n<n>'s rows; ImMicro and sepsis only)
9
+ Every compared pair must share the donor set and the reference sha. Pooled = one call over all donors (the headline);
10
+ per fold = the number of folds in which LoRA is better (precision / coverage depend on the fold's reference, so they
11
+ are only compared within a call's fold). Giroux disease metrics are read from scores_nosex/ when that rescore exists.
12
+ Writes scsemi/analysis/cv_budget_<date>/{pooled.csv, folds.csv, SUMMARY.md}; cohorts not yet scored are listed.
13
+ usage: summarize_cv_budget.py [OUT_DIR]
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ import pandas as pd
22
+
23
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
24
+ DATASETS = ["immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
25
+ NAME = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "imperial_eskd": "Imperial", "giroux2022": "Giroux",
26
+ "ji2025_chili": "Ji"}
27
+ METRICS = [("comp_l1", True), ("precision", False), ("coverage", False),
28
+ ("contrast_mean_cp10k_r_gen", False), ("deg_top50_sum", False)]
29
+ SHORT = {"comp_l1": "L1", "precision": "precision", "coverage": "coverage", "contrast_mean_cp10k_r_gen": "logFC r",
30
+ "deg_top50_sum": "DEG"}
31
+ PAIRS = [("A", "scsemi_cv_20261002", "scsemi__raw", "real_lora__raw", "all training pairs")] + \
32
+ [("B", "scsemi_budget_20261002", f"scsemi_n{n}__raw", f"lora_n{n}__raw", f"{n} pairs") for n in (5, 10, 20, 40)]
33
+
34
+
35
+ def load(p: Path):
36
+ f = p / "summary.json"
37
+ return json.loads(f.read_text()) if f.exists() else None
38
+
39
+
40
+ def head(s: dict, arm: str, s_nosex: dict | None) -> dict:
41
+ h = dict(s["headline"][arm])
42
+ if s_nosex is not None: # disease metrics without sex-linked genes (Giroux), as in the deck
43
+ for k in ("contrast_mean_cp10k_r_gen", "deg_top50_sum"):
44
+ h[k] = s_nosex["headline"][arm].get(k)
45
+ return h
46
+
47
+
48
+ def same(a: dict, b: dict, what: str) -> None:
49
+ if set(a["donors"]) != set(b["donors"]) or a["reference"]["reference_sha256"] != b["reference"]["reference_sha256"]:
50
+ raise SystemExit(f"{what}: donors or reference differ between the LoRA and scSemiProfiler calls")
51
+
52
+
53
+ def main(out: Path) -> int:
54
+ out.mkdir(parents=True, exist_ok=True)
55
+ pooled, folds, pending = [], [], []
56
+ for ds in DATASETS:
57
+ for exp, sub, sarm, larm, lab in PAIRS:
58
+ if exp == "B" and ds not in ("immicro", "ye2026_sepsis"):
59
+ continue
60
+ sp, lp = load(T / "scores" / ds / sub / "pooled"), load(T / "scores" / ds / "pooled")
61
+ if sp is None or sarm not in sp["arms"]:
62
+ pending.append(f"{NAME[ds]} {exp} {lab}")
63
+ continue
64
+ same(sp, lp, f"{ds} {sub} pooled")
65
+ nos = lambda p: load(T / "scores_nosex" / ds / p) if ds == "giroux2022" else None
66
+ hs, hl = head(sp, sarm, nos(f"{sub}/pooled")), head(lp, larm, nos("pooled"))
67
+ for k, low in METRICS:
68
+ pooled.append({"dataset": ds, "exp": exp, "pairs": lab, "metric": k, "lora": hl.get(k),
69
+ "scsemi": hs.get(k), "lower_better": low})
70
+ for f in range(5):
71
+ sf, lf = load(T / "scores" / ds / sub / f"fold{f}"), load(T / "scores" / ds / f"fold{f}")
72
+ if sf is None or lf is None or larm not in lf["arms"]:
73
+ continue
74
+ same(sf, lf, f"{ds} {sub} fold{f}")
75
+ hs, hl = sf["headline"][sarm], lf["headline"][larm]
76
+ for k, low in METRICS[:3]:
77
+ folds.append({"dataset": ds, "exp": exp, "pairs": lab, "fold": f, "metric": k,
78
+ "lora": hl[k], "scsemi": hs[k], "lower_better": low})
79
+ P, F = pd.DataFrame(pooled), pd.DataFrame(folds)
80
+ P.to_csv(out / "pooled.csv", index=False)
81
+ F.to_csv(out / "folds.csv", index=False)
82
+ lines = ["# scSemiProfiler vs LoRA with the same training pairs (5-fold CV and equal pair budget)", "",
83
+ "Pooled = one scoring call over every donor (each scored by the fold model that never saw it). "
84
+ "Cells: LoRA / scSemiProfiler; bold = better. Folds won = folds in which LoRA is better.", "",
85
+ f"Not scored yet: {', '.join(pending) or 'none'}", ""]
86
+ if len(P):
87
+ for (ds, exp, lab), g in P.groupby(["dataset", "exp", "pairs"], sort=False):
88
+ cells = []
89
+ for _, r in g.iterrows():
90
+ if r.lora is None or r.scsemi is None or pd.isna(r.lora) or pd.isna(r.scsemi):
91
+ continue
92
+ lw = (r.lora < r.scsemi) if r.lower_better else (r.lora > r.scsemi)
93
+ fmt = (lambda v: f"{v:.0f}") if r.metric == "deg_top50_sum" else (lambda v: f"{v:.3f}")
94
+ a, b = fmt(r.lora), fmt(r.scsemi)
95
+ cells.append(f"{SHORT[r.metric]} {'**' + a + '**' if lw else a} / {b if lw else '**' + b + '**'}")
96
+ fw = F[(F.dataset == ds) & (F.exp == exp) & (F.pairs == lab)]
97
+ won = []
98
+ for k, low in METRICS[:3]:
99
+ x = fw[fw.metric == k]
100
+ if len(x):
101
+ w = ((x.lora < x.scsemi) if low else (x.lora > x.scsemi)).sum()
102
+ won.append(f"{SHORT[k]} {w}/{len(x)}")
103
+ lines.append(f"- **{NAME[ds]}, {lab}** — " + "; ".join(cells) + (f" (folds won by LoRA: {', '.join(won)})" if won else ""))
104
+ (out / "SUMMARY.md").write_text("\n".join(lines) + "\n")
105
+ print("\n".join(lines))
106
+ return 0
107
+
108
+
109
+ if __name__ == "__main__":
110
+ sys.exit(main(Path(sys.argv[1]) if len(sys.argv) > 1 else T / "scsemi" / "analysis" / "cv_budget_20261005"))