junidude14 commited on
Commit
e2683a0
·
verified ·
1 Parent(s): f645c5c

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/figures/FIGURES.md ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Figures: paired bulk → single-cell fine-tuning benchmark
2
+
3
+ Generated by `figures/make_figures.py` on 2026-09-30 15:50. Do not edit by hand: the numbers below are filled in from the score files. Re-run the script after new scores arrive.
4
+
5
+ Every figure is PNG (300 dpi) + PDF, sized for one column (89 mm wide). Each panel's plotted numbers, with the score file they came from, are in `source_data/<figure>.csv` (column `panel`) and `source_data/<figure>/panel_<id>.csv`. Colours are the same in every figure (Okabe–Ito palette): zero-shot raw light blue, zero-shot paired calibration blue, scSemiProfiler orange, LoRA vermillion, sc-only fine-tune purple. Reference lines: dashed = zero-shot generation from the sc-derived pseudobulk; dotted = real-bulk broadcast; dash-dot = cohort-mean null.
6
+
7
+ **Metric definitions (all from `tools/score_ft.py`).**
8
+ - **Composition L1**: sum over six scANVI labels of |generated − observed| cell-type fraction, averaged over scored samples. Lower is better. The null is each sample's observed composition vs the mean of the other donors' samples (`comp_l1_obs_loo_null`).
9
+ - **Precision / coverage**: PCA-50, k = 10 nearest-neighbour balls on up to 150 observed reference cells per scored sample. They depend on which samples are scored, so arms are compared only inside one scoring call (one draw, or one pooled call).
10
+ - **Disease logFC r**: per cell type (T, B, monocyte, NK), Pearson r between the generated and observed case-vs-control log2 fold change of donor-averaged mean CP10K; the plotted value is the mean of the four r. **Real-bulk broadcast** = the same r for the input real bulk's own logFC, copied to every cell type.
11
+ - **Top-50 DEG**: per cell type, Welch test + BH on donor pseudobulk (log1p CPM); overlap of the observed and generated top-50 lists (FDR < 0.05, ranked by |logFC|), summed over T/B/Mono/NK/DC (maximum 250; Giroux 123, because some observed top lists hold fewer than 50 significant genes).
12
+ - **Across-donor fraction r**: Pearson r across scored samples of generated vs observed fraction of one cell type (from `per_donor.csv`).
13
+
14
+ ## Fig. 1 — Few-pair scenario (`fig1_fewpair`)
15
+
16
+ **Plotted.** Rows a–e: composition L1, coverage, precision, disease logFC r, top-50 DEG. Columns: the five datasets. Each draw fine-tunes on 5 training donors (all their pairs) and scores every other usable sample (n under each dataset name = scored samples per draw). Arms: zero-shot on raw real bulk; zero-shot with paired calibration fitted on the same 5 pairs; scSemiProfiler with the same 5 pairs as representatives; LoRA on the same 5 pairs (fixed 3,000 steps, no inner validation; training rows per draw: ImMicro 5; Sepsis 5; Ji 7–9; Giroux 12–14; Imperial runs are on server_2 and not checked here). Bars = mean over draws; whiskers = SD; dots = single draws (5 draws). Reference segments are means over draws. In row e, Imperial has its own y-axis on the right because its DEG counts are about 5× larger. ImMicro has no case–control groups, so rows d–e are blank there. scSemiProfiler draws available: ImMicro 5/5, Sepsis 5/5, Ji 5/5, Giroux 5/5, Imperial 5/5. When fewer than 5 draws exist, the count is printed above its bar ("n=0" = none yet).
17
+
18
+ **Takeaway.** Five pairs are enough to fix most of the real-bulk shift in cell realism: LoRA-5 raises coverage over zero-shot calibration in 5/5 datasets. It raises the disease signal in every disease dataset (Sepsis 0.10 → 0.35, Ji 0.14 → 0.33, Giroux 0.24 → 0.33, Imperial 0.68 → 0.75). That is above the real-bulk broadcast (Sepsis 0.32, Ji 0.23, Giroux 0.54, Imperial 0.66) in Sepsis, Ji and Imperial, but not in Giroux. Composition improves significantly only in ImMicro (paired Wilcoxon over donor-draws, p 2.9e-24; Sepsis, Ji, Giroux and Imperial: p ≥ 0.11). In ImMicro, L1 goes 0.203 → 0.176. On the draws where both exist, LoRA-5 is better than scSemiProfiler-5 in this many datasets (same draws only): Composition 5/5; Coverage 5/5; Precision 5/5; disease r 2/4; Top-50 4/4. This sentence is computed by the script; rewrite it by hand once all 25 draws are in.
19
+
20
+ ## Fig. 2 — Five-fold CV, pooled (`fig2_fivefold`)
21
+
22
+ **Plotted.** Same rows as Fig. 1. Each sample is scored once, by the fold model that never trained on it, in one pooled scoring call per dataset (n under each name = scored samples). Arms: zero-shot with paired calibration (α fitted on the fold's training donors); sc-only fine-tune (full model on the training donors' sc pseudobulk, no real bulk) with paired-calibrated input; LoRA fine-tuned on all training donors' real bulk → cells (early stopping on inner-validation donors). One value per arm, so no error bars. Sepsis DEG comes from `scores/ye2026_sepsis/pooled_deg/`. The Ji column is shaded: its bulk is whole blood, not PBMC.
23
+
24
+ **Takeaway.** With all training pairs, LoRA has the highest coverage of the three arms in 5/5 datasets and the highest disease signal in 4/4 disease datasets. On Ji whole-blood bulk the sc-only model fails (coverage 0.11, disease r 0.25) while LoRA reaches coverage 0.86 and r 0.48: the paired bulk is what teaches the whole-blood → PBMC map. Composition improves significantly over zero-shot calibration only in ImMicro and Imperial (ImMicro L1 0.199 → 0.162, p 1.9e-07; Imperial L1 0.494 → 0.376, p 7.0e-11; paired Wilcoxon over scored samples). Zero-shot generation from the sc pseudobulk, which real-bulk users do not have, is still better on composition in Sepsis, Ji and Imperial; LoRA matches or beats it in ImMicro and Giroux.
25
+
26
+ ## Fig. 3 — LoRA learning curve (`fig3_learning_curve`)
27
+
28
+ **Plotted.** ImMicro (left) and sepsis (right), pooled 5-fold scoring (n = 107 and 82 samples). x = training pairs per fold: 0 = zero-shot with paired calibration; 5, 10, 20, 40 = nested stratified subsets (one subset per fold); all = every training donor (78–79 ImMicro, 58–59 sepsis). Inner-validation donors (7–8 per fold, from RUN.json) are outside every subset. Rows: composition L1; coverage; ImMicro across-donor NK fraction r / sepsis disease logFC r; sepsis top-50 DEG (from `pooled_deg`); selected early-stopping step per fold (dots; bar = median; dashed line = 20,000-step cap), from `runs/<ds>/fold<k>/<arm>/RUN.json`. One pooled value per point, so no error bars.
29
+
30
+ **Takeaway.** Five pairs already remove most of the systematic shift: coverage goes 0.53 → 0.84 (ImMicro) and 0.43 → 0.77 (sepsis). Donor-level and disease signals keep improving with more pairs: ImMicro NK r 0.20 → 0.40 → 0.56 → 0.70 → 0.70; sepsis logFC r 0.29 → 0.42 → 0.37 → 0.48 → 0.53, above the broadcast (0.32) from 10 pairs on. Sepsis DEG reaches the broadcast level (21) only from 40 pairs on. With 5 pairs early stopping lands at 2,000–3,000 steps (sepsis) and 2,750–5,000 (ImMicro); ImMicro runs with 20+ pairs mostly hit the cap (4/5 folds at 20 pairs, 5/5 at 40).
31
+
32
+ ## Supp. Fig. S1 — Per-cell-type disease signal (`figS1_celltype_contrast`)
33
+
34
+ **Plotted.** For each disease dataset (rows) and setting (left: 5 pairs, mean ± SD over 5 draws; right: all training pairs, 5-fold pooled): the per-cell-type logFC r (T, B, Mono, NK) of zero-shot with paired calibration, LoRA, and the real-bulk broadcast. Statistic `mean_cp10k` from `contrast.csv`. Group sizes (pooled, case vs control): sepsis 61 vs 21, Ji 18 vs 15, Giroux 11 vs 13, Imperial 113 vs 34 samples.
35
+
36
+ **Takeaway.** With all pairs, LoRA beats the broadcast in every cell type in Sepsis, Ji and Imperial. The exception: in Giroux LoRA wins only T. There the case-control difference is shared across cell types, so the bulk logFC alone already fits each type well. The largest gain over the broadcast is in Sepsis T (+0.37), Ji Mono (+0.39), Giroux T (+0.08), Imperial T (+0.27). With 5 pairs the per-type r varies between draws; the mean SD over cell types is largest in Sepsis (0.17; Ji 0.11, Giroux 0.08, Imperial 0.03).
37
+
38
+ ## Supp. Fig. S2 — K augmentation gives no gain (`figS2_k_augmentation`)
39
+
40
+ **Plotted.** ImMicro and sepsis, pooled 5-fold scoring. Arms: plain LoRA (real bulk at K = 1000); LoRA where each training cell also sees its donor's real bulk at K ∈ {250, 500, 1000, 2000, 4000}; LoRA where half of each batch is a pretraining-style recipe. Panels a–b: composition L1, precision, coverage (p = paired Wilcoxon of per-sample L1 vs plain LoRA). Panels c–d: per-type across-donor fraction r (ImMicro) or disease logFC r (sepsis). Panel f: sepsis top-50 DEG with the real-bulk broadcast (dotted); panel e is blank (ImMicro has no contrast). One pooled value per bar.
41
+
42
+ **Takeaway.** Neither augmentation helps. Multi-K is slightly worse on ImMicro composition (ΔL1 +0.006, p 0.04); every other difference is within noise (p ≥ 0.70). The protocol keeps a single K = 1000.
43
+
44
+ ## Status
45
+
46
+ - scSemiProfiler-5 draws used: ImMicro 5/5, Sepsis 5/5, Ji 5/5, Giroux 5/5, Imperial 5/5.
47
+ - Rejected scSemiProfiler outputs (not plotted): none.
48
+ - Consistency checks vs `scores/<ds>/fewshot_n5/aggregate.json`: all match.
49
+
50
+ ## Re-run
51
+
52
+ ```bash
53
+ cd /home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927
54
+ python3 figures/make_figures.py
55
+ ```
56
+ CPU only; about a minute. It re-reads every score file, so new `scores/<ds>/fewshot_n5/draw<j>_scsemi5/` directories are picked up automatically. A scSemiProfiler output is used only if its donor set and reference equal those of the same draw's other arms and its receipt is verified; otherwise it is listed as rejected above.
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/figures/fig1_fewpair.pdf ADDED
Binary file (88.5 kB). View file
 
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/README.md ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - Representatives are every training donor of fold k, including inner-validation donors; targets are fold k's rows.
296
+ - The input builder, wrapper, exporter and queue already support `cv|DATASET|FOLD`.
297
+ - Output: `generated/<ds>/fold<k>/scsemi__raw.npz`.
298
+
299
+ **Cost.** Pretraining runs once per training row, so it dominates: the targets are only 1/5 of the rows. Same timing basis as above:
300
+
301
+ | dataset (5 folds) | representatives per fold | pretrain | targets | total GPU | largest prepared fold |
302
+ |---|---:|---:|---:|---:|---:|
303
+ | ji2025_chili | 25–27 | 7.3 h | 0.3–0.9 h | 7.7–8.2 h | 9 GiB |
304
+ | giroux2022 | 18–21 | 14.8 h | 0.2–1.7 h | 15.1–16.6 h | 29 GiB |
305
+ | ye2026_sepsis | 65–66 | 34.5 h | 0.8–4.0 h | 35.4–38.6 h | 53 GiB |
306
+ | immicro | 85–86 | 23.2 h | 1.1–2.7 h | 24.3–25.9 h | 25 GiB |
307
+ | **server_1 total** | | | | **82–89 h** | |
308
+ | imperial_eskd (server_2) | 110–133 | 30.4 h | 1.6–3.6 h | 32–34 h | 39 GiB |
309
+
310
+ That is about 3× the few-pair campaign. The memory note below applies to every fold, because every large training row becomes a representative.
311
+
312
+ ## Files
313
+
314
+ - `tools/prepare_draw_inputs.py`: builds the split inputs (bulk.h5ad, rep_sc.h5ad, manifest).
315
+ - `tools/run_scsemi_paired.py`: the upstream wrapper (prepare / pretrain / infer / status).
316
+ - `tools/export_npz.py`: the adapter.
317
+ - `tools/validate_export.py`: independent validation of an exported NPZ.
318
+ - `tools/run_queue_scsemi.sh`: the queue runner.
319
+ - `tools/make_queues.sh`: writes the queue files.
320
+ - `tools/cpu_unit.sh`: CPU systemd unit, ≤ 6 threads, MemoryMax ≤ 16G, 32 GiB floor.
321
+ - `tools/lean_cellgraph.py`: output-identical `fast_cellgraph`.
322
+ - `tools/verify_lean_cellgraph.py`: function-level check of the lean cell graph.
323
+ - `tools/compare_prepared.py`: file-by-file comparison of prepared splits.
324
+ - `tools/compat_patch_20260928.py`: the size-1 trailing batch fix.
325
+ - `tools/scan_trailing_batch.py`: scans every representative for the size-1 batch condition.
326
+ - `tools/compare_runs.py`: bitwise comparison of trained artefacts between two work dirs.
327
+ - `compat_migrations.json`: approved code transitions.
328
+ - `tools/build_geneset_assets.py`: builds the gene-set asset.
329
+ - `tools/prepare_env_server2.sh`: builds the server_2 environment.
330
+ - `genesets/`: the mapped GMT and its manifest.
331
+ - `vendor/`: a copy of the frozen pinned upstream, hash-verified.
332
+ - `work/`: per-split runs.
333
+ - `smoke/`: CPU smoke runs.
334
+ - `validation/`: bit-identity records.
335
+ - `logs/`: logs.
paper-releases/pbisc-diffusion/updates/20260930T065633Z-summary-deck-scsemi-final/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/build_archive_request.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Archive-maintenance request for the paired fine-tuning benchmark (PBISC-Diffusion paper, pbisc-diffusion).
3
+
4
+ Follows paper-release-20260928/maintenance/POLICY.md: every payload is listed explicitly (host, exact path, kind,
5
+ state); generated arrays are not payloads but inference locations with their receipts; work that is still running
6
+ (the scSemiProfiler baseline) is registered as running/planned locations only.
7
+
8
+ Payloads (completed): code, documents, figures and their source CSVs, score tables, paired-data manifests and
9
+ small data (features, pairs, folds, splits, cell metadata), the condition NPZs every sampler read, run receipts
10
+ (RUN.json / history.json, which carry every fine-tuned checkpoint's sha256), queues, and the recommended-protocol
11
+ LoRA checkpoints (all-training-donor LoRA per fold, and the 5-pair LoRA per draw) on both hosts.
12
+ Not uploaded (location/provenance only): other fine-tuned checkpoints (sha256 in their RUN.json), the per-cell
13
+ count arrays cells_panel6k.npz / cells_full.npz (sha256 in BUILD.json / MANIFEST.json; rebuilt from the datalake
14
+ processing outputs), generated NPZs.
15
+ usage: build_archive_request.py OUT.json
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import glob
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
27
+ DATASETS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
28
+
29
+
30
+ def files(patterns, root=T):
31
+ out = []
32
+ for p in patterns:
33
+ for f in sorted(glob.glob(str(root / p), recursive=True)):
34
+ q = Path(f)
35
+ if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and not q.name.endswith((".bak", ".pyc")) \
36
+ and ".bak_" not in q.name:
37
+ out.append(str(q))
38
+ return sorted(set(out))
39
+
40
+
41
+ def remote_files(patterns):
42
+ cmd = "cd %s && for p in %s; do ls -1d $p 2>/dev/null; done; true" % (T, " ".join(patterns))
43
+ res = subprocess.run(["ssh", "-n", "spark-0110", cmd], capture_output=True, text=True, check=True)
44
+ return sorted({str(T / l.strip()) for l in res.stdout.splitlines() if l.strip()})
45
+
46
+
47
+ def remote_json(path):
48
+ res = subprocess.run(["ssh", "-n", "spark-0110", f"cat '{path}'"], capture_output=True, text=True)
49
+ return json.loads(res.stdout) if res.returncode == 0 and res.stdout.strip() else None
50
+
51
+
52
+ def main(out: str) -> int:
53
+ assets = []
54
+
55
+ def add(paths, kind, host="server_1", state="completed"):
56
+ for p in paths:
57
+ assets.append({"host": host, "source": p, "kind": kind, "state": state})
58
+
59
+ add(files(["tools/*.py", "tools/*.sh", "tests/*.py", "figures/make_figures.py",
60
+ "scsemi/tools/*.py", "scsemi/tools/*.sh", "scsemi/tests/*.py"]), "code")
61
+ add(files(["README.md", "FEASIBILITY.md", "figures/FIGURES.md", "scsemi/README.md",
62
+ "data/*/QC_REPORT.md"]), "document")
63
+ add(files(["figures/*.png", "figures/*.pdf"]), "figure")
64
+ add(files(["figures/source_data/**/*.csv"]), "table")
65
+ add(files(["scores/*/*/summary.json", "scores/*/*/per_donor.csv", "scores/*/*/contrast.csv", "scores/*/*/README.md",
66
+ "scores/*/fewshot_n5/*/summary.json", "scores/*/fewshot_n5/*/per_donor.csv",
67
+ "scores/*/fewshot_n5/*/contrast.csv", "scores/*/fewshot_n5/*/README.md",
68
+ "scores/*/AGGREGATE.md", "scores/*/aggregate.json",
69
+ "scores/*/fewshot_n5/AGGREGATE.md", "scores/*/fewshot_n5/aggregate.json"]), "table")
70
+ add(files(["data/*/features.npz", "data/*/cells_obs.parquet", "data/*/fold*/alpha.npy",
71
+ "data/*/fewshot_n5/draw*/alpha.npy"]), "data")
72
+ add(files(["data/*/pairs.csv", "data/*/folds.csv", "data/*/samples.csv", "data/*/identity_*.csv",
73
+ "data/*/pairs_sensitivity_offday.csv", "data/*/MANIFEST.json", "data/*/PREPARE.json",
74
+ "data/*/BUILD.json", "data/*/cells_full.BUILD.json", "data/*/fewshot_n5/DRAWS.json",
75
+ "data/*/fewshot_n5/draw*/*.txt"]), "metadata")
76
+ add(files(["data/*/conditions_*.npz", "data/*/fold*/*.npz", "data/*/fewshot_n5/*.npz",
77
+ "data/*/fewshot_n5/draw*/*.npz"]), "condition")
78
+ add(files(["runs/**/RUN.json", "runs/**/history.json"]), "log")
79
+ # server_2 ran its own copies of the scSemiProfiler queues (some exist only there): keep them as the as-run record
80
+ subprocess.run(["rsync", "-a", f"spark-0110:{T}/scsemi/queues/", f"{T}/scsemi/queues/as_run_server2/",
81
+ "--include=server2_*.txt", "--exclude=*"], check=True)
82
+ add(files(["queues/*.txt", "scsemi/queues/*.txt", "scsemi/queues/as_run_server2/*.txt",
83
+ "scsemi/vendor/compatibility.patch",
84
+ "scsemi/vendor/source_manifest.json"]), "config")
85
+ # recommended protocol weights (LoRA merged into the base weights): server_1 datasets here, Imperial on server_2
86
+ add(files(["runs/*/fold*/real_lora/checkpoint_ft.pt", "runs/*/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint")
87
+ add(remote_files(["runs/imperial_eskd/fold*/real_lora/checkpoint_ft.pt",
88
+ "runs/imperial_eskd/fewshot_n5/draw*/lora/checkpoint_ft.pt"]), "checkpoint", host="server_2")
89
+ add(remote_files(["runs/imperial_eskd/*/*/RUN.json", "runs/imperial_eskd/*/*/history.json",
90
+ "runs/imperial_eskd/fewshot_n5/*/*/RUN.json", "runs/imperial_eskd/fewshot_n5/*/*/history.json"]),
91
+ "log", host="server_2")
92
+
93
+ # ---- inference locations (not payloads) ------------------------------------------------------------------------
94
+ locs = []
95
+
96
+ def receipt_fields(rec: dict | None) -> dict:
97
+ if not rec:
98
+ return {}
99
+ keep = {}
100
+ for k in ("output_sha256", "checkpoint", "checkpoint_sha256", "input_condition_path", "input_condition_sha256",
101
+ "condition_npz", "condition_sha256", "seed", "steps", "generated_counts_rows"):
102
+ if k in rec and not isinstance(rec[k], (dict, list)):
103
+ keep[k] = rec[k]
104
+ if "output_sha256" in keep:
105
+ keep["sha256"] = keep["output_sha256"]
106
+ return keep
107
+
108
+ def loc(host, npz, experiment, cohort, rec=None, state="completed"):
109
+ rpath = npz[:-4] + ".log"
110
+ item = {"host": host, "path": npz, "state": state, "experiment": experiment, "cohort": cohort,
111
+ "artifact_role": "inference_output"}
112
+ if state in ("completed", "final"):
113
+ item["receipt"] = rpath
114
+ item.update(receipt_fields(rec))
115
+ locs.append(item)
116
+
117
+ for ds in DATASETS:
118
+ # present on server_1
119
+ for npz in files([f"generated/{ds}/**/*.npz"]):
120
+ rel = Path(npz).relative_to(T / "generated" / ds)
121
+ rp = Path(npz[:-4] + ".log")
122
+ rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
123
+ if rec is None:
124
+ continue
125
+ loc("server_1", npz, f"paired_finetune_{rel.parts[0]}", ds, rec)
126
+ # moved to server_2 (sha-verified move; .moved marker kept on server_1)
127
+ for mk in files([f"generated/{ds}/**/*.moved"]):
128
+ npz = mk[:-6] + ".npz"
129
+ rp = Path(mk[:-6] + ".log")
130
+ rec = json.loads(rp.read_text()) if rp.is_file() and rp.stat().st_size else None
131
+ rel = Path(npz).relative_to(T / "generated" / ds)
132
+ item_state = "completed" if rec else "presence_only"
133
+ loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", ds, rec, state=item_state)
134
+ locs[-1]["move_marker_server_1"] = mk
135
+ # Imperial outputs live on server_2
136
+ for npz in remote_files(["generated/imperial_eskd/*/*.npz", "generated/imperial_eskd/fewshot_n5/*/*.npz",
137
+ "generated/imperial_eskd/pooled/*.npz"]):
138
+ rec = remote_json(npz[:-4] + ".log")
139
+ if rec is None:
140
+ continue
141
+ rel = Path(npz).relative_to(T / "generated" / "imperial_eskd")
142
+ loc("server_2", npz, f"paired_finetune_{rel.parts[0]}", "imperial_eskd", rec)
143
+ # scSemiProfiler draws of the other datasets that ran on server_2 (queues server2_*.txt)
144
+ for npz in remote_files([f"generated/{ds}/fewshot_n5/draw*/scsemi5__raw.npz" for ds in DATASETS
145
+ if ds != "imperial_eskd"]):
146
+ rec = remote_json(npz[:-4] + ".log")
147
+ if rec is None:
148
+ continue
149
+ rel = Path(npz).relative_to(T / "generated")
150
+ loc("server_2", npz, "paired_finetune_fewshot_n5", rel.parts[0], rec)
151
+ # scSemiProfiler baseline still running: register in-progress / planned draws by their future output path
152
+ done = {l["path"] for l in locs}
153
+ run_queues = [T / "scsemi" / "queues" / "server1_fewshot_d0first.txt"] + \
154
+ sorted((T / "scsemi" / "queues" / "as_run_server2").glob("server2_*.txt"))
155
+ for qf in run_queues:
156
+ host = "server_1" if qf.name.startswith("server1_") else "server_2"
157
+ for line in qf.read_text().splitlines():
158
+ if not line.startswith("fewshot|"):
159
+ continue
160
+ _, ds, j = line.split("|")[:3]
161
+ npz = str(T / "generated" / ds / "fewshot_n5" / f"draw{j}" / "scsemi5__raw.npz")
162
+ if npz in done:
163
+ continue
164
+ state = "planned"
165
+ locs.append({"host": host, "path": npz, "state": state, "experiment": "paired_finetune_fewshot_n5_scsemiprofiler",
166
+ "cohort": ds, "artifact_role": "inference_output",
167
+ "note": "scSemiProfiler 5-pair baseline queued or running on this host at request time"})
168
+ done.add(npz)
169
+ req = {
170
+ "project_id": "pbisc-diffusion",
171
+ "summary": (
172
+ "Within-dataset paired fine-tuning benchmark of the final 6k 1x E16 model (plans/paired_finetune_intradataset_20260927): "
173
+ "LoRA (recommended protocol), full and condition-encoder fine-tuning, sc-only control, LoRA learning curve, "
174
+ "K-augmentation null, 5-pair deployment scenario, on ImMicro, Ye 2026 sepsis, Imperial ESKD COVID, Giroux 2022 and "
175
+ "Ji 2025 (whole-blood bulk); scores (scANVI composition, precision/coverage, contrast logFC r, top-50 DEG), figures, "
176
+ "paired-data manifests, conditions, run receipts and the recommended-protocol LoRA checkpoints. The scSemiProfiler "
177
+ "5-pair baseline: every finished draw is included as score tables and a completed location; draws not yet "
178
+ "finished at request time (none on 2026-09-30: 25/25 done) are planned locations. Not uploaded: per-cell count "
179
+ "arrays and non-recommended fine-tuned checkpoints (sha256 recorded in BUILD/MANIFEST and RUN.json)."),
180
+ "assets": assets,
181
+ "inference_locations": locs,
182
+ }
183
+ Path(out).write_text(json.dumps(req, indent=1))
184
+ kinds = {}
185
+ for a in assets:
186
+ kinds[(a["host"], a["kind"])] = kinds.get((a["host"], a["kind"]), 0) + 1
187
+ print(json.dumps({"assets": len(assets), "by_host_kind": {f"{h}/{k}": v for (h, k), v in sorted(kinds.items())},
188
+ "locations": len(locs), "location_states": {s: sum(l["state"] == s for l in locs) for s in {l["state"] for l in locs}}},
189
+ indent=1))
190
+ return 0
191
+
192
+
193
+ if __name__ == "__main__":
194
+ sys.exit(main(sys.argv[1]))