Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/compat_patch_20260928.py +130 -0
- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/cpu_unit.sh +41 -0
- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/export_npz.py +171 -0
- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/lean_cellgraph.py +80 -0
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/compat_patch_20260928.py
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Compatibility addition 2026-09-28: a size-1 trailing training batch (CPU only; no computation is run).
|
| 3 |
+
|
| 4 |
+
Problem: vaegan.fastgenerator.train() builds scvi DataSplitter(train_size=1.0, batch_size=B) with drop_last False.
|
| 5 |
+
When n_obs % B == 1 the last training minibatch holds one cell and the encoder's BatchNorm1d raises
|
| 6 |
+
"Expected more than 1 value per channel when training" (pretrain B = 128; inference B = min(n, 9000)).
|
| 7 |
+
Upstream anticipated this: the same train() carries a commented-out branch that switches to a drop-last splitter
|
| 8 |
+
(DataSplitter2, itself dead code) exactly when n_obs % batch_size == 1.
|
| 9 |
+
|
| 10 |
+
Change (vaegan.py, marker SCSEMI_COMPAT_20260928): in that case only, pass scvi's supported DataSplitter option
|
| 11 |
+
drop_last=True (scvi 1.4.1 pops it and applies it to the training loader only; validate_data_split then keeps
|
| 12 |
+
n_train = n_obs). Every other cell count takes the byte-identical original call, so unaffected representatives
|
| 13 |
+
compute exactly as before. No cell is removed from the data: each epoch reshuffles all n cells and the one cell
|
| 14 |
+
left over by the batch grid is skipped for that epoch.
|
| 15 |
+
|
| 16 |
+
Updates, each by atomic replace, under an exclusive lock on scsemi/.code_update.lock (the runner holds a shared
|
| 17 |
+
lock while it verifies vendor hashes and imports the vendor):
|
| 18 |
+
vendor/scSemiProfiler/scSemiProfiler/vaegan.py, vendor/compatibility.patch (git diff vs the pinned commit),
|
| 19 |
+
vendor/source_manifest.json (file hashes, patch hash, changes list); the previous manifest is kept as
|
| 20 |
+
vendor/source_manifest.before_20260928.json. Idempotent: an already-patched, consistent vendor is left alone.
|
| 21 |
+
usage: compat_patch_20260928.py [--vendor DIR] [--no-lock]
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import fcntl
|
| 27 |
+
import hashlib
|
| 28 |
+
import json
|
| 29 |
+
import os
|
| 30 |
+
import subprocess
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
HERE = Path(__file__).resolve().parents[1]
|
| 34 |
+
COMMIT = "c2aea021188759e56ecf14578915c0237aaa75d2"
|
| 35 |
+
MARK = "# SCSEMI_COMPAT_20260928"
|
| 36 |
+
CHANGE = ("drop a size-1 trailing training batch: scvi DataSplitter(drop_last=True) only when n_obs % batch_size "
|
| 37 |
+
"== 1 (upstream's own commented-out remedy); all other cell counts unchanged")
|
| 38 |
+
OLD = """ data_splitter = DataSplitter(
|
| 39 |
+
self.adata_manager,
|
| 40 |
+
train_size=1.0,
|
| 41 |
+
validation_size=0,
|
| 42 |
+
batch_size=batch_size,)
|
| 43 |
+
"""
|
| 44 |
+
NEW = """ # SCSEMI_COMPAT_20260928: upstream's commented-out remedy above (a drop-last splitter when
|
| 45 |
+
# n_obs % batch_size == 1), through scvi's supported DataSplitter option: drop the trailing training
|
| 46 |
+
# batch only when it would hold a single cell (BatchNorm cannot train on one sample). Every other
|
| 47 |
+
# cell count takes the original call unchanged.
|
| 48 |
+
if self.adata.n_obs % batch_size == 1:
|
| 49 |
+
data_splitter = DataSplitter(
|
| 50 |
+
self.adata_manager,
|
| 51 |
+
train_size=1.0,
|
| 52 |
+
validation_size=0,
|
| 53 |
+
batch_size=batch_size,
|
| 54 |
+
drop_last=True,)
|
| 55 |
+
else:
|
| 56 |
+
data_splitter = DataSplitter(
|
| 57 |
+
self.adata_manager,
|
| 58 |
+
train_size=1.0,
|
| 59 |
+
validation_size=0,
|
| 60 |
+
batch_size=batch_size,)
|
| 61 |
+
"""
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def sha(b: bytes) -> str:
|
| 65 |
+
return hashlib.sha256(b).hexdigest()
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def atomic_write(path: Path, data: bytes) -> None:
|
| 69 |
+
tmp = path.with_name(f".{path.name}.tmp{os.getpid()}")
|
| 70 |
+
with open(tmp, "wb") as f:
|
| 71 |
+
f.write(data)
|
| 72 |
+
f.flush()
|
| 73 |
+
os.fsync(f.fileno())
|
| 74 |
+
os.replace(tmp, path)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def main() -> int:
|
| 78 |
+
ap = argparse.ArgumentParser()
|
| 79 |
+
ap.add_argument("--vendor", type=Path, default=HERE / "vendor")
|
| 80 |
+
ap.add_argument("--no-lock", action="store_true", help="staging copies only")
|
| 81 |
+
a = ap.parse_args()
|
| 82 |
+
vendor = a.vendor.resolve()
|
| 83 |
+
repo = vendor / "scSemiProfiler"
|
| 84 |
+
if subprocess.check_output(["git", "-C", str(repo), "rev-parse", "HEAD"], text=True).strip() != COMMIT:
|
| 85 |
+
raise SystemExit("refuse: vendor is not at the pinned commit")
|
| 86 |
+
if not a.no_lock and vendor != (HERE / "vendor").resolve():
|
| 87 |
+
raise SystemExit("--no-lock is required for a vendor outside scsemi/vendor")
|
| 88 |
+
lock = None
|
| 89 |
+
if not a.no_lock:
|
| 90 |
+
lock = open(HERE / ".code_update.lock", "a")
|
| 91 |
+
fcntl.flock(lock, fcntl.LOCK_EX)
|
| 92 |
+
try:
|
| 93 |
+
man_path = vendor / "source_manifest.json"
|
| 94 |
+
man = json.loads(man_path.read_text())
|
| 95 |
+
vg = repo / "scSemiProfiler/vaegan.py"
|
| 96 |
+
text = vg.read_text()
|
| 97 |
+
on_disk = {n: sha((repo / n).read_bytes()) for n in man["files"]}
|
| 98 |
+
if MARK in text:
|
| 99 |
+
if on_disk == man["files"] and CHANGE in man["changes"]:
|
| 100 |
+
print(json.dumps({"status": "already patched", "vaegan_sha256": on_disk["scSemiProfiler/vaegan.py"]}))
|
| 101 |
+
return 0
|
| 102 |
+
raise SystemExit("vaegan.py carries the marker but the manifest is inconsistent; inspect")
|
| 103 |
+
if on_disk != man["files"]:
|
| 104 |
+
raise SystemExit("vendor files differ from source_manifest.json before patching; inspect")
|
| 105 |
+
if text.count(OLD) != 1:
|
| 106 |
+
raise SystemExit("expected exactly one DataSplitter call in vaegan.train()")
|
| 107 |
+
atomic_write(vendor / "source_manifest.before_20260928.json", man_path.read_bytes())
|
| 108 |
+
atomic_write(vg, text.replace(OLD, NEW).encode())
|
| 109 |
+
diff = subprocess.check_output(["git", "-C", str(repo), "diff", "--", "scSemiProfiler/vaegan.py",
|
| 110 |
+
"scSemiProfiler/fast_generator.py"])
|
| 111 |
+
atomic_write(vendor / "compatibility.patch", diff)
|
| 112 |
+
new = dict(man)
|
| 113 |
+
new["compatibility_patch_sha256"] = sha(diff)
|
| 114 |
+
new["changes"] = list(man["changes"]) + [CHANGE]
|
| 115 |
+
new["files"] = {str(p.relative_to(repo)): sha(p.read_bytes()) for p in sorted((repo / "scSemiProfiler").glob("*.py"))}
|
| 116 |
+
new["previous_manifest_sha256"] = sha((vendor / "source_manifest.before_20260928.json").read_bytes())
|
| 117 |
+
atomic_write(man_path, (json.dumps(new, indent=2) + "\n").encode())
|
| 118 |
+
print(json.dumps({"status": "patched", "vaegan_sha256": new["files"]["scSemiProfiler/vaegan.py"],
|
| 119 |
+
"patch_sha256": new["compatibility_patch_sha256"],
|
| 120 |
+
"source_canonical_sha256": sha(json.dumps(new, sort_keys=True).encode()),
|
| 121 |
+
"previous_source_canonical_sha256": sha(json.dumps(man, sort_keys=True).encode())}))
|
| 122 |
+
finally:
|
| 123 |
+
if lock is not None:
|
| 124 |
+
fcntl.flock(lock, fcntl.LOCK_UN)
|
| 125 |
+
lock.close()
|
| 126 |
+
return 0
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
if __name__ == "__main__":
|
| 130 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/cpu_unit.sh
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# CPU-only step as a transient systemd user unit in ml.slice (server_1 and server_2; same paths on both).
|
| 3 |
+
# MemoryMax <= 16G, MemorySwapMax 0, OOMPolicy kill, OOMScoreAdjust +500, CPUQuota = THREADS x 100 % (<= 6),
|
| 4 |
+
# Nice 10, CUDA hidden, no bytecode. PYTHONNOUSERSITE=1 unless ALLOW_USER_SITE=1 (the frozen server_1 runtime_env
|
| 5 |
+
# takes certifi / charset_normalizer from ~/.local, exactly as the frozen campaign ran). Refuses to start unless MemAvailable >= 32 GiB + MEMMAX (the co-scheduled
|
| 6 |
+
# trainer keeps a 32 GiB floor). Waits; returns the command's exit code (last log line "UNIT_EXIT <rc>").
|
| 7 |
+
# usage: cpu_unit.sh NAME THREADS MEMMAX_GIB COMMAND [ARG ...] log -> scsemi/logs/NAME_<stamp>.log
|
| 8 |
+
set -uo pipefail
|
| 9 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 10 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 11 |
+
S=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi
|
| 12 |
+
name=$1; thr=$2; mem=$3; shift 3
|
| 13 |
+
(( thr >= 1 && thr <= 6 )) || { echo "THREADS must be 1..6" >&2; exit 2; }
|
| 14 |
+
(( mem >= 1 && mem <= 16 )) || { echo "MEMMAX_GIB must be 1..16" >&2; exit 2; }
|
| 15 |
+
avail=$(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo)
|
| 16 |
+
(( avail >= 32 + mem )) || { echo "MemAvailable ${avail} GiB < $((32 + mem)); not starting $name" >&2; exit 3; }
|
| 17 |
+
systemctl --user is-active --quiet ml-memory-guard.service || { echo "memory guard inactive; not starting $name" >&2; exit 4; }
|
| 18 |
+
mkdir -p "$S/logs"
|
| 19 |
+
if [[ "${ALLOW_USER_SITE:-0}" == 1 ]]; then nousersite=; else nousersite=1; fi
|
| 20 |
+
stamp=$(date +%Y%m%dT%H%M%S)
|
| 21 |
+
unit=scsemi-${name}-${stamp}
|
| 22 |
+
log=$S/logs/${name}_${stamp}.log
|
| 23 |
+
echo -e "$(date -Is)\tstart\t$unit\t$(hostname -s)\tMemAvailable=${avail}GiB\tthreads=$thr\tmem=${mem}G\t$*" >> "$S/logs/units.tsv"
|
| 24 |
+
systemd-run --user --unit="$unit" --slice=ml.slice --working-directory="$S" --expand-environment=no \
|
| 25 |
+
-p MemoryMax="${mem}G" -p MemorySwapMax=0 -p OOMPolicy=kill -p OOMScoreAdjust=500 \
|
| 26 |
+
-p CPUQuota=$((thr * 100))% -p Nice=10 -p Restart=no \
|
| 27 |
+
-p StandardOutput=append:"$log" -p StandardError=append:"$log" \
|
| 28 |
+
--setenv=CUDA_VISIBLE_DEVICES= --setenv=PYTHONNOUSERSITE="$nousersite" --setenv=PYTHONDONTWRITEBYTECODE=1 \
|
| 29 |
+
--setenv=PYTHONUNBUFFERED=1 --setenv=OMP_NUM_THREADS="$thr" --setenv=OPENBLAS_NUM_THREADS="$thr" \
|
| 30 |
+
--setenv=MKL_NUM_THREADS="$thr" --setenv=NUMBA_NUM_THREADS="$thr" --setenv=NUMEXPR_NUM_THREADS="$thr" \
|
| 31 |
+
/bin/bash -c '"$@"; rc=$?; echo "UNIT_EXIT $rc"; exit $rc' _ "$@" >/dev/null
|
| 32 |
+
echo "unit=$unit log=$log"
|
| 33 |
+
sleep 3
|
| 34 |
+
while [[ "$(systemctl --user show "$unit" -p ActiveState --value 2>/dev/null)" =~ ^(active|activating|deactivating)$ ]]; do sleep 10; done
|
| 35 |
+
rc=$(tail -n 1 "$log" | awk '$1=="UNIT_EXIT"{print $2}')
|
| 36 |
+
rc=${rc:-255}
|
| 37 |
+
[[ $rc == 255 ]] && echo "no UNIT_EXIT line (killed? OOM?): $(systemctl --user show "$unit" -p Result --value 2>/dev/null)" >> "$log"
|
| 38 |
+
systemctl --user reset-failed "$unit" >/dev/null 2>&1 || true
|
| 39 |
+
echo -e "$(date -Is)\tend\t$unit\trc=$rc" >> "$S/logs/units.tsv"
|
| 40 |
+
echo "unit $unit finished rc=$rc"
|
| 41 |
+
exit "$rc"
|
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/export_npz.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Adapter: completed scSemiProfiler target shards -> the benchmark's generated NPZ + JSON receipt (CPU only).
|
| 3 |
+
|
| 4 |
+
Per target (condition-NPZ order):
|
| 5 |
+
cells upstream output has one generated cell per cell of the assigned representative (n_rep cells).
|
| 6 |
+
Keep 1,500: n_rep >= 1500 -> 1,500 drawn without replacement; n_rep < 1500 -> whole permutations of the
|
| 7 |
+
n_rep cells concatenated until 1,500 (each cell used floor/ceil(1500/n_rep) times). Stream
|
| 8 |
+
default_rng([20260927, uint64(sha256(target)[:8])]) (the scorer's donor-keyed stream form); kept rows sorted.
|
| 9 |
+
depth upstream values are normalized expression (library-normalised ZINB means, values <= 10 zeroed). Each kept
|
| 10 |
+
cell is rescaled to sum to D = the median per-cell UMI on the modeled genes of the representatives'
|
| 11 |
+
observed cells (inputs_manifest depth.value; label-free, from the training pairs only). All-zero cells stay
|
| 12 |
+
zero (counted). Result = expected counts (Poisson rates), what score_ft.py reads out.
|
| 13 |
+
genes modeled genes placed at their 6k-panel columns; every other panel column is 0.
|
| 14 |
+
metadata_json.input_condition_path = the split's test_raw.npz, so the scorer's bulk-broadcast baseline works.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import argparse
|
| 19 |
+
import hashlib
|
| 20 |
+
import json
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
from datetime import datetime, timezone
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 28 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pandas as pd
|
| 32 |
+
import scipy.sparse as sp
|
| 33 |
+
|
| 34 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 35 |
+
PANEL = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv"
|
| 36 |
+
SEED = 20260927
|
| 37 |
+
N_CELLS = 1500
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def sha(path: Path) -> str:
|
| 41 |
+
h = hashlib.sha256()
|
| 42 |
+
with open(path, "rb") as f:
|
| 43 |
+
for block in iter(lambda: f.read(1 << 24), b""):
|
| 44 |
+
h.update(block)
|
| 45 |
+
return h.hexdigest()
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def target_rng(target: str) -> np.random.Generator:
|
| 49 |
+
key = int.from_bytes(hashlib.sha256(str(target).encode()).digest()[:8], "little")
|
| 50 |
+
return np.random.default_rng([SEED, key])
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def pick_rows(n_src: int, target: str, n_out: int = N_CELLS) -> np.ndarray:
|
| 54 |
+
if n_src < 1:
|
| 55 |
+
raise ValueError(f"{target}: no generated cells")
|
| 56 |
+
rng = target_rng(target)
|
| 57 |
+
if n_src >= n_out:
|
| 58 |
+
return np.sort(rng.choice(n_src, size=n_out, replace=False))
|
| 59 |
+
reps = math.ceil(n_out / n_src)
|
| 60 |
+
return np.sort(np.concatenate([rng.permutation(n_src) for _ in range(reps)])[:n_out])
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def to_expected_counts(X: np.ndarray, depth: float) -> tuple[np.ndarray, int]:
|
| 64 |
+
lib = X.sum(1, dtype=np.float64)
|
| 65 |
+
scale = np.divide(depth, lib, out=np.zeros_like(lib), where=lib > 0)
|
| 66 |
+
return (X * scale[:, None]).astype(np.float32), int((lib <= 0).sum())
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def main(argv=None) -> int:
|
| 70 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 71 |
+
ap.add_argument("--work", type=Path, required=True)
|
| 72 |
+
ap.add_argument("--out", type=Path, required=True, help="generated NPZ path (receipt = same stem .log)")
|
| 73 |
+
a = ap.parse_args(argv)
|
| 74 |
+
work, out = a.work.resolve(), a.out.resolve()
|
| 75 |
+
man = json.loads((work / "inputs/inputs_manifest.json").read_text())
|
| 76 |
+
run = json.loads((work / "run_manifest.json").read_text())
|
| 77 |
+
smoke = bool(man.get("smoke"))
|
| 78 |
+
if smoke and "/scsemi/smoke/" not in str(out):
|
| 79 |
+
raise SystemExit("smoke outputs never go to the benchmark's generated/ tree")
|
| 80 |
+
if out.exists() or out.with_suffix(".log").exists():
|
| 81 |
+
raise SystemExit(f"{out} or its receipt exists; never overwrite (preserve and inspect)")
|
| 82 |
+
signature = run["run_signature"]
|
| 83 |
+
genes = man["modeled_genes"]["gene_ids"]
|
| 84 |
+
pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
|
| 85 |
+
panel = pd.read_csv(PANEL)
|
| 86 |
+
panel_ids = np.asarray(panel.gene_id.astype(str).tolist(), dtype=str) # fixed-width unicode: loads with allow_pickle=False
|
| 87 |
+
panel_symbols = np.asarray(panel.gene_symbol.astype(str).tolist(), dtype=str)
|
| 88 |
+
if not np.array_equal(panel_ids[pidx], np.asarray(genes)):
|
| 89 |
+
raise SystemExit("modeled genes do not sit at the recorded panel columns")
|
| 90 |
+
depth = float(man["depth"]["value"])
|
| 91 |
+
if not (np.isfinite(depth) and depth > 0):
|
| 92 |
+
raise SystemExit("invalid depth")
|
| 93 |
+
targets = man["condition_sample_order"] if not smoke else [t for t in man["condition_sample_order"]
|
| 94 |
+
if t in set(man["target_order_test_samples"])]
|
| 95 |
+
if sorted(targets) != sorted(man["target_order_test_samples"]):
|
| 96 |
+
raise SystemExit("targets differ from the condition NPZ order")
|
| 97 |
+
per, src_rows = [], []
|
| 98 |
+
G = np.zeros((len(targets) * N_CELLS, panel_ids.size), dtype=np.float32)
|
| 99 |
+
for i, t in enumerate(targets):
|
| 100 |
+
rec = json.loads((work / "shards" / f"{t}.json").read_text())
|
| 101 |
+
shard = work / "shards" / f"{t}.npz"
|
| 102 |
+
if not rec.get("complete") or rec["run_signature"] != signature or rec["shard_sha256"] != sha(shard):
|
| 103 |
+
raise SystemExit(f"{t}: shard incomplete or receipt mismatch")
|
| 104 |
+
C = sp.load_npz(shard).tocsr()
|
| 105 |
+
if C.shape[1] != len(genes):
|
| 106 |
+
raise SystemExit(f"{t}: shard has {C.shape[1]} genes")
|
| 107 |
+
rows = pick_rows(C.shape[0], t)
|
| 108 |
+
X = C[rows].toarray().astype(np.float64)
|
| 109 |
+
if not np.isfinite(X).all() or (X < 0).any():
|
| 110 |
+
raise SystemExit(f"{t}: non-finite or negative values")
|
| 111 |
+
E, n_zero = to_expected_counts(X, depth)
|
| 112 |
+
G[i * N_CELLS:(i + 1) * N_CELLS, pidx] = E
|
| 113 |
+
src_rows.append(rows.astype(np.int32))
|
| 114 |
+
mult = np.bincount(rows, minlength=C.shape[0])
|
| 115 |
+
per.append({"sample_id": t, "representative": rec["representative"], "n_upstream_cells": int(C.shape[0]),
|
| 116 |
+
"with_replacement": bool(C.shape[0] < N_CELLS), "max_multiplicity": int(mult.max()),
|
| 117 |
+
"zero_library_cells": n_zero, "elapsed_seconds": rec["elapsed_seconds"],
|
| 118 |
+
"median_nonzero_genes": float(np.median((E > 0).sum(1)))})
|
| 119 |
+
lib = G.sum(1, dtype=np.float64)
|
| 120 |
+
nz = lib > 0
|
| 121 |
+
checks = {"finite": bool(np.isfinite(G).all()), "nonnegative": bool((G >= 0).all()),
|
| 122 |
+
"zero_outside_modeled_genes": bool(not G[:, np.setdiff1d(np.arange(panel_ids.size), pidx)].any()),
|
| 123 |
+
"nonzero_cells_sum_to_depth": bool(np.allclose(lib[nz], depth, rtol=1e-4)),
|
| 124 |
+
"gene_order_equals_panel": True, "cells_per_target": N_CELLS}
|
| 125 |
+
if not all(v for k, v in checks.items() if isinstance(v, bool)):
|
| 126 |
+
raise SystemExit(f"output checks failed: {checks}")
|
| 127 |
+
n_t = len(targets)
|
| 128 |
+
avail = np.zeros((n_t, panel_ids.size), dtype=bool)
|
| 129 |
+
avail[:, pidx] = True
|
| 130 |
+
meta = {"method": "scSemiProfiler", "arm": "scsemi5" if man["mode"] == "fewshot" else "scsemi",
|
| 131 |
+
"setting": run["protocol"]["setting"], "dataset": man["dataset"], "mode": man["mode"], "split": man["split"],
|
| 132 |
+
"input_condition_path": man["condition_npz"], "input_condition_sha256": man["condition_sha256"],
|
| 133 |
+
"seed": SEED, "run_signature": signature, "upstream_commit": run["protocol"]["upstream_commit"],
|
| 134 |
+
"protocol": run["protocol"], "representatives": [r["sample_id"] for r in man["representatives"]],
|
| 135 |
+
"train_donors": man["train_donors"], "n_modeled_genes": len(genes),
|
| 136 |
+
"unit": "expected_counts (Poisson rates)", "depth_rule": man["depth"]["rule"], "depth": depth,
|
| 137 |
+
"cell_rule": "1500 per target from the n_rep upstream cells: without replacement if n_rep >= 1500, else "
|
| 138 |
+
"whole permutations concatenated to 1500; default_rng([20260927, uint64 LE sha256(target)[:8]]); "
|
| 139 |
+
"kept rows sorted (source_row)",
|
| 140 |
+
"support_readout": "upstream (values <= 10 normalized units zeroed by fast_semi)", "smoke": smoke,
|
| 141 |
+
"code_migrations": [{"at": m["at"], "transitions": m["transitions"], "to_code_signature": m["to_code_signature"]}
|
| 142 |
+
for m in run.get("migrations", [])],
|
| 143 |
+
"work": str(work)}
|
| 144 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
tmp = out.with_name(out.stem + ".tmp.npz")
|
| 146 |
+
np.savez_compressed(tmp, generated_counts=G, gene_ids=panel_ids, gene_symbols=panel_symbols,
|
| 147 |
+
sample_ids=np.asarray(targets), bulk_index=np.repeat(np.arange(n_t, dtype=np.int64), N_CELLS),
|
| 148 |
+
cells_per_bulk=np.full(n_t, N_CELLS, dtype=np.int64), output_availability_mask=avail,
|
| 149 |
+
source_row=np.concatenate(src_rows), metadata_json=np.asarray(json.dumps(meta)))
|
| 150 |
+
with np.load(tmp, allow_pickle=False) as chk: # the scorer opens NPZs with allow_pickle=False
|
| 151 |
+
for key in chk.files:
|
| 152 |
+
chk[key]
|
| 153 |
+
os.replace(tmp, out)
|
| 154 |
+
receipt = {"output": str(out), "output_sha256": sha(out), "written_utc": datetime.now(timezone.utc).isoformat(),
|
| 155 |
+
"condition_npz": man["condition_npz"], "condition_sha256": man["condition_sha256"], "seed": SEED,
|
| 156 |
+
"bulks": n_t, "cells": int(G.shape[0]), "genes": int(panel_ids.size), "modeled_genes": len(genes),
|
| 157 |
+
"depth": depth, "checks": checks, "per_target": per,
|
| 158 |
+
"total_target_seconds": float(sum(p["elapsed_seconds"] for p in per)),
|
| 159 |
+
"median_target_seconds": float(np.median([p["elapsed_seconds"] for p in per])),
|
| 160 |
+
"run_signature": signature, "code_migrations": meta["code_migrations"],
|
| 161 |
+
"exporter_sha256": sha(Path(__file__)), "smoke": smoke}
|
| 162 |
+
rtmp = out.with_name(out.stem + ".log.tmp")
|
| 163 |
+
rtmp.write_text(json.dumps(receipt, indent=1) + "\n")
|
| 164 |
+
os.replace(rtmp, out.with_suffix(".log"))
|
| 165 |
+
print(json.dumps({k: receipt[k] for k in ("output", "bulks", "cells", "modeled_genes", "depth",
|
| 166 |
+
"median_target_seconds")}))
|
| 167 |
+
return 0
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
if __name__ == "__main__":
|
| 171 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/lean_cellgraph.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Memory-lean, output-identical drop-in for upstream scSemiProfiler.singlecell_process.fast_cellgraph.
|
| 2 |
+
|
| 3 |
+
Upstream (commit c2aea02) keeps several dense n x n float64/float32 copies of the k-NN graph, materialises an
|
| 4 |
+
n x (k-1) x G gather plus two temporaries of the same size for the neighbour-smoothed features (~10 GB at 15.6k cells,
|
| 5 |
+
above the 16 GiB CPU-unit cap), and finds each cell's neighbours with an O(n^2) Python loop. This version performs
|
| 6 |
+
the same arithmetic in the same order:
|
| 7 |
+
adj = kneighbors_graph(X, k, connectivity, include_self=True).toarray() + float32(diagw) on the diagonal,
|
| 8 |
+
divided by the (float64) row-sum vector broadcast over the last axis exactly as upstream (adj / adj.sum(1)),
|
| 9 |
+
selfw = diagonal (float32), diagonal then set to 0; stored densely in obsm['adj'] as upstream
|
| 10 |
+
neighbors= the column indices of each row's non-zeros in np.where row-major order; vectorised when every row has
|
| 11 |
+
exactly k-1 of them (always true for a k-NN graph with self), otherwise upstream's loop verbatim
|
| 12 |
+
neighborx= log(1+X)*selfw[0] + log(1+X[neighbors]).sum(1)*(1-selfw[0])/(k-1), computed in row chunks (a row's
|
| 13 |
+
value depends only on that row, and numpy's axis-1 sum is per-element, so chunking does not change bits)
|
| 14 |
+
It returns (adata, adj_tensor) like upstream. tools/verify_lean_cellgraph.py checks bit-identity against upstream
|
| 15 |
+
on real representatives before this is used, and run_scsemi_paired.py records its use in the run signature.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from sklearn.neighbors import kneighbors_graph
|
| 22 |
+
|
| 23 |
+
CHUNK = 1024
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _upstream_neighbor_loop(xs: np.ndarray, ys: np.ndarray, n: int, maxn: int) -> np.ndarray:
|
| 27 |
+
neighbors = np.zeros((n, maxn - 1)) - 1
|
| 28 |
+
for i in range(n):
|
| 29 |
+
ns = np.zeros(maxn - 1) - 1
|
| 30 |
+
flag = 0
|
| 31 |
+
j = 0
|
| 32 |
+
k = 0
|
| 33 |
+
while flag != 2 and j < xs.shape[0]:
|
| 34 |
+
if xs[j] == i:
|
| 35 |
+
ns[k] = (ys[j])
|
| 36 |
+
k += 1
|
| 37 |
+
flag = 1
|
| 38 |
+
elif flag == 1:
|
| 39 |
+
flag = 2
|
| 40 |
+
j += 1
|
| 41 |
+
neighbors[i] = ns
|
| 42 |
+
return neighbors.astype(int)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def fast_cellgraph_lean(adata, k: int = 15, diagw: float = 1.0):
|
| 46 |
+
Xd = np.array(adata.X)
|
| 47 |
+
n = Xd.shape[0]
|
| 48 |
+
adj = kneighbors_graph(Xd, k, mode='connectivity', include_self=True).toarray()
|
| 49 |
+
# upstream: diag = identity(n).astype('float32') * diagw ; adj = adj + diag ; adj = adj / adj.sum(axis=1)
|
| 50 |
+
dval = (np.ones(1, dtype=np.float32) * diagw)[0]
|
| 51 |
+
idx = np.arange(n)
|
| 52 |
+
adj[idx, idx] = adj[idx, idx] + dval
|
| 53 |
+
rs = adj.sum(axis=1)
|
| 54 |
+
for s in range(0, n, CHUNK):
|
| 55 |
+
adj[s:s + CHUNK] = adj[s:s + CHUNK] / rs # broadcast over the last axis, as upstream
|
| 56 |
+
selfw = adj[idx, idx].copy().astype('float32')
|
| 57 |
+
adata.obs['selfw'] = selfw
|
| 58 |
+
adj[idx, idx] = 0
|
| 59 |
+
adata.obsm['adj'] = adj
|
| 60 |
+
# upstream: neighboridx = np.where(torch.from_numpy(adj.astype('float32')) != 0)
|
| 61 |
+
xs_l, ys_l = [], []
|
| 62 |
+
for s in range(0, n, CHUNK):
|
| 63 |
+
r, c = np.nonzero(adj[s:s + CHUNK].astype('float32') != 0)
|
| 64 |
+
xs_l.append(r + s)
|
| 65 |
+
ys_l.append(c)
|
| 66 |
+
xs, ys = np.concatenate(xs_l), np.concatenate(ys_l)
|
| 67 |
+
maxn = k
|
| 68 |
+
counts = np.bincount(xs, minlength=n)
|
| 69 |
+
if n and np.all(counts == maxn - 1):
|
| 70 |
+
neighbors = ys.reshape(n, maxn - 1).astype(int)
|
| 71 |
+
else:
|
| 72 |
+
neighbors = _upstream_neighbor_loop(xs, ys, n, maxn)
|
| 73 |
+
adata.obsm['neighbors'] = neighbors
|
| 74 |
+
out = np.empty(Xd.shape, dtype=np.result_type(np.log(1 + Xd[:1]) * selfw[0]))
|
| 75 |
+
w0 = selfw[0]
|
| 76 |
+
for s in range(0, n, CHUNK):
|
| 77 |
+
e = min(n, s + CHUNK)
|
| 78 |
+
out[s:e] = np.log(1 + Xd[s:e]) * w0 + np.log(1 + Xd[neighbors[s:e], :]).sum(axis=1) * (1 - selfw[0]) / (maxn - 1)
|
| 79 |
+
adata.obsm['neighborx'] = out
|
| 80 |
+
return adata, torch.from_numpy(adj.astype('float32'))
|