junidude14 commited on
Commit
43d656b
·
verified ·
1 Parent(s): 06c951a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/20260928/diffusion/data/annotator/aifi_scanvi_f01common_v1/scvi_model/model.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:56890d18ee1fcdc80c6ac591ee46aaa9bc8a951fbc61b0c86e948d664595beb8
3
+ size 9165917
paper-releases/20260928/diffusion/data/annotator/aifi_scanvi_f01common_v1/train_config_resolved.json ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "config_path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/config_f01common.json",
3
+ "config_sha256": "84e9389eb63f7ebf45bb42eadf36704d919251bcb7e8d7330e654e0833f60038",
4
+ "cli_overrides": {},
5
+ "resolved": {
6
+ "anndata": {
7
+ "batch_key": "batch_key",
8
+ "labels_key": "aifi_l2_train",
9
+ "layer": "counts",
10
+ "split_key": "split",
11
+ "train_split": "train",
12
+ "unlabeled_category": "Unknown",
13
+ "val_split": "val"
14
+ },
15
+ "eval": {
16
+ "batch_size": 2048,
17
+ "in_sample_cells": 20000,
18
+ "other_label": "Other",
19
+ "pbmc5_labels": [
20
+ "T cell",
21
+ "B cell",
22
+ "Monocyte",
23
+ "NK cell",
24
+ "DC"
25
+ ]
26
+ },
27
+ "l2_to_l1_module": "/home/sj_server_1/PBISC/immun-pbmc-fm/model/vae_bulk2sc/scripts/aifi_celltype_mapping.py",
28
+ "output_dir": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/runs/aifi_scanvi_f01common_v1",
29
+ "reference_h5ad": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/reference/aifi_reference_f01common.h5ad",
30
+ "reference_manifest": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/aifi_scanvi_rebuild_20260916/reference/REFERENCE_MANIFEST.json",
31
+ "run_name": "aifi_scanvi_f01common_v1",
32
+ "scanvi_model": {
33
+ "classifier_parameters": {
34
+ "dropout_rate": 0.1,
35
+ "n_hidden": 128,
36
+ "n_layers": 2
37
+ },
38
+ "linear_classifier": false
39
+ },
40
+ "scanvi_train": {
41
+ "batch_size": 1024,
42
+ "check_val_every_n_epoch": 1,
43
+ "max_epochs": 25,
44
+ "n_samples_per_label": 100,
45
+ "plan_kwargs": {
46
+ "classification_ratio": 50,
47
+ "lr": 0.001
48
+ },
49
+ "train_size": 0.9
50
+ },
51
+ "scvi_model": {
52
+ "dispersion": "gene",
53
+ "dropout_rate": 0.1,
54
+ "gene_likelihood": "nb",
55
+ "n_hidden": 256,
56
+ "n_latent": 30,
57
+ "n_layers": 2
58
+ },
59
+ "scvi_train": {
60
+ "batch_size": 1024,
61
+ "check_val_every_n_epoch": 1,
62
+ "early_stopping": true,
63
+ "early_stopping_monitor": "elbo_validation",
64
+ "early_stopping_patience": 8,
65
+ "max_epochs": 40,
66
+ "plan_kwargs": {
67
+ "lr": 0.001
68
+ },
69
+ "train_size": 0.9
70
+ },
71
+ "seed": 20260916
72
+ },
73
+ "device": "cuda"
74
+ }
paper-releases/20260928/diffusion/data/annotator/aifi_scanvi_f01common_v1/train_scanvi.py ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Train the AIFI scANVI cell-type annotator: scVI pretrain -> scANVI (config-driven JSON).
3
+
4
+ Rebuilt 2026-09-16. The original ``training/annotation/runs/aifi_scanvi_new_blocks_v1`` model
5
+ and its hyper-parameters are lost; only the query-side contract survives and is honoured
6
+ here (see README "Contract"):
7
+
8
+ layer="counts" labels_key="aifi_l2_train" unlabeled_category="Unknown" batch_key="batch_key"
9
+
10
+ Pipeline
11
+ --------
12
+ 1. Load the reference h5ad (``build_reference.py`` output); alias ``layers["counts"] = X``.
13
+ 2. Split by ``obs["split"]`` (train donors / held-out val donors).
14
+ 3. ``SCVI.setup_anndata`` + ``SCVI.train`` (unsupervised pretrain)
15
+ 4. ``SCANVI.from_scvi_model`` + ``SCANVI.train`` (semi-supervised; all reference cells labelled)
16
+ 5. Save ``scvi_model/`` and ``scanvi_model/`` (no AnnData inside).
17
+ 6. Evaluate on the held-out donors THROUGH THE PRODUCTION PATH: labels set to "Unknown",
18
+ ``SCANVI.prepare_query_anndata`` -> ``SCANVI.load_query_data`` -> ``predict(soft=True)``
19
+ with ZERO query-training epochs. Reports accuracy / macro-F1 at AIFI L2, collapsed L1,
20
+ and PBMC5(+Other), plus confusion matrices and per-class tables.
21
+
22
+ Usage
23
+ -----
24
+ python train_scanvi.py --config config_6k.json --device cuda
25
+ python train_scanvi.py --config config_6k.json --device cpu --max-cells 3000 --max-epochs 2 \
26
+ --batch-size 128 --output-dir runs/smoke_6k_cpu # CPU smoke
27
+
28
+ Every hyper-parameter lives in the config JSON; CLI flags only override for smoke runs
29
+ (and the override is recorded in ``train_config_resolved.json``).
30
+ """
31
+
32
+ from __future__ import annotations
33
+
34
+ import argparse
35
+ import json
36
+ import os
37
+ import sys
38
+ import time
39
+ from datetime import datetime, timezone
40
+ from importlib.metadata import version as _pkg_version
41
+ from pathlib import Path
42
+
43
+ import numpy as np
44
+ import pandas as pd
45
+
46
+ PLAN_DIR = Path(__file__).resolve().parent
47
+ sys.path.insert(0, str(PLAN_DIR))
48
+ import scanvi_common as C # noqa: E402
49
+
50
+
51
+ def parse_args(argv=None) -> argparse.Namespace:
52
+ p = argparse.ArgumentParser(description="scVI -> scANVI training on the AIFI reference.", formatter_class=argparse.ArgumentDefaultsHelpFormatter)
53
+ p.add_argument("--config", required=True, type=Path)
54
+ p.add_argument("--device", choices=["cpu", "cuda"], default="cpu")
55
+ p.add_argument("--max-cells", type=int, default=None, help="SMOKE: seeded subsample of training cells (val gets ~1/3, >=500)")
56
+ p.add_argument("--max-epochs", type=int, default=None, help="SMOKE: override max_epochs for both stages")
57
+ p.add_argument("--batch-size", type=int, default=None, help="override batch_size for both stages")
58
+ p.add_argument("--output-dir", type=Path, default=None, help="override config output_dir")
59
+ p.add_argument("--expected-config-sha256", default=None, help="refuse to run if the config file hash differs")
60
+ p.add_argument("--num-threads", type=int, default=8)
61
+ p.add_argument("--skip-in-sample-eval", action="store_true")
62
+ return p.parse_args(argv)
63
+
64
+
65
+ def deep_update(base: dict, override: dict) -> dict:
66
+ out = dict(base)
67
+ for k, v in override.items():
68
+ if isinstance(v, dict) and isinstance(out.get(k), dict):
69
+ out[k] = deep_update(out[k], v)
70
+ else:
71
+ out[k] = v
72
+ return out
73
+
74
+
75
+ def main(argv=None) -> int:
76
+ args = parse_args(argv)
77
+ # Device policy must be fixed BEFORE torch / scvi are imported.
78
+ if args.device == "cpu":
79
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
80
+ elif not os.environ.get("CUDA_VISIBLE_DEVICES"):
81
+ print("WARNING: --device cuda but CUDA_VISIBLE_DEVICES is unset; the launcher should set it", file=sys.stderr)
82
+
83
+ config_text = args.config.read_text(encoding="utf-8")
84
+ config_sha = C.sha256_text(config_text)
85
+ if args.expected_config_sha256 and args.expected_config_sha256 != config_sha:
86
+ raise SystemExit(f"config sha256 {config_sha} != expected {args.expected_config_sha256}")
87
+ cfg = json.loads(config_text)
88
+
89
+ overrides: dict = {}
90
+ if args.output_dir is not None:
91
+ overrides["output_dir"] = str(args.output_dir)
92
+ if args.max_epochs is not None:
93
+ overrides.setdefault("scvi_train", {})["max_epochs"] = int(args.max_epochs)
94
+ overrides.setdefault("scanvi_train", {})["max_epochs"] = int(args.max_epochs)
95
+ if args.batch_size is not None:
96
+ overrides.setdefault("scvi_train", {})["batch_size"] = int(args.batch_size)
97
+ overrides.setdefault("scanvi_train", {})["batch_size"] = int(args.batch_size)
98
+ if args.max_cells is not None:
99
+ overrides["max_cells"] = int(args.max_cells)
100
+ cfg = deep_update(cfg, overrides)
101
+
102
+ out_dir = Path(cfg["output_dir"])
103
+ out_dir.mkdir(parents=True, exist_ok=True)
104
+ log_path = out_dir / "train.log"
105
+ status_path = out_dir / "status.json"
106
+ t_start = time.monotonic()
107
+
108
+ def log(msg: str) -> None:
109
+ line = f"{datetime.now(timezone.utc).isoformat(timespec='seconds')} {msg}"
110
+ print(line, flush=True)
111
+ with open(log_path, "a", encoding="utf-8") as fh:
112
+ fh.write(line + "\n")
113
+
114
+ def status(state: str, **extra) -> None:
115
+ payload = {"state": state, "updated_at_utc": datetime.now(timezone.utc).isoformat(), "elapsed_s": round(time.monotonic() - t_start, 1), "output_dir": str(out_dir), "pid": os.getpid(), **extra}
116
+ C.write_json(status_path, payload)
117
+
118
+ status("starting")
119
+ import anndata as ad # noqa: E402
120
+ import scvi # noqa: E402
121
+ import torch # noqa: E402
122
+ from scvi.model import SCANVI, SCVI # noqa: E402
123
+
124
+ torch.set_num_threads(int(args.num_threads))
125
+ if args.device == "cuda" and not torch.cuda.is_available():
126
+ status("failed", error="cuda requested but torch.cuda.is_available() is False")
127
+ raise SystemExit("cuda requested but not available")
128
+ accelerator = "gpu" if args.device == "cuda" else "cpu"
129
+ seed = int(cfg.get("seed", 0))
130
+ scvi.settings.seed = seed
131
+ log(f"scvi-tools {scvi.__version__} torch {torch.__version__} anndata {_pkg_version('anndata')} device={args.device} seed={seed}")
132
+ log(f"config {args.config} sha256={config_sha}")
133
+ log(f"overrides={json.dumps(overrides)}")
134
+
135
+ ac = cfg["anndata"]
136
+ layer, labels_key, unl, batch_key = ac["layer"], ac["labels_key"], ac["unlabeled_category"], ac["batch_key"]
137
+ split_key, train_split, val_split = ac.get("split_key", "split"), ac.get("train_split", "train"), ac.get("val_split", "val")
138
+ l2_to_l1 = C.load_l2_to_l1(cfg.get("l2_to_l1_module", C.L2_TO_L1_MODULE))
139
+ pbmc5 = tuple(cfg.get("eval", {}).get("pbmc5_labels", C.PBMC5_LABELS))
140
+ other = cfg.get("eval", {}).get("other_label", C.OTHER_LABEL)
141
+
142
+ # ---- data ---------------------------------------------------------------
143
+ ref_path = Path(cfg["reference_h5ad"])
144
+ log(f"loading reference {ref_path}")
145
+ adata = ad.read_h5ad(ref_path)
146
+ if layer not in adata.layers:
147
+ adata.layers[layer] = adata.X # alias, no copy: X holds raw integer counts
148
+ for col in (labels_key, batch_key, split_key, "AIFI_L1", "AIFI_L2"):
149
+ if col not in adata.obs.columns:
150
+ raise SystemExit(f"reference obs lacks {col!r}")
151
+ classes = sorted(adata.obs[labels_key].astype(str).unique())
152
+ if unl in classes:
153
+ raise SystemExit(f"reference already contains the unlabeled category {unl!r}")
154
+ missing_map = [c for c in classes if c not in l2_to_l1]
155
+ if missing_map:
156
+ raise SystemExit(f"AIFI L2 classes without L1 mapping: {missing_map}")
157
+ if not np.all(adata.layers[layer].data == np.round(adata.layers[layer].data)):
158
+ raise SystemExit("reference counts are not integer-valued")
159
+
160
+ is_train = adata.obs[split_key].astype(str).to_numpy() == train_split
161
+ is_val = adata.obs[split_key].astype(str).to_numpy() == val_split
162
+ train_idx = np.flatnonzero(is_train)
163
+ val_idx = np.flatnonzero(is_val)
164
+ rng = np.random.default_rng(seed)
165
+ max_cells = cfg.get("max_cells")
166
+ if max_cells is not None and max_cells < train_idx.size:
167
+ train_idx = np.sort(rng.choice(train_idx, size=int(max_cells), replace=False))
168
+ n_val = min(val_idx.size, max(int(max_cells) // 3, 500))
169
+ val_idx = np.sort(rng.choice(val_idx, size=n_val, replace=False))
170
+ log(f"SMOKE subsample: train {train_idx.size} val {val_idx.size}")
171
+ train = adata[train_idx].copy()
172
+ val = adata[val_idx].copy()
173
+ del adata
174
+ # Register all 29 classes even if a smoke subset lacks some, so the classifier head is complete.
175
+ train.obs[labels_key] = pd.Categorical(train.obs[labels_key].astype(str), categories=classes)
176
+ train.obs[batch_key] = pd.Categorical(train.obs[batch_key].astype(str))
177
+ train_donors = sorted(train.obs["donor_id"].astype(str).unique())
178
+ val_donors = sorted(val.obs["donor_id"].astype(str).unique())
179
+ if set(train_donors) & set(val_donors):
180
+ raise SystemExit("donor leakage between train and val splits")
181
+ log(f"train {train.n_obs:,} cells x {train.n_vars:,} genes, {len(train_donors)} donors, {train.obs[batch_key].nunique()} batches, {len(classes)} classes")
182
+ log(f"val {val.n_obs:,} cells, {len(val_donors)} held-out donors")
183
+ status("training_scvi", n_train=int(train.n_obs), n_val=int(val.n_obs), n_genes=int(train.n_vars))
184
+
185
+ # ---- stage 1: scVI ------------------------------------------------------
186
+ scvi_model_kw = dict(cfg["scvi_model"])
187
+ scvi_train_kw = dict(cfg["scvi_train"])
188
+ scvi_plan_kw = scvi_train_kw.pop("plan_kwargs", {})
189
+ SCVI.setup_anndata(train, layer=layer, batch_key=batch_key, labels_key=labels_key)
190
+ vae = SCVI(train, **scvi_model_kw)
191
+ log(f"scVI model: {scvi_model_kw}; train: {scvi_train_kw}; plan: {scvi_plan_kw}")
192
+ t0 = time.monotonic()
193
+ vae.train(accelerator=accelerator, devices=1, plan_kwargs=scvi_plan_kw, enable_progress_bar=False, **scvi_train_kw)
194
+ scvi_seconds = time.monotonic() - t0
195
+ hist_scvi = {k: v for k, v in vae.history.items()} if vae.history else {}
196
+ _write_history(hist_scvi, out_dir / "history_scvi.csv")
197
+ vae.save(out_dir / "scvi_model", overwrite=True, save_anndata=False)
198
+ log(f"scVI done in {scvi_seconds/60:.1f} min; epochs run={_epochs_run(hist_scvi)}")
199
+ status("training_scanvi", scvi_seconds=round(scvi_seconds, 1))
200
+
201
+ # ---- stage 2: scANVI ----------------------------------------------------
202
+ scanvi_model_kw = dict(cfg.get("scanvi_model", {}))
203
+ scanvi_train_kw = dict(cfg["scanvi_train"])
204
+ scanvi_plan_kw = scanvi_train_kw.pop("plan_kwargs", {})
205
+ lvae = SCANVI.from_scvi_model(vae, unlabeled_category=unl, labels_key=labels_key, **scanvi_model_kw)
206
+ log(f"scANVI model: {scanvi_model_kw}; train: {scanvi_train_kw}; plan: {scanvi_plan_kw}")
207
+ t0 = time.monotonic()
208
+ lvae.train(accelerator=accelerator, devices=1, plan_kwargs=scanvi_plan_kw, enable_progress_bar=False, **scanvi_train_kw)
209
+ scanvi_seconds = time.monotonic() - t0
210
+ hist_scanvi = {k: v for k, v in lvae.history.items()} if lvae.history else {}
211
+ _write_history(hist_scanvi, out_dir / "history_scanvi.csv")
212
+ model_dir = out_dir / "scanvi_model"
213
+ lvae.save(model_dir, overwrite=True, save_anndata=False)
214
+ pd.DataFrame({"gene_id": train.var_names, **{c: train.var[c].to_numpy() for c in train.var.columns}}).to_csv(out_dir / "genes.csv", index=False)
215
+ log(f"scANVI done in {scanvi_seconds/60:.1f} min; epochs run={_epochs_run(hist_scanvi)}; saved {model_dir}")
216
+ status("evaluating", scanvi_seconds=round(scanvi_seconds, 1))
217
+
218
+ # ---- evaluation ---------------------------------------------------------
219
+ eval_cfg = cfg.get("eval", {})
220
+ eval_bs = int(eval_cfg.get("batch_size", 2048))
221
+ metrics: dict = {"contract": {"layer": layer, "labels_key": labels_key, "unlabeled_category": unl, "batch_key": batch_key, "query_train_epochs": 0}}
222
+
223
+ if not args.skip_in_sample_eval:
224
+ n_in = min(int(eval_cfg.get("in_sample_cells", 20000)), train.n_obs)
225
+ in_idx = np.sort(rng.choice(train.n_obs, size=n_in, replace=False))
226
+ soft_in = lvae.predict(indices=in_idx, soft=True, batch_size=eval_bs)
227
+ pred_in, _, _ = C.soft_to_predictions(soft_in)
228
+ truth_in = train.obs["AIFI_L2"].astype(str).to_numpy()[in_idx]
229
+ metrics["in_sample_l2"] = C.classification_metrics(truth_in, pred_in)
230
+ log(f"in-sample L2 (n={n_in}): acc={metrics['in_sample_l2']['accuracy']:.4f} macroF1={metrics['in_sample_l2']['macro_f1_present_classes']:.4f}")
231
+
232
+ # Held-out donors through the production query path (labels hidden, zero epochs).
233
+ val_truth_l2 = val.obs["AIFI_L2"].astype(str).to_numpy()
234
+ val_truth_l1 = val.obs["AIFI_L1"].astype(str).to_numpy()
235
+ val.obs[labels_key] = pd.Categorical([unl] * val.n_obs)
236
+ val.obs[batch_key] = pd.Categorical(val.obs[batch_key].astype(str))
237
+ SCANVI.prepare_query_anndata(val, str(model_dir))
238
+ query = SCANVI.load_query_data(val, str(model_dir), accelerator=accelerator)
239
+ t0 = time.monotonic()
240
+ soft = query.predict(soft=True, batch_size=eval_bs)
241
+ pred_l2, conf_l2, probs = C.soft_to_predictions(soft)
242
+ pred_l1 = C.collapse_l1(pred_l2, l2_to_l1)
243
+ truth_l1_from_map = C.collapse_l1(val_truth_l2, l2_to_l1)
244
+ l1_consistent = float(np.mean(truth_l1_from_map == val_truth_l1))
245
+ pred_p5 = C.collapse_pbmc5(pred_l1, pbmc5=pbmc5, other=other)
246
+ truth_p5 = C.collapse_pbmc5(val_truth_l1, pbmc5=pbmc5, other=other)
247
+ metrics["held_out_donors"] = {
248
+ "n_cells": int(val.n_obs),
249
+ "donors": val_donors,
250
+ "predict_seconds": round(time.monotonic() - t0, 1),
251
+ "atlas_L1_vs_map_collapse_agreement": l1_consistent,
252
+ "l2": C.classification_metrics(val_truth_l2, pred_l2, labels=classes),
253
+ "l1": C.classification_metrics(val_truth_l1, pred_l1),
254
+ "pbmc5_plus_other": C.classification_metrics(truth_p5, pred_p5, labels=list(pbmc5) + [other]),
255
+ "mean_max_prob": float(conf_l2.mean()),
256
+ "frac_max_prob_ge_0.5": float(np.mean(conf_l2 >= 0.5)),
257
+ }
258
+ C.confusion_frame(val_truth_l2, pred_l2, labels=classes).to_csv(out_dir / "confusion_l2.csv")
259
+ C.confusion_frame(val_truth_l1, pred_l1).to_csv(out_dir / "confusion_l1.csv")
260
+ C.confusion_frame(truth_p5, pred_p5, labels=list(pbmc5) + [other]).to_csv(out_dir / "confusion_pbmc5.csv")
261
+ pd.DataFrame(metrics["held_out_donors"]["l2"]["per_class"]).T.rename_axis("AIFI_L2").to_csv(out_dir / "per_class_l2.csv")
262
+ pd.DataFrame(
263
+ {
264
+ "barcode": val.obs_names,
265
+ "atlas_row": val.obs["atlas_row"].to_numpy() if "atlas_row" in val.obs.columns else -1,
266
+ "donor_id": val.obs["donor_id"].astype(str).to_numpy(),
267
+ "batch_key": val.obs[batch_key].astype(str).to_numpy(),
268
+ "truth_l2": val_truth_l2,
269
+ "truth_l1": val_truth_l1,
270
+ "pred_l2": pred_l2,
271
+ "pred_l1": pred_l1,
272
+ "pred_pbmc5": pred_p5,
273
+ "max_prob": conf_l2.astype(np.float32),
274
+ }
275
+ ).to_parquet(out_dir / "val_predictions.parquet", index=False)
276
+ ho = metrics["held_out_donors"]
277
+ log(
278
+ f"held-out donors (n={val.n_obs:,}): L2 acc={ho['l2']['accuracy']:.4f} macroF1={ho['l2']['macro_f1_present_classes']:.4f} | "
279
+ f"L1 acc={ho['l1']['accuracy']:.4f} macroF1={ho['l1']['macro_f1_present_classes']:.4f} | "
280
+ f"PBMC5+Other acc={ho['pbmc5_plus_other']['accuracy']:.4f} macroF1={ho['pbmc5_plus_other']['macro_f1_present_classes']:.4f}"
281
+ )
282
+ C.write_json(out_dir / "metrics.json", metrics)
283
+
284
+ # ---- manifests ----------------------------------------------------------
285
+ resolved = {"config_path": str(args.config), "config_sha256": config_sha, "cli_overrides": overrides, "resolved": cfg, "device": args.device}
286
+ C.write_json(out_dir / "train_config_resolved.json", resolved)
287
+ ref_manifest_path = cfg.get("reference_manifest")
288
+ ref_sha = None
289
+ if ref_manifest_path and Path(ref_manifest_path).exists():
290
+ rm = json.loads(Path(ref_manifest_path).read_text())
291
+ for entry in rm.get("outputs", {}).values():
292
+ if Path(entry.get("path", "")).resolve() == ref_path.resolve():
293
+ ref_sha = entry.get("sha256")
294
+ manifest = {
295
+ "schema_version": "aifi_scanvi_rebuild.model_manifest.v1",
296
+ "run_name": cfg.get("run_name"),
297
+ "built_at_utc": datetime.now(timezone.utc).isoformat(),
298
+ "smoke": bool(overrides),
299
+ "device": args.device,
300
+ "contract": metrics["contract"],
301
+ "reference": {"h5ad": str(ref_path), "sha256": ref_sha, "manifest": ref_manifest_path},
302
+ "n_train_cells": int(train.n_obs),
303
+ "n_val_cells": int(val.n_obs),
304
+ "n_genes": int(train.n_vars),
305
+ "genes_csv": str(out_dir / "genes.csv"),
306
+ "classes": classes,
307
+ "n_batches": int(train.obs[batch_key].nunique()),
308
+ "train_donors": train_donors,
309
+ "val_donors": val_donors,
310
+ "scvi_model_dir": str(out_dir / "scvi_model"),
311
+ "scanvi_model_dir": str(model_dir),
312
+ "scanvi_model_pt_sha256": C.sha256_file(model_dir / "model.pt"),
313
+ "config": resolved,
314
+ "versions": {"scvi-tools": scvi.__version__, "torch": torch.__version__, "anndata": _pkg_version("anndata"), "numpy": np.__version__, "python": sys.version.split()[0]},
315
+ "timings_s": {"scvi": round(scvi_seconds, 1), "scanvi": round(scanvi_seconds, 1), "total": round(time.monotonic() - t_start, 1)},
316
+ "epochs_run": {"scvi": _epochs_run(hist_scvi), "scanvi": _epochs_run(hist_scanvi)},
317
+ "held_out_summary": {
318
+ "l2_accuracy": ho["l2"]["accuracy"],
319
+ "l2_macro_f1": ho["l2"]["macro_f1_present_classes"],
320
+ "l1_accuracy": ho["l1"]["accuracy"],
321
+ "l1_macro_f1": ho["l1"]["macro_f1_present_classes"],
322
+ "pbmc5_other_accuracy": ho["pbmc5_plus_other"]["accuracy"],
323
+ "pbmc5_other_macro_f1": ho["pbmc5_plus_other"]["macro_f1_present_classes"],
324
+ },
325
+ }
326
+ C.write_json(out_dir / "MODEL_MANIFEST.json", manifest)
327
+ status("complete", **manifest["held_out_summary"])
328
+ log(f"complete in {(time.monotonic() - t_start)/60:.1f} min -> {out_dir}")
329
+ return 0
330
+
331
+
332
+ def _write_history(history: dict, path: Path) -> None:
333
+ if not history:
334
+ return
335
+ frames = []
336
+ for key, frame in history.items():
337
+ if isinstance(frame, pd.DataFrame):
338
+ f = frame.copy()
339
+ f.columns = [key if c == key else f"{key}.{c}" for c in f.columns]
340
+ frames.append(f)
341
+ if frames:
342
+ pd.concat(frames, axis=1).rename_axis("epoch").to_csv(path)
343
+
344
+
345
+ def _epochs_run(history: dict) -> int | None:
346
+ for key in ("elbo_train", "train_loss_epoch", "elbo_validation"):
347
+ frame = history.get(key)
348
+ if isinstance(frame, pd.DataFrame):
349
+ return int(len(frame))
350
+ return None
351
+
352
+
353
+ if __name__ == "__main__":
354
+ try:
355
+ raise SystemExit(main())
356
+ except SystemExit:
357
+ raise
358
+ except Exception as exc: # record failure for the coordinator, then re-raise
359
+ try:
360
+ args = parse_args()
361
+ cfg = json.loads(args.config.read_text())
362
+ out = Path(args.output_dir or cfg["output_dir"])
363
+ if out.exists():
364
+ C.write_json(out / "status.json", {"state": "failed", "error": f"{type(exc).__name__}: {exc}", "updated_at_utc": datetime.now(timezone.utc).isoformat()})
365
+ finally:
366
+ raise
paper-releases/20260928/diffusion/data/calibration/aida_donor_pseudobulk_20097.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "schema_version": "pbisc_sdd.utility6k.refcal_refs.aida_donor_pseudobulk.v1",
3
+ "written_utc": "2026-09-26T14:10:09.896141+00:00",
4
+ "tool": {
5
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/refcal_refs/tools/build_aida_reference.py",
6
+ "sha256": "c0cd15c918d932546c8cc80c362ada126e5b7f589b3bd9d9c66dd2ff5314d93f"
7
+ },
8
+ "inputs": {
9
+ "/home/sj_server_1/gblee/datalake/single-cell-RNA-seq-datasets/PBMC-cells/006_A_collection_ced320a1-29f3-47c1-a735-513c7084d5_AIDA_Asian_Immune_Diversity_Atlas/9deda9ad-6a71-401e-b909-5263919d85f9.h5ad": "a5bce74985df8cbe8cf1f18877a1607ed556d99061dc08e7bdbc4dbae732c593",
10
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data/e2_full_source/metadata/var.parquet": "64f4e30e17763bef37793e7229edb6caa0a7ffe3f3bfa5a08e1d4ca8ea7ea1dc",
11
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/ordered_train_recipes.csv": "7c3aadcc409c685605f0f610a0dcc48b1ee5e126dcd80b427e835d1e598e5a3a",
12
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data/e2_full_index/metadata/source_shards.parquet": "14c9befabe3c901613321682d8a1b3be0de5182613265584ee6baea2e6badf28",
13
+ "/home/sj_server_1/PBISC/immun-pbmc-fm/model_7_no_annotation_sh_hwang/data/e2_full_index/metadata/sample_index.parquet": "8c4b38d313eac651f545979ef5813c60fa47ff59da8c07f11e1712b8a83d2322"
14
+ },
15
+ "counts_source": "atlas raw/X (integer UMI counts), every cell; atlas X (normalised) unused",
16
+ "assay": [
17
+ "10x 5' v2"
18
+ ],
19
+ "healthy_filter": "every cell has disease == normal (checked; no cell removed); one sample per donor (checked)",
20
+ "gene_join": "unversioned Ensembl id of raw/var, canonical order (mirror of build_aifi_reference.py)",
21
+ "n_cells": 1265624,
22
+ "n_donors": 625,
23
+ "n_atlas_genes": 35477,
24
+ "n_canonical_present": 19242,
25
+ "canonical_present_but_feature_is_filtered": 12,
26
+ "canonical_present_but_feature_is_filtered_umi_fraction": 0.00015387565965793663,
27
+ "fraction_of_umis_on_atlas_genes_outside_canonical": 0.04249055437807392,
28
+ "training_corpus_harmonisation": {
29
+ "aida_corpus_shards": 8,
30
+ "corpus_measured_genes_union": 19247,
31
+ "corpus_measured_genes_intersection": 19242,
32
+ "join_present_not_in_corpus_union": 0,
33
+ "corpus_union_not_in_join": 5,
34
+ "cell_check": {
35
+ "shard_id": "006_A_collection_ced320a1-29f3-47c1-a735-513c7084d5_AIDA_Asian_Immune_Diversity_Atlas__9deda9ad-6a71-401e-b909-5263919d85f9__part_000__363bd8da25f0",
36
+ "cells_compared": 5000,
37
+ "donor_ids_equal": true,
38
+ "counts_equal_on_genes_measured_by_both": true,
39
+ "corpus_mass_on_genes_outside_this_join": 0.0,
40
+ "join_mass_on_genes_unmeasured_in_corpus": 0.0
41
+ }
42
+ },
43
+ "cells_per_donor": {
44
+ "min": 77,
45
+ "median": 2014.0,
46
+ "max": 25331
47
+ },
48
+ "natural_l1_composition_pooled": {
49
+ "B": 0.06786059682812588,
50
+ "CD34_HSPC": 0.00010666675094656865,
51
+ "DC": 0.0037056819402919035,
52
+ "ILC": 0.0005586177253275854,
53
+ "Myeloid": 0.22797687148789847,
54
+ "NK": 0.14304485376383508,
55
+ "Plasma_Cell": 0.0013210874635752798,
56
+ "Platelet": 0.011693046275987181,
57
+ "T": 0.5437325777640121
58
+ },
59
+ "natural_l2_composition_pooled": {
60
+ "B": 0.0072248945974475835,
61
+ "CD16+_NK": 0.11982626751705087,
62
+ "CD34_HSPC": 0.00010666675094656865,
63
+ "CD4+_T": 0.28588506539066894,
64
+ "CD56+_NK": 0.004860843346839188,
65
+ "CD8+_T": 0.18990948338527083,
66
+ "DC": 0.0007063709284906101,
67
+ "ILC": 0.0005586177253275854,
68
+ "Monocyte": 0.19654494541822848,
69
+ "Myeloid": 0.02055902858984975,
70
+ "NK": 0.018357742899945007,
71
+ "Plasma_Cell": 0.0013210874635752798,
72
+ "Platelet": 0.011693046275987181,
73
+ "T": 0.04329879964349601,
74
+ "atypical_B": 0.0038321017932656143,
75
+ "cDC": 0.010872897479820232,
76
+ "dnT": 0.00038637067565090423,
77
+ "gdT": 0.02425285866892537,
78
+ "memory_B": 0.027744416983243047,
79
+ "naive_B": 0.02905918345416964,
80
+ "pDC": 0.002999311011801293
81
+ },
82
+ "monocyte_fraction_per_donor": {
83
+ "label": "Annotation_Level2 == Monocyte",
84
+ "natural_median": 0.1883720930232558,
85
+ "natural_q25_q75": [
86
+ 0.1412639405204461,
87
+ 0.2438084755090809
88
+ ]
89
+ },
90
+ "donors_by_country": {
91
+ "SG": 216,
92
+ "KR": 166,
93
+ "JP": 152,
94
+ "TH": 60,
95
+ "IN": 31
96
+ },
97
+ "donors_by_ethnicity": {
98
+ "Korean": 165,
99
+ "Japanese": 149,
100
+ "Singaporean Chinese": 85,
101
+ "Singaporean Indian": 70,
102
+ "Singaporean Malay": 61,
103
+ "Thai": 59,
104
+ "Indian": 30,
105
+ "unknown": 6
106
+ },
107
+ "donors_by_sex": {
108
+ "female": 350,
109
+ "male": 275
110
+ },
111
+ "training_corpus": {
112
+ "file": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/ordered_train_recipes.csv",
113
+ "aida_recipes": 251,
114
+ "all_recipes": 8192,
115
+ "aida_donors_in_recipes": 191,
116
+ "reference_donors_in_recipes": 191,
117
+ "aida_samples_by_split_in_corpus": {
118
+ "train": 500,
119
+ "val": 63,
120
+ "test": 62
121
+ },
122
+ "note": "AIDA is part of the model_8 training corpus (like AIFI); every AIDA donor is used here"
123
+ },
124
+ "output": {
125
+ "path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/utility_studies_final6k_20260925/refcal_refs/reference/aida_donor_pseudobulk_20097.npz",
126
+ "sha256": "6daea5b8cf14cbde306ef5a09295fc2a502258a8b62b753a782b5226af5f90c6",
127
+ "bytes": 21349852
128
+ },
129
+ "elapsed_s": 80.6,
130
+ "reference_mean_cpm_sum": 1000000.0
131
+ }