junidude14 commited on
Commit
b98be14
·
verified ·
1 Parent(s): 2184faf

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T124345Z-trunk4x-lora-sepsis-launch/diffusion/dataset/server_1/model8/plans/trunk4x_lora_sepsis_20261013/tools/ft_sdd_frozen.py ADDED
@@ -0,0 +1,503 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fine-tune the final PBISC-SDD model inside one paired dataset fold.
3
+
4
+ Training pairs are (condition of row r, one retained cell of row r). The condition comes from a condition NPZ
5
+ written by prepare_dataset.py (real bulk or pseudobulk, fixed-depth policy) and goes through the checkpoint's own
6
+ conditioner exactly as the standalone sampler does (sample_sdd_standalone.load_conditions), then
7
+ condition_with_measurement_context(base, bulk_measurement_fraction, output_availability_mask). The loss is the
8
+ pretraining loss (SparseDataDiffusion.training_loss: measured-only value L2 + support BCE, self-conditioning),
9
+ with bf16 autocast, AdamW and gradient clipping as in pretraining.
10
+
11
+ Rows: fold k's test rows are never loaded. Training rows = the other folds minus the inner-validation rows;
12
+ inner-validation rows give a fixed-draw diffusion loss every --eval-every steps, and the EMA state with the lowest
13
+ inner-validation loss is kept (early stopping with --patience evaluations).
14
+
15
+ Modes (what is trainable):
16
+ full every denoiser parameter
17
+ condenc only denoiser.condition_encoder (the bulk -> context map)
18
+ lora low-rank updates W = W0 + (alpha/r) B A on every nn.Linear of the denoiser (B starts at zero);
19
+ merged into the weights before saving
20
+
21
+ Batches are donor-balanced: a row is drawn uniformly, then one of its cells uniformly.
22
+
23
+ The output checkpoint keeps the input checkpoint's schema and self-contained keys, with model_state and
24
+ ema_state.model_state set to the selected weights, so scripts/sample_sdd_standalone.py samples it unchanged.
25
+ src/pbisc_sdd is sealed and is only imported.
26
+ """
27
+ from __future__ import annotations
28
+
29
+ import argparse
30
+ import hashlib
31
+ import json
32
+ import math
33
+ import os
34
+ import sys
35
+ import time
36
+ from datetime import datetime, timezone
37
+ from pathlib import Path
38
+
39
+ import numpy as np
40
+ import pandas as pd
41
+ import torch
42
+ from torch import nn
43
+ import torch.nn.utils.parametrize as parametrize
44
+
45
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
46
+ for p in (M8 / "src", M8 / "scripts"):
47
+ if str(p) not in sys.path:
48
+ sys.path.insert(0, str(p))
49
+ import sample_sdd_standalone as SS # noqa: E402
50
+ from pbisc_sdd.data import condition_with_measurement_context # noqa: E402
51
+
52
+ SCHEMA = "pbisc_sdd.ft_intradataset.run.v1"
53
+ KEEP_KEYS = ("schema_version", "model_config", "diffusion_config", "value_scaler", "conditioner_state",
54
+ "gene_positions", "gene_ids", "gene_symbols", "gene_measurement_coverage",
55
+ "full_gene_measurement_coverage", "corpus_fingerprint", "experiment_config", "proportion_hint",
56
+ "training_contract")
57
+
58
+
59
+ def sha256_file(path: Path) -> str:
60
+ h = hashlib.sha256()
61
+ with open(path, "rb") as f:
62
+ for block in iter(lambda: f.read(1 << 24), b""):
63
+ h.update(block)
64
+ return h.hexdigest()
65
+
66
+
67
+ def log(msg: str) -> None:
68
+ print(f"{datetime.now().isoformat(timespec='seconds')} {msg}", flush=True)
69
+
70
+
71
+ # ----------------------------------------------------------------------------------------------- LoRA
72
+ class LoRADelta(nn.Module):
73
+ """Parametrization W -> W + scale * B @ A (B zero-initialised, so the start equals the pretrained W)."""
74
+
75
+ def __init__(self, out_features: int, in_features: int, rank: int, alpha: float) -> None:
76
+ super().__init__()
77
+ self.A = nn.Parameter(torch.empty(rank, in_features))
78
+ self.B = nn.Parameter(torch.zeros(out_features, rank))
79
+ nn.init.kaiming_uniform_(self.A, a=math.sqrt(5))
80
+ self.scale = float(alpha) / float(rank)
81
+
82
+ def forward(self, weight: torch.Tensor) -> torch.Tensor:
83
+ return weight + self.scale * (self.B @ self.A).to(dtype=weight.dtype)
84
+
85
+
86
+ def add_lora(model: nn.Module, rank: int, alpha: float) -> list[str]:
87
+ names = []
88
+ for name, module in model.named_modules():
89
+ if isinstance(module, nn.Linear):
90
+ delta = LoRADelta(module.out_features, module.in_features, rank, alpha).to(
91
+ device=module.weight.device, dtype=module.weight.dtype)
92
+ parametrize.register_parametrization(module, "weight", delta)
93
+ names.append(name)
94
+ return names
95
+
96
+
97
+ def merge_lora(model: nn.Module) -> None:
98
+ for module in model.modules():
99
+ if isinstance(module, nn.Linear) and parametrize.is_parametrized(module, "weight"):
100
+ parametrize.remove_parametrizations(module, "weight", leave_parametrized=True)
101
+
102
+
103
+ def set_trainable(denoiser: nn.Module, mode: str, rank: int, alpha: float) -> dict:
104
+ for p in denoiser.parameters():
105
+ p.requires_grad_(False)
106
+ info: dict = {"mode": mode}
107
+ if mode == "full":
108
+ for p in denoiser.parameters():
109
+ p.requires_grad_(True)
110
+ elif mode == "condenc":
111
+ for p in denoiser.condition_encoder.parameters():
112
+ p.requires_grad_(True)
113
+ elif mode == "lora":
114
+ info["lora_layers"] = add_lora(denoiser, rank, alpha)
115
+ info["lora_rank"], info["lora_alpha"] = rank, alpha
116
+ for name, p in denoiser.named_parameters():
117
+ p.requires_grad_(name.endswith(".A") or name.endswith(".B"))
118
+ else:
119
+ raise SystemExit(f"unknown mode {mode}")
120
+ trainable = [n for n, p in denoiser.named_parameters() if p.requires_grad]
121
+ info["n_trainable"] = int(sum(p.numel() for p in denoiser.parameters() if p.requires_grad))
122
+ info["n_total_base"] = int(sum(p.numel() for n, p in denoiser.named_parameters()
123
+ if not (n.endswith(".A") or n.endswith(".B"))))
124
+ info["trainable_tensors"] = len(trainable)
125
+ return info
126
+
127
+
128
+ # ----------------------------------------------------------------------------------------------- data
129
+ class Cells:
130
+ """Retained cells on the 6k panel (CSR, rows sorted by dataset row)."""
131
+
132
+ def __init__(self, path: Path, panel_gene_ids: np.ndarray) -> None:
133
+ z = np.load(path, allow_pickle=False)
134
+ self.indptr = z["indptr"].astype(np.int64)
135
+ self.indices = z["indices"].astype(np.int64)
136
+ self.data = z["data"].astype(np.float32)
137
+ self.row_sample = z["row_sample"].astype(np.int64)
138
+ self.n_genes = int(z["shape"][1])
139
+ if not np.array_equal(z["panel_gene_ids"].astype(str), panel_gene_ids.astype(str)):
140
+ raise SystemExit("cells_panel6k columns differ from the checkpoint gene panel")
141
+ if bool((np.diff(self.row_sample) < 0).any()):
142
+ raise SystemExit("cells are not sorted by dataset row")
143
+ n_rows = int(self.row_sample.max()) + 1
144
+ self.start = np.searchsorted(self.row_sample, np.arange(n_rows), side="left")
145
+ self.count = np.searchsorted(self.row_sample, np.arange(n_rows), side="right") - self.start
146
+
147
+ def dense(self, cells: np.ndarray) -> np.ndarray:
148
+ s, e = self.indptr[cells], self.indptr[cells + 1]
149
+ lens = e - s
150
+ idx = np.concatenate([np.arange(a, b) for a, b in zip(s, e)]) if len(cells) else np.zeros(0, np.int64)
151
+ out = np.zeros((len(cells), self.n_genes), dtype=np.float32)
152
+ out[np.repeat(np.arange(len(cells)), lens), self.indices[idx]] = self.data[idx]
153
+ return out
154
+
155
+
156
+ def draw_batch(cells: Cells, rows: np.ndarray, batch: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
157
+ r = rows[rng.integers(0, len(rows), size=batch)]
158
+ c = cells.start[r] + np.floor(rng.random(batch) * cells.count[r]).astype(np.int64)
159
+ return r, c
160
+
161
+
162
+ # ----------------------------------------------------------------------------------------------- main
163
+ def main(argv=None) -> int:
164
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
165
+ ap.add_argument("--checkpoint", type=Path, required=True)
166
+ ap.add_argument("--checkpoint-sha", required=True)
167
+ ap.add_argument("--dataset-dir", type=Path, required=True)
168
+ ap.add_argument("--condition-npz", type=Path, required=True, help="all-row condition NPZ used for training")
169
+ ap.add_argument("--fold", type=int, required=True)
170
+ ap.add_argument("--mode", choices=("full", "condenc", "lora"), required=True)
171
+ ap.add_argument("--lora-rank", type=int, default=16)
172
+ ap.add_argument("--lora-alpha", type=float, default=16.0)
173
+ ap.add_argument("--lr", type=float, required=True)
174
+ ap.add_argument("--warmup", type=int, default=200)
175
+ ap.add_argument("--batch-size", type=int, default=256)
176
+ ap.add_argument("--max-steps", type=int, default=20000)
177
+ ap.add_argument("--eval-every", type=int, default=250)
178
+ ap.add_argument("--patience", type=int, default=8)
179
+ ap.add_argument("--ema-decay", type=float, default=0.999)
180
+ ap.add_argument("--val-cells-per-row", type=int, default=256)
181
+ ap.add_argument("--val-repeats", type=int, default=2)
182
+ ap.add_argument("--seed", type=int, default=20260927)
183
+ ap.add_argument("--out-dir", type=Path, required=True)
184
+ ap.add_argument("--device", default="cuda")
185
+ ap.add_argument("--max-cuda-gib", type=float, default=8.0)
186
+ ap.add_argument("--min-system-gib", type=float, default=32.0)
187
+ ap.add_argument("--smoke", action="store_true", help="tiny run for tests (few steps, CPU allowed)")
188
+ ap.add_argument("--train-n", type=int, default=0, help="learning curve: number of training donors to keep")
189
+ ap.add_argument("--train-donors-file", default="", help="few-pair scenario: train on these donor_ids (one per "
190
+ "line), no inner validation, every other usable row is test; --fold is ignored")
191
+ ap.add_argument("--fixed-steps", type=int, default=0, help="train exactly this many steps without inner "
192
+ "validation and keep the final EMA state (for when no pairs can be spared for early stopping)")
193
+ ap.add_argument("--subset-seed", type=int, default=0)
194
+ ap.add_argument("--strata-regex", default="", help="groups matching this regex form one stratum, the rest another")
195
+ ap.add_argument("--support-manifest", type=Path, default=None,
196
+ help="strict paired support.json: exact sample IDs, no inner validation; requires --fixed-steps 3000")
197
+ a = ap.parse_args(argv)
198
+
199
+ if a.support_manifest is not None:
200
+ if a.mode != "lora" or a.train_donors_file or a.train_n or a.fixed_steps != 3000 or a.smoke:
201
+ raise SystemExit("strict support requires LoRA, --fixed-steps 3000, no donor/subset override or smoke")
202
+ strict_tools = M8 / "plans/paper_figures_strictpairs_20261012/tools"
203
+ sys.path.insert(0, str(strict_tools))
204
+ from support_manifest import load_manifest, validate_existing_run
205
+ support_preflight = load_manifest(a.support_manifest, pd.read_csv(a.dataset_dir / "folds.csv",
206
+ dtype={"sample_id": str, "donor_id": str}))
207
+ if support_preflight["cohort"] != a.dataset_dir.name:
208
+ raise SystemExit("support cohort differs from dataset directory")
209
+ a.out_dir.mkdir(parents=True, exist_ok=True)
210
+ done = a.out_dir / "checkpoint_ft.pt"
211
+ if done.exists() and (a.out_dir / "RUN.json").exists():
212
+ if a.support_manifest is not None:
213
+ stored = json.loads((a.out_dir / "RUN.json").read_text())
214
+ validate_existing_run(support_preflight, stored, fixed_steps=a.fixed_steps,
215
+ lora_rank=a.lora_rank, source_checkpoint_sha256=a.checkpoint_sha,
216
+ condition_npz_sha256=sha256_file(a.condition_npz),
217
+ lr=a.lr, lora_alpha=a.lora_alpha, warmup=a.warmup,
218
+ batch_size=a.batch_size, ema_decay=a.ema_decay, seed=a.seed)
219
+ if sha256_file(a.checkpoint) != a.checkpoint_sha:
220
+ raise SystemExit("source checkpoint differs from requested hash")
221
+ if stored.get("checkpoint_sha256") != sha256_file(done):
222
+ raise SystemExit("existing strict checkpoint differs from RUN.json hash")
223
+ log(f"{done} exists; nothing to do")
224
+ return 0
225
+ if a.support_manifest is not None and (done.exists() or (a.out_dir / "RUN.json").exists()):
226
+ raise SystemExit("strict output is incomplete; inspect rather than overwrite")
227
+ avail = int(open("/proc/meminfo").read().split("MemAvailable:")[1].split()[0]) / 1048576
228
+ if avail < a.min_system_gib:
229
+ raise SystemExit(f"MemAvailable {avail:.1f} GiB < floor {a.min_system_gib}")
230
+ got = sha256_file(a.checkpoint)
231
+ if got != a.checkpoint_sha:
232
+ raise SystemExit(f"checkpoint sha {got[:12]} != {a.checkpoint_sha[:12]}")
233
+ cells_path = a.dataset_dir / "cells_panel6k.npz"
234
+ isolation = None
235
+ if a.support_manifest is not None:
236
+ from support_input_isolation import materialize
237
+ cells_path, isolation = materialize(a.support_manifest, dataset_dir=a.dataset_dir)
238
+ device = torch.device(a.device)
239
+ if device.type == "cuda" and device.index is None:
240
+ device = torch.device("cuda", 0)
241
+ if device.type == "cuda":
242
+ total = torch.cuda.get_device_properties(device).total_memory
243
+ torch.cuda.set_per_process_memory_fraction(min(1.0, a.max_cuda_gib * 2**30 / total), device)
244
+ torch.manual_seed(a.seed)
245
+ rng = np.random.default_rng(a.seed)
246
+
247
+ bundle = SS.restore_standalone(a.checkpoint, device=device, weights="ema", conditioner_source="embedded")
248
+ diffusion, scaler = bundle.diffusion, bundle.scaler
249
+ ext = SS.load_conditions(a.condition_npz, bundle, default_cells_per_bulk=1)
250
+ folds = pd.read_csv(a.dataset_dir / "folds.csv")
251
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), ext.sample_ids.astype(str)):
252
+ raise SystemExit("condition NPZ rows differ from folds.csv")
253
+ support = None
254
+ if a.support_manifest is not None:
255
+ from support_manifest import select_rows
256
+ support = support_preflight
257
+ train_rows, test_rows = select_rows(support, folds)
258
+ inner_rows = np.zeros(0, dtype=np.int64)
259
+ selected_visits = set(folds.loc[folds["donor_id"].astype(str).isin(support["train_donor_ids"]),
260
+ "sample_id"].astype(str))
261
+ if selected_visits - set(support["train_sample_ids"]) != set(support["excluded_sample_ids"]):
262
+ raise SystemExit("support excludes inconsistent selected-donor visits")
263
+ folds = folds.assign(fold=np.where(folds.index.isin(test_rows), 0,
264
+ np.where(folds.index.isin(train_rows), 1, -1)),
265
+ inner_val_custom=False)
266
+ a.fold = 0
267
+ inner_col = "inner_val_custom"
268
+ elif a.train_donors_file:
269
+ # few-pair deployment scenario: train on the listed donors only, no inner validation, and treat every other
270
+ # usable row (fold >= 0) as test; --fold is ignored
271
+ want = {l.strip() for l in Path(a.train_donors_file).read_text().splitlines() if l.strip()}
272
+ is_train = folds["donor_id"].astype(str).isin(want) & (folds["fold"] >= 0)
273
+ if int(folds.loc[is_train, "donor_id"].nunique()) != len(want):
274
+ raise SystemExit("some listed training donors are missing or excluded")
275
+ folds = folds.assign(fold=np.where(folds["fold"] < 0, -1, np.where(is_train, 1, 0)))
276
+ folds["inner_val_custom"] = False
277
+ a.fold = 0
278
+ inner_col = "inner_val_custom"
279
+ else:
280
+ inner_col = f"inner_val_f{a.fold}"
281
+ test_rows = folds.index[folds["fold"] == a.fold].to_numpy()
282
+ inner_rows = folds.index[folds[inner_col]].to_numpy()
283
+ # fold -1 marks rows excluded by the pairing identity checks: never trained on, never tested
284
+ train_rows = folds.index[(folds["fold"] != a.fold) & (folds["fold"] >= 0)
285
+ & ~folds[inner_col]].to_numpy()
286
+ subset_info = None
287
+ if a.train_n:
288
+ # learning curve: keep a stratified, nested subset of the training donors (inner-validation and test
289
+ # rows unchanged). Each stratum is permuted once by --subset-seed, so smaller subsets are prefixes of
290
+ # larger ones; allocation is proportional to stratum size with at least one donor per stratum.
291
+ grp = folds.loc[train_rows, "group"].astype(str)
292
+ strata = (grp.str.contains(a.strata_regex, regex=True) if a.strata_regex
293
+ else pd.Series(True, index=grp.index)).to_numpy()
294
+ srng = np.random.default_rng(a.subset_seed)
295
+ labels = sorted(set(strata.tolist()))
296
+ perm = {s: train_rows[strata == s][srng.permutation(int((strata == s).sum()))] for s in labels}
297
+ n = min(int(a.train_n), len(train_rows))
298
+ sizes = {s: len(perm[s]) for s in labels}
299
+ alloc = {s: max(1, int(np.floor(n * sizes[s] / len(train_rows)))) for s in labels}
300
+ while sum(alloc.values()) < n:
301
+ s = max(labels, key=lambda s: n * sizes[s] / len(train_rows) - alloc[s])
302
+ alloc[s] += 1
303
+ while sum(alloc.values()) > n:
304
+ s = max((s for s in labels if alloc[s] > 1), key=lambda s: alloc[s])
305
+ alloc[s] -= 1
306
+ train_rows = np.sort(np.concatenate([perm[s][:alloc[s]] for s in labels]))
307
+ subset_info = {"train_n": int(n), "subset_seed": a.subset_seed, "strata_regex": a.strata_regex,
308
+ "allocation": {str(k): int(v) for k, v in alloc.items()}}
309
+ if set(test_rows) & (set(inner_rows) | set(train_rows)):
310
+ raise SystemExit("test rows overlap training rows")
311
+ if set(folds.loc[test_rows, "donor_id"]) & set(folds.loc[np.r_[train_rows, inner_rows], "donor_id"]):
312
+ raise SystemExit("a test donor also appears in training")
313
+
314
+ cells = Cells(cells_path, bundle.gene_ids)
315
+ with np.load(cells_path, allow_pickle=False) as z:
316
+ panel_measured = z["panel_measured"].astype(bool)
317
+ if not np.array_equal(panel_measured, ext.output_availability_mask.astype(bool)):
318
+ raise SystemExit("cells' measured panel differs from the condition NPZ output_availability_mask")
319
+
320
+ base = torch.from_numpy(ext.base_conditions.astype(np.float32)).to(device)
321
+ bulk_frac = torch.from_numpy(ext.bulk_measurement_fraction.astype(np.float32)).to(device)
322
+ avail_rows = torch.from_numpy(ext.output_availability_mask.astype(bool)).to(device)
323
+ cond_rows = condition_with_measurement_context(base, bulk_frac, avail_rows) # [rows, condition_dim]
324
+
325
+ denoiser = diffusion.denoiser
326
+ info = set_trainable(denoiser, a.mode, a.lora_rank, a.lora_alpha)
327
+ params = [p for p in denoiser.parameters() if p.requires_grad]
328
+ named = [(n, p) for n, p in denoiser.named_parameters() if p.requires_grad]
329
+ opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
330
+ ema = {n: p.detach().clone() for n, p in named}
331
+ log(f"mode={a.mode} trainable={info['n_trainable']:,} rows train/inner/test="
332
+ f"{len(train_rows)}/{len(inner_rows)}/{len(test_rows)} cells(train)={int(cells.count[train_rows].sum()):,}")
333
+
334
+ # fixed inner-validation draws
335
+ vrng = np.random.default_rng(a.seed + 1)
336
+ val_cells, val_rows = [], []
337
+ for r in inner_rows:
338
+ n = int(cells.count[r])
339
+ take = min(a.val_cells_per_row, n)
340
+ pick = cells.start[r] + np.sort(vrng.choice(n, size=take, replace=False))
341
+ val_cells.append(pick)
342
+ val_rows.append(np.full(take, r))
343
+ val_cells = np.concatenate(val_cells) if val_cells else np.zeros(0, np.int64)
344
+ val_rows = np.concatenate(val_rows) if val_rows else np.zeros(0, np.int64)
345
+
346
+ def to_batch(r: np.ndarray, c: np.ndarray):
347
+ x_log = torch.from_numpy(np.log1p(cells.dense(c))).to(device)
348
+ rr = torch.from_numpy(r).to(device)
349
+ availability = avail_rows[rr]
350
+ return scaler.to_unit_tensor(x_log), cond_rows[rr], availability, x_log > 0
351
+
352
+ def swap_in_ema() -> dict:
353
+ backup = {n: p.detach().clone() for n, p in named}
354
+ with torch.no_grad():
355
+ for n, p in named:
356
+ p.copy_(ema[n])
357
+ return backup
358
+
359
+ def restore(backup: dict) -> None:
360
+ with torch.no_grad():
361
+ for n, p in named:
362
+ p.copy_(backup[n])
363
+
364
+ @torch.no_grad()
365
+ def val_loss() -> float:
366
+ if len(val_cells) == 0:
367
+ return float("nan")
368
+ diffusion.eval()
369
+ tot, n = 0.0, 0
370
+ for rep in range(a.val_repeats):
371
+ for i in range(0, len(val_cells), a.batch_size):
372
+ g = torch.Generator(device=device).manual_seed(a.seed + 1_000_003 * rep + i)
373
+ v, c, m, act = to_batch(val_rows[i:i + a.batch_size], val_cells[i:i + a.batch_size])
374
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
375
+ res = diffusion.training_loss(v, c, availability_mask=m, active_target=act, generator=g)
376
+ tot += float(res.loss) * v.shape[0]
377
+ n += v.shape[0]
378
+ diffusion.train()
379
+ return tot / max(n, 1)
380
+
381
+ history = []
382
+ best = {"loss": val_loss(), "step": 0}
383
+ best_state = {n: t.detach().cpu().clone() for n, t in ema.items()}
384
+ history.append({"step": 0, "inner_val_loss": best["loss"], "train_loss": None})
385
+ log(f"step 0 inner-val loss {best['loss']:.5f} (pretrained)")
386
+ gen = torch.Generator(device=device).manual_seed(a.seed + 7)
387
+ diffusion.train()
388
+ t0 = time.time()
389
+ run_loss, run_n, bad = 0.0, 0, 0
390
+ max_steps = 20 if a.smoke else (a.fixed_steps or a.max_steps)
391
+ eval_every = 5 if a.smoke else a.eval_every
392
+ step = 0
393
+ for step in range(1, max_steps + 1):
394
+ for gparam in opt.param_groups:
395
+ gparam["lr"] = a.lr * min(1.0, step / max(1, a.warmup))
396
+ r, c = draw_batch(cells, train_rows, a.batch_size, rng)
397
+ v, cond, m, act = to_batch(r, c)
398
+ opt.zero_grad(set_to_none=True)
399
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
400
+ res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=gen)
401
+ if not bool(torch.isfinite(res.loss)):
402
+ raise FloatingPointError(f"non-finite loss at step {step}")
403
+ res.loss.backward()
404
+ norm = nn.utils.clip_grad_norm_(params, 5.0)
405
+ if not bool(torch.isfinite(norm)):
406
+ raise FloatingPointError(f"non-finite grad norm at step {step}")
407
+ opt.step()
408
+ with torch.no_grad():
409
+ for n_, p in named:
410
+ ema[n_].lerp_(p.detach(), 1.0 - a.ema_decay)
411
+ run_loss += float(res.loss.detach())
412
+ run_n += 1
413
+ if a.fixed_steps and step == max_steps:
414
+ best = {"loss": float("nan"), "step": step}
415
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
416
+ if step % eval_every == 0 and not a.fixed_steps:
417
+ backup = swap_in_ema()
418
+ vl = val_loss()
419
+ restore(backup)
420
+ rec = {"step": step, "inner_val_loss": vl, "train_loss": run_loss / run_n,
421
+ "sec": round(time.time() - t0, 1)}
422
+ history.append(rec)
423
+ run_loss, run_n = 0.0, 0
424
+ if vl < best["loss"] - 1e-6:
425
+ best = {"loss": vl, "step": step}
426
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
427
+ bad = 0
428
+ else:
429
+ bad += 1
430
+ log(f"step {step} train {rec['train_loss']:.5f} inner-val {vl:.5f} best {best['loss']:.5f}@{best['step']} "
431
+ f"({rec['sec']:.0f}s)")
432
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
433
+ if bad >= a.patience:
434
+ log(f"early stop: no improvement in {a.patience} evaluations")
435
+ break
436
+
437
+ # load the selected EMA state, merge LoRA, save a self-contained checkpoint
438
+ with torch.no_grad():
439
+ for n_, p in named:
440
+ p.copy_(best_state[n_].to(device))
441
+ if a.mode == "lora":
442
+ merge_lora(denoiser)
443
+ state = {k: v.detach().cpu().clone() for k, v in denoiser.state_dict().items()}
444
+ payload_in = SS._load_checkpoint_cpu(a.checkpoint)
445
+ ref_state = payload_in["ema_state"]["model_state"]
446
+ if set(ref_state.keys()) != set(state.keys()):
447
+ raise SystemExit("fine-tuned state keys differ from the checkpoint's")
448
+ changed = {k: float((state[k].float() - ref_state[k].float()).abs().max()) for k in state}
449
+ out = {k: payload_in[k] for k in KEEP_KEYS if k in payload_in}
450
+ out["model_state"] = state
451
+ out["ema_state"] = {"model_state": state}
452
+ ft_meta = {
453
+ "schema": SCHEMA, "source_checkpoint": str(a.checkpoint), "source_checkpoint_sha256": got,
454
+ "dataset_dir": str(a.dataset_dir), "condition_npz": str(a.condition_npz),
455
+ "condition_npz_sha256": ext.input_sha256, "fold": a.fold, "mode": a.mode, "trainable": info,
456
+ "lr": a.lr, "warmup": a.warmup, "batch_size": a.batch_size, "ema_decay": a.ema_decay,
457
+ "max_steps": max_steps, "steps_run": step, "eval_every": eval_every, "patience": a.patience,
458
+ "train_subset": subset_info, "train_donors_file": a.train_donors_file or None,
459
+ "support_manifest": str(a.support_manifest) if support else None,
460
+ "support_sha256": support["sha256"] if support else None,
461
+ "train_donor_ids": support["train_donor_ids"] if support else None,
462
+ "excluded_selected_donor_visits": support["excluded_sample_ids"] if support else None,
463
+ "fixed_steps": a.fixed_steps or None,
464
+ "selected_step": best["step"], "selected_inner_val_loss": best["loss"],
465
+ "pretrained_inner_val_loss": history[0]["inner_val_loss"],
466
+ "train_rows": [str(x) for x in folds.loc[train_rows, "sample_id"]],
467
+ "inner_val_rows": [str(x) for x in folds.loc[inner_rows, "sample_id"]],
468
+ "test_rows_never_loaded_for_training": [str(x) for x in folds.loc[test_rows, "sample_id"]],
469
+ "max_abs_weight_change": max(changed.values()),
470
+ "n_tensors_changed": int(sum(v > 0 for v in changed.values())),
471
+ "seed": a.seed, "wall_seconds": round(time.time() - t0, 1),
472
+ "written_utc": datetime.now(timezone.utc).isoformat(),
473
+ }
474
+ if isolation is not None:
475
+ ft_meta["support_expression_isolation"] = isolation
476
+ out["finetune"] = ft_meta
477
+ tmp = a.out_dir / "checkpoint_ft.pt.tmp"
478
+ torch.save(out, tmp)
479
+ os.replace(tmp, done)
480
+ ft_meta["checkpoint_sha256"] = sha256_file(done)
481
+ # reload through the sampler's own restore path and compare one forward pass
482
+ check = SS.restore_standalone(done, device=torch.device("cpu"), weights="ema", conditioner_source="embedded")
483
+ ref = SS.restore_standalone(done, device=torch.device("cpu"), weights="raw", conditioner_source="embedded")
484
+ xs = torch.randn(4, check.diffusion.state_dim, generator=torch.Generator().manual_seed(0))
485
+ tt = torch.full((4,), 0.5)
486
+ cc = cond_rows[torch.from_numpy(train_rows[:1]).to(device)].repeat(4, 1).float().cpu()
487
+ denoiser_cpu = denoiser.to("cpu").float().eval()
488
+ with torch.no_grad():
489
+ o1 = check.diffusion.denoiser(xs, tt, cc).value_prediction
490
+ o2 = denoiser_cpu(xs, tt, cc).value_prediction
491
+ o3 = ref.diffusion.denoiser(xs, tt, cc).value_prediction
492
+ ft_meta["reload_forward_max_abs_diff"] = float(max((o1 - o2).abs().max(), (o1 - o3).abs().max()))
493
+ if ft_meta["reload_forward_max_abs_diff"] > 1e-4:
494
+ raise SystemExit(f"reloaded checkpoint differs: {ft_meta['reload_forward_max_abs_diff']}")
495
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
496
+ (a.out_dir / "RUN.json").write_text(json.dumps(ft_meta, indent=1))
497
+ log(f"saved {done} (selected step {best['step']}, inner-val {best['loss']:.5f} vs pretrained "
498
+ f"{history[0]['inner_val_loss']:.5f}); sha {ft_meta['checkpoint_sha256'][:12]}")
499
+ return 0
500
+
501
+
502
+ if __name__ == "__main__":
503
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261013T124345Z-trunk4x-lora-sepsis-launch/diffusion/dataset/server_1/model8/plans/trunk4x_lora_sepsis_20261013/tools/gpu_campaign.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Sequential GPU campaign; must be invoked via remote ml-run. No retries."""
2
+ from pathlib import Path
3
+ from datetime import datetime,timezone
4
+ import json,os,sys,subprocess,hashlib,socket,traceback
5
+ ROOT=Path(__file__).resolve().parents[1];M=ROOT.parents[1]
6
+ def sha(p):
7
+ with Path(p).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
8
+ def state(phase,**kw):
9
+ j=dict(phase=phase,host=socket.gethostname(),at=datetime.now(timezone.utc).isoformat(),**kw)
10
+ tmp=ROOT/'GPU_STATUS.tmp';tmp.write_text(json.dumps(j,indent=2)+'\n');tmp.replace(ROOT/'GPU_STATUS.json');print(json.dumps(j),flush=True)
11
+ def run(argv,path):
12
+ if path.exists():raise RuntimeError('Existing operation log; inspect instead of retry: '+str(path))
13
+ subprocess.run(['systemctl','--user','is-active','--quiet','ml-memory-guard.service'],check=True)
14
+ subprocess.run(['/home/sj_server_2/.local/libexec/ml-memory-guard','--check'],check=True)
15
+ pids=subprocess.check_output(['nvidia-smi','--query-compute-apps=pid','--format=csv,noheader'],text=True).strip()
16
+ if pids:raise RuntimeError('Unexpected active CUDA PID while holding shared lock: '+pids)
17
+ with path.open('x') as f:subprocess.run(argv,stdout=f,stderr=subprocess.STDOUT,check=True)
18
+ def main():
19
+ assert 'ml.slice' in Path('/proc/self/cgroup').read_text()
20
+ protocol=json.loads((ROOT/'PROTOCOL.json').read_text());state('preflight')
21
+ for rel,h in protocol['files'].items():assert sha(ROOT/rel)==h,rel
22
+ for rel,h in protocol['code'].items():assert sha(ROOT/rel)==h,rel
23
+ for arm,cfg in protocol['arms'].items():
24
+ cp=M/'runs'/cfg['run']/'checkpoint_epoch_016.pt';assert sha(cp)==cfg['sha256']
25
+ for draw in range(5):
26
+ data=ROOT/f'data/draw{draw}/ye2026_sepsis';sup=json.loads((data/'support.json').read_text())
27
+ for arm,cfg in protocol['arms'].items():
28
+ if (ROOT/f'completed/{arm}_draw{draw}.json').exists():raise RuntimeError('Already completed; no implicit replay')
29
+ out=ROOT/f'runs/{arm}/draw{draw}';out.mkdir(parents=True,exist_ok=True)
30
+ if (out/'checkpoint_ft.pt').exists():raise RuntimeError('Checkpoint already present; inspect before retry')
31
+ state('training',arm=arm,draw=draw,log=str(out/'train.log'))
32
+ base=M/'runs'/cfg['run']/'checkpoint_epoch_016.pt'
33
+ cmd=[sys.executable,'-u',str(ROOT/'tools/ft_sdd_frozen.py'),'--checkpoint',str(base),'--checkpoint-sha',cfg['sha256'],
34
+ '--dataset-dir',str(data),'--condition-npz',str(ROOT/'data/conditions_raw_fixed.npz'),'--fold','0','--mode','lora',
35
+ '--lora-rank','16','--lora-alpha','16','--lr','0.0005','--warmup','200','--batch-size','256','--ema-decay','0.999',
36
+ '--seed','20260927','--train-donors-file',str(data/'train_donors.txt'),'--fixed-steps','3000','--out-dir',str(out),
37
+ '--max-cuda-gib','24','--min-system-gib','32']
38
+ run(cmd,out/'train.log');r=json.loads((out/'RUN.json').read_text())
39
+ assert set(r['train_rows'])==set(sup['train_sample_ids']) and set(r['test_rows_never_loaded_for_training'])==set(sup['test_sample_ids'])
40
+ assert not r['inner_val_rows'] and r['steps_run']==3000 and r['source_checkpoint_sha256']==cfg['sha256']
41
+ cp=out/'checkpoint_ft.pt';assert sha(cp)==r['checkpoint_sha256']
42
+ gen=ROOT/f'generated/{arm}/draw{draw}/cells.npz';gen.parent.mkdir(parents=True,exist_ok=True)
43
+ # Conservative disk floor: retain existing outputs, stop rather than consume last headroom.
44
+ import shutil
45
+ if shutil.disk_usage(ROOT).free<40*2**30:raise RuntimeError('Remote free disk <40GiB; preserve and inspect')
46
+ state('generating',arm=arm,draw=draw,output=str(gen))
47
+ run([sys.executable,'-u',str(ROOT/'tools/sample_one_frozen.py'),'--checkpoint',str(cp),'--checkpoint-sha',r['checkpoint_sha256'],
48
+ '--condition',str(data/'test_raw.npz'),'--output',str(gen),'--seed','20260928'],gen.parent/'wrapper.log')
49
+ receipt=json.loads(gen.with_suffix('.log').read_text());assert receipt['output_sha256']==sha(gen)
50
+ done={'arm':arm,'draw':draw,'host':socket.gethostname(),'checkpoint':str(cp),'checkpoint_sha256':r['checkpoint_sha256'],
51
+ 'output':str(gen),'output_sha256':receipt['output_sha256'],'support_sha256':sup['sha256'],'at':datetime.now(timezone.utc).isoformat()}
52
+ (ROOT/'completed').mkdir(exist_ok=True);(ROOT/f'completed/{arm}_draw{draw}.json').write_text(json.dumps(done,indent=2)+'\n')
53
+ state('gpu_complete',arms=2,draws=5)
54
+ if __name__=='__main__':
55
+ try:main()
56
+ except BaseException as e:state('failed',error=str(e));raise
paper-releases/pbisc-diffusion/updates/20261013T124345Z-trunk4x-lora-sepsis-launch/diffusion/dataset/server_1/model8/plans/trunk4x_lora_sepsis_20261013/tools/prepare.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU-only exact-support panel projection, preserving cell-row RNG semantics."""
2
+ from pathlib import Path
3
+ import os,sys,json,hashlib,shutil
4
+ import numpy as np
5
+ import pandas as pd
6
+ from scipy import sparse
7
+ assert os.environ.get('CUDA_VISIBLE_DEVICES')==''
8
+ ROOT=Path(__file__).resolve().parents[1];M=ROOT.parents[1];F=M/'plans/paired_finetune_intradataset_20260927';S=M/'plans/paper_figures_strictpairs_20261012'
9
+ sys.path.insert(0,str(S/'tools'))
10
+ from support_input_isolation import read_ranges
11
+
12
+ def sha(p):
13
+ with Path(p).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
14
+ def write(p,j):p.parent.mkdir(parents=True,exist_ok=True);p.write_text(json.dumps(j,indent=2)+'\n')
15
+ def main():
16
+ ds=F/'data/ye2026_sepsis';source=ds/'cells_full.npz';source_hash=sha(source)
17
+ old=json.loads((M/'runs/s0_6k_allK_topup16_seed20260627_arch4x_ctx512_v1/data_audit.json').read_text())
18
+ one=json.loads((M/'runs/s0_6k_allK_topup16_seed20260627_bundle_v2/data_audit.json').read_text())
19
+ assert old['gene_ids']==one['gene_ids']
20
+ genes=np.asarray(old['gene_ids'],dtype=str)
21
+ with np.load(ds/'features.npz',allow_pickle=False) as z:
22
+ canon=z['gene_ids'].astype(str);pos=np.array([list(canon).index(g) for g in genes]);measured=z['sc_valid'][:,pos]
23
+ with np.load(source,allow_pickle=False) as z:ip=z['indptr'];rs=z['row_sample'];shape=z['shape']
24
+ folds=pd.read_csv(ds/'folds.csv');gene_map=np.full(len(canon),-1,dtype=np.int32);gene_map[pos]=np.arange(6000)
25
+ config={'schema':'pbisc.trunk-lora.representative.v1','cohort':'ye2026_sepsis','primary_comparison':'legacy_panel_1x_vs_legacy_panel_trunk4x','draws':[],'arms':{'trunk4x':{'run':'s0_6k_allK_topup16_seed20260627_arch4x_ctx512_v1','sha256':'f780813e784d0467ad278e0aea07b629349089ae4cd09aab718f1ce70bd179fd'},'panel_matched_1x':{'run':'s0_6k_allK_topup16_seed20260627_bundle_v2','sha256':'6c1aa7b55a5784a3b97c15d75b053e59d69549d6f84c38edf44ff4f6858ed99c'}},'train':{'rank':16,'alpha':16,'steps':3000,'lr':0.0005,'warmup':200,'batch_size':256,'ema':0.999,'seed':20260927},'sampling':{'steps':50,'seed':20260928,'cells_per_sample':1500,'support_readout':'bernoulli'},'source_full_cells_sha256':source_hash,'files':{}}
26
+ for draw in range(5):
27
+ support_path=S/f'protocol/splits/ye2026_sepsis/disease/draw{draw}/support.json';support=json.loads(support_path.read_text())
28
+ legacy=json.loads((F/f'runs/ye2026_sepsis/fewshot_n5/draw{draw}/lora/RUN.json').read_text())
29
+ assert set(support['train_sample_ids'])==set(legacy['train_rows']) and not legacy['inner_val_rows']
30
+ assert set(support['test_sample_ids'])==set(legacy['test_rows_never_loaded_for_training'])
31
+ rows=folds.index[folds.sample_id.isin(support['train_sample_ids'])].to_numpy();use=np.isin(rs,rows);selected=np.flatnonzero(use)
32
+ starts=selected[np.r_[True,np.diff(selected)!=1]];ends=selected[np.r_[np.diff(selected)!=1,True]]+1
33
+ ranges=[(int(ip[a]),int(ip[b])) for a,b in zip(starts,ends)]
34
+ data=read_ranges(source,'data',ranges,expected_length=int(ip[-1]));indices=read_ranges(source,'indices',ranges,expected_length=int(ip[-1]))
35
+ sip=np.r_[0,np.cumsum(np.where(use,np.diff(ip),0),dtype=np.int64)]
36
+ x=sparse.csr_matrix((data,indices,sip),shape=tuple(shape));xp=x[:,pos].tocsr();del x,data,indices
37
+ assert xp[~use].nnz==0 and xp.shape[0]==len(rs)
38
+ out=ROOT/f'data/draw{draw}/ye2026_sepsis';out.mkdir(parents=True,exist_ok=True)
39
+ np.savez_compressed(out/'cells_panel6k.npz',data=xp.data,indices=xp.indices,indptr=xp.indptr,row_sample=rs,shape=np.array(xp.shape),panel_gene_ids=genes,panel_measured=measured)
40
+ shutil.copy2(ds/'folds.csv',out/'folds.csv');shutil.copy2(support_path,out/'support.json')
41
+ (out/'train_donors.txt').write_text('\n'.join(support['train_donor_ids'])+'\n')
42
+ shutil.copy2(S/f'data/ye2026_sepsis/disease/draw{draw}/test_raw.npz',out/'test_raw.npz')
43
+ j={'draw':draw,'train':support['train_sample_ids'],'test':support['test_sample_ids'],'support_sha256':support['sha256'],'support_cells':int(use.sum()),'non_support_expression_entries':0,'isolated_panel_sha256':sha(out/'cells_panel6k.npz'),'cell_rng_row_order_preserved':True,'legacy_run':str(F/f'runs/ye2026_sepsis/fewshot_n5/draw{draw}/lora/RUN.json')}
44
+ write(out/'PREPARATION.json',j);config['draws'].append(j);print('Prepared',draw,flush=True)
45
+ shutil.copy2(ds/'conditions_raw_fixed.npz',ROOT/'data/conditions_raw_fixed.npz')
46
+ shutil.copy2(F/'tools/ft_sdd.py',ROOT/'tools/ft_sdd_frozen.py')
47
+ shutil.copy2(S/'tools/sample_one.py',ROOT/'tools/sample_one_frozen.py')
48
+ shutil.copy2(S/'tools/runtime.py',ROOT/'tools/runtime.py')
49
+ current=json.loads((M/'runs/f01_6k_1x_seed20260627/data_audit.json').read_text())['gene_ids'];common=[g for g in current if g in set(genes)]
50
+ assert len(common)==4258
51
+ (ROOT/'data/common_genes.txt').write_text('\n'.join(common)+'\n')
52
+ for p in (ROOT/'data').rglob('*'):
53
+ if p.is_file():config['files'][str(p.relative_to(ROOT))]=sha(p)
54
+ config['code']={str(p.relative_to(ROOT)):sha(p) for p in (ROOT/'tools').glob('*.py')}
55
+ write(ROOT/'PROTOCOL.json',config)
56
+ print('PROTOCOL complete; no held-out expression materialized for training',flush=True)
57
+ if __name__=='__main__':main()
paper-releases/pbisc-diffusion/updates/20261013T124345Z-trunk4x-lora-sepsis-launch/diffusion/dataset/server_1/model8/plans/trunk4x_lora_sepsis_20261013/tools/runtime.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 socket
12
+ import subprocess
13
+ import time
14
+
15
+
16
+ class ReceiptError(RuntimeError):
17
+ """An output cannot be attributed safely to the requested operation."""
18
+
19
+
20
+ def sha256(path: Path) -> str:
21
+ h = hashlib.sha256()
22
+ with path.open("rb") as stream:
23
+ for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
24
+ h.update(chunk)
25
+ return h.hexdigest()
26
+
27
+
28
+ def stamp() -> str:
29
+ return datetime.now(timezone.utc).isoformat()
30
+
31
+
32
+ def atomic_json(path: Path, value: dict) -> None:
33
+ path.parent.mkdir(parents=True, exist_ok=True)
34
+ tmp = path.with_suffix(path.suffix + f".tmp-{os.getpid()}")
35
+ tmp.write_text(json.dumps(value, indent=2, allow_nan=False) + "\n")
36
+ tmp.replace(path)
37
+
38
+
39
+ def stat_record(path: Path) -> dict:
40
+ st = path.stat()
41
+ return {"path": str(path.resolve()), "bytes": st.st_size, "mtime_ns": st.st_mtime_ns}
42
+
43
+
44
+ class Runtime:
45
+ def __init__(self, root: Path):
46
+ self.root = root.resolve()
47
+ self.started_at = stamp()
48
+ self._execution_map, self._map_path, self._map_sha256 = self._load_execution_map()
49
+ (self.root / "receipts").mkdir(parents=True, exist_ok=True)
50
+ (self.root / "logs").mkdir(parents=True, exist_ok=True)
51
+ self._guard_restarted = False
52
+
53
+ @staticmethod
54
+ def _absolute_path(value: str, *, executable: bool = False) -> Path:
55
+ if (not isinstance(value, str) or not value or
56
+ any(ord(char) < 32 for char in value) or not Path(value).is_absolute()):
57
+ raise ValueError("execution paths must be absolute strings without control characters")
58
+ path = Path(value)
59
+ if executable and (not path.is_file() or not os.access(path, os.X_OK)):
60
+ raise ValueError(f"execution path is not an executable file: {value}")
61
+ return path
62
+
63
+ def _load_execution_map(self) -> tuple[dict, str | None, str | None]:
64
+ config_path = os.environ.get("PBISC_STRICT_EXECUTION_MAP")
65
+ if not config_path:
66
+ return {}, None, None
67
+ path = self._absolute_path(config_path)
68
+ try:
69
+ raw = path.read_bytes()
70
+ config = json.loads(raw)
71
+ except (OSError, ValueError) as exc:
72
+ raise ValueError(f"cannot read execution map: {path}") from exc
73
+ required = {"host", "executables", "ml_run", "guard_check", "path"}
74
+ if not isinstance(config, dict) or set(config) != required:
75
+ raise ValueError(f"execution map must contain exactly {sorted(required)}")
76
+ if not isinstance(config["host"], str) or not re.fullmatch(r"[A-Za-z0-9_.-]+", config["host"]):
77
+ raise ValueError("execution map host must be a nonempty host label")
78
+ if not isinstance(config["executables"], dict):
79
+ raise ValueError("execution map executables must be a mapping")
80
+ for canonical, actual in config["executables"].items():
81
+ self._absolute_path(canonical)
82
+ self._absolute_path(actual, executable=True)
83
+ for field in ("ml_run", "guard_check"):
84
+ self._absolute_path(config[field], executable=True)
85
+ if not isinstance(config["path"], str):
86
+ raise ValueError("execution map path must be an absolute-directory PATH string")
87
+ for directory in config["path"].split(os.pathsep):
88
+ self._absolute_path(directory)
89
+ return config, str(path.resolve()), hashlib.sha256(raw).hexdigest()
90
+
91
+ def execution_argv(self, argv: list[str]) -> list[str]:
92
+ if not argv:
93
+ raise ValueError("execution command must not be empty")
94
+ actual = [str(arg) for arg in argv]
95
+ actual[0] = self._execution_map.get("executables", {}).get(actual[0], actual[0])
96
+ return actual
97
+
98
+ def execution_metadata(self, argv: list[str] | None = None,
99
+ command: list[str] | None = None) -> dict:
100
+ return {"host": socket.gethostname(), "map_host": self._execution_map.get("host"),
101
+ "map_path": self._map_path, "map_sha256": self._map_sha256,
102
+ "argv": self.execution_argv(argv) if argv is not None else None,
103
+ "command": command}
104
+
105
+ def _execution_environment(self) -> dict:
106
+ env = os.environ.copy()
107
+ if self._execution_map:
108
+ env["PATH"] = self._execution_map["path"]
109
+ return env
110
+
111
+ def receipt_path(self, name: str) -> Path:
112
+ if not re.fullmatch(r"[A-Za-z0-9_.-]+", name):
113
+ raise ValueError(f"invalid operation name {name!r}")
114
+ return self.root / "receipts" / f"{name}.json"
115
+
116
+ def event(self, name: str, state: str, **details) -> None:
117
+ record = {"at": stamp(), "operation": name, "state": state, **details}
118
+ with (self.root / "events.jsonl").open("a") as stream:
119
+ stream.write(json.dumps(record, allow_nan=False) + "\n")
120
+ print(f"{record['at']} {name}: {state}", flush=True)
121
+
122
+ def signature(self, argv: list[str], inputs: list[Path]) -> str:
123
+ value = {"argv": [str(x) for x in argv], "inputs": [
124
+ {"path": str(p.resolve()), "sha256": sha256(p)} for p in inputs]}
125
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
126
+
127
+ def write_receipt(self, name: str, value: dict) -> None:
128
+ atomic_json(self.receipt_path(name), value)
129
+
130
+ def can_skip(self, name: str, signature: str, outputs: list[Path],
131
+ previous_outputs: dict | None = None) -> bool:
132
+ receipt = self.receipt_path(name)
133
+ if not receipt.exists():
134
+ for p in outputs:
135
+ if not p.exists():
136
+ continue
137
+ prior = (previous_outputs or {}).get(str(p))
138
+ if (not prior or p.suffix in (".npz", ".pt", ".pth", ".safetensors") or
139
+ not p.resolve().is_relative_to(self.root)):
140
+ raise ReceiptError(f"{name}: unreceipted output exists; preserve and inspect")
141
+ backup = Path(prior["backup"])
142
+ if (not backup.is_file() or backup.resolve() == p.resolve() or
143
+ sha256(p) != prior["sha256"] or sha256(backup) != prior["sha256"]):
144
+ raise ReceiptError(f"{name}: preview replacement is not bound to a preserved copy")
145
+ return False
146
+ record = json.loads(receipt.read_text())
147
+ if record.get("state") != "completed":
148
+ raise ReceiptError(f"{name}: previous {record.get('state')}; inspect before explicit recovery")
149
+ if record.get("signature") != signature:
150
+ self._verify_source_reuse(name, record.get("signature"), signature, receipt)
151
+ old = record.get("outputs", [])
152
+ if len(old) != len(outputs):
153
+ raise ReceiptError(f"{name}: output contract changed")
154
+ for p, expected in zip(outputs, old):
155
+ if not p.is_file() or stat_record(p) != {k: expected[k] for k in ("path", "bytes", "mtime_ns")}:
156
+ raise ReceiptError(f"{name}: output missing or modified: {p}")
157
+ if sha256(p) != expected.get("sha256"):
158
+ raise ReceiptError(f"{name}: output hash changed: {p}")
159
+ return True
160
+
161
+ def _verify_source_reuse(self, name: str, old_signature: str, new_signature: str,
162
+ receipt: Path) -> None:
163
+ """Allow only a reviewed, hash-bound transition; never rewrite its historical receipt."""
164
+ manifest = self.root / "recoveries" / "SOURCE_REUSE.json"
165
+ if not manifest.is_file():
166
+ raise ReceiptError(f"{name}: scientific inputs or command changed; use a new version")
167
+ try:
168
+ recovery = json.loads(manifest.read_bytes())
169
+ if (not isinstance(recovery, dict) or
170
+ recovery.get("schema") != "pbisc.strictpairs.source-reuse.v1" or
171
+ not isinstance(recovery.get("transitions"), list)):
172
+ raise ValueError("invalid source reuse manifest schema")
173
+ if not all(isinstance(item, dict) for item in recovery["transitions"]):
174
+ raise ValueError("invalid source reuse transition")
175
+ matches = [item for item in recovery["transitions"]
176
+ if (item.get("operation"), item.get("old_signature"), item.get("new_signature"))
177
+ == (name, old_signature, new_signature)]
178
+ if len(matches) != 1:
179
+ raise ValueError("no unique approval for this exact operation and signature transition")
180
+ transition = matches[0]
181
+ if not all(isinstance(value, str) and re.fullmatch(r"[0-9a-f]{64}", value)
182
+ for value in (old_signature, new_signature)):
183
+ raise ValueError("source reuse signatures must be SHA-256 values")
184
+
185
+ def verify_file(binding: dict) -> Path:
186
+ if not isinstance(binding, dict):
187
+ raise ValueError("invalid source reuse file binding")
188
+ path = self._absolute_path(binding["path"])
189
+ digest = binding["sha256"]
190
+ if (not isinstance(digest, str) or not re.fullmatch(r"[0-9a-f]{64}", digest) or
191
+ not path.is_file() or sha256(path) != digest):
192
+ raise ValueError(f"source reuse bound file changed or missing: {path}")
193
+ return path
194
+
195
+ original = verify_file(transition["original_receipt"])
196
+ if sha256(receipt) != sha256(original):
197
+ raise ValueError("current historical receipt differs from preserved original")
198
+ evidence = transition["evidence"]
199
+ if not isinstance(evidence, list) or not evidence:
200
+ raise ValueError("source reuse requires named evidence files")
201
+ names = set()
202
+ for binding in evidence:
203
+ if (not isinstance(binding, dict) or not isinstance(binding.get("name"), str) or
204
+ not binding["name"].strip() or binding["name"] in names):
205
+ raise ValueError("source reuse evidence must have unique nonempty names")
206
+ names.add(binding["name"])
207
+ verify_file(binding)
208
+ except (OSError, ValueError, KeyError, TypeError) as exc:
209
+ raise ReceiptError(f"{name}: source reuse attestation failed: {exc}") from exc
210
+
211
+ def record_completed(self, name: str, signature: str, outputs: list[Path], seconds: float,
212
+ *, execution: dict | None = None, argv: list[str] | None = None,
213
+ previous_outputs: dict | None = None) -> None:
214
+ records = []
215
+ for path in outputs:
216
+ if not path.is_file() or path.stat().st_size == 0:
217
+ raise ReceiptError(f"{name}: missing or empty required output {path}")
218
+ records.append({**stat_record(path), "sha256": sha256(path)})
219
+ self.write_receipt(name, {"state": "completed", "signature": signature,
220
+ "outputs": records, "seconds": seconds, "at": stamp(),
221
+ "execution": execution if execution is not None else self.execution_metadata(),
222
+ "argv": argv, "previous_outputs": previous_outputs})
223
+
224
+ def wrapped_command(self, name: str, argv: list[str], resource: str,
225
+ memory_gib: int, threads: int) -> list[str]:
226
+ if resource not in ("cpu", "gpu"):
227
+ raise ValueError("resource must explicitly be cpu or gpu")
228
+ if not 1 <= threads <= 8 or not 1 <= memory_gib <= 64:
229
+ raise ValueError("unsafe CPU/memory budget")
230
+ actual_argv = self.execution_argv(argv)
231
+ path = self._execution_map.get("path", "/home/sj_server_1/.local/bin:/home/sj_server_1/miniforge3/bin:/usr/local/bin:/usr/bin:/bin")
232
+ env = [f"PATH={path}",
233
+ "PYTHONDONTWRITEBYTECODE=1", "PYTHONUNBUFFERED=1", f"OMP_NUM_THREADS={threads}",
234
+ f"OPENBLAS_NUM_THREADS={threads}", f"MKL_NUM_THREADS={threads}",
235
+ f"NUMBA_NUM_THREADS={threads}"]
236
+ if resource == "gpu":
237
+ return [self._execution_map.get("ml_run", "/home/sj_server_1/.local/bin/ml-run"),
238
+ "/usr/bin/env", "CUDA_VISIBLE_DEVICES=0",
239
+ "PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True", *env, *actual_argv]
240
+ unit = f"pbisc-strict-{name[:100]}-{os.getpid()}-{time.time_ns()}"
241
+ return ["systemd-run", "--user", "--wait", "--collect", "--pipe", "--quiet",
242
+ f"--unit={unit}", "--slice=app.slice", f"--working-directory={self.root}",
243
+ "--expand-environment=no", "-p", f"MemoryMax={memory_gib}G", "-p", "MemorySwapMax=0",
244
+ "-p", "OOMPolicy=kill", "-p", "OOMScoreAdjust=500", "-p", f"CPUQuota={threads * 100}%",
245
+ "/usr/bin/env", "CUDA_VISIBLE_DEVICES=", *env, *actual_argv]
246
+
247
+ def preflight(self, resource: str, memory_gib: int) -> None:
248
+ # Every substantial CPU operation and every CUDA operation checks all three controls.
249
+ env = self._execution_environment()
250
+ active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
251
+ capture_output=True, text=True, env=env)
252
+ if active.returncode:
253
+ if not self._guard_restarted:
254
+ self._guard_restarted = True
255
+ subprocess.run(["systemctl", "--user", "restart", "ml-memory-guard.service"], check=True, env=env)
256
+ subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"], check=True, env=env)
257
+ subprocess.run([self._execution_map.get("guard_check", "/home/sj_server_1/.local/libexec/ml-memory-guard"),
258
+ "--check"], check=True, env=env)
259
+ compute = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory",
260
+ "--format=csv,noheader"], capture_output=True, text=True, check=True, env=env)
261
+ guard_log = subprocess.run(["journalctl", "-t", "ml-memory-guard", "--since", self.started_at,
262
+ "--no-pager"], capture_output=True, text=True, check=True, env=env)
263
+ if "stopping ml.slice" in guard_log.stdout:
264
+ raise RuntimeError("memory guard stopped ml.slice; inspect evidence before any restart")
265
+ available = next(int(line.split()[1]) / 1048576 for line in Path("/proc/meminfo").read_text().splitlines()
266
+ if line.startswith("MemAvailable:"))
267
+ floor = max(32, memory_gib + 24) if resource == "cpu" else 48
268
+ if shutil.disk_usage(self.root).free < 64 * 2**30:
269
+ raise BlockingIOError("less than 64 GiB free disk; preserve originals and wait for storage")
270
+ if available < floor:
271
+ raise BlockingIOError(f"MemAvailable {available:.1f} GiB below {floor} GiB launch floor")
272
+ if resource == "gpu":
273
+ if compute.stdout.strip():
274
+ raise BlockingIOError("another CUDA process is active")
275
+ lock = subprocess.run(["flock", "--nonblock", "/run/user/1000/ml-gpu0.lock", "true"], env=env)
276
+ if lock.returncode:
277
+ raise BlockingIOError("shared GPU lock is held")
278
+
279
+ def execute(self, name: str, argv: list[str], *, resource: str = "cpu", memory_gib: int = 16,
280
+ threads: int = 4, inputs: list[Path] | None = None,
281
+ outputs: list[Path] | None = None, wait_seconds: int = 86400,
282
+ previous_outputs: dict | None = None) -> bool:
283
+ inputs, outputs = inputs or [], outputs or []
284
+ signature = self.signature(argv, inputs)
285
+ if self.can_skip(name, signature, outputs, previous_outputs=previous_outputs):
286
+ self.event(name, "verified_skip")
287
+ return False
288
+ wait_start, announced = time.monotonic(), False
289
+ while True:
290
+ try:
291
+ self.preflight(resource, memory_gib)
292
+ break
293
+ except BlockingIOError as exc:
294
+ if not announced:
295
+ self.event(name, "waiting_resources", reason=str(exc))
296
+ announced = True
297
+ if time.monotonic() - wait_start > wait_seconds:
298
+ raise TimeoutError(str(exc)) from exc
299
+ time.sleep(15)
300
+ command = self.wrapped_command(name, argv, resource, memory_gib, threads)
301
+ execution = self.execution_metadata(argv, command)
302
+ self.write_receipt(name, {"state": "running", "signature": signature, "argv": argv,
303
+ "resource": resource, "at": stamp(), "previous_outputs": previous_outputs,
304
+ "execution": execution})
305
+ self.event(name, "running", resource=resource)
306
+ t0 = time.monotonic()
307
+ try:
308
+ with (self.root / "logs" / f"{name}.log").open("a") as log:
309
+ result = subprocess.run(command, cwd=self.root, stdout=log, stderr=subprocess.STDOUT,
310
+ env=self._execution_environment())
311
+ elapsed = time.monotonic() - t0
312
+ if result.returncode:
313
+ raise subprocess.CalledProcessError(result.returncode, command)
314
+ self.record_completed(name, signature, outputs, elapsed, execution=execution, argv=argv,
315
+ previous_outputs=previous_outputs)
316
+ except BaseException as exc:
317
+ self.write_receipt(name, {"state": "failed", "signature": signature, "at": stamp(),
318
+ "error": str(exc), "seconds": time.monotonic() - t0,
319
+ "execution": execution, "argv": argv})
320
+ self.event(name, "failed", error=str(exc))
321
+ raise
322
+ self.event(name, "completed", seconds=elapsed)
323
+ return True