junidude14 commited on
Commit
0b93fce
·
verified ·
1 Parent(s): 369f7fd

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/fetch_s2.sh ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Bring the Imperial K = 4,000 draws generated on spark-0110 (server_2) back to this host (2026-10-06).
3
+ # Why: server_2's GPU became free (its root-owned vLLM stopped) while this host's GPU was working through sepsis, so
4
+ # Imperial draws DRAWS (default "2 3 4") run there (tools/run_gpu.sh imperial_eskd, unit bulkonly-k4000-gpu-s2; same
5
+ # code, data, base checkpoint, torch 2.14.0+cu130 and numpy 2.4.2 on both hosts, sha-checked 2026-10-06). This
6
+ # host's queue files of those draws are stubs (full queue: queues/<ds>_draw<j>.txt.full), so its runner skips them;
7
+ # server_2's queue files of the other draws are stubs.
8
+ # For each draw, once server_2's logs/gpu_imperial_eskd_draw<j>.log says "complete":
9
+ # rsync generated/imperial_eskd/draw<j>/ and runs/imperial_eskd/draw<j>/lora_k4000/ to the same paths here, without
10
+ # checkpoint_ft.pt (the LoRA weights stay on server_2, where model_8 checkpoints are kept; the CPU tools check the
11
+ # receipts' checkpoint sha against RUN.json);
12
+ # every NPZ's sha256 must equal its receipt and every queue step must have its output, else WARN (draw held back);
13
+ # then copy the draw's GPU log, which releases the draw to tools/run_cpu.sh.
14
+ # Stops with WARN if server_2's runner is no longer active while a draw is incomplete. usage: fetch_s2.sh [DRAWS...]
15
+ set -uo pipefail
16
+ P4=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/bulkonly_lora5_k4000_20261006
17
+ R=spark-0110
18
+ ds=imperial_eskd
19
+ DRAWS=("${@:-2 3 4}"); read -r -a DRAWS <<< "${DRAWS[*]}"
20
+ LOG=$P4/logs/fetch_s2_$(date +%Y%m%dT%H%M%S).log
21
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
22
+ rsh() { ssh -n -o BatchMode=yes "$R" "export XDG_RUNTIME_DIR=/run/user/\$(id -u); export DBUS_SESSION_BUS_ADDRESS=unix:path=\$XDG_RUNTIME_DIR/bus; $*"; }
23
+ declare -A done_d=()
24
+ log "fetcher start: $ds draws ${DRAWS[*]} from $R"
25
+ while (( ${#done_d[@]} < ${#DRAWS[@]} )); do
26
+ for j in "${DRAWS[@]}"; do
27
+ [[ -n "${done_d[$j]:-}" ]] && continue
28
+ glog=$P4/logs/gpu_${ds}_draw${j}.log
29
+ if rsh "grep -q '=== $ds draw$j complete' '$glog'"; then
30
+ log "draw$j complete on $R; fetching"
31
+ mkdir -p "$P4/generated/$ds/draw$j" "$P4/runs/$ds/draw$j/lora_k4000"
32
+ rsync -a "$R:$P4/generated/$ds/draw$j/" "$P4/generated/$ds/draw$j/" >> "$LOG" 2>&1 \
33
+ && rsync -a --exclude checkpoint_ft.pt "$R:$P4/runs/$ds/draw$j/lora_k4000/" "$P4/runs/$ds/draw$j/lora_k4000/" >> "$LOG" 2>&1 \
34
+ || { log "WARN: rsync of draw$j failed; retry next round"; continue; }
35
+ if python3 - "$P4/queues/${ds}_draw${j}.txt.full" >> "$LOG" 2>&1 <<'EOF'
36
+ import hashlib, json, os, sys
37
+ def sha(p):
38
+ h = hashlib.sha256()
39
+ with open(p, "rb") as f:
40
+ for b in iter(lambda: f.read(1 << 24), b""):
41
+ h.update(b)
42
+ return h.hexdigest()
43
+ bad = 0
44
+ for line in open(sys.argv[1]):
45
+ f = line.strip().split("|")
46
+ if f[0] == "train":
47
+ bad += not os.path.exists(os.path.join(f[1], "RUN.json"))
48
+ elif f[0] == "sample":
49
+ rec = json.load(open(f[4][:-4] + ".log"))
50
+ ok = sha(f[4]) == rec["output_sha256"]
51
+ print(("ok " if ok else "SHA MISMATCH ") + os.path.basename(f[4]), rec["output_sha256"][:12])
52
+ bad += not ok
53
+ sys.exit(1 if bad else 0)
54
+ EOF
55
+ then
56
+ rsync -a "$R:$glog" "$glog" >> "$LOG" 2>&1
57
+ done_d[$j]=1
58
+ log "draw$j fetched and verified (every NPZ sha = its receipt); released to run_cpu.sh"
59
+ else
60
+ log "WARN: draw$j failed verification after fetch (see log); held back"
61
+ done_d[$j]=failed
62
+ fi
63
+ elif ! rsh "systemctl --user is-active --quiet bulkonly-k4000-gpu-s2"; then
64
+ log "WARN: server_2 runner inactive and draw$j incomplete; fetcher stops"; exit 1
65
+ fi
66
+ done
67
+ (( ${#done_d[@]} < ${#DRAWS[@]} )) && sleep 120
68
+ done
69
+ log "all assigned draws handled: $(for j in "${!done_d[@]}"; do printf 'draw%s=%s ' "$j" "${done_d[$j]}"; done)"
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/gpu_draw.sh ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # One few-pair draw's K = 4,000 GPU work (2026-10-06). Runs INSIDE one ml-run step (ml.slice, shared GPU lock held
3
+ # for the whole draw, so the scSemiProfiler queue gets the GPU between draws). Steps: queues/<ds>_draw<j>.txt
4
+ # (tools/make_queue.py), in order:
5
+ # train paired_finetune_intradataset_20260927/tools/ft_sdd.py with the LoRA-5 protocol (base f01 6k 1x E16,
6
+ # --mode lora --lr 5e-4 --fold 0 --fixed-steps 3000, LoRA r16, seed 20260927, the draw's train_donors.txt)
7
+ # on the K = 4,000 training condition; skipped when RUN.json exists; checkpoint sha must equal RUN.json
8
+ # sample scripts/sample_sdd_standalone.py with the benchmark's flags (EMA, DDIM 50, Bernoulli support read-out,
9
+ # threshold 0, batch 256, embedded conditioner); stdout = JSON receipt <out>.log, stderr <out>.err, peak
10
+ # memory <out>.time (GNU time -v); skipped when the NPZ exists and its receipt has an output_sha256
11
+ # Before each step: MemAvailable >= 32 GiB floor + the step's peak estimate (0.45 GiB per 1,000 cells; 16 GiB for
12
+ # training) and the thermal gate, waiting at most WAIT_MIN (120) minutes. A failure ends the step with exit 1 (the
13
+ # runner stops; no retry); a failed sampler's partial outputs are kept under generated/_failed/<stamp>/.
14
+ # usage (tools/run_gpu.sh): ml-run /bin/bash gpu_draw.sh DATASET DRAW
15
+ set -uo pipefail
16
+ M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
17
+ P4=$M8/plans/bulkonly_lora5_k4000_20261006
18
+ FT=$M8/plans/paired_finetune_intradataset_20260927
19
+ BASE=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
20
+ BASE_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
21
+ THERMAL=$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh
22
+ for cand in /home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python /home/sj_server_2/miniforge3/envs/b2sc-infer/bin/python; do
23
+ [[ -x "$cand" ]] && { PY=$cand; break; }
24
+ done
25
+ export CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1
26
+ ds=$1; j=$2
27
+ Q=$P4/queues/${ds}_draw${j}.txt
28
+ LOG=$P4/logs/gpu_${ds}_draw${j}.log
29
+ log() { echo "$(date +%FT%T) $*" >> "$LOG"; }
30
+ fail() { log "FAIL: $*"; exit 1; }
31
+ gate() { # gate NEED_GIB -> prints "MemAvailable ..; thermal verdict"
32
+ local need=$1 t0 a v
33
+ t0=$(date +%s)
34
+ while :; do
35
+ a=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo)
36
+ if (( a >= need )) && v=$(bash "$THERMAL"); then echo "MemAvailable ${a} GiB >= ${need}; $v"; return 0; fi
37
+ (( $(date +%s) - t0 > ${WAIT_MIN:-120} * 60 )) && { echo "MemAvailable ${a} GiB < ${need} or GPU hot"; return 1; }
38
+ sleep 30
39
+ done
40
+ }
41
+ [[ -s "$Q" ]] || fail "queue missing: $Q"
42
+ [[ -n "${PY:-}" ]] || fail "no torch python on this host"
43
+ log "=== $ds draw$j on $(hostname -s), py=$PY, unit=${INVOCATION_ID:-?}"
44
+ CK=""
45
+ while IFS='|' read -r kind a1 a2 a3 a4 a5 <&3; do # queue on fd 3: no step can eat it
46
+ [[ -z "${kind// }" || $kind == \#* ]] && continue
47
+ if [[ $kind == train ]]; then
48
+ run=$a1; cond=$a2; donors=$a3
49
+ mkdir -p "$run"
50
+ if [[ -s $run/RUN.json && -s $run/checkpoint_ft.pt ]]; then
51
+ log "train $(basename "$run"): done already"
52
+ else
53
+ g=$(gate 48) || fail "train gate: $g"
54
+ log "--- train $run ($g)"
55
+ "$PY" -u "$FT/tools/ft_sdd.py" --checkpoint "$BASE" --checkpoint-sha "$BASE_SHA" --dataset-dir "$FT/data/$ds" \
56
+ --condition-npz "$cond" --fold 0 --mode lora --lr 5e-4 --out-dir "$run" --train-donors-file "$donors" \
57
+ --fixed-steps 3000 >> "$run/train.log" 2>&1 || fail "train failed (see $run/train.log)"
58
+ fi
59
+ want=$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['checkpoint_sha256'])" "$run/RUN.json") \
60
+ || fail "RUN.json unreadable"
61
+ got=$(sha256sum "$run/checkpoint_ft.pt" | cut -d' ' -f1)
62
+ [[ "$got" == "$want" ]] || fail "checkpoint sha ${got:0:12} != RUN.json ${want:0:12}"
63
+ log "train ok: $(python3 -c "import json,sys;d=json.load(open(sys.argv[1]));print(d['steps_run'],'steps',d['wall_seconds'],'s','rows',len(d['train_rows']),'sha',d['checkpoint_sha256'][:12])" "$run/RUN.json")"
64
+ CK=$run/checkpoint_ft.pt
65
+ elif [[ $kind == sample ]]; then
66
+ tag=$a1; cond=$a2; seed=$a3; out=$a4; cells=$a5
67
+ [[ -n "$CK" ]] || fail "$tag: no trained checkpoint before sampling"
68
+ rec=${out%.npz}.log; err=${out%.npz}.err; tim=${out%.npz}.time
69
+ if [[ -s $out && -s $rec ]] && python3 -c "import json,sys;assert json.load(open(sys.argv[1]))['output_sha256']" "$rec" 2>/dev/null; then
70
+ log "$tag: sampled already"; continue
71
+ fi
72
+ [[ -s $cond ]] || fail "$tag: condition missing $cond"
73
+ mkdir -p "$(dirname "$out")"
74
+ g=$(gate $(( 32 + (cells * 45 + 99999) / 100000 ))) || fail "$tag gate: $g"
75
+ log "--- $tag cells=$cells seed=$seed ($g)"
76
+ if /usr/bin/time -v -o "$tim" env PYTHONPATH="$M8/src" "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
77
+ --checkpoint "$CK" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 --steps 50 \
78
+ --seed "$seed" --device cuda --conditioner-source embedded --active-logit-threshold 0.0 \
79
+ --support-readout bernoulli > "$rec" 2> "$err"; then
80
+ log "$tag done: $(python3 -c "import json,sys;d=json.load(open(sys.argv[1]));print('cells',d['cells'],'bulks',d['bulks'],'zero_frac %.4f' % d['generated_zero_fraction'],'sha',d['output_sha256'][:12])" "$rec") peak_rss $(awk -F': ' '/Maximum resident/ {printf "%.1f GiB", $2/1048576}' "$tim") wall $(awk -F': ' '/Elapsed/ {print $2}' "$tim")"
81
+ else
82
+ stamp=$(date +%Y%m%dT%H%M%S); keep=$P4/generated/_failed/$stamp; mkdir -p "$keep"
83
+ mv -f "$out" "$rec" "$err" "$tim" "$keep/" 2>/dev/null
84
+ fail "$tag sampler failed; partial outputs kept in $keep"
85
+ fi
86
+ else
87
+ fail "unknown queue line kind: $kind"
88
+ fi
89
+ done 3< "$Q"
90
+ log "=== $ds draw$j complete"
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/make_queue.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Write the GPU queue of each few-pair draw of one cohort (CPU only; 2026-10-06). Read by tools/gpu_draw.sh.
3
+
4
+ queues/<ds>_draw<j>.txt, in order:
5
+ train|RUN_DIR|TRAIN_CONDITION|TRAIN_DONORS_FILE
6
+ LoRA r16 on the draw's training donors (FT data/<ds>/fewshot_n5/draw<j>/train_donors.txt, the K = 1,000 draw's
7
+ donors) with the K = 4,000 training condition, fixed 3,000 steps: the LoRA-5 protocol with only K changed
8
+ sample|TAG|CONDITION_PART|SEED|OUTPUT_NPZ|CELLS
9
+ the draw's paired-test parts (1,500 cells per sample), then the bulk-only parts (4,000 cells per sample)
10
+ Seeds. Draw j uses base seed 20260927 + j * 1,000,003 for both sets; a part starting at row r0 adds r0 * 10,000,019
11
+ (the PARTS.json seed), so every cell has the seed it would have in the unsplit file of its draw. The K = 1,000
12
+ version used 20260927 for every draw, so its five draws share per-cell noise (its completeness review); the offset
13
+ makes the five K = 4,000 draws independent. Draw 0 keeps 20260927. No cell of one draw shares a noise or support
14
+ seed with a cell of another draw: cells per row are < 7,919 and the draw offsets (<= 4,000,012) are not multiples of
15
+ 10,000,019 and differ from them by more than 11,918. Within a draw, the paired-test and bulk-only files reuse the
16
+ same seeds by row, as in the K = 1,000 version (different samples and conditions, never compared cell by cell).
17
+ usage: CUDA_VISIBLE_DEVICES='' make_queue.py DATASET
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
27
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
28
+
29
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
30
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
31
+ PLAN = Path(__file__).resolve().parents[1]
32
+ BASE_SEED = 20260927
33
+ DRAW_STRIDE = 1_000_003
34
+ ROW_STRIDE = 10_000_019
35
+ K = 4000
36
+
37
+
38
+ def parts(manifest: Path, draw: int) -> list[dict]:
39
+ m = json.loads(manifest.read_text())
40
+ if m["base_seed"] != BASE_SEED or m["row_stride"] != ROW_STRIDE:
41
+ raise SystemExit(f"{manifest}: unexpected base seed / row stride")
42
+ out = []
43
+ for p in m["parts"]:
44
+ if p["seed"] != BASE_SEED + p["rows"][0] * ROW_STRIDE:
45
+ raise SystemExit(f"{manifest}: part {p['part']} seed")
46
+ out.append({**p, "path": manifest.parent / p["file"], "draw_seed": p["seed"] + draw * DRAW_STRIDE})
47
+ return out
48
+
49
+
50
+ def main(argv=None) -> int:
51
+ ds = (argv or sys.argv[1:])[0]
52
+ data = PLAN / "data" / ds
53
+ draws = json.loads((FT / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"]
54
+ (PLAN / "queues").mkdir(exist_ok=True)
55
+ summary = {}
56
+ for j in sorted(draws, key=int):
57
+ jj = int(j)
58
+ if not 0 <= jj <= 4:
59
+ raise SystemExit("draw index out of the seed-offset range checked above")
60
+ gen = PLAN / "generated" / ds / f"draw{jj}"
61
+ lines = [f"# {ds} draw {jj}: LoRA r16 at K = {K} on the draw's 5 training donors, then paired-test parts "
62
+ f"(1,500 cells per sample) and bulk-only parts (4,000 cells per sample); base seed "
63
+ f"{BASE_SEED + jj * DRAW_STRIDE}",
64
+ f"train|{PLAN}/runs/{ds}/draw{jj}/lora_k{K}|{data}/conditions_raw_fixed_K{K}.npz|"
65
+ f"{FT}/data/{ds}/fewshot_n5/draw{jj}/train_donors.txt"]
66
+ n_cells = 0
67
+ for kind, man, stem in (("paired", data / "paired_test" / f"draw{jj}_test_raw_K{K}.PARTS.json", "paired_test"),
68
+ ("bulkonly", data / f"bulkonly_raw_K{K}.PARTS.json", "bulkonly")):
69
+ for p in parts(man, jj):
70
+ lines.append(f"sample|{ds}_d{jj}_{kind}_p{p['part']}|{p['path']}|{p['draw_seed']}|"
71
+ f"{gen}/{stem}_K{K}_part{p['part']}.npz|{p['cells']}")
72
+ n_cells += p["cells"]
73
+ q = PLAN / "queues" / f"{ds}_draw{jj}.txt"
74
+ q.write_text("\n".join(lines) + "\n")
75
+ summary[jj] = {"queue": str(q), "steps": len(lines) - 1, "cells": n_cells}
76
+ print(json.dumps(summary, indent=1))
77
+ return 0
78
+
79
+
80
+ if __name__ == "__main__":
81
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/merge_paired.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Merge one draw's K = 4,000 paired-test parts into the one NPZ the benchmark scorer reads (CPU only; 2026-10-06).
3
+
4
+ Why: score_ft.py takes one NPZ per arm and reads it out with one Poisson draw over the whole file. The paired-test
5
+ set of a draw was generated in row parts (tools/split_conditions.py, seed-equivalent: each cell has the seed of the
6
+ unsplit draw file), so the parts concatenated in row order are that draw's unsplit generation.
7
+ Checks: each part's NPZ sha equals its receipt, its condition sha the part file of
8
+ data/<ds>/paired_test/draw<j>_test_raw_K4000.PARTS.json, its seed the queue seed (PARTS seed + draw x 1,000,003), and
9
+ every part has the checkpoint of runs/<ds>/draw<j>/lora_k4000/RUN.json and the same gene axis.
10
+ Output generated/<ds>/draw<j>/paired_test_K4000.npz (compressed) with the keys the scorer and extract_paired.py read:
11
+ generated_counts (cells x 6k float32, parts concatenated), bulk_index (shifted by each part's first row),
12
+ sample_ids, recipe_k, cells_per_bulk, bulk_measurement_fraction, output_availability_mask (per bulk, concatenated),
13
+ gene_ids, gene_symbols, gene_positions (equal in every part), metadata_json (the first part's, with
14
+ input_condition_path / sha256 = the unsplit draw condition, seed = the draw's base seed, merged_from = the parts).
15
+ The other per-cell arrays (generated_log1p, active_logits, active_mask, support_mask) stay in the part files.
16
+ Receipt <merged>.log (JSON, the sampler receipt's keys that the scorer reads): output_sha256, condition_npz,
17
+ condition_sha256, checkpoint, checkpoint_sha256, seed, cells, bulks, parts.
18
+ usage: CUDA_VISIBLE_DEVICES='' merge_paired.py DATASET DRAW
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import sys
26
+ import time
27
+ from datetime import datetime, timezone
28
+ from pathlib import Path
29
+
30
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
31
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
32
+
33
+ import numpy as np
34
+
35
+ PLAN = Path(__file__).resolve().parents[1]
36
+ DRAW_STRIDE = 1_000_003 # tools/make_queue.py
37
+ K = 4000
38
+
39
+
40
+ def sha(p: Path) -> str:
41
+ h = hashlib.sha256()
42
+ with open(p, "rb") as f:
43
+ for b in iter(lambda: f.read(1 << 24), b""):
44
+ h.update(b)
45
+ return h.hexdigest()
46
+
47
+
48
+ def main(argv=None) -> int:
49
+ t0 = time.monotonic()
50
+ ds, j = (argv or sys.argv[1:])[0], int((argv or sys.argv[1:])[1])
51
+ cdir = PLAN / "data" / ds / "paired_test"
52
+ man = json.loads((cdir / f"draw{j}_test_raw_K{K}.PARTS.json").read_text())
53
+ unsplit = Path(man["source"])
54
+ if sha(unsplit) != man["source_sha256"]:
55
+ raise SystemExit(f"{unsplit}: sha differs from PARTS.json")
56
+ run = json.loads((PLAN / "runs" / ds / f"draw{j}" / f"lora_k{K}" / "RUN.json").read_text())
57
+ gdir = PLAN / "generated" / ds / f"draw{j}"
58
+ out = gdir / f"paired_test_K{K}.npz"
59
+ per_cell, per_bulk, fixed, parts, meta0, rec0 = {"generated_counts": [], "bulk_index": []}, {}, {}, [], None, None
60
+ for p in man["parts"]:
61
+ npz = gdir / f"paired_test_K{K}_part{p['part']}.npz"
62
+ rec = json.loads(npz.with_suffix(".log").read_text())
63
+ got = sha(npz)
64
+ if got != rec["output_sha256"]:
65
+ raise SystemExit(f"{npz.name}: sha {got[:12]} != receipt {rec['output_sha256'][:12]}")
66
+ if rec.get("condition_sha256") != p["sha256"] or sha(cdir / p["file"]) != p["sha256"]:
67
+ raise SystemExit(f"{npz.name}: condition sha differs from {p['file']}")
68
+ if int(rec["seed"]) != int(p["seed"]) + j * DRAW_STRIDE:
69
+ raise SystemExit(f"{npz.name}: seed {rec['seed']} is not the queue seed")
70
+ if rec.get("checkpoint_sha256") != run["checkpoint_sha256"]:
71
+ raise SystemExit(f"{npz.name}: checkpoint differs from RUN.json")
72
+ d = np.load(npz, allow_pickle=False)
73
+ n_rows = int(d["sample_ids"].shape[0])
74
+ if n_rows != p["n_samples"]:
75
+ raise SystemExit(f"{npz.name}: {n_rows} bulks != PARTS.json {p['n_samples']}")
76
+ per_cell["generated_counts"].append(np.asarray(d["generated_counts"], dtype=np.float32))
77
+ per_cell["bulk_index"].append(d["bulk_index"].astype(np.int64) + int(p["rows"][0]))
78
+ for key in ("sample_ids", "recipe_k", "cells_per_bulk", "bulk_measurement_fraction", "output_availability_mask"):
79
+ per_bulk.setdefault(key, []).append(d[key])
80
+ for key in ("gene_ids", "gene_symbols", "gene_positions"):
81
+ if key in fixed and not np.array_equal(fixed[key], d[key]):
82
+ raise SystemExit(f"{npz.name}: {key} differs between parts")
83
+ fixed[key] = d[key]
84
+ if meta0 is None:
85
+ meta0, rec0 = json.loads(str(d["metadata_json"])), rec
86
+ parts.append({"part": p["part"], "rows": p["rows"], "npz": str(npz), "sha256": got, "seed": int(rec["seed"]),
87
+ "condition": str(cdir / p["file"]), "condition_sha256": p["sha256"], "cells": int(rec["cells"])})
88
+ arrays = {k: np.concatenate(v) for k, v in per_cell.items()} | {k: np.concatenate(v) for k, v in per_bulk.items()} | fixed
89
+ z = np.load(unsplit, allow_pickle=True)
90
+ if not np.array_equal(arrays["sample_ids"].astype(str), z["sample_ids"].astype(str)):
91
+ raise SystemExit("merged sample order differs from the unsplit condition")
92
+ if not (np.bincount(arrays["bulk_index"], minlength=len(z["sample_ids"])) == z["cells_per_bulk"]).all():
93
+ raise SystemExit("cells per sample differ from the unsplit condition")
94
+ if not np.all(np.diff(arrays["bulk_index"]) >= 0):
95
+ raise SystemExit("bulk_index is not in row order")
96
+ base_seed = int(man["base_seed"]) + j * DRAW_STRIDE
97
+ meta = dict(meta0)
98
+ meta.update({"input_condition_path": str(unsplit), "input_condition_sha256": man["source_sha256"],
99
+ "seed": base_seed, "merged_from": parts,
100
+ "merge_note": "row parts of one draw concatenated in row order (seed-equivalent to the unsplit file)"})
101
+ arrays["metadata_json"] = np.array(json.dumps(meta))
102
+ np.savez_compressed(out, **arrays)
103
+ out_sha = sha(out)
104
+ receipt = {"output": str(out), "output_sha256": out_sha, "condition_npz": str(unsplit),
105
+ "condition_sha256": man["source_sha256"], "checkpoint": rec0.get("checkpoint"),
106
+ "checkpoint_sha256": run["checkpoint_sha256"], "seed": base_seed, "cells": int(arrays["bulk_index"].size),
107
+ "bulks": int(arrays["sample_ids"].size), "genes": int(arrays["generated_counts"].shape[1]),
108
+ "weights": rec0.get("weights"), "steps": rec0.get("steps"), "torch_version": rec0.get("torch_version"),
109
+ "parts": parts, "merged_utc": datetime.now(timezone.utc).isoformat(),
110
+ "tool": str(Path(__file__).resolve()), "tool_sha256": sha(Path(__file__)),
111
+ "seconds": round(time.monotonic() - t0, 1)}
112
+ out.with_suffix(".log").write_text(json.dumps(receipt, indent=1) + "\n")
113
+ print(json.dumps({k: receipt[k] for k in ("output_sha256", "cells", "bulks", "seed", "seconds")}))
114
+ return 0
115
+
116
+
117
+ if __name__ == "__main__":
118
+ sys.exit(main())