Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/ft_sdd_aug.py +530 -0
- paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/run_queue_aug.sh +79 -0
- paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/score_scratch.sh +26 -0
- paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/utility_studies_final6k_20260925/tools/sample_queue.sh +84 -0
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/ft_sdd_aug.py
ADDED
|
@@ -0,0 +1,530 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Fine-tune the final PBISC-SDD model inside one paired dataset fold (augmentation variant of ft_sdd.py).
|
| 3 |
+
|
| 4 |
+
Adds two optional training augmentations; with both off it trains exactly like ft_sdd.py:
|
| 5 |
+
--multi-k each training cell sees its donor's real bulk at a recipe size K drawn from a list
|
| 6 |
+
(per-cell depth kept), instead of the NPZ's single K
|
| 7 |
+
--recipe-frac part of every batch comes from one pretraining-style recipe: K cells of one training donor,
|
| 8 |
+
condition = their full-axis pseudobulk at recipe size K (needs data/<dataset>/cells_full.npz)
|
| 9 |
+
Inner validation always uses the real bulk at the NPZ's K.
|
| 10 |
+
|
| 11 |
+
No-pretraining ablation (added 2026-10-05; default unchanged): --init random re-initialises every denoiser weight the
|
| 12 |
+
way pretraining started (a fresh ConditionalSBDDenoiser(model_config) under torch.manual_seed(--init-seed)) and trains
|
| 13 |
+
it with --mode full. The checkpoint still supplies the architecture, the 6k panel, the value scaler and the bulk
|
| 14 |
+
conditioner's z-score constants (preprocessing, not learned weights). "pretrained_inner_val_loss" in RUN.json is then
|
| 15 |
+
the random-init step-0 loss; "init" records which start was used.
|
| 16 |
+
|
| 17 |
+
Training pairs are (condition of row r, one retained cell of row r). The condition comes from a condition NPZ
|
| 18 |
+
written by prepare_dataset.py (real bulk or pseudobulk, fixed-depth policy) and goes through the checkpoint's own
|
| 19 |
+
conditioner exactly as the standalone sampler does (sample_sdd_standalone.load_conditions), then
|
| 20 |
+
condition_with_measurement_context(base, bulk_measurement_fraction, output_availability_mask). The loss is the
|
| 21 |
+
pretraining loss (SparseDataDiffusion.training_loss: measured-only value L2 + support BCE, self-conditioning),
|
| 22 |
+
with bf16 autocast, AdamW and gradient clipping as in pretraining.
|
| 23 |
+
|
| 24 |
+
Rows: fold k's test rows are never loaded. Training rows = the other folds minus the inner-validation rows;
|
| 25 |
+
inner-validation rows give a fixed-draw diffusion loss every --eval-every steps, and the EMA state with the lowest
|
| 26 |
+
inner-validation loss is kept (early stopping with --patience evaluations).
|
| 27 |
+
|
| 28 |
+
Modes (what is trainable):
|
| 29 |
+
full every denoiser parameter
|
| 30 |
+
condenc only denoiser.condition_encoder (the bulk -> context map)
|
| 31 |
+
lora low-rank updates W = W0 + (alpha/r) B A on every nn.Linear of the denoiser (B starts at zero);
|
| 32 |
+
merged into the weights before saving
|
| 33 |
+
|
| 34 |
+
Batches are donor-balanced: a row is drawn uniformly, then one of its cells uniformly.
|
| 35 |
+
|
| 36 |
+
The output checkpoint keeps the input checkpoint's schema and self-contained keys, with model_state and
|
| 37 |
+
ema_state.model_state set to the selected weights, so scripts/sample_sdd_standalone.py samples it unchanged.
|
| 38 |
+
src/pbisc_sdd is sealed and is only imported.
|
| 39 |
+
"""
|
| 40 |
+
from __future__ import annotations
|
| 41 |
+
|
| 42 |
+
import argparse
|
| 43 |
+
import hashlib
|
| 44 |
+
import json
|
| 45 |
+
import math
|
| 46 |
+
import os
|
| 47 |
+
import sys
|
| 48 |
+
import time
|
| 49 |
+
from datetime import datetime, timezone
|
| 50 |
+
from pathlib import Path
|
| 51 |
+
|
| 52 |
+
import numpy as np
|
| 53 |
+
import pandas as pd
|
| 54 |
+
import torch
|
| 55 |
+
from torch import nn
|
| 56 |
+
import torch.nn.utils.parametrize as parametrize
|
| 57 |
+
|
| 58 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 59 |
+
for p in (M8 / "src", M8 / "scripts"):
|
| 60 |
+
if str(p) not in sys.path:
|
| 61 |
+
sys.path.insert(0, str(p))
|
| 62 |
+
import sample_sdd_standalone as SS # noqa: E402
|
| 63 |
+
from pbisc_sdd.data import condition_with_measurement_context # noqa: E402
|
| 64 |
+
|
| 65 |
+
SCHEMA = "pbisc_sdd.ft_intradataset.run.v1"
|
| 66 |
+
KEEP_KEYS = ("schema_version", "model_config", "diffusion_config", "value_scaler", "conditioner_state",
|
| 67 |
+
"gene_positions", "gene_ids", "gene_symbols", "gene_measurement_coverage",
|
| 68 |
+
"full_gene_measurement_coverage", "corpus_fingerprint", "experiment_config", "proportion_hint",
|
| 69 |
+
"training_contract")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def sha256_file(path: Path) -> str:
|
| 73 |
+
h = hashlib.sha256()
|
| 74 |
+
with open(path, "rb") as f:
|
| 75 |
+
for block in iter(lambda: f.read(1 << 24), b""):
|
| 76 |
+
h.update(block)
|
| 77 |
+
return h.hexdigest()
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def log(msg: str) -> None:
|
| 81 |
+
print(f"{datetime.now().isoformat(timespec='seconds')} {msg}", flush=True)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# ----------------------------------------------------------------------------------------------- LoRA
|
| 85 |
+
class LoRADelta(nn.Module):
|
| 86 |
+
"""Parametrization W -> W + scale * B @ A (B zero-initialised, so the start equals the pretrained W)."""
|
| 87 |
+
|
| 88 |
+
def __init__(self, out_features: int, in_features: int, rank: int, alpha: float) -> None:
|
| 89 |
+
super().__init__()
|
| 90 |
+
self.A = nn.Parameter(torch.empty(rank, in_features))
|
| 91 |
+
self.B = nn.Parameter(torch.zeros(out_features, rank))
|
| 92 |
+
nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
|
| 93 |
+
self.scale = float(alpha) / float(rank)
|
| 94 |
+
|
| 95 |
+
def forward(self, weight: torch.Tensor) -> torch.Tensor:
|
| 96 |
+
return weight + self.scale * (self.B @ self.A).to(dtype=weight.dtype)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def add_lora(model: nn.Module, rank: int, alpha: float) -> list[str]:
|
| 100 |
+
names = []
|
| 101 |
+
for name, module in model.named_modules():
|
| 102 |
+
if isinstance(module, nn.Linear):
|
| 103 |
+
delta = LoRADelta(module.out_features, module.in_features, rank, alpha).to(
|
| 104 |
+
device=module.weight.device, dtype=module.weight.dtype)
|
| 105 |
+
parametrize.register_parametrization(module, "weight", delta)
|
| 106 |
+
names.append(name)
|
| 107 |
+
return names
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def merge_lora(model: nn.Module) -> None:
|
| 111 |
+
for module in model.modules():
|
| 112 |
+
if isinstance(module, nn.Linear) and parametrize.is_parametrized(module, "weight"):
|
| 113 |
+
parametrize.remove_parametrizations(module, "weight", leave_parametrized=True)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def set_trainable(denoiser: nn.Module, mode: str, rank: int, alpha: float) -> dict:
|
| 117 |
+
for p in denoiser.parameters():
|
| 118 |
+
p.requires_grad_(False)
|
| 119 |
+
info: dict = {"mode": mode}
|
| 120 |
+
if mode == "full":
|
| 121 |
+
for p in denoiser.parameters():
|
| 122 |
+
p.requires_grad_(True)
|
| 123 |
+
elif mode == "condenc":
|
| 124 |
+
for p in denoiser.condition_encoder.parameters():
|
| 125 |
+
p.requires_grad_(True)
|
| 126 |
+
elif mode == "lora":
|
| 127 |
+
info["lora_layers"] = add_lora(denoiser, rank, alpha)
|
| 128 |
+
info["lora_rank"], info["lora_alpha"] = rank, alpha
|
| 129 |
+
for name, p in denoiser.named_parameters():
|
| 130 |
+
p.requires_grad_(name.endswith(".A") or name.endswith(".B"))
|
| 131 |
+
else:
|
| 132 |
+
raise SystemExit(f"unknown mode {mode}")
|
| 133 |
+
trainable = [n for n, p in denoiser.named_parameters() if p.requires_grad]
|
| 134 |
+
info["n_trainable"] = int(sum(p.numel() for p in denoiser.parameters() if p.requires_grad))
|
| 135 |
+
info["n_total_base"] = int(sum(p.numel() for n, p in denoiser.named_parameters()
|
| 136 |
+
if not (n.endswith(".A") or n.endswith(".B"))))
|
| 137 |
+
info["trainable_tensors"] = len(trainable)
|
| 138 |
+
return info
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
# ----------------------------------------------------------------------------------------------- data
|
| 142 |
+
class Cells:
|
| 143 |
+
"""Retained cells on the 6k panel (CSR, rows sorted by dataset row)."""
|
| 144 |
+
|
| 145 |
+
def __init__(self, path: Path, panel_gene_ids: np.ndarray) -> None:
|
| 146 |
+
z = np.load(path, allow_pickle=False)
|
| 147 |
+
self.indptr = z["indptr"].astype(np.int64)
|
| 148 |
+
self.indices = z["indices"].astype(np.int64)
|
| 149 |
+
self.data = z["data"].astype(np.float32)
|
| 150 |
+
self.row_sample = z["row_sample"].astype(np.int64)
|
| 151 |
+
self.n_genes = int(z["shape"][1])
|
| 152 |
+
if not np.array_equal(z["panel_gene_ids"].astype(str), panel_gene_ids.astype(str)):
|
| 153 |
+
raise SystemExit("cells_panel6k columns differ from the checkpoint gene panel")
|
| 154 |
+
if bool((np.diff(self.row_sample) < 0).any()):
|
| 155 |
+
raise SystemExit("cells are not sorted by dataset row")
|
| 156 |
+
n_rows = int(self.row_sample.max()) + 1
|
| 157 |
+
self.start = np.searchsorted(self.row_sample, np.arange(n_rows), side="left")
|
| 158 |
+
self.count = np.searchsorted(self.row_sample, np.arange(n_rows), side="right") - self.start
|
| 159 |
+
|
| 160 |
+
def dense(self, cells: np.ndarray) -> np.ndarray:
|
| 161 |
+
s, e = self.indptr[cells], self.indptr[cells + 1]
|
| 162 |
+
lens = e - s
|
| 163 |
+
idx = np.concatenate([np.arange(a, b) for a, b in zip(s, e)]) if len(cells) else np.zeros(0, np.int64)
|
| 164 |
+
out = np.zeros((len(cells), self.n_genes), dtype=np.float32)
|
| 165 |
+
out[np.repeat(np.arange(len(cells)), lens), self.indices[idx]] = self.data[idx]
|
| 166 |
+
return out
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def draw_batch(cells: Cells, rows: np.ndarray, batch: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
|
| 170 |
+
r = rows[rng.integers(0, len(rows), size=batch)]
|
| 171 |
+
c = cells.start[r] + np.floor(rng.random(batch) * cells.count[r]).astype(np.int64)
|
| 172 |
+
return r, c
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
# ----------------------------------------------------------------------------------------------- main
|
| 176 |
+
def main(argv=None) -> int:
|
| 177 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 178 |
+
ap.add_argument("--checkpoint", type=Path, required=True)
|
| 179 |
+
ap.add_argument("--checkpoint-sha", required=True)
|
| 180 |
+
ap.add_argument("--dataset-dir", type=Path, required=True)
|
| 181 |
+
ap.add_argument("--condition-npz", type=Path, required=True, help="all-row condition NPZ used for training")
|
| 182 |
+
ap.add_argument("--fold", type=int, required=True)
|
| 183 |
+
ap.add_argument("--mode", choices=("full", "condenc", "lora"), required=True)
|
| 184 |
+
ap.add_argument("--lora-rank", type=int, default=16)
|
| 185 |
+
ap.add_argument("--lora-alpha", type=float, default=16.0)
|
| 186 |
+
ap.add_argument("--lr", type=float, required=True)
|
| 187 |
+
ap.add_argument("--warmup", type=int, default=200)
|
| 188 |
+
ap.add_argument("--batch-size", type=int, default=256)
|
| 189 |
+
ap.add_argument("--max-steps", type=int, default=20000)
|
| 190 |
+
ap.add_argument("--eval-every", type=int, default=250)
|
| 191 |
+
ap.add_argument("--patience", type=int, default=8)
|
| 192 |
+
ap.add_argument("--ema-decay", type=float, default=0.999)
|
| 193 |
+
ap.add_argument("--val-cells-per-row", type=int, default=256)
|
| 194 |
+
ap.add_argument("--val-repeats", type=int, default=2)
|
| 195 |
+
ap.add_argument("--seed", type=int, default=20260927)
|
| 196 |
+
ap.add_argument("--out-dir", type=Path, required=True)
|
| 197 |
+
ap.add_argument("--device", default="cuda")
|
| 198 |
+
ap.add_argument("--max-cuda-gib", type=float, default=8.0)
|
| 199 |
+
ap.add_argument("--min-system-gib", type=float, default=32.0)
|
| 200 |
+
ap.add_argument("--smoke", action="store_true", help="tiny run for tests (few steps, CPU allowed)")
|
| 201 |
+
ap.add_argument("--train-n", type=int, default=0, help="learning curve: number of training donors to keep")
|
| 202 |
+
ap.add_argument("--subset-seed", type=int, default=0)
|
| 203 |
+
ap.add_argument("--strata-regex", default="", help="groups matching this regex form one stratum, the rest another")
|
| 204 |
+
ap.add_argument("--multi-k", default="", help="comma list: present each real bulk at these recipe sizes K "
|
| 205 |
+
"(per-cell depth kept); one K drawn per training cell. Inner validation stays at the NPZ's K")
|
| 206 |
+
ap.add_argument("--recipe-frac", type=float, default=0.0,
|
| 207 |
+
help="fraction of each batch taken from one pretraining-style recipe of a training donor")
|
| 208 |
+
ap.add_argument("--recipe-k-grid", default="250,500,1000,2000,4000",
|
| 209 |
+
help="recipe sizes K (the pretraining grid); a donor only uses K up to its own cell count")
|
| 210 |
+
ap.add_argument("--init", choices=("pretrained", "random"), default="pretrained",
|
| 211 |
+
help="random: no-pretraining ablation, fresh denoiser weights (requires --mode full)")
|
| 212 |
+
ap.add_argument("--init-seed", type=int, default=20260627, help="torch seed of the random init (pretraining's)")
|
| 213 |
+
a = ap.parse_args(argv)
|
| 214 |
+
if a.init == "random" and a.mode != "full":
|
| 215 |
+
raise SystemExit("--init random needs --mode full (LoRA / condenc need pretrained base weights)")
|
| 216 |
+
|
| 217 |
+
a.out_dir.mkdir(parents=True, exist_ok=True)
|
| 218 |
+
done = a.out_dir / "checkpoint_ft.pt"
|
| 219 |
+
if done.exists() and (a.out_dir / "RUN.json").exists():
|
| 220 |
+
log(f"{done} exists; nothing to do")
|
| 221 |
+
return 0
|
| 222 |
+
avail = int(open("/proc/meminfo").read().split("MemAvailable:")[1].split()[0]) / 1048576
|
| 223 |
+
if avail < a.min_system_gib:
|
| 224 |
+
raise SystemExit(f"MemAvailable {avail:.1f} GiB < floor {a.min_system_gib}")
|
| 225 |
+
got = sha256_file(a.checkpoint)
|
| 226 |
+
if got != a.checkpoint_sha:
|
| 227 |
+
raise SystemExit(f"checkpoint sha {got[:12]} != {a.checkpoint_sha[:12]}")
|
| 228 |
+
device = torch.device(a.device)
|
| 229 |
+
if device.type == "cuda" and device.index is None:
|
| 230 |
+
device = torch.device("cuda", 0)
|
| 231 |
+
if device.type == "cuda":
|
| 232 |
+
total = torch.cuda.get_device_properties(device).total_memory
|
| 233 |
+
torch.cuda.set_per_process_memory_fraction(min(1.0, a.max_cuda_gib * 2**30 / total), device)
|
| 234 |
+
torch.manual_seed(a.seed)
|
| 235 |
+
rng = np.random.default_rng(a.seed)
|
| 236 |
+
|
| 237 |
+
bundle = SS.restore_standalone(a.checkpoint, device=device, weights="ema", conditioner_source="embedded")
|
| 238 |
+
diffusion, scaler = bundle.diffusion, bundle.scaler
|
| 239 |
+
init_info = {"init": a.init}
|
| 240 |
+
if a.init == "random":
|
| 241 |
+
from pbisc_sdd.model import ConditionalSBDDenoiser
|
| 242 |
+
torch.manual_seed(a.init_seed)
|
| 243 |
+
fresh = ConditionalSBDDenoiser(diffusion.denoiser.config)
|
| 244 |
+
diffusion.denoiser.load_state_dict(fresh.state_dict(), strict=True)
|
| 245 |
+
torch.manual_seed(a.seed)
|
| 246 |
+
init_info.update({"init_seed": a.init_seed, "n_tensors": len(fresh.state_dict()),
|
| 247 |
+
"kept_from_checkpoint": ["model_config", "diffusion_config", "gene panel", "value_scaler",
|
| 248 |
+
"conditioner z-score constants"]})
|
| 249 |
+
del fresh
|
| 250 |
+
log(f"random init of every denoiser weight (seed {a.init_seed}); no pretrained weights used")
|
| 251 |
+
ext = SS.load_conditions(a.condition_npz, bundle, default_cells_per_bulk=1)
|
| 252 |
+
folds = pd.read_csv(a.dataset_dir / "folds.csv")
|
| 253 |
+
if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), ext.sample_ids.astype(str)):
|
| 254 |
+
raise SystemExit("condition NPZ rows differ from folds.csv")
|
| 255 |
+
test_rows = folds.index[folds["fold"] == a.fold].to_numpy()
|
| 256 |
+
inner_rows = folds.index[folds[f"inner_val_f{a.fold}"]].to_numpy()
|
| 257 |
+
# fold -1 marks rows excluded by the pairing identity checks: never trained on, never tested
|
| 258 |
+
train_rows = folds.index[(folds["fold"] != a.fold) & (folds["fold"] >= 0)
|
| 259 |
+
& ~folds[f"inner_val_f{a.fold}"]].to_numpy()
|
| 260 |
+
subset_info = None
|
| 261 |
+
if a.train_n:
|
| 262 |
+
# learning curve: keep a stratified, nested subset of the training donors (inner-validation and test
|
| 263 |
+
# rows unchanged). Each stratum is permuted once by --subset-seed, so smaller subsets are prefixes of
|
| 264 |
+
# larger ones; allocation is proportional to stratum size with at least one donor per stratum.
|
| 265 |
+
grp = folds.loc[train_rows, "group"].astype(str)
|
| 266 |
+
strata = (grp.str.contains(a.strata_regex, regex=True) if a.strata_regex
|
| 267 |
+
else pd.Series(True, index=grp.index)).to_numpy()
|
| 268 |
+
srng = np.random.default_rng(a.subset_seed)
|
| 269 |
+
labels = sorted(set(strata.tolist()))
|
| 270 |
+
perm = {s: train_rows[strata == s][srng.permutation(int((strata == s).sum()))] for s in labels}
|
| 271 |
+
n = min(int(a.train_n), len(train_rows))
|
| 272 |
+
sizes = {s: len(perm[s]) for s in labels}
|
| 273 |
+
alloc = {s: max(1, int(np.floor(n * sizes[s] / len(train_rows)))) for s in labels}
|
| 274 |
+
while sum(alloc.values()) < n:
|
| 275 |
+
s = max(labels, key=lambda s: n * sizes[s] / len(train_rows) - alloc[s])
|
| 276 |
+
alloc[s] += 1
|
| 277 |
+
while sum(alloc.values()) > n:
|
| 278 |
+
s = max((s for s in labels if alloc[s] > 1), key=lambda s: alloc[s])
|
| 279 |
+
alloc[s] -= 1
|
| 280 |
+
train_rows = np.sort(np.concatenate([perm[s][:alloc[s]] for s in labels]))
|
| 281 |
+
subset_info = {"train_n": int(n), "subset_seed": a.subset_seed, "strata_regex": a.strata_regex,
|
| 282 |
+
"allocation": {str(k): int(v) for k, v in alloc.items()}}
|
| 283 |
+
if set(test_rows) & (set(inner_rows) | set(train_rows)):
|
| 284 |
+
raise SystemExit("test rows overlap training rows")
|
| 285 |
+
if set(folds.loc[test_rows, "donor_id"]) & set(folds.loc[np.r_[train_rows, inner_rows], "donor_id"]):
|
| 286 |
+
raise SystemExit("a test donor also appears in training")
|
| 287 |
+
|
| 288 |
+
cells = Cells(a.dataset_dir / "cells_panel6k.npz", bundle.gene_ids)
|
| 289 |
+
z = np.load(a.dataset_dir / "cells_panel6k.npz", allow_pickle=False)
|
| 290 |
+
panel_measured = z["panel_measured"].astype(bool)
|
| 291 |
+
if not np.array_equal(panel_measured, ext.output_availability_mask.astype(bool)):
|
| 292 |
+
raise SystemExit("cells' measured panel differs from the condition NPZ output_availability_mask")
|
| 293 |
+
|
| 294 |
+
base = torch.from_numpy(ext.base_conditions.astype(np.float32)).to(device)
|
| 295 |
+
bulk_frac = torch.from_numpy(ext.bulk_measurement_fraction.astype(np.float32)).to(device)
|
| 296 |
+
avail_rows = torch.from_numpy(ext.output_availability_mask.astype(bool)).to(device)
|
| 297 |
+
cond_rows = condition_with_measurement_context(base, bulk_frac, avail_rows) # [rows, condition_dim]
|
| 298 |
+
|
| 299 |
+
# --- augmentation 1: the same real bulk presented at several recipe sizes K (per-cell depth kept) -------------
|
| 300 |
+
multi_k = [int(x) for x in a.multi_k.split(",") if x] if a.multi_k else []
|
| 301 |
+
cond_multi = None
|
| 302 |
+
if multi_k:
|
| 303 |
+
with np.load(a.condition_npz, allow_pickle=False) as z:
|
| 304 |
+
bulk_counts = np.asarray(z["bulk_counts"], dtype=np.float64)
|
| 305 |
+
k0 = np.asarray(z["recipe_k"], dtype=np.float64).reshape(-1)
|
| 306 |
+
stacks = []
|
| 307 |
+
for K in multi_k:
|
| 308 |
+
# the loader's arithmetic: float32 counts -> log1p -> conditioner.transform(row, K)
|
| 309 |
+
b = np.stack([bundle.conditioner.transform(
|
| 310 |
+
np.log1p(np.asarray(bulk_counts[r] * (K / k0[r]), dtype=np.float32)).astype(np.float32), int(K))
|
| 311 |
+
for r in range(bulk_counts.shape[0])]).astype(np.float32)
|
| 312 |
+
stacks.append(condition_with_measurement_context(torch.from_numpy(b).to(device), bulk_frac, avail_rows))
|
| 313 |
+
cond_multi = torch.stack(stacks) # [nK, rows, condition_dim]
|
| 314 |
+
for i, K in enumerate(multi_k):
|
| 315 |
+
if bool((k0 == K).all()) and not torch.allclose(cond_multi[i], cond_rows, atol=1e-5):
|
| 316 |
+
raise SystemExit(f"multi-K condition at K={K} differs from the loader's condition")
|
| 317 |
+
|
| 318 |
+
# --- augmentation 2: pretraining-style recipes from the training donors' own cells -----------------------------
|
| 319 |
+
recipe_grid = [int(x) for x in a.recipe_k_grid.split(",") if x]
|
| 320 |
+
n_rec = int(round(a.recipe_frac * a.batch_size)) if a.recipe_frac > 0 else 0
|
| 321 |
+
full = sc_valid_full = None
|
| 322 |
+
if n_rec:
|
| 323 |
+
import scipy.sparse as sp
|
| 324 |
+
zf = np.load(a.dataset_dir / "cells_full.npz", allow_pickle=False)
|
| 325 |
+
if not np.array_equal(zf["row_sample"].astype(np.int64), cells.row_sample):
|
| 326 |
+
raise SystemExit("cells_full.npz rows differ from cells_panel6k.npz rows")
|
| 327 |
+
full = sp.csr_matrix((zf["data"], zf["indices"], zf["indptr"]), shape=tuple(zf["shape"]))
|
| 328 |
+
with np.load(a.dataset_dir / "features.npz", allow_pickle=False) as fz:
|
| 329 |
+
sc_valid_full = fz["sc_valid"].astype(bool)
|
| 330 |
+
if full.shape[1] != sc_valid_full.shape[1]:
|
| 331 |
+
raise SystemExit("cells_full gene axis differs from features.npz")
|
| 332 |
+
recipe_rows = np.asarray([r for r in train_rows if cells.count[r] >= min(recipe_grid)], dtype=np.int64)
|
| 333 |
+
if recipe_rows.size == 0:
|
| 334 |
+
raise SystemExit("no training donor has enough cells for the smallest recipe size")
|
| 335 |
+
panel_pos = np.asarray(bundle.panel_positions, dtype=np.int64)
|
| 336 |
+
|
| 337 |
+
def draw_recipe():
|
| 338 |
+
"""One recipe: K cells of one training donor; condition = their pseudobulk at recipe size K, as in pretraining."""
|
| 339 |
+
d = int(recipe_rows[rng.integers(0, recipe_rows.size)])
|
| 340 |
+
ks = [k for k in recipe_grid if k <= cells.count[d]]
|
| 341 |
+
K = int(ks[rng.integers(0, len(ks))])
|
| 342 |
+
idx = cells.start[d] + np.sort(rng.choice(int(cells.count[d]), size=K, replace=False))
|
| 343 |
+
pb = np.asarray(full[idx].sum(axis=0), dtype=np.float32).ravel()
|
| 344 |
+
b = bundle.conditioner.transform(np.log1p(pb).astype(np.float32), K).astype(np.float32)
|
| 345 |
+
frac = torch.from_numpy(sc_valid_full[d][panel_pos].astype(np.float32)).to(device)[None]
|
| 346 |
+
c = condition_with_measurement_context(torch.from_numpy(b).to(device)[None], frac, avail_rows[d][None])
|
| 347 |
+
tgt = rng.choice(idx, size=n_rec, replace=K < n_rec)
|
| 348 |
+
return d, tgt, c, K
|
| 349 |
+
|
| 350 |
+
denoiser = diffusion.denoiser
|
| 351 |
+
info = set_trainable(denoiser, a.mode, a.lora_rank, a.lora_alpha)
|
| 352 |
+
params = [p for p in denoiser.parameters() if p.requires_grad]
|
| 353 |
+
named = [(n, p) for n, p in denoiser.named_parameters() if p.requires_grad]
|
| 354 |
+
opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
|
| 355 |
+
ema = {n: p.detach().clone() for n, p in named}
|
| 356 |
+
log(f"mode={a.mode} trainable={info['n_trainable']:,} rows train/inner/test="
|
| 357 |
+
f"{len(train_rows)}/{len(inner_rows)}/{len(test_rows)} cells(train)={int(cells.count[train_rows].sum()):,}")
|
| 358 |
+
|
| 359 |
+
# fixed inner-validation draws
|
| 360 |
+
vrng = np.random.default_rng(a.seed + 1)
|
| 361 |
+
val_cells, val_rows = [], []
|
| 362 |
+
for r in inner_rows:
|
| 363 |
+
n = int(cells.count[r])
|
| 364 |
+
take = min(a.val_cells_per_row, n)
|
| 365 |
+
pick = cells.start[r] + np.sort(vrng.choice(n, size=take, replace=False))
|
| 366 |
+
val_cells.append(pick)
|
| 367 |
+
val_rows.append(np.full(take, r))
|
| 368 |
+
val_cells = np.concatenate(val_cells) if val_cells else np.zeros(0, np.int64)
|
| 369 |
+
val_rows = np.concatenate(val_rows) if val_rows else np.zeros(0, np.int64)
|
| 370 |
+
|
| 371 |
+
def to_batch(r: np.ndarray, c: np.ndarray):
|
| 372 |
+
x_log = torch.from_numpy(np.log1p(cells.dense(c))).to(device)
|
| 373 |
+
rr = torch.from_numpy(r).to(device)
|
| 374 |
+
availability = avail_rows[rr]
|
| 375 |
+
return scaler.to_unit_tensor(x_log), cond_rows[rr], availability, x_log > 0
|
| 376 |
+
|
| 377 |
+
def swap_in_ema() -> dict:
|
| 378 |
+
backup = {n: p.detach().clone() for n, p in named}
|
| 379 |
+
with torch.no_grad():
|
| 380 |
+
for n, p in named:
|
| 381 |
+
p.copy_(ema[n])
|
| 382 |
+
return backup
|
| 383 |
+
|
| 384 |
+
def restore(backup: dict) -> None:
|
| 385 |
+
with torch.no_grad():
|
| 386 |
+
for n, p in named:
|
| 387 |
+
p.copy_(backup[n])
|
| 388 |
+
|
| 389 |
+
@torch.no_grad()
|
| 390 |
+
def val_loss() -> float:
|
| 391 |
+
if len(val_cells) == 0:
|
| 392 |
+
return float("nan")
|
| 393 |
+
diffusion.eval()
|
| 394 |
+
tot, n = 0.0, 0
|
| 395 |
+
for rep in range(a.val_repeats):
|
| 396 |
+
for i in range(0, len(val_cells), a.batch_size):
|
| 397 |
+
g = torch.Generator(device=device).manual_seed(a.seed + 1_000_003 * rep + i)
|
| 398 |
+
v, c, m, act = to_batch(val_rows[i:i + a.batch_size], val_cells[i:i + a.batch_size])
|
| 399 |
+
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 400 |
+
res = diffusion.training_loss(v, c, availability_mask=m, active_target=act, generator=g)
|
| 401 |
+
tot += float(res.loss) * v.shape[0]
|
| 402 |
+
n += v.shape[0]
|
| 403 |
+
diffusion.train()
|
| 404 |
+
return tot / max(n, 1)
|
| 405 |
+
|
| 406 |
+
history = []
|
| 407 |
+
best = {"loss": val_loss(), "step": 0}
|
| 408 |
+
best_state = {n: t.detach().cpu().clone() for n, t in ema.items()}
|
| 409 |
+
history.append({"step": 0, "inner_val_loss": best["loss"], "train_loss": None})
|
| 410 |
+
log(f"step 0 inner-val loss {best['loss']:.5f} ({'pretrained' if a.init == 'pretrained' else 'random init'})")
|
| 411 |
+
gen = torch.Generator(device=device).manual_seed(a.seed + 7)
|
| 412 |
+
diffusion.train()
|
| 413 |
+
t0 = time.time()
|
| 414 |
+
run_loss, run_n, bad = 0.0, 0, 0
|
| 415 |
+
max_steps = 20 if a.smoke else a.max_steps
|
| 416 |
+
eval_every = 5 if a.smoke else a.eval_every
|
| 417 |
+
step = 0
|
| 418 |
+
for step in range(1, max_steps + 1):
|
| 419 |
+
for gparam in opt.param_groups:
|
| 420 |
+
gparam["lr"] = a.lr * min(1.0, step / max(1, a.warmup))
|
| 421 |
+
r, c = draw_batch(cells, train_rows, a.batch_size - n_rec, rng)
|
| 422 |
+
v, cond, m, act = to_batch(r, c)
|
| 423 |
+
if cond_multi is not None:
|
| 424 |
+
kidx = torch.from_numpy(rng.integers(0, len(multi_k), size=len(r))).to(device)
|
| 425 |
+
cond = cond_multi[kidx, torch.from_numpy(r).to(device)]
|
| 426 |
+
if n_rec:
|
| 427 |
+
d_r, tgt, c_r, _k = draw_recipe()
|
| 428 |
+
x_log_r = torch.from_numpy(np.log1p(cells.dense(tgt))).to(device)
|
| 429 |
+
v = torch.cat([v, scaler.to_unit_tensor(x_log_r)])
|
| 430 |
+
cond = torch.cat([cond, c_r.expand(n_rec, -1)])
|
| 431 |
+
m = torch.cat([m, avail_rows[d_r][None].expand(n_rec, -1)])
|
| 432 |
+
act = torch.cat([act, x_log_r > 0])
|
| 433 |
+
opt.zero_grad(set_to_none=True)
|
| 434 |
+
with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
|
| 435 |
+
res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=gen)
|
| 436 |
+
if not bool(torch.isfinite(res.loss)):
|
| 437 |
+
raise FloatingPointError(f"non-finite loss at step {step}")
|
| 438 |
+
res.loss.backward()
|
| 439 |
+
norm = nn.utils.clip_grad_norm_(params, 5.0)
|
| 440 |
+
if not bool(torch.isfinite(norm)):
|
| 441 |
+
raise FloatingPointError(f"non-finite grad norm at step {step}")
|
| 442 |
+
opt.step()
|
| 443 |
+
with torch.no_grad():
|
| 444 |
+
for n_, p in named:
|
| 445 |
+
ema[n_].lerp_(p.detach(), 1.0 - a.ema_decay)
|
| 446 |
+
run_loss += float(res.loss.detach())
|
| 447 |
+
run_n += 1
|
| 448 |
+
if step % eval_every == 0:
|
| 449 |
+
backup = swap_in_ema()
|
| 450 |
+
vl = val_loss()
|
| 451 |
+
restore(backup)
|
| 452 |
+
rec = {"step": step, "inner_val_loss": vl, "train_loss": run_loss / run_n,
|
| 453 |
+
"sec": round(time.time() - t0, 1)}
|
| 454 |
+
history.append(rec)
|
| 455 |
+
run_loss, run_n = 0.0, 0
|
| 456 |
+
if vl < best["loss"] - 1e-6:
|
| 457 |
+
best = {"loss": vl, "step": step}
|
| 458 |
+
best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
|
| 459 |
+
bad = 0
|
| 460 |
+
else:
|
| 461 |
+
bad += 1
|
| 462 |
+
log(f"step {step} train {rec['train_loss']:.5f} inner-val {vl:.5f} best {best['loss']:.5f}@{best['step']} "
|
| 463 |
+
f"({rec['sec']:.0f}s)")
|
| 464 |
+
(a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
|
| 465 |
+
if bad >= a.patience:
|
| 466 |
+
log(f"early stop: no improvement in {a.patience} evaluations")
|
| 467 |
+
break
|
| 468 |
+
|
| 469 |
+
# load the selected EMA state, merge LoRA, save a self-contained checkpoint
|
| 470 |
+
with torch.no_grad():
|
| 471 |
+
for n_, p in named:
|
| 472 |
+
p.copy_(best_state[n_].to(device))
|
| 473 |
+
if a.mode == "lora":
|
| 474 |
+
merge_lora(denoiser)
|
| 475 |
+
state = {k: v.detach().cpu().clone() for k, v in denoiser.state_dict().items()}
|
| 476 |
+
payload_in = SS._load_checkpoint_cpu(a.checkpoint)
|
| 477 |
+
ref_state = payload_in["ema_state"]["model_state"]
|
| 478 |
+
if set(ref_state.keys()) != set(state.keys()):
|
| 479 |
+
raise SystemExit("fine-tuned state keys differ from the checkpoint's")
|
| 480 |
+
changed = {k: float((state[k].float() - ref_state[k].float()).abs().max()) for k in state}
|
| 481 |
+
out = {k: payload_in[k] for k in KEEP_KEYS if k in payload_in}
|
| 482 |
+
out["model_state"] = state
|
| 483 |
+
out["ema_state"] = {"model_state": state}
|
| 484 |
+
ft_meta = {
|
| 485 |
+
"schema": SCHEMA, "source_checkpoint": str(a.checkpoint), "source_checkpoint_sha256": got,
|
| 486 |
+
"dataset_dir": str(a.dataset_dir), "condition_npz": str(a.condition_npz),
|
| 487 |
+
"condition_npz_sha256": ext.input_sha256, "fold": a.fold, "mode": a.mode, "trainable": info,
|
| 488 |
+
"lr": a.lr, "warmup": a.warmup, "batch_size": a.batch_size, "ema_decay": a.ema_decay,
|
| 489 |
+
"max_steps": max_steps, "steps_run": step, "eval_every": eval_every, "patience": a.patience,
|
| 490 |
+
"train_subset": subset_info, **init_info,
|
| 491 |
+
"augmentation": {"multi_k": multi_k, "recipe_frac": a.recipe_frac, "recipe_cells_per_step": n_rec,
|
| 492 |
+
"recipe_k_grid": recipe_grid if n_rec else None},
|
| 493 |
+
"selected_step": best["step"], "selected_inner_val_loss": best["loss"],
|
| 494 |
+
"pretrained_inner_val_loss": history[0]["inner_val_loss"],
|
| 495 |
+
"train_rows": [str(x) for x in folds.loc[train_rows, "sample_id"]],
|
| 496 |
+
"inner_val_rows": [str(x) for x in folds.loc[inner_rows, "sample_id"]],
|
| 497 |
+
"test_rows_never_loaded_for_training": [str(x) for x in folds.loc[test_rows, "sample_id"]],
|
| 498 |
+
"max_abs_weight_change": max(changed.values()),
|
| 499 |
+
"n_tensors_changed": int(sum(v > 0 for v in changed.values())),
|
| 500 |
+
"seed": a.seed, "wall_seconds": round(time.time() - t0, 1),
|
| 501 |
+
"written_utc": datetime.now(timezone.utc).isoformat(),
|
| 502 |
+
}
|
| 503 |
+
out["finetune"] = ft_meta
|
| 504 |
+
tmp = a.out_dir / "checkpoint_ft.pt.tmp"
|
| 505 |
+
torch.save(out, tmp)
|
| 506 |
+
os.replace(tmp, done)
|
| 507 |
+
ft_meta["checkpoint_sha256"] = sha256_file(done)
|
| 508 |
+
# reload through the sampler's own restore path and compare one forward pass
|
| 509 |
+
check = SS.restore_standalone(done, device=torch.device("cpu"), weights="ema", conditioner_source="embedded")
|
| 510 |
+
ref = SS.restore_standalone(done, device=torch.device("cpu"), weights="raw", conditioner_source="embedded")
|
| 511 |
+
xs = torch.randn(4, check.diffusion.state_dim, generator=torch.Generator().manual_seed(0))
|
| 512 |
+
tt = torch.full((4,), 0.5)
|
| 513 |
+
cc = cond_rows[torch.from_numpy(train_rows[:1]).to(device)].repeat(4, 1).float().cpu()
|
| 514 |
+
denoiser_cpu = denoiser.to("cpu").float().eval()
|
| 515 |
+
with torch.no_grad():
|
| 516 |
+
o1 = check.diffusion.denoiser(xs, tt, cc).value_prediction
|
| 517 |
+
o2 = denoiser_cpu(xs, tt, cc).value_prediction
|
| 518 |
+
o3 = ref.diffusion.denoiser(xs, tt, cc).value_prediction
|
| 519 |
+
ft_meta["reload_forward_max_abs_diff"] = float(max((o1 - o2).abs().max(), (o1 - o3).abs().max()))
|
| 520 |
+
if ft_meta["reload_forward_max_abs_diff"] > 1e-4:
|
| 521 |
+
raise SystemExit(f"reloaded checkpoint differs: {ft_meta['reload_forward_max_abs_diff']}")
|
| 522 |
+
(a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
|
| 523 |
+
(a.out_dir / "RUN.json").write_text(json.dumps(ft_meta, indent=1))
|
| 524 |
+
log(f"saved {done} (selected step {best['step']}, inner-val {best['loss']:.5f} vs pretrained "
|
| 525 |
+
f"{history[0]['inner_val_loss']:.5f}); sha {ft_meta['checkpoint_sha256'][:12]}")
|
| 526 |
+
return 0
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
if __name__ == "__main__":
|
| 530 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/run_queue_aug.sh
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Run a fine-tuning benchmark queue on this host's GPU, one step at a time.
|
| 3 |
+
# train|RUN_DIR|CONDITION_NPZ|FOLD|MODE|LR[|extra ft_sdd.py args ...]
|
| 4 |
+
# sample|TAG|CKPT (path, or "base")|CONDITION_NPZ|SEED|OUTPUT_NPZ
|
| 5 |
+
# A train step is skipped when RUN_DIR/RUN.json exists; a sample step is skipped by sample_queue.sh when its
|
| 6 |
+
# receipt and output exist. A sample step whose CKPT is a fine-tuned run waits for that run's RUN.json and takes
|
| 7 |
+
# the checkpoint sha from it. Every GPU step goes through ml-run (ml.slice, shared GPU lock) after the thermal
|
| 8 |
+
# gate and gpu_usable.sh, the same gates sample_queue.sh uses.
|
| 9 |
+
# env: QUEUE (required), DATASET_DIR (required), MAX_WAIT_H (24)
|
| 10 |
+
# GATE=thermal (2026-10-05): only the thermal gate before a step; ml-run then waits in the shared-lock flock
|
| 11 |
+
# while another job (e.g. the scSemi queue, which re-takes the lock seconds after each chunk) holds the GPU, so
|
| 12 |
+
# the two queues interleave instead of this one polling for a free lock. Default: thermal + gpu_usable.sh.
|
| 13 |
+
set -uo pipefail
|
| 14 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 15 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 16 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 17 |
+
TASK=$M8/plans/paired_finetune_intradataset_20260927
|
| 18 |
+
SQ=$M8/plans/utility_studies_final6k_20260925/tools/sample_queue.sh
|
| 19 |
+
BASE_CKPT=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
|
| 20 |
+
BASE_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
|
| 21 |
+
PY=/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python
|
| 22 |
+
QUEUE="${QUEUE:?QUEUE}"; DATASET_DIR="${DATASET_DIR:?DATASET_DIR}"; MAX_WAIT_H="${MAX_WAIT_H:-24}"
|
| 23 |
+
mkdir -p "$TASK/logs"
|
| 24 |
+
LOG=$TASK/logs/run_queue_$(basename "$QUEUE" .txt)_$(date +%Y%m%dT%H%M%S).log
|
| 25 |
+
log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
|
| 26 |
+
start=$(date +%s)
|
| 27 |
+
GATE="${GATE:-default}"
|
| 28 |
+
gate() {
|
| 29 |
+
if [[ $GATE == thermal ]]; then
|
| 30 |
+
until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh"); do
|
| 31 |
+
(( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: thermal gate not passed within ${MAX_WAIT_H} h"; exit 1; }
|
| 32 |
+
sleep 60
|
| 33 |
+
done
|
| 34 |
+
echo "$verdict; GPU via ml-run flock"
|
| 35 |
+
return
|
| 36 |
+
fi
|
| 37 |
+
until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh") \
|
| 38 |
+
&& usable=$(bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh" 2>/dev/null); do
|
| 39 |
+
(( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
|
| 40 |
+
sleep 120
|
| 41 |
+
done
|
| 42 |
+
echo "$verdict; GPU $usable"
|
| 43 |
+
}
|
| 44 |
+
n_fail=0
|
| 45 |
+
while IFS= read -r line; do
|
| 46 |
+
[[ -z "${line// }" || "$line" == \#* ]] && continue
|
| 47 |
+
IFS='|' read -r kind rest <<< "$line"
|
| 48 |
+
if [[ $kind == train ]]; then
|
| 49 |
+
IFS='|' read -r _ run cond fold mode lr extra <<< "$line"
|
| 50 |
+
if [[ -s "$run/RUN.json" ]]; then log "train $run done already; skipped"; continue; fi
|
| 51 |
+
mkdir -p "$run"
|
| 52 |
+
log "--- train $(basename "$(dirname "$run")")/$(basename "$run") mode=$mode lr=$lr ($(gate))"
|
| 53 |
+
# shellcheck disable=SC2086
|
| 54 |
+
if "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 55 |
+
OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$TASK/tools/ft_sdd_aug.py" --checkpoint "$BASE_CKPT" \
|
| 56 |
+
--checkpoint-sha "$BASE_SHA" --dataset-dir "$DATASET_DIR" --condition-npz "$cond" --fold "$fold" \
|
| 57 |
+
--mode "$mode" --lr "$lr" --out-dir "$run" ${extra//|/ } >> "$run/train.log" 2>&1; then
|
| 58 |
+
log "train $run done: $(python3 -c "import json;d=json.load(open('$run/RUN.json'));print('step',d['selected_step'],'val %.5f (pre %.5f)'%(d['selected_inner_val_loss'],d['pretrained_inner_val_loss']),d['checkpoint_sha256'][:12])")"
|
| 59 |
+
else
|
| 60 |
+
n_fail=$((n_fail+1)); log "WARN: train $run failed (see $run/train.log)"
|
| 61 |
+
fi
|
| 62 |
+
elif [[ $kind == sample ]]; then
|
| 63 |
+
IFS='|' read -r _ tag ckpt cond seed out <<< "$line"
|
| 64 |
+
if [[ $ckpt == base ]]; then ck=$BASE_CKPT; sha=$BASE_SHA
|
| 65 |
+
else
|
| 66 |
+
rj=$(dirname "$ckpt")/RUN.json
|
| 67 |
+
[[ -s $rj ]] || { log "WARN: $tag: $rj missing (training failed?); skipped"; n_fail=$((n_fail+1)); continue; }
|
| 68 |
+
ck=$ckpt; sha=$(python3 -c "import json;print(json.load(open('$rj'))['checkpoint_sha256'])")
|
| 69 |
+
fi
|
| 70 |
+
q=$(mktemp "$TASK/logs/q_${tag}_XXXX.txt"); echo "$tag|$cond|$seed|$out" > "$q"
|
| 71 |
+
CKPT=$ck CKPT_SHA=$sha QUEUE=$q MAX_WAIT_H=$MAX_WAIT_H bash "$SQ" >> "$LOG" 2>&1 || { n_fail=$((n_fail+1)); log "WARN: sample $tag failed"; }
|
| 72 |
+
rm -f "$q"
|
| 73 |
+
[[ -s ${out%.npz}.log ]] && log "sample $tag done"
|
| 74 |
+
else
|
| 75 |
+
log "WARN: unknown line: $line"
|
| 76 |
+
fi
|
| 77 |
+
done < "$QUEUE"
|
| 78 |
+
log "queue finished: failed=$n_fail"
|
| 79 |
+
(( n_fail == 0 ))
|
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/score_scratch.sh
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# No-pretraining ablation (2026-10-05): score the finished --init random fold-0 arms of ye2026_sepsis together with the
|
| 3 |
+
# fold-0 comparison arms in ONE score_ft.py call (same scorer version, same 17 test donors, same reference view and
|
| 4 |
+
# contrast; the comparison arms' fold-0 scores predate the DEG score). Comparison NPZs live on spark-0110; pass a
|
| 5 |
+
# local staging dir holding sha-checked copies plus their generation receipts (<arm>.npz + <arm>.log).
|
| 6 |
+
# usage: score_scratch.sh STAGING_DIR -> scores/ye2026_sepsis/fold0_scratch_20261005/
|
| 7 |
+
set -euo pipefail
|
| 8 |
+
TASK=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
|
| 9 |
+
PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
|
| 10 |
+
STAGE=$1
|
| 11 |
+
G=$TASK/generated/ye2026_sepsis/fold0
|
| 12 |
+
OUT=$TASK/scores/ye2026_sepsis/fold0_scratch_20261005
|
| 13 |
+
args=()
|
| 14 |
+
for a in zs__raw lora_n5__raw real_lora__raw lora_recipe__raw real_full__raw; do
|
| 15 |
+
[[ -s $STAGE/$a.npz && -s $STAGE/$a.log ]] || { echo "missing staged $a"; exit 2; }
|
| 16 |
+
args+=(--arm "$a=$STAGE/$a.npz")
|
| 17 |
+
done
|
| 18 |
+
for a in scratch_full__raw scratch_n5__raw scratch_recipe__raw; do
|
| 19 |
+
[[ -s $G/$a.npz && -s $G/$a.log ]] && grep -q '"output_sha256"' "$G/$a.log" && args+=(--arm "$a=$G/$a.npz") \
|
| 20 |
+
|| echo "not finished yet: $a"
|
| 21 |
+
done
|
| 22 |
+
read -r -a cargs <<< "$(bash "$TASK/tools/contrast_args.sh" ye2026_sepsis)"
|
| 23 |
+
mkdir -p "$OUT"
|
| 24 |
+
echo "scoring ${#args[@]} arg(s) -> $OUT"
|
| 25 |
+
bash "$TASK/tools/run_unit.sh" "score-sepsis-f0-scratch" 8 "$PY" "$TASK/tools/score_ft.py" --dataset ye2026_sepsis \
|
| 26 |
+
--out "$OUT" --threads 8 "${args[@]}" "${cargs[@]}"
|
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/utility_studies_final6k_20260925/tools/sample_queue.sh
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Sample a list of condition sets from the final model (0.1%-floor 6k panel, 1x, part 16) one after
|
| 3 |
+
# another on this host's GPU. Every set uses the same checkpoint, sampler, step count and read-out;
|
| 4 |
+
# a set differs from the others only in its condition NPZ and seed, both written in the queue file.
|
| 5 |
+
#
|
| 6 |
+
# MOVE_TO_REMOTE: optional ssh host; each finished NPZ + receipt is copied to the same path there and the local NPZ
|
| 7 |
+
# is deleted only after the remote sha256 equals the receipt (a .moved marker is left locally)
|
| 8 |
+
# OVERRIDE_CELLS: optional, cells generated per bulk for every set of the queue (cells are drawn independently,
|
| 9 |
+
# so this changes precision, not the distribution)
|
| 10 |
+
# Queue file: one set per line, "tag|condition_npz|seed|output_npz"; blank lines and # comments skipped.
|
| 11 |
+
# A set whose output NPZ and receipt already exist is skipped, so a rerun resumes where it stopped.
|
| 12 |
+
# Every GPU step goes through ml-run and waits for gpu_usable.sh and the thermal gate first.
|
| 13 |
+
#
|
| 14 |
+
# env: QUEUE (required), CKPT (default: final 6k part 16), CKPT_SHA (checked before any sampling),
|
| 15 |
+
# STEPS (50), READOUT (bernoulli), THR (0.0), MAX_WAIT_H (24)
|
| 16 |
+
# GATE=thermal (2026-10-05): thermal gate only; ml-run then waits in the shared-lock flock while another job
|
| 17 |
+
# holds the GPU (interleaves with a queue that re-takes the lock between chunks). Default: + gpu_usable.sh.
|
| 18 |
+
set -uo pipefail
|
| 19 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 20 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 21 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 22 |
+
PLAN=$M8/plans/utility_studies_final6k_20260925
|
| 23 |
+
QUEUE="${QUEUE:?QUEUE}"
|
| 24 |
+
CKPT="${CKPT:-$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt}"
|
| 25 |
+
CKPT_SHA="${CKPT_SHA:-8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633}"
|
| 26 |
+
STEPS="${STEPS:-50}"; READOUT="${READOUT:-bernoulli}"; THR="${THR:-0.0}"; MAX_WAIT_H="${MAX_WAIT_H:-24}"
|
| 27 |
+
for cand in /home/sj_server_2/miniforge3/envs/b2sc-infer/bin/python \
|
| 28 |
+
/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python; do
|
| 29 |
+
[[ -x "$cand" ]] && { PY=$cand; break; }
|
| 30 |
+
done
|
| 31 |
+
mkdir -p "$PLAN/logs"
|
| 32 |
+
LOG=$PLAN/logs/sample_queue_$(basename "$QUEUE" .txt)_$(hostname -s)_$(date +%Y%m%dT%H%M%S).log
|
| 33 |
+
log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
|
| 34 |
+
start=$(date +%s)
|
| 35 |
+
|
| 36 |
+
[[ -s "$CKPT" ]] || { log "ABORT: checkpoint missing: $CKPT"; exit 1; }
|
| 37 |
+
got=$(sha256sum "$CKPT" | cut -d' ' -f1)
|
| 38 |
+
[[ "$got" == "$CKPT_SHA" ]] || { log "ABORT: checkpoint sha ${got:0:12} != expected ${CKPT_SHA:0:12}"; exit 1; }
|
| 39 |
+
log "queue=$QUEUE ckpt=$(basename "$CKPT") sha=${got:0:12} steps=$STEPS readout=$READOUT thr=$THR py=$PY"
|
| 40 |
+
|
| 41 |
+
n_ok=0; n_fail=0
|
| 42 |
+
while IFS='|' read -r tag cond seed out; do
|
| 43 |
+
[[ -z "${tag// }" || "$tag" == \#* ]] && continue
|
| 44 |
+
rec=${out%.npz}.log; err=${out%.npz}.err
|
| 45 |
+
if [[ -s "$rec" && ( -s "$out" || -f "${out%.npz}.moved" ) ]]; then log "$tag already sampled; skipped"; continue; fi
|
| 46 |
+
[[ -s "$cond" ]] || { log "WARN: $tag condition missing: $cond"; n_fail=$((n_fail+1)); continue; }
|
| 47 |
+
mkdir -p "$(dirname "$out")"
|
| 48 |
+
until verdict=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh") \
|
| 49 |
+
&& { [[ "${GATE:-default}" == thermal ]] && usable="via ml-run flock" \
|
| 50 |
+
|| usable=$(bash "$M8/plans/arch_ablation_6k_20260913/tools/gpu_usable.sh" 2>/dev/null); }; do
|
| 51 |
+
(( $(date +%s) - start > MAX_WAIT_H * 3600 )) && { log "ABORT: no usable GPU within ${MAX_WAIT_H} h"; exit 1; }
|
| 52 |
+
sleep 120
|
| 53 |
+
done
|
| 54 |
+
log "--- $tag seed=$seed ($verdict; GPU $usable)"
|
| 55 |
+
if "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 56 |
+
PYTHONPATH="$M8/src" OMP_NUM_THREADS=4 "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
|
| 57 |
+
--checkpoint "$CKPT" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 \
|
| 58 |
+
--steps "$STEPS" --seed "$seed" --device cuda --conditioner-source embedded \
|
| 59 |
+
--active-logit-threshold "$THR" --support-readout "$READOUT" \
|
| 60 |
+
${OVERRIDE_CELLS:+--override-cells-per-bulk "$OVERRIDE_CELLS"} > "$rec" 2> "$err"; then
|
| 61 |
+
n_ok=$((n_ok+1))
|
| 62 |
+
log "$tag done: $(python3 -c "import json;d=json.load(open('$rec'));print('cells', d.get('generated_counts_rows','?'), 'zero_frac %.4f' % d.get('generated_zero_fraction',-1), d.get('output_sha256','')[:12])" 2>/dev/null || echo "see $rec")"
|
| 63 |
+
if [[ -n "${MOVE_TO_REMOTE:-}" ]]; then
|
| 64 |
+
# keep this host's disk free: copy the NPZ and its receipt to the same path on the remote host,
|
| 65 |
+
# and delete the local NPZ only when the remote sha256 equals the receipt's output_sha256
|
| 66 |
+
want=$(python3 -c "import json;print(json.load(open('$rec')).get('output_sha256',''))" 2>/dev/null)
|
| 67 |
+
ssh -n "$MOVE_TO_REMOTE" "mkdir -p '$(dirname "$out")'" && \
|
| 68 |
+
ionice -c3 rsync -a --bwlimit=200000 "$out" "$rec" "$MOVE_TO_REMOTE:$(dirname "$out")/" >> "$LOG" 2>&1
|
| 69 |
+
got=$(ssh -n "$MOVE_TO_REMOTE" "sha256sum '$out' 2>/dev/null" | cut -d' ' -f1)
|
| 70 |
+
if [[ -n "$want" && "$want" == "$got" ]]; then
|
| 71 |
+
rm -f "$out"; echo "moved to $MOVE_TO_REMOTE (sha ${got:0:12}) $(date +%FT%T)" > "${out%.npz}.moved"
|
| 72 |
+
log "$tag moved to $MOVE_TO_REMOTE, local NPZ removed (sha ${got:0:12})"
|
| 73 |
+
else
|
| 74 |
+
log "WARN: $tag remote copy sha ${got:0:12} != receipt ${want:0:12}; local NPZ kept"
|
| 75 |
+
fi
|
| 76 |
+
fi
|
| 77 |
+
else
|
| 78 |
+
n_fail=$((n_fail+1))
|
| 79 |
+
log "WARN: $tag failed (see $err); receipt removed so a rerun retries it"
|
| 80 |
+
rm -f "$rec"
|
| 81 |
+
fi
|
| 82 |
+
done < "$QUEUE"
|
| 83 |
+
log "queue finished: ok=$n_ok failed=$n_fail"
|
| 84 |
+
(( n_fail == 0 ))
|