junidude14 commited on
Commit
2325485
·
verified ·
1 Parent(s): 50a34ae

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/README.md ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scSemiProfiler as a paired few-pair baseline (`scsemi5`)
2
+
3
+ Set up 2026-09-28. This is scSemiProfiler run in its own design: single cells for a few representatives, bulk for everyone. It is scored head-to-head with our LoRA-5 arm on the same draws.
4
+
5
+ - **Representatives:** the 5 training donors of each few-pair draw (`data/<ds>/fewshot_n5/draw<j>/train_donors.txt`). Every usable row of those donors is used, with its real single cells and its real bulk.
6
+ - **Targets:** the draw's `test_samples.txt` rows, from their real bulk only.
7
+
8
+ The frozen ImMicro campaign (`plans/immicro_scsemi_comparison_20260927/`) is not modified. Its pinned vendor code, compatibility patch, gene-set translation and `runtime_env` are reused.
9
+
10
+ ## What upstream does with real bulk (`bulktype`)
11
+
12
+ Source: `vendor/scSemiProfiler/scSemiProfiler/inference.py::fast_semi`, `initial_setup.py`, `singlecell_process.py`, `representative_selection.py`. The upstream commit is `c2aea02`.
13
+
14
+ **Bulk preprocessing (`initsetup`).** Bulk is library-normalised to 10^4 (`normed=False`), then `log1p`. It is PCA-reduced to `min(100, n_samples-1)` components; the PCA is fitted on all samples, representatives and targets. This matrix is the only bulk the method uses afterwards.
15
+
16
+ **Representative single cells (`scprocess`).**
17
+ - Each cell is library-normalised to 10^4.
18
+ - Background removal zeroes every value ≤ 10 (1e-3 of the library).
19
+ - Gene-set scores are computed from c2.cp and the variable ones are kept (`hvset`).
20
+ - A k=15 cell graph is built and neighbor-smoothed features are added.
21
+
22
+ **Pretraining per representative.**
23
+ - Pretrain 1 reconstructs the representative's cells: VAE 100 epochs, then GAN 100×3.
24
+ - Pretrain 2 adds a bulk loss whose target is the representative's own pseudobulk, i.e. the mean of its processed cells: VAE 50, GAN 50×3.
25
+ - The representative's real bulk is not used in pretraining.
26
+
27
+ **`bulktype='real'` (used here).** The target's bulk-loss vector is
28
+
29
+ `pseudobulk_rep × (bulk_tgt + 0.1) / (bulk_rep + 0.1)`
30
+
31
+ - Both bulks are real CP10K (`expm1` of the processed bulk).
32
+ - The ratio is 1 on the gene-set features.
33
+ - So the real bulk enters only as a gene-wise fold change between the target and its own representative. That cancels the bulk→sc platform bias, and the absolute scale comes from the representative's single cells.
34
+
35
+ **`bulktype='pseudobulk'` (frozen ImMicro campaign).** The target's CP10K bulk replaces the gene part of that vector directly. This is meant for inputs that are already in pseudobulk space.
36
+
37
+ **Inference.**
38
+ - 5 ministages × 150 epochs.
39
+ - The bulk weight rises 8 → 1024 across ministages, with a shrinking upper-bound mask.
40
+ - The encoder input is the representative's cells, so the method outputs one generated cell per representative cell. Composition is inherited from the representative except where cells shift state.
41
+ - Output = ZINB mean, rescaled to each representative cell's library. Values ≤ 10 are zeroed, which leaves about 2 % non-zero in the frozen run.
42
+
43
+ **Assignment.** Each target uses exactly one representative. Upstream's rule is `representative_selection.update_membership`: nearest representative by Euclidean distance in the bulk PCA above. The fixed representatives replace upstream's KMeans / active-learning choice. `assignment.json` records every distance.
44
+
45
+ ## Protocol (per split)
46
+
47
+ | item | setting |
48
+ |---|---|
49
+ | upstream | commit `c2aea021…`, frozen compatibility patch; vendor file hashes checked at every call |
50
+ | inputs | raw bulk counts and raw UMI counts on the modeled genes (`normed=False`, `logged=False`) |
51
+ | modeled genes | 6k panel genes with `bulk_valid` in every representative and target row and `sc_valid` in every representative row (no target sc mask) |
52
+ | `initsetup` | `geneselection=False`, `batch=1` (its KMeans output is overwritten) |
53
+ | representatives | every usable row of the 5 training donors (Ji 7–9, Giroux 12–14, Imperial 12–15, sepsis and ImMicro 5 rows per draw) |
54
+ | `scprocess` | `cellfilter=False`, `threshold=1e-3`, `geneset=True`, `k=15` |
55
+ | gene sets | pinned c2.cp v7.4 translated to panel Ensembl IDs with the frozen campaign's own `translate_gmt()`; restricted to the frozen 5,913-gene axis, all 2,922 pathways are identical to the frozen mapped GMT (`genesets/geneset_assets.json`) |
56
+ | budget | upstream defaults: pretrain 1 = VAE100/GAN100 (lr 1e-3); pretrain 2 = VAE50/GAN50 (lr 1e-4); inference = 150 epochs × 5 ministages (lr 2e-4), `bulktype='real'`, `pseudocount=0.1` |
57
+ | seeds | base 20260927; pretrain 1 = base+1000+row, pretrain 2 = base+2000+row, target = base+row (row = index in the bulk file) |
58
+
59
+ ## Modeled genes
60
+
61
+ The count equals the scorer's scoring genes in every dataset. The masks do not vary within a dataset's usable rows, so the count is the same in all 5 draws.
62
+
63
+ | dataset | modeled genes |
64
+ |---|---:|
65
+ | ImMicro | 5,508 |
66
+ | Ye 2026 sepsis | 5,975 |
67
+ | Ji 2025 ChILI | 5,752 |
68
+ | Giroux 2022 | 5,563 |
69
+ | Imperial ESKD | 5,927 |
70
+
71
+ Each split's `inputs/inputs_manifest.json` records the count and the equality check.
72
+
73
+ ## Output adapter (`tools/export_npz.py` → `generated/<ds>/fewshot_n5/draw<j>/scsemi5__raw.npz` + `.log`)
74
+
75
+ **Cells.** 1,500 per target, taken from its representative's n generated cells:
76
+ - n ≥ 1500: drawn without replacement.
77
+ - n < 1500: whole permutations are concatenated to 1,500, so each cell is used ⌊1500/n⌋ or ⌈1500/n⌉ times. This affects representatives with few cells (Imperial down to 265, Ji 759, ImMicro 1,299).
78
+ - The stream is `default_rng([20260927, uint64(sha256(target)[:8])])`. The kept rows are stored in `source_row`.
79
+
80
+ **Depth.** Each generated cell is rescaled to sum to D.
81
+ - D = the median per-cell UMI, on the modeled genes, of all the representatives' observed cells in the draw.
82
+ - D is a label-free choice from the training pairs; it is recorded in the manifest, the metadata and the receipt.
83
+ - All-zero cells stay zero and are counted.
84
+ - The result is expected counts (Poisson rates); `score_ft.py` reads them out with its fixed Poisson seed.
85
+
86
+ **Genes.** Modeled genes go at their panel columns; every other panel column is 0.
87
+
88
+ **`metadata_json`.** `input_condition_path` = the draw's `test_raw.npz`, with its sha. The receipt carries `output_sha256`, per-target runtime and checks.
89
+
90
+ **Validation.** `tools/validate_export.py` recomputes every row from the lossless shards and checks:
91
+ - the scorer contract (panel gene order, keys, `allow_pickle=False`);
92
+ - finiteness and non-negativity;
93
+ - 1,500 cells per target;
94
+ - the condition samples;
95
+ - the receipt sha.
96
+
97
+ ## Deviations from upstream defaults (all deliberate)
98
+
99
+ 1. **Fixed representatives, no active learning or KMeans.** Both methods must see the same pairs. Assignment uses upstream's own nearest-representative function.
100
+ 2. **`geneselection=False`.** The Python API default is the top-6,000 bulk HVGs. The modeled axis is fixed (5.5–6.0k genes) so both methods are scored on the same genes. With fewer than 6,000 genes, HVG selection would keep nearly all of them anyway.
101
+ 3. **`cellfilter=False`.** This is the Python API default; the CLI default is on. The benchmark cells are already QC-retained, and upstream's filter needs `MT-` symbols while our axis uses Ensembl IDs.
102
+ 4. **Gene-set GMT translated from symbols to Ensembl IDs.** Same translation as the frozen campaign.
103
+ 5. **Frozen compatibility patch.** Three changes: an unused `scvi.nn` import is removed; `use_gpu` is translated to `accelerator`; the `geneset_len=0` slice is fixed (inactive here).
104
+ 5b. **Compatibility addition 2026-09-28 (`trailing_size1_batch_20260928`).** When a representative's cell count n satisfies n % 128 == 1, the last pretraining minibatch holds one cell and the encoder's BatchNorm1d crashes (seen in Ji draw 0 at N150_BC, 2,433 cells, and Imperial draw 0 at C141_0202, 1,025 cells).
105
+ - In `vaegan.train()` the scvi `DataSplitter` now gets its supported `drop_last=True` option in that case only. That is the remedy upstream itself left commented out in the same function (a drop-last splitter when `n_obs % batch_size == 1`).
106
+ - Every other cell count takes the byte-identical original call. No cell is removed from the data: each epoch reshuffles all n cells and skips the single leftover one.
107
+ - Tool: `tools/compat_patch_20260928.py`. It updates `vendor/compatibility.patch` and `vendor/source_manifest.json`, and keeps the previous manifest as `source_manifest.before_20260928.json`.
108
+ - CPU evidence (`validation/trailing_batch_fix_*.json`): the crash reproduces on the old code; the new code passes pretrain, inference, export and validation for N150_BC; for an unaffected representative, old and new code give bitwise-identical pretrain checkpoints, per-target models and shards.
109
+ - Scan (`validation/trailing_batch_scan_server{1,2}.json`, all 25 few-pair and 25 CV splits): the few-pair splits hit are Ji 0, 1, 3 (N150_BC), Giroux 0–4 (BAAF62_d7, 7,297 cells) and Imperial 0 (C141_0202). No representative hits the inference condition (n > 9000 and n % 9000 == 1).
110
+ 6. **Memory-lean cell graph** (`tools/lean_cellgraph.py`), used in place of upstream `fast_cellgraph` inside `scprocess`.
111
+ - Upstream's version was OOM-killed at the 16 GiB CPU cap on the largest Giroux representative (15,650 cells). It holds dense n×n copies plus an n×14×G gather and two temporaries of that size, and runs an O(n²) Python loop.
112
+ - The lean version does the same arithmetic in the same order: it computes the gather in row chunks and vectorises the neighbor lookup, falling back to upstream's loop when a row doesn't have exactly k−1 neighbors.
113
+ - Its outputs are **bit-identical** to upstream, checked on `selfw`, `adj`, `neighbors`, `neighborx` and the returned tensor (`validation/lean_cellgraph_*.json`, `validation/prepared_*`). It is 5–8× faster.
114
+ - That rep now prepares at 7.1 GiB peak.
115
+ - Its sha256 is part of the run signature.
116
+ 7. **Engineering only, with no change to the computation.**
117
+ - The upstream pipeline is run in bounded, resumable chunks: `scinfer`'s loop is re-expressed per representative and per target.
118
+ - The pretrain-2 checkpoint path is passed to `fast_semi`, which upstream supports.
119
+ - Each upstream dense output is re-encoded as CSR, verified bit-equal, and the dense `.npy` is deleted (its sha is kept).
120
+ - `sample_sc/*.h5ad` is deleted after a Giroux draw is exported and validated (its sha is in `prepared.json`).
121
+ 8. **Adapter.** 1,500 cells per target and depth D, as above. The normalized output is not called raw counts.
122
+
123
+ ## Validation done (CPU only; CUDA hidden throughout)
124
+
125
+ - `tests/test_adapter.py`: 6 unit tests pass (row rule, depth rule).
126
+ - **Ji draw 0 smoke** (2 representatives × 400 cells, 4 targets, epochs cut to 1–2; `smoke/ji2025_chili_draw0/`):
127
+ - inputs → upstream prepare (792 gene-set features) → pretrain and infer in two resumable calls each → export → independent validation (max deviation 1.5e-5) → `score_ft.py`.
128
+ - The scorer accepted the receipt (`receipt_verified=True`) and ran every metric, including the contrast/DEG path.
129
+ - The first export revealed that object-dtype `gene_ids` could not be loaded with `allow_pickle=False`. The exporter was fixed, and the failed output is kept under `generated/_failed_object_dtype_20260928/`.
130
+ - **Queue runner, CPU smoke mode** (`SMOKE_CPU=1`; `smoke/queue_test*.txt`): full control flow, chunked loops, export, validation, `clean_sample_sc`, scoring, and skip-on-rerun.
131
+ - **Memory stress and bit-identity of the prepare step:** see "Memory (measured)" below.
132
+ - **Cross-host equivalence.** The same Imperial smoke was run on server_1 (frozen `runtime_env`) and server_2 (new venv). Every artifact is bit-identical: inputs, prepared project, pretrain checkpoints, target shards, exported NPZ and scores. The run signature is the same.
133
+
134
+ ## Code updates on running queues (`compat_migrations.json`)
135
+
136
+ A work dir's identity is the run signature it was created with, and every receipt is signed with it.
137
+
138
+ **Migrating a run to new code.** A later code version may continue a run only if:
139
+ - its binding differs from the run's latest binding only in `source` (the vendor manifest) and/or `wrapper_sha256`; and
140
+ - each change is an approved transition listed in `compat_migrations.json`.
141
+
142
+ The migration is then appended to `run_manifest.json`. New receipts carry `code_signature`, and the export receipt and metadata list the migrations. Any other difference refuses, as before.
143
+
144
+ **Deploy protocol.** Vendor files are replaced only under an exclusive lock on `.code_update.lock`, and the runner holds a shared lock while it verifies vendor hashes and imports the vendor. The 2026-09-28 deploy went in this order on both hosts:
145
+ 1. transitions file;
146
+ 2. atomic runner swap;
147
+ 3. a ≥120 s wait, so calls started on the old runner are past their vendor import;
148
+ 4. the vendor patch under the lock.
149
+
150
+ Live production dirs migrated cleanly on both hosts, with their identity kept.
151
+
152
+ ## Environments
153
+
154
+ **server_1.** The frozen `plans/immicro_scsemi_comparison_20260927/runtime_env` is reused unmodified: a venv on `miniforge3/envs/scanvi` plus faiss-cpu, gseapy, igraph, texttable, requests and urllib3. It also takes certifi, charset_normalizer, regex and defusedxml from `~/.local`, as the frozen campaign did. `env_server1.json` has the details.
155
+
156
+ **server_2.** `scsemi/runtime_env` is built by `tools/prepare_env_server2.sh`. It uses the same base env path and versions, with every one of those packages pinned inside the venv, and runs with `PYTHONNOUSERSITE=1`. `runtime_env/scsemi_environment.json` has the details.
157
+
158
+ ## Launch (coordinating agent only; GPU steps go through `ml-run` after `thermal_guard.sh` + `gpu_usable.sh`)
159
+
160
+ **server_1** (queue order: ji2025_chili, giroux2022, ye2026_sepsis, immicro; 5 draws each):
161
+ ```bash
162
+ S=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi
163
+ systemd-run --user --unit=scsemi-queue-s1 --setenv=QUEUE=$S/queues/server1_fewshot.txt --setenv=SCORE=1 \
164
+ /bin/bash $S/tools/run_queue_scsemi.sh
165
+ ```
166
+
167
+ **server_2** (Imperial; its data and outputs live there):
168
+ ```bash
169
+ ssh spark-0110 'S=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/scsemi; \
170
+ systemd-run --user --unit=scsemi-queue-s2 --setenv=QUEUE=$S/queues/server2_fewshot.txt --setenv=SCORE=1 \
171
+ /bin/bash $S/tools/run_queue_scsemi.sh'
172
+ ```
173
+
174
+ **Knobs:**
175
+ - `CHUNK_REPS` (2 representatives per GPU call) and `CHUNK_TARGETS` (12 targets per GPU call).
176
+ - `MAX_WAIT_H` (24).
177
+ - `PREP_ONLY=1`: CPU steps only.
178
+ - `PREP_MEM` (16): see the memory note.
179
+
180
+ **How the queue behaves:**
181
+ - It skips splits that are already exported and validated, and resumes partial splits from their receipts.
182
+ - A failure is logged; the split's outputs are kept with no retry, and the queue moves on.
183
+ - An unreceipted upstream artefact stops that split for inspection.
184
+ - Each split runs under `work/.../.split.lock`, so a `PREP_ONLY` CPU queue and the GPU queue can run at the same time safely.
185
+
186
+ **Logs and per-target runtime:**
187
+ - `logs/queue_*.log`
188
+ - `work/<ds>/fewshot_n5/draw<j>/{events.jsonl,gpu.log,shards/<target>.json}` (`elapsed_seconds`)
189
+ - the export receipt (`per_target`, `median_target_seconds`)
190
+
191
+ **Scoring.** With `SCORE=1`, `score_ft.py` runs on the draw's test donors with `contrast_args.sh`, output to `scores/<ds>/fewshot_n5/draw<j>_scsemi5/`. It uses the same donors and reference view as the draw's other arms, so the metrics are directly comparable.
192
+
193
+ ## GPU-time estimate
194
+
195
+ Basis: the frozen campaign's measured timings on GB10:
196
+ - **Per target:** 37.1 s with 1,500 representative cells, i.e. 750 full-batch steps.
197
+ - **Pretraining:** 80.2 s for 1,500 cells, i.e. 11.1 ms per 128-cell step over 600 epochs.
198
+
199
+ How they scale:
200
+ - Pretraining scales with representative cells.
201
+ - The per-target range runs from 37 s (overhead-bound) to 37 s × (mean representative cells / 1,500) (data-bound). The inference batch is `min(n, 9000)`.
202
+
203
+ | dataset (5 draws) | targets | pretrain | targets | total GPU |
204
+ |---|---:|---:|---:|---:|
205
+ | ji2025_chili | 126 | 2.2 h | 1.3–3.3 h | 3.5–5.4 h |
206
+ | giroux2022 | 54 | 10.5 h | 0.6–4.1 h | 11.1–14.6 h |
207
+ | ye2026_sepsis | 385 | 2.6 h | 4.0–19.0 h | 6.6–21.6 h |
208
+ | immicro | 510 | 1.4 h | 5.3–13.0 h | 6.6–14.4 h |
209
+ | **server_1 total** | | | | **28–56 h** |
210
+ | imperial_eskd (server_2) | 715 | 3.0 h | 7.4–14.3 h | 10.4–17.3 h |
211
+
212
+ The Ji draw 0 receipts (`median_target_seconds`) will place the real per-target cost inside this range.
213
+
214
+ Load balancing: server_2 can take Giroux or sepsis once `data/<ds>/` and `scoring_cache/<ds>/` are rsynced there.
215
+
216
+ **As run (draw → host).** server_1 ran `queues/server1_fewshot_d0first.txt`. server_2 ran Imperial 0–4 and then extra queues that took draws off the server_1 tail. Its as-run copies are in `queues/as_run_server2/`; `tools/build_archive_request.py` refreshes them.
217
+
218
+ | host | draws |
219
+ |---|---|
220
+ | server_1 | Ji 0–4, Giroux 0–4, sepsis 0–3, ImMicro 0, 1, 4 |
221
+ | server_2 | Imperial 0–4, ImMicro 2, 3, sepsis 4 |
222
+
223
+ - ImMicro 4 started on server_2. At 2026-09-29 23:18 the memory guard stopped it, triggered by another user's vLLM, after 2 of 5 representatives. It was re-queued on server_1 and reruns there from scratch.
224
+ - Sepsis 4 was moved to server_2 on 2026-09-30 at 07:47 (`queues/server2_sepsis_d4_20260930.txt`, unit `scsemi-queue-s2c`) so both hosts finish at about the same time.
225
+ - The inputs match on both hosts: the `cells_panel6k` sha256 and the draw's run signature are identical.
226
+
227
+ ## Disk and memory
228
+
229
+ ### Memory (measured)
230
+
231
+ Upstream `scprocess`, called once over all representatives, is where memory runs out. It densifies every representative cell, keeps several dense n×n graph copies and an n×14×G gather per representative, and builds a cells×2,922 float64 gene-set matrix.
232
+
233
+ Measured at the 16 GiB CPU-unit cap:
234
+ - The largest Giroux representative (15,650 cells) was OOM-killed inside `fast_cellgraph`.
235
+ - The full Giroux draw 0 (149k representative cells) was OOM-killed at a 14.0 GiB peak in the cohort gene-set stage.
236
+ - The Imperial draws run with pure upstream code peaked at 8.5–13.4 GiB.
237
+
238
+ Two changes fix this:
239
+ - the lean cell graph (deviation 6);
240
+ - per-representative orchestration: the cohort `hvset` is computed first with upstream's own steps and order, then upstream `scprocess` runs once per representative.
241
+
242
+ Both reproduce upstream bit for bit, checked file by file on every prepared file (`validation/`):
243
+ - `prepared_imperial_upstream_vs_final.json`: 5 Imperial draws (70 representatives), final code vs **pure upstream**.
244
+ - `prepared_server1_oneshot_vs_perrep.json`: 15 Ji / sepsis / ImMicro draws, per-representative vs one-shot.
245
+ - `prepared_smoke_ji_upstream_vs_perrep.json`: smoke vs pure upstream.
246
+ - `lean_cellgraph_ji2025_chili_draw0.json`: function-level check on 8 representatives plus a synthetic case.
247
+
248
+ Peak RSS of the final prepare:
249
+
250
+ | dataset | peak RSS |
251
+ |---|---:|
252
+ | Ji | 2.9–4.1 GiB |
253
+ | sepsis | 3.8–6.3 GiB |
254
+ | ImMicro | 2.6–2.9 GiB |
255
+ | Imperial | 3.9–5.9 GiB |
256
+ | Giroux draw 0 | 11.6 GiB |
257
+
258
+ Giroux draws 1–4 have 128–156k representative cells, so a similar peak is expected. `PREP_MEM` (default 16) is the knob if one ever needs more; any value above 16 needs the coordinator's approval.
259
+
260
+ GPU steps (`ml-run`, `ml.slice`) hold a representative's dense graph a few times in host RAM: at most about 7 GB for the 15.6k-cell representative.
261
+
262
+ ### Disk
263
+
264
+ **Prepared `scsemi_project/sample_sc/*.h5ad`** (dense n×n graphs):
265
+
266
+ | dataset | per draw |
267
+ |---|---:|
268
+ | Ji | 3 GB |
269
+ | ImMicro | 2 GB |
270
+ | sepsis | 5 GB |
271
+ | Giroux | 24 GB |
272
+ | Imperial | 4.5 GB |
273
+
274
+ Every server_1 queue line sets `clean_sample_sc`, so these are deleted once the draw is exported and validated. Their sha256 stays in `prepared.json`, and the files can be re-derived bit-identically.
275
+
276
+ **Other outputs:**
277
+ - Per-target upstream models: about 20 MB each, so ~22 GB on server_1 and ~14 GB on server_2.
278
+ - Lossless CSR target shards: about 2 % dense.
279
+ - Exported NPZs: compressed.
280
+
281
+ On 2026-09-28 server_1 had 190 GB free, with 73 GB already used by the 15 pre-prepared draws. Giroux draws 1–4 are prepared lazily by the queue, one at a time.
282
+
283
+ ### Current state (2026-09-28, CPU only; no GPU step has run)
284
+
285
+ All splits of the few-pair campaign have been CPU-prepared (inputs + upstream prepare) under the final code, except Giroux draws 1–4:
286
+ - server_1: Ji 0–4, sepsis 0–4, ImMicro 0–4, Giroux 0.
287
+ - server_2: Imperial 0–4.
288
+
289
+ The GPU queues therefore start directly at pretraining; the queue prepares Giroux 1–4 on the way.
290
+
291
+ server_2 keeps `work/_archive_prelean_20260928/` (pure-upstream reference prepares) and `work/_archive_oneshot_lean_20260928/`. Both are verified duplicates, safe to delete.
292
+
293
+ ## Optional CV variant (`queues/server1_cv.txt`; not started)
294
+
295
+ Superseded on 2026-10-02 by "5-fold CV (A) and equal pair budget (B)" below: the dense cohort hvset of a CV fold
296
+ does not fit the 16 GiB CPU cap, and the costs below are replaced by measured ones.
297
+
298
+ - Representatives are every training donor of fold k, including inner-validation donors; targets are fold k's rows.
299
+ - The input builder, wrapper, exporter and queue already support `cv|DATASET|FOLD`.
300
+ - Output: `generated/<ds>/fold<k>/scsemi__raw.npz`.
301
+
302
+ **Cost.** Pretraining runs once per training row, so it dominates: the targets are only 1/5 of the rows. Same timing basis as above:
303
+
304
+ | dataset (5 folds) | representatives per fold | pretrain | targets | total GPU | largest prepared fold |
305
+ |---|---:|---:|---:|---:|---:|
306
+ | ji2025_chili | 25–27 | 7.3 h | 0.3–0.9 h | 7.7–8.2 h | 9 GiB |
307
+ | giroux2022 | 18–21 | 14.8 h | 0.2–1.7 h | 15.1–16.6 h | 29 GiB |
308
+ | ye2026_sepsis | 65–66 | 34.5 h | 0.8–4.0 h | 35.4–38.6 h | 53 GiB |
309
+ | immicro | 85–86 | 23.2 h | 1.1–2.7 h | 24.3–25.9 h | 25 GiB |
310
+ | **server_1 total** | | | | **82–89 h** | |
311
+ | imperial_eskd (server_2) | 110–133 | 30.4 h | 1.6–3.6 h | 32–34 h | 39 GiB |
312
+
313
+ That is about 3× the few-pair campaign. The memory note below applies to every fold, because every large training row becomes a representative.
314
+
315
+ ## 5-fold CV (A) and equal pair budget (B), prepared 2026-10-02 (CPU only; no GPU step run)
316
+
317
+ - **(A)** `cv|<ds>|<k>`, all five cohorts. Representatives = fold k's training + inner-val rows = exactly the rows
318
+ `runs/<ds>/fold<k>/real_lora/RUN.json` lists (checked for all 25 folds, Imperial against server_2's RUN.json).
319
+ Targets = fold k's rows. Output `generated/<ds>/fold<k>/scsemi__raw.npz`.
320
+ - **(B)** `budget|<ds>|<k>|…|<n>`, immicro and ye2026_sepsis, n ∈ {5, 10, 20, 40}. Representatives = `lora_n<n>`'s
321
+ `train_rows + inner_val_rows` (= `data/<ds>/CAL_BUDGET.json` `fit_sample_ids`; the builder refuses any mismatch).
322
+ Targets = fold k's rows. Output `generated/<ds>/fold<k>/scsemi_n<n>__raw.npz`, export arm `scsemi_n<n>`.
323
+
324
+ ### Reuse of pretraining: not cohort-wide, only B from A of the same fold
325
+
326
+ A representative r's pretraining reads `sample_sc/<r>.h5ad`, `geneset_scores/<r>.npy` and `hvset.npy` (vendor
327
+ `setdata`) and is seeded base + 1000/2000 + r's bulk row index; inference reads the same plus the rep / target rows
328
+ of `processed_bulkdata` (per-sample CP10K, independent of other rows), `hvgenes.npy` and r's pretrain-2 model.
329
+
330
+ - **Gene axis:** the per-split rule gives exactly the cohort-fixed axis (= the scorer's scoring genes) in every CV and
331
+ budget split of every cohort (`validation/hvset_dependence_20261002.json`). No gene differs.
332
+ - **`geneset_scores/<r>`** depends only on r's cells and the axis: byte-identical for all 35 representatives that
333
+ occur in more than one few-pair draw.
334
+ - **`hvset`** is scanpy's seurat HVG on the pooled gene-set scores of *all* representatives of the split. It decides
335
+ which ~700–780 of the 2,922 pathway scores are r's features and enters `feature_var`. Those 35 representatives had a
336
+ different `sample_sc/<r>` and different pretrain checkpoints in every draw, although their seed index was the same.
337
+ Across CV folds hvset is never identical (symmetric difference / Jaccard): Ji 35–86 / 0.89–0.95, Giroux 43–66 /
338
+ 0.92–0.95, sepsis 50–121 / 0.85–0.94, ImMicro 7–21 / 0.97–0.99, Imperial 35–77 / 0.90–0.95. A cohort-wide hvset
339
+ would differ from every fold's by 9–88 pathways and would be selected partly on that fold's test donors' cells.
340
+ - **Seeds:** in A the bulk rows are all usable rows in every fold, so the seed index is fold-independent; a B split's
341
+ bulk has fewer rows.
342
+ - **GPU determinism:** ImMicro few-pair draw 4, representatives HS19 and HS25, were pretrained independently on server_2
343
+ (2026-09-29) and server_1 (2026-09-30): all four checkpoints have the same sha256.
344
+
345
+ So a cohort-fixed pretrain is not equivalent to the per-split protocol (and leaks test-donor cells into feature
346
+ selection); A keeps one pretrain per representative per fold. B can reuse A exactly when it takes A's hvset and seeds:
347
+ `reuse_cv` does that, as a declared protocol variant. B's pathway selection then comes from fold k's whole training
348
+ pool (never a test donor) instead of the n budget rows alone; B-vs-A hvset differences it replaces: sepsis n=5 124–179
349
+ (Jaccard 0.79–0.85) down to n=40 47–99; ImMicro n=5 40–55 (0.93–0.95) down to n=40 8–34. The plain alternative
350
+ (`queues/server1_budget_plain_20261002.txt`: own hvset, own pretraining) costs 77 GPU hours more.
351
+
352
+ ### Code (opt-in; without the new flags / options every tool behaves and signs as before)
353
+
354
+ - `tools/lean_hvset.py` + `run_scsemi_paired.py --lean-hvset`: the cohort hvset streamed one representative at a time.
355
+ Bit-identical to `cohort_hvset` (means, variances, hvset bytes) on three draws, and the streamed hvset equals
356
+ `hvset.npy` of all 25 few-pair draws. Needed because the dense step holds ~70 KiB per representative cell (~34 GiB
357
+ for a sepsis CV fold).
358
+ - `run_scsemi_paired.py --reuse-from W` (prepare copies W's hvset and refuses unless every representative's
359
+ `sample_sc` / `geneset_scores` is byte-identical to W's; seeds = W's) and `--phase link` (CPU, hard-links W's
360
+ receipted checkpoints, receipts name the source). Refused when W's representatives include a target row or donor,
361
+ or the gene axis, scprocess / pretrain protocol, vendor source, environment, wrapper, cell-graph or gene-set asset differ.
362
+ - `prepare_draw_inputs.py --mode budget --fold k --n N` and `--check-only`; `export_npz.py` arm `scsemi_n<n>`.
363
+ - `run_queue_scsemi.sh`: `budget` lines, options `lean_hvset`, `reuse_cv`, `clean_prepared` (also deletes
364
+ `geneset_scores/*.npy`, 23 KB per cell), `offload` (`tools/offload_work.sh`: models + `rep_sc.h5ad` to spark-0110 at
365
+ the same absolute path, sha-verified), `offload|<ds>|cv` lines, env `MIN_FREE_GIB`, `REUSE_ALLOW_PRETRAIN`; smoke
366
+ lines may name `cv` / `budget`.
367
+ - `tools/check_units.py` (dry run of a queue), `tools/hvset_dependence.py` (the analysis above),
368
+ `tools/reuse_gpu_check.sh` (one-call GPU confirmation), `../tools/finalize_scsemi_cv_budget.sh` (scoring),
369
+ `../tools/extra_metrics.py --design scored`.
370
+ - CPU checks: `smoke/queue_test_cv_budget_20261002.txt` (SMOKE_CPU: CV with lean hvset → budget reusing it → link →
371
+ inference → export → validation, both passed); `validation/reuse_seed_cpu_smoke_20261002.json` (a budget split whose
372
+ own row index differs, pretrained without link with the CV seeds, gives byte-identical checkpoints);
373
+ `validation/check_units_*.json` (every unit's builder run, LoRA donor lists, assignment, cost, disk).
374
+ - Edited files are backed up as `*.bak_20261002`. `compat_migrations.json` is unchanged: no earlier work dir needs to
375
+ continue under the new wrapper (all 25 few-pair draws are exported and validated).
376
+
377
+ ### Queue, time, disk (server_1 only)
378
+
379
+ `queues/server1_cv_budget_20261002.txt` (65 units + 2 offload lines). Measured cost model (25 few-pair draws):
380
+ pretrain 0.0488 s per representative cell; a target 8.0 s + 0.0188 s per cell of its representative; call overhead
381
+ under 2 %. GPU hours from `validation/check_units_server1_cv_budget_20261002.json`:
382
+
383
+ | block | units | GPU h | cumulative wall (incl. CPU prepare) |
384
+ |---|---:|---:|---:|
385
+ | A ji2025_chili (canary) | 5 | 7.4 | 8 h |
386
+ | A immicro | 5 | 23.6 | 32 h |
387
+ | B immicro n 5/10/20/40 (reuse) | 20 | 9.2 | 43 h |
388
+ | A ye2026_sepsis | 5 | 35.1 | 80 h |
389
+ | B ye2026_sepsis n 5/10/20/40 (reuse) | 20 | 13.2 | 95 h |
390
+ | A giroux2022 | 5 | 15.3 | 111 h |
391
+ | A imperial_eskd | 5 | 31.0 | 144 h (6.0 d) |
392
+
393
+ Plain B instead of reuse: 99.7 instead of 22.4 GPU h (≈ 9.3 d in total). `…_userorder.txt` has the same units in the
394
+ order first requested (Ji, Giroux A → sepsis, ImMicro A → B n-major → Imperial A); it finishes at the same time but
395
+ ImMicro's B lands ~2.5 days later.
396
+
397
+ Disk: the prepared cell graphs + gene-set scores of one split are the transient peak (sepsis CV fold 63 GB, Imperial
398
+ 48 GB, sepsis n=40 48 GB) and are deleted after export (`clean_prepared`). Models and inputs stay until offloaded:
399
+ right after export for Ji, Giroux, Imperial and every B split, and for the ImMicro / sepsis CV runs after their B
400
+ lines. Local peak ≈ 85–95 GB (sepsis A); launch with `MIN_FREE_GIB=80` so a prepare waits instead of filling the disk.
401
+ Memory: CPU prepare ≤ 16 GiB (largest representative 15.7k cells, as in the few-pair runs), GPU calls ≤ ~28 GiB host
402
+ RAM (sepsis few-pair maximum); every CPU unit waits for MemAvailable ≥ 32 GiB + its cap.
403
+
404
+ ## Files
405
+
406
+ - `tools/prepare_draw_inputs.py`: builds the split inputs (bulk.h5ad, rep_sc.h5ad, manifest).
407
+ - `tools/run_scsemi_paired.py`: the upstream wrapper (prepare / pretrain / infer / status).
408
+ - `tools/export_npz.py`: the adapter.
409
+ - `tools/validate_export.py`: independent validation of an exported NPZ.
410
+ - `tools/run_queue_scsemi.sh`: the queue runner.
411
+ - `tools/make_queues.sh`: writes the queue files.
412
+ - `tools/cpu_unit.sh`: CPU systemd unit, ≤ 6 threads, MemoryMax ≤ 16G, 32 GiB floor.
413
+ - `tools/lean_cellgraph.py`: output-identical `fast_cellgraph`.
414
+ - `tools/verify_lean_cellgraph.py`: function-level check of the lean cell graph.
415
+ - `tools/compare_prepared.py`: file-by-file comparison of prepared splits.
416
+ - `tools/compat_patch_20260928.py`: the size-1 trailing batch fix.
417
+ - `tools/scan_trailing_batch.py`: scans every representative for the size-1 batch condition.
418
+ - `tools/compare_runs.py`: bitwise comparison of trained artefacts between two work dirs.
419
+ - `tools/lean_hvset.py`: output-identical, streamed cohort hvset (2026-10-02).
420
+ - `tools/hvset_dependence.py`: gene axis and hvset per CV / budget split, lean-hvset bit-identity (2026-10-02).
421
+ - `tools/check_units.py`: dry run of a queue file (builder, LoRA donor lists, assignment, cost, disk) (2026-10-02).
422
+ - `tools/reuse_gpu_check.sh`: one GPU call confirming a reused pretrain equals a fresh one (2026-10-02).
423
+ - `tools/offload_work.sh`: move a finished split's models + inputs to spark-0110, same absolute paths (2026-10-02).
424
+ - `compat_migrations.json`: approved code transitions.
425
+ - `tools/build_geneset_assets.py`: builds the gene-set asset.
426
+ - `tools/prepare_env_server2.sh`: builds the server_2 environment.
427
+ - `genesets/`: the mapped GMT and its manifest.
428
+ - `vendor/`: a copy of the frozen pinned upstream, hash-verified.
429
+ - `work/`: per-split runs.
430
+ - `smoke/`: CPU smoke runs.
431
+ - `validation/`: bit-identity records.
432
+ - `logs/`: logs.
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_scsemi_paired.py ADDED
@@ -0,0 +1,672 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Pinned scSemiProfiler in its native paired-representative mode, real bulk, gene sets on (resumable).
3
+
4
+ Phases (each invocation does a bounded amount of work and exits; receipts make every step skippable):
5
+ prepare CPU. upstream initsetup(bulk, normed=False) + fixed representatives + upstream nearest-representative
6
+ assignment (representative_selection.update_membership on processed_bulkdata.obsm['X_pca']) +
7
+ upstream scprocess(rep cells, normed=False, threshold 1e-3, geneset=True, k=15).
8
+ pretrain GPU (via ml-run only). Per representative: fastrecon (VAE100/GAN100, lr 1e-3) then reconst_pretrain2
9
+ (VAE50/GAN50, lr 1e-4), exactly the calls upstream scinfer() makes. --max-reps bounds one call.
10
+ infer GPU (via ml-run only). Per target: fast_semi(rep, target, rep's pretrain-2 model, bulktype='real',
11
+ pseudocount 0.1, lr 2e-4, 150 epochs x 5 ministages), the call upstream scinfer() makes.
12
+ The upstream dense output is re-encoded losslessly as CSR (verified equal) with a receipt holding the
13
+ per-target runtime. --max-targets bounds one call.
14
+
15
+ CUDA work belongs to the coordinating agent and must run through ml-run. No automatic retries. Partial
16
+ outputs are preserved; an unreceipted upstream artefact stops the run for inspection.
17
+ --smoke (only under scsemi/smoke/, CPU) shrinks the epoch budget to exercise the plumbing.
18
+
19
+ Opt-in additions 2026-10-02 (without these flags every phase behaves and signs exactly as before):
20
+ --lean-hvset prepare computes hvset.npy with tools/lean_hvset.cohort_hvset_lean (one representative in memory;
21
+ output-identical to cohort_hvset, validation/hvset_dependence_20261002.json). Needed for CV folds,
22
+ whose dense cohort hvset needs ~70 KiB per representative cell (above the 16 GiB CPU cap). Recorded
23
+ in the run binding, so pass it on every phase of that work dir.
24
+ --reuse-from W (equal-budget splits) the split's representatives are a subset of the prepared run W of the same
25
+ fold (its CV run). prepare copies W's hvset.npy instead of selecting one, then runs upstream
26
+ scprocess per representative and refuses unless every sample_sc/<r>.h5ad and geneset_scores/<r>.npy
27
+ is byte-identical to W's (prepared.json); pretraining seeds are W's (base + 1000/2000 + row index in
28
+ W's bulk order). Phase 'link' (CPU) then hard-links W's receipted pretrain checkpoints with receipts
29
+ naming their source; a representative without one is pretrained by phase 'pretrain' with W's seed,
30
+ which gives the same bytes (GPU pretraining is bit-reproducible: README "Reuse of pretraining").
31
+ Refuses when W's representatives include any of this split's targets. Recorded in the binding.
32
+ """
33
+ from __future__ import annotations
34
+
35
+ import argparse
36
+ from datetime import datetime, timezone
37
+ import fcntl
38
+ import gc
39
+ import hashlib
40
+ import importlib.metadata
41
+ import json
42
+ import os
43
+ from pathlib import Path
44
+ import re
45
+ import resource
46
+ import shutil
47
+ import sys
48
+ import time
49
+ import types
50
+
51
+ HERE = Path(__file__).resolve().parents[1]
52
+ SEED = 20260927
53
+ MIGRATIONS = HERE / "compat_migrations.json" # approved code transitions a run may migrate across
54
+ MIGRATABLE = {"source", "wrapper_sha256"} # binding components an approved transition may change
55
+ PROTOCOL = {
56
+ "method": "scSemiProfiler", "setting": "paired_fixed_representatives_realbulk_genesets",
57
+ "upstream_commit": "c2aea021188759e56ecf14578915c0237aaa75d2",
58
+ "initsetup": {"logged": False, "normed": False, "geneselection": False, "batch": 1},
59
+ "scprocess": {"logged": False, "normed": False, "cellfilter": False, "threshold": 0.001, "geneset": True,
60
+ "weight": 0.5, "k": 15},
61
+ "representatives": "fixed: every usable row of the split's training donors (no active learning)",
62
+ "assignment": "upstream representative_selection.update_membership: nearest representative by Euclidean "
63
+ "distance in processed_bulkdata.obsm['X_pca'] (initsetup PCA of log1p CP10K real bulk)",
64
+ "pretrain1": {"vaesteps": 100, "gansteps": 100, "lr": 1e-3, "k": 15, "diagw": 1},
65
+ "pretrain2": {"vaesteps": 50, "gansteps": 50, "lr": 1e-4, "k": 15, "diagw": 1.0},
66
+ "infer": {"bulktype": "real", "pseudocount": 0.1, "lr": 2e-4, "epochs": 150, "ministages": 5, "k": 15,
67
+ "diagw": 1.0},
68
+ "seeds": {"base": SEED, "pretrain1": "base + 1000 + bulk row index", "pretrain2": "base + 2000 + bulk row index",
69
+ "target": "base + bulk row index (frozen campaign rule)"},
70
+ "output_unit": "normalized_expression (upstream fast_semi output: ZINB mean, rep-cell library, values <= 10 zeroed)",
71
+ "cellgraph_impl": "tools/lean_cellgraph.fast_cellgraph_lean replaces upstream singlecell_process.fast_cellgraph "
72
+ "inside scprocess: same arithmetic, chunked (16 GiB CPU cap); bit-identical outputs verified "
73
+ "(validation/lean_cellgraph_*.json)",
74
+ "scprocess_orchestration": "cohort hvset first (upstream scprocess's own steps: sorted sample_ids, normalize_total "
75
+ "1e4, dense, X*(X>10), getGeneSetMatrix score formula, concatenate, log1p, "
76
+ "highly_variable_genes) -> hvset.npy; then upstream scprocess once per representative "
77
+ "(it skips hvset when hvset.npy exists). Bit-identical to one scprocess call over all "
78
+ "representatives (validation/prepared_*.json); peak memory is one representative",
79
+ }
80
+
81
+
82
+ def cohort_hvset(project: Path, rep_sc: Path, threshold: float) -> "np.ndarray":
83
+ """Upstream scprocess's hvset block, run representative by representative (same order, same arithmetic)."""
84
+ import numpy as np
85
+ import anndata
86
+ import scanpy as sc
87
+ from scSemiProfiler.singlecell_process import getGeneSetMatrix
88
+ R = anndata.read_h5ad(rep_sc)
89
+ sids = np.unique(R.obs["sample_ids"])
90
+ zps = []
91
+ for sid in sids:
92
+ a = R[(R.obs["sample_ids"] == sid).to_numpy()].copy()
93
+ sc.pp.normalize_total(a, target_sum=1e4)
94
+ X = np.array(a.X.todense())
95
+ X = X * np.array(X > 1e4 * threshold)
96
+ genes_upper = [g.upper() for g in list(a.var.index)]
97
+ gene_set_matrix, _ = getGeneSetMatrix("c2.cp.v7.4.symbols.gmt", genes_upper, "genesets/")
98
+ zp = X.dot(np.array(gene_set_matrix).T)
99
+ eps = 1e-6
100
+ den = (np.array(gene_set_matrix.sum(axis=1)) + eps)
101
+ zp = (zp + eps) / den
102
+ zp = zp - eps / den
103
+ zps.append(zp)
104
+ del a, X
105
+ zps = np.concatenate(zps, axis=0)
106
+ zdata = anndata.AnnData(zps)
107
+ sc.pp.log1p(zdata)
108
+ sc.pp.highly_variable_genes(zdata)
109
+ hvset = zdata.var.highly_variable
110
+ np.save(str(project) + "/hvset.npy", hvset)
111
+ return np.asarray(hvset)
112
+ SMOKE_BUDGET = {"pretrain1": {"vaesteps": 1, "gansteps": 1}, "pretrain2": {"vaesteps": 1, "gansteps": 1},
113
+ "infer": {"epochs": 2}}
114
+
115
+
116
+ def sha256(path: Path) -> str:
117
+ digest = hashlib.sha256()
118
+ with Path(path).open("rb") as stream:
119
+ for chunk in iter(lambda: stream.read(16 * 1024 * 1024), b""):
120
+ digest.update(chunk)
121
+ return digest.hexdigest()
122
+
123
+
124
+ def write_json(path: Path, value: dict) -> None:
125
+ path.parent.mkdir(parents=True, exist_ok=True)
126
+ tmp = path.with_name(path.name + ".tmp")
127
+ with tmp.open("w") as stream:
128
+ json.dump(value, stream, indent=1, default=str)
129
+ stream.write("\n")
130
+ stream.flush()
131
+ os.fsync(stream.fileno())
132
+ tmp.replace(path)
133
+
134
+
135
+ def canonical_sha(value) -> str:
136
+ return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
137
+
138
+
139
+ def resolve_run_identity(run_file: Path, binding: dict, code_signature: str) -> tuple[str, list]:
140
+ """The run's identity is the signature it was created with (every receipt is signed with it). A later code
141
+ version may continue the run only if its binding differs from the run's latest binding in MIGRATABLE components
142
+ alone and each change is an approved transition in compat_migrations.json; the migration is appended to
143
+ run_manifest.json. Anything else refuses, as before."""
144
+ rec = json.loads(run_file.read_text())
145
+ identity = rec["run_signature"]
146
+ migrations = rec.get("migrations", [])
147
+ if migrations:
148
+ last, last_sig = migrations[-1]["to_binding"], migrations[-1]["to_code_signature"]
149
+ else:
150
+ last, last_sig = {k: rec.get(k) for k in binding}, identity
151
+ if canonical_sha(last) != identity:
152
+ raise SystemExit("run_manifest.json binding does not hash to its run_signature; inspect")
153
+ if last == binding:
154
+ return identity, migrations
155
+ changed = sorted(k for k in set(last) | set(binding) if last.get(k) != binding.get(k))
156
+ if set(changed) - MIGRATABLE:
157
+ raise SystemExit(f"work dir belongs to different inputs/code/environment ({changed}); use a fresh work dir")
158
+ approved = json.loads(MIGRATIONS.read_text())["transitions"] if MIGRATIONS.exists() else []
159
+ used = []
160
+ for k in changed:
161
+ frm = canonical_sha(last[k]) if k == "source" else last[k]
162
+ to = canonical_sha(binding[k]) if k == "source" else binding[k]
163
+ hit = [x for x in approved if x["component"] == k and x["from"] == frm and x["to"] == to]
164
+ if not hit:
165
+ raise SystemExit(f"code change in {k} ({str(frm)[:12]} -> {str(to)[:12]}) is not an approved migration "
166
+ f"in {MIGRATIONS.name}; use a fresh work dir")
167
+ used.append(hit[0]["id"])
168
+ migrations = migrations + [{"at": datetime.now(timezone.utc).isoformat(), "host": os.uname().nodename,
169
+ "from_code_signature": last_sig, "to_code_signature": code_signature,
170
+ "changed": changed, "transitions": used, "to_binding": binding}]
171
+ rec["migrations"] = migrations
172
+ write_json(run_file, rec)
173
+ return identity, migrations
174
+
175
+
176
+ REUSE_PROTOCOL_KEYS = ("upstream_commit", "scprocess", "pretrain1", "pretrain2", "seeds", "cellgraph_impl",
177
+ "scprocess_orchestration")
178
+ REUSE_BINDING_KEYS = ("source", "environment", "wrapper_sha256", "lean_cellgraph_sha256", "geneset_mapped_gmt_sha256")
179
+
180
+
181
+ def load_reuse_source(src: Path, work: Path, man: dict, protocol: dict, binding: dict) -> dict:
182
+ """--reuse-from: the source run W whose hvset and pretraining this split reuses. Everything a representative's
183
+ pretraining depends on besides its own cells must be W's: hvset (copied), gene axis, scprocess / pretrain protocol,
184
+ vendor source, environment, wrapper, cell-graph code, gene-set asset; the seeds are W's. W's representatives must
185
+ be a superset of this split's and must not contain any of its targets (W's hvset was selected on W's cells)."""
186
+ if src == work:
187
+ raise SystemExit("--reuse-from points at this work dir")
188
+ for f in ("run_manifest.json", "prepared.json", "inputs/inputs_manifest.json"):
189
+ if not (src / f).exists():
190
+ raise SystemExit(f"--reuse-from {src}: {f} missing (prepare the source run first)")
191
+ srun = json.loads((src / "run_manifest.json").read_text())
192
+ sprep = json.loads((src / "prepared.json").read_text())
193
+ sman = json.loads((src / "inputs/inputs_manifest.json").read_text())
194
+ if sprep["run_signature"] != srun["run_signature"]:
195
+ raise SystemExit(f"--reuse-from {src}: prepared.json belongs to another run signature")
196
+ sb = srun["migrations"][-1]["to_binding"] if srun.get("migrations") else srun
197
+ why = []
198
+ if sman["dataset"] != man["dataset"] or bool(sman.get("smoke")) != bool(man.get("smoke")):
199
+ why.append("dataset / smoke flag")
200
+ if sman["modeled_genes"]["gene_ids"] != man["modeled_genes"]["gene_ids"]:
201
+ why.append("modeled gene axis")
202
+ why += [f"protocol.{k}" for k in REUSE_PROTOCOL_KEYS if sb["protocol"].get(k) != protocol.get(k)]
203
+ why += [k for k in REUSE_BINDING_KEYS if sb.get(k) != binding.get(k)]
204
+ s_reps = {r["sample_id"] for r in sman["representatives"]}
205
+ reps = [r["sample_id"] for r in man["representatives"]]
206
+ if not set(reps) <= s_reps:
207
+ why.append(f"representatives not in the source run: {sorted(set(reps) - s_reps)[:5]}")
208
+ if "target_donors" not in man:
209
+ why.append("inputs manifest has no target_donors (build the split with --mode budget)")
210
+ else:
211
+ s_donors = {r["donor_id"] for r in sman["representatives"]}
212
+ if set(man["targets"]) & s_reps or set(man["target_donors"]) & s_donors:
213
+ why.append("a target (row or donor) is a representative of the source run")
214
+ if why:
215
+ raise SystemExit(f"--reuse-from {src} refused: {why}")
216
+ order = sman["bulk_row_order"]
217
+ return {"binding": {"work": str(src), "run_signature": srun["run_signature"],
218
+ "hvset_sha256": sprep["files"]["hvset.npy"],
219
+ "seed_rule": "pretrain seeds = the source run's: base + 1000/2000 + row index in its bulk_row_order"},
220
+ "src": src, "prep": sprep, "signature": srun["run_signature"],
221
+ "seed_index": {r: order.index(r) for r in reps}}
222
+
223
+
224
+ def main(argv=None) -> int:
225
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
226
+ ap.add_argument("--work", type=Path, required=True)
227
+ ap.add_argument("--phase", choices=["prepare", "pretrain", "infer", "status", "link"], required=True)
228
+ ap.add_argument("--device", default="cuda:0")
229
+ ap.add_argument("--threads", type=int, default=4)
230
+ ap.add_argument("--max-reps", type=int, default=0, help="pretrain: at most N representatives this call (0 = all)")
231
+ ap.add_argument("--max-targets", type=int, default=0, help="infer: at most N targets this call (0 = all)")
232
+ ap.add_argument("--smoke", action="store_true")
233
+ ap.add_argument("--lean-hvset", action="store_true", help="prepare: streamed, output-identical hvset (see docstring)")
234
+ ap.add_argument("--reuse-from", type=Path, default=None, help="prepared source run whose hvset / pretraining is reused")
235
+ a = ap.parse_args(argv)
236
+ if not 1 <= a.threads <= 6:
237
+ ap.error("--threads must be 1..6")
238
+ if a.phase == "link" and a.reuse_from is None:
239
+ ap.error("--phase link needs --reuse-from")
240
+ for name in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
241
+ os.environ[name] = str(a.threads)
242
+ work = a.work.resolve()
243
+ if a.smoke and "/scsemi/smoke/" not in str(work) + "/":
244
+ raise SystemExit("--smoke only under scsemi/smoke/")
245
+ if a.phase in ("prepare", "status", "link") and a.device != "cpu":
246
+ a.device = "cpu"
247
+ if a.device == "cpu" and os.environ.get("CUDA_VISIBLE_DEVICES") != "":
248
+ raise SystemExit("CPU phases require CUDA_VISIBLE_DEVICES=''")
249
+ if a.device.startswith("cuda") and a.smoke:
250
+ raise SystemExit("smoke runs are CPU only")
251
+ inputs = work / "inputs"
252
+ project = work / "scsemi_project"
253
+ events = work / "events.jsonl"
254
+ protocol = json.loads(json.dumps(PROTOCOL))
255
+ if a.smoke:
256
+ for k, v in SMOKE_BUDGET.items():
257
+ protocol[k].update(v)
258
+ protocol["SMOKE"] = "reduced epoch budget; plumbing test only, never a benchmark output"
259
+ if a.lean_hvset and a.reuse_from is None:
260
+ protocol["hvset_impl"] = ("tools/lean_hvset.cohort_hvset_lean: streamed, one representative in memory; "
261
+ "output-identical to cohort_hvset (validation/hvset_dependence_20261002.json)")
262
+
263
+ def event(kind: str, **values) -> None:
264
+ v = {"at": datetime.now(timezone.utc).isoformat(), "event": kind, "phase": a.phase, **values,
265
+ "max_rss_gib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**20, 2)}
266
+ with events.open("a") as s:
267
+ s.write(json.dumps(v, default=str) + "\n")
268
+ s.flush()
269
+ os.fsync(s.fileno())
270
+ print(json.dumps(v, default=str), flush=True)
271
+
272
+ # shared code lock: tools/compat_patch_*.py replaces vendor files under the exclusive lock, so this call never
273
+ # verifies or imports a half-updated vendor; released once the vendor modules are imported
274
+ code_lock = open(HERE / ".code_update.lock", "a")
275
+ fcntl.flock(code_lock, fcntl.LOCK_SH)
276
+ man = json.loads((inputs / "inputs_manifest.json").read_text())
277
+ if bool(man.get("smoke")) != a.smoke:
278
+ raise SystemExit("smoke flag differs from the inputs' smoke flag")
279
+ for name, digest in man["files"].items():
280
+ if sha256(inputs / name) != digest:
281
+ raise SystemExit(f"input {name} differs from its manifest")
282
+ vendor = HERE / "vendor/scSemiProfiler"
283
+ source = json.loads((vendor.parent / "source_manifest.json").read_text())
284
+ for name, expected in source["files"].items():
285
+ if sha256(vendor / name) != expected:
286
+ raise SystemExit(f"vendor source hash mismatch: {name}")
287
+ assets = json.loads((HERE / "genesets/geneset_assets.json").read_text())
288
+ gmt_src = HERE / "genesets/c2.cp.v7.4.symbols.gmt"
289
+ if sha256(gmt_src) != assets["mapped_gmt_sha256"] or sha256(vendor / "genesets/c2.cp.v7.4.symbols.gmt") != assets["original_gmt_sha256"]:
290
+ raise SystemExit("gene-set asset hash mismatch")
291
+ versions = {n: importlib.metadata.version(n) for n in ["torch", "scvi-tools", "scanpy", "anndata", "lightning",
292
+ "numpy", "scikit-learn", "faiss-cpu", "gseapy"]}
293
+ binding = {"protocol": protocol, "inputs": man["files"], "source": source, "environment": versions,
294
+ "wrapper_sha256": sha256(Path(__file__)), "lean_cellgraph_sha256": sha256(HERE / "tools/lean_cellgraph.py"),
295
+ "geneset_mapped_gmt_sha256": assets["mapped_gmt_sha256"]}
296
+ if a.lean_hvset and a.reuse_from is None:
297
+ binding["lean_hvset_sha256"] = sha256(HERE / "tools/lean_hvset.py")
298
+ reuse = None
299
+ if a.reuse_from is not None:
300
+ reuse = load_reuse_source(a.reuse_from.resolve(), work, man, protocol, binding)
301
+ binding["reuse"] = reuse["binding"]
302
+ code_signature = canonical_sha(binding)
303
+ run_file = work / "run_manifest.json"
304
+ migrations: list = []
305
+ if run_file.exists():
306
+ signature, migrations = resolve_run_identity(run_file, binding, code_signature)
307
+ else:
308
+ signature = code_signature
309
+ reps = [r["sample_id"] for r in man["representatives"]]
310
+ targets = list(man["target_order_test_samples"])
311
+ sids_expected = man["bulk_row_order"]
312
+ for s_ in sids_expected:
313
+ if not re.fullmatch(r"[A-Za-z0-9_.+-]+", s_):
314
+ raise SystemExit(f"unsafe sample id {s_!r}")
315
+ if not run_file.exists():
316
+ write_json(run_file, {"run_signature": signature, **binding, "work": str(work), "hostname": os.uname().nodename})
317
+
318
+ def status() -> dict:
319
+ pre = json.loads((work / "prepared.json").read_text()) if (work / "prepared.json").exists() else None
320
+ done_r = [r for r in reps if all((project / "models" / f"{b}{r}.receipt.json").exists()
321
+ for b in ("fast_reconst1_", "fastreconst2_"))]
322
+ done_t = [t for t in targets if (work / "shards" / f"{t}.json").exists()]
323
+ st = {"prepared": pre is not None, "n_reps": len(reps), "reps_pretrained": len(done_r),
324
+ "n_targets": len(targets), "targets_done": len(done_t),
325
+ "pretrain_complete": len(done_r) == len(reps), "infer_complete": len(done_t) == len(targets),
326
+ "run_signature": signature, "updated": datetime.now(timezone.utc).isoformat()}
327
+ write_json(work / "status.json", st)
328
+ return st
329
+
330
+ if a.phase == "status":
331
+ fcntl.flock(code_lock, fcntl.LOCK_UN)
332
+ print(json.dumps(status()))
333
+ return 0
334
+
335
+ import numpy as np
336
+ import anndata
337
+ import scipy.sparse as sp
338
+ sys.path.insert(0, str(vendor))
339
+ import torch
340
+ import scvi
341
+ import scSemiProfiler
342
+ from scSemiProfiler.inference import fastrecon, reconst_pretrain2, fast_semi
343
+ from scSemiProfiler.representative_selection import update_membership
344
+ fcntl.flock(code_lock, fcntl.LOCK_UN)
345
+ torch.set_num_threads(a.threads)
346
+ os.chdir(work) # upstream reads "genesets/" and writes vaegan_train.txt relative to the cwd
347
+ event("start", run_signature=signature, code_signature=code_signature,
348
+ migrations=[m["transitions"] for m in migrations], device=a.device, host=os.uname().nodename)
349
+ try:
350
+ # ------------------------------------------------------------------ prepare (CPU)
351
+ prep = work / "prepared.json"
352
+ if a.phase == "prepare":
353
+ if prep.exists():
354
+ event("prepare_already_done")
355
+ status()
356
+ return 0
357
+ if project.exists():
358
+ raise SystemExit("partial upstream project without prepared.json; preserve and inspect")
359
+ gdir = work / "genesets"
360
+ gdir.mkdir(exist_ok=True)
361
+ shutil.copyfile(gmt_src, gdir / "c2.cp.v7.4.symbols.gmt")
362
+ t0 = time.monotonic()
363
+ P = protocol["initsetup"]
364
+ scSemiProfiler.initsetup(str(project), str(inputs / "bulk.h5ad"), logged=P["logged"], normed=P["normed"],
365
+ geneselection=P["geneselection"], batch=P["batch"])
366
+ if not (project / "processed_bulkdata.h5ad").exists():
367
+ raise SystemExit("upstream initsetup did not write processed_bulkdata.h5ad")
368
+ sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
369
+ if sids != sids_expected:
370
+ raise SystemExit("upstream sids.txt differs from the input bulk order")
371
+ rep_idx = [sids.index(r) for r in reps]
372
+ scSemiProfiler.set_representatives(str(project), rep_idx)
373
+ bulk = anndata.read_h5ad(project / "processed_bulkdata.h5ad")
374
+ pca = np.asarray(bulk.obsm["X_pca"], dtype=np.float64)
375
+ labels = update_membership(reduced_bulk=pca, representatives=rep_idx)
376
+ (project / "status/init_cluster_labels.txt").write_text("".join(f"{int(x)}\n" for x in labels))
377
+ dist = np.sqrt(((pca[:, None, :] - pca[rep_idx][None, :, :]) ** 2).sum(-1))
378
+ assign = {t: {"representative": reps[int(labels[sids.index(t)])],
379
+ "distances": {reps[i]: float(dist[sids.index(t), i]) for i in range(len(reps))}} for t in targets}
380
+ for i, r in enumerate(reps):
381
+ if int(labels[sids.index(r)]) != i:
382
+ raise SystemExit(f"representative {r} not assigned to itself")
383
+ write_json(work / "assignment.json", {"rule": protocol["assignment"], "n_pca_components": int(pca.shape[1]),
384
+ "bulk_row_order": sids, "representative_indices": rep_idx,
385
+ "targets": assign,
386
+ "targets_per_representative": {r: sum(v["representative"] == r for v in assign.values()) for r in reps}})
387
+ del bulk
388
+ S = protocol["scprocess"]
389
+ import scSemiProfiler.singlecell_process as upstream_sp
390
+ sys.path.insert(0, str(HERE / "tools"))
391
+ from lean_cellgraph import fast_cellgraph_lean
392
+ upstream_sp.fast_cellgraph = fast_cellgraph_lean # resolved from module globals inside scprocess
393
+ if S["logged"] or S["normed"] or S["cellfilter"] or S["geneset"] is not True:
394
+ raise SystemExit("cohort_hvset replicates the logged=False, normed=False, cellfilter=False, geneset=True path only")
395
+ (project / "geneset_scores").mkdir(exist_ok=True)
396
+ if reuse is not None: # the source run's hvset (byte copy, sha-checked); upstream scprocess skips hvset
397
+ src_hv = reuse["src"] / "scsemi_project/hvset.npy"
398
+ if sha256(src_hv) != reuse["binding"]["hvset_sha256"]:
399
+ raise SystemExit(f"{src_hv} differs from the source run's prepared.json")
400
+ shutil.copyfile(src_hv, project / "hvset.npy")
401
+ event("hvset_copied_from_source", source=str(reuse["src"]))
402
+ elif a.lean_hvset:
403
+ from lean_hvset import cohort_hvset_lean
404
+ cohort_hvset_lean(project, inputs / "rep_sc.h5ad", S["threshold"])
405
+ event("cohort_hvset_done", impl="lean_hvset")
406
+ else:
407
+ cohort_hvset(project, inputs / "rep_sc.h5ad", S["threshold"])
408
+ event("cohort_hvset_done")
409
+ R = anndata.read_h5ad(inputs / "rep_sc.h5ad")
410
+ per_rep = work / "inputs_per_rep"
411
+ per_rep.mkdir(exist_ok=True)
412
+ for r in reps:
413
+ f_r = per_rep / f"{r}.h5ad"
414
+ R[(R.obs["sample_ids"] == r).to_numpy()].copy().write_h5ad(f_r)
415
+ scSemiProfiler.scprocess(str(project), str(f_r), logged=S["logged"], normed=S["normed"],
416
+ cellfilter=S["cellfilter"], threshold=S["threshold"], geneset=S["geneset"],
417
+ weight=S["weight"], k=S["k"])
418
+ f_r.unlink()
419
+ gc.collect()
420
+ per_rep.rmdir()
421
+ del R
422
+ genes = man["modeled_genes"]["gene_ids"]
423
+ if np.load(project / "hvgenes.npy", allow_pickle=True).astype(str).tolist() != genes:
424
+ raise SystemExit("upstream altered the modeled gene axis")
425
+ hvset = np.load(project / "hvset.npy", allow_pickle=False).astype(bool)
426
+ if hvset.shape != (2922,) or not hvset.any():
427
+ raise SystemExit("no variable gene-set features selected; refuse silent no-geneset fallback")
428
+ qc = {"selected_gene_sets": int(hvset.sum()), "reps": {}}
429
+ for r in reps:
430
+ f_sc, f_gs = project / "sample_sc" / f"{r}.h5ad", project / "geneset_scores" / f"{r}.npy"
431
+ if not f_sc.exists() or not f_gs.exists():
432
+ raise SystemExit(f"upstream scprocess did not write {r}")
433
+ g = np.load(f_gs, allow_pickle=False)
434
+ if not np.isfinite(g).all() or (g < 0).any():
435
+ raise SystemExit(f"{r}: non-finite / negative gene-set scores")
436
+ h = anndata.read_h5ad(f_sc, backed="r")
437
+ X = np.asarray(h.X[:])
438
+ n_feat = len(h.uns["feature_var"])
439
+ if h.var_names.astype(str).tolist() != genes or n_feat != len(genes) + int(hvset.sum()):
440
+ raise SystemExit(f"{r}: prepared axis / feature variance length mismatch")
441
+ glib = X.sum(1)
442
+ slib = g[:, hvset].sum(1)
443
+ h.file.close()
444
+ if g.shape[0] != X.shape[0]:
445
+ raise SystemExit(f"{r}: gene-set score rows differ from cells")
446
+ if (glib <= 0).any() or (slib <= 0).any():
447
+ raise SystemExit(f"{r}: {int((glib <= 0).sum())} cells with empty thresholded gene library, "
448
+ f"{int((slib <= 0).sum())} with empty selected gene-set library (log would be -inf)")
449
+ qc["reps"][r] = {"n_cells": int(X.shape[0]), "median_thresholded_gene_library": float(np.median(glib)),
450
+ "median_nonzero_genes": float(np.median((X > 0).sum(1))),
451
+ "zero_score_pathways": int(np.all(g == 0, axis=0).sum())}
452
+ del X, g
453
+ files = ["processed_bulkdata.h5ad", "hvgenes.npy", "sids.txt", "hvset.npy", "hvmask.npy",
454
+ "status/init_representatives.txt", "status/init_cluster_labels.txt"]
455
+ files += [f"sample_sc/{r}.h5ad" for r in reps] + [f"geneset_scores/{r}.npy" for r in reps]
456
+ write_json(work / "geneset_feature_qc.json", {"run_signature": signature, **qc})
457
+ file_sha = {f: sha256(project / f) for f in files}
458
+ extra = {}
459
+ if reuse is not None: # every pretraining input of every representative must be the source run's bytes
460
+ keys = ["hvset.npy"] + [f"sample_sc/{r}.h5ad" for r in reps] + [f"geneset_scores/{r}.npy" for r in reps]
461
+ bad = [k for k in keys if file_sha[k] != reuse["prep"]["files"].get(k)]
462
+ if bad:
463
+ raise SystemExit(f"prepared files differ from the source run {reuse['src']}: {bad[:6]}")
464
+ extra["reuse_check"] = {"source_work": str(reuse["src"]), "source_run_signature": reuse["signature"],
465
+ "identical_files": keys, "all_identical": True}
466
+ event("reuse_check_passed", n_files=len(keys))
467
+ write_json(prep, {"run_signature": signature, "seconds": round(time.monotonic() - t0, 1),
468
+ "files": file_sha,
469
+ "genesets_gmt_sha256": sha256(gdir / "c2.cp.v7.4.symbols.gmt"), **extra})
470
+ event("prepared", seconds=round(time.monotonic() - t0, 1), selected_gene_sets=int(hvset.sum()))
471
+ status()
472
+ return 0
473
+
474
+ # ------------------------------------------------------------------ GPU phases
475
+ if not prep.exists():
476
+ raise SystemExit("run --phase prepare first")
477
+ prepared = json.loads(prep.read_text())
478
+ if prepared["run_signature"] != signature:
479
+ raise SystemExit("prepared.json belongs to another run signature")
480
+ for name, digest in prepared["files"].items():
481
+ if name.startswith("sample_sc/"):
482
+ continue # large; verified per representative when used
483
+ if sha256(project / name) != digest:
484
+ raise SystemExit(f"prepared file changed: {name}")
485
+ sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
486
+ assign = json.loads((work / "assignment.json").read_text())["targets"]
487
+ for sub in ("models", "history", "tmp", "inferreddata"):
488
+ (project / sub).mkdir(exist_ok=True)
489
+ verified_sc: set[str] = set()
490
+
491
+ def verify_sc(r: str) -> None:
492
+ if r not in verified_sc:
493
+ if sha256(project / f"sample_sc/{r}.h5ad") != prepared["files"][f"sample_sc/{r}.h5ad"]:
494
+ raise SystemExit(f"prepared sample_sc/{r}.h5ad changed")
495
+ verified_sc.add(r)
496
+
497
+ def ckpt_ok(path: Path) -> bool:
498
+ rp = path.with_name(path.name + ".receipt.json")
499
+ if not path.exists():
500
+ if rp.exists():
501
+ raise SystemExit(f"receipt without checkpoint: {rp}")
502
+ return False
503
+ if not rp.exists():
504
+ raise SystemExit(f"unreceipted checkpoint {path}; preserve and inspect")
505
+ rec = json.loads(rp.read_text())
506
+ if rec["run_signature"] != signature or rec["sha256"] != sha256(path):
507
+ raise SystemExit(f"checkpoint receipt mismatch: {path}")
508
+ return True
509
+
510
+ def shim(state_path: Path):
511
+ sd = torch.load(state_path, map_location=a.device, weights_only=True)
512
+ return types.SimpleNamespace(module=types.SimpleNamespace(state_dict=lambda: sd))
513
+
514
+ if a.phase == "link": # CPU: reuse the source run's receipted pretrain checkpoints (hard link, sha-checked)
515
+ smodels = reuse["src"] / "scsemi_project/models"
516
+ n_link = n_missing = 0
517
+ for r in reps:
518
+ for stage, base in ((1, "fast_reconst1_"), (2, "fastreconst2_")):
519
+ dst = project / "models" / f"{base}{r}"
520
+ if ckpt_ok(dst):
521
+ continue
522
+ src = smodels / f"{base}{r}"
523
+ srp = src.with_name(src.name + ".receipt.json")
524
+ if not (src.exists() and srp.exists()):
525
+ n_missing += 1
526
+ event("link_source_missing", representative=r, stage=stage)
527
+ continue
528
+ srec = json.loads(srp.read_text())
529
+ want_seed = SEED + 1000 * stage + reuse["seed_index"][r]
530
+ if not (srec.get("complete") and srec["run_signature"] == reuse["signature"] and srec["stage"] == stage
531
+ and srec["representative"] == r and srec["seed"] == want_seed and srec["sha256"] == sha256(src)):
532
+ raise SystemExit(f"source checkpoint {src} does not match its receipt, the source run or the seed")
533
+ try:
534
+ os.link(src, dst)
535
+ except OSError:
536
+ shutil.copy2(src, dst)
537
+ if sha256(dst) != srec["sha256"]:
538
+ raise SystemExit(f"linked checkpoint {dst} differs from its source")
539
+ write_json(dst.with_name(dst.name + ".receipt.json"), {
540
+ "run_signature": signature, "sha256": srec["sha256"], "stage": stage, "representative": r,
541
+ "seed": want_seed, "elapsed_seconds": 0.0, "code_signature": code_signature,
542
+ "device": srec.get("device"), "complete": True,
543
+ "reused_from": {"path": str(src), "run_signature": reuse["signature"], "receipt": srec}})
544
+ n_link += 1
545
+ st = status()
546
+ event("link_done", linked=n_link, source_missing=n_missing,
547
+ **{k: st[k] for k in ("reps_pretrained", "n_reps")})
548
+ return 0
549
+
550
+ if a.phase == "pretrain":
551
+ P1, P2 = protocol["pretrain1"], protocol["pretrain2"]
552
+ n_done = 0
553
+ for r in reps:
554
+ c1 = project / "models" / f"fast_reconst1_{r}"
555
+ c2 = project / "models" / f"fastreconst2_{r}"
556
+ ok1, ok2 = ckpt_ok(c1), ckpt_ok(c2)
557
+ if ok1 and ok2:
558
+ continue
559
+ if a.max_reps and n_done >= a.max_reps:
560
+ break
561
+ verify_sc(r)
562
+ idx = reuse["seed_index"][r] if reuse is not None else sids.index(r)
563
+ model1 = None
564
+ if not ok1:
565
+ scvi.settings.seed = SEED + 1000 + idx
566
+ event("pretrain_start", stage=1, representative=r, seed=SEED + 1000 + idx)
567
+ t0 = time.monotonic()
568
+ model1 = fastrecon(str(project), r, device=a.device, k=P1["k"], diagw=P1["diagw"],
569
+ vaesteps=P1["vaesteps"], gansteps=P1["gansteps"], lr=P1["lr"])
570
+ el = time.monotonic() - t0
571
+ write_json(c1.with_name(c1.name + ".receipt.json"), {"run_signature": signature, "sha256": sha256(c1),
572
+ "stage": 1, "representative": r, "seed": SEED + 1000 + idx, "elapsed_seconds": el,
573
+ "code_signature": code_signature,
574
+ "device": a.device, "complete": True})
575
+ event("pretrain_complete", stage=1, representative=r, elapsed_seconds=round(el, 1))
576
+ if not ok2:
577
+ pre = model1 if model1 is not None else shim(c1)
578
+ scvi.settings.seed = SEED + 2000 + idx
579
+ event("pretrain_start", stage=2, representative=r, seed=SEED + 2000 + idx)
580
+ t0 = time.monotonic()
581
+ model2 = reconst_pretrain2(str(project), r, pre, device=a.device, k=P2["k"], diagw=P2["diagw"],
582
+ vaesteps=P2["vaesteps"], gansteps=P2["gansteps"], lr=P2["lr"])
583
+ el = time.monotonic() - t0
584
+ write_json(c2.with_name(c2.name + ".receipt.json"), {"run_signature": signature, "sha256": sha256(c2),
585
+ "stage": 2, "representative": r, "seed": SEED + 2000 + idx, "elapsed_seconds": el,
586
+ "code_signature": code_signature,
587
+ "device": a.device, "complete": True})
588
+ event("pretrain_complete", stage=2, representative=r, elapsed_seconds=round(el, 1))
589
+ del model2
590
+ del model1
591
+ gc.collect()
592
+ if a.device.startswith("cuda"):
593
+ torch.cuda.empty_cache()
594
+ n_done += 1
595
+ st = status()
596
+ event("pretrain_call_done", reps_this_call=n_done, **{k: st[k] for k in ("reps_pretrained", "n_reps")})
597
+ return 0
598
+
599
+ if a.phase == "infer":
600
+ I = protocol["infer"]
601
+ missing = [r for r in reps if not (ckpt_ok(project / "models" / f"fast_reconst1_{r}")
602
+ and ckpt_ok(project / "models" / f"fastreconst2_{r}"))]
603
+ if missing:
604
+ raise SystemExit(f"pretraining incomplete for {missing}")
605
+ shards = work / "shards"
606
+ shards.mkdir(exist_ok=True)
607
+ genelen = len(man["modeled_genes"]["gene_ids"])
608
+ n_done = 0
609
+ for t in targets:
610
+ rec_path = shards / f"{t}.json"
611
+ shard = shards / f"{t}.npz"
612
+ if rec_path.exists():
613
+ rec = json.loads(rec_path.read_text())
614
+ if rec["run_signature"] != signature or rec["shard_sha256"] != sha256(shard):
615
+ raise SystemExit(f"target shard receipt mismatch: {t}")
616
+ continue
617
+ if shard.exists():
618
+ raise SystemExit(f"shard without receipt: {shard}; preserve and inspect")
619
+ if a.max_targets and n_done >= a.max_targets:
620
+ break
621
+ r = assign[t]["representative"]
622
+ verify_sc(r)
623
+ upstream = project / "inferreddata" / f"{r}_to_{t}.npy"
624
+ if upstream.exists():
625
+ raise SystemExit(f"unreceipted upstream output {upstream}; preserve and inspect")
626
+ rid, tid = sids.index(r), sids.index(t)
627
+ scvi.settings.seed = SEED + tid
628
+ event("target_start", sample_id=t, representative=r, seed=SEED + tid)
629
+ t0 = time.monotonic()
630
+ fast_semi(str(project), rid, tid, str(project / "models" / f"fastreconst2_{r}"), device=a.device,
631
+ k=I["k"], diagw=I["diagw"], bulktype=I["bulktype"], pseudocount=I["pseudocount"], lr=I["lr"],
632
+ epochs=I["epochs"], ministages=I["ministages"])
633
+ elapsed = time.monotonic() - t0
634
+ M = np.load(upstream, allow_pickle=False)
635
+ n_rep_cells = json.loads((work / "geneset_feature_qc.json").read_text())["reps"][r]["n_cells"]
636
+ if M.shape != (n_rep_cells, genelen) or not np.isfinite(M).all() or (M < 0).any():
637
+ raise SystemExit(f"{t}: invalid upstream output {M.shape} (expected {(n_rep_cells, genelen)})")
638
+ C = sp.csr_matrix(M)
639
+ tmp = shards / f"{t}.tmp.npz"
640
+ sp.save_npz(tmp, C, compressed=False)
641
+ back = sp.load_npz(tmp).toarray()
642
+ if back.dtype != M.dtype or not np.array_equal(back, M):
643
+ raise SystemExit(f"{t}: CSR re-encoding is not lossless")
644
+ tmp.replace(shard)
645
+ lib = M.sum(1)
646
+ rec = {"sample_id": t, "representative": r, "rep_bulk_index": rid, "target_bulk_index": tid,
647
+ "seed": SEED + tid, "elapsed_seconds": elapsed, "device": a.device, "run_signature": signature,
648
+ "code_signature": code_signature,
649
+ "shape": list(M.shape), "dtype": str(M.dtype), "nnz": int(C.nnz),
650
+ "zero_fraction": float(1 - C.nnz / M.size), "zero_rows": int((lib == 0).sum()),
651
+ "mean_library_normalized": float(lib.mean()), "matrix_unit": "normalized_expression",
652
+ "upstream_npy": str(upstream), "upstream_npy_sha256": sha256(upstream),
653
+ "shard": str(shard), "shard_sha256": sha256(shard), "lossless_csr_verified": True,
654
+ "upstream_npy_removed": True, "created_at": datetime.now(timezone.utc).isoformat(), "complete": True}
655
+ write_json(rec_path, rec)
656
+ upstream.unlink() # dense copy of a verified lossless shard (disk)
657
+ del M, C, back
658
+ gc.collect()
659
+ n_done += 1
660
+ event("target_complete", sample_id=t, representative=r, elapsed_seconds=round(elapsed, 2),
661
+ zero_rows=rec["zero_rows"], zero_fraction=round(rec["zero_fraction"], 4))
662
+ st = status()
663
+ event("infer_call_done", targets_this_call=n_done, **{k: st[k] for k in ("targets_done", "n_targets")})
664
+ return 0
665
+ except BaseException as exc:
666
+ event("failed", error_type=type(exc).__name__, message=str(exc)[:2000])
667
+ raise
668
+ return 0
669
+
670
+
671
+ if __name__ == "__main__":
672
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/extra_metrics.py ADDED
@@ -0,0 +1,876 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Reviewer-expected realism / diversity metrics for the paired fine-tuning benchmark (CPU only; never imports torch).
3
+
4
+ Added 2026-10-01. Every scored unit (one few-pair draw, or one pooled 5-fold call) is re-read exactly as tools/score_ft.py
5
+ scored it, and four metric families are added next to the existing precision/coverage:
6
+
7
+ 1. classifier two-sample tests (real vs generated): kNN (k = 5) and random-forest 5-fold cross-validated ROC AUC
8
+ (scGAN / scDiffusion style) and the leave-one-out 1-NN accuracy (scLDM; Lopez-Paz & Oquab 2017);
9
+ 2. MMD^2 (unbiased, Gaussian RBF; median-heuristic bandwidth and the fixed multiples 0.5 / 1 / 2, plus their sum);
10
+ 3. scSemiProfiler's normalized error E_N (Wang et al. 2024, Methods eq. 17-18; get_error in vendor utils.py);
11
+ 4. precision / coverage at k = 3 and 5 next to k = 10 (k = 10 re-computed first and checked against score_ft.py).
12
+
13
+ Families 1, 2 and 4 use exactly the scorer's embedding and cells: score_ft.make_view (PCA-50 fitted on the scored
14
+ donors' R1 cells), the scorer's whole-NPZ Poisson read-out (seed 20260916), its donor-keyed generated subsample
15
+ (F.generated_subsample) and its pairwise depth matching (F.SB.depth_match with a fresh rng(20260929)). They are
16
+ reported both without ("raw", the deck's headline precision/coverage) and with depth matching ("dm"). The
17
+ real-vs-real control is the scorer's own: held-out real cells R2 of the same donors, same n per donor.
18
+
19
+ E_N follows scSemiProfiler's own space instead: per arm, log1p CP10K -> PCA-100 fitted on real and generated cells
20
+ together; Dif_sc = symmetric 1-NN distance (eq. 17); lower bound = random half split of the whole PCA matrix; upper
21
+ bound = random pairs of different real samples. Distances: squared L2 as their code computes them (faiss
22
+ IndexFlatL2), and plain L2 as the paper's text writes them. Two cell sets:
23
+ "all": every observed QC cell of each scored sample vs all of its generated cells (their setting);
24
+ control = a random within-sample half split of the observed cells (half A as 'real', half B as 'generated').
25
+ "pc": the precision/coverage cells (R1 vs the generated subsample, n per donor equal); control = R1 vs R2.
26
+ Representatives: scSemiProfiler sets a representative's error to the lower bound. Our scored samples never include a
27
+ representative (the 5 training donors of a few-pair draw are not scored in any arm), so no sample is set to LB; for
28
+ scsemi5 the table also gives the value that convention would produce (E_N x n_test / (n_test + n_representative_rows)).
29
+
30
+ usage (CPU; run through tools/run_extra_unit.sh):
31
+ extra_metrics.py --design fewshot --dataset giroux2022 --draws 0,1,2,3,4 [--threads 7] [--no-en-all]
32
+ extra_metrics.py --design pooled --dataset giroux2022
33
+ extra_metrics.py --collect # scores_extra/*.csv + TABLES.md from every unit written so far
34
+ extra_metrics.py --design scored --dataset immicro --score-dir scores/immicro/scsemi_cv_20261002/pooled \
35
+ --arms scsemi__raw --unit scsemi_cv_20261002/pooled # (2026-10-02) any scored call + arms -> new sub-path;
36
+ # --collect does not read these units
37
+ Outputs: scores_extra/<dataset>/<fewshot_n5/draw<j> | pooled>/{metrics.csv, per_donor.csv, en.csv, en_per_sample.csv,
38
+ repro.json, manifest.json}.
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import os
43
+ import sys
44
+
45
+
46
+ def _threads_from_argv(default: int = 7) -> int:
47
+ for i, a in enumerate(sys.argv):
48
+ if a == "--threads" and i + 1 < len(sys.argv):
49
+ return int(sys.argv[i + 1])
50
+ if a.startswith("--threads="):
51
+ return int(a.split("=", 1)[1])
52
+ return default
53
+
54
+
55
+ _THR = str(_threads_from_argv())
56
+ for _k in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMBA_NUM_THREADS"):
57
+ os.environ[_k] = _THR
58
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
59
+
60
+ import argparse # noqa: E402
61
+ import hashlib # noqa: E402
62
+ import json # noqa: E402
63
+ import shutil # noqa: E402
64
+ import subprocess # noqa: E402
65
+ import time # noqa: E402
66
+ from pathlib import Path # noqa: E402
67
+
68
+ import numpy as np # noqa: E402
69
+ import pandas as pd # noqa: E402
70
+ import scipy.sparse as sp # noqa: E402
71
+
72
+ TOOLS = Path(__file__).resolve().parent
73
+ sys.path.insert(0, str(TOOLS))
74
+ import ft_common as F # noqa: E402
75
+ import score_ft as S # noqa: E402 (module level: argparse/env only; main() is not run)
76
+
77
+ TASK = F.TASK
78
+ SCORES = TASK / "scores"
79
+ CODE_FILES = (Path(__file__).resolve(), TOOLS / "ft_common.py", TOOLS / "score_ft.py", F.SB_PATH)
80
+ OUT_ROOT = TASK / "scores_extra"
81
+ REMOTE = "spark-0110"
82
+ MIN_FREE_GIB = 40.0
83
+
84
+ SEED = 20261001 # every new random stream of this file (CV folds, RF, bandwidth subsample, E_N)
85
+ KS = (3, 5, 10)
86
+ KNN_C2ST_K = 5 # sklearn default, scDiffusion's kNN classifier
87
+ RF_TREES = 300 # scGAN: fully grown trees, max_features = sqrt; 300 instead of 1000 trees (cost)
88
+ CV_FOLDS = 5 # scGAN: five-fold cross-validation, equal real / generated counts
89
+ BW_MULTIPLES = (0.5, 1.0, 2.0) # scGAN: sigma in {m/2, m, 2m}
90
+ BW_MAX_CELLS = 4000 # R1 cells used for the median pairwise distance
91
+ EN_PCS = 100 # scSemiProfiler: PCA to 100 dimensions
92
+ EN_LB_MAX_QUERIES = 20000 # all-cells E_N: LB estimated from this many query cells per direction (index = full half)
93
+ EN_CHUNK = 8192
94
+
95
+ FEW_ARMS = ("zs_raw", "zs_cal", "scsemi5", "lora5", "zs_pseudo")
96
+ POOLED_ARMS = ("zs__raw", "zs__cal", "pseudo_full__cal", "real_lora__raw", "zs__pseudo")
97
+ CONTROL = "real_R2" # R1 vs R2 (P/C cells) / within-sample half split (all cells)
98
+ CONTROL_OOS = "real_R3" # out-of-sample real side: R2' vs R3 (families 1-2)
99
+ ARM_LABEL = {"zs_raw": "Zero-shot, real bulk", "zs__raw": "Zero-shot, real bulk",
100
+ "zs_cal": "Zero-shot + calibration", "zs__cal": "Zero-shot + calibration",
101
+ "scsemi5": "scSemiProfiler, 5 donors", "lora5": "LoRA, 5 donors",
102
+ "real_lora__raw": "LoRA, all training pairs", "pseudo_full__cal": "sc-only fine-tune (+ calibration)",
103
+ "zs_pseudo": "Zero-shot, sc pseudobulk input (reference)",
104
+ "zs__pseudo": "Zero-shot, sc pseudobulk input (reference)",
105
+ CONTROL: "Real vs real control (held-out real cells)",
106
+ CONTROL_OOS: "Real vs real control (out-of-sample: R2 vs R3)"}
107
+ # --design scored (added 2026-10-02): any existing score_ft.py call dir and arms, output under scores_extra/<ds>/<unit>
108
+ ARM_LABEL.update({"scsemi__raw": "scSemiProfiler, all training pairs (5-fold CV)",
109
+ **{f"scsemi_n{n}__raw": f"scSemiProfiler, {n} pairs + inner-val (equal budget)" for n in (5, 10, 20, 40)},
110
+ **{f"lora_n{n}__raw": f"LoRA, {n} pairs + inner-val" for n in (5, 10, 20, 40)}})
111
+ SCORED: dict = {} # {"dir": Path, "arms": tuple, "unit": str}; set by main for --design scored
112
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
113
+
114
+
115
+ def log(msg: str) -> None:
116
+ F.log(msg)
117
+
118
+
119
+ # =========================================================================== pure metric functions
120
+ def sqdist_min(Q: np.ndarray, X: np.ndarray, *, exclude_self: bool = False, max_block: float = 1.5e8) -> tuple:
121
+ """For every row of Q: the minimum squared L2 distance to the rows of X and its index (brute force, float64,
122
+ chunked BLAS). exclude_self: Q is X and the diagonal is skipped (leave-one-out)."""
123
+ Q = np.ascontiguousarray(Q, dtype=np.float64)
124
+ X = np.ascontiguousarray(X, dtype=np.float64)
125
+ xx = np.einsum("ij,ij->i", X, X)
126
+ qq = np.einsum("ij,ij->i", Q, Q)
127
+ out = np.empty(Q.shape[0])
128
+ arg = np.empty(Q.shape[0], dtype=np.int64)
129
+ chunk = max(16, int(max_block // max(X.shape[0], 1)))
130
+ for s in range(0, Q.shape[0], chunk):
131
+ e = min(s + chunk, Q.shape[0])
132
+ D = qq[s:e, None] + xx[None, :] - 2.0 * (Q[s:e] @ X.T)
133
+ if exclude_self:
134
+ D[np.arange(e - s), np.arange(s, e)] = np.inf
135
+ a = np.argmin(D, axis=1)
136
+ arg[s:e] = a
137
+ out[s:e] = np.maximum(D[np.arange(e - s), a], 0.0)
138
+ return out, arg
139
+
140
+
141
+ def one_nn_loo(zr: np.ndarray, zg: np.ndarray) -> dict:
142
+ """Leave-one-out 1-NN two-sample accuracy (Lopez-Paz & Oquab 2017; scLDM eq. 32): pool both sets, predict each
143
+ point's label by its nearest other point; 0.5 = indistinguishable, 1 = separable."""
144
+ Z = np.vstack([zr, zg])
145
+ y = np.r_[np.ones(len(zr), bool), np.zeros(len(zg), bool)]
146
+ _, a = sqdist_min(Z, Z, exclude_self=True)
147
+ ok = y[a] == y
148
+ return {"nn1_acc": float(ok.mean()), "nn1_acc_real": float(ok[y].mean()), "nn1_acc_gen": float(ok[~y].mean())}
149
+
150
+
151
+ def c2st_auc(zr: np.ndarray, zg: np.ndarray, *, kind: str, seed: int = SEED, n_jobs: int = 1) -> dict:
152
+ """Classifier two-sample test: stratified 5-fold CV ROC AUC of real (1) vs generated (0); mean and SD over folds."""
153
+ from sklearn.ensemble import RandomForestClassifier
154
+ from sklearn.metrics import roc_auc_score
155
+ from sklearn.model_selection import StratifiedKFold
156
+ from sklearn.neighbors import KNeighborsClassifier
157
+ Z = np.vstack([zr, zg]).astype(np.float32)
158
+ y = np.r_[np.ones(len(zr), np.int8), np.zeros(len(zg), np.int8)]
159
+ aucs = []
160
+ for tr, te in StratifiedKFold(CV_FOLDS, shuffle=True, random_state=seed).split(Z, y):
161
+ if kind == "knn":
162
+ clf = KNeighborsClassifier(n_neighbors=KNN_C2ST_K, n_jobs=n_jobs)
163
+ elif kind == "rf":
164
+ clf = RandomForestClassifier(n_estimators=RF_TREES, max_features="sqrt", n_jobs=n_jobs, random_state=seed)
165
+ else:
166
+ raise ValueError(kind)
167
+ clf.fit(Z[tr], y[tr])
168
+ p = clf.predict_proba(Z[te])[:, list(clf.classes_).index(1)]
169
+ aucs.append(roc_auc_score(y[te], p))
170
+ return {f"c2st_{kind}_auc": float(np.mean(aucs)), f"c2st_{kind}_auc_sd": float(np.std(aucs, ddof=1))}
171
+
172
+
173
+ def median_bandwidth(z: np.ndarray, *, seed: int = SEED, max_cells: int = BW_MAX_CELLS) -> float:
174
+ """Median heuristic (Gretton et al. 2012): median pairwise Euclidean distance among (<= max_cells) real cells."""
175
+ rng = np.random.default_rng(seed)
176
+ idx = np.sort(rng.choice(len(z), size=min(max_cells, len(z)), replace=False))
177
+ x = np.asarray(z[idx], np.float64)
178
+ sq = np.einsum("ij,ij->i", x, x)
179
+ D = np.maximum(sq[:, None] + sq[None, :] - 2 * x @ x.T, 0.0)
180
+ iu = np.triu_indices(len(x), 1)
181
+ return float(np.sqrt(np.median(D[iu])))
182
+
183
+
184
+ def _kernel_sums(A: np.ndarray, B: np.ndarray, sigmas, same: bool, max_block: float = 6e7) -> np.ndarray:
185
+ """sum over pairs of exp(-||a - b||^2 / (2 sigma^2)) for every sigma (diagonal excluded when same)."""
186
+ A = np.ascontiguousarray(A, np.float64)
187
+ B = np.ascontiguousarray(B, np.float64)
188
+ aa, bb = np.einsum("ij,ij->i", A, A), np.einsum("ij,ij->i", B, B)
189
+ g = np.asarray([1.0 / (2.0 * s * s) for s in sigmas])
190
+ tot = np.zeros(len(sigmas))
191
+ chunk = max(16, int(max_block // max(len(B), 1)))
192
+ for s in range(0, len(A), chunk):
193
+ e = min(s + chunk, len(A))
194
+ D = np.maximum(aa[s:e, None] + bb[None, :] - 2.0 * (A[s:e] @ B.T), 0.0)
195
+ for i, gi in enumerate(g):
196
+ K = np.exp(-gi * D)
197
+ if same:
198
+ K[np.arange(e - s), np.arange(s, e)] = 0.0
199
+ tot[i] += K.sum()
200
+ return tot
201
+
202
+
203
+ def mmd2_unbiased(zr: np.ndarray, zg: np.ndarray, sigmas) -> np.ndarray:
204
+ """Unbiased MMD^2 (Gretton et al. 2012, eq. 3) with Gaussian RBF k(x, y) = exp(-||x - y||^2 / (2 sigma^2)), one value
205
+ per sigma; the kernel sum over the sigmas (scGAN's multi-scale kernel) is the sum of the per-sigma values."""
206
+ n, m = len(zr), len(zg)
207
+ kxx = _kernel_sums(zr, zr, sigmas, True) / (n * (n - 1))
208
+ kyy = _kernel_sums(zg, zg, sigmas, True) / (m * (m - 1))
209
+ kxy = _kernel_sums(zr, zg, sigmas, False) / (n * m)
210
+ return kxx + kyy - 2.0 * kxy
211
+
212
+
213
+ def pc_at_k(zr: np.ndarray, zg: np.ndarray, k: int) -> dict:
214
+ """Kynkaanniemi precision and Naeem coverage / density with k-NN balls of the real set: the scorer's own
215
+ stage_b_embed functions (knn_radius, precision_coverage). density is rescaled from SB's fixed k = 10 to k."""
216
+ radius = F.SB.knn_radius(zr, k)
217
+ r = F.SB.precision_coverage(zr, radius, zg)
218
+ r["density"] = r["density"] * F.K_NN / k
219
+ return r
220
+
221
+
222
+ def expected_coverage(n_real: int, n_gen: int, k: int) -> float:
223
+ """Naeem et al. 2020, eq. 9: E[coverage] for identical real and fake distributions."""
224
+ num = np.prod([(n_real - i) for i in range(1, k + 1)], dtype=np.float64)
225
+ den = np.prod([(n_gen + n_real - i) for i in range(1, k + 1)], dtype=np.float64)
226
+ return float(1.0 - num / den)
227
+
228
+
229
+ def two_sample_block(zr: np.ndarray, zg: np.ndarray, sigma_m: float, *, n_jobs: int, rf: bool = True) -> dict:
230
+ out = {}
231
+ out.update(c2st_auc(zr, zg, kind="knn", n_jobs=n_jobs))
232
+ if rf:
233
+ out.update(c2st_auc(zr, zg, kind="rf", n_jobs=n_jobs))
234
+ out.update(one_nn_loo(zr, zg))
235
+ sig = [m * sigma_m for m in BW_MULTIPLES]
236
+ mm = mmd2_unbiased(zr, zg, sig)
237
+ for mult, val in zip(BW_MULTIPLES, mm):
238
+ out[f"mmd2_bw{mult:g}"] = float(val)
239
+ out["mmd2_sum"] = float(mm.sum())
240
+ out["mmd_bandwidth_m"] = float(sigma_m)
241
+ return out
242
+
243
+
244
+ # =========================================================================== scSemiProfiler E_N
245
+ def log1p_cp10k_sparse(X: sp.csr_matrix) -> sp.csr_matrix:
246
+ """SB.cp10k_log1p (per-cell CP10K over the columns, log1p; empty cells stay zero) kept sparse, float32."""
247
+ X = X.tocsr().astype(np.float64)
248
+ lib = np.asarray(X.sum(axis=1)).ravel()
249
+ D = (sp.diags(np.divide(F.CP10K, lib, out=np.zeros_like(lib), where=lib > 0)) @ X).tocsr()
250
+ D.data = np.log1p(D.data)
251
+ return D.astype(np.float32)
252
+
253
+
254
+ class Gram:
255
+ """Running X^T X, column sums and row count of log1p-CP10K features (float64), for an exact PCA by eigh of the
256
+ covariance (the solver sklearn's PCA calls covariance_eigh; equal to the full-SVD PCA up to component signs)."""
257
+
258
+ def __init__(self, p: int):
259
+ self.G = np.zeros((p, p))
260
+ self.s = np.zeros(p)
261
+ self.n = 0
262
+
263
+ def add(self, L: sp.csr_matrix, chunk: int = EN_CHUNK) -> "Gram":
264
+ for a in range(0, L.shape[0], chunk):
265
+ B = L[a:a + chunk].toarray() # float32 (log1p CP10K)
266
+ self.G += (B.T @ B).astype(np.float64) # sgemm within a chunk, float64 across chunks
267
+ self.s += B.sum(0, dtype=np.float64)
268
+ self.n += B.shape[0]
269
+ return self
270
+
271
+ def __add__(self, other: "Gram") -> "Gram":
272
+ g = Gram(len(self.s))
273
+ g.G, g.s, g.n = self.G + other.G, self.s + other.s, self.n + other.n
274
+ return g
275
+
276
+ def pca(self, n_comp: int = EN_PCS) -> tuple[np.ndarray, np.ndarray]:
277
+ from scipy.linalg import eigh
278
+ p = len(self.s)
279
+ n_comp = int(min(n_comp, p, self.n - 1))
280
+ mu = self.s / self.n
281
+ C = (self.G - self.n * np.outer(mu, mu)) / (self.n - 1)
282
+ w, V = eigh(C, subset_by_index=[p - n_comp, p - 1])
283
+ return mu, np.ascontiguousarray(V[:, ::-1].T) # components x genes, descending variance
284
+
285
+
286
+ def embed(L: sp.csr_matrix, mu: np.ndarray, comps: np.ndarray, chunk: int = EN_CHUNK) -> np.ndarray:
287
+ """(x - mu) @ comps.T for sparse features x (dense row chunks, float64 BLAS)."""
288
+ out = np.empty((L.shape[0], comps.shape[0]))
289
+ for a in range(0, L.shape[0], chunk):
290
+ out[a:a + chunk] = (L[a:a + chunk].toarray().astype(np.float64) - mu) @ comps.T
291
+ return out
292
+
293
+
294
+ def dif_sc(a: np.ndarray, b: np.ndarray) -> dict:
295
+ """scSemiProfiler eq. 17 with K = 1: mean over the cells of both samples of the distance to the nearest cell of the
296
+ other sample. 'sq' = squared L2 (their code: faiss IndexFlatL2), 'l2' = L2 (their text)."""
297
+ da, _ = sqdist_min(a, b)
298
+ db, _ = sqdist_min(b, a)
299
+ n = len(a) + len(b)
300
+ return {"sq": float((da.sum() + db.sum()) / n), "l2": float((np.sqrt(da).sum() + np.sqrt(db).sum()) / n)}
301
+
302
+
303
+ def lower_bound(Z: np.ndarray, rng: np.random.Generator, max_queries: int | None) -> dict:
304
+ """LB: random half split of the whole PCA matrix (real + generated), symmetric 1-NN (their code: shuffle, first
305
+ n//2 rows vs the rest). With max_queries, each direction averages max_queries random query cells of one half
306
+ against the complete other half (an unbiased estimate of the same mean)."""
307
+ perm = rng.permutation(len(Z))
308
+ h = len(Z) // 2
309
+ A, B = Z[perm[:h]], Z[perm[h:]]
310
+ qa = A if (max_queries is None or len(A) <= max_queries) else A[np.sort(rng.choice(len(A), max_queries, replace=False))]
311
+ qb = B if (max_queries is None or len(B) <= max_queries) else B[np.sort(rng.choice(len(B), max_queries, replace=False))]
312
+ da, _ = sqdist_min(qa, B)
313
+ db, _ = sqdist_min(qb, A)
314
+ exact = len(qa) == len(A) and len(qb) == len(B)
315
+ if exact: # their arithmetic: mean over the concatenated distances of both directions
316
+ sq = float((da.sum() + db.sum()) / (len(da) + len(db)))
317
+ l2 = float((np.sqrt(da).sum() + np.sqrt(db).sum()) / (len(da) + len(db)))
318
+ else: # same weights as the exact concatenation (|A| and |B| cells), each direction estimated
319
+ wa, wb = len(A) / (len(A) + len(B)), len(B) / (len(A) + len(B))
320
+ sq = float(wa * da.mean() + wb * db.mean())
321
+ l2 = float(wa * np.sqrt(da).mean() + wb * np.sqrt(db).mean())
322
+ return {"sq": sq, "l2": l2, "exact": exact, "n_queries": [int(len(qa)), int(len(qb))], "n_half": [int(len(A)), int(len(B))]}
323
+
324
+
325
+ def en_from_embeddings(gts: list, semis: list, rng: np.random.Generator, *, lb_max_queries: int | None,
326
+ Z_all: np.ndarray) -> dict:
327
+ """E_N for one arm from per-sample embeddings (PCA already fitted on real + generated together).
328
+ UB: per sample i a uniformly random partner j != i (real cells of both), Dif averaged over samples.
329
+ Dif_i: real vs generated of sample i. E_N = (mean_i Dif_i - LB) / (UB - LB) (eq. 18); per sample (Dif_i - LB) / (UB - LB)."""
330
+ P = len(gts)
331
+ lb = lower_bound(Z_all, rng, lb_max_queries)
332
+ partner = (np.arange(P) + rng.integers(1, P, size=P)) % P if P > 1 else np.zeros(P, int)
333
+ ub_i = [dif_sc(gts[i], gts[partner[i]]) for i in range(P)]
334
+ dif_i = [dif_sc(gts[i], semis[i]) for i in range(P)]
335
+ out = {"lb": lb, "partner": partner.tolist(), "per_sample": []}
336
+ for d in ("sq", "l2"):
337
+ ub = float(np.mean([u[d] for u in ub_i]))
338
+ dif = np.asarray([x[d] for x in dif_i])
339
+ out[d] = {"lb": lb[d], "ub": ub, "dif_mean": float(dif.mean()), "en": float((dif.mean() - lb[d]) / (ub - lb[d])),
340
+ "en_i": ((dif - lb[d]) / (ub - lb[d])).tolist(), "dif_i": dif.tolist()}
341
+ return out
342
+
343
+
344
+ def get_error_legacy(gts: list, semis: list, representatives: list, cluster_labels: list, n_comp: int = EN_PCS) -> dict:
345
+ """Line-by-line re-statement of scSemiProfiler utils.get_error for one round (global np.random state, sklearn PCA,
346
+ self-pairing allowed in the UB, representatives at LB, squared L2). Only for the equivalence test."""
347
+ from sklearn.decomposition import PCA
348
+ P = len(gts)
349
+ X = np.concatenate([np.concatenate(gts, 0), np.concatenate(semis, 0)], 0)
350
+ Xr = PCA(n_components=n_comp).fit_transform(X)
351
+ xg, xs, off = [], [], 0
352
+ for g in gts:
353
+ xg.append(Xr[off:off + len(g)])
354
+ off += len(g)
355
+ for s in semis:
356
+ xs.append(Xr[off:off + len(s)])
357
+ off += len(s)
358
+ lbgt = Xr.copy()
359
+ np.random.shuffle(lbgt)
360
+ h = lbgt.shape[0] // 2
361
+ a, b = lbgt[:h], lbgt[h:]
362
+ da, _ = sqdist_min(a, b)
363
+ db, _ = sqdist_min(b, a)
364
+ lb = float(np.r_[da, db].mean())
365
+ ubs = []
366
+ for i in range(P):
367
+ r = np.random.randint(0, P)
368
+ ubs.append(dif_sc(xg[i], xg[r])["sq"])
369
+ ub = float(np.mean(ubs))
370
+ semi = [lb if i in representatives else dif_sc(xg[i], xs[i])["sq"] for i in range(P)]
371
+ naive = [lb if i in representatives else dif_sc(xg[i], xg[representatives[cluster_labels[i]]])["sq"] for i in range(P)]
372
+ return {"upperbound": ub, "lowerbound": lb, "semierror": float(np.mean(semi)), "naiveerror": float(np.mean(naive)),
373
+ "en_semi": (float(np.mean(semi)) - lb) / (ub - lb)}
374
+
375
+
376
+ # =========================================================================== unit inputs
377
+ def sha256(path: Path) -> str:
378
+ h = hashlib.sha256()
379
+ with open(path, "rb") as fh:
380
+ for block in iter(lambda: fh.read(1 << 24), b""):
381
+ h.update(block)
382
+ return h.hexdigest()
383
+
384
+
385
+ def free_gib(path: Path) -> float:
386
+ st = os.statvfs(path)
387
+ return st.f_bavail * st.f_frsize / 2**30
388
+
389
+
390
+ def resolve_npz(path: Path, want_sha: str, fetch_root: Path, fetched: list) -> Path:
391
+ """The scored NPZ: the local file if present, else a sha-checked copy from server_2 (same path) under fetch_root,
392
+ with its receipt (.log) next to it so score_ft.open_arm can check output_sha256."""
393
+ path = Path(path)
394
+ if path.is_file():
395
+ return path
396
+ rel = path.relative_to(TASK)
397
+ dst = fetch_root / rel
398
+ marker = path.with_suffix(".moved")
399
+ if dst.is_file() and dst.with_suffix(".log").is_file():
400
+ if sha256(dst) == want_sha:
401
+ return dst
402
+ dst.unlink()
403
+ size = int(subprocess.run(["ssh", "-n", REMOTE, f"stat -c %s '{path}'"], capture_output=True, text=True,
404
+ check=True).stdout.strip())
405
+ need = size / 2**30 + MIN_FREE_GIB
406
+ if free_gib(fetch_root) < need:
407
+ raise SystemExit(f"disk: {free_gib(fetch_root):.1f} GiB free < {need:.1f} GiB needed to fetch {path}")
408
+ dst.parent.mkdir(parents=True, exist_ok=True)
409
+ log(f"fetching {rel} ({size / 2**30:.2f} GiB) from {REMOTE}")
410
+ subprocess.run(["rsync", "-a", "--bwlimit=200000", f"{REMOTE}:{path}", str(dst)], check=True)
411
+ rec = path.with_suffix(".log")
412
+ if rec.is_file():
413
+ shutil.copy2(rec, dst.with_suffix(".log"))
414
+ else:
415
+ subprocess.run(["rsync", "-a", f"{REMOTE}:{rec}", str(dst.with_suffix(".log"))], check=True)
416
+ fetched.append(dst)
417
+ got = sha256(dst)
418
+ if got != want_sha:
419
+ raise SystemExit(f"{dst}: sha {got[:12]} differs from the scored NPZ sha {want_sha[:12]}")
420
+ if marker.is_file():
421
+ txt = marker.read_text()
422
+ if f"sha {want_sha[:12]}" not in txt:
423
+ raise SystemExit(f"{marker}: marker sha differs ({txt.strip()})")
424
+ return dst
425
+
426
+
427
+ def unit_calls(design: str, ds: str, draw: int | None) -> list[tuple[Path, tuple]]:
428
+ if design == "fewshot":
429
+ base = SCORES / ds / "fewshot_n5"
430
+ return [(base / f"draw{draw}", ("zs_raw", "zs_cal", "lora5", "zs_pseudo")), (base / f"draw{draw}_scsemi5", ("scsemi5",))]
431
+ if design == "pooled":
432
+ return [(SCORES / ds / "pooled", POOLED_ARMS)]
433
+ if design == "scored":
434
+ return [(SCORED["dir"], SCORED["arms"])]
435
+ raise ValueError(design)
436
+
437
+
438
+ def unit_dir(design: str, ds: str, draw: int | None) -> Path:
439
+ if design == "scored":
440
+ return OUT_ROOT / ds / SCORED["unit"]
441
+ return OUT_ROOT / ds / (f"fewshot_n5/draw{draw}" if design == "fewshot" else "pooled")
442
+
443
+
444
+ def observed_cells(spec, ref: dict, man: dict, donors: np.ndarray, cache: dict) -> tuple[list, dict]:
445
+ """All observed QC cells of the scored samples on the scoring genes (counts), per sample in the reference's
446
+ canonical cell order, from the same files the reference was built from (inputs sha-checked against
447
+ reference_manifest.json). cache: per dataset, reused by the draws of one process."""
448
+ if spec.name not in cache:
449
+ cache.clear()
450
+ cache[spec.name] = _observed_all(spec, ref, man)
451
+ X, srow, sid, inputs = cache[spec.name]
452
+ out = []
453
+ for d in donors:
454
+ out.append(X[np.flatnonzero(srow == int(np.flatnonzero(sid == d)[0]))].tocsr())
455
+ n = np.asarray([o.shape[0] for o in out])
456
+ ref_n = ref["n_cells"][[int(np.flatnonzero(ref["donors"].astype(str) == d)[0]) for d in donors]]
457
+ if not np.array_equal(n, ref_n):
458
+ raise SystemExit("observed cell counts per sample differ from the reference")
459
+ return out, {"inputs_sha256": inputs, "n_cells_total": int(n.sum())}
460
+
461
+
462
+ def _observed_all(spec, ref: dict, man: dict):
463
+ feat = F.load_features(spec.features)
464
+ if feat["sha256"] != man["features"]["sha256"]:
465
+ raise SystemExit("features sha differs from the reference's")
466
+ gs = F.gene_sets(feat)
467
+ if not np.array_equal(gs["score_ids"], ref["score_ids"].astype(str)):
468
+ raise SystemExit("scoring genes differ from the reference")
469
+ cells = F.load_cells_datadir(spec, gs)
470
+ if cells is None or cells["inputs_sha256"] != man["cells"]["inputs_sha256"]:
471
+ raise SystemExit("observed cell files differ from the ones the reference was built from")
472
+ keys, _ = F.cell_keys(cells["table"].reset_index(drop=True))
473
+ srow = np.asarray(cells["sample_row"])
474
+ order = np.lexsort((keys, srow)) # the reference's canonical order (F.build_reference)
475
+ X = cells["X"].tocsr()[order][:, gs["score_idx"]].tocsr().astype(np.float32)
476
+ return X, srow[order], feat["sample_ids"], cells["inputs_sha256"]
477
+
478
+
479
+ CODE_SHA256 = {str(p): sha256(p) for p in CODE_FILES} # at import = the code this process runs
480
+
481
+
482
+ # =========================================================================== one unit
483
+ def pair_embeddings(v: dict, R: sp.csr_matrix, r_d: np.ndarray, Q: sp.csr_matrix, q_d: np.ndarray,
484
+ zr_raw: np.ndarray | None = None) -> dict:
485
+ """Real set R and query set Q in the scorer's PCA-50: 'raw' = SB.project; 'dm' = score_ft.depth_matched's own
486
+ steps (SB.depth_match of the pair with a fresh rng(DEPTH_SEED), real set in the 'R1' slot, then SB.project),
487
+ returning the embeddings instead of only their precision/coverage. zr_raw: the view's fitted z1 for R = R1."""
488
+ names = v["donors"]
489
+ thinned, _ = F.SB.depth_match({"R1": R, "Q": Q}, {"R1": names[r_d], "Q": names[q_d]}, list(names),
490
+ np.random.default_rng(F.DEPTH_SEED))
491
+ return {"raw": (zr_raw if zr_raw is not None else F.SB.project(R, v["mean"], v["comps"]),
492
+ F.SB.project(Q, v["mean"], v["comps"])),
493
+ "dm": (F.SB.project(thinned["R1"], v["mean"], v["comps"]), F.SB.project(thinned["Q"], v["mean"], v["comps"]))}
494
+
495
+
496
+ def per_donor_pc(r1_d, q_d, S_, res) -> tuple:
497
+ nq, n1 = np.bincount(q_d, minlength=S_), np.bincount(r1_d, minlength=S_)
498
+ return (np.bincount(q_d, weights=res["inside"], minlength=S_) / nq,
499
+ np.bincount(r1_d, weights=res["covered"], minlength=S_) / n1)
500
+
501
+
502
+ def score_set(name: str, v: dict, Q: sp.csr_matrix, q_d: np.ndarray, sigma_m: float, n_jobs: int,
503
+ expect: dict | None, oos: tuple | None) -> tuple[list, pd.DataFrame, dict]:
504
+ """Families 1, 2, 4 for one query set (an arm's P/C subsample, or R2), raw and depth matched, real side = R1
505
+ (the scorer's space). oos = (R2 counts, R2 donor index, set name): families 1-2 again with R2 as the real side."""
506
+ S_ = v["donors"].size
507
+ E = pair_embeddings(v, v["R1"], v["r1_d"], Q, q_d, zr_raw=v["z1"])
508
+ rows, per, chk = [], {"donor": v["donors"], "set": name}, {}
509
+ for mode, (zr, zg) in E.items():
510
+ t0 = time.monotonic()
511
+ m = {"set": name, "real_side": "R1", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
512
+ for k in KS:
513
+ # k = 10 raw: the view's own radii (score_ft.arm_metrics); every other k / mode: radii recomputed on zr
514
+ res = F.SB.precision_coverage(zr, v["radius"], zg) if (k == F.K_NN and mode == "raw") else pc_at_k(zr, zg, k)
515
+ m[f"precision_k{k}"], m[f"coverage_k{k}"], m[f"density_k{k}"] = res["precision"], res["coverage"], res["density"]
516
+ m[f"expected_coverage_identical_k{k}"] = expected_coverage(len(zr), len(zg), k)
517
+ pp, pc = per_donor_pc(v["r1_d"], q_d, S_, res)
518
+ per[f"precision_k{k}_{mode}"], per[f"coverage_k{k}_{mode}"] = pp, pc
519
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
520
+ m["seconds"] = round(time.monotonic() - t0, 1)
521
+ rows.append(m)
522
+ log(f" {name} [R1 {mode}] P/C k10 {m['precision_k10']:.4f}/{m['coverage_k10']:.4f} k5 {m['precision_k5']:.4f}/"
523
+ f"{m['coverage_k5']:.4f} k3 {m['precision_k3']:.4f}/{m['coverage_k3']:.4f} | AUC knn {m['c2st_knn_auc']:.3f} "
524
+ f"rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
525
+ if oos is not None:
526
+ R2, r2_d, oname = oos
527
+ for mode, (zr, zg) in pair_embeddings(v, R2, r2_d, Q, q_d).items():
528
+ t0 = time.monotonic()
529
+ m = {"set": oname, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
530
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=n_jobs))
531
+ m["seconds"] = round(time.monotonic() - t0, 1)
532
+ rows.append(m)
533
+ log(f" {oname} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN {m['nn1_acc']:.3f} "
534
+ f"| MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
535
+ if expect is not None: # reproduction of the scorer's k = 10 values
536
+ for mode, key in (("raw", ""), ("dm", "_depth_matched")):
537
+ mm = next(r for r in rows if r["mode"] == mode)
538
+ for q in ("precision", "coverage"):
539
+ chk[f"{q}{key}"] = {"ours": mm[f"{q}_k10"], "scorer": expect[f"{q}{key}"],
540
+ "abs_diff": abs(mm[f"{q}_k10"] - expect[f"{q}{key}"])}
541
+ if "per_donor" in expect:
542
+ d = np.abs(per[f"{q}_k10_{mode}"] - expect["per_donor"][f"{q}{key}"])
543
+ chk[f"{q}{key}_per_donor_max_abs_diff"] = float(d.max())
544
+ return rows, pd.DataFrame(per), chk
545
+
546
+
547
+ def run_unit(design: str, ds: str, draw: int | None, a) -> None:
548
+ t_unit = time.monotonic()
549
+ spec = F.DATASETS[ds]
550
+ out = unit_dir(design, ds, draw)
551
+ if (out / "manifest.json").is_file() and not a.force:
552
+ log(f"{out} done already")
553
+ return
554
+ out.mkdir(parents=True, exist_ok=True)
555
+ lock = out / ".in_progress"
556
+ if lock.is_file(): # another process (other stream) is computing this unit: skip unless its pid is gone
557
+ pid = int(lock.read_text().split()[0])
558
+ if Path(f"/proc/{pid}").exists():
559
+ log(f"{out} is being computed by pid {pid}; skipped")
560
+ return
561
+ lock.write_text(f"{os.getpid()} {F.now()}\n")
562
+ try:
563
+ _run_unit(design, ds, draw, a, t_unit, spec, out)
564
+ finally:
565
+ lock.unlink(missing_ok=True)
566
+
567
+
568
+ def _run_unit(design: str, ds: str, draw: int | None, a, t_unit: float, spec, out: Path) -> None:
569
+ calls = unit_calls(design, ds, draw)
570
+ summ = {}
571
+ for cdir, arms in calls:
572
+ s = json.loads((cdir / "summary.json").read_text())
573
+ miss = [x for x in arms if x not in s["arms"]]
574
+ if miss:
575
+ raise SystemExit(f"{cdir}: arms {miss} not scored there")
576
+ summ[cdir] = s
577
+ first = summ[calls[0][0]]
578
+ donors = [str(x) for x in first["donors"]]
579
+ for cdir, s in summ.items():
580
+ if [str(x) for x in s["donors"]] != donors:
581
+ raise SystemExit(f"{cdir}: scored donors differ from {calls[0][0]}")
582
+ if s["reference"]["reference_sha256"] != first["reference"]["reference_sha256"]:
583
+ raise SystemExit(f"{cdir}: reference sha differs")
584
+ cache = F.CACHE_ROOT / ds
585
+ ref, man = F.load_reference(cache)
586
+ if man["reference_sha256"] != first["reference"]["reference_sha256"]:
587
+ raise SystemExit(f"{cache}: reference sha differs from the scored one")
588
+ log(f"{ds} {design} {'' if draw is None else f'draw{draw} '}: {len(donors)} scored samples; fitting the scorer's view")
589
+ v = S.make_view(ref, donors)
590
+ repro = {"unit": str(out), "pca": {"ours": v["pca"], "scorer": first["reference"]["pca"]},
591
+ "r2_control": {"ours": v["r2_control"], "scorer": first["reference"]["r2_control"]}, "arms": {}}
592
+ S_ = v["donors"].size
593
+ sigma_m = median_bandwidth(v["z1"])
594
+ log(f"bandwidth m (median pairwise distance of R1, PCA-50) = {sigma_m:.4f}")
595
+ rows, per_frames, en_rows, en_ps = [], [], [], []
596
+ fetched: list[Path] = []
597
+ fetch_root = Path(a.fetch_dir)
598
+
599
+ # ---------------- E_N inputs shared by all arms
600
+ rng_c = F.donor_rng
601
+ R1L = log1p_cp10k_sparse(v["R1"])
602
+ gram_r1 = Gram(R1L.shape[1]).add(R1L)
603
+ r1_split = [np.flatnonzero(v["r1_d"] == s) for s in range(S_)]
604
+ obs, obs_info = observed_cells(spec, ref, man, v["donors"], a.obs_cache)
605
+ # out-of-sample real sets from the scorer's donor-keyed permutation (F.reference_split): R1 = perm[:n],
606
+ # R2 = perm[n:2n] (both checked equal to reference.npz), R3 = perm[2n:3n] (fewer cells when the sample is small);
607
+ # the R2-vs-R3 control uses R2' = perm[n:n+m], m = min(n, |R3|), so both sides have the same size per sample.
608
+ r3_blocks, r2b_blocks, r3_d, r2b_d, oos_info = [], [], [], [], {"n_r3": [], "short_samples": []}
609
+ for k in range(S_):
610
+ nk, d = obs[k].shape[0], str(v["donors"][k])
611
+ a1, a2 = F.reference_split(nk, d)
612
+ if (obs[k][a1] != v["R1"][np.flatnonzero(v["r1_d"] == k)]).nnz or \
613
+ (obs[k][a2] != v["R2"][np.flatnonzero(v["r2_d"] == k)]).nnz:
614
+ raise SystemExit(f"{d}: R1 / R2 rebuilt from the observed cells differ from reference.npz")
615
+ perm = F.donor_rng(F.SUB_SEED, d).permutation(nk)
616
+ n = a1.size
617
+ r3 = np.sort(perm[2 * n:3 * n])
618
+ m_ = r3.size
619
+ if m_ < n:
620
+ oos_info["short_samples"].append({"sample": d, "n": int(n), "n_r3": int(m_)})
621
+ r3_blocks.append(obs[k][r3])
622
+ r2b_blocks.append(obs[k][np.sort(perm[n:n + m_])])
623
+ r3_d.append(np.full(m_, k))
624
+ r2b_d.append(np.full(m_, k))
625
+ oos_info["n_r3"].append(int(m_))
626
+ R3, R2b = sp.vstack(r3_blocks, format="csr"), sp.vstack(r2b_blocks, format="csr")
627
+ r3_d, r2b_d = np.concatenate(r3_d), np.concatenate(r2b_d)
628
+ log(f"observed cells: {obs_info['n_cells_total']} in {S_} samples; R1/R2 rebuilt = reference.npz; R3 {R3.shape[0]} "
629
+ f"cells ({len(oos_info['short_samples'])} samples with fewer than n)")
630
+ oos_r2 = (v["R2"], v["r2_d"])
631
+ if not a.no_en_all:
632
+ obsL = [log1p_cp10k_sparse(o) for o in obs]
633
+ gram_obs = Gram(R1L.shape[1])
634
+ for L in obsL:
635
+ gram_obs.add(L)
636
+ del obs
637
+
638
+ def en_unit(set_name: str, cellset: str, gts_L: list, semis_L: list, gram_real: Gram, n_rep_rows: int | None):
639
+ t0 = time.monotonic()
640
+ g = Gram(gts_L[0].shape[1])
641
+ for L in semis_L:
642
+ g.add(L)
643
+ mu, comps = (gram_real + g).pca(EN_PCS)
644
+ gts = [embed(L, mu, comps) for L in gts_L]
645
+ semis = [embed(L, mu, comps) for L in semis_L]
646
+ Z_all = np.vstack(gts + semis)
647
+ rng = np.random.default_rng([SEED, 17 if cellset == "pc" else 29])
648
+ res = en_from_embeddings(gts, semis, rng, Z_all=Z_all,
649
+ lb_max_queries=None if cellset == "pc" else EN_LB_MAX_QUERIES)
650
+ n_test = len(gts)
651
+ for d in ("sq", "l2"):
652
+ r = res[d]
653
+ en_rows.append({"set": set_name, "cellset": cellset, "distance": d, "n_samples": n_test,
654
+ "n_cells_real": int(sum(len(x) for x in gts)), "n_cells_gen": int(sum(len(x) for x in semis)),
655
+ "n_pcs": int(comps.shape[0]), "lb": r["lb"], "ub": r["ub"], "dif_mean": r["dif_mean"],
656
+ "en": r["en"], "lb_exact": res["lb"]["exact"], "lb_queries": res["lb"]["n_queries"],
657
+ "n_representative_rows": n_rep_rows,
658
+ "en_reps_at_lb": (r["en"] * n_test / (n_test + n_rep_rows)) if n_rep_rows else None,
659
+ "seconds": round(time.monotonic() - t0, 1)})
660
+ en_ps.append(pd.DataFrame({"set": set_name, "cellset": cellset, "distance": d, "donor": v["donors"],
661
+ "n_real": [len(x) for x in gts], "n_gen": [len(x) for x in semis],
662
+ "partner": v["donors"][res["partner"]], "dif": r["dif_i"], "en_i": r["en_i"]}))
663
+ log(f" {set_name} E_N[{cellset}] sq {res['sq']['en']:.4f} (LB {res['sq']['lb']:.3f} UB {res['sq']['ub']:.3f} "
664
+ f"Dif {res['sq']['dif_mean']:.3f}) l2 {res['l2']['en']:.4f} ({round(time.monotonic() - t0, 1)} s)")
665
+
666
+ # ---------------- control: R1 vs R2 (the scorer's own)
667
+ expect_r2 = {"precision": first["reference"]["r2_control"]["precision"],
668
+ "coverage": first["reference"]["r2_control"]["coverage"],
669
+ "precision_depth_matched": first["reference"]["r2_control"]["depth_matched"]["precision"],
670
+ "coverage_depth_matched": first["reference"]["r2_control"]["depth_matched"]["coverage"]}
671
+ r, p, chk = score_set(CONTROL, v, v["R2"], v["r2_d"], sigma_m, a.threads, expect_r2, oos=None)
672
+ rows += r
673
+ # out-of-sample control: R2' (real side) vs R3, families 1-2 only
674
+ for mode, (zr, zg) in pair_embeddings(v, R2b, r2b_d, R3, r3_d).items():
675
+ t0 = time.monotonic()
676
+ m = {"set": CONTROL_OOS, "real_side": "R2", "mode": mode, "n_real": int(len(zr)), "n_gen": int(len(zg))}
677
+ m.update(two_sample_block(zr, zg, sigma_m, n_jobs=a.threads))
678
+ m["seconds"] = round(time.monotonic() - t0, 1)
679
+ rows.append(m)
680
+ log(f" {CONTROL_OOS} [R2 {mode}] AUC knn {m['c2st_knn_auc']:.3f} rf {m['c2st_rf_auc']:.3f} | 1-NN "
681
+ f"{m['nn1_acc']:.3f} | MMD2 {m['mmd2_bw1']:.4f} ({m['seconds']} s)")
682
+ per_frames.append(p)
683
+ repro["arms"][CONTROL] = chk
684
+ R2L = log1p_cp10k_sparse(v["R2"])
685
+ en_unit(CONTROL, "pc", [R1L[i] for i in r1_split], [R2L[np.flatnonzero(v["r2_d"] == s)] for s in range(S_)],
686
+ gram_r1, None)
687
+ if not a.no_en_all:
688
+ A_, B_ = [], []
689
+ for s in range(S_):
690
+ perm = rng_c(SEED, v["donors"][s]).permutation(obsL[s].shape[0])
691
+ h = obsL[s].shape[0] // 2
692
+ A_.append(obsL[s][np.sort(perm[:h])])
693
+ B_.append(obsL[s][np.sort(perm[h:])])
694
+ # the PCA basis is the one of all observed cells (A and B together): gram_real = A-part, semis add the B-part
695
+ gA = Gram(R1L.shape[1])
696
+ for L in A_:
697
+ gA.add(L)
698
+ en_unit(CONTROL, "all", A_, B_, gA, None)
699
+ del A_, B_
700
+
701
+ # ---------------- arms
702
+ pcache = a.pcache # Poisson read-outs (scoring genes) by NPZ sha; zs_*_all are reused by later draws
703
+ n_rep_rows = None
704
+ if design == "fewshot":
705
+ dj = json.loads((TASK / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"][str(draw)]
706
+ n_rep_rows = int(dj["n_train_rows"])
707
+ panel_ids = ref["panel_ids"].astype(str)
708
+ for cdir, arms in calls:
709
+ s = summ[cdir]
710
+ per_csv = pd.read_csv(cdir / "per_donor.csv")
711
+ for name in arms:
712
+ t0 = time.monotonic()
713
+ pa = s["per_arm"][name]
714
+ path = resolve_npz(Path(pa["npz"]), pa["npz_sha256"], fetch_root, fetched)
715
+ arm = S.open_arm(name, path, panel_ids, allow_no_receipt=False)
716
+ if arm["sha256"] != pa["npz_sha256"] or not arm["receipt_verified"]:
717
+ raise SystemExit(f"{name}: NPZ sha / receipt check failed for {path}")
718
+ npos = {n: i for i, n in enumerate(arm["sample_ids"])}
719
+ rws = [np.flatnonzero(arm["bulk_index"] == npos[x]) for x in v["donors"]]
720
+ sel = np.concatenate(rws)
721
+ gen_d = np.repeat(np.arange(S_), [x.size for x in rws])
722
+ if arm["sha256"] not in pcache:
723
+ rates = np.ascontiguousarray(arm["d"]["generated_counts"], dtype=np.float32)
724
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096)
725
+ del rates
726
+ pcache[arm["sha256"]] = full[:, ref["score_idx"]].tocsr()
727
+ del full
728
+ arm["d"].close()
729
+ Xg = pcache[arm["sha256"]][sel].tocsr()
730
+ sub = np.concatenate([np.flatnonzero(gen_d == k)[F.generated_subsample(int((gen_d == k).sum()),
731
+ int(v["n_ref"][k]), v["donors"][k])]
732
+ for k in range(S_)])
733
+ Q, q_d = Xg[sub].tocsr(), gen_d[sub]
734
+ gc = pd.read_parquet(cdir / "arms" / name / "generated_cells.parquet", columns=["npz_row", "in_pc_subsample"])
735
+ same_rows = bool(np.array_equal(gc.npz_row.to_numpy(), sel)
736
+ and np.array_equal(np.flatnonzero(gc.in_pc_subsample.to_numpy()), np.sort(sub)))
737
+ if not same_rows:
738
+ raise SystemExit(f"{name}: scored rows / P/C subsample differ from {cdir}/arms/{name}/generated_cells.parquet")
739
+ pdn = per_csv[per_csv.arm == name].set_index("donor").loc[v["donors"]]
740
+ h = s["headline"][name]
741
+ expect = {"precision": h["precision"], "coverage": h["coverage"], "precision_depth_matched": h["precision_dm"],
742
+ "coverage_depth_matched": h["coverage_dm"],
743
+ "per_donor": {k: pdn[k].to_numpy() for k in ("precision", "coverage", "precision_depth_matched",
744
+ "coverage_depth_matched")}}
745
+ log(f"{name}: {path.name} sha {arm['sha256'][:12]} (receipt verified), {sel.size} scored cells, "
746
+ f"{sub.size} in the P/C subsample (same rows as the scorer)")
747
+ r, p, chk = score_set(name, v, Q, q_d, sigma_m, a.threads, expect, oos=(oos_r2[0], oos_r2[1], name))
748
+ chk["rows_and_subsample_equal_scorer"] = same_rows
749
+ chk["npz"] = {"path": str(path), "scored_path": pa["npz"], "sha256": arm["sha256"]}
750
+ rows += r
751
+ per_frames.append(p)
752
+ repro["arms"][name] = chk
753
+ QL = log1p_cp10k_sparse(Q)
754
+ en_unit(name, "pc", [R1L[i] for i in r1_split], [QL[np.flatnonzero(q_d == k)] for k in range(S_)], gram_r1,
755
+ n_rep_rows if name == "scsemi5" else None)
756
+ if not a.no_en_all:
757
+ XgL = log1p_cp10k_sparse(Xg)
758
+ en_unit(name, "all", obsL, [XgL[np.flatnonzero(gen_d == k)] for k in range(S_)], gram_obs,
759
+ n_rep_rows if name == "scsemi5" else None)
760
+ del XgL
761
+ log(f"{name} done in {time.monotonic() - t0:.0f} s")
762
+ if not (design == "fewshot" and name in ("zs_raw", "zs_pseudo")):
763
+ pcache.pop(arm["sha256"], None) # not reused by another unit
764
+ # ---------------- write
765
+ meta = {"dataset": ds, "design": design, "unit": "pooled" if draw is None else f"draw{draw}"}
766
+ if design == "scored":
767
+ meta["unit"] = SCORED["unit"]
768
+ met = pd.DataFrame(rows)
769
+ for k, x in reversed(list(meta.items())):
770
+ met.insert(0, k, x)
771
+ met.insert(3, "label", met["set"].map(ARM_LABEL))
772
+ met.to_csv(out / "metrics.csv", index=False)
773
+ perd = pd.concat(per_frames, ignore_index=True)
774
+ for k, x in reversed(list(meta.items())):
775
+ perd.insert(0, k, x)
776
+ perd.to_csv(out / "per_donor.csv", index=False)
777
+ en = pd.DataFrame(en_rows)
778
+ for k, x in reversed(list(meta.items())):
779
+ en.insert(0, k, x)
780
+ en.to_csv(out / "en.csv", index=False)
781
+ ep = pd.concat(en_ps, ignore_index=True)
782
+ for k, x in reversed(list(meta.items())):
783
+ ep.insert(0, k, x)
784
+ ep.to_csv(out / "en_per_sample.csv", index=False)
785
+ worst = max([c.get("abs_diff", 0.0) for arm in repro["arms"].values() for c in arm.values() if isinstance(c, dict)]
786
+ + [0.0])
787
+ repro["max_abs_diff_k10_pooled"] = worst
788
+ repro["oos_r3"] = oos_info
789
+ repro["pca_equal"] = repro["pca"]["ours"] == repro["pca"]["scorer"]
790
+ (out / "repro.json").write_text(json.dumps(repro, indent=1, default=float) + "\n")
791
+ code = CODE_SHA256 # hashed when the process started
792
+ manifest = {"schema": "paired_ft_extra_metrics.v1", **meta, "written_utc": F.now(), "command": sys.argv,
793
+ "threads": a.threads, "donors": list(map(str, v["donors"])), "n_samples": int(S_),
794
+ "calls": {str(c): {"arms": list(arms), "summary_sha256": sha256(c / "summary.json")} for c, arms in calls},
795
+ "reference_sha256": man["reference_sha256"], "bandwidth_m": sigma_m,
796
+ "params": {"seed": SEED, "ks": KS, "knn_c2st_k": KNN_C2ST_K, "rf_trees": RF_TREES, "cv_folds": CV_FOLDS,
797
+ "bw_multiples": BW_MULTIPLES, "bw_max_cells": BW_MAX_CELLS, "en_pcs": EN_PCS,
798
+ "en_lb_max_queries_all_cells": EN_LB_MAX_QUERIES, "en_all_cells": not a.no_en_all},
799
+ "n_representative_rows": n_rep_rows, "fetched_from_server2": [str(f) for f in fetched],
800
+ "code_sha256": code, "seconds": round(time.monotonic() - t_unit, 1),
801
+ "max_abs_diff_k10_pooled": worst}
802
+ (out / "manifest.json").write_text(json.dumps(manifest, indent=1, default=float) + "\n")
803
+ log(f"unit {meta['unit']} of {ds} written to {out} in {manifest['seconds']} s (k=10 max |diff| vs scorer {worst:.2e})")
804
+ for f in fetched:
805
+ if f.name.startswith("zs__raw_all") or f.name.startswith("zs__pseudo_all"):
806
+ continue # shared by the draws of the cohort; removed by main after the last draw
807
+ f.unlink(missing_ok=True)
808
+ f.with_suffix(".log").unlink(missing_ok=True)
809
+ log(f"removed fetched copy {f}")
810
+
811
+
812
+ # =========================================================================== collect
813
+ def collect() -> None:
814
+ """Tables and concatenated CSVs: tools/collect_extra_metrics.py (pandas only)."""
815
+ import collect_extra_metrics as C
816
+ C.main()
817
+
818
+
819
+ def parse(argv=None):
820
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
821
+ p.add_argument("--design", choices=["fewshot", "pooled", "scored"])
822
+ p.add_argument("--score-dir", default=None, help="--design scored: a score_ft.py output dir (summary.json)")
823
+ p.add_argument("--arms", default=None, help="--design scored: comma list of arms scored in --score-dir")
824
+ p.add_argument("--unit", default=None, help="--design scored: output sub-path under scores_extra/<dataset>/ "
825
+ "(e.g. scsemi_cv_20261002/pooled)")
826
+ p.add_argument("--dataset", choices=DATASETS)
827
+ p.add_argument("--draws", default="0,1,2,3,4")
828
+ p.add_argument("--threads", type=int, default=7)
829
+ p.add_argument("--fetch-dir", default=None, help="where server_2 NPZ copies go (default: scratch under scores_extra)")
830
+ p.add_argument("--no-en-all", action="store_true", help="skip the all-cells E_N (P/C-cell E_N is always computed)")
831
+ p.add_argument("--force", action="store_true", help="recompute units that already have a manifest")
832
+ p.add_argument("--collect", action="store_true")
833
+ return p.parse_args(argv)
834
+
835
+
836
+ def main(argv=None) -> int:
837
+ a = parse(argv)
838
+ if a.collect:
839
+ collect()
840
+ return 0
841
+ if not (1 <= a.threads <= 8):
842
+ raise SystemExit("--threads must be 1..8")
843
+ try:
844
+ from threadpoolctl import threadpool_limits
845
+ threadpool_limits(a.threads)
846
+ except ImportError:
847
+ pass
848
+ if a.design is None or a.dataset is None:
849
+ raise SystemExit("--design and --dataset are required (or --collect)")
850
+ a.fetch_dir = a.fetch_dir or str(OUT_ROOT / "_fetch_tmp")
851
+ Path(a.fetch_dir).mkdir(parents=True, exist_ok=True)
852
+ a.pcache, a.obs_cache = {}, {}
853
+ if a.design == "scored":
854
+ if not (a.score_dir and a.arms and a.unit):
855
+ raise SystemExit("--design scored needs --score-dir, --arms and --unit")
856
+ unit = Path(a.unit)
857
+ if unit.is_absolute() or ".." in unit.parts or unit.parts[0] in ("pooled", "fewshot_n5"):
858
+ raise SystemExit("--unit must be a new relative sub-path (not pooled/ or fewshot_n5/)")
859
+ SCORED.update({"dir": Path(a.score_dir).resolve(), "arms": tuple(x for x in a.arms.split(",") if x),
860
+ "unit": str(unit)})
861
+ run_unit("scored", a.dataset, None, a)
862
+ elif a.design == "pooled":
863
+ run_unit("pooled", a.dataset, None, a)
864
+ else:
865
+ for j in [int(x) for x in a.draws.split(",") if x.strip()]:
866
+ run_unit("fewshot", a.dataset, j, a)
867
+ shared = Path(a.fetch_dir) / "generated" / a.dataset / "fewshot_n5"
868
+ for f in list(shared.glob("zs__*_all.npz")) if shared.is_dir() else []:
869
+ f.unlink(missing_ok=True)
870
+ f.with_suffix(".log").unlink(missing_ok=True)
871
+ log(f"removed fetched copy {f}")
872
+ return 0
873
+
874
+
875
+ if __name__ == "__main__":
876
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261002T002920Z-deck-extra-metrics-scsemi-prep/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/finalize_scsemi_cv_budget.sh ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Post-run scoring of the 2026-10-02 scSemiProfiler runs (CPU only; run on the host that holds every fold NPZ of the arms;
3
+ # modelled on finalize_rankcal.sh, same tools, nothing existing is re-scored, re-pooled or overwritten):
4
+ # cv : scSemiProfiler 5-fold CV (representatives = LoRA real_lora train + inner-val rows) arm scsemi__raw
5
+ # compare with real_lora__raw in scores/<ds>/{fold<k>,pooled}/ (same donors)
6
+ # budget : scSemiProfiler equal pair budget (representatives = lora_n<n> train + inner-val rows), n in {5,10,20,40}
7
+ # arms scsemi_n<n>__raw; compare with lora_n<n>__raw in scores/<ds>/{fold<k>,pooled}/ (immicro, ye2026_sepsis)
8
+ # Steps: per fold, score the arms -> scores/<ds>/<sub>/fold<k>/ (score_arms.sh: same scorer, contrast arguments and
9
+ # CPU unit as score_fold.sh; same donors as scores/<ds>/fold<k>/);
10
+ # pool the five folds -> generated/<ds>/pooled_<sub>/ (pool_folds.py --arms --out: nothing existing re-pooled;
11
+ # the broadcast condition of an __raw arm is the folds' test_raw.npz);
12
+ # score all donors -> scores/<ds>/<sub>/pooled/ (same donors as scores/<ds>/pooled/; with a contrast, e.g. sepsis,
13
+ # score_ft.py also writes the top-50 DEG score, i.e. the metrics of scores/<ds>/pooled_deg/).
14
+ # Already-scored output dirs are skipped, so a rerun resumes. <sub> = scsemi_cv_20261002 | scsemi_budget_20261002.
15
+ # usage: finalize_scsemi_cv_budget.sh DATASET cv|budget
16
+ set -uo pipefail
17
+ T=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
18
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
19
+ ds=${1:?usage: finalize_scsemi_cv_budget.sh DATASET cv|budget}; exp=${2:?usage: finalize_scsemi_cv_budget.sh DATASET cv|budget}
20
+ case $exp in
21
+ cv) sub=scsemi_cv_20261002; arms=(scsemi__raw) ;;
22
+ budget) sub=scsemi_budget_20261002; arms=(scsemi_n5__raw scsemi_n10__raw scsemi_n20__raw scsemi_n40__raw)
23
+ [[ $ds == immicro || $ds == ye2026_sepsis ]] || { echo "budget arms exist for immicro and ye2026_sepsis only" >&2; exit 2; } ;;
24
+ *) echo "usage: finalize_scsemi_cv_budget.sh DATASET cv|budget" >&2; exit 2 ;;
25
+ esac
26
+ G=$T/generated/$ds; S=$T/scores/$ds/$sub
27
+ missing=0
28
+ for f in 0 1 2 3 4; do
29
+ for a in "${arms[@]}"; do
30
+ [[ -s $G/fold$f/$a.npz ]] || { echo "not here: $G/fold$f/$a.npz$([[ -f $G/fold$f/$a.moved ]] && echo ' (moved)')"; missing=1; }
31
+ v=$G/fold$f/$a.validation.json
32
+ [[ -s $v ]] && python3 -c "import json,sys;sys.exit(0 if json.load(open(sys.argv[1]))['passed'] else 1)" "$v" \
33
+ || { echo "no passing validation: $v"; missing=1; }
34
+ done
35
+ done
36
+ (( missing == 0 )) || { echo "ABORT: every fold NPZ of $ds/$exp must be here and validated ($(hostname -s))" >&2; exit 1; }
37
+ n_fail=0
38
+ for f in 0 1 2 3 4; do
39
+ bash "$T/tools/score_arms.sh" "$ds" "$G/fold$f" "$S/fold$f" "score-$ds-$sub-f$f" "${arms[@]}" || { n_fail=$((n_fail+1)); echo "score $ds $exp fold $f failed"; }
40
+ done
41
+ P=$G/pooled_$sub
42
+ csv=$(IFS=,; echo "${arms[*]}")
43
+ if [[ -s $P/POOL_MANIFEST.json ]]; then echo "$P pooled already"
44
+ else
45
+ until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 56 )); do sleep 120; done
46
+ bash "$T/tools/run_unit.sh" "pool-$ds-$sub" 4 "$PY" "$T/tools/pool_folds.py" "$ds" --arms "$csv" --out "$P" \
47
+ || { echo "pool $ds $exp failed"; exit 1; }
48
+ fi
49
+ bash "$T/tools/score_arms.sh" "$ds" "$P" "$S/pooled" "score-$ds-$sub-pooled" "${arms[@]}" || { n_fail=$((n_fail+1)); echo "pooled score failed"; }
50
+ echo "finalize_scsemi_cv_budget $ds $exp done $(date -Is) failed=$n_fail -> $S"
51
+ (( n_fail == 0 ))