Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/CAMPAIGN_STATUS.json +10 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/PROGRESS.md +43 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/events.jsonl +77 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/legacy_adapters/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py +496 -0
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/CAMPAIGN_STATUS.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"state": "running",
|
| 3 |
+
"stage": "global",
|
| 4 |
+
"started_at": "2026-10-12T12:33:47.457996+00:00",
|
| 5 |
+
"units_selected": 40,
|
| 6 |
+
"units_completed_this_invocation": 0,
|
| 7 |
+
"figure6": "waiting_user_data_no_execution",
|
| 8 |
+
"active": "global-imperial_eskd",
|
| 9 |
+
"updated_at": "2026-10-12T12:45:13.986209+00:00"
|
| 10 |
+
}
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/PROGRESS.md
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Implementation ledger — paper_figures_strictpairs_20261012
|
| 2 |
+
|
| 3 |
+
## State (updated 2026-10-12 12:28 UTC)
|
| 4 |
+
- Implementation and guarded execution are in progress; the full scientific campaign is not complete.
|
| 5 |
+
- Source Model8 Git has no commits and existing staged/untracked research assets. All new output is isolated in this versioned plan root; only opt-in legacy adapters may be changed with byte backups.
|
| 6 |
+
- Canonical manuscript is clean at `fb6380f` as observed on 2026-10-12. Other authorized work changed the Abstract during this task; preserve the latest approved frontmatter when assembling the isolated manuscript.
|
| 7 |
+
|
| 8 |
+
## Work packages
|
| 9 |
+
1. Strict support selection and opt-in legacy adapters: implemented; 40 support units prepared and tested.
|
| 10 |
+
2. Figure1 concept/corpus: complete with SVG/PDF/PNG and source provenance.
|
| 11 |
+
3. Architecture/panel rescoring: eight arms complete on the shared held-out reference; separate sweep floors retained.
|
| 12 |
+
4. Campaign: ImMicro fold0 n5 LoRA training, LoRA/pairedcal/scSemi generation and two all-ImMicro raw/refcal controls complete. The first full five-arm score is running. Remaining strict units await this integration gate.
|
| 13 |
+
5. Figure3–5 visual/statistical pipeline: implemented; strict final outputs await upstream generation/scoring. Historical rare results are explicitly diagnostic.
|
| 14 |
+
6. Review deck and staged manuscript PDF: produced with pending labels. Final rendering/export integration and archive snapshot preparation are in progress. Canonical manuscript is not modified by this task.
|
| 15 |
+
|
| 16 |
+
Latest completed verification: 93 focused CPU tests passed (2026-10-12). This does not certify unexecuted full-cohort analyses.
|
| 17 |
+
|
| 18 |
+
## Interface preflight
|
| 19 |
+
| Producer | Consumer | Binding |
|
| 20 |
+
|---|---|---|
|
| 21 |
+
| Support manifests | LoRA/calibration/scSemi/deconvolution | exact sample IDs, unique donors, no test donor or extra visit access |
|
| 22 |
+
| Rescoring/campaign | Figures/Results | source-bound typed metrics and readiness, no mixing old n+validation with strict-n |
|
| 23 |
+
| Figure1 | Methods/other panels | K_cond=1000; rho=3869.603120208939; N_gen=1500 distinct |
|
| 24 |
+
| Rare metrics | Figure5 | include zeros, patient IDs, mandatory marker availability, descriptive Behcet |
|
| 25 |
+
|
| 26 |
+
Ruling: use a new versioned workspace within the registered Model8 core because its source Git is unborn and has substantial pre-existing research assets; do not stage/commit those assets or clone a misleading incomplete tree. Manuscript changes will be staged as an isolated copy and reviewed before safe integration.
|
| 27 |
+
|
| 28 |
+
## Prelaunch review correction
|
| 29 |
+
- Fixed inconsistent Imperial date axis (C137 draw4 now2020-04-30), strict QC-excluded visit validation, complete trainer resume binding, runtime outputSHAverification.
|
| 30 |
+
- Restored oldscSemi wrapper byte-exact; added opt-in strictwrapper.
|
| 31 |
+
- Preserved prelaunch generated support/conditions at backups/preflight_rejected_v1; never used for GPU work.
|
| 32 |
+
- Figure1 produced+visually checked; pretrain P/C8arms rescoredCPU; source tables ready.
|
| 33 |
+
|
| 34 |
+
## Execution checkpoint — 2026-10-12 13:02 UTC
|
| 35 |
+
- First complete five-arm healthy unit (`immicro/healthy/fold0/n5`) passed generation, scoring, extras and donor bootstrap. This is 1/20 healthy learning-curve units and 1/5 Figure3 folds, not a final pooled claim.
|
| 36 |
+
- Sepsis scSemi all five existing exact-five runs were audited and adopted without new GPU training: same 5 representatives, 77 targets, own-n HVG, equivalent prepared cells, model/shard/output SHA checks, independent shard-level export validation. Embedded legacy metadata remains unchanged. See `reports/deconv_scsemi_reuse_audit.md`.
|
| 37 |
+
- Eight pretraining arms now have common-readout composition scores in addition to P/C. Full NPZ hashes and frozen-annotation concordance were verified; neither 6k nor r16 is described as best on every endpoint.
|
| 38 |
+
- Historical healthy rank/full now uses only real-bulk FT with the same outer-fold train/validation/test IDs; strict size curves contain all five comparator arms. Zero-target-pair baselines are explicit.
|
| 39 |
+
- Disease main statistics use patient-aware contrasts and shared patient bootstrap across draws. Old visit-level sensitivity stays separate. Figure4 historical comparison uses actual real-bulk LoRA and scSemi five-fold sources, including Giroux exclusions.
|
| 40 |
+
- Figure3 has common cell-type-colored UMAP panels, full-cell composition fractions, and separate adaptation/generation times. Figure5 has all-state detection/abundance tables and separate Behcet any-C1Q vs multi-C1Q plots; Behcet calibration uses the same three candidate pairs, not external AIFI.
|
| 41 |
+
- `pbisc-strict-global-controls-20261012.service` is generating disease controls sequentially. `pbisc-strict-full-campaign-20261012.service` is queued behind its controller lock, then runs all 40 units, CPU derivations, gated PDFs/PPTX, and a one-time verified final archive delta. Failures stop for inspection; no OOM/restart loop.
|
| 42 |
+
- Latest full test run: 134 passed. Reviewed primary disease statistics/adoption provenance have no outstanding P1/P2 from the final narrow review. Full disease/rare and healthy multi-fold scientific results remain pending execution.
|
| 43 |
+
- Canonical manuscript remains unchanged by this task. Staging refreshes the latest approved frontmatter. Figure6 has no analysis or experiment launched. No GitHub push/Overleaf sync.
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/events.jsonl
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"at": "2026-10-12T10:45:14.083923+00:00", "operation": "prepare-external-controls", "state": "running", "resource": "cpu"}
|
| 2 |
+
{"at": "2026-10-12T10:45:15.467429+00:00", "operation": "prepare-external-controls", "state": "completed", "seconds": 1.3822942541446537}
|
| 3 |
+
{"at": "2026-10-12T10:45:15.519881+00:00", "operation": "prepare-strict-conditions", "state": "running", "resource": "cpu"}
|
| 4 |
+
{"at": "2026-10-12T10:45:19.800949+00:00", "operation": "prepare-strict-conditions", "state": "completed", "seconds": 4.280744560994208}
|
| 5 |
+
{"at": "2026-10-12T10:53:34.411976+00:00", "operation": "prepare-strict-conditions-v2", "state": "running", "resource": "cpu"}
|
| 6 |
+
{"at": "2026-10-12T10:53:38.844668+00:00", "operation": "prepare-strict-conditions-v2", "state": "completed", "seconds": 4.432218081085011}
|
| 7 |
+
{"at": "2026-10-12T10:56:16.826391+00:00", "operation": "immicro-healthy-fold0-n5-train", "state": "running", "resource": "gpu"}
|
| 8 |
+
{"at": "2026-10-12T10:58:18.438144+00:00", "operation": "immicro-healthy-fold0-n5-train", "state": "completed", "seconds": 121.50741662294604}
|
| 9 |
+
{"at": "2026-10-12T10:58:18.492261+00:00", "operation": "immicro-healthy-fold0-n5-lora", "state": "running", "resource": "gpu"}
|
| 10 |
+
{"at": "2026-10-12T10:59:46.264460+00:00", "operation": "immicro-healthy-fold0-n5-lora", "state": "completed", "seconds": 87.37215070892125}
|
| 11 |
+
{"at": "2026-10-12T10:59:46.330009+00:00", "operation": "immicro-healthy-fold0-n5-pairedcal", "state": "running", "resource": "gpu"}
|
| 12 |
+
{"at": "2026-10-12T11:01:12.194662+00:00", "operation": "immicro-healthy-fold0-n5-pairedcal", "state": "completed", "seconds": 85.47015835391358}
|
| 13 |
+
{"at": "2026-10-12T11:02:35.126883+00:00", "operation": "immicro-healthy-fold0-n5-train", "state": "binding_upgraded_after_review", "cells_sha256": "e1168468b621183604038b79280f46961c5819fe2386d9da0b454f7db642742a"}
|
| 14 |
+
{"at": "2026-10-12T11:05:12.203135+00:00", "operation": "immicro-healthy-fold0-n5-scinputs", "state": "running", "resource": "cpu"}
|
| 15 |
+
{"at": "2026-10-12T11:05:14.052055+00:00", "operation": "immicro-healthy-fold0-n5-scinputs", "state": "completed", "seconds": 1.8483133830595762}
|
| 16 |
+
{"at": "2026-10-12T11:05:14.100941+00:00", "operation": "immicro-healthy-fold0-n5-scprepare", "state": "running", "resource": "cpu"}
|
| 17 |
+
{"at": "2026-10-12T11:05:42.081655+00:00", "operation": "immicro-healthy-fold0-n5-scprepare", "state": "completed", "seconds": 27.97998751490377}
|
| 18 |
+
{"at": "2026-10-12T11:05:42.136933+00:00", "operation": "immicro-healthy-fold0-n5-scpretrain-0", "state": "running", "resource": "gpu"}
|
| 19 |
+
{"at": "2026-10-12T11:06:34.938737+00:00", "operation": "pilot-score-diffusion-only", "state": "running", "resource": "cpu"}
|
| 20 |
+
{"at": "2026-10-12T11:06:53.783449+00:00", "operation": "pilot-score-diffusion-only", "state": "completed", "seconds": 18.844257805030793}
|
| 21 |
+
{"at": "2026-10-12T11:14:24.459568+00:00", "operation": "immicro-healthy-fold0-n5-scpretrain-0", "state": "completed", "seconds": 522.3221146850847}
|
| 22 |
+
{"at": "2026-10-12T11:14:24.514474+00:00", "operation": "immicro-healthy-fold0-n5-scpretrain-2", "state": "running", "resource": "gpu"}
|
| 23 |
+
{"at": "2026-10-12T11:17:40.865068+00:00", "operation": "immicro-healthy-fold0-n5-scpretrain-2", "state": "completed", "seconds": 196.35023813904263}
|
| 24 |
+
{"at": "2026-10-12T11:17:40.912011+00:00", "operation": "immicro-healthy-fold0-n5-scpretrain-4", "state": "running", "resource": "gpu"}
|
| 25 |
+
{"at": "2026-10-12T11:21:26.371024+00:00", "operation": "immicro-healthy-fold0-n5-scpretrain-4", "state": "completed", "seconds": 225.45824180706404}
|
| 26 |
+
{"at": "2026-10-12T11:21:26.412306+00:00", "operation": "immicro-healthy-fold0-n5-scinfer-0", "state": "running", "resource": "gpu"}
|
| 27 |
+
{"at": "2026-10-12T11:31:42.831264+00:00", "operation": "immicro-healthy-fold0-n5-scinfer-0", "state": "completed", "seconds": 616.4185961470939}
|
| 28 |
+
{"at": "2026-10-12T11:31:42.897066+00:00", "operation": "immicro-healthy-fold0-n5-scinfer-8", "state": "running", "resource": "gpu"}
|
| 29 |
+
{"at": "2026-10-12T11:40:46.096833+00:00", "operation": "immicro-healthy-fold0-n5-scinfer-8", "state": "completed", "seconds": 543.1994235909078}
|
| 30 |
+
{"at": "2026-10-12T11:40:46.149541+00:00", "operation": "immicro-healthy-fold0-n5-scinfer-16", "state": "running", "resource": "gpu"}
|
| 31 |
+
{"at": "2026-10-12T11:46:48.753305+00:00", "operation": "immicro-healthy-fold0-n5-scinfer-16", "state": "completed", "seconds": 362.60319669591263}
|
| 32 |
+
{"at": "2026-10-12T11:46:48.795304+00:00", "operation": "immicro-healthy-fold0-n5-scexport", "state": "running", "resource": "cpu"}
|
| 33 |
+
{"at": "2026-10-12T11:46:54.280606+00:00", "operation": "immicro-healthy-fold0-n5-scexport", "state": "completed", "seconds": 5.4691027260851115}
|
| 34 |
+
{"at": "2026-10-12T11:46:54.326996+00:00", "operation": "immicro-healthy-fold0-n5-scvalidate", "state": "running", "resource": "cpu"}
|
| 35 |
+
{"at": "2026-10-12T11:46:57.583484+00:00", "operation": "immicro-healthy-fold0-n5-scvalidate", "state": "completed", "seconds": 3.2557712129782885}
|
| 36 |
+
{"at": "2026-10-12T11:52:30.409963+00:00", "operation": "immicro-healthy-fold0-n5-scexport", "state": "entrypoint_binding_verified"}
|
| 37 |
+
{"at": "2026-10-12T11:53:34.784746+00:00", "operation": "pilot-deconv-prepare-sepsis0", "state": "running", "resource": "cpu"}
|
| 38 |
+
{"at": "2026-10-12T11:54:08.678003+00:00", "operation": "pilot-deconv-prepare-sepsis0", "state": "completed", "seconds": 33.892768485005945}
|
| 39 |
+
{"at": "2026-10-12T11:56:07.952863+00:00", "operation": "global-immicro-raw", "state": "running", "resource": "gpu"}
|
| 40 |
+
{"at": "2026-10-12T12:03:37.604803+00:00", "operation": "global-immicro-raw", "state": "completed", "seconds": 447.602641884936}
|
| 41 |
+
{"at": "2026-10-12T12:03:37.719304+00:00", "operation": "global-immicro-refcal", "state": "running", "resource": "gpu"}
|
| 42 |
+
{"at": "2026-10-12T12:10:54.387319+00:00", "operation": "global-immicro-refcal", "state": "completed", "seconds": 434.7524452728685}
|
| 43 |
+
{"at": "2026-10-12T12:24:53.722073+00:00", "operation": "immicro-healthy-fold0-n5-score", "state": "running", "resource": "cpu"}
|
| 44 |
+
{"at": "2026-10-12T12:31:35.344883+00:00", "operation": "immicro-healthy-fold0-n5-score", "state": "completed", "seconds": 401.62207144801505}
|
| 45 |
+
{"at": "2026-10-12T12:33:49.577517+00:00", "operation": "global-immicro-raw", "state": "verified_skip"}
|
| 46 |
+
{"at": "2026-10-12T12:33:51.458420+00:00", "operation": "global-immicro-refcal", "state": "verified_skip"}
|
| 47 |
+
{"at": "2026-10-12T12:33:51.547071+00:00", "operation": "global-ye2026_sepsis-raw", "state": "running", "resource": "gpu"}
|
| 48 |
+
{"at": "2026-10-12T12:39:55.266132+00:00", "operation": "global-ye2026_sepsis-raw", "state": "completed", "seconds": 362.0762440508697}
|
| 49 |
+
{"at": "2026-10-12T12:39:55.362317+00:00", "operation": "global-ye2026_sepsis-refcal", "state": "running", "resource": "gpu"}
|
| 50 |
+
{"at": "2026-10-12T12:45:13.985921+00:00", "operation": "global-ye2026_sepsis-refcal", "state": "completed", "seconds": 317.21102344593965}
|
| 51 |
+
{"at": "2026-10-12T12:45:14.111139+00:00", "operation": "global-imperial_eskd-raw", "state": "running", "resource": "gpu"}
|
| 52 |
+
{"at": "2026-10-12T12:47:28.111830+00:00", "operation": "figure2-reviewed-preview-v2", "state": "running", "resource": "cpu"}
|
| 53 |
+
{"at": "2026-10-12T12:47:29.868899+00:00", "operation": "figure2-reviewed-preview-v2", "state": "completed", "seconds": 1.7551806829869747}
|
| 54 |
+
{"at": "2026-10-12T12:48:11.505500+00:00", "operation": "figure5-expanded-diagnostic-v2", "state": "running", "resource": "cpu"}
|
| 55 |
+
{"at": "2026-10-12T12:48:16.941174+00:00", "operation": "figure5-expanded-diagnostic-v2", "state": "completed", "seconds": 5.422949705040082}
|
| 56 |
+
{"at": "2026-10-12T12:55:13.220965+00:00", "operation": "immicro-healthy-fold0-n5-score", "state": "native_validation_signature_migrated", "previous_signature": "b13e46f90317e3f06fd6fb5c6fed206472c5cf498ba25c862342bf8e8b6fd770"}
|
| 57 |
+
{"at": "2026-10-12T12:59:05.407255+00:00", "operation": "figures234-reviewed-preview-v3", "state": "running", "resource": "cpu"}
|
| 58 |
+
{"at": "2026-10-12T12:59:08.798280+00:00", "operation": "figures234-reviewed-preview-v3", "state": "completed", "seconds": 3.389978000894189}
|
| 59 |
+
{"at": "2026-10-12T12:59:08.850592+00:00", "operation": "behcet-rule-label-reviewed-v3", "state": "running", "resource": "cpu"}
|
| 60 |
+
{"at": "2026-10-12T12:59:09.641226+00:00", "operation": "behcet-rule-label-reviewed-v3", "state": "completed", "seconds": 0.7895921289455146}
|
| 61 |
+
{"at": "2026-10-12T12:59:09.693352+00:00", "operation": "deck-reviewed-preview-v3", "state": "running", "resource": "cpu"}
|
| 62 |
+
{"at": "2026-10-12T12:59:10.541832+00:00", "operation": "deck-reviewed-preview-v3", "state": "completed", "seconds": 0.8453024930786341}
|
| 63 |
+
{"at": "2026-10-12T12:59:36.184000+00:00", "operation": "global-imperial_eskd-raw", "state": "completed", "seconds": 858.9609018329065}
|
| 64 |
+
{"at": "2026-10-12T12:59:36.306078+00:00", "operation": "global-imperial_eskd-refcal", "state": "running", "resource": "gpu"}
|
| 65 |
+
{"at": "2026-10-12T13:01:05.931439+00:00", "operation": "manuscript-current-frontmatter-preview-v3", "state": "running", "resource": "cpu"}
|
| 66 |
+
{"at": "2026-10-12T13:01:06.089599+00:00", "operation": "manuscript-current-frontmatter-preview-v3", "state": "completed", "seconds": 0.1570085440762341}
|
| 67 |
+
{"at": "2026-10-12T13:01:06.152842+00:00", "operation": "compile-review-pdfs-v3", "state": "running", "resource": "cpu"}
|
| 68 |
+
{"at": "2026-10-12T13:01:15.406023+00:00", "operation": "compile-review-pdfs-v3", "state": "completed", "seconds": 9.24971738201566}
|
| 69 |
+
{"at": "2026-10-12T13:03:25.163537+00:00", "operation": "verify-cpu-final", "state": "running", "resource": "cpu"}
|
| 70 |
+
{"at": "2026-10-12T13:04:03.055577+00:00", "operation": "verify-cpu-final", "state": "completed", "seconds": 37.88490461395122}
|
| 71 |
+
{"at": "2026-10-12T13:05:19.299649+00:00", "operation": "verify-cpu-final-with-r", "state": "running", "resource": "cpu"}
|
| 72 |
+
{"at": "2026-10-12T13:05:55.368337+00:00", "operation": "verify-cpu-final-with-r", "state": "completed", "seconds": 36.068204927956685}
|
| 73 |
+
{"at": "2026-10-12T13:07:22.571134+00:00", "operation": "deck-readable-ablation-preview-v4", "state": "running", "resource": "cpu"}
|
| 74 |
+
{"at": "2026-10-12T13:07:23.313441+00:00", "operation": "deck-readable-ablation-preview-v4", "state": "completed", "seconds": 0.7396434370893985}
|
| 75 |
+
{"at": "2026-10-12T13:07:23.366765+00:00", "operation": "convert-readable-review-deck-v4", "state": "running", "resource": "cpu"}
|
| 76 |
+
{"at": "2026-10-12T13:07:28.757394+00:00", "operation": "convert-readable-review-deck-v4", "state": "completed", "seconds": 5.388529522111639}
|
| 77 |
+
{"at": "2026-10-12T13:07:38.190161+00:00", "operation": "archive-implementation-snapshot", "state": "running", "resource": "cpu"}
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/legacy_adapters/plans/paired_finetune_intradataset_20260927/tools/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())
|