junidude14 commited on
Commit
dad81cb
·
verified ·
1 Parent(s): efc49af

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/16/ft_sdd.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/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/17/prepare_draw_inputs.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Build scSemiProfiler inputs for one paired split (CPU only).
3
+
4
+ Representatives = every usable row of the split's training donors (paired sc + real bulk).
5
+ Targets = the split's test rows (real bulk only; their cells are never read here).
6
+
7
+ --mode fewshot --draw j : training donors = data/<ds>/fewshot_n5/draw<j>/train_donors.txt,
8
+ targets = draw<j>/test_samples.txt, condition = draw<j>/test_raw.npz
9
+ --mode cv --fold k : training donors = every usable donor not in fold k (inner-val donors included),
10
+ targets = fold k's rows, condition = data/<ds>/fold<k>/test_raw.npz
11
+ --mode budget --fold k --n N (added 2026-10-02): representatives = exactly the rows LoRA lora_n<N> of fold k saw,
12
+ runs/<ds>/fold<k>/lora_n<N>/RUN.json train_rows + inner_val_rows (checked against
13
+ data/<ds>/CAL_BUDGET.json fit_sample_ids when present); targets = fold k's rows (checked
14
+ against the run's test_rows_never_loaded_for_training); condition = fold<k>/test_raw.npz.
15
+ The manifest also records target_donors (used by run_scsemi_paired.py --reuse-from).
16
+ --check-only (added 2026-10-02): build and check everything (split, genes, cells, depth, condition), write
17
+ nothing under --work; print the summary (and the representative / target lists to
18
+ --check-out if given). Without it the builder behaves exactly as before.
19
+
20
+ Modeled genes = final 6k panel genes measured in the bulk of every representative and target row AND in the
21
+ single cells of every representative row (features.npz bulk_valid / sc_valid). No target single-cell mask,
22
+ depth or cell count enters.
23
+
24
+ Writes <work>/inputs/:
25
+ bulk.h5ad raw bulk counts (float64) of reps + targets on the modeled genes, obs['sample_ids'],
26
+ rows in features.npz order; upstream initsetup(normed=False) library-normalises + log1p's it
27
+ rep_sc.h5ad raw UMI counts (float32 CSR) of every representative cell on the modeled genes,
28
+ obs['sample_ids'] = the representative row's sample id; upstream scprocess(normed=False)
29
+ inputs_manifest.json rows, genes, depth rule, source hashes
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import argparse
34
+ import hashlib
35
+ import json
36
+ import os
37
+ import sys
38
+ from datetime import datetime, timezone
39
+ from pathlib import Path
40
+
41
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
42
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
43
+
44
+ import numpy as np
45
+ import pandas as pd
46
+ import scipy.sparse as sp
47
+
48
+ TASK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
49
+ HERE = TASK / "scsemi"
50
+ sys.path.insert(0, str(TASK / "tools"))
51
+ import prepare_dataset as PD # noqa: E402 (the benchmark's own loader: bulk_raw with unmeasured NaN -> 0, masks, use)
52
+
53
+ SEED = 20260927
54
+
55
+
56
+ def sha(path: Path) -> str:
57
+ h = hashlib.sha256()
58
+ with open(path, "rb") as f:
59
+ for block in iter(lambda: f.read(1 << 24), b""):
60
+ h.update(block)
61
+ return h.hexdigest()
62
+
63
+
64
+ def split_rows(ds: str, mode: str, j: int, sample_ids: np.ndarray, folds: pd.DataFrame,
65
+ n: int | None = None, support_manifest: Path | None = None) -> dict:
66
+ data = TASK / "data" / ds
67
+ usable = folds["fold"].to_numpy() >= 0
68
+ donors = folds["donor_id"].astype(str).to_numpy()
69
+ extra = {}
70
+ if support_manifest is not None:
71
+ strict_tools = TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/tools"
72
+ sys.path.insert(0, str(strict_tools))
73
+ from support_manifest import load_manifest, select_rows
74
+ m = load_manifest(support_manifest, folds)
75
+ if m["cohort"] != ds:
76
+ raise SystemExit("support cohort differs from dataset")
77
+ rep, tgt = select_rows(m, folds)
78
+ rel = support_manifest.resolve().parent.relative_to(
79
+ TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/protocol/splits")
80
+ cond = TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/data" / rel / "test_raw.npz"
81
+ return {"rep": rep, "tgt": tgt, "train_donors": m["train_donor_ids"],
82
+ "test": m["test_sample_ids"], "condition": cond,
83
+ "sources": {"support.json": support_manifest},
84
+ "support_sha256": m["sha256"], "target_donors": m["test_donor_ids"]}
85
+ if mode == "fewshot":
86
+ dd = data / "fewshot_n5" / f"draw{j}"
87
+ train_donors = [x.strip() for x in (dd / "train_donors.txt").read_text().splitlines() if x.strip()]
88
+ test = [x.strip() for x in (dd / "test_samples.txt").read_text().splitlines() if x.strip()]
89
+ cond = dd / "test_raw.npz"
90
+ sources = {"train_donors.txt": dd / "train_donors.txt", "test_samples.txt": dd / "test_samples.txt"}
91
+ rep = np.flatnonzero(np.isin(donors, train_donors) & usable)
92
+ elif mode == "cv":
93
+ fold = folds["fold"].to_numpy()
94
+ test = sample_ids[fold == j].tolist()
95
+ rep = np.flatnonzero(usable & (fold != j))
96
+ train_donors = sorted(set(donors[rep]))
97
+ cond = data / f"fold{j}" / "test_raw.npz"
98
+ sources = {}
99
+ elif mode == "budget":
100
+ fold = folds["fold"].to_numpy()
101
+ rj = TASK / "runs" / ds / f"fold{j}" / f"lora_n{n}" / "RUN.json"
102
+ run = json.loads(rj.read_text())
103
+ if run["fold"] != j or (run.get("train_subset") or {}).get("train_n") != n:
104
+ raise SystemExit(f"{rj}: not the fold {j} n={n} learning-curve run")
105
+ fit = list(run["train_rows"]) + list(run["inner_val_rows"])
106
+ test = sample_ids[fold == j].tolist()
107
+ if sorted(run["test_rows_never_loaded_for_training"]) != sorted(test):
108
+ raise SystemExit(f"{rj}: its test rows differ from fold {j}'s rows")
109
+ pos = {s: i for i, s in enumerate(sample_ids)}
110
+ if len(set(fit)) != len(fit) or any(s not in pos for s in fit):
111
+ raise SystemExit(f"{rj}: duplicate or unknown fit rows")
112
+ rep = np.asarray(sorted(pos[s] for s in fit), dtype=np.int64)
113
+ if not (usable[rep] & (fold[rep] != j)).all():
114
+ raise SystemExit(f"{rj}: a fit row is unusable or in fold {j}")
115
+ cb = data / "CAL_BUDGET.json"
116
+ if cb.exists():
117
+ e = json.loads(cb.read_text())["folds"][str(j)]["n"][str(n)]
118
+ if sorted(e["fit_sample_ids"]) != sorted(fit) or e["lora_checkpoint_sha256"] != run["checkpoint_sha256"]:
119
+ raise SystemExit(f"{cb}: fold {j} n={n} fit rows / LoRA checkpoint differ from {rj}")
120
+ train_donors = sorted(set(donors[rep]))
121
+ cond = data / f"fold{j}" / "test_raw.npz"
122
+ sources = {"lora_RUN.json": rj, **({"CAL_BUDGET.json": cb} if cb.exists() else {})}
123
+ extra = {"budget": {"n": int(n), "fold": int(j), "lora_run": str(rj), "lora_checkpoint_sha256": run["checkpoint_sha256"],
124
+ "n_train_rows": len(run["train_rows"]), "n_inner_val_rows": len(run["inner_val_rows"]),
125
+ "train_rows": list(run["train_rows"]), "inner_val_rows": list(run["inner_val_rows"])}}
126
+ else:
127
+ raise SystemExit(f"unknown mode {mode}")
128
+ pos = {s: i for i, s in enumerate(sample_ids)}
129
+ miss = [s for s in test if s not in pos]
130
+ if miss:
131
+ raise SystemExit(f"test samples not in features.npz: {miss[:5]}")
132
+ tgt = np.asarray([pos[s] for s in test], dtype=np.int64)
133
+ if not usable[tgt].all():
134
+ raise SystemExit("a test row is not usable (fold -1)")
135
+ if set(donors[rep]) & set(donors[tgt]):
136
+ raise SystemExit("a donor is both representative and target")
137
+ if len(set(test)) != len(test):
138
+ raise SystemExit("duplicate test samples")
139
+ return {"rep": rep, "tgt": tgt, "train_donors": train_donors, "test": test, "condition": cond, "sources": sources,
140
+ **extra}
141
+
142
+
143
+ def main(argv=None) -> int:
144
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
145
+ ap.add_argument("--dataset", required=True)
146
+ ap.add_argument("--mode", choices=["fewshot", "cv", "budget"], default="fewshot")
147
+ ap.add_argument("--draw", type=int, help="fewshot draw index")
148
+ ap.add_argument("--fold", type=int, help="cv / budget fold index")
149
+ ap.add_argument("--n", type=int, help="budget: the LoRA learning-curve n (runs/<ds>/fold<k>/lora_n<n>)")
150
+ ap.add_argument("--work", type=Path, required=True)
151
+ ap.add_argument("--smoke-reps", type=int, default=0, help="SMOKE ONLY: keep the first N representative rows")
152
+ ap.add_argument("--smoke-cells", type=int, default=0, help="SMOKE ONLY: at most N cells per representative")
153
+ ap.add_argument("--smoke-targets", default="", help="SMOKE ONLY: comma list of target sample ids")
154
+ ap.add_argument("--smoke-rep-ids", default="", help="SMOKE ONLY: comma list of representative sample ids to keep")
155
+ ap.add_argument("--check-only", action="store_true", help="dry run: check everything, write nothing under --work")
156
+ ap.add_argument("--check-out", type=Path, default=None, help="--check-only: write the split summary JSON here")
157
+ ap.add_argument("--support-manifest", type=Path, default=None,
158
+ help="strict support.json; representatives are its exact n sample IDs")
159
+ a = ap.parse_args(argv)
160
+ if a.support_manifest is not None:
161
+ if a.draw is not None or a.fold is not None or a.n is not None:
162
+ raise SystemExit("--support-manifest cannot be combined with --draw/--fold/--n")
163
+ a.mode = "strict"
164
+ j = 0
165
+ else:
166
+ j = a.draw if a.mode == "fewshot" else a.fold
167
+ if j is None:
168
+ raise SystemExit("--draw (fewshot) or --fold (cv, budget) required")
169
+ if (a.mode == "budget") != (a.n is not None):
170
+ raise SystemExit("--n is required with --mode budget and only valid there")
171
+ smoke = bool(a.smoke_reps or a.smoke_cells or a.smoke_targets or a.smoke_rep_ids)
172
+ if a.support_manifest is not None and smoke:
173
+ raise SystemExit("strict support forbids smoke subsetting")
174
+ work = a.work.resolve()
175
+ if smoke and "/scsemi/smoke/" not in str(work) + "/":
176
+ raise SystemExit("smoke subsetting only under scsemi/smoke/")
177
+ out = work / "inputs"
178
+ if not a.check_only:
179
+ if (out / "inputs_manifest.json").exists():
180
+ raise SystemExit(f"{out}/inputs_manifest.json exists; inputs are immutable (preserve and inspect)")
181
+ out.mkdir(parents=True, exist_ok=True)
182
+ data = TASK / "data" / a.dataset
183
+ isolation = None
184
+ if a.support_manifest is not None:
185
+ strict_tools = TASK.parents[1] / "plans/paper_figures_strictpairs_20261012/tools"
186
+ sys.path.insert(0, str(strict_tools))
187
+ from support_input_isolation import bulk_only_load, materialize
188
+ d = bulk_only_load(data)
189
+ else:
190
+ d = PD.load(data)
191
+ folds = pd.read_csv(data / "folds.csv")
192
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), d["sample_ids"]):
193
+ raise SystemExit("folds.csv rows differ from features.npz")
194
+ s = split_rows(a.dataset, a.mode, j, d["sample_ids"], folds, n=a.n,
195
+ support_manifest=a.support_manifest)
196
+ rep, tgt = s["rep"], s["tgt"]
197
+ if a.smoke_rep_ids:
198
+ keep_r = set(a.smoke_rep_ids.split(","))
199
+ rep = np.asarray([r for r in rep if d["sample_ids"][r] in keep_r], dtype=np.int64)
200
+ if a.smoke_reps:
201
+ rep = rep[: a.smoke_reps]
202
+ if a.smoke_targets:
203
+ keep = set(a.smoke_targets.split(","))
204
+ tgt = np.asarray([t for t in tgt if d["sample_ids"][t] in keep], dtype=np.int64)
205
+ s["test"] = [x for x in s["test"] if x in keep]
206
+ if a.mode == "fewshot" and not smoke:
207
+ usable = np.flatnonzero(folds["fold"].to_numpy() >= 0)
208
+ if set(rep.tolist()) | set(tgt.tolist()) != set(usable.tolist()):
209
+ raise SystemExit("representatives + targets do not cover the usable rows")
210
+ # modeled genes
211
+ cells_path = data / "cells_panel6k.npz"
212
+ if a.support_manifest is not None:
213
+ cells_path, isolation = materialize(a.support_manifest, dataset_dir=data)
214
+ z = np.load(cells_path, allow_pickle=False)
215
+ panel = z["panel_gene_ids"].astype(str)
216
+ gpos = {g: i for i, g in enumerate(d["gene_ids"])}
217
+ pcanon = np.asarray([gpos[g] for g in panel], dtype=np.int64)
218
+ rows = np.sort(np.concatenate([rep, tgt]))
219
+ bulk_ok = d["bulk_valid"][rows][:, pcanon].all(0)
220
+ sc_ok = d["sc_valid"][rep][:, pcanon].all(0)
221
+ model_pidx = np.flatnonzero(bulk_ok & sc_ok)
222
+ genes = panel[model_pidx]
223
+ if genes.size < 1000:
224
+ raise SystemExit(f"only {genes.size} modeled genes")
225
+ # scorer's scoring genes (all rows of the dataset) for the record
226
+ score_mask = d["bulk_valid"][:, pcanon].all(0) & d["sc_valid"][:, pcanon].all(0)
227
+ # bulk
228
+ import anndata as ad
229
+ B = d["bulk"][rows][:, pcanon[model_pidx]].astype(np.float64)
230
+ if not np.isfinite(B).all() or (B < 0).any():
231
+ raise SystemExit("non-finite or negative bulk on the modeled genes")
232
+ if (B.sum(1) <= 0).any():
233
+ raise SystemExit("a bulk row has no counts on the modeled genes")
234
+ sym = pd.read_csv(TASK.parents[1] / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv")
235
+ sym = sym.set_index("gene_id").gene_symbol.astype(str)
236
+ var = pd.DataFrame({"gene_symbol": sym.reindex(genes).to_numpy()}, index=pd.Index(genes, name="gene_id"))
237
+ obs_b = pd.DataFrame({"sample_ids": d["sample_ids"][rows], "donor_id": d["donor_ids"][rows],
238
+ "group": d["groups"][rows], "role": np.where(np.isin(rows, rep), "representative", "target")},
239
+ index=pd.Index(d["sample_ids"][rows], name="obs"))
240
+ if not a.check_only:
241
+ ad.AnnData(X=B, obs=obs_b, var=var).write_h5ad(out / "bulk.h5ad")
242
+ # representative cells
243
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(int(x) for x in z["shape"]))
244
+ rs = np.asarray(z["row_sample"], dtype=np.int64)
245
+ z.close()
246
+ blocks, obs_rows, per_rep = [], [], []
247
+ rng = np.random.default_rng(SEED)
248
+ for r in rep:
249
+ cells = np.flatnonzero(rs == r)
250
+ if a.smoke_cells and cells.size > a.smoke_cells:
251
+ cells = np.sort(rng.choice(cells, a.smoke_cells, replace=False))
252
+ Xr = X[cells][:, model_pidx].tocsr().astype(np.float32)
253
+ lib = np.asarray(Xr.sum(1)).ravel()
254
+ if (lib <= 0).any():
255
+ raise SystemExit(f"{d['sample_ids'][r]}: {int((lib <= 0).sum())} cells without counts on the modeled genes")
256
+ blocks.append(Xr)
257
+ obs_rows.append(pd.DataFrame({"sample_ids": d["sample_ids"][r], "donor_id": d["donor_ids"][r],
258
+ "source_cell_row": cells}))
259
+ per_rep.append({"sample_id": str(d["sample_ids"][r]), "donor_id": str(d["donor_ids"][r]),
260
+ "group": str(d["groups"][r]), "n_cells": int(cells.size),
261
+ "median_umi_modeled_genes": float(np.median(lib))})
262
+ Xs = sp.vstack(blocks, format="csr")
263
+ obs_s = pd.concat(obs_rows, ignore_index=True)
264
+ obs_s.index = pd.Index([f"{a_}|{b_}" for a_, b_ in zip(obs_s.sample_ids, obs_s.source_cell_row)], name="cell")
265
+ if not a.check_only:
266
+ ad.AnnData(X=Xs, obs=obs_s, var=var.copy()).write_h5ad(out / "rep_sc.h5ad")
267
+ lib_all = np.asarray(Xs.sum(1)).ravel()
268
+ depth = float(np.median(lib_all))
269
+ cond = s["condition"]
270
+ man = {
271
+ "schema": "scsemi_paired.inputs.v1", "written_utc": datetime.now(timezone.utc).isoformat(),
272
+ "dataset": a.dataset, "mode": a.mode, "split": j, "smoke": smoke,
273
+ "smoke_settings": {"reps": a.smoke_reps, "cells": a.smoke_cells, "targets": a.smoke_targets,
274
+ "rep_ids": a.smoke_rep_ids} if smoke else None,
275
+ "train_donors": s["train_donors"],
276
+ "representatives": per_rep, "targets": [str(x) for x in d["sample_ids"][tgt]],
277
+ "target_order_test_samples": s["test"],
278
+ "bulk_row_order": [str(x) for x in d["sample_ids"][rows]],
279
+ "n_representatives": int(rep.size), "n_targets": int(tgt.size), "n_rep_cells": int(Xs.shape[0]),
280
+ "modeled_genes": {"n": int(genes.size), "gene_ids": genes.tolist(), "panel_index": model_pidx.tolist(),
281
+ "rule": "6k panel genes with bulk_valid in every rep+target row and sc_valid in every rep row",
282
+ "equals_scorer_scoring_genes": bool(np.array_equal(model_pidx, np.flatnonzero(score_mask))),
283
+ "n_scorer_scoring_genes": int(score_mask.sum())},
284
+ "depth": {"value": depth, "rule": "median over all representative cells (all rows of the training donors) of the "
285
+ "per-cell UMI sum on the modeled genes; every generated cell is scaled to this expected library",
286
+ "n_cells": int(lib_all.size)},
287
+ "condition_npz": str(cond), "condition_sha256": sha(cond),
288
+ "sources": {"features.npz": sha(data / "features.npz"), "folds.csv": sha(data / "folds.csv"),
289
+ "cells_panel6k.npz": sha(data / "cells_panel6k.npz"),
290
+ **{k: sha(v) for k, v in s["sources"].items()}},
291
+ "files": ({"bulk.h5ad": sha(out / "bulk.h5ad"), "rep_sc.h5ad": sha(out / "rep_sc.h5ad")}
292
+ if not a.check_only else None),
293
+ "builder_sha256": sha(Path(__file__)),
294
+ }
295
+ if a.mode == "strict":
296
+ man["support_sha256"] = s["support_sha256"]
297
+ man["target_donors"] = s["target_donors"]
298
+ man["support_expression_isolation"] = isolation
299
+ man["sources"]["cells_support_only.npz"] = isolation["isolated_cells_sha256"]
300
+ man["sources"]["support_input_isolation.py"] = isolation["builder_sha256"]
301
+ man["depth"]["rule"] = ("median over cells of the exact support samples of the per-cell UMI sum "
302
+ "on the modeled genes; every generated cell is scaled to this expected library")
303
+ if a.mode == "budget":
304
+ man["target_donors"] = sorted({str(x) for x in d["donor_ids"][tgt]})
305
+ man["budget"] = s["budget"]
306
+ with np.load(cond, allow_pickle=False) as cz:
307
+ cond_ids = cz["sample_ids"].astype(str).tolist()
308
+ if not smoke and sorted(cond_ids) != sorted(man["targets"]):
309
+ raise SystemExit("condition NPZ sample_ids differ from the targets")
310
+ man["condition_sample_order"] = cond_ids
311
+ if a.check_only:
312
+ summary = {"dataset": a.dataset, "mode": a.mode, "split": j, "n": a.n, "work": str(work),
313
+ "reps": [r["sample_id"] for r in per_rep], "targets": man["targets"],
314
+ "rep_cells": {r["sample_id"]: r["n_cells"] for r in per_rep}, "n_rep_cells": int(Xs.shape[0]),
315
+ "modeled_genes": int(genes.size), "modeled_panel_index": model_pidx.tolist(),
316
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"],
317
+ "depth": depth, "condition_npz": str(cond), "condition_matches_targets": True,
318
+ "train_donors": s["train_donors"], **({"budget": s["budget"]} if a.mode == "budget" else {})}
319
+ if a.check_out is not None:
320
+ a.check_out.parent.mkdir(parents=True, exist_ok=True)
321
+ a.check_out.write_text(json.dumps(summary, indent=1) + "\n")
322
+ print(json.dumps({k: summary[k] for k in ("dataset", "mode", "split", "n", "n_rep_cells", "modeled_genes",
323
+ "equals_scorer_genes", "depth")} | {"reps": len(summary["reps"]),
324
+ "targets": len(summary["targets"])}))
325
+ return 0
326
+ tmp = out / "inputs_manifest.json.tmp"
327
+ tmp.write_text(json.dumps(man, indent=1) + "\n")
328
+ tmp.replace(out / "inputs_manifest.json")
329
+ print(json.dumps({"dataset": a.dataset, "mode": a.mode, "split": j, "reps": int(rep.size), "targets": int(tgt.size),
330
+ "rep_cells": int(Xs.shape[0]), "modeled_genes": int(genes.size),
331
+ "equals_scorer_genes": man["modeled_genes"]["equals_scorer_scoring_genes"], "depth": depth}))
332
+ return 0
333
+
334
+
335
+ if __name__ == "__main__":
336
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/18/immicro-healthy-fold1-n5-train-proof.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "operation": "immicro-healthy-fold1-n5-train",
3
+ "old_signature_reproduced": "1f82de5256dadba1d66d0756684eac3d4373329abe9606684ebb9036cd42618f",
4
+ "new_signature": "6b102fb7edbdafd80b61c231398bf40bfbf6bec4420c148a9e265b1064a45263",
5
+ "source_backups": [
6
+ {
7
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/support_input_isolation.py",
8
+ "backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/backups/recovery_input_isolation_20261012T142024Z/plans/paper_figures_strictpairs_20261012/tools/support_input_isolation.py",
9
+ "sha256": "1e383c79085c6d20afd839b401ec2e321df3d535d3d1b5552ba9f0e59ba033af"
10
+ },
11
+ {
12
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py",
13
+ "backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/backups/recovery_input_isolation_20261012T142024Z/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py",
14
+ "sha256": "e7f3d38b65932ffe99292a8841a15eb9e7cce205afec1de6b34b59a06731b82d"
15
+ },
16
+ {
17
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py",
18
+ "backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/backups/recovery_input_isolation_20261012T142024Z/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py",
19
+ "sha256": "b11b9f206a04fdac99dc489a8387647f0a334a59d5761a0c1bd964301933da8f"
20
+ }
21
+ ],
22
+ "support_manifest_sha256": "0c8f07d519c3220b15f67ad58975b8f4938556d12da65c1d9e15a6625cc4422d",
23
+ "selected_computation_replay": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/isolated/immicro/healthy/fold1/n5/REPLAY.json",
24
+ "outputs_unchanged": [
25
+ {
26
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/runs/immicro/healthy/fold1/n5/lora/checkpoint_ft.pt",
27
+ "bytes": 217979993,
28
+ "mtime_ns": 1791811321684029262,
29
+ "sha256": "b3307fb321381403e5b584e9b458dc26bb150e507193331cd51938a40333c0be"
30
+ },
31
+ {
32
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/runs/immicro/healthy/fold1/n5/lora/RUN.json",
33
+ "bytes": 2971,
34
+ "mtime_ns": 1791811324045528145,
35
+ "sha256": "9cb350164d0cfa7ca254754ba0149a2b8b45fbb4ce87c363e5669171dd8393a6"
36
+ }
37
+ ],
38
+ "limitation": "Original loaders materialized non-support arrays before selection. Reuse establishes selected-computation equivalence, not historical physical input isolation."
39
+ }
paper-releases/pbisc-diffusion/updates/20261012T143729Z-strictpairs-recovery-two-host/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T143729Z-strictpairs-recovery-two-host/snapshot/19/immicro-healthy-fold0-n5-train-proof.json ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "operation": "immicro-healthy-fold0-n5-train",
3
+ "old_signature_reproduced": "2ca886713c69144fd1ef558468dbeba98e7f9840c0fe183f683af69e065b14e2",
4
+ "new_signature": "ab97afdd574f8ec532dfade4e716e9ddfccf68dc732848f35932a6f8c15561d8",
5
+ "source_backups": [
6
+ {
7
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/support_input_isolation.py",
8
+ "backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/backups/recovery_input_isolation_20261012T142024Z/plans/paper_figures_strictpairs_20261012/tools/support_input_isolation.py",
9
+ "sha256": "1e383c79085c6d20afd839b401ec2e321df3d535d3d1b5552ba9f0e59ba033af"
10
+ },
11
+ {
12
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py",
13
+ "backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/backups/recovery_input_isolation_20261012T142024Z/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py",
14
+ "sha256": "e7f3d38b65932ffe99292a8841a15eb9e7cce205afec1de6b34b59a06731b82d"
15
+ },
16
+ {
17
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py",
18
+ "backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/backups/recovery_input_isolation_20261012T142024Z/plans/paired_finetune_intradataset_20260927/scsemi/tools/prepare_draw_inputs.py",
19
+ "sha256": "b11b9f206a04fdac99dc489a8387647f0a334a59d5761a0c1bd964301933da8f"
20
+ }
21
+ ],
22
+ "support_manifest_sha256": "a8ead926beae1f969e4cdf4b4a555a110e37d0bf3a27be3f9e4720c879f88740",
23
+ "selected_computation_replay": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/isolated/immicro/healthy/fold0/n5/REPLAY.json",
24
+ "outputs_unchanged": [
25
+ {
26
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/runs/immicro/healthy/fold0/n5/lora/checkpoint_ft.pt",
27
+ "bytes": 217979993,
28
+ "mtime_ns": 1791802695247754575,
29
+ "sha256": "51eb269bf13e9ead76da3fdd3bb9ca6400c2de7014f85286ecc0e0c11ad9df11"
30
+ },
31
+ {
32
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/runs/immicro/healthy/fold0/n5/lora/RUN.json",
33
+ "bytes": 2970,
34
+ "mtime_ns": 1791802697688986618,
35
+ "sha256": "92452f8776859a729274f5afc2e785a7d5869e80123a8297a5a3ac48719cc980"
36
+ }
37
+ ],
38
+ "limitation": "Original loaders materialized non-support arrays before selection. Reuse establishes selected-computation equivalence, not historical physical input isolation."
39
+ }