Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/finalize_rankcal.sh +44 -0
- paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/make_rankcal_queues.sh +61 -0
- paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/pool_folds.py +125 -0
- paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/prepare_cal_budget.py +121 -0
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/finalize_rankcal.sh
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Post-run scoring of the 2026-10-01 experiments (CPU only; run on the host that holds every fold NPZ of the arms):
|
| 3 |
+
# rank : LoRA rank sweep, r = 4 and 64 (alpha = r), n in {5, 20, all}; compare with lora_n5 / lora_n20 / real_lora (r 16)
|
| 4 |
+
# cal : zero-shot + paired calibration with alpha from the pairs lora_n<n> saw (n train + inner-val), n in {5,10,20,40}
|
| 5 |
+
# Steps: per fold, score the experiment's arms -> scores/<ds>/<exp dir>/fold<k>/ (same donors as scores/<ds>/fold<k>/);
|
| 6 |
+
# pool the five folds -> generated/<ds>/pooled_<exp dir>/ (pool_folds.py --arms --out: nothing existing re-pooled);
|
| 7 |
+
# score all donors -> scores/<ds>/<exp dir>/pooled/ (same donors as scores/<ds>/pooled/; sepsis includes the
|
| 8 |
+
# top-50 DEG score of scores/<ds>/pooled_deg/).
|
| 9 |
+
# Already-scored output dirs are skipped, so a rerun resumes.
|
| 10 |
+
# usage: finalize_rankcal.sh DATASET rank|cal
|
| 11 |
+
set -uo pipefail
|
| 12 |
+
T=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
|
| 13 |
+
PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
|
| 14 |
+
ds=$1; exp=$2
|
| 15 |
+
case $exp in
|
| 16 |
+
rank) sub=lora_rank_20261001
|
| 17 |
+
arms=(lora_r4_n5__raw lora_r64_n5__raw lora_r4_n20__raw lora_r64_n20__raw lora_r4__raw lora_r64__raw) ;;
|
| 18 |
+
cal) sub=cal_budget_20261001
|
| 19 |
+
arms=(zs__cal_n5 zs__cal_n10 zs__cal_n20 zs__cal_n40) ;;
|
| 20 |
+
*) echo "usage: finalize_rankcal.sh DATASET rank|cal" >&2; exit 2 ;;
|
| 21 |
+
esac
|
| 22 |
+
G=$T/generated/$ds; S=$T/scores/$ds/$sub
|
| 23 |
+
missing=0
|
| 24 |
+
for f in 0 1 2 3 4; do
|
| 25 |
+
for a in "${arms[@]}"; do
|
| 26 |
+
[[ -s $G/fold$f/$a.npz ]] || { echo "not here: $G/fold$f/$a.npz$([[ -f $G/fold$f/$a.moved ]] && echo ' (moved)')"; missing=1; }
|
| 27 |
+
done
|
| 28 |
+
done
|
| 29 |
+
(( missing == 0 )) || { echo "ABORT: run this on the host that holds every fold NPZ of $ds/$exp ($(hostname -s))" >&2; exit 1; }
|
| 30 |
+
n_fail=0
|
| 31 |
+
for f in 0 1 2 3 4; do
|
| 32 |
+
bash "$T/tools/score_arms.sh" "$ds" "$G/fold$f" "$S/fold$f" "score-$ds-$exp-f$f" "${arms[@]}" || { n_fail=$((n_fail+1)); echo "score $ds $exp fold $f failed"; }
|
| 33 |
+
done
|
| 34 |
+
P=$G/pooled_$sub
|
| 35 |
+
csv=$(IFS=,; echo "${arms[*]}")
|
| 36 |
+
if [[ -s $P/POOL_MANIFEST.json ]]; then echo "$P pooled already"
|
| 37 |
+
else
|
| 38 |
+
until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 56 )); do sleep 120; done
|
| 39 |
+
bash "$T/tools/run_unit.sh" "pool-$ds-$exp" 4 "$PY" "$T/tools/pool_folds.py" "$ds" --arms "$csv" --out "$P" \
|
| 40 |
+
|| { echo "pool $ds $exp failed"; exit 1; }
|
| 41 |
+
fi
|
| 42 |
+
bash "$T/tools/score_arms.sh" "$ds" "$P" "$S/pooled" "score-$ds-$exp-pooled" "${arms[@]}" || { n_fail=$((n_fail+1)); echo "pooled score failed"; }
|
| 43 |
+
echo "finalize_rankcal $ds $exp done $(date -Is) failed=$n_fail -> $S"
|
| 44 |
+
(( n_fail == 0 ))
|
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/make_rankcal_queues.sh
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Write the run_queue.sh / run_queue_s2.sh queues of the 2026-10-01 experiments (ImMicro and Ye 2026 sepsis, folds 0-4).
|
| 3 |
+
#
|
| 4 |
+
# 1. LoRA rank sweep: r in {4, 64} with alpha = r (update scale alpha/r = 1, as the existing r 16 / alpha 16 runs),
|
| 5 |
+
# n in {5, 20, all}. Everything else is ft_sdd.py's defaults and the queue values of the r 16 arms: lr 5e-4,
|
| 6 |
+
# warmup 200, batch 256, EMA 0.999, eval every 250, patience 8, cap 20,000, seed 20260927, base E16, raw real bulk
|
| 7 |
+
# (conditions_raw_fixed.npz). n-pair runs pass the r 16 learning curve's --train-n / --subset-seed 1000+fold /
|
| 8 |
+
# --strata-regex (sepsis: "sepsis"), so they train on the same donors and inner-validation donors as lora_n5 /
|
| 9 |
+
# lora_n20 (checked by check_rankcal.py). Sampling = test_raw.npz, seed 20260927, as for every existing arm.
|
| 10 |
+
# Arms: lora_r<r>_n5, lora_r<r>_n20, lora_r<r> (all training pairs; the r 16 analogue is real_lora).
|
| 11 |
+
# 2. Zero-shot + paired calibration at equal pair budget: base model, condition fold<k>/test_cal_n<n>.npz
|
| 12 |
+
# (prepare_cal_budget.py: alpha from the n training + inner-validation pairs of lora_n<n>), n in {5, 10, 20, 40}.
|
| 13 |
+
# Arms: zs__cal_n<n> (the all-training-pairs analogue is zs__cal).
|
| 14 |
+
#
|
| 15 |
+
# Host split (about half the GPU time each; every (dataset, n) cell keeps both ranks on one host):
|
| 16 |
+
# server_1 run_queue.sh immicro_lora_rank_s1.txt ImMicro r4/r64, n = 20 and all (40 steps)
|
| 17 |
+
# server_2 run_queue_s2.sh ye2026_sepsis_cal_budget_s2.txt sepsis zs__cal_n{5,10,20,40} (20 steps)
|
| 18 |
+
# immicro_cal_budget_s2.txt ImMicro zs__cal_n{5,10,20,40} (20 steps)
|
| 19 |
+
# ye2026_sepsis_lora_rank_s2.txt sepsis r4/r64, n = 5, 20 and all (60 steps)
|
| 20 |
+
# immicro_lora_rank_n5_s2.txt ImMicro r4/r64, n = 5 (20 steps)
|
| 21 |
+
# usage: make_rankcal_queues.sh
|
| 22 |
+
set -euo pipefail
|
| 23 |
+
T=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
|
| 24 |
+
SEED=20260927
|
| 25 |
+
|
| 26 |
+
rank_queue() { # rank_queue DATASET QUEUE_NAME SIZE...
|
| 27 |
+
local ds=$1 q=$T/queues/$2.txt; shift 2
|
| 28 |
+
local D=$T/data/$ds t=${ds:0:3} strata=""
|
| 29 |
+
[[ $ds == ye2026_sepsis ]] && strata="|--strata-regex|sepsis"
|
| 30 |
+
echo "# $ds LoRA rank sweep (2026-10-01): r in {4,64}, alpha = r; sizes $*; all else as the r 16 arms (real_lora, lora_n*)" > "$q"
|
| 31 |
+
for size in "$@"; do
|
| 32 |
+
for f in 0 1 2 3 4; do
|
| 33 |
+
local R=$T/runs/$ds/fold$f G=$T/generated/$ds/fold$f
|
| 34 |
+
for r in 4 64; do
|
| 35 |
+
local arm=lora_r$r sub=""
|
| 36 |
+
if [[ $size != all ]]; then arm=lora_r${r}_n$size; sub="|--train-n|$size|--subset-seed|$((1000 + f))$strata"; fi
|
| 37 |
+
echo "train|$R/$arm|$D/conditions_raw_fixed.npz|$f|lora|5e-4|--lora-rank|$r|--lora-alpha|$r$sub" >> "$q"
|
| 38 |
+
echo "sample|${t}_f${f}_$arm|$R/$arm/checkpoint_ft.pt|$D/fold$f/test_raw.npz|$SEED|$G/${arm}__raw.npz" >> "$q"
|
| 39 |
+
done
|
| 40 |
+
done
|
| 41 |
+
done
|
| 42 |
+
echo "$q $(grep -vc '^#' "$q") steps"
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
cal_queue() { # cal_queue DATASET QUEUE_NAME
|
| 46 |
+
local ds=$1 q=$T/queues/$2.txt
|
| 47 |
+
local D=$T/data/$ds t=${ds:0:3}
|
| 48 |
+
echo "# $ds zero-shot + paired calibration at the lora_n<n> pair budget (2026-10-01): alpha from lora_n<n>'s train + inner-val rows" > "$q"
|
| 49 |
+
for n in 5 10 20 40; do
|
| 50 |
+
for f in 0 1 2 3 4; do
|
| 51 |
+
echo "sample|${t}_f${f}_zs_cal_n$n|base|$D/fold$f/test_cal_n$n.npz|$SEED|$T/generated/$ds/fold$f/zs__cal_n$n.npz" >> "$q"
|
| 52 |
+
done
|
| 53 |
+
done
|
| 54 |
+
echo "$q $(grep -vc '^#' "$q") steps"
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
rank_queue immicro immicro_lora_rank_s1 20 all
|
| 58 |
+
rank_queue immicro immicro_lora_rank_n5_s2 5
|
| 59 |
+
rank_queue ye2026_sepsis ye2026_sepsis_lora_rank_s2 5 20 all
|
| 60 |
+
cal_queue immicro immicro_cal_budget_s2
|
| 61 |
+
cal_queue ye2026_sepsis ye2026_sepsis_cal_budget_s2
|
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/pool_folds.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Pool the five folds' test-donor generations into one NPZ per arm, so every donor is scored in one call
|
| 3 |
+
(cross-fitted: each donor's cells come from the fold model that never trained on it). CPU only.
|
| 4 |
+
|
| 5 |
+
For each arm present in every fold, writes generated/<dataset>/pooled/<arm>.npz with the keys score_ft.py reads
|
| 6 |
+
(generated_counts, gene_ids, sample_ids, bulk_index, metadata_json) plus a receipt <arm>.log whose output_sha256 is
|
| 7 |
+
the pooled file's sha. The pooled condition NPZ for the broadcast baseline concatenates the folds' test condition
|
| 8 |
+
rows (test_raw / test_cal / test_pseudo, the one each arm was generated from).
|
| 9 |
+
|
| 10 |
+
Note: score_ft.py draws its Poisson read-out once over the whole NPZ, so pooled labels are a new draw, not the
|
| 11 |
+
per-fold ones; the per-fold scores stay the primary per-fold record.
|
| 12 |
+
|
| 13 |
+
--arms A,B pools only those arms (each must be finished in every fold) and builds only the condition pools they
|
| 14 |
+
need; --out DIR writes to DIR instead of generated/<dataset>/pooled, so adding arms later never re-pools or rewrites
|
| 15 |
+
the existing pooled files (their shas are in receipts). An arm <name>__<kind> takes its broadcast condition from
|
| 16 |
+
fold<k>/test_<kind>.npz (raw / cal / pseudo, or e.g. cal_n5). Without both flags the behaviour is unchanged.
|
| 17 |
+
usage: pool_folds.py DATASET [--folds 0,1,2,3,4] [--arms A,B,...] [--out DIR]
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import hashlib
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
import sys
|
| 26 |
+
from datetime import datetime, timezone
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 32 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 33 |
+
TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 34 |
+
COND_OF = {"raw": "test_raw.npz", "cal": "test_cal.npz", "pseudo": "test_pseudo.npz"}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sha(p: Path) -> str:
|
| 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 |
+
|
| 44 |
+
|
| 45 |
+
def main(argv=None) -> int:
|
| 46 |
+
ap = argparse.ArgumentParser()
|
| 47 |
+
ap.add_argument("dataset")
|
| 48 |
+
ap.add_argument("--folds", default="0,1,2,3,4")
|
| 49 |
+
ap.add_argument("--arms", default="", help="comma list: pool only these arms (default: every arm in all folds)")
|
| 50 |
+
ap.add_argument("--out", default="", help="output dir (default generated/<dataset>/pooled)")
|
| 51 |
+
a = ap.parse_args(argv)
|
| 52 |
+
folds = [int(x) for x in a.folds.split(",")]
|
| 53 |
+
G = TASK / "generated" / a.dataset
|
| 54 |
+
D = TASK / "data" / a.dataset
|
| 55 |
+
out = Path(a.out) if a.out else G / "pooled"
|
| 56 |
+
arms = sorted(set.intersection(*[{p.stem for p in (G / f"fold{f}").glob("*.npz")} for f in folds]))
|
| 57 |
+
kinds = dict(COND_OF)
|
| 58 |
+
if a.arms:
|
| 59 |
+
want = [x for x in a.arms.split(",") if x]
|
| 60 |
+
missing = [x for x in want if x not in arms]
|
| 61 |
+
if missing:
|
| 62 |
+
raise SystemExit(f"not finished (NPZ) in every fold {folds}: {missing}")
|
| 63 |
+
arms = want
|
| 64 |
+
kinds = {k: COND_OF.get(k, f"test_{k}.npz") for k in sorted({x.split("__")[-1] for x in arms})}
|
| 65 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
# pooled condition NPZs (broadcast baseline), one per input kind
|
| 67 |
+
cond_paths = {}
|
| 68 |
+
for kind, fname in kinds.items():
|
| 69 |
+
# prepare_dataset.py stored donor_ids/groups as object arrays (pandas strings); these are our own files,
|
| 70 |
+
# read them with pickle allowed and store every object array back as fixed-width unicode
|
| 71 |
+
parts = []
|
| 72 |
+
for f in folds:
|
| 73 |
+
z = np.load(D / f"fold{f}" / fname, allow_pickle=True)
|
| 74 |
+
parts.append({k: (z[k].astype(str) if z[k].dtype == object else z[k]) for k in z.files})
|
| 75 |
+
keys = [k for k in parts[0] if parts[0][k].ndim >= 1 and parts[0][k].shape[0] == parts[0]["sample_ids"].shape[0]]
|
| 76 |
+
merged = {k: np.concatenate([p[k] for p in parts], axis=0) for k in keys}
|
| 77 |
+
for k in parts[0]:
|
| 78 |
+
if k not in merged:
|
| 79 |
+
merged[k] = parts[0][k]
|
| 80 |
+
if len(set(merged["sample_ids"].astype(str))) != merged["sample_ids"].shape[0]:
|
| 81 |
+
raise SystemExit(f"{kind}: a sample appears in two folds' test sets")
|
| 82 |
+
cp = out / f"conditions_pooled_{kind}.npz"
|
| 83 |
+
np.savez(cp, **merged)
|
| 84 |
+
cond_paths[kind] = (cp, sha(cp))
|
| 85 |
+
manifest = {"dataset": a.dataset, "folds": folds, "written_utc": datetime.now(timezone.utc).isoformat(),
|
| 86 |
+
"arms": {}, "conditions": {k: {"path": str(p), "sha256": s} for k, (p, s) in cond_paths.items()}}
|
| 87 |
+
for arm in arms:
|
| 88 |
+
kind = arm.split("__")[-1]
|
| 89 |
+
counts, sids, bidx, srcs, off = [], [], [], [], 0
|
| 90 |
+
for f in folds:
|
| 91 |
+
p = G / f"fold{f}" / f"{arm}.npz"
|
| 92 |
+
rec = json.loads(p.with_suffix(".log").read_text())
|
| 93 |
+
if rec.get("output_sha256") != sha(p):
|
| 94 |
+
raise SystemExit(f"{p}: sha differs from its receipt")
|
| 95 |
+
z = np.load(p, allow_pickle=False)
|
| 96 |
+
counts.append(np.asarray(z["generated_counts"], dtype=np.float32))
|
| 97 |
+
s = z["sample_ids"].astype(str)
|
| 98 |
+
sids.append(s)
|
| 99 |
+
bidx.append(z["bulk_index"].astype(np.int64) + off)
|
| 100 |
+
off += s.size
|
| 101 |
+
gene_ids = z["gene_ids"]
|
| 102 |
+
srcs.append({"fold": f, "path": str(p), "sha256": rec["output_sha256"],
|
| 103 |
+
"checkpoint_sha256": rec.get("checkpoint_sha256"), "seed": rec.get("seed")})
|
| 104 |
+
sample_ids = np.concatenate(sids)
|
| 105 |
+
if len(set(sample_ids)) != sample_ids.size:
|
| 106 |
+
raise SystemExit(f"{arm}: duplicate sample across folds")
|
| 107 |
+
cp, cs = cond_paths[kind]
|
| 108 |
+
meta = {"input_condition_path": str(cp), "input_condition_sha256": cs, "pooled_from": srcs,
|
| 109 |
+
"note": "cross-fitted pool of fold test-donor generations"}
|
| 110 |
+
path = out / f"{arm}.npz"
|
| 111 |
+
np.savez(path, generated_counts=np.concatenate(counts, axis=0), gene_ids=gene_ids, sample_ids=sample_ids,
|
| 112 |
+
bulk_index=np.concatenate(bidx), metadata_json=np.asarray(json.dumps(meta)))
|
| 113 |
+
s = sha(path)
|
| 114 |
+
path.with_suffix(".log").write_text(json.dumps({"output_sha256": s, "pooled_from": srcs,
|
| 115 |
+
"condition_npz": str(cp), "condition_sha256": cs}, indent=1))
|
| 116 |
+
manifest["arms"][arm] = {"path": str(path), "sha256": s, "n_samples": int(sample_ids.size),
|
| 117 |
+
"n_cells": int(sum(c.shape[0] for c in counts))}
|
| 118 |
+
print(f"{arm}: {sample_ids.size} samples, {manifest['arms'][arm]['n_cells']} cells", flush=True)
|
| 119 |
+
del counts
|
| 120 |
+
(out / "POOL_MANIFEST.json").write_text(json.dumps(manifest, indent=1))
|
| 121 |
+
return 0
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
if __name__ == "__main__":
|
| 125 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261001T023742Z-deck-calibration-giroux-sexgenes/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/prepare_cal_budget.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Equal-budget paired calibration for the fold learning curve (CPU only).
|
| 3 |
+
|
| 4 |
+
The fold arm zs__cal fits alpha on all of a fold's training donors. Here, for each fold k and n in --ns, alpha is
|
| 5 |
+
fitted on exactly the rows the LoRA learning-curve run runs/<dataset>/fold<k>/lora_n<n> saw: its RUN.json
|
| 6 |
+
train_rows + inner_val_rows (n training pairs + the fold's inner-validation pairs). Alpha is then applied to the
|
| 7 |
+
bulk of that fold's test rows (the rows lora_n<n> never loaded). Test donors never enter the fit.
|
| 8 |
+
|
| 9 |
+
Same loader, condition arithmetic and NPZ writer as prepare_dataset.py (fold zs__cal) and prepare_fewshot.py
|
| 10 |
+
(alpha from the 5 drawn pairs): alpha = gene_multiplier(bulk[fit], pseudo[fit], valid), valid = genes measured in
|
| 11 |
+
every fit row's bulk and single cells; condition = to_condition_counts(cpm(bulk) * alpha, bulk_valid).
|
| 12 |
+
|
| 13 |
+
Writes data/<dataset>/fold<k>/test_cal_n<n>.npz and alpha_n<n>.npy, and data/<dataset>/CAL_BUDGET.json.
|
| 14 |
+
An existing test_cal_n<n>.npz is never rewritten (its sha is in the generation receipts): it is only checked to hold
|
| 15 |
+
the same rows and counts.
|
| 16 |
+
Check first: refitting with all training rows must reproduce fold<k>/test_cal.npz bulk_counts and alpha.npy exactly.
|
| 17 |
+
usage: CUDA_VISIBLE_DEVICES='' prepare_cal_budget.py DATASET [--ns 5,10,20,40] [--folds 0,1,2,3,4] [--check-only]
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
from datetime import datetime, timezone
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
|
| 31 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 32 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 33 |
+
TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 34 |
+
sys.path.insert(0, str(TASK / "tools"))
|
| 35 |
+
import prepare_dataset as PD # noqa: E402 (same loader, arithmetic and writer as the fold benchmark)
|
| 36 |
+
|
| 37 |
+
SCHEMA = "pbisc_sdd.ft_intradataset.cal_budget.v1"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def calibrate(d: dict, fit: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 41 |
+
valid = d["bulk_valid"][fit].all(axis=0) & d["sc_valid"][fit].all(axis=0)
|
| 42 |
+
alpha = PD.RB.gene_multiplier(d["bulk"][fit], d["pseudo"][fit], valid)
|
| 43 |
+
return alpha, PD.RB.to_condition_counts(PD.RB.cpm(d["bulk"]) * alpha[None, :], d["bulk_valid"])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def main(argv=None) -> int:
|
| 47 |
+
ap = argparse.ArgumentParser()
|
| 48 |
+
ap.add_argument("dataset")
|
| 49 |
+
ap.add_argument("--ns", default="5,10,20,40")
|
| 50 |
+
ap.add_argument("--folds", default="0,1,2,3,4")
|
| 51 |
+
ap.add_argument("--check-only", action="store_true", help="verify inputs and arithmetic, write nothing")
|
| 52 |
+
a = ap.parse_args(argv)
|
| 53 |
+
ds = TASK / "data" / a.dataset
|
| 54 |
+
d = PD.load(ds)
|
| 55 |
+
folds = pd.read_csv(ds / "folds.csv")
|
| 56 |
+
if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
|
| 57 |
+
raise SystemExit("folds.csv rows differ from features.npz")
|
| 58 |
+
prep = json.loads((ds / "PREPARE.json").read_text())
|
| 59 |
+
cpb = int(prep["cells_per_bulk"])
|
| 60 |
+
pos = {s: i for i, s in enumerate(d["sample_ids"])}
|
| 61 |
+
man = {"schema": SCHEMA, "dataset": a.dataset, "written_utc": datetime.now(timezone.utc).isoformat(),
|
| 62 |
+
"rule": "alpha fitted on runs/<ds>/fold<k>/lora_n<n>/RUN.json train_rows + inner_val_rows; applied to the "
|
| 63 |
+
"fold's test rows (prepare_dataset.py arithmetic)",
|
| 64 |
+
"cells_per_bulk": cpb, "features_sha256": prep["features_sha256"], "builder": str(PD.BUILDER),
|
| 65 |
+
"builder_sha256": PD.sha256_file(PD.BUILDER), "folds": {}}
|
| 66 |
+
for f in [int(x) for x in a.folds.split(",")]:
|
| 67 |
+
fd = ds / f"fold{f}"
|
| 68 |
+
test = folds.index[folds["fold"] == f].to_numpy()
|
| 69 |
+
# 1. the arithmetic reproduces the existing fold calibration (alpha on all training rows)
|
| 70 |
+
fit_all = folds.index[(folds["fold"] != f) & (folds["fold"] >= 0)].to_numpy()
|
| 71 |
+
alpha_all, cal_all = calibrate(d, fit_all)
|
| 72 |
+
old = np.load(fd / "test_cal.npz", allow_pickle=True)
|
| 73 |
+
if not (np.array_equal(old["bulk_counts"], cal_all[test]) and np.array_equal(np.load(fd / "alpha.npy"), alpha_all)
|
| 74 |
+
and np.array_equal(old["sample_ids"].astype(str), d["sample_ids"][test])):
|
| 75 |
+
raise SystemExit(f"fold{f}: refit on all training rows does not reproduce test_cal.npz / alpha.npy")
|
| 76 |
+
man["folds"][f] = {"test_rows": int(test.size), "reproduces_test_cal": True, "n": {}}
|
| 77 |
+
for n in [int(x) for x in a.ns.split(",")]:
|
| 78 |
+
rj = TASK / "runs" / a.dataset / f"fold{f}" / f"lora_n{n}" / "RUN.json"
|
| 79 |
+
run = json.loads(rj.read_text())
|
| 80 |
+
if run["fold"] != f or (run.get("train_subset") or {}).get("train_n") != n:
|
| 81 |
+
raise SystemExit(f"{rj}: not the fold {f} n={n} learning-curve run")
|
| 82 |
+
fit_ids = list(run["train_rows"]) + list(run["inner_val_rows"])
|
| 83 |
+
fit = np.asarray(sorted(pos[s] for s in fit_ids), dtype=np.int64)
|
| 84 |
+
if len(set(fit_ids)) != fit.size or not (folds.loc[fit, "fold"].ne(f) & folds.loc[fit, "fold"].ge(0)).all():
|
| 85 |
+
raise SystemExit(f"{rj}: fit rows include test, excluded or duplicate rows")
|
| 86 |
+
if sorted(run["test_rows_never_loaded_for_training"]) != sorted(d["sample_ids"][test]):
|
| 87 |
+
raise SystemExit(f"{rj}: its test rows differ from fold{f}'s test rows")
|
| 88 |
+
if set(folds.loc[fit, "donor_id"]) & set(folds.loc[test, "donor_id"]):
|
| 89 |
+
raise SystemExit(f"{rj}: a test donor is among the fit donors")
|
| 90 |
+
alpha, cal = calibrate(d, fit)
|
| 91 |
+
out = fd / f"test_cal_n{n}.npz"
|
| 92 |
+
if out.exists():
|
| 93 |
+
z = np.load(out, allow_pickle=True)
|
| 94 |
+
same = np.array_equal(z["bulk_counts"], cal[test]) and np.array_equal(z["sample_ids"].astype(str),
|
| 95 |
+
d["sample_ids"][test])
|
| 96 |
+
if not same:
|
| 97 |
+
raise SystemExit(f"{out} exists with different content; not touching it")
|
| 98 |
+
sha, state = PD.sha256_file(out), "existing, verified"
|
| 99 |
+
elif a.check_only:
|
| 100 |
+
sha, state = None, "check-only"
|
| 101 |
+
else:
|
| 102 |
+
sha, state = PD.write_npz(out, d, test, cal, d["bulk_valid"], cpb, f"cal_n{n}"), "written"
|
| 103 |
+
np.save(fd / f"alpha_n{n}.npy", alpha)
|
| 104 |
+
man["folds"][f]["n"][n] = {
|
| 105 |
+
"file": str(out), "sha256": sha, "state": state, "lora_run": str(rj),
|
| 106 |
+
"lora_checkpoint_sha256": run["checkpoint_sha256"],
|
| 107 |
+
"fit_sample_ids": [str(x) for x in d["sample_ids"][fit]], "n_fit_rows": int(fit.size),
|
| 108 |
+
"n_train_rows": len(run["train_rows"]), "n_inner_val_rows": len(run["inner_val_rows"]),
|
| 109 |
+
"fit_groups": folds.loc[fit, "group"].value_counts().to_dict(),
|
| 110 |
+
"alpha_genes_estimated": int((alpha != 1.0).sum()),
|
| 111 |
+
"alpha_genes_estimated_all_training": int((alpha_all != 1.0).sum())}
|
| 112 |
+
print(f"fold{f} n={n}: fit {fit.size} rows ({len(run['train_rows'])} train + {len(run['inner_val_rows'])} "
|
| 113 |
+
f"inner-val), {int((alpha != 1.0).sum())} alpha genes (all-training {int((alpha_all != 1.0).sum())}), "
|
| 114 |
+
f"{test.size} test rows -> {out.name} [{state}]", flush=True)
|
| 115 |
+
if not a.check_only:
|
| 116 |
+
(ds / "CAL_BUDGET.json").write_text(json.dumps(man, indent=1, default=str))
|
| 117 |
+
return 0
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
sys.exit(main())
|