junidude14 commited on
Commit
e7a1524
·
verified ·
1 Parent(s): 01a82e6

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/build_archive_request.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Archive-maintenance request for the cross-cohort (LOCO) benchmark (PBISC-Diffusion paper, pbisc-diffusion).
3
+
4
+ Follows paper-release-20260928/maintenance/POLICY.md. Payloads (completed): code, README, queues, splits / prepare
5
+ manifests, run receipts (RUN.json, history.json, milestones.json, train.log; every fine-tuned checkpoint's sha256 is in
6
+ RUN.json), score tables, aggregates and the LoRA integrity audit. Not uploaded: fine-tuned checkpoints and generated
7
+ NPZs (location + receipt only). Generated NPZs are on server_1, or on server_2 at the same path after a sha-checked
8
+ move (tools/offload_scored.sh leaves <name>.moved on server_1). Queue units not finished yet are registered as planned while claims/.queue_live exists, else as stopped.
9
+ Condition NPZs and Liu inputs were published in earlier deltas; unchanged files are skipped by update.py.
10
+ usage: build_archive_request.py OUT.json "summary text"
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import glob
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ P = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002")
20
+ EXPERIMENT = "paired_crosscohort_loco_20261002"
21
+
22
+
23
+ def files(patterns):
24
+ out = []
25
+ for pat in patterns:
26
+ for f in sorted(glob.glob(str(P / pat), recursive=True)):
27
+ q = Path(f)
28
+ if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and ".bak" not in q.name \
29
+ and not q.name.endswith(".tmp"):
30
+ out.append(str(q))
31
+ return sorted(set(out))
32
+
33
+
34
+ def main(out: str, summary: str) -> int:
35
+ assets = []
36
+
37
+ def add(paths, kind):
38
+ for p in paths:
39
+ assets.append({"host": "server_1", "source": p, "kind": kind, "state": "completed"})
40
+
41
+ add(files(["tools/*.py", "tools/*.sh"]), "code")
42
+ add(files(["README.md"]), "document")
43
+ add(files(["queues/*.txt"]), "config")
44
+ add(files(["PREPARE.json", "PREPARE_EXTRA.json", "splits/*.json", "data/*/*.txt", "audit/*.json"]), "metadata")
45
+ add(files(["runs/**/RUN.json", "runs/**/history.json", "runs/**/milestones.json", "runs/**/train.log",
46
+ "audit/*.log"]), "log")
47
+ add(files(["scores/aggregate.csv", "scores/AGGREGATE.md", "scores/k1000_saturated_summary.csv",
48
+ "scores/*/*/summary.json", "scores/*/*/per_donor.csv", "scores/*/*/contrast.csv", "scores/*/*/README.md",
49
+ "scores_nosex/*/*/summary.json", "scores_nosex/*/*/per_donor.csv", "scores_nosex/*/*/contrast.csv",
50
+ "scores_nosex/*/*/README.md"]), "table")
51
+ # 2026-10-05 no-pretraining pilot (held-out sepsis): masked rescore of every arm (tools/mask_rescore.py: genes no
52
+ # training cohort measured zeroed) and the masked-NPZ receipts (the masked NPZs themselves are deleted after scoring)
53
+ add(files(["scores_masked/*/*.csv", "scores_masked/*/*/summary.json", "scores_masked/*/*/per_donor.csv",
54
+ "scores_masked/*/*/contrast.csv", "scores_masked/*/*/README.md",
55
+ "scores_masked/*/*/arms/*/deg_top50_lists.csv", "scores_masked/*/*/arms/*/labels/labels.manifest.json"]), "table")
56
+ add(files(["generated_masked/*/*/*.log", "logs/mask_rescore/*.log"]), "log")
57
+
58
+ locs, seen = [], set()
59
+ for rec in sorted(glob.glob(str(P / "generated" / "**" / "*.log"), recursive=True)):
60
+ try:
61
+ r = json.loads(Path(rec).read_text())
62
+ except Exception:
63
+ continue
64
+ if not isinstance(r, dict) or not r.get("output_sha256"):
65
+ continue
66
+ npz = rec[:-4] + ".npz"
67
+ moved = Path(rec[:-4] + ".moved")
68
+ if Path(npz).is_file():
69
+ host = "server_1"
70
+ elif moved.is_file():
71
+ host = "server_2"
72
+ else:
73
+ continue
74
+ rel = Path(npz).relative_to(P / "generated")
75
+ item = {"host": host, "path": npz, "state": "completed", "experiment": EXPERIMENT, "cohort": rel.parts[0],
76
+ "artifact_role": "inference_output", "receipt": rec, "sha256": r["output_sha256"]}
77
+ for k in ("output_sha256", "checkpoint", "checkpoint_sha256", "input_condition_path", "input_condition_sha256",
78
+ "condition_npz", "condition_sha256", "seed", "steps"):
79
+ if k in r and not isinstance(r[k], (dict, list)):
80
+ item[k] = r[k]
81
+ if host == "server_2":
82
+ item["move_marker_server_1"] = str(moved)
83
+ locs.append(item)
84
+ seen.add(npz)
85
+ # unfinished units of the active queue: planned
86
+ for q in ("loco_liu_sat_20261003.txt",):
87
+ for line in (P / "queues" / q).read_text().splitlines():
88
+ if not line or line.startswith("#"):
89
+ continue
90
+ f = line.split("|")
91
+ if f[0] == "zs":
92
+ outs, cohort = [P / "generated" / f[1] / f"zs_K{f[2]}.npz"], f[1]
93
+ else:
94
+ cohort = json.loads((P / "splits" / f"{f[1]}.json").read_text())["held_out"]
95
+ if f[0] == "xcal":
96
+ outs = [P / "generated" / cohort / f[1] / f"xcal_K{f[2]}.npz"]
97
+ else: # milestone outputs are unknown until training ends: register the run's output stem
98
+ outs = [P / "generated" / cohort / f[1] / f"K{f[2]}_{f[3]}.npz"]
99
+ if glob.glob(str(outs[0])[:-4] + "_s*.log"):
100
+ continue
101
+ key = ("zs_%s_K%s" % (f[1], f[2]) if f[0] == "zs" else "xcal_%s_K%s" % (f[1], f[2]) if f[0] == "xcal"
102
+ else "loco_%s_K%s_%s" % (f[1], f[2], f[3]))
103
+ queue_live = (P / "claims" / ".queue_live").exists()
104
+ for o in outs:
105
+ if str(o) in seen:
106
+ continue
107
+ if queue_live:
108
+ state, note = "planned", ("queued or running at request time (run_loco_queue.sh, server_1); a "
109
+ "step-saturation run writes one output per milestone, <stem>_s<step>.npz")
110
+ else:
111
+ state, note = "stopped", ("not run: user decision 2026-10-03 19:45, the cross-cohort benchmark is "
112
+ "reported at K = 1000 only; queue stopped (claim " + key + ")")
113
+ locs.append({"host": "server_1", "path": str(o), "state": state, "experiment": EXPERIMENT,
114
+ "cohort": cohort, "artifact_role": "inference_output", "note": note})
115
+ seen.add(str(o))
116
+ req = {"project_id": "pbisc-diffusion", "summary": summary, "assets": assets, "inference_locations": locs}
117
+ Path(out).write_text(json.dumps(req, indent=1))
118
+ kinds, states = {}, {}
119
+ for a in assets:
120
+ kinds[a["kind"]] = kinds.get(a["kind"], 0) + 1
121
+ for l in locs:
122
+ states[(l["host"], l["state"])] = states.get((l["host"], l["state"]), 0) + 1
123
+ print(json.dumps({"assets": len(assets), "by_kind": kinds, "locations": {f"{h}/{s}": n for (h, s), n in states.items()}}))
124
+ return 0
125
+
126
+
127
+ if __name__ == "__main__":
128
+ sys.exit(main(sys.argv[1], sys.argv[2]))
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_crosscohort_20261002/tools/ft_sdd_multi.py ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Fine-tune the final PBISC-SDD model on the paired pairs of several cohorts (cross-cohort / LOCO benchmark).
3
+
4
+ Same training as plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py (imported: LoRA parametrization,
5
+ trainable sets, cell store, checkpoint schema, reload check), with the rows of several cohorts:
6
+ - a split file (tools/prepare_loco.py: splits/<split>.json) names the training cohorts and, per cohort, the
7
+ training and inner-validation sample ids; the held-out cohort is never read
8
+ - each cohort keeps its own condition NPZ at recipe size --k (real bulk, fixed depth), its own per-row
9
+ measurement fraction and output availability mask, and its own cells (cells_panel6k.npz)
10
+ - batches are cohort-balanced (--balance cohort, default): each of the batch's cells picks a cohort uniformly,
11
+ then a training row of that cohort uniformly, then one of the row's cells uniformly. --balance row draws a
12
+ row uniformly from all cohorts' training rows (as ft_sdd.py does inside one cohort)
13
+ - inner validation: fixed draws per cohort; the early-stopping loss is the mean over cohorts that have
14
+ inner-validation rows of each cohort's mean loss (cohort-balanced); per-cohort losses go to history.json
15
+ Loss, optimiser, EMA, early stopping and the saved checkpoint are as in ft_sdd.py, so
16
+ scripts/sample_sdd_standalone.py samples the output unchanged.
17
+
18
+ Step-saturation protocol (--block N, user decision 2026-10-03): training runs in blocks of N steps (cap --max-steps).
19
+ At the end of every block the best-so-far EMA state (lowest inner-validation loss) is saved as a milestone checkpoint
20
+ checkpoint_ft_s<step>.pt (LoRA merged, same schema), and training stops when the block lowered the best
21
+ inner-validation loss by less than --saturation-frac (default 1 %) of the total improvement over the pretrained model
22
+ ("saturated"); patience early stopping still applies inside a block. RUN.json lists the milestones; checkpoint_ft.pt
23
+ is the overall best (= the last milestone). Without --block the behaviour is exactly the earlier single-cap run.
24
+
25
+ No-pretraining ablation (added 2026-10-05; default unchanged): --init random re-initialises every denoiser weight as at
26
+ the start of pretraining (a fresh ConditionalSBDDenoiser(model_config) under torch.manual_seed(--init-seed)) and needs
27
+ --mode full. The checkpoint still supplies the architecture, the 6k panel, the value scaler and the bulk conditioner's
28
+ z-score constants (preprocessing, not learned weights). "pretrained_inner_val_loss" is then the random-init step-0 loss.
29
+ """
30
+ from __future__ import annotations
31
+
32
+ import argparse
33
+ import json
34
+ import os
35
+ import sys
36
+ import time
37
+ from datetime import datetime, timezone
38
+ from pathlib import Path
39
+
40
+ import numpy as np
41
+ import pandas as pd
42
+ import torch
43
+ from torch import nn
44
+
45
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
46
+ SRC_TOOLS = M8 / "plans/paired_finetune_intradataset_20260927/tools"
47
+ sys.path.insert(0, str(SRC_TOOLS))
48
+ import ft_sdd as FT # noqa: E402
49
+
50
+ SS = FT.SS
51
+ cwmc = FT.condition_with_measurement_context
52
+ SCHEMA = "pbisc_sdd.ft_crosscohort.run.v1"
53
+ log = FT.log
54
+
55
+
56
+ class Cohort:
57
+ def __init__(self, spec: dict, k: int, bundle, device, ci: int) -> None:
58
+ self.name = spec["cohort"]
59
+ self.index = ci
60
+ ds = Path(spec["dataset_dir"])
61
+ self.cond_npz = Path(spec["condition_npz"][str(k)])
62
+ ext = SS.load_conditions(self.cond_npz, bundle, default_cells_per_bulk=1)
63
+ if not bool((np.asarray(ext.recipe_k) == k).all()):
64
+ raise SystemExit(f"{self.name}: condition NPZ recipe_k is not {k}")
65
+ folds = pd.read_csv(ds / "folds.csv")
66
+ sids = folds["sample_id"].astype(str).to_numpy()
67
+ if not np.array_equal(sids, ext.sample_ids.astype(str)):
68
+ raise SystemExit(f"{self.name}: condition NPZ rows differ from folds.csv")
69
+ pos = {s: i for i, s in enumerate(sids)}
70
+ self.train_rows = np.asarray([pos[s] for s in spec["train_sample_ids"]], dtype=np.int64)
71
+ self.inner_rows = np.asarray([pos[s] for s in spec["inner_val_sample_ids"]], dtype=np.int64)
72
+ usable = folds["fold"].to_numpy() >= 0
73
+ if not usable[self.train_rows].all() or not usable[self.inner_rows].all():
74
+ raise SystemExit(f"{self.name}: a training or inner-validation row is not usable")
75
+ if set(folds.loc[self.train_rows, "donor_id"]) & set(folds.loc[self.inner_rows, "donor_id"]):
76
+ raise SystemExit(f"{self.name}: an inner-validation donor is also a training donor")
77
+ self.cells = FT.Cells(ds / "cells_panel6k.npz", bundle.gene_ids)
78
+ with np.load(ds / "cells_panel6k.npz", allow_pickle=False) as z:
79
+ pm = z["panel_measured"].astype(bool)
80
+ if not np.array_equal(pm, ext.output_availability_mask.astype(bool)):
81
+ raise SystemExit(f"{self.name}: cells' measured panel differs from the condition NPZ")
82
+ base = torch.from_numpy(ext.base_conditions.astype(np.float32)).to(device)
83
+ frac = torch.from_numpy(ext.bulk_measurement_fraction.astype(np.float32)).to(device)
84
+ self.avail = torch.from_numpy(ext.output_availability_mask.astype(bool)).to(device)
85
+ self.cond = cwmc(base, frac, self.avail)
86
+ self.cond_sha = ext.input_sha256
87
+ self.sample_ids = sids
88
+ self.donors = folds["donor_id"].astype(str).to_numpy()
89
+
90
+ def draw(self, n: int, rng: np.random.Generator) -> tuple[np.ndarray, np.ndarray]:
91
+ r = self.train_rows[rng.integers(0, len(self.train_rows), size=n)]
92
+ c = self.cells.start[r] + np.floor(rng.random(n) * self.cells.count[r]).astype(np.int64)
93
+ return r, c
94
+
95
+
96
+ def main(argv=None) -> int:
97
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
98
+ ap.add_argument("--checkpoint", type=Path, required=True)
99
+ ap.add_argument("--checkpoint-sha", required=True)
100
+ ap.add_argument("--split", type=Path, required=True, help="splits/<split>.json from prepare_loco.py")
101
+ ap.add_argument("--k", type=int, required=True, help="recipe size of the training conditions")
102
+ ap.add_argument("--mode", choices=("full", "condenc", "lora"), required=True)
103
+ ap.add_argument("--lora-rank", type=int, default=16)
104
+ ap.add_argument("--lora-alpha", type=float, default=16.0)
105
+ ap.add_argument("--lr", type=float, required=True)
106
+ ap.add_argument("--balance", choices=("cohort", "row"), default="cohort")
107
+ ap.add_argument("--warmup", type=int, default=200)
108
+ ap.add_argument("--batch-size", type=int, default=256)
109
+ ap.add_argument("--max-steps", type=int, default=20000)
110
+ ap.add_argument("--eval-every", type=int, default=250)
111
+ ap.add_argument("--patience", type=int, default=8)
112
+ ap.add_argument("--ema-decay", type=float, default=0.999)
113
+ ap.add_argument("--val-cells-per-row", type=int, default=256)
114
+ ap.add_argument("--val-repeats", type=int, default=2)
115
+ ap.add_argument("--seed", type=int, default=20261002)
116
+ ap.add_argument("--out-dir", type=Path, required=True)
117
+ ap.add_argument("--device", default="cuda")
118
+ ap.add_argument("--max-cuda-gib", type=float, default=8.0)
119
+ ap.add_argument("--min-system-gib", type=float, default=32.0)
120
+ ap.add_argument("--smoke", action="store_true", help="tiny run for tests (20 steps, CPU allowed)")
121
+ ap.add_argument("--block", type=int, default=0, help="step-saturation protocol: block length (0 = off)")
122
+ ap.add_argument("--saturation-frac", type=float, default=0.01,
123
+ help="stop when a block improves the best inner-val loss by less than this fraction of the total")
124
+ ap.add_argument("--init", choices=("pretrained", "random"), default="pretrained",
125
+ help="random: no-pretraining ablation, fresh denoiser weights (requires --mode full)")
126
+ ap.add_argument("--init-seed", type=int, default=20260627, help="torch seed of the random init (pretraining's)")
127
+ a = ap.parse_args(argv)
128
+ if a.init == "random" and a.mode != "full":
129
+ raise SystemExit("--init random needs --mode full (LoRA / condenc need pretrained base weights)")
130
+
131
+ a.out_dir.mkdir(parents=True, exist_ok=True)
132
+ done = a.out_dir / "checkpoint_ft.pt"
133
+ if done.exists() and (a.out_dir / "RUN.json").exists():
134
+ log(f"{done} exists; nothing to do")
135
+ return 0
136
+ avail = int(open("/proc/meminfo").read().split("MemAvailable:")[1].split()[0]) / 1048576
137
+ if avail < a.min_system_gib:
138
+ raise SystemExit(f"MemAvailable {avail:.1f} GiB < floor {a.min_system_gib}")
139
+ got = FT.sha256_file(a.checkpoint)
140
+ if got != a.checkpoint_sha:
141
+ raise SystemExit(f"checkpoint sha {got[:12]} != {a.checkpoint_sha[:12]}")
142
+ split = json.loads(a.split.read_text())
143
+ device = torch.device(a.device)
144
+ if device.type == "cuda" and device.index is None:
145
+ device = torch.device("cuda", 0)
146
+ if device.type == "cuda":
147
+ total = torch.cuda.get_device_properties(device).total_memory
148
+ torch.cuda.set_per_process_memory_fraction(min(1.0, a.max_cuda_gib * 2**30 / total), device)
149
+ torch.manual_seed(a.seed)
150
+ rng = np.random.default_rng(a.seed)
151
+
152
+ bundle = SS.restore_standalone(a.checkpoint, device=device, weights="ema", conditioner_source="embedded")
153
+ diffusion, scaler = bundle.diffusion, bundle.scaler
154
+ init_info = {"init": a.init}
155
+ if a.init == "random":
156
+ from pbisc_sdd.model import ConditionalSBDDenoiser
157
+ torch.manual_seed(a.init_seed)
158
+ fresh = ConditionalSBDDenoiser(diffusion.denoiser.config)
159
+ diffusion.denoiser.load_state_dict(fresh.state_dict(), strict=True)
160
+ torch.manual_seed(a.seed)
161
+ init_info.update({"init_seed": a.init_seed, "kept_from_checkpoint": [
162
+ "model_config", "diffusion_config", "gene panel", "value_scaler", "conditioner z-score constants"]})
163
+ del fresh
164
+ log(f"random init of every denoiser weight (seed {a.init_seed}); no pretrained weights used")
165
+ held = split["held_out"]
166
+ cohorts = [Cohort(c, a.k, bundle, device, i) for i, c in enumerate(split["training_cohorts"])]
167
+ if held in {c.name for c in cohorts}:
168
+ raise SystemExit("the held-out cohort is among the training cohorts")
169
+ held_samples = set(split["test"]["sample_ids"])
170
+ for c in cohorts:
171
+ if held_samples & set(c.sample_ids[np.r_[c.train_rows, c.inner_rows]]):
172
+ raise SystemExit(f"{c.name}: held-out sample ids among the training rows")
173
+
174
+ denoiser = diffusion.denoiser
175
+ info = FT.set_trainable(denoiser, a.mode, a.lora_rank, a.lora_alpha)
176
+ params = [p for p in denoiser.parameters() if p.requires_grad]
177
+ named = [(n, p) for n, p in denoiser.named_parameters() if p.requires_grad]
178
+ opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
179
+ ema = {n: p.detach().clone() for n, p in named}
180
+ log(f"split={split['split']} K={a.k} mode={a.mode} trainable={info['n_trainable']:,} balance={a.balance} " +
181
+ "; ".join(f"{c.name}: train {len(c.train_rows)} rows / {int(c.cells.count[c.train_rows].sum()):,} cells, "
182
+ f"inner {len(c.inner_rows)}" for c in cohorts))
183
+
184
+ # fixed inner-validation draws per cohort
185
+ vcpr = 8 if a.smoke else a.val_cells_per_row
186
+ val = {}
187
+ for c in cohorts:
188
+ vrng = np.random.default_rng([a.seed + 1, c.index])
189
+ cs, rs = [], []
190
+ for r in c.inner_rows:
191
+ n = int(c.cells.count[r])
192
+ take = min(vcpr, n)
193
+ cs.append(c.cells.start[r] + np.sort(vrng.choice(n, size=take, replace=False)))
194
+ rs.append(np.full(take, r))
195
+ if cs:
196
+ val[c.name] = (c, np.concatenate(rs), np.concatenate(cs))
197
+
198
+ def to_batch(parts: list) -> tuple:
199
+ xs, conds, avs = [], [], []
200
+ for c, r, cells in parts:
201
+ xs.append(c.cells.dense(cells))
202
+ rr = torch.from_numpy(r).to(device)
203
+ conds.append(c.cond[rr])
204
+ avs.append(c.avail[rr])
205
+ x_log = torch.from_numpy(np.log1p(np.concatenate(xs))).to(device)
206
+ return scaler.to_unit_tensor(x_log), torch.cat(conds), torch.cat(avs), x_log > 0
207
+
208
+ def draw_batch() -> list:
209
+ if a.balance == "cohort":
210
+ k = rng.integers(0, len(cohorts), size=a.batch_size)
211
+ sizes = np.bincount(k, minlength=len(cohorts))
212
+ else:
213
+ n_rows = np.array([len(c.train_rows) for c in cohorts], dtype=np.float64)
214
+ k = rng.choice(len(cohorts), size=a.batch_size, p=n_rows / n_rows.sum())
215
+ sizes = np.bincount(k, minlength=len(cohorts))
216
+ parts = []
217
+ for c, n in zip(cohorts, sizes):
218
+ if n:
219
+ r, cells = c.draw(int(n), rng)
220
+ parts.append((c, r, cells))
221
+ return parts
222
+
223
+ def swap_in_ema() -> dict:
224
+ backup = {n: p.detach().clone() for n, p in named}
225
+ with torch.no_grad():
226
+ for n, p in named:
227
+ p.copy_(ema[n])
228
+ return backup
229
+
230
+ def restore(backup: dict) -> None:
231
+ with torch.no_grad():
232
+ for n, p in named:
233
+ p.copy_(backup[n])
234
+
235
+ @torch.no_grad()
236
+ def val_loss() -> tuple[float, dict]:
237
+ if not val:
238
+ return float("nan"), {}
239
+ diffusion.eval()
240
+ per = {}
241
+ for name, (c, rs, cs) in val.items():
242
+ tot, n = 0.0, 0
243
+ for rep in range(a.val_repeats):
244
+ for i in range(0, len(cs), a.batch_size):
245
+ g = torch.Generator(device=device).manual_seed(a.seed + 1_000_003 * rep + i + 7_919 * c.index)
246
+ v, cond, m, act = to_batch([(c, rs[i:i + a.batch_size], cs[i:i + a.batch_size])])
247
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
248
+ res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=g)
249
+ tot += float(res.loss) * v.shape[0]
250
+ n += v.shape[0]
251
+ per[name] = tot / max(n, 1)
252
+ diffusion.train()
253
+ return float(np.mean(list(per.values()))), per
254
+
255
+ payload_in = SS._load_checkpoint_cpu(a.checkpoint)
256
+ ref_state = payload_in["ema_state"]["model_state"]
257
+ milestones: list = []
258
+ block = (10 if a.smoke else a.block) if a.block else 0
259
+
260
+ def materialize(bstate: dict) -> dict:
261
+ """Full denoiser state (checkpoint key names) with the trainable tensors from bstate, LoRA merged.
262
+ The live trainable tensors are swapped in and restored; a parametrized Linear's .weight is W + (alpha/r) B A,
263
+ exactly what merge_lora leaves. (No deepcopy: copies share the parametrized class, and merging a copy would
264
+ strip .weight from the live modules.)"""
265
+ backup_ = {n_: p_.detach().clone() for n_, p_ in named}
266
+ sd = denoiser.state_dict()
267
+ st = {}
268
+ with torch.no_grad():
269
+ for n_, p_ in named:
270
+ p_.copy_(bstate[n_].to(p_.device))
271
+ for k in ref_state:
272
+ if k in sd and not k.endswith((".A", ".B")):
273
+ st[k] = sd[k].detach().cpu().clone()
274
+ else:
275
+ mod_name, attr = k.rsplit(".", 1)
276
+ st[k] = getattr(denoiser.get_submodule(mod_name), attr).detach().cpu().clone()
277
+ for n_, p_ in named:
278
+ p_.copy_(backup_[n_])
279
+ if set(ref_state.keys()) != set(st.keys()):
280
+ raise SystemExit("fine-tuned state keys differ from the checkpoint's")
281
+ return st
282
+
283
+ def write_milestone(step_: int, reason: str) -> None:
284
+ tot_imp = history[0]["inner_val_loss"] - best["loss"]
285
+ prev = milestones[-1]["selected_inner_val_loss"] if milestones else history[0]["inner_val_loss"]
286
+ rec_ = {"milestone_step": step_, "selected_step": best["step"], "selected_inner_val_loss": best["loss"],
287
+ "block_improvement": prev - best["loss"], "total_improvement": tot_imp, "reason": reason}
288
+ path = a.out_dir / f"checkpoint_ft_s{step_}.pt"
289
+ out_ = {k: payload_in[k] for k in FT.KEEP_KEYS if k in payload_in}
290
+ st = materialize(best_state)
291
+ out_["model_state"] = st
292
+ out_["ema_state"] = {"model_state": st}
293
+ out_["finetune"] = {"schema": SCHEMA, "split": split["split"], "held_out": held, "recipe_k": a.k,
294
+ "mode": a.mode, "trainable": info, "lr": a.lr, "seed": a.seed, **init_info, **rec_}
295
+ tmp_ = path.with_name(path.name + ".tmp")
296
+ torch.save(out_, tmp_)
297
+ os.replace(tmp_, path)
298
+ rec_.update(checkpoint=str(path), checkpoint_sha256=FT.sha256_file(path))
299
+ milestones.append(rec_)
300
+ (a.out_dir / "milestones.json").write_text(json.dumps(milestones, indent=1))
301
+
302
+ history = []
303
+ v0, per0 = val_loss()
304
+ best = {"loss": v0, "step": 0}
305
+ best_state = {n: t.detach().cpu().clone() for n, t in ema.items()}
306
+ history.append({"step": 0, "inner_val_loss": v0, "inner_val_per_cohort": per0, "train_loss": None})
307
+ log(f"step 0 inner-val loss {v0:.5f} ({'pretrained' if a.init == 'pretrained' else 'random init'}) {per0}")
308
+ gen = torch.Generator(device=device).manual_seed(a.seed + 7)
309
+ diffusion.train()
310
+ t0 = time.time()
311
+ run_loss, run_n, bad = 0.0, 0, 0
312
+ stop_reason = "max_steps"
313
+ max_steps = 20 if a.smoke else a.max_steps
314
+ eval_every = 5 if a.smoke else a.eval_every
315
+ step = 0
316
+ for step in range(1, max_steps + 1):
317
+ for gparam in opt.param_groups:
318
+ gparam["lr"] = a.lr * min(1.0, step / max(1, a.warmup))
319
+ v, cond, m, act = to_batch(draw_batch())
320
+ opt.zero_grad(set_to_none=True)
321
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
322
+ res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=gen)
323
+ if not bool(torch.isfinite(res.loss)):
324
+ raise FloatingPointError(f"non-finite loss at step {step}")
325
+ res.loss.backward()
326
+ norm = nn.utils.clip_grad_norm_(params, 5.0)
327
+ if not bool(torch.isfinite(norm)):
328
+ raise FloatingPointError(f"non-finite grad norm at step {step}")
329
+ opt.step()
330
+ with torch.no_grad():
331
+ for n_, p in named:
332
+ ema[n_].lerp_(p.detach(), 1.0 - a.ema_decay)
333
+ run_loss += float(res.loss.detach())
334
+ run_n += 1
335
+ if step % eval_every == 0:
336
+ backup = swap_in_ema()
337
+ vl, per = val_loss()
338
+ restore(backup)
339
+ rec = {"step": step, "inner_val_loss": vl, "inner_val_per_cohort": per, "train_loss": run_loss / run_n,
340
+ "sec": round(time.time() - t0, 1)}
341
+ history.append(rec)
342
+ run_loss, run_n = 0.0, 0
343
+ if vl < best["loss"] - 1e-6:
344
+ best = {"loss": vl, "step": step}
345
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
346
+ bad = 0
347
+ else:
348
+ bad += 1
349
+ log(f"step {step} train {rec['train_loss']:.5f} inner-val {vl:.5f} best {best['loss']:.5f}@{best['step']} "
350
+ f"({rec['sec']:.0f}s) " + " ".join(f"{k}={x:.4f}" for k, x in per.items()))
351
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
352
+ if block and step % block == 0:
353
+ prev = milestones[-1]["selected_inner_val_loss"] if milestones else history[0]["inner_val_loss"]
354
+ tot_imp = history[0]["inner_val_loss"] - best["loss"]
355
+ blk_imp = prev - best["loss"]
356
+ saturated = blk_imp <= a.saturation_frac * max(tot_imp, 0.0)
357
+ write_milestone(step, "saturated" if saturated else "block_end")
358
+ log(f"block end {step}: best {best['loss']:.5f}@{best['step']}; block improvement {blk_imp:.6f} "
359
+ f"({100 * blk_imp / max(tot_imp, 1e-12):.2f} % of total {tot_imp:.6f}) -> "
360
+ + ("saturated, stop" if saturated else "continue"))
361
+ if saturated:
362
+ stop_reason = "saturated"
363
+ break
364
+ if bad >= a.patience:
365
+ log(f"early stop: no improvement in {a.patience} evaluations")
366
+ stop_reason = "early_stop"
367
+ break
368
+ if block and (not milestones or milestones[-1]["milestone_step"] != step):
369
+ write_milestone(step, stop_reason)
370
+
371
+ with torch.no_grad():
372
+ for n_, p in named:
373
+ p.copy_(best_state[n_].to(device))
374
+ if a.mode == "lora":
375
+ FT.merge_lora(denoiser)
376
+ state = {k: v.detach().cpu().clone() for k, v in denoiser.state_dict().items()}
377
+ if set(ref_state.keys()) != set(state.keys()):
378
+ raise SystemExit("fine-tuned state keys differ from the checkpoint's")
379
+ changed = {k: float((state[k].float() - ref_state[k].float()).abs().max()) for k in state}
380
+ out = {k: payload_in[k] for k in FT.KEEP_KEYS if k in payload_in}
381
+ out["model_state"] = state
382
+ out["ema_state"] = {"model_state": state}
383
+ ft_meta = {
384
+ "schema": SCHEMA, "source_checkpoint": str(a.checkpoint), "source_checkpoint_sha256": got,
385
+ "split": split["split"], "split_file": str(a.split), "split_sha256": FT.sha256_file(a.split),
386
+ "held_out": held, "recipe_k": a.k, "balance": a.balance, "mode": a.mode, "trainable": info, **init_info,
387
+ "lr": a.lr, "warmup": a.warmup, "batch_size": a.batch_size, "ema_decay": a.ema_decay,
388
+ "max_steps": max_steps, "steps_run": step, "eval_every": eval_every, "patience": a.patience,
389
+ "selected_step": best["step"], "selected_inner_val_loss": best["loss"],
390
+ "pretrained_inner_val_loss": history[0]["inner_val_loss"],
391
+ "cohorts": [{"cohort": c.name, "condition_npz": str(c.cond_npz), "condition_npz_sha256": c.cond_sha,
392
+ "train_rows": c.sample_ids[c.train_rows].tolist(),
393
+ "inner_val_rows": c.sample_ids[c.inner_rows].tolist()} for c in cohorts],
394
+ "held_out_test_rows_never_loaded": split["test"]["sample_ids"],
395
+ "max_abs_weight_change": max(changed.values()),
396
+ "n_tensors_changed": int(sum(x > 0 for x in changed.values())),
397
+ "seed": a.seed, "wall_seconds": round(time.time() - t0, 1), "smoke": bool(a.smoke),
398
+ "block": block, "saturation_frac": a.saturation_frac if block else None, "stop_reason": stop_reason,
399
+ "milestones": milestones,
400
+ "written_utc": datetime.now(timezone.utc).isoformat(),
401
+ }
402
+ if milestones:
403
+ last = torch.load(milestones[-1]["checkpoint"], map_location="cpu", weights_only=False)["model_state"]
404
+ ft_meta["last_milestone_max_abs_diff"] = float(max((last[k].float() - state[k].float()).abs().max() for k in state))
405
+ if ft_meta["last_milestone_max_abs_diff"] > 1e-4:
406
+ raise SystemExit(f"last milestone differs from the final state: {ft_meta['last_milestone_max_abs_diff']}")
407
+ out["finetune"] = ft_meta
408
+ tmp = a.out_dir / "checkpoint_ft.pt.tmp"
409
+ torch.save(out, tmp)
410
+ os.replace(tmp, done)
411
+ ft_meta["checkpoint_sha256"] = FT.sha256_file(done)
412
+ check = SS.restore_standalone(done, device=torch.device("cpu"), weights="ema", conditioner_source="embedded")
413
+ ref = SS.restore_standalone(done, device=torch.device("cpu"), weights="raw", conditioner_source="embedded")
414
+ xs = torch.randn(4, check.diffusion.state_dim, generator=torch.Generator().manual_seed(0))
415
+ tt = torch.full((4,), 0.5)
416
+ c0 = cohorts[0]
417
+ cc = c0.cond[torch.from_numpy(c0.train_rows[:1]).to(device)].repeat(4, 1).float().cpu()
418
+ denoiser_cpu = denoiser.to("cpu").float().eval()
419
+ with torch.no_grad():
420
+ o1 = check.diffusion.denoiser(xs, tt, cc).value_prediction
421
+ o2 = denoiser_cpu(xs, tt, cc).value_prediction
422
+ o3 = ref.diffusion.denoiser(xs, tt, cc).value_prediction
423
+ ft_meta["reload_forward_max_abs_diff"] = float(max((o1 - o2).abs().max(), (o1 - o3).abs().max()))
424
+ if ft_meta["reload_forward_max_abs_diff"] > 1e-4:
425
+ raise SystemExit(f"reloaded checkpoint differs: {ft_meta['reload_forward_max_abs_diff']}")
426
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
427
+ (a.out_dir / "RUN.json").write_text(json.dumps(ft_meta, indent=1))
428
+ log(f"saved {done} (selected step {best['step']}, inner-val {best['loss']:.5f} vs pretrained "
429
+ f"{history[0]['inner_val_loss']:.5f}); sha {ft_meta['checkpoint_sha256'][:12]}")
430
+ return 0
431
+
432
+
433
+ if __name__ == "__main__":
434
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_contrast/ji2025_chili/scsemi_cv_20261002/pooled/rbo.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ dataset,design,unit,arm,predictor,celltype,p,rbo_ext_t_desc,rbo_ext_t_asc,rbo_ext_mean_up_down,pred_defined,len_obs,len_pred
2
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,generated:scsemi__raw,T cell,0.98,0.011486547715618621,0.021948300607087717,0.01671742416135317,True,5696,2360
3
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,broadcast:conditions_pooled_raw.npz@a13338f5,T cell,0.98,0.06862133972224015,0.026907909519025466,0.04776462462063281,True,5696,5541
4
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,generated:scsemi__raw,B cell,0.98,0.04635205860105943,0.05429629421130003,0.05032417640617973,True,5418,1011
5
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,broadcast:conditions_pooled_raw.npz@a13338f5,B cell,0.98,0.02088705394053869,0.010974416557598995,0.015930735249068843,True,5418,5541
6
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,generated:scsemi__raw,Monocyte,0.98,0.041882659654424566,0.10394229949553557,0.07291247957498007,True,5699,1260
7
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,broadcast:conditions_pooled_raw.npz@a13338f5,Monocyte,0.98,0.1069044021836209,0.029628771308169273,0.06826658674589509,True,5699,5541
8
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,generated:scsemi__raw,NK cell,0.98,0.03894548605874574,0.014456991997347589,0.026701239028046664,True,5516,1734
9
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,broadcast:conditions_pooled_raw.npz@a13338f5,NK cell,0.98,0.052019645865070636,0.020611336546570918,0.036315491205820775,True,5516,5541
10
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,generated:scsemi__raw,DC,0.98,0.03478846070826556,0.109347199267769,0.07206782998801728,True,5168,718
11
+ ji2025_chili,scored,scsemi_cv_20261002/pooled,scsemi__raw,broadcast:conditions_pooled_raw.npz@a13338f5,DC,0.98,0.07810266432508176,0.04437506040888489,0.061238862366983324,True,5168,5541
paper-releases/pbisc-diffusion/updates/20261005T133325Z-deck-scratch-samepairs-tracking/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scores_contrast/ji2025_chili/scsemi_cv_20261002/pooled/repro.json ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "arms": {
3
+ "scsemi__raw": {
4
+ "contrast_max_abs_diff": 8.326672684688674e-17,
5
+ "contrast_all_equal": true,
6
+ "n_genes_equal": true,
7
+ "welch_lists_equal": true,
8
+ "welch_counts_equal": true,
9
+ "pass": true
10
+ }
11
+ },
12
+ "observed_split_half_full_aggregates": {
13
+ "n_equal": true,
14
+ "det_equal": true,
15
+ "sum_equal_float32": true,
16
+ "cp10k_max_abs_diff_float32": 0.0,
17
+ "cp10k_equal_float32": true
18
+ },
19
+ "comparable_with_scorer": true,
20
+ "all_pass": true
21
+ }