Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/rare_metrics.py +121 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/rescore_pretrain_ablations.py +321 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/run_scsemi_strict.py +85 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/runtime.py +203 -0
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/rare_metrics.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Zero-aware rare-state statistics; sample is the matching unit and donor is the bootstrap unit."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from scipy.stats import mannwhitneyu, spearmanr
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def validate_marker_coverage(state: dict, symbols: list[str]) -> None:
|
| 10 |
+
if state["kind"] != "markers":
|
| 11 |
+
return
|
| 12 |
+
needed = set(state["genes"])
|
| 13 |
+
needed.update(g for group in state.get("require_any", []) for g in group)
|
| 14 |
+
needed.update(state.get("exclude", []))
|
| 15 |
+
missing = sorted(needed.difference(symbols))
|
| 16 |
+
if missing:
|
| 17 |
+
raise ValueError(f'{state["name"]}: missing mandatory marker(s): {", ".join(missing)}')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def call_marker_state(counts: np.ndarray, symbols: list[str], state: dict) -> np.ndarray:
|
| 21 |
+
validate_marker_coverage(state, symbols)
|
| 22 |
+
if counts.ndim != 2 or counts.shape[1] != len(symbols):
|
| 23 |
+
raise ValueError("marker counts and symbols are not aligned")
|
| 24 |
+
pos = {g: i for i, g in enumerate(symbols)}
|
| 25 |
+
detected = counts > 0
|
| 26 |
+
hit = detected[:, [pos[g] for g in state["genes"]]].sum(axis=1) >= state["k"]
|
| 27 |
+
for group in state.get("require_any", []):
|
| 28 |
+
hit &= detected[:, [pos[g] for g in group]].any(axis=1)
|
| 29 |
+
for gene in state.get("exclude", []):
|
| 30 |
+
hit &= ~detected[:, pos[gene]]
|
| 31 |
+
return hit
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def validate_design(manifest: dict) -> str:
|
| 35 |
+
design = manifest["design"]
|
| 36 |
+
if design not in {"strict5pair", "legacy_5donor", "fivefold"}:
|
| 37 |
+
raise ValueError(f"unknown design {design}")
|
| 38 |
+
if design != "strict5pair":
|
| 39 |
+
return "diagnostic"
|
| 40 |
+
samples = manifest["train_sample_ids"]
|
| 41 |
+
donors = manifest["train_donor_ids"]
|
| 42 |
+
if len(samples) != 5 or len(donors) != 5 or len(set(samples)) != 5 or len(set(donors)) != 5:
|
| 43 |
+
raise ValueError("strict5pair needs exactly five samples from five unique donor IDs")
|
| 44 |
+
return "strict"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _with_rates(rows: pd.DataFrame) -> pd.DataFrame:
|
| 48 |
+
x = rows.copy()
|
| 49 |
+
for side in ("obs", "gen"):
|
| 50 |
+
p, s = x[f"{side}_parent"], x[f"{side}_state"]
|
| 51 |
+
if (p < 0).any() or (s < 0).any() or (s > p).any():
|
| 52 |
+
raise ValueError(f"{side} state counts must be between 0 and parent counts")
|
| 53 |
+
x[f"{side}_pct"] = 100 * s / p.where(p > 0)
|
| 54 |
+
if f"{side}_total" in x:
|
| 55 |
+
if (x[f"{side}_total"] < p).any():
|
| 56 |
+
raise ValueError(f"{side} total below parent")
|
| 57 |
+
x[f"{side}_overall_pct"] = 100 * s / x[f"{side}_total"].where(x[f"{side}_total"] > 0)
|
| 58 |
+
return x
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def aggregate_donors(rows: pd.DataFrame) -> pd.DataFrame:
|
| 62 |
+
"""Sum counts across all visits from a donor; never treat visit IDs as independent donors."""
|
| 63 |
+
cols = ["obs_parent", "obs_state", "gen_parent", "gen_state"]
|
| 64 |
+
cols += [c for c in ("obs_total", "gen_total") if c in rows]
|
| 65 |
+
if rows.groupby("sample_id").donor_id.nunique().gt(1).any():
|
| 66 |
+
raise ValueError("sample maps to multiple donors")
|
| 67 |
+
summed = rows.groupby("donor_id", dropna=False, as_index=False)[cols].sum()
|
| 68 |
+
if "group" in rows:
|
| 69 |
+
group = rows.groupby("donor_id").group.agg(
|
| 70 |
+
lambda v: v.iloc[0] if v.nunique() == 1 else "mixed")
|
| 71 |
+
summed["group"] = summed.donor_id.map(group)
|
| 72 |
+
return _with_rates(summed)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def high_low_abundance_auroc(donors: pd.DataFrame) -> float:
|
| 76 |
+
"""Rank generated abundance for donors above/below median observed abundance."""
|
| 77 |
+
x = donors[["gen_pct", "obs_pct"]].dropna()
|
| 78 |
+
if x.obs_pct.nunique() < 2:
|
| 79 |
+
return float("nan")
|
| 80 |
+
med = x.obs_pct.median()
|
| 81 |
+
hi = x.loc[x.obs_pct > med, "gen_pct"]
|
| 82 |
+
lo = x.loc[x.obs_pct < med, "gen_pct"]
|
| 83 |
+
if len(hi) < 2 or len(lo) < 2:
|
| 84 |
+
return float("nan")
|
| 85 |
+
return float(mannwhitneyu(hi, lo).statistic / (len(hi) * len(lo)))
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def abundance_summary(rows: pd.DataFrame) -> dict:
|
| 89 |
+
x = _with_rates(rows)
|
| 90 |
+
d = aggregate_donors(rows)
|
| 91 |
+
valid_sample = x[["obs_pct", "gen_pct"]].dropna()
|
| 92 |
+
valid_donor = d[["obs_pct", "gen_pct"]].dropna()
|
| 93 |
+
op, gp = x.obs_parent.sum(), x.gen_parent.sum()
|
| 94 |
+
obs_pct = 100 * x.obs_state.sum() / op if op else float("nan")
|
| 95 |
+
gen_pct = 100 * x.gen_state.sum() / gp if gp else float("nan")
|
| 96 |
+
rho = (float(spearmanr(valid_donor.obs_pct, valid_donor.gen_pct).statistic)
|
| 97 |
+
if len(valid_donor) >= 3 and valid_donor.obs_pct.nunique() > 1
|
| 98 |
+
and valid_donor.gen_pct.nunique() > 1 else float("nan"))
|
| 99 |
+
return dict(n_samples=int(len(x)), n_donors=int(len(d)), obs_state=int(x.obs_state.sum()),
|
| 100 |
+
obs_parent=int(op), gen_state=int(x.gen_state.sum()), gen_parent=int(gp),
|
| 101 |
+
obs_pct=obs_pct, gen_pct=gen_pct,
|
| 102 |
+
generated_zero_samples=int((x.gen_state == 0).sum()),
|
| 103 |
+
generated_zero_donors=int((d.gen_state == 0).sum()),
|
| 104 |
+
parent_zero_samples=int((x.gen_parent == 0).sum()),
|
| 105 |
+
mae_sample_pp=float((valid_sample.obs_pct - valid_sample.gen_pct).abs().mean())
|
| 106 |
+
if len(valid_sample) else float("nan"),
|
| 107 |
+
mae_donor_pp=float((valid_donor.obs_pct - valid_donor.gen_pct).abs().mean())
|
| 108 |
+
if len(valid_donor) else float("nan"),
|
| 109 |
+
spearman_donor=rho,
|
| 110 |
+
high_low_abundance_auroc=high_low_abundance_auroc(d))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def bootstrap_mae(rows: pd.DataFrame, *, seed: int = 20261012, n_boot: int = 2000) -> tuple[float, float]:
|
| 114 |
+
"""Percentile interval for donor mean absolute percentage-point error."""
|
| 115 |
+
d = aggregate_donors(rows)[["obs_pct", "gen_pct"]].dropna()
|
| 116 |
+
err = (d.obs_pct - d.gen_pct).abs().to_numpy()
|
| 117 |
+
if not len(err):
|
| 118 |
+
return float("nan"), float("nan")
|
| 119 |
+
rng = np.random.default_rng(seed)
|
| 120 |
+
means = np.mean(err[rng.integers(len(err), size=(n_boot, len(err)))], axis=1)
|
| 121 |
+
return tuple(float(v) for v in np.quantile(means, [0.025, 0.975]))
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/rescore_pretrain_ablations.py
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CPU-only, donor-balanced Figure 2 pretraining ablation P/C rescore.
|
| 3 |
+
|
| 4 |
+
This deliberately creates a new k=10 recipe. The saved k=15 architecture
|
| 5 |
+
scores are cited as historical evidence, never silently merged into this CSV.
|
| 6 |
+
No model is loaded, and compressed NPZ expression members are read in chunks.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import gzip
|
| 14 |
+
import hashlib
|
| 15 |
+
import json
|
| 16 |
+
import zipfile
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import h5py
|
| 20 |
+
import numpy as np
|
| 21 |
+
from scipy import sparse
|
| 22 |
+
from sklearn.decomposition import PCA
|
| 23 |
+
from sklearn.neighbors import NearestNeighbors
|
| 24 |
+
|
| 25 |
+
MODEL = Path(__file__).resolve().parents[3]
|
| 26 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 27 |
+
ARCH = MODEL / "analysis/scsemi_benchmark_diffusion_20260913"
|
| 28 |
+
PANEL = MODEL / "analysis/floor01_benchmark_20260923"
|
| 29 |
+
BENCH = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/bulk2sc-paper/results/scsemiprofiler_vs_pbisc_heldout_20260629/inputs/004_A_GSE135779_SLE_PBMC/primary_kmeans")
|
| 30 |
+
TRUTH = BENCH / "target_truth_sc.h5ad"
|
| 31 |
+
GENES_TSV = Path("/home/sj_server_1/gblee/datalake/single-cell/GSE135779/GSE135779_genes.tsv.gz")
|
| 32 |
+
ARCH_NAMES = ("bern6k", "bernctx2048", "bern4xctx512", "bern4x")
|
| 33 |
+
PANEL_NAMES = ("f012k", "f013k", "f016k", "f01p15k")
|
| 34 |
+
SEED = 20261012
|
| 35 |
+
POISSON_SEED = 20260916
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def sha_array(a: np.ndarray) -> str:
|
| 39 |
+
return hashlib.sha256(np.ascontiguousarray(a).tobytes()).hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def gene_columns(have, want) -> np.ndarray:
|
| 43 |
+
if len(set(have)) != len(have) or len(set(want)) != len(want):
|
| 44 |
+
raise ValueError("duplicate gene identifiers")
|
| 45 |
+
positions = {g: i for i, g in enumerate(have)}
|
| 46 |
+
missing = [g for g in want if g not in positions]
|
| 47 |
+
if missing:
|
| 48 |
+
raise ValueError(f"{len(missing)} missing genes; first={missing[:3]}")
|
| 49 |
+
return np.asarray([positions[g] for g in want], dtype=np.int64)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def balanced_real_split(labels, donors, per_donor: int, seed: int):
|
| 53 |
+
rng = np.random.default_rng(seed)
|
| 54 |
+
one, two = [], []
|
| 55 |
+
labels = np.asarray(labels)
|
| 56 |
+
for donor in donors:
|
| 57 |
+
rows = np.flatnonzero(labels == donor)
|
| 58 |
+
if rows.size < 2 * per_donor:
|
| 59 |
+
raise ValueError(f"{donor}: only {rows.size} real cells for two independent splits")
|
| 60 |
+
chosen = rng.choice(rows, size=2 * per_donor, replace=False)
|
| 61 |
+
one.extend(chosen[:per_donor]); two.extend(chosen[per_donor:])
|
| 62 |
+
return np.asarray(one, np.int64), np.asarray(two, np.int64)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def score_pc(reference: np.ndarray, candidate: np.ndarray, k: int = 10) -> dict:
|
| 66 |
+
if len(reference) <= k or not len(candidate):
|
| 67 |
+
raise ValueError("too few cells for local radius")
|
| 68 |
+
nn_r = NearestNeighbors(n_neighbors=k + 1, algorithm="brute", n_jobs=1).fit(reference)
|
| 69 |
+
# Bound query working memory independently of the total cell count.
|
| 70 |
+
def batched_query(fitted, queries, neighbors):
|
| 71 |
+
distances, indices = [], []
|
| 72 |
+
for start in range(0, len(queries), 256):
|
| 73 |
+
d, i = fitted.kneighbors(queries[start:start + 256], n_neighbors=neighbors, return_distance=True)
|
| 74 |
+
distances.append(d); indices.append(i)
|
| 75 |
+
return np.concatenate(distances), np.concatenate(indices)
|
| 76 |
+
|
| 77 |
+
radius = batched_query(nn_r, reference, k + 1)[0][:, k]
|
| 78 |
+
nn_c = NearestNeighbors(n_neighbors=1, algorithm="brute", n_jobs=1).fit(candidate)
|
| 79 |
+
d_rg = batched_query(nn_c, reference, 1)[0][:, 0]
|
| 80 |
+
d_gr, i_gr = batched_query(nn_r, candidate, 1)
|
| 81 |
+
coverage = float(np.mean(d_rg <= radius))
|
| 82 |
+
precision = float(np.mean(d_gr[:, 0] <= radius[i_gr[:, 0]]))
|
| 83 |
+
return {"coverage": coverage, "precision": precision,
|
| 84 |
+
"f1": float(2 * coverage * precision / (coverage + precision)) if coverage + precision else 0.0,
|
| 85 |
+
"median_real_to_candidate_distance": float(np.median(d_rg)),
|
| 86 |
+
"median_candidate_to_real_distance": float(np.median(d_gr))}
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def cp10k_log1p(x: np.ndarray) -> np.ndarray:
|
| 90 |
+
x = np.asarray(x, np.float32)
|
| 91 |
+
if not np.isfinite(x).all() or (x < 0).any():
|
| 92 |
+
raise ValueError("negative or nonfinite count/rate")
|
| 93 |
+
totals = x.sum(axis=1, keepdims=True)
|
| 94 |
+
return np.log1p(np.divide(x * 10000, totals, out=np.zeros_like(x), where=totals > 0))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def zip_npy_metadata(path: Path, key: str) -> tuple[tuple[int, ...], np.dtype, bool]:
|
| 98 |
+
with zipfile.ZipFile(path) as z, z.open(key + ".npy") as f:
|
| 99 |
+
version = np.lib.format.read_magic(f)
|
| 100 |
+
if version == (1, 0):
|
| 101 |
+
shape, fortran, dtype = np.lib.format.read_array_header_1_0(f)
|
| 102 |
+
elif version == (2, 0):
|
| 103 |
+
shape, fortran, dtype = np.lib.format.read_array_header_2_0(f)
|
| 104 |
+
else:
|
| 105 |
+
raise ValueError(f"unsupported NPY header version {version} in {path}:{key}")
|
| 106 |
+
return shape, dtype, fortran
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def stream_selected_npz(path: Path, rows: np.ndarray, cols: np.ndarray, batch: int = 128) -> np.ndarray:
|
| 110 |
+
shape, dtype, fortran = zip_npy_metadata(path, "generated_counts")
|
| 111 |
+
if len(shape) != 2 or fortran or dtype != np.dtype("<f4"):
|
| 112 |
+
raise ValueError(f"unsupported matrix layout in {path}: {shape} {dtype} {fortran}")
|
| 113 |
+
if np.any(rows < 0) or np.any(rows >= shape[0]):
|
| 114 |
+
raise ValueError("selected generated row outside matrix")
|
| 115 |
+
selected = np.zeros(shape[0], bool); selected[rows] = True
|
| 116 |
+
output = np.empty((len(rows), len(cols)), np.float32)
|
| 117 |
+
# The output follows the caller's row order. The ZIP member is read once.
|
| 118 |
+
dest = np.full(shape[0], -1, np.int64); dest[rows] = np.arange(len(rows))
|
| 119 |
+
with zipfile.ZipFile(path) as z, z.open("generated_counts.npy") as f:
|
| 120 |
+
version = np.lib.format.read_magic(f)
|
| 121 |
+
if version == (1, 0):
|
| 122 |
+
np.lib.format.read_array_header_1_0(f)
|
| 123 |
+
elif version == (2, 0):
|
| 124 |
+
np.lib.format.read_array_header_2_0(f)
|
| 125 |
+
else:
|
| 126 |
+
raise ValueError(f"unsupported NPY header version {version}")
|
| 127 |
+
row_bytes = shape[1] * dtype.itemsize
|
| 128 |
+
for start in range(0, shape[0], batch):
|
| 129 |
+
stop = min(shape[0], start + batch)
|
| 130 |
+
block = f.read((stop - start) * row_bytes)
|
| 131 |
+
if len(block) != (stop - start) * row_bytes:
|
| 132 |
+
raise IOError(f"truncated generated_counts member: {path}")
|
| 133 |
+
needed = np.flatnonzero(selected[start:stop])
|
| 134 |
+
if needed.size:
|
| 135 |
+
matrix = np.frombuffer(block, dtype=dtype).reshape(stop - start, shape[1])
|
| 136 |
+
output[dest[start + needed]] = matrix[needed][:, cols]
|
| 137 |
+
return output
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def npz_metadata(path: Path):
|
| 141 |
+
with np.load(path, allow_pickle=False) as z:
|
| 142 |
+
return {"gene_ids": z["gene_ids"].astype(str).tolist(),
|
| 143 |
+
"sample_ids": z["sample_ids"].astype(str).tolist(),
|
| 144 |
+
"bulk_index": z["bulk_index"].astype(np.int32),
|
| 145 |
+
"generation": json.loads(str(z["metadata_json"].item()))}
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def selected_generated_rows(bulk_index, n_donors: int, per_donor: int, seed: int):
|
| 149 |
+
rng = np.random.default_rng(seed)
|
| 150 |
+
rows = []
|
| 151 |
+
for donor in range(n_donors):
|
| 152 |
+
candidate = np.flatnonzero(bulk_index == donor)
|
| 153 |
+
if len(candidate) < per_donor:
|
| 154 |
+
raise ValueError(f"generated donor {donor} has {len(candidate)} cells")
|
| 155 |
+
rows.extend(rng.choice(candidate, per_donor, replace=False))
|
| 156 |
+
return np.asarray(rows, np.int64)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def load_real(rows: np.ndarray, panel_cols: np.ndarray) -> np.ndarray:
|
| 160 |
+
with h5py.File(TRUTH) as f:
|
| 161 |
+
x = f["X"]
|
| 162 |
+
csr = sparse.csr_matrix((x["data"][:], x["indices"][:], x["indptr"][:]), shape=tuple(x.attrs["shape"]))
|
| 163 |
+
return csr[rows][:, panel_cols].toarray().astype(np.float32)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def panel_gene_ids() -> list[str]:
|
| 167 |
+
# Reuse the measured 1006-gene axis from the existing floor-0.1% evaluation.
|
| 168 |
+
manifest = PANEL / "metrics/panel_2980_all_diffusion/pbmc5_other/evaluation_manifest.json"
|
| 169 |
+
ids = json.loads(manifest.read_text())["evaluation_gene_ids"]
|
| 170 |
+
if len(ids) != 1006:
|
| 171 |
+
raise ValueError(f"expected 1006 measured genes, got {len(ids)}")
|
| 172 |
+
return ids
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def benchmark_gene_ids():
|
| 176 |
+
with gzip.open(GENES_TSV, "rt") as f:
|
| 177 |
+
raw = [line.split("\t", 1)[0] for line in f]
|
| 178 |
+
with (BENCH / "gene_panel.csv").open(newline="") as f:
|
| 179 |
+
panel = list(csv.DictReader(f))
|
| 180 |
+
return [raw[int(x["raw_gene_index"])] for x in panel]
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def family_specs():
|
| 184 |
+
return {"architecture_floor1pct": [(n, ARCH / f"generated_{n}_e16.npz") for n in ARCH_NAMES],
|
| 185 |
+
"panel_floor0.1pct": [(n, PANEL / f"generated_{n}_e16.npz") for n in PANEL_NAMES]}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def write_legacy_architecture_snapshot():
|
| 189 |
+
"""Copy measured E16 rows into a separate, explicitly non-comparable table."""
|
| 190 |
+
legacy_rows = []
|
| 191 |
+
for name in ARCH_NAMES:
|
| 192 |
+
source = ARCH / f"metrics/real_manifold_with{name}_epochs/real_manifold_coverage_metrics.csv"
|
| 193 |
+
if not source.exists():
|
| 194 |
+
raise FileNotFoundError(source)
|
| 195 |
+
with source.open(newline="") as f:
|
| 196 |
+
matches = [r for r in csv.DictReader(f) if r["method"] == f"diffusion_{name}_e16"]
|
| 197 |
+
if len(matches) != 1:
|
| 198 |
+
raise ValueError(f"{source}: expected exactly one E16 row, got {len(matches)}")
|
| 199 |
+
r = matches[0]
|
| 200 |
+
legacy_rows.append({"method": name, "coverage_1x": r["real_to_generated_coverage_1x"],
|
| 201 |
+
"precision_1x": r["generated_to_real_precision_1x"], "f1_1x": r["bidirectional_f1_1x"],
|
| 202 |
+
"real_cells": r["real_cells_used"], "generated_cells": r["generated_cells_used"],
|
| 203 |
+
"local_k": r["local_k"], "genes": r["panel_genes"], "source_csv": str(source),
|
| 204 |
+
"comparability": "legacy k15 2980 genes; separate recipe"})
|
| 205 |
+
out = ROOT / "source_data/ablation_pretrain_legacy_architecture_k15.csv"
|
| 206 |
+
with out.open("w", newline="") as f:
|
| 207 |
+
writer = csv.DictWriter(f, fieldnames=list(legacy_rows[0]))
|
| 208 |
+
writer.writeheader(); writer.writerows(legacy_rows)
|
| 209 |
+
return out
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def plan():
|
| 213 |
+
result = {}
|
| 214 |
+
for family, sources in family_specs().items():
|
| 215 |
+
details = {}
|
| 216 |
+
for name, path in sources:
|
| 217 |
+
if not path.exists():
|
| 218 |
+
details[name] = {"path": str(path), "status": "missing"}
|
| 219 |
+
else:
|
| 220 |
+
shape, dtype, _ = zip_npy_metadata(path, "generated_counts")
|
| 221 |
+
details[name] = {"path": str(path), "bytes": path.stat().st_size,
|
| 222 |
+
"matrix_shape": shape, "matrix_dtype": str(dtype), "status": "present"}
|
| 223 |
+
result[family] = details
|
| 224 |
+
return result
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def execute(per_donor: int, families: list[str]):
|
| 228 |
+
if per_donor < 11 or per_donor > 500:
|
| 229 |
+
raise ValueError("per-donor count must be 11..500")
|
| 230 |
+
import pandas as pd
|
| 231 |
+
|
| 232 |
+
output_csv = ROOT / "source_data/ablation_pretrain_pc.csv"
|
| 233 |
+
output_json = ROOT / "source_data/ablation_pretrain_pc_receipt.json"
|
| 234 |
+
ids = panel_gene_ids()
|
| 235 |
+
bench_ids = benchmark_gene_ids()
|
| 236 |
+
truth_cols = gene_columns(bench_ids, ids)
|
| 237 |
+
with h5py.File(TRUTH) as f:
|
| 238 |
+
obs = f["obs/donor_id"]
|
| 239 |
+
categories = [x.decode() if isinstance(x, bytes) else str(x) for x in obs["categories"][:]]
|
| 240 |
+
labels = np.asarray(categories)[obs["codes"][:]]
|
| 241 |
+
rows_out = []
|
| 242 |
+
receipt = {"schema": "pbisc.fig2.pretrain_pc.v1", "recipe": {
|
| 243 |
+
"n_pcs": 50, "pca_fit": "real R1 only; randomized SVD; all common measured genes",
|
| 244 |
+
"normalization": "panel CP10k and log1p, independent per cell",
|
| 245 |
+
"readout": "generated_counts as Poisson rate; one draw after common-gene subset; real counts untouched",
|
| 246 |
+
"poisson_seed": POISSON_SEED, "local_k": 10, "real_split_seed": SEED,
|
| 247 |
+
"generated_row_seed": SEED, "per_donor_per_set": per_donor,
|
| 248 |
+
"distance": "Euclidean in fixed real-R1 PCA50; exact brute kNN in bounded batches",
|
| 249 |
+
"cells_as_replicates": False},
|
| 250 |
+
"gene_axis": {"ids_sha256": sha_array(np.asarray(ids, dtype="S20")), "n": len(ids),
|
| 251 |
+
"source": str(PANEL / "metrics/panel_2980_all_diffusion/pbmc5_other/evaluation_manifest.json")},
|
| 252 |
+
"truth_source": str(TRUTH), "families": {}, "limitations": [
|
| 253 |
+
"One generation seed and one Poisson readout seed; donor is the biological unit.",
|
| 254 |
+
"Architecture floor-1% and panel floor-0.1% families are distinct comparisons.",
|
| 255 |
+
"Legacy architecture manifold scores use k=15 and a different unbalanced, unpoissonized recipe; they are not mixed into this table."]}
|
| 256 |
+
for family in families:
|
| 257 |
+
specs = family_specs()[family]
|
| 258 |
+
present = [(n, p) for n, p in specs if p.exists()]
|
| 259 |
+
missing = [n for n, p in specs if not p.exists()]
|
| 260 |
+
if missing:
|
| 261 |
+
receipt["families"][family] = {"status": "incomplete", "missing": missing}
|
| 262 |
+
continue
|
| 263 |
+
metadata = {n: npz_metadata(p) for n, p in present}
|
| 264 |
+
sample_ids = metadata[present[0][0]]["sample_ids"]
|
| 265 |
+
if any(metadata[n]["sample_ids"] != sample_ids for n, _ in present):
|
| 266 |
+
raise ValueError(f"{family}: donor order differs")
|
| 267 |
+
if any(not np.array_equal(metadata[n]["bulk_index"], metadata[present[0][0]]["bulk_index"]) for n, _ in present):
|
| 268 |
+
raise ValueError(f"{family}: generated row donor map differs")
|
| 269 |
+
if not set(sample_ids).issubset(set(categories)):
|
| 270 |
+
raise ValueError(f"{family}: generated donors absent from truth")
|
| 271 |
+
r1, r2 = balanced_real_split(labels, sample_ids, per_donor, SEED)
|
| 272 |
+
g_rows = selected_generated_rows(metadata[present[0][0]]["bulk_index"], len(sample_ids), per_donor, SEED)
|
| 273 |
+
R1 = cp10k_log1p(load_real(r1, truth_cols)); R2 = cp10k_log1p(load_real(r2, truth_cols))
|
| 274 |
+
pca = PCA(n_components=50, svd_solver="randomized", random_state=SEED)
|
| 275 |
+
Rp = pca.fit_transform(R1).astype(np.float32)
|
| 276 |
+
R2p = pca.transform(R2).astype(np.float32)
|
| 277 |
+
base = score_pc(Rp, R2p)
|
| 278 |
+
rows_out.append({"family": family, "method": "real_R2_independent", "n_genes": len(ids),
|
| 279 |
+
"n_donors": len(sample_ids), "real_cells": len(r1), "candidate_cells": len(r2),
|
| 280 |
+
"local_k": 10, **base})
|
| 281 |
+
f_receipt = {"status": "complete", "donor_ids": sample_ids,
|
| 282 |
+
"real_R1_rows_sha256": sha_array(r1), "real_R2_rows_sha256": sha_array(r2),
|
| 283 |
+
"generated_rows_sha256": sha_array(g_rows), "source_files": {}}
|
| 284 |
+
for name, path in present:
|
| 285 |
+
meta = metadata[name]
|
| 286 |
+
cols = gene_columns(meta["gene_ids"], ids)
|
| 287 |
+
counts = stream_selected_npz(path, g_rows, cols)
|
| 288 |
+
rng = np.random.default_rng(POISSON_SEED)
|
| 289 |
+
counts = rng.poisson(counts).astype(np.float32)
|
| 290 |
+
Gp = pca.transform(cp10k_log1p(counts)).astype(np.float32)
|
| 291 |
+
result = score_pc(Rp, Gp)
|
| 292 |
+
rows_out.append({"family": family, "method": name, "n_genes": len(ids),
|
| 293 |
+
"n_donors": len(sample_ids), "real_cells": len(r1),
|
| 294 |
+
"candidate_cells": len(g_rows), "local_k": 10, **result})
|
| 295 |
+
f_receipt["source_files"][name] = {"path": str(path), "size_bytes": path.stat().st_size,
|
| 296 |
+
"mtime_ns": path.stat().st_mtime_ns, "gene_ids_sha256": sha_array(np.asarray(meta["gene_ids"], dtype="S20")),
|
| 297 |
+
"selected_poisson_counts_sha256": sha_array(counts), "generation": meta["generation"]}
|
| 298 |
+
print(f"{family}/{name}: coverage={result['coverage']:.4f} precision={result['precision']:.4f}", flush=True)
|
| 299 |
+
receipt["families"][family] = f_receipt
|
| 300 |
+
if not rows_out:
|
| 301 |
+
raise ValueError("no complete family available for rescoring")
|
| 302 |
+
pd.DataFrame(rows_out).to_csv(output_csv, index=False)
|
| 303 |
+
output_json.write_text(json.dumps(receipt, indent=2) + "\n")
|
| 304 |
+
write_legacy_architecture_snapshot()
|
| 305 |
+
return rows_out, receipt
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
def main(argv=None):
|
| 309 |
+
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
| 310 |
+
parser.add_argument("--plan", action="store_true")
|
| 311 |
+
parser.add_argument("--family", action="append", choices=list(family_specs()))
|
| 312 |
+
parser.add_argument("--per-donor", type=int, default=100)
|
| 313 |
+
args = parser.parse_args(argv)
|
| 314 |
+
if args.plan:
|
| 315 |
+
print(json.dumps(plan(), indent=2)); return 0
|
| 316 |
+
execute(args.per_donor, args.family or list(family_specs()))
|
| 317 |
+
return 0
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
if __name__ == "__main__":
|
| 321 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/run_scsemi_strict.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Opt-in strict support guard around the byte-identical legacy scSemi runner.
|
| 3 |
+
|
| 4 |
+
Pass the legacy runner arguments plus --support-manifest PATH. The n support
|
| 5 |
+
representatives select their own HVG; any reuse/link path is rejected.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import hashlib
|
| 11 |
+
import importlib.util
|
| 12 |
+
import json
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 19 |
+
M8 = PLAN.parents[1]
|
| 20 |
+
OLD = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _sha(path: Path) -> str:
|
| 24 |
+
h = hashlib.sha256()
|
| 25 |
+
with Path(path).open("rb") as stream:
|
| 26 |
+
for block in iter(lambda: stream.read(16 * 1024 * 1024), b""):
|
| 27 |
+
h.update(block)
|
| 28 |
+
return h.hexdigest()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def validate_strict_inputs(support_path: Path, work: Path, *, phase: str,
|
| 32 |
+
reuse_from: Path | None) -> dict:
|
| 33 |
+
if reuse_from is not None or phase == "link":
|
| 34 |
+
raise ValueError("strict scSemi requires own n-support HVG/pretraining; reuse and link are forbidden")
|
| 35 |
+
inputs = json.loads((Path(work) / "inputs/inputs_manifest.json").read_text())
|
| 36 |
+
if inputs.get("mode") != "strict" or inputs.get("smoke"):
|
| 37 |
+
raise ValueError("work inputs are not a full strict-support split")
|
| 38 |
+
cohort = inputs["dataset"]
|
| 39 |
+
folds = pd.read_csv(OLD / "data" / cohort / "folds.csv", dtype={"sample_id": str, "donor_id": str})
|
| 40 |
+
sys.path.insert(0, str(PLAN / "tools"))
|
| 41 |
+
from support_manifest import load_manifest
|
| 42 |
+
support = load_manifest(support_path, folds)
|
| 43 |
+
reps = [r["sample_id"] for r in inputs["representatives"]]
|
| 44 |
+
if (cohort != support["cohort"] or inputs.get("support_sha256") != support["sha256"] or
|
| 45 |
+
reps != support["train_sample_ids"] or inputs.get("targets") != support["test_sample_ids"] or
|
| 46 |
+
inputs.get("train_donors") != support["train_donor_ids"] or
|
| 47 |
+
inputs.get("sources", {}).get("support.json") != _sha(support_path)):
|
| 48 |
+
raise ValueError("scSemi inputs differ from exact strict support IDs/hash")
|
| 49 |
+
if "n_representatives" in inputs and inputs["n_representatives"] != support["n_pairs"]:
|
| 50 |
+
raise ValueError("scSemi representative budget differs from support")
|
| 51 |
+
return support
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def main(argv: list[str] | None = None) -> int:
|
| 55 |
+
args = list(sys.argv[1:] if argv is None else argv)
|
| 56 |
+
ap = argparse.ArgumentParser(description=__doc__, add_help=False)
|
| 57 |
+
ap.add_argument("--support-manifest", type=Path, required=True)
|
| 58 |
+
ap.add_argument("--work", type=Path, required=True)
|
| 59 |
+
ap.add_argument("--phase", required=True)
|
| 60 |
+
ap.add_argument("--reuse-from", type=Path)
|
| 61 |
+
known, _ = ap.parse_known_args(args)
|
| 62 |
+
validate_strict_inputs(known.support_manifest, known.work, phase=known.phase,
|
| 63 |
+
reuse_from=known.reuse_from)
|
| 64 |
+
stripped = []
|
| 65 |
+
skip = False
|
| 66 |
+
for token in args:
|
| 67 |
+
if skip:
|
| 68 |
+
skip = False
|
| 69 |
+
continue
|
| 70 |
+
if token == "--support-manifest":
|
| 71 |
+
skip = True
|
| 72 |
+
continue
|
| 73 |
+
if token.startswith("--support-manifest="):
|
| 74 |
+
continue
|
| 75 |
+
stripped.append(token)
|
| 76 |
+
script = OLD / "scsemi/tools/run_scsemi_paired.py"
|
| 77 |
+
spec = importlib.util.spec_from_file_location("legacy_scsemi_runner", script)
|
| 78 |
+
runner = importlib.util.module_from_spec(spec)
|
| 79 |
+
sys.modules[spec.name] = runner
|
| 80 |
+
spec.loader.exec_module(runner)
|
| 81 |
+
return runner.main(stripped)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
raise SystemExit(main())
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/runtime.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bounded, receipt-bound execution; never retries failed scientific operations."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import re
|
| 10 |
+
import shutil
|
| 11 |
+
import subprocess
|
| 12 |
+
import time
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ReceiptError(RuntimeError):
|
| 16 |
+
"""An output cannot be attributed safely to the requested operation."""
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def sha256(path: Path) -> str:
|
| 20 |
+
h = hashlib.sha256()
|
| 21 |
+
with path.open("rb") as stream:
|
| 22 |
+
for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
|
| 23 |
+
h.update(chunk)
|
| 24 |
+
return h.hexdigest()
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def stamp() -> str:
|
| 28 |
+
return datetime.now(timezone.utc).isoformat()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def atomic_json(path: Path, value: dict) -> None:
|
| 32 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
tmp = path.with_suffix(path.suffix + f".tmp-{os.getpid()}")
|
| 34 |
+
tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
|
| 35 |
+
tmp.replace(path)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def stat_record(path: Path) -> dict:
|
| 39 |
+
st = path.stat()
|
| 40 |
+
return {"path": str(path.resolve()), "bytes": st.st_size, "mtime_ns": st.st_mtime_ns}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class Runtime:
|
| 44 |
+
def __init__(self, root: Path):
|
| 45 |
+
self.root = root.resolve()
|
| 46 |
+
self.started_at = stamp()
|
| 47 |
+
(self.root / "receipts").mkdir(parents=True, exist_ok=True)
|
| 48 |
+
(self.root / "logs").mkdir(parents=True, exist_ok=True)
|
| 49 |
+
self._guard_restarted = False
|
| 50 |
+
|
| 51 |
+
def receipt_path(self, name: str) -> Path:
|
| 52 |
+
if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
|
| 53 |
+
raise ValueError(f"invalid operation name {name!r}")
|
| 54 |
+
return self.root / "receipts" / f"{name}.json"
|
| 55 |
+
|
| 56 |
+
def event(self, name: str, state: str, **details) -> None:
|
| 57 |
+
record = {"at": stamp(), "operation": name, "state": state, **details}
|
| 58 |
+
with (self.root / "events.jsonl").open("a") as stream:
|
| 59 |
+
stream.write(json.dumps(record, allow_nan=False) + "\n")
|
| 60 |
+
print(f"{record['at']} {name}: {state}", flush=True)
|
| 61 |
+
|
| 62 |
+
def signature(self, argv: list[str], inputs: list[Path]) -> str:
|
| 63 |
+
value = {"argv": [str(x) for x in argv], "inputs": [
|
| 64 |
+
{"path": str(p.resolve()), "sha256": sha256(p)} for p in inputs]}
|
| 65 |
+
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
| 66 |
+
|
| 67 |
+
def write_receipt(self, name: str, value: dict) -> None:
|
| 68 |
+
atomic_json(self.receipt_path(name), value)
|
| 69 |
+
|
| 70 |
+
def can_skip(self, name: str, signature: str, outputs: list[Path],
|
| 71 |
+
previous_outputs: dict | None = None) -> bool:
|
| 72 |
+
receipt = self.receipt_path(name)
|
| 73 |
+
if not receipt.exists():
|
| 74 |
+
for p in outputs:
|
| 75 |
+
if not p.exists():
|
| 76 |
+
continue
|
| 77 |
+
prior = (previous_outputs or {}).get(str(p))
|
| 78 |
+
if (not prior or p.suffix in (".npz", ".pt", ".pth", ".safetensors") or
|
| 79 |
+
not p.resolve().is_relative_to(self.root)):
|
| 80 |
+
raise ReceiptError(f"{name}: unreceipted output exists; preserve and inspect")
|
| 81 |
+
backup = Path(prior["backup"])
|
| 82 |
+
if (not backup.is_file() or backup.resolve() == p.resolve() or
|
| 83 |
+
sha256(p) != prior["sha256"] or sha256(backup) != prior["sha256"]):
|
| 84 |
+
raise ReceiptError(f"{name}: preview replacement is not bound to a preserved copy")
|
| 85 |
+
return False
|
| 86 |
+
record = json.loads(receipt.read_text())
|
| 87 |
+
if record.get("state") != "completed":
|
| 88 |
+
raise ReceiptError(f"{name}: previous {record.get('state')}; inspect before explicit recovery")
|
| 89 |
+
if record.get("signature") != signature:
|
| 90 |
+
raise ReceiptError(f"{name}: scientific inputs or command changed; use a new version")
|
| 91 |
+
old = record.get("outputs", [])
|
| 92 |
+
if len(old) != len(outputs):
|
| 93 |
+
raise ReceiptError(f"{name}: output contract changed")
|
| 94 |
+
for p, expected in zip(outputs, old):
|
| 95 |
+
if not p.is_file() or stat_record(p) != {k: expected[k] for k in ("path", "bytes", "mtime_ns")}:
|
| 96 |
+
raise ReceiptError(f"{name}: output missing or modified: {p}")
|
| 97 |
+
if sha256(p) != expected.get("sha256"):
|
| 98 |
+
raise ReceiptError(f"{name}: output hash changed: {p}")
|
| 99 |
+
return True
|
| 100 |
+
|
| 101 |
+
def record_completed(self, name: str, signature: str, outputs: list[Path], seconds: float) -> None:
|
| 102 |
+
records = []
|
| 103 |
+
for path in outputs:
|
| 104 |
+
if not path.is_file() or path.stat().st_size == 0:
|
| 105 |
+
raise ReceiptError(f"{name}: missing or empty required output {path}")
|
| 106 |
+
records.append({**stat_record(path), "sha256": sha256(path)})
|
| 107 |
+
self.write_receipt(name, {"state": "completed", "signature": signature,
|
| 108 |
+
"outputs": records, "seconds": seconds, "at": stamp()})
|
| 109 |
+
|
| 110 |
+
def wrapped_command(self, name: str, argv: list[str], resource: str,
|
| 111 |
+
memory_gib: int, threads: int) -> list[str]:
|
| 112 |
+
if resource not in ("cpu", "gpu"):
|
| 113 |
+
raise ValueError("resource must explicitly be cpu or gpu")
|
| 114 |
+
if not 1 <= threads <= 8 or not 1 <= memory_gib <= 64:
|
| 115 |
+
raise ValueError("unsafe CPU/memory budget")
|
| 116 |
+
env = ["PATH=/home/sj_server_1/.local/bin:/home/sj_server_1/miniforge3/bin:/usr/local/bin:/usr/bin:/bin",
|
| 117 |
+
"PYTHONDONTWRITEBYTECODE=1", "PYTHONUNBUFFERED=1", f"OMP_NUM_THREADS={threads}",
|
| 118 |
+
f"OPENBLAS_NUM_THREADS={threads}", f"MKL_NUM_THREADS={threads}",
|
| 119 |
+
f"NUMBA_NUM_THREADS={threads}"]
|
| 120 |
+
if resource == "gpu":
|
| 121 |
+
return ["/home/sj_server_1/.local/bin/ml-run", "/usr/bin/env", "CUDA_VISIBLE_DEVICES=0",
|
| 122 |
+
"PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True", *env, *map(str, argv)]
|
| 123 |
+
unit = f"pbisc-strict-{name[:100]}-{os.getpid()}-{time.time_ns()}"
|
| 124 |
+
return ["systemd-run", "--user", "--wait", "--collect", "--pipe", "--quiet",
|
| 125 |
+
f"--unit={unit}", "--slice=app.slice", f"--working-directory={self.root}",
|
| 126 |
+
"--expand-environment=no", "-p", f"MemoryMax={memory_gib}G", "-p", "MemorySwapMax=0",
|
| 127 |
+
"-p", "OOMPolicy=kill", "-p", "OOMScoreAdjust=500", "-p", f"CPUQuota={threads * 100}%",
|
| 128 |
+
"/usr/bin/env", "CUDA_VISIBLE_DEVICES=", *env, *map(str, argv)]
|
| 129 |
+
|
| 130 |
+
def preflight(self, resource: str, memory_gib: int) -> None:
|
| 131 |
+
# Every substantial CPU operation and every CUDA operation checks all three controls.
|
| 132 |
+
active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
|
| 133 |
+
capture_output=True, text=True)
|
| 134 |
+
if active.returncode:
|
| 135 |
+
if not self._guard_restarted:
|
| 136 |
+
self._guard_restarted = True
|
| 137 |
+
subprocess.run(["systemctl", "--user", "restart", "ml-memory-guard.service"], check=True)
|
| 138 |
+
subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"], check=True)
|
| 139 |
+
subprocess.run(["/home/sj_server_1/.local/libexec/ml-memory-guard", "--check"], check=True)
|
| 140 |
+
compute = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory",
|
| 141 |
+
"--format=csv,noheader"], capture_output=True, text=True, check=True)
|
| 142 |
+
guard_log = subprocess.run(["journalctl", "-t", "ml-memory-guard", "--since", self.started_at,
|
| 143 |
+
"--no-pager"], capture_output=True, text=True, check=True)
|
| 144 |
+
if "stopping ml.slice" in guard_log.stdout:
|
| 145 |
+
raise RuntimeError("memory guard stopped ml.slice; inspect evidence before any restart")
|
| 146 |
+
available = next(int(line.split()[1]) / 1048576 for line in Path("/proc/meminfo").read_text().splitlines()
|
| 147 |
+
if line.startswith("MemAvailable:"))
|
| 148 |
+
floor = max(32, memory_gib + 24) if resource == "cpu" else 48
|
| 149 |
+
if shutil.disk_usage(self.root).free < 64 * 2**30:
|
| 150 |
+
raise BlockingIOError("less than 64 GiB free disk; preserve originals and wait for storage")
|
| 151 |
+
if available < floor:
|
| 152 |
+
raise BlockingIOError(f"MemAvailable {available:.1f} GiB below {floor} GiB launch floor")
|
| 153 |
+
if resource == "gpu":
|
| 154 |
+
if compute.stdout.strip():
|
| 155 |
+
raise BlockingIOError("another CUDA process is active")
|
| 156 |
+
lock = subprocess.run(["flock", "--nonblock", "/run/user/1000/ml-gpu0.lock", "true"])
|
| 157 |
+
if lock.returncode:
|
| 158 |
+
raise BlockingIOError("shared GPU lock is held")
|
| 159 |
+
|
| 160 |
+
def execute(self, name: str, argv: list[str], *, resource: str = "cpu", memory_gib: int = 16,
|
| 161 |
+
threads: int = 4, inputs: list[Path] | None = None,
|
| 162 |
+
outputs: list[Path] | None = None, wait_seconds: int = 86400,
|
| 163 |
+
previous_outputs: dict | None = None) -> bool:
|
| 164 |
+
inputs, outputs = inputs or [], outputs or []
|
| 165 |
+
signature = self.signature(argv, inputs)
|
| 166 |
+
if self.can_skip(name, signature, outputs, previous_outputs=previous_outputs):
|
| 167 |
+
self.event(name, "verified_skip")
|
| 168 |
+
return False
|
| 169 |
+
wait_start, announced = time.monotonic(), False
|
| 170 |
+
while True:
|
| 171 |
+
try:
|
| 172 |
+
self.preflight(resource, memory_gib)
|
| 173 |
+
break
|
| 174 |
+
except BlockingIOError as exc:
|
| 175 |
+
if not announced:
|
| 176 |
+
self.event(name, "waiting_resources", reason=str(exc))
|
| 177 |
+
announced = True
|
| 178 |
+
if time.monotonic() - wait_start > wait_seconds:
|
| 179 |
+
raise TimeoutError(str(exc)) from exc
|
| 180 |
+
time.sleep(15)
|
| 181 |
+
command = self.wrapped_command(name, argv, resource, memory_gib, threads)
|
| 182 |
+
self.write_receipt(name, {"state": "running", "signature": signature, "argv": argv,
|
| 183 |
+
"resource": resource, "at": stamp(), "previous_outputs": previous_outputs})
|
| 184 |
+
self.event(name, "running", resource=resource)
|
| 185 |
+
t0 = time.monotonic()
|
| 186 |
+
try:
|
| 187 |
+
with (self.root / "logs" / f"{name}.log").open("a") as log:
|
| 188 |
+
result = subprocess.run(command, cwd=self.root, stdout=log, stderr=subprocess.STDOUT)
|
| 189 |
+
elapsed = time.monotonic() - t0
|
| 190 |
+
if result.returncode:
|
| 191 |
+
raise subprocess.CalledProcessError(result.returncode, command)
|
| 192 |
+
self.record_completed(name, signature, outputs, elapsed)
|
| 193 |
+
if previous_outputs:
|
| 194 |
+
receipt = json.loads(self.receipt_path(name).read_text())
|
| 195 |
+
receipt["previous_outputs"] = previous_outputs
|
| 196 |
+
self.write_receipt(name, receipt)
|
| 197 |
+
except BaseException as exc:
|
| 198 |
+
self.write_receipt(name, {"state": "failed", "signature": signature, "at": stamp(),
|
| 199 |
+
"error": str(exc), "seconds": time.monotonic() - t0})
|
| 200 |
+
self.event(name, "failed", error=str(exc))
|
| 201 |
+
raise
|
| 202 |
+
self.event(name, "completed", seconds=elapsed)
|
| 203 |
+
return True
|