junidude14 commited on
Commit
1a75018
·
verified ·
1 Parent(s): 6f1ecf8

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/28/ISOLATION.json ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "pbisc.paper.support-expression-isolation.v1",
3
+ "support_manifest": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/protocol/splits/immicro/healthy/fold0/n5/support.json",
4
+ "support_sha256": "85c04462a9c768c205fc0adfcb0a40e5f94f504a93d6d822944387bc055b65d4",
5
+ "cohort": "immicro",
6
+ "unit": "fold0_n5",
7
+ "train_sample_ids": [
8
+ "HS40",
9
+ "HS30",
10
+ "HS53",
11
+ "HS39",
12
+ "HS109"
13
+ ],
14
+ "train_donor_ids": [
15
+ "HS40",
16
+ "HS30",
17
+ "HS53",
18
+ "HS39",
19
+ "HS109"
20
+ ],
21
+ "source_cells": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/immicro/cells_panel6k.npz",
22
+ "source_cells_sha256": "e1168468b621183604038b79280f46961c5819fe2386d9da0b454f7db642742a",
23
+ "source_folds_sha256": "0adc10f4ac973e5b7558effbea0fd6950a6bf59e5af1d3a376e12eb00bf6a643",
24
+ "isolated_cells": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/isolated/immicro/healthy/fold0/n5/cells_support_only.npz",
25
+ "isolated_cells_sha256": "210852d2bc7d96c41973d1e054d8022061775566d8ca6b2c3abfb3c612a42760",
26
+ "builder_sha256": "762f5f7bbf908c478544b0c5c05a8fbf6c3bf63eff6a2d7af88105473c1c20a2",
27
+ "audit": {
28
+ "selected_sample_rows": [
29
+ 27,
30
+ 35,
31
+ 36,
32
+ 49,
33
+ 104
34
+ ],
35
+ "selected_cells": 18179,
36
+ "selected_nonzero_entries": 7032111,
37
+ "original_cell_rows": 392251,
38
+ "nonselected_expression_rows_empty": true,
39
+ "original_expression_ranges": [
40
+ [
41
+ 39381299,
42
+ 41950421
43
+ ],
44
+ [
45
+ 51123627,
46
+ 53172512
47
+ ],
48
+ [
49
+ 70214002,
50
+ 70836609
51
+ ],
52
+ [
53
+ 144456310,
54
+ 146247807
55
+ ]
56
+ ],
57
+ "cell_row_indexing": "unchanged original cell-row indices; non-support rows have empty CSR rows",
58
+ "data_sha256": "68f455a04934edc4c64777ae5de4be989ac02b7ea631acfd6a082c6bde090e0d",
59
+ "indices_sha256": "cddf7c6ec873dc5274c0eac1679d4e4ce0d46142f01fd699f2537bdacce4d1e4"
60
+ },
61
+ "expression_access": "Only selected CSR ranges interpreted. Nonselected compressed bytes may be streamed and discarded.",
62
+ "target_sc_aggregate_keys_accessed": [],
63
+ "permitted_all_row_metadata": [
64
+ "indptr",
65
+ "row_sample",
66
+ "shape",
67
+ "panel_gene_ids",
68
+ "panel_measured"
69
+ ]
70
+ }
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/29/ISOLATION.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema": "pbisc.paper.support-expression-isolation.v1",
3
+ "support_manifest": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/protocol/splits/immicro/healthy/fold1/n5/support.json",
4
+ "support_sha256": "84d7e7a40992a7f24ceb5017c7534e2897d89246de9747c0a683442ad506e155",
5
+ "cohort": "immicro",
6
+ "unit": "fold1_n5",
7
+ "train_sample_ids": [
8
+ "HS25",
9
+ "HS95",
10
+ "HS77",
11
+ "HS14",
12
+ "HS108"
13
+ ],
14
+ "train_donor_ids": [
15
+ "HS25",
16
+ "HS95",
17
+ "HS77",
18
+ "HS14",
19
+ "HS108"
20
+ ],
21
+ "source_cells": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/immicro/cells_panel6k.npz",
22
+ "source_cells_sha256": "e1168468b621183604038b79280f46961c5819fe2386d9da0b454f7db642742a",
23
+ "source_folds_sha256": "0adc10f4ac973e5b7558effbea0fd6950a6bf59e5af1d3a376e12eb00bf6a643",
24
+ "isolated_cells": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/isolated/immicro/healthy/fold1/n5/cells_support_only.npz",
25
+ "isolated_cells_sha256": "2c9f63bb7c207d9e74f6bb400e6a33284310ae4becabd5f5d1744622d7edb2bd",
26
+ "builder_sha256": "762f5f7bbf908c478544b0c5c05a8fbf6c3bf63eff6a2d7af88105473c1c20a2",
27
+ "audit": {
28
+ "selected_sample_rows": [
29
+ 12,
30
+ 22,
31
+ 73,
32
+ 91,
33
+ 103
34
+ ],
35
+ "selected_cells": 15829,
36
+ "selected_nonzero_entries": 5827615,
37
+ "original_cell_rows": 392251,
38
+ "nonselected_expression_rows_empty": true,
39
+ "original_expression_ranges": [
40
+ [
41
+ 19315918,
42
+ 20936925
43
+ ],
44
+ [
45
+ 32541625,
46
+ 33326602
47
+ ],
48
+ [
49
+ 102941774,
50
+ 104113707
51
+ ],
52
+ [
53
+ 125793775,
54
+ 127286443
55
+ ],
56
+ [
57
+ 143699280,
58
+ 144456310
59
+ ]
60
+ ],
61
+ "cell_row_indexing": "unchanged original cell-row indices; non-support rows have empty CSR rows",
62
+ "data_sha256": "dc4b7969ff82490fc659fd1ece85cfd77bb08a35e165aaf47bfa7132802d7174",
63
+ "indices_sha256": "ae0414a973516ad0ed080b8ed626d680fa29211263d7ec1d13377f9fdf2d82c9"
64
+ },
65
+ "expression_access": "Only selected CSR ranges interpreted. Nonselected compressed bytes may be streamed and discarded.",
66
+ "target_sc_aggregate_keys_accessed": [],
67
+ "permitted_all_row_metadata": [
68
+ "indptr",
69
+ "row_sample",
70
+ "shape",
71
+ "panel_gene_ids",
72
+ "panel_measured"
73
+ ]
74
+ }
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/30/support_input_isolation.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Materialize expression only for exact support samples; keep original row indices.
3
+
4
+ Unselected cell rows contain no expression entries. Their sample/row-count
5
+ metadata remains so random cell selection in the legacy trainer is unchanged.
6
+ ZIP bytes before selected ranges may be decompressed and discarded, but are
7
+ never interpreted or materialized as expression arrays.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import hashlib
13
+ import json
14
+ import os
15
+ from pathlib import Path
16
+ import zipfile
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from support_manifest import load_manifest, select_rows
22
+
23
+ PLAN = Path(__file__).resolve().parents[1]
24
+ OLD = PLAN.parents[1] / "plans/paired_finetune_intradataset_20260927"
25
+ SCHEMA = "pbisc.paper.support-expression-isolation.v1"
26
+ CHUNK = 8 * 1024 * 1024
27
+
28
+
29
+ def sha(path: Path) -> str:
30
+ h = hashlib.sha256()
31
+ with Path(path).open("rb") as stream:
32
+ for block in iter(lambda: stream.read(CHUNK), b""):
33
+ h.update(block)
34
+ return h.hexdigest()
35
+
36
+
37
+ def _discard(stream, size: int) -> None:
38
+ while size:
39
+ got = stream.read(min(size, CHUNK))
40
+ if not got:
41
+ raise ValueError("truncated NPZ member")
42
+ size -= len(got)
43
+
44
+
45
+ def read_ranges(path: Path, member: str, ranges: list[tuple[int, int]]) -> np.ndarray:
46
+ """Read only selected slices of a one-dimensional numeric NPZ member."""
47
+ with zipfile.ZipFile(path) as archive, archive.open(member + ".npy") as stream:
48
+ version = np.lib.format.read_magic(stream)
49
+ if version == (1, 0):
50
+ shape, order, dtype = np.lib.format.read_array_header_1_0(stream)
51
+ elif version == (2, 0):
52
+ shape, order, dtype = np.lib.format.read_array_header_2_0(stream)
53
+ else:
54
+ raise ValueError(f"unsupported npy version {version}")
55
+ if len(shape) != 1 or dtype.hasobject:
56
+ raise ValueError("only numeric one-dimensional members are permitted")
57
+ previous = 0
58
+ for lo, hi in ranges:
59
+ if not previous <= lo <= hi <= shape[0]:
60
+ raise ValueError("invalid or overlapping selected ranges")
61
+ previous = hi
62
+ out = np.empty(sum(hi - lo for lo, hi in ranges), dtype=dtype)
63
+ position, offset = 0, 0
64
+ view = memoryview(out).cast("B")
65
+ for lo, hi in ranges:
66
+ _discard(stream, (lo - position) * dtype.itemsize)
67
+ remaining = (hi - lo) * dtype.itemsize
68
+ while remaining:
69
+ got = stream.read(min(remaining, CHUNK))
70
+ if not got:
71
+ raise ValueError("truncated selected expression range")
72
+ view[offset:offset + len(got)] = got
73
+ offset += len(got)
74
+ remaining -= len(got)
75
+ position = hi
76
+ return out
77
+
78
+
79
+ def isolated_arrays(source: Path, selected_rows: np.ndarray) -> tuple[dict, dict]:
80
+ # Every key accessed here is structural metadata; expression is streamed below.
81
+ with np.load(source, allow_pickle=False) as z:
82
+ ip = z["indptr"].astype(np.int64)
83
+ rs = z["row_sample"].astype(np.int64)
84
+ shape = z["shape"].astype(np.int64)
85
+ panel = z["panel_gene_ids"]
86
+ measured = z["panel_measured"]
87
+ if len(ip) != len(rs) + 1 or int(shape[0]) != len(rs) or np.any(np.diff(rs) < 0):
88
+ raise ValueError("invalid or unsorted cell-row metadata")
89
+ if ip[0] != 0 or np.any(np.diff(ip) < 0):
90
+ raise ValueError("invalid CSR indptr")
91
+ selected_rows = np.unique(selected_rows).astype(np.int64)
92
+ if not set(selected_rows.tolist()) <= set(rs.tolist()):
93
+ raise ValueError("support sample has no retained cells")
94
+ use = np.isin(rs, selected_rows)
95
+ chosen = np.flatnonzero(use)
96
+ starts = chosen[np.r_[True, np.diff(chosen) != 1]]
97
+ ends = chosen[np.r_[np.diff(chosen) != 1, True]] + 1
98
+ ranges = [(int(ip[a]), int(ip[b])) for a, b in zip(starts, ends)]
99
+ data = read_ranges(source, "data", ranges)
100
+ indices = read_ranges(source, "indices", ranges)
101
+ lengths = np.where(use, np.diff(ip), 0)
102
+ new_ip = np.r_[0, np.cumsum(lengths, dtype=np.int64)]
103
+ if len(data) != len(indices) or len(data) != int(new_ip[-1]):
104
+ raise ValueError("selected CSR member sizes disagree")
105
+ arrays = dict(data=data, indices=indices, indptr=new_ip, row_sample=rs,
106
+ shape=shape, panel_gene_ids=panel, panel_measured=measured)
107
+ audit = {"selected_sample_rows": selected_rows.tolist(),
108
+ "selected_cells": int(use.sum()), "selected_nonzero_entries": int(len(data)),
109
+ "original_cell_rows": int(len(rs)), "nonselected_expression_rows_empty": True,
110
+ "original_expression_ranges": ranges,
111
+ "cell_row_indexing": "unchanged original cell-row indices; non-support rows have empty CSR rows",
112
+ "data_sha256": hashlib.sha256(data.tobytes()).hexdigest(),
113
+ "indices_sha256": hashlib.sha256(indices.tobytes()).hexdigest()}
114
+ return arrays, audit
115
+
116
+
117
+ def resolve_support(support_path: Path) -> tuple[dict, Path, Path, np.ndarray]:
118
+ support_path = support_path.resolve()
119
+ relative = support_path.parent.relative_to(PLAN / "protocol/splits")
120
+ initial = json.loads(support_path.read_text())
121
+ dataset = OLD / "data" / initial["cohort"]
122
+ folds = pd.read_csv(dataset / "folds.csv", dtype={"sample_id": str, "donor_id": str})
123
+ support = load_manifest(support_path, folds)
124
+ rows, _ = select_rows(support, folds)
125
+ return support, dataset, PLAN / "isolated" / relative, rows
126
+
127
+
128
+ def materialize(support_path: Path) -> tuple[Path, dict]:
129
+ support, dataset, out, rows = resolve_support(support_path)
130
+ source = dataset / "cells_panel6k.npz"
131
+ receipt_path = out / "ISOLATION.json"
132
+ cell_path = out / "cells_support_only.npz"
133
+ if receipt_path.exists():
134
+ receipt = json.loads(receipt_path.read_text())
135
+ if (receipt.get("schema") != SCHEMA or receipt["support_sha256"] != support["sha256"]
136
+ or receipt["source_cells_sha256"] != sha(source)
137
+ or receipt["source_folds_sha256"] != sha(dataset / "folds.csv")
138
+ or receipt["isolated_cells_sha256"] != sha(cell_path)):
139
+ raise ValueError("immutable isolation receipt/input mismatch")
140
+ return cell_path, receipt
141
+ if cell_path.exists():
142
+ raise ValueError("unreceipted isolated cell file exists; inspect without overwriting")
143
+ out.mkdir(parents=True, exist_ok=True)
144
+ arrays, audit = isolated_arrays(source, rows)
145
+ temporary = out / "cells_support_only.npz.tmp"
146
+ if temporary.exists():
147
+ raise ValueError("partial isolation output exists; inspect before retry")
148
+ with temporary.open("xb") as stream:
149
+ np.savez_compressed(stream, **arrays)
150
+ os.replace(temporary, cell_path)
151
+ receipt = {"schema": SCHEMA, "support_manifest": str(support_path.resolve()),
152
+ "support_sha256": support["sha256"], "cohort": support["cohort"],
153
+ "unit": support["unit"], "train_sample_ids": support["train_sample_ids"],
154
+ "train_donor_ids": support["train_donor_ids"], "source_cells": str(source),
155
+ "source_cells_sha256": sha(source), "source_folds_sha256": sha(dataset / "folds.csv"),
156
+ "isolated_cells": str(cell_path), "isolated_cells_sha256": sha(cell_path),
157
+ "builder_sha256": sha(Path(__file__)), "audit": audit,
158
+ "expression_access": "Only selected CSR ranges interpreted. Nonselected compressed bytes may be streamed and discarded.",
159
+ "target_sc_aggregate_keys_accessed": [], "permitted_all_row_metadata":
160
+ ["indptr", "row_sample", "shape", "panel_gene_ids", "panel_measured"]}
161
+ receipt_path.write_text(json.dumps(receipt, indent=2) + "\n")
162
+ return cell_path, receipt
163
+
164
+
165
+ def validate_replay(support_path: Path, seed: int = 20260927) -> dict:
166
+ """Compare every selected CSR value and replay cell draws without training."""
167
+ path, receipt = materialize(support_path)
168
+ support, dataset, out, rows = resolve_support(support_path)
169
+ expected, audit = isolated_arrays(dataset / "cells_panel6k.npz", rows)
170
+ with np.load(path, allow_pickle=False) as got:
171
+ for key, value in expected.items():
172
+ if not np.array_equal(got[key], value):
173
+ raise ValueError(f"isolation replay differs: {key}")
174
+ rs = got["row_sample"]
175
+ ip = got["indptr"]
176
+ if np.any(np.diff(ip)[~np.isin(rs, rows)] != 0):
177
+ raise ValueError("non-support expression was retained")
178
+ with np.load(dataset / "cells_panel6k.npz", allow_pickle=False) as original:
179
+ orig_rs = original["row_sample"]
180
+ n = max(int(orig_rs.max()), int(rs.max())) + 1
181
+ old_start = np.searchsorted(orig_rs, np.arange(n), "left")
182
+ start = np.searchsorted(rs, np.arange(n), "left")
183
+ old_count = np.searchsorted(orig_rs, np.arange(n), "right") - old_start
184
+ count = np.searchsorted(rs, np.arange(n), "right") - start
185
+ rng_a, rng_b = np.random.default_rng(seed), np.random.default_rng(seed)
186
+ canonical_rows = np.sort(rows)
187
+ for _ in range(3000):
188
+ ra = canonical_rows[rng_a.integers(0, len(rows), 256)]
189
+ rb = canonical_rows[rng_b.integers(0, len(rows), 256)]
190
+ ca = old_start[ra] + np.floor(rng_a.random(256) * old_count[ra]).astype(np.int64)
191
+ cb = start[rb] + np.floor(rng_b.random(256) * count[rb]).astype(np.int64)
192
+ if not np.array_equal(ra, rb) or not np.array_equal(ca, cb):
193
+ raise ValueError("training draw replay changed")
194
+ result = {"schema": "pbisc.paper.support-isolation-replay.v1", "support_sha256": support["sha256"],
195
+ "isolated_cells_sha256": receipt["isolated_cells_sha256"], "all_selected_values_exact": True,
196
+ "training_draws_exact": True, "updates": 3000, "batch_size": 256, "seed": seed,
197
+ "legacy_access_limitation": "Earlier loaders materialized non-support arrays before selection; replay verifies selected computation only and does not change historical access claims."}
198
+ (out / "REPLAY.json").write_text(json.dumps(result, indent=2) + "\n")
199
+ return result
200
+
201
+
202
+ def bulk_only_load(dataset: Path) -> dict:
203
+ """prepare_dataset.load equivalent for bulk and metadata, without sc sums."""
204
+ with np.load(dataset / "features.npz", allow_pickle=False) as f:
205
+ samples = pd.read_csv(dataset / "samples.csv")
206
+ ids = (f["sample_ids"] if "sample_ids" in f.files else f["donor_ids"]).astype(str)
207
+ if not np.array_equal(ids, samples.sample_id.astype(str).to_numpy()):
208
+ raise ValueError("sample order differs between metadata and features")
209
+ bv, sv = f["bulk_valid"].astype(bool), f["sc_valid"].astype(bool)
210
+ raw = f["bulk_raw"]
211
+ if np.any(~np.isfinite(raw[bv])) or np.any(raw[bv] < 0):
212
+ raise ValueError("invalid measured bulk counts")
213
+ bulk = np.where(bv, raw, 0)
214
+ result = {"gene_ids": f["gene_ids"].astype(str), "sample_ids": ids,
215
+ "donor_ids": samples.donor_id.astype(str).to_numpy(),
216
+ "groups": samples.group.astype(str).to_numpy(),
217
+ "bulk_valid": bv, "sc_valid": sv, "bulk": bulk,
218
+ "n_cells": samples.n_cells.to_numpy(np.int64)}
219
+ # This field is not used to choose support; canonical folds do that.
220
+ result["use"] = f["identity_pass"].astype(bool) if "identity_pass" in f.files else np.ones(len(ids), bool)
221
+ return result
222
+
223
+
224
+ def main(argv=None) -> int:
225
+ ap = argparse.ArgumentParser(description=__doc__)
226
+ ap.add_argument("--support-manifest", type=Path, required=True)
227
+ ap.add_argument("--validate-replay", action="store_true")
228
+ ap.add_argument("--seed", type=int, default=20260927)
229
+ a = ap.parse_args(argv)
230
+ if a.validate_replay:
231
+ result = validate_replay(a.support_manifest, a.seed)
232
+ else:
233
+ path, receipt = materialize(a.support_manifest)
234
+ result = {"path": str(path), "sha256": receipt["isolated_cells_sha256"], "audit": receipt["audit"]}
235
+ print(json.dumps(result))
236
+ return 0
237
+
238
+
239
+ if __name__ == "__main__":
240
+ raise SystemExit(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/31/ft_sdd.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ device = torch.device(a.device)
234
+ if device.type == "cuda" and device.index is None:
235
+ device = torch.device("cuda", 0)
236
+ if device.type == "cuda":
237
+ total = torch.cuda.get_device_properties(device).total_memory
238
+ torch.cuda.set_per_process_memory_fraction(min(1.0, a.max_cuda_gib * 2**30 / total), device)
239
+ torch.manual_seed(a.seed)
240
+ rng = np.random.default_rng(a.seed)
241
+
242
+ bundle = SS.restore_standalone(a.checkpoint, device=device, weights="ema", conditioner_source="embedded")
243
+ diffusion, scaler = bundle.diffusion, bundle.scaler
244
+ ext = SS.load_conditions(a.condition_npz, bundle, default_cells_per_bulk=1)
245
+ folds = pd.read_csv(a.dataset_dir / "folds.csv")
246
+ if not np.array_equal(folds["sample_id"].astype(str).to_numpy(), ext.sample_ids.astype(str)):
247
+ raise SystemExit("condition NPZ rows differ from folds.csv")
248
+ support = None
249
+ if a.support_manifest is not None:
250
+ from support_manifest import select_rows
251
+ support = support_preflight
252
+ train_rows, test_rows = select_rows(support, folds)
253
+ inner_rows = np.zeros(0, dtype=np.int64)
254
+ selected_visits = set(folds.loc[folds["donor_id"].astype(str).isin(support["train_donor_ids"]),
255
+ "sample_id"].astype(str))
256
+ if selected_visits - set(support["train_sample_ids"]) != set(support["excluded_sample_ids"]):
257
+ raise SystemExit("support excludes inconsistent selected-donor visits")
258
+ folds = folds.assign(fold=np.where(folds.index.isin(test_rows), 0,
259
+ np.where(folds.index.isin(train_rows), 1, -1)),
260
+ inner_val_custom=False)
261
+ a.fold = 0
262
+ inner_col = "inner_val_custom"
263
+ elif a.train_donors_file:
264
+ # few-pair deployment scenario: train on the listed donors only, no inner validation, and treat every other
265
+ # usable row (fold >= 0) as test; --fold is ignored
266
+ want = {l.strip() for l in Path(a.train_donors_file).read_text().splitlines() if l.strip()}
267
+ is_train = folds["donor_id"].astype(str).isin(want) & (folds["fold"] >= 0)
268
+ if int(folds.loc[is_train, "donor_id"].nunique()) != len(want):
269
+ raise SystemExit("some listed training donors are missing or excluded")
270
+ folds = folds.assign(fold=np.where(folds["fold"] < 0, -1, np.where(is_train, 1, 0)))
271
+ folds["inner_val_custom"] = False
272
+ a.fold = 0
273
+ inner_col = "inner_val_custom"
274
+ else:
275
+ inner_col = f"inner_val_f{a.fold}"
276
+ test_rows = folds.index[folds["fold"] == a.fold].to_numpy()
277
+ inner_rows = folds.index[folds[inner_col]].to_numpy()
278
+ # fold -1 marks rows excluded by the pairing identity checks: never trained on, never tested
279
+ train_rows = folds.index[(folds["fold"] != a.fold) & (folds["fold"] >= 0)
280
+ & ~folds[inner_col]].to_numpy()
281
+ subset_info = None
282
+ if a.train_n:
283
+ # learning curve: keep a stratified, nested subset of the training donors (inner-validation and test
284
+ # rows unchanged). Each stratum is permuted once by --subset-seed, so smaller subsets are prefixes of
285
+ # larger ones; allocation is proportional to stratum size with at least one donor per stratum.
286
+ grp = folds.loc[train_rows, "group"].astype(str)
287
+ strata = (grp.str.contains(a.strata_regex, regex=True) if a.strata_regex
288
+ else pd.Series(True, index=grp.index)).to_numpy()
289
+ srng = np.random.default_rng(a.subset_seed)
290
+ labels = sorted(set(strata.tolist()))
291
+ perm = {s: train_rows[strata == s][srng.permutation(int((strata == s).sum()))] for s in labels}
292
+ n = min(int(a.train_n), len(train_rows))
293
+ sizes = {s: len(perm[s]) for s in labels}
294
+ alloc = {s: max(1, int(np.floor(n * sizes[s] / len(train_rows)))) for s in labels}
295
+ while sum(alloc.values()) < n:
296
+ s = max(labels, key=lambda s: n * sizes[s] / len(train_rows) - alloc[s])
297
+ alloc[s] += 1
298
+ while sum(alloc.values()) > n:
299
+ s = max((s for s in labels if alloc[s] > 1), key=lambda s: alloc[s])
300
+ alloc[s] -= 1
301
+ train_rows = np.sort(np.concatenate([perm[s][:alloc[s]] for s in labels]))
302
+ subset_info = {"train_n": int(n), "subset_seed": a.subset_seed, "strata_regex": a.strata_regex,
303
+ "allocation": {str(k): int(v) for k, v in alloc.items()}}
304
+ if set(test_rows) & (set(inner_rows) | set(train_rows)):
305
+ raise SystemExit("test rows overlap training rows")
306
+ if set(folds.loc[test_rows, "donor_id"]) & set(folds.loc[np.r_[train_rows, inner_rows], "donor_id"]):
307
+ raise SystemExit("a test donor also appears in training")
308
+
309
+ cells = Cells(a.dataset_dir / "cells_panel6k.npz", bundle.gene_ids)
310
+ z = np.load(a.dataset_dir / "cells_panel6k.npz", allow_pickle=False)
311
+ panel_measured = z["panel_measured"].astype(bool)
312
+ if not np.array_equal(panel_measured, ext.output_availability_mask.astype(bool)):
313
+ raise SystemExit("cells' measured panel differs from the condition NPZ output_availability_mask")
314
+
315
+ base = torch.from_numpy(ext.base_conditions.astype(np.float32)).to(device)
316
+ bulk_frac = torch.from_numpy(ext.bulk_measurement_fraction.astype(np.float32)).to(device)
317
+ avail_rows = torch.from_numpy(ext.output_availability_mask.astype(bool)).to(device)
318
+ cond_rows = condition_with_measurement_context(base, bulk_frac, avail_rows) # [rows, condition_dim]
319
+
320
+ denoiser = diffusion.denoiser
321
+ info = set_trainable(denoiser, a.mode, a.lora_rank, a.lora_alpha)
322
+ params = [p for p in denoiser.parameters() if p.requires_grad]
323
+ named = [(n, p) for n, p in denoiser.named_parameters() if p.requires_grad]
324
+ opt = torch.optim.AdamW(params, lr=a.lr, weight_decay=0.0)
325
+ ema = {n: p.detach().clone() for n, p in named}
326
+ log(f"mode={a.mode} trainable={info['n_trainable']:,} rows train/inner/test="
327
+ f"{len(train_rows)}/{len(inner_rows)}/{len(test_rows)} cells(train)={int(cells.count[train_rows].sum()):,}")
328
+
329
+ # fixed inner-validation draws
330
+ vrng = np.random.default_rng(a.seed + 1)
331
+ val_cells, val_rows = [], []
332
+ for r in inner_rows:
333
+ n = int(cells.count[r])
334
+ take = min(a.val_cells_per_row, n)
335
+ pick = cells.start[r] + np.sort(vrng.choice(n, size=take, replace=False))
336
+ val_cells.append(pick)
337
+ val_rows.append(np.full(take, r))
338
+ val_cells = np.concatenate(val_cells) if val_cells else np.zeros(0, np.int64)
339
+ val_rows = np.concatenate(val_rows) if val_rows else np.zeros(0, np.int64)
340
+
341
+ def to_batch(r: np.ndarray, c: np.ndarray):
342
+ x_log = torch.from_numpy(np.log1p(cells.dense(c))).to(device)
343
+ rr = torch.from_numpy(r).to(device)
344
+ availability = avail_rows[rr]
345
+ return scaler.to_unit_tensor(x_log), cond_rows[rr], availability, x_log > 0
346
+
347
+ def swap_in_ema() -> dict:
348
+ backup = {n: p.detach().clone() for n, p in named}
349
+ with torch.no_grad():
350
+ for n, p in named:
351
+ p.copy_(ema[n])
352
+ return backup
353
+
354
+ def restore(backup: dict) -> None:
355
+ with torch.no_grad():
356
+ for n, p in named:
357
+ p.copy_(backup[n])
358
+
359
+ @torch.no_grad()
360
+ def val_loss() -> float:
361
+ if len(val_cells) == 0:
362
+ return float("nan")
363
+ diffusion.eval()
364
+ tot, n = 0.0, 0
365
+ for rep in range(a.val_repeats):
366
+ for i in range(0, len(val_cells), a.batch_size):
367
+ g = torch.Generator(device=device).manual_seed(a.seed + 1_000_003 * rep + i)
368
+ v, c, m, act = to_batch(val_rows[i:i + a.batch_size], val_cells[i:i + a.batch_size])
369
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
370
+ res = diffusion.training_loss(v, c, availability_mask=m, active_target=act, generator=g)
371
+ tot += float(res.loss) * v.shape[0]
372
+ n += v.shape[0]
373
+ diffusion.train()
374
+ return tot / max(n, 1)
375
+
376
+ history = []
377
+ best = {"loss": val_loss(), "step": 0}
378
+ best_state = {n: t.detach().cpu().clone() for n, t in ema.items()}
379
+ history.append({"step": 0, "inner_val_loss": best["loss"], "train_loss": None})
380
+ log(f"step 0 inner-val loss {best['loss']:.5f} (pretrained)")
381
+ gen = torch.Generator(device=device).manual_seed(a.seed + 7)
382
+ diffusion.train()
383
+ t0 = time.time()
384
+ run_loss, run_n, bad = 0.0, 0, 0
385
+ max_steps = 20 if a.smoke else (a.fixed_steps or a.max_steps)
386
+ eval_every = 5 if a.smoke else a.eval_every
387
+ step = 0
388
+ for step in range(1, max_steps + 1):
389
+ for gparam in opt.param_groups:
390
+ gparam["lr"] = a.lr * min(1.0, step / max(1, a.warmup))
391
+ r, c = draw_batch(cells, train_rows, a.batch_size, rng)
392
+ v, cond, m, act = to_batch(r, c)
393
+ opt.zero_grad(set_to_none=True)
394
+ with torch.autocast(device_type=device.type, dtype=torch.bfloat16, enabled=device.type == "cuda"):
395
+ res = diffusion.training_loss(v, cond, availability_mask=m, active_target=act, generator=gen)
396
+ if not bool(torch.isfinite(res.loss)):
397
+ raise FloatingPointError(f"non-finite loss at step {step}")
398
+ res.loss.backward()
399
+ norm = nn.utils.clip_grad_norm_(params, 5.0)
400
+ if not bool(torch.isfinite(norm)):
401
+ raise FloatingPointError(f"non-finite grad norm at step {step}")
402
+ opt.step()
403
+ with torch.no_grad():
404
+ for n_, p in named:
405
+ ema[n_].lerp_(p.detach(), 1.0 - a.ema_decay)
406
+ run_loss += float(res.loss.detach())
407
+ run_n += 1
408
+ if a.fixed_steps and step == max_steps:
409
+ best = {"loss": float("nan"), "step": step}
410
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
411
+ if step % eval_every == 0 and not a.fixed_steps:
412
+ backup = swap_in_ema()
413
+ vl = val_loss()
414
+ restore(backup)
415
+ rec = {"step": step, "inner_val_loss": vl, "train_loss": run_loss / run_n,
416
+ "sec": round(time.time() - t0, 1)}
417
+ history.append(rec)
418
+ run_loss, run_n = 0.0, 0
419
+ if vl < best["loss"] - 1e-6:
420
+ best = {"loss": vl, "step": step}
421
+ best_state = {n_: t.detach().cpu().clone() for n_, t in ema.items()}
422
+ bad = 0
423
+ else:
424
+ bad += 1
425
+ log(f"step {step} train {rec['train_loss']:.5f} inner-val {vl:.5f} best {best['loss']:.5f}@{best['step']} "
426
+ f"({rec['sec']:.0f}s)")
427
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
428
+ if bad >= a.patience:
429
+ log(f"early stop: no improvement in {a.patience} evaluations")
430
+ break
431
+
432
+ # load the selected EMA state, merge LoRA, save a self-contained checkpoint
433
+ with torch.no_grad():
434
+ for n_, p in named:
435
+ p.copy_(best_state[n_].to(device))
436
+ if a.mode == "lora":
437
+ merge_lora(denoiser)
438
+ state = {k: v.detach().cpu().clone() for k, v in denoiser.state_dict().items()}
439
+ payload_in = SS._load_checkpoint_cpu(a.checkpoint)
440
+ ref_state = payload_in["ema_state"]["model_state"]
441
+ if set(ref_state.keys()) != set(state.keys()):
442
+ raise SystemExit("fine-tuned state keys differ from the checkpoint's")
443
+ changed = {k: float((state[k].float() - ref_state[k].float()).abs().max()) for k in state}
444
+ out = {k: payload_in[k] for k in KEEP_KEYS if k in payload_in}
445
+ out["model_state"] = state
446
+ out["ema_state"] = {"model_state": state}
447
+ ft_meta = {
448
+ "schema": SCHEMA, "source_checkpoint": str(a.checkpoint), "source_checkpoint_sha256": got,
449
+ "dataset_dir": str(a.dataset_dir), "condition_npz": str(a.condition_npz),
450
+ "condition_npz_sha256": ext.input_sha256, "fold": a.fold, "mode": a.mode, "trainable": info,
451
+ "lr": a.lr, "warmup": a.warmup, "batch_size": a.batch_size, "ema_decay": a.ema_decay,
452
+ "max_steps": max_steps, "steps_run": step, "eval_every": eval_every, "patience": a.patience,
453
+ "train_subset": subset_info, "train_donors_file": a.train_donors_file or None,
454
+ "support_manifest": str(a.support_manifest) if support else None,
455
+ "support_sha256": support["sha256"] if support else None,
456
+ "train_donor_ids": support["train_donor_ids"] if support else None,
457
+ "excluded_selected_donor_visits": support["excluded_sample_ids"] if support else None,
458
+ "fixed_steps": a.fixed_steps or None,
459
+ "selected_step": best["step"], "selected_inner_val_loss": best["loss"],
460
+ "pretrained_inner_val_loss": history[0]["inner_val_loss"],
461
+ "train_rows": [str(x) for x in folds.loc[train_rows, "sample_id"]],
462
+ "inner_val_rows": [str(x) for x in folds.loc[inner_rows, "sample_id"]],
463
+ "test_rows_never_loaded_for_training": [str(x) for x in folds.loc[test_rows, "sample_id"]],
464
+ "max_abs_weight_change": max(changed.values()),
465
+ "n_tensors_changed": int(sum(v > 0 for v in changed.values())),
466
+ "seed": a.seed, "wall_seconds": round(time.time() - t0, 1),
467
+ "written_utc": datetime.now(timezone.utc).isoformat(),
468
+ }
469
+ out["finetune"] = ft_meta
470
+ tmp = a.out_dir / "checkpoint_ft.pt.tmp"
471
+ torch.save(out, tmp)
472
+ os.replace(tmp, done)
473
+ ft_meta["checkpoint_sha256"] = sha256_file(done)
474
+ # reload through the sampler's own restore path and compare one forward pass
475
+ check = SS.restore_standalone(done, device=torch.device("cpu"), weights="ema", conditioner_source="embedded")
476
+ ref = SS.restore_standalone(done, device=torch.device("cpu"), weights="raw", conditioner_source="embedded")
477
+ xs = torch.randn(4, check.diffusion.state_dim, generator=torch.Generator().manual_seed(0))
478
+ tt = torch.full((4,), 0.5)
479
+ cc = cond_rows[torch.from_numpy(train_rows[:1]).to(device)].repeat(4, 1).float().cpu()
480
+ denoiser_cpu = denoiser.to("cpu").float().eval()
481
+ with torch.no_grad():
482
+ o1 = check.diffusion.denoiser(xs, tt, cc).value_prediction
483
+ o2 = denoiser_cpu(xs, tt, cc).value_prediction
484
+ o3 = ref.diffusion.denoiser(xs, tt, cc).value_prediction
485
+ ft_meta["reload_forward_max_abs_diff"] = float(max((o1 - o2).abs().max(), (o1 - o3).abs().max()))
486
+ if ft_meta["reload_forward_max_abs_diff"] > 1e-4:
487
+ raise SystemExit(f"reloaded checkpoint differs: {ft_meta['reload_forward_max_abs_diff']}")
488
+ (a.out_dir / "history.json").write_text(json.dumps(history, indent=1))
489
+ (a.out_dir / "RUN.json").write_text(json.dumps(ft_meta, indent=1))
490
+ log(f"saved {done} (selected step {best['step']}, inner-val {best['loss']:.5f} vs pretrained "
491
+ f"{history[0]['inner_val_loss']:.5f}); sha {ft_meta['checkpoint_sha256'][:12]}")
492
+ return 0
493
+
494
+
495
+ if __name__ == "__main__":
496
+ sys.exit(main())