junidude14 commited on
Commit
95009a3
·
verified ·
1 Parent(s): 4e12694

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/README.md ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Within-dataset fine-tuning of the final model on paired bulk + scRNA data
2
+
3
+ User decision (2026-09-27): release the pseudobulk-pretrained final model as something users fine-tune on their own paired bulk + scRNA data. Validate it inside each paired dataset: split donors, fine-tune on the training donors' real bulk → their cells, and test on held-out donors. Start with ImMicro and Ye 2026 sepsis, run the same way. Feasibility of other datasets: `FEASIBILITY.md`.
4
+
5
+ ## Setup
6
+
7
+ - **Base model:** `runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt` (sha 8c7cd0e8…), EMA weights. E16 is also the best-validation epoch (0.13691).
8
+ - **Data** (`data/<dataset>/`):
9
+ - `features.npz`: bulk and pseudobulk on the 20,097 axis, with measured masks.
10
+ - `cells_panel6k.npz`: retained cells on the 6k panel. Each row's cells sum exactly to its pseudobulk.
11
+ - **ImMicro:** 107 donors, 392,251 baseline cells. Built by `tools/build_immicro_cells.py`.
12
+ - **Sepsis:** 85 pairs, 82 pass identity checks, 610,713 cells. Built by the pairing agent; details in `data/ye2026_sepsis/QC_REPORT.md`. The GEX is 5′ even though GEO says 3′.
13
+ - **Folds** (`tools/prepare_dataset.py`):
14
+ - Donor-level 5-fold, stratified by group (ImMicro pool; sepsis clinical group).
15
+ - About 10 % of each fold's training donors are inner-validation, used only for early stopping.
16
+ - Identity-failed sepsis rows sit in fold −1 and are never used.
17
+ - **Conditions:**
18
+ - Fixed depth (K = 1000, one depth anchor), the published `build_realbulk_conditions.py` arithmetic.
19
+ - No test donor's single-cell depth or cell count enters its condition.
20
+ - The ImMicro raw and pseudo NPZs equal the published fixed ones bit for bit.
21
+ - Paired calibration α is fitted on each fold's training donors only.
22
+ - **Training** (`tools/ft_sdd.py`):
23
+ - Pretraining loss, bf16, AdamW, grad clip 5, EMA 0.999, donor-balanced batches of 256.
24
+ - Up to 20,000 steps. Inner-validation loss is checked every 250 steps and the best EMA state is kept.
25
+ - Modes: full (54.2 M trainable parameters), LoRA r = 16 (1.3 M, merged before saving), condition encoder only (9.5 M).
26
+ - Output checkpoints keep the base schema, so `scripts/sample_sdd_standalone.py` samples them unchanged.
27
+ - **Sampling:** test donors only, 1,500 cells each, seed 20260927, DDIM 50, EMA, Bernoulli read-out. GPU only through `tools/run_queue.sh` → `ml-run`.
28
+ - **Scoring** (`tools/score_ft.py`, `tools/score_fold.sh`):
29
+ - Frozen f01common scANVI six-type gate. Metrics: composition L1, precision/coverage (PCA-50, k = 10, reference = the scored donors' observed cells), pseudobulk r, donor recovery top-1.
30
+ - For sepsis, also per-cell-type sepsis-vs-control logFC r against observed and against bulk broadcast.
31
+ - Validated against the published ImMicro native arms: composition L1 and labels are identical.
32
+ - Precision/coverage depends on the reference draw and on how many donors are scored, so compare arms within a fold.
33
+ - **Giroux: sex-linked genes excluded from the disease metrics** (user decision 2026-10-01). Its moderate vs mild contrast is fully confounded with sex (scored subjects 4 F / 0 M vs 0 F / 5 M). Giroux logFC r, partial r, top-50 DEG and the broadcast baseline are reported from `scores_nosex/giroux2022/`, scored with `score_ft.py --exclude-genes data/sex_linked_genes/sex_linked_genes_exclude.csv` (196 genes: chrY non-PAR + X-inactivation escape genes of Tukiainen 2017; PAR genes kept) and the original frozen labels (`--reuse-labels`). Details: `scores_nosex/README.md`, `data/sex_linked_genes/README.md`.
34
+
35
+ ## ImMicro fold 0 pilot (22 test donors; real bulk input unless noted)
36
+
37
+ | arm | comp L1 ↓ | precision | coverage | pseudobulk r | donor top-1 | monocyte % (obs 18.5) |
38
+ |---|---:|---:|---:|---:|---:|---:|
39
+ | zero-shot raw | 0.484 | 0.910 | 0.423 | 0.892 | 0.05 | 37.0 |
40
+ | zero-shot paired cal (fold α) | 0.168 | 0.985 | 0.725 | 0.882 | 0.14 | 14.7 |
41
+ | zero-shot pseudobulk | 0.188 | 0.993 | 0.722 | 0.881 | 0.09 | 13.7 |
42
+ | FT condition encoder only | 0.204 | 0.979 | 0.728 | 0.892 | 0.14 | 13.0 |
43
+ | FT LoRA r = 16 | 0.153 | 0.992 | **0.915** | 0.901 | 0.18 | 14.8 |
44
+ | **FT full** | **0.147** | 0.987 | 0.841 | **0.912** | **0.32** | 14.7 |
45
+ | FT on pseudobulk (sc only), raw input | 0.426 | 0.725 | 0.257 | 0.929 | 0.18 | 23.4 |
46
+ | FT on pseudobulk (sc only), paired-cal input | 0.231 | 0.954 | 0.816 | 0.917 | 0.18 | 14.3 |
47
+
48
+ Leave-one-out composition null of the observed cells: 0.163. Chance donor top-1: 0.045.
49
+
50
+ Selected inner-validation loss (pretrained 0.10985):
51
+ - full 0.10071, still falling at the 20,000-step cap;
52
+ - LoRA 0.10127;
53
+ - condition encoder 0.10429.
54
+
55
+ **Reading (one fold, one seed):**
56
+ - Real-bulk fine-tuning beats every zero-shot arm, including the pseudobulk input.
57
+ - It also beats sc-only adaptation. The sc-only model with paired calibration reaches similar coverage (0.82), so coverage comes largely from adapting to the cohort. Composition and donor specificity, however, need the paired bulk: L1 0.147 vs 0.231, top-1 0.32 vs 0.18.
58
+ - LoRA and full are close: LoRA covers more of the observed cells, full is more donor-specific.
59
+ - The condition encoder alone captures about 60 % of full's inner-validation gain but does not beat zero-shot calibration, so it was dropped.
60
+
61
+ ## ImMicro, all five folds (107 donors, each scored by the fold model that never trained on it)
62
+
63
+ Per-fold scores, fold mean ± SD (`scores/immicro/AGGREGATE.md`):
64
+
65
+ | arm | comp L1 ↓ | precision | coverage | pseudobulk r |
66
+ |---|---:|---:|---:|---:|
67
+ | zero-shot raw | 0.454 ± 0.032 | 0.877 | 0.424 | 0.892 |
68
+ | zero-shot paired cal | 0.199 ± 0.029 | 0.976 | 0.725 | 0.880 |
69
+ | zero-shot pseudobulk | 0.204 ± 0.016 | 0.986 | 0.721 | 0.881 |
70
+ | FT LoRA r = 16 | 0.162 ± 0.017 | 0.989 | **0.919** | 0.900 |
71
+ | **FT full** | **0.157 ± 0.020** | 0.981 | 0.851 | **0.914** |
72
+ | sc-only FT, raw input | 0.444 ± 0.021 | 0.678 | 0.237 | 0.927 |
73
+ | sc-only FT, paired-cal input | 0.240 ± 0.015 | 0.955 | 0.829 | 0.917 |
74
+
75
+ **Donor-level composition L1, paired Wilcoxon over 107 donors** (FT full vs each arm):
76
+
77
+ | comparison | Δ L1 | FT full better in | p |
78
+ |---|---:|---:|---:|
79
+ | vs zero-shot paired cal | −0.042 | 68 % | 1e-7 |
80
+ | vs zero-shot pseudobulk | −0.048 | 74 % | 4e-8 |
81
+ | vs sc-only FT + paired cal | −0.083 | 91 % | 2e-16 |
82
+ | vs LoRA | −0.005 | 58 % | 0.14 |
83
+ | vs leave-one-out cohort-mean null (0.161) | −0.007 | 50 % | 0.64 |
84
+
85
+ **Across-donor correlation of generated vs observed cell-type fraction (T / B / Mono / NK):**
86
+ - FT full: 0.79 / 0.80 / 0.83 / 0.81
87
+ - zero-shot paired cal: 0.67 / 0.71 / 0.85 / 0.49
88
+ - zero-shot pseudobulk: 0.71 / 0.77 / 0.90 / 0.60
89
+
90
+ **Donor top-1:** 0.15 ± 0.10 for FT full vs 0.13 for zero-shot paired cal. The fold-0 value of 0.32 did not replicate.
91
+
92
+ **Pooled scoring** (`scores/immicro/pooled/`: one call over all 107 donors, reference = all 107 donors' observed cells, so absolute precision/coverage are lower than the per-fold values):
93
+
94
+ | arm | precision / coverage | depth-matched precision / coverage |
95
+ |---|---|---|
96
+ | FT LoRA | 0.924 / 0.784 | 0.961 / 0.962 |
97
+ | FT full | 0.890 / 0.695 | 0.946 / 0.950 |
98
+ | zero-shot paired cal | 0.905 / 0.527 | 0.944 / 0.769 |
99
+ | zero-shot pseudobulk | 0.936 / 0.524 | 0.965 / 0.741 |
100
+
101
+ **Reading:**
102
+ - Fine-tuning on real bulk removes the real-bulk bias.
103
+ - It beats the pseudobulk input, which was the zero-shot ceiling.
104
+ - It improves the across-donor ranking of T, B and NK fractions.
105
+ - It does not beat the observed cohort mean on per-donor composition L1. Healthy donors vary little, so that null is strong.
106
+ - Full is better on composition; LoRA gives wider coverage.
107
+
108
+ ## Sepsis, all five folds (82 identity-passed pairs: 61 sepsis, 21 controls; cross-fitted)
109
+
110
+ Pooled scoring over all 82 donors (`scores/ye2026_sepsis/pooled/`). The contrast is computed over all 61 vs 21 donors. The per-fold contrast (4–5 controls per fold) is too noisy to use.
111
+
112
+ | arm | comp L1 ↓ | precision | coverage | sepsis-vs-control logFC r (T / B / Mono / NK; mean) | r of bulk broadcast | partial r beyond broadcast |
113
+ |---|---:|---:|---:|---|---:|---:|
114
+ | zero-shot raw | 0.511 | 0.614 | 0.067 | −0.11 / 0.06 / 0.07 / −0.07; **−0.01** | 0.316 | −0.095 |
115
+ | zero-shot paired cal | 0.401 | 0.903 | 0.431 | 0.04 / 0.16 / 0.25 / 0.04; **0.12** | 0.278 | 0.039 |
116
+ | zero-shot pseudobulk (sc-derived input) | **0.233** | 0.915 | 0.480 | 0.55 / 0.50 / 0.40 / 0.43; **0.47** | 0.730 | 0.210 |
117
+ | FT LoRA | 0.362 | **0.926** | **0.829** | 0.63 / 0.57 / 0.58 / 0.34; **0.53** | 0.316 | **0.469** |
118
+ | **FT full** | 0.372 | 0.866 | 0.795 | 0.62 / 0.60 / 0.63 / 0.29; **0.53** | 0.316 | **0.468** |
119
+ | sc-only FT, raw input | 0.472 | 0.606 | 0.134 | 0.01 / 0.22 / 0.34 / 0.03; 0.15 | 0.316 | 0.038 |
120
+ | sc-only FT, paired-cal input | 0.360 | 0.863 | 0.726 | 0.25 / 0.32 / 0.52 / 0.10; 0.30 | 0.278 | 0.190 |
121
+
122
+ Leave-one-out composition null: 0.515. Observed monocyte %: 20.8; the FT arms generate 18.0–18.5 %.
123
+
124
+ Per-fold means are in `scores/ye2026_sepsis/AGGREGATE.md`. The fold-level ranking is the same: FT full L1 0.372 ± 0.083 vs zero-shot paired cal 0.404 ± 0.071.
125
+
126
+ **Donor-level composition L1** (paired Wilcoxon, 82 donors):
127
+
128
+ | comparison | Δ L1 | p |
129
+ |---|---:|---:|
130
+ | FT full vs zero-shot paired cal | −0.029 | 0.24 |
131
+ | FT LoRA vs zero-shot paired cal | −0.039 | 0.19 |
132
+ | FT full vs sc-only FT + cal | +0.011 | 0.80 |
133
+ | FT full vs zero-shot pseudobulk | +0.138 | 2e-7 |
134
+ | FT full vs null | −0.144 (better in 72 %) | 7e-6 |
135
+
136
+ **Across-donor fraction correlation (T / B / Mono / NK):**
137
+ - FT full: 0.68 / 0.79 / 0.60 / 0.68
138
+ - zero-shot paired cal: 0.64 / 0.71 / 0.60 / 0.59
139
+ - zero-shot pseudobulk: 0.91 / 0.95 / 0.97 / 0.80
140
+
141
+ **Reading:**
142
+ - **Disease signal is the sepsis result.**
143
+ - Fine-tuned models generate cells whose per-cell-type sepsis-vs-control logFC agrees with the observed cells at r 0.53. Zero-shot calibrated bulk gives 0.12.
144
+ - They beat the real-bulk broadcast baseline in every cell type (T 0.62 vs 0.26, B 0.60 vs 0.28, Mono 0.63 vs 0.55, NK 0.29 vs 0.19). In SLE the zero-shot model lost to broadcast.
145
+ - The partial r beyond broadcast is 0.47 (zero-shot 0.04).
146
+ - They also exceed zero-shot generation from the sc-derived pseudobulk (0.47).
147
+ - **The paired bulk matters.** sc-only fine-tuning with paired-cal input reaches 0.30.
148
+ - **Composition does not improve over zero-shot calibration** (n.s.) and stays far behind the pseudobulk input: the sepsis real bulk carries weak composition information, monocytes especially (r 0.60).
149
+ - **Coverage roughly doubles** (0.43 → 0.80–0.83).
150
+ - **Full and LoRA are equivalent here.** LoRA has the higher precision.
151
+
152
+ ## Sepsis fold 0 pilot (17 test donors: 12 sepsis, 5 controls; real bulk input unless noted)
153
+
154
+ Early stopping selected fewer steps than for ImMicro:
155
+
156
+ | arm | selected step | inner-val loss (pretrained 0.12500) |
157
+ |---|---:|---:|
158
+ | full | 3,750 | 0.11344 |
159
+ | LoRA | 6,500 | 0.11357 |
160
+ | condition encoder | 5,500 | 0.11606 |
161
+ | sc-only (pseudobulk) | 20,000 | 0.11275 (pretrained 0.11720, pseudobulk conditions) |
162
+
163
+ | arm | comp L1 ↓ | precision | coverage | donor top-1 | monocyte % (obs 24.6) | sepsis-vs-control logFC r, mean of T/B/Mono/NK | partial r beyond bulk broadcast |
164
+ |---|---:|---:|---:|---:|---:|---:|---:|
165
+ | zero-shot raw | 0.451 | 0.879 | 0.181 | 0.41 | 37.3 | 0.064 | −0.035 |
166
+ | zero-shot paired cal | 0.388 | 0.984 | 0.626 | 0.41 | 25.7 | 0.255 | 0.161 |
167
+ | zero-shot pseudobulk | **0.236** | 0.990 | 0.700 | **0.65** | 29.5 | 0.328 | 0.187 |
168
+ | FT condition encoder | 0.380 | 0.983 | 0.741 | 0.35 | 17.5 | 0.261 | 0.181 |
169
+ | FT LoRA r = 16 | 0.373 | 0.986 | 0.858 | 0.47 | 15.3 | 0.487 | **0.410** |
170
+ | FT full | 0.388 | 0.978 | **0.871** | 0.35 | 16.2 | **0.489** | 0.393 |
171
+ | FT sc only, raw input | 0.422 | 0.928 | 0.351 | 0.47 | 29.6 | 0.167 | 0.030 |
172
+ | FT sc only, paired-cal input | 0.396 | 0.979 | 0.850 | 0.35 | 21.7 | 0.465 | 0.357 |
173
+
174
+ - The leave-one-out composition null is 0.513: donors differ far more than in ImMicro.
175
+ - Contrast = per-cell-type log2 fold change of donor-averaged mean CP10K, over genes detected in ≥ 1 % of observed cells of the type.
176
+ - **Bulk broadcast baseline** (the input real bulk's sepsis-vs-control logFC copied to every cell type):
177
+ - mean r 0.482 (T 0.393, B 0.470, Mono 0.702, NK 0.361);
178
+ - with pseudobulk instead of real bulk: 0.668.
179
+
180
+ **Reading (one fold, one seed, only 5 controls):**
181
+ - Fine-tuning roughly doubles the per-cell-type disease-signal agreement (0.26 → 0.49).
182
+ - For the first time the generated cells carry a clear part beyond the bulk broadcast (partial r ≈ 0.4). In SLE the zero-shot model gave about 0.2.
183
+ - By cell type, FT beats broadcast for T and B, but not for monocytes (0.57 vs 0.70).
184
+ - Most of the gain comes from adapting to the cohort: sc-only FT with the paired-cal input reaches 0.465 / 0.357.
185
+ - Composition is not improved by any real-bulk arm (0.37–0.39 vs zero-shot pseudobulk 0.236). FT arms under-produce monocytes (15–17 % vs 24.6 %).
186
+ - So in sepsis the real bulk does not carry the donors' composition to the model, unlike ImMicro. One candidate cause not yet checked: granulocyte or low-density-neutrophil signal in sepsis PBMC bulk.
187
+
188
+ ## Sepsis top-50 DEG (added 2026-09-28; `scores/ye2026_sepsis/pooled_deg/`)
189
+
190
+ **Definition:** the NC benchmark's own `bulk2sc-paper/scripts/evaluate_generated_vs_truth.py`, imported, not copied (`welch_bh_deg`, `top_deg_genes`).
191
+ - Per cell type: donor pseudobulk on the 5,975 scoring genes, log1p CPM, two-sided Welch test, BH correction.
192
+ - List: genes with FDR < 0.05, ranked by |logFC|, top 50.
193
+ - Score: the number of genes shared by the observed and generated lists, summed over T/B/Mono/NK/DC (maximum 250). The SLE "81" is the same kind of sum.
194
+
195
+ | arm | T | B | Mono | NK | DC | sum / 250 | logFC r |
196
+ |---|---:|---:|---:|---:|---:|---:|---:|
197
+ | zero-shot raw | 3 | 0 | 4 | 1 | 1 | 9 | −0.01 |
198
+ | zero-shot paired cal | 5 | 1 | 4 | 0 | 1 | 11 | 0.12 |
199
+ | zero-shot pseudobulk | 11 | 5 | 1 | 1 | 4 | 22 | 0.47 |
200
+ | sc-only FT + cal | 1 | 1 | 9 | 0 | 4 | 15 | 0.30 |
201
+ | LoRA 5 pairs | 4 | 0 | 1 | 0 | 0 | 5 | 0.29 |
202
+ | LoRA 10 | 3 | 1 | 4 | 0 | 0 | 8 | 0.42 |
203
+ | LoRA 40 | 0 | 3 | 12 | 0 | 7 | 22 | 0.48 |
204
+ | LoRA all (58) | 1 | 1 | 19 | 0 | 2 | 23 | 0.53 |
205
+ | full all | 1 | 2 | 21 | 0 | 0 | 24 | 0.53 |
206
+
207
+ Real-bulk broadcast list: 21.
208
+
209
+ **Reading:**
210
+ - With enough pairs, top-50 DEG doubles over zero-shot calibration (11 → 23–24).
211
+ - It only reaches the broadcast level, and almost all of it is monocytes.
212
+ - T and NK overlap is near zero because the generated T cells produce almost no significant genes (12 vs 1,578 observed for full). The disease signal is in the right direction (logFC r 0.6) but too weak for FDR-based DEG calls.
213
+ - Paper note: `methods.tex:87` describes CP10K, but the evaluator uses CPM.
214
+
215
+ ## New datasets and the few-pair scenario (started 2026-09-28)
216
+
217
+ **Datasets** (built by agents with the same QC/identity rules; details in each `data/<ds>/QC_REPORT.md`):
218
+
219
+ | dataset | bulk | sc | usable pairs (donors) | contrast |
220
+ |---|---|---|---|---|
221
+ | Imperial ESKD COVID (Gisby 2022 + Stephenson 2025) | PBMC, htseq | 10x 5′ CITE atlas | 157 (57 patients; longitudinal) | covid_positive vs covid_negative |
222
+ | Giroux 2022 (Duke outpatient COVID) | PBMC, NuGEN SoLo total RNA (no RPL/RPS/MT genes) | 10x 5′ v1 | 24 (9 subjects) | severe vs mild |
223
+ | Ji 2025 ChILI | **PAXgene whole blood**, QuantSeq 3′ | 10x 5′ | 33 (20 patients) | ChILI (TOL, FU1) vs ICI controls (BC, AC) |
224
+
225
+ Dataset notes:
226
+ - **Imperial:** pairs are matched on the metadata swab day. The day in the bulk column name counts from symptom onset.
227
+ - **Giroux:** the author bulk table lacks the exposed and healthy subjects.
228
+ - **Ji:** the bulk is whole blood, so this is a whole-blood → PBMC test.
229
+
230
+ **Rules:**
231
+ - Rows with fewer than 200 cells are excluded (strict-QC protocol minimum). Only Imperial is affected.
232
+ - The scorer now accepts several samples per donor: the scored unit is the sample, and the composition null leaves out every sample of that donor.
233
+
234
+ **Few-pair scenario** (`tools/prepare_fewshot.py`, `make_fewshot_queue.sh`, `score_fewshot.sh`):
235
+ - **Training donors:** 5, stratified by case/control where the dataset has one. All their pairs are used.
236
+ - **Training:** LoRA for a fixed 3,000 steps with no inner validation (`ft_sdd.py --train-donors-file --fixed-steps`).
237
+ - **Test:** every other usable donor.
238
+ - **Comparators:**
239
+ - zero-shot raw;
240
+ - zero-shot paired cal, with alpha from the **same 5 pairs**;
241
+ - zero-shot pseudobulk (reference).
242
+ - **Repeats:** 5 draws.
243
+ - **Datasets:** also run on ImMicro and sepsis so all five datasets share the protocol.
244
+
245
+ **Also run:** the 5-fold CV of `make_cv_queue.sh` on each new dataset (zero-shot ×3, LoRA on all training donors, sc-only control).
246
+
247
+ **Hosts:**
248
+ - Imperial runs entirely on server_2 (GPU and scoring; outputs about 110 GB). `tools/run_queue_s2.sh` is the server_2 env copy of `run_queue.sh`.
249
+ - The rest runs on server_1.
250
+ - Scored ImMicro and sepsis generations were moved to server_2, sha-checked, with `.moved` markers (`tools/move_generated.sh`).
251
+
252
+ ## Results: few-pair scenario (LoRA on 5 donors, fixed 3,000 steps; test = every other donor; mean ± SD over 5 draws)
253
+
254
+ | dataset | arm | comp L1 | precision | coverage | case-control logFC r | partial r beyond broadcast | top-50 DEG (sum) |
255
+ |---|---|---:|---:|---:|---:|---:|---:|
256
+ | ImMicro | zero-shot cal (same 5 pairs) | 0.203 ± 0.011 | 0.904 | 0.535 | — | — | — |
257
+ | ImMicro | **LoRA 5** | **0.176 ± 0.012** | **0.952** | **0.792** | — | — | — |
258
+ | sepsis | zero-shot cal | 0.446 ± 0.046 | 0.899 | 0.428 | 0.10 ± 0.04 | 0.00 | 9.4 ± 2.6 |
259
+ | sepsis | **LoRA 5** | 0.466 ± 0.044 | 0.906 | **0.694** | **0.35 ± 0.16** | **0.31** | 16.4 ± 6.7 |
260
+ | Ji (whole blood) | zero-shot cal | 0.514 ± 0.016 | 0.782 | 0.114 | 0.14 ± 0.09 | 0.12 | 0.0 |
261
+ | Ji (whole blood) | **LoRA 5** | 0.513 ± 0.115 | **0.978** | **0.707** | **0.33 ± 0.08** | **0.30** | 0.2 |
262
+
263
+ Composition, LoRA 5 vs zero-shot cal (paired over donor-draws):
264
+ - ImMicro: better in 69 %, p 3e-24.
265
+ - Sepsis: p 0.96.
266
+ - Ji: p 0.60.
267
+
268
+ Real-bulk broadcast r:
269
+ - sepsis 0.32, top-50 DEG 20;
270
+ - Ji 0.23.
271
+
272
+ Zero-shot from the sc-derived pseudobulk (reference):
273
+ - ImMicro L1 0.211;
274
+ - sepsis L1 0.237, r 0.48, DEG 20.8;
275
+ - Ji L1 0.171, r 0.18.
276
+
277
+ ## Results: Ji 2025, 5-fold (33 pairs pooled; 18 ChILI vs 15 controls; whole-blood bulk → PBMC cells)
278
+
279
+ | arm | comp L1 | precision | coverage | ChILI-vs-control logFC r (T/B/Mono/NK; mean) | partial r | top-50 DEG |
280
+ |---|---:|---:|---:|---|---:|---:|
281
+ | zero-shot raw | 0.738 | 0.717 | 0.055 | 0.18/−0.08/0.22/0.02; 0.08 | 0.03 | 0 |
282
+ | zero-shot cal | 0.501 | 0.740 | 0.106 | 0.23/0.00/0.21/0.13; 0.14 | 0.11 | 0 |
283
+ | zero-shot pseudobulk (reference) | 0.173 | 0.985 | 0.685 | 0.28/−0.06/0.32/0.03; 0.14 | 0.03 | 5 |
284
+ | **LoRA (all training donors)** | 0.504 | **0.971** | **0.857** | **0.48/0.24/0.79/0.41; 0.48** | **0.45** | **15** |
285
+ | sc-only FT, raw input | 0.596 | 0.718 | 0.094 | 0.15 | 0.11 | 0 |
286
+ | sc-only FT, cal input | 0.609 | 0.694 | 0.113 | 0.25 | 0.22 | 0 |
287
+
288
+ Baselines:
289
+ - Real-bulk broadcast: r 0.24, DEG 4.
290
+ - Leave-donor-out composition null: 0.452.
291
+
292
+ **Reading:**
293
+ - Whole-blood bulk is far from PBMC; the zero-shot arms fall outside the observed cell space.
294
+ - LoRA on the paired whole-blood bulk brings the cells back (coverage 0.86), and the ChILI signal agrees with the observed cells at r 0.48 (monocytes 0.79).
295
+ - The sc-only control does not work here (coverage 0.11), so the paired bulk is what teaches the whole-blood → PBMC map.
296
+ - Composition stays at zero-shot-cal level and worse than the cohort mean: whole-blood bulk does not carry PBMC composition.
297
+
298
+ ## Results: Imperial and Giroux (2026-09-28)
299
+
300
+ **Imperial ESKD COVID** (157 samples / 57 patients; COVID+ 113 vs COVID− 34 samples; runs and scores on server_2, copied to `scores/imperial_eskd/`)
301
+
302
+ | setting | arm | comp L1 | precision | coverage | COVID logFC r (T/B/Mono/NK; mean) | partial r | top-50 DEG |
303
+ |---|---|---:|---:|---:|---|---:|---:|
304
+ | 5 pairs | zero-shot cal | 0.506 | 0.845 | 0.634 | 0.68 | 0.41 | 104 |
305
+ | 5 pairs | **LoRA 5** | 0.503 | 0.853 | **0.737** | **0.75** | **0.60** | **114** |
306
+ | 5-fold | zero-shot cal | 0.494 | 0.842 | 0.639 | 0.68/0.62/0.71/0.70 | 0.41 | 111 |
307
+ | 5-fold | **LoRA** | **0.376** (p 7e-11) | 0.847 | **0.850** | **0.90/0.75/0.79/0.83; 0.82** | **0.69** | **143** |
308
+ | 5-fold | sc-only FT + cal | 0.461 | 0.691 | 0.555 | 0.81 | 0.63 | 129 |
309
+
310
+ Baselines:
311
+ - Real-bulk broadcast: r 0.66, DEG 84 (75 in the 5-pair setting).
312
+ - Zero-shot from the sc pseudobulk: L1 0.300, r 0.68.
313
+ - Composition null: 0.505.
314
+
315
+ **Giroux 2022** (24 pairs / 9 subjects; severe 11 vs mild 13)
316
+
317
+ | setting | arm | comp L1 | coverage | severe-vs-mild r | partial r | top-50 DEG |
318
+ |---|---|---:|---:|---:|---:|---:|
319
+ | 5 pairs | zero-shot cal | 0.288 | 0.944 | 0.24 | 0.11 | 1.8 |
320
+ | 5 pairs | **LoRA 5** | 0.256 | 0.961 | 0.33 | 0.19 | 11.6 |
321
+ | 5-fold | zero-shot cal | 0.266 | 0.906 | 0.31 | 0.14 | 12 |
322
+ | 5-fold | **LoRA** | 0.258 | 0.928 | **0.50** | **0.33** | **25** |
323
+
324
+ - Here the real-bulk broadcast beats every generated arm: r 0.64, DEG 39 (5-pair: r 0.54, DEG 25).
325
+ - The severe-vs-mild difference is shared across cell types.
326
+ - **Superseded for the disease metrics (2026-10-01):** severity is confounded with sex (scored 4 F / 0 M vs 0 F / 5 M) and the
327
+ observed and broadcast DEG lists were led by chrY genes. Without the 196 sex-linked genes (`scores_nosex/giroux2022/`):
328
+
329
+ | setting | arm | severe-vs-mild r | partial r | top-50 DEG |
330
+ |---|---|---:|---:|---:|
331
+ | 5 pairs | zero-shot cal | 0.23 | 0.11 | 0.0 |
332
+ | 5 pairs | **LoRA 5** | 0.30 | 0.19 | 0.2 |
333
+ | 5-fold | zero-shot cal | 0.27 | 0.13 | 0 |
334
+ | 5-fold | **LoRA** | **0.46** | **0.32** | **5** |
335
+
336
+ - The real-bulk broadcast still beats every arm on r (5-fold 0.58, 5-pair 0.49) but not on DEG: the observed lists
337
+ shrink (5-fold max 123 → 101) and every overlap, broadcast included, falls to 0–5 (5-fold broadcast 5 = LoRA 5).
338
+ - chrY-only exclusion (`scores_nochrY/`) gives nearly the same numbers; the same exclusion moves the sex-balanced
339
+ cohorts' pooled r by ≤ 0.007 and DEG by ≤ 1 (`scores_nosex/README.md`).
340
+
341
+ ## Five-dataset summary (LoRA vs zero-shot paired calibration)
342
+
343
+ | dataset (bulk) | cell realism (coverage) | composition | disease signal vs zero-shot | vs real-bulk broadcast |
344
+ |---|---|---|---|---|
345
+ | ImMicro (PBMC, healthy) | ↑ both settings | ↑ both settings (≈ cohort-mean null) | n/a | n/a |
346
+ | sepsis (PBMC) | ↑ | = | ↑ (0.12 → 0.35 with 5 pairs, 0.53 with all) | above (r); ≈ (DEG) |
347
+ | Ji (whole blood) | ↑↑ (0.11 → 0.71–0.86) | = | ↑ (0.14 → 0.33 / 0.48) | above (r and DEG) |
348
+ | Imperial (PBMC) | ↑ | = with 5 pairs, ↑ with all | ↑ (0.68 → 0.75 / 0.82; DEG 104 → 114 / 143) | above (r and DEG) |
349
+ | Giroux (PBMC, 9 subjects; sex-linked genes excluded) | ≈ (already high) | = | ↑ (0.23 → 0.30 / 0.27 → 0.46) | below (r); DEG ≈ 0 for all |
350
+
351
+ ## Recommended protocol (user decision 2026-09-28: recommend LoRA)
352
+
353
+ 1. **Backbone:** the public pseudobulk-pretrained final model (6k, 1×, E16), frozen.
354
+ 2. **Paired data:** the user's paired bulk + scRNA from the same sample (raw counts, canonical 20,097 axis, measured masks); check identity (sex genes, expression match).
355
+ - Hold out about 10 % of the pairs, and at least 5–7 donors, for early stopping.
356
+ 3. **Condition:** real bulk at the fixed-depth policy (K = 1000, one depth anchor). No single-cell depth or cell count is needed at inference.
357
+ 4. **LoRA training** (`tools/ft_sdd.py --mode lora`):
358
+ - Rank 16, alpha 16, on all 22 denoiser Linear layers (1.30 M trainable parameters).
359
+ - AdamW with lr 5e-4, warmup 200 steps, weight decay 0. Grad clip 5, bf16, EMA 0.999.
360
+ - Donor-balanced batches of 256 cells: draw a donor uniformly, then one of its cells; the condition is that donor's real bulk.
361
+ - Inner-validation loss every 250 steps; stop after 2,000 steps without improvement; cap at 20,000 steps; keep the best EMA state.
362
+ - Merge the LoRA into the weights; the standard sampler then works unchanged.
363
+ 5. **Apply** only to bulk made with the same bulk protocol as the training pairs.
364
+
365
+ **What was run** (LoRA, per fold):
366
+
367
+ | dataset | train donors | inner-val donors | train cells | selected step | cell-epochs at selection | wall time |
368
+ |---|---:|---:|---:|---|---|---:|
369
+ | ImMicro | 78–79 | 7 | ~290 k | 19,500–20,000 (cap reached, loss still falling) | ~17–18 | ~13 min |
370
+ | sepsis | 58–59 | 7–8 | ~410–426 k | 3,750–13,000 (early stop) | 2.4–8.0, mostly ~4 | 4–11 min |
371
+
372
+ **Open questions being tested:**
373
+ - The minimum number of pairs is not known.
374
+ - Whether varied K helps is not known.
375
+
376
+ ## LoRA learning curve (2026-09-28)
377
+
378
+ One nested subset per fold and n; the inner-validation donors (7–8) sit outside the training subset.
379
+
380
+ **Sepsis** (pooled over all 82 donors; contrast 61 vs 21):
381
+
382
+ | training pairs | comp L1 | precision | coverage | sepsis-vs-control logFC r (T/B/Mono/NK; mean) | partial r beyond broadcast | selected steps |
383
+ |---:|---:|---:|---:|---|---:|---|
384
+ | 0 (zero-shot paired cal) | 0.401 | 0.903 | 0.431 | 0.04/0.16/0.25/0.04; 0.12 | 0.04 | — |
385
+ | 5 | 0.428 | 0.911 | 0.767 | 0.36/0.37/0.25/0.19; 0.29 | 0.25 | 2,000–3,000 |
386
+ | 10 | 0.390 | 0.916 | 0.786 | 0.54/0.49/0.33/0.32; 0.42 | 0.37 | 2,000–3,250 |
387
+ | 20 | 0.380 | 0.927 | 0.807 | 0.43/0.33/0.47/0.24; 0.37 | 0.30 | 2,500–4,000 |
388
+ | 40 | 0.365 | 0.922 | 0.818 | 0.57/0.52/0.52/0.29; 0.48 | 0.40 | 3,000–7,000 |
389
+ | 58 (all) | 0.362 | 0.926 | 0.829 | 0.63/0.57/0.58/0.34; 0.53 | 0.47 | 3,750–13,000 |
390
+
391
+ Reference rows:
392
+ - Real-bulk broadcast: mean r 0.32.
393
+ - sc-only FT with all 58 donors + paired cal: 0.30.
394
+ - Zero-shot from the sc-derived pseudobulk: 0.47, with composition 0.233.
395
+
396
+ **ImMicro** (folds 0–3, 86 donors, per-fold scoring; the selected-step column includes fold 4):
397
+
398
+ | training pairs | comp L1 (better than zero-shot cal in, p) | coverage | across-donor fraction r (T/B/Mono/NK) | selected steps |
399
+ |---:|---|---:|---|---|
400
+ | 0 (zero-shot paired cal) | 0.206 | 0.724 | 0.65/0.68/0.85/0.47 | — |
401
+ | 5 | 0.176 (70 %, 4e-5) | 0.920 | 0.62/0.71/0.82/0.19 | 2,750–5,000 |
402
+ | 10 | 0.193 (60 %, 0.05) | 0.890 | 0.56/0.72/0.75/0.45 | 3,250–19,500 |
403
+ | 20 | 0.178 (70 %, 1e-4) | 0.898 | 0.63/0.73/0.78/0.61 | 5,250–20,000 (4 of 5 folds at cap) |
404
+ | 40 | 0.171 (73 %, 3e-5) | 0.910 | 0.69/0.75/0.82/0.70 | cap |
405
+ | 78–79 (all) | 0.168 (65 %, 6e-6) | 0.917 | 0.74/0.75/0.88/0.72 | cap |
406
+
407
+ **Reading:**
408
+ - **Five pairs already fix most of the systematic real-bulk shift.**
409
+ - Coverage jumps from 0.43/0.72 to 0.77/0.92.
410
+ - ImMicro composition drops from 0.206 to 0.176.
411
+ - **Donor-level ranking and the disease signal keep improving with more pairs.**
412
+ - ImMicro NK r goes 0.19 → 0.45 → 0.61 → 0.70 → 0.72.
413
+ - Sepsis contrast goes 0.29 → 0.42 → 0.37 → 0.48 → 0.53. The dip at 20 is one subset per fold, so it is noise-level.
414
+ - About 10 pairs already beat the real-bulk broadcast in sepsis.
415
+ - With few pairs, early stopping lands at about 2,000–3,000 steps. That is a usable fixed schedule when no pairs can be spared for inner validation.
416
+
417
+ **ImMicro, all five folds pooled (107 donors; reference = all 107 donors):**
418
+
419
+ | training pairs | comp L1 (vs zero-shot cal, p) | across-donor NK r |
420
+ |---:|---|---:|
421
+ | 5 | 0.171 (2e-5) | 0.20 |
422
+ | 10 | 0.188 (0.06) | 0.40 |
423
+ | 20 | 0.172 (4e-5) | 0.56 |
424
+ | 40 | 0.171 (1e-4) | 0.70 |
425
+ | all | 0.162 (2e-7) | 0.70 |
426
+
427
+ Zero-shot paired cal gives L1 0.199.
428
+
429
+ ## K augmentation (2026-09-28)
430
+
431
+ **Sepsis, pooled over 82 donors; each arm vs plain LoRA:**
432
+
433
+ | arm | comp L1 | coverage | sepsis-vs-control r (mean) | partial r beyond broadcast |
434
+ |---|---:|---:|---:|---:|
435
+ | plain LoRA (K = 1000) | 0.362 | 0.829 | 0.527 | 0.469 |
436
+ | multi-K real bulk (K 250–4000) | 0.366 (p 0.70) | 0.819 | 0.509 | 0.447 |
437
+ | + half-batch pretraining recipes | 0.365 (p 0.73) | 0.817 | 0.496 | 0.431 |
438
+
439
+ - Inner-validation losses were within 0.0001 of plain LoRA in every fold.
440
+ - Neither augmentation helps: every metric is equal or slightly worse.
441
+
442
+ **ImMicro, pooled over 107 donors:**
443
+
444
+ | arm | comp L1 (vs plain LoRA, p) | precision | coverage | across-donor r (T/B/Mono/NK) |
445
+ |---|---|---:|---:|---|
446
+ | plain LoRA | 0.162 | 0.924 | 0.784 | 0.74/0.75/0.86/0.70 |
447
+ | multi-K | 0.168 (p 0.04, worse) | 0.928 | 0.775 | 0.74/0.76/0.85/0.66 |
448
+ | recipes | 0.161 (p 0.75) | 0.933 | 0.766 | 0.78/0.78/0.86/0.65 |
449
+
450
+ Inner-validation losses were within 0.0001 of plain LoRA in every fold.
451
+
452
+ **Conclusion:**
453
+ - Varying K brings no gain in either dataset. On the real-bulk side K is only a scale label.
454
+ - Recipes repeat the pretraining task, which does not teach the real-bulk mapping.
455
+ - The protocol keeps a single K = 1000 for the real-bulk condition.
456
+
457
+ ## Running (2026-09-28)
458
+
459
+ - **LoRA learning curve:**
460
+ - n training donors ∈ {5, 10, 20, 40}, nested and stratified (sepsis keeps its case:control ratio), subset seed 1000 + fold.
461
+ - Inner-validation and test rows are unchanged. `--train-n` in `ft_sdd.py`.
462
+ - Queues `*_lora_learning_curve.txt`: sepsis first, then ImMicro.
463
+ - **K augmentation** (`tools/ft_sdd_aug.py`, queues `*_lora_aug.txt`, after the learning curve):
464
+ - `lora_multik`: each training cell sees its donor's real bulk at K ∈ {250, 500, 1000, 2000, 4000}, with the per-cell depth kept.
465
+ - `lora_recipe`: half of each batch comes from one pretraining-style recipe. A recipe is K cells of one training donor (K from the pretraining grid, capped at that donor's cell count); its condition is their full-axis pseudobulk at recipe size K.
466
+ - Recipes need the full-axis cells in `data/<dataset>/cells_full.npz`, built by `tools/build_full_cells.py`. Their panel columns equal `cells_panel6k.npz` and their per-row sums equal `pseudo_raw_sum`.
467
+ - **Automation:** fold scoring, aggregation and pooled scoring follow automatically (`ft-lc-finalize-*`, `ft-aug-finalize-*` units).
468
+
469
+ ## Queue
470
+
471
+ - Sepsis fold 0 pilot (same eight arms) → ImMicro folds 1–4 → sepsis folds 1–4.
472
+ - Arms for folds 1–4: zero-shot raw/cal/pseudo, FT full, FT LoRA, sc-only FT control.
473
+ - Chained as systemd user units (`ft-*`), logs in `logs/`.
474
+
475
+ ## Additions of 2026-10-02 (CPU analyses + one GPU sampling step)
476
+
477
+ **No-pair x = 0 of the learning curve: exon-length-corrected zero-shot.** The learning curve's x = 0 used zero-shot +
478
+ calibration with alpha from every training pair of the fold, which is not "0 pairs" (user, 2026-10-02). It is replaced
479
+ by two arms that use no paired data:
480
+ - the real bulk as measured (pooled `zs__raw`);
481
+ - the same bulk after exon-length correction (`zs__len`). Counts are divided by the Ensembl union-exon kb, using the
482
+ `conditions_more` rule imported unchanged. The rest is the same fixed-depth arithmetic.
483
+
484
+ How the `zs__len` arm was built and scored:
485
+ - **Conditions:** `tools/build_tpm_zeroshot.py` writes `data/<ds>/zeroshot_tpm_20261002/all_usable_tpm.npz`. The raw arm
486
+ rebuilt through the same path equals `fewshot_n5/all_usable_raw.npz` bit for bit. Sepsis loses 112 measured genes
487
+ that have no valid length.
488
+ - **Sampling:** `tools/sample_lockwait.sh` runs the same sampler flags as `sample_queue.sh` and queues on the GPU lock
489
+ through `ml-run`. Seed 20260927 gives the same per-cell noise as the raw all-usable arm. Outputs:
490
+ `generated/<ds>/zeroshot_tpm_20261002/zs__tpm_all.npz`, server_1, with receipts.
491
+ - **Scoring:** `tools/score_tpm_zeroshot.sh` writes `scores/<ds>/zeroshot_tpm_20261002/pooled/`. It uses the same
492
+ donors and reference cells as `scores/<ds>/pooled`, and its `zs__raw` arm reproduces the pooled call. The pooled raw
493
+ NPZ and conditions were read from sha-checked copies of the server_2 originals; the copies were deleted after
494
+ scoring.
495
+
496
+ | pooled, 5-fold donors | composition L1 | precision | coverage | sepsis logFC r | sepsis top-50 DEG |
497
+ |---|---|---|---|---|---|
498
+ | ImMicro, as measured / length-corrected / calibration (all pairs) | 0.455 / 0.420 / 0.199 | 0.680 / 0.889 / 0.905 | 0.192 / 0.505 / 0.527 | | |
499
+ | Sepsis, as measured / length-corrected / calibration (all pairs) | 0.511 / 0.557 / 0.401 | 0.614 / 0.816 / 0.903 | 0.067 / 0.399 / 0.431 | −0.01 / 0.11 / 0.12 | 9 / 11 / 11 |
500
+
501
+ Length correction alone recovers most of the coverage that calibration gives, without any pair. It does not fix
502
+ composition (ImMicro L1 0.42; sepsis gets worse) or the disease signal (r 0.11). Deck section 8 and paper Fig. 3 now
503
+ show both no-pair points at x = 0. The rightmost point is labelled with its training-pair count (78–79 / 58–59), not
504
+ "all".
505
+
506
+ **Rank and threshold-free disease metrics: `scores_contrast/`** (tools/contrast_extra.py, `contrast_extra_limma.R`,
507
+ `contrast_extra_tables.py`; README and TABLES.md there).
508
+ - **Metrics:** for every few-pair draw and every pooled call, it adds Spearman logFC r, the split-half ceiling
509
+ (observed vs observed, Spearman–Brown), limma-voom top-50 DEG, the chance overlap of both DE tests, CAT curves
510
+ (same sign, chance k / 2G) and RBO.
511
+ - **Checks:** 135 / 135 reproduction checks pass against the scorer's Pearson r, partial r and Welch top-50.
512
+ - **Findings:**
513
+ - The ceiling (0.88–0.96 split-half, 0.96–0.99 noise-free) is not limiting.
514
+ - Spearman is lower than Pearson for generated arms.
515
+ - In sepsis the broadcast is ahead of LoRA on Spearman and on limma top-50 (pooled 36 vs 18), while CAT and RBO
516
+ favour LoRA.
517
+ - Imperial and Ji favour LoRA on every metric; Giroux favours the broadcast on every metric.
518
+ - Repeated samples of one patient (Imperial, Giroux, Ji) count as separate samples in both DE tests, as in the scorer.
519
+
520
+ ## No-pretraining ablation, sepsis fold 0 (2026-10-05)
521
+
522
+ **Question (user).** Is pretraining needed at all? The same model was trained from scratch on the cohort and compared
523
+ with the pretrained arms on the same fold-0 test donors (17: 12 sepsis, 5 controls).
524
+
525
+ **Setup.**
526
+ - `tools/ft_sdd_aug.py --init random`: every denoiser weight (54.2 M) is re-initialised as at the start of pretraining
527
+ (a fresh `ConditionalSBDDenoiser(model_config)`, torch seed 20260627) and the whole network is trained.
528
+ - The checkpoint still supplies the architecture, the 6k panel, the value scaler and the bulk conditioner's z-score
529
+ constants. These are preprocessing, not learned weights.
530
+ - Training: pretraining lr 2e-4, batch 256, EMA 0.999. Inner-validation selection, evaluated every 1,000 steps,
531
+ patience 10, at most 100k steps.
532
+ - Queue: `queues/ye2026_sepsis_scratch_20261005.txt`, run with `GATE=thermal` (new option in `run_queue_aug.sh` and
533
+ `sample_queue.sh`: thermal gate only, then wait in ml-run's lock flock, so the run interleaves with the scSemi queue).
534
+ - Same training donors, conditions (real bulk, K = 1,000), test rows and sampling seed as the pretrained arms.
535
+ - Scoring:
536
+ - `tools/score_scratch.sh` makes one `score_ft.py` call over all 8 arms. The comparison NPZs were copied back from
537
+ spark-0110 and sha-checked. Their composition, precision, coverage and logFC r reproduce `scores/ye2026_sepsis/fold0`
538
+ exactly.
539
+ - `tools/compare_scratch.py` → `scores/ye2026_sepsis/fold0_scratch_20261005/ablation_table.csv`.
540
+ - `extra_metrics.py --design scored` → `scores_extra/ye2026_sepsis/fold0_scratch_20261005/`.
541
+ - Donor-level table: `ablation_extra_donor.csv`.
542
+ - Rare states: `plans/rare_states_screen_20261004` (`sepsis_states.py --scope fold0`).
543
+
544
+ **Results** (inner-val loss of the selected state; pretrained start 0.125, random start 1.78):
545
+
546
+ | arm | inner-val | comp L1 ↓ | coverage (dm) | C2ST kNN AUC ↓ | MMD² ↓ | pseudobulk r | logFC r (partial) | across-donor composition r | own donor top-1 | donor spread gen/obs |
547
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|---:|
548
+ | zero-shot (pretrained) | – | 0.451 | 0.18 (0.16) | 0.990 | 0.346 | 0.883 | 0.06 (−0.04) | 0.61 | 7/17 | 0.92 |
549
+ | pretrained + LoRA, 5 pairs | 0.1143 | **0.363** | 0.81 (0.92) | 0.919 | 0.072 | 0.893 | 0.23 (0.13) | **0.70** | 4/17 | **0.66** |
550
+ | **scratch, 5 pairs** | 0.1223 | 0.448 | 0.80 (0.92) | 0.911 | 0.069 | 0.936 | 0.18 (0.14) | **0.17** | 1/17 | **0.28** |
551
+ | pretrained + LoRA, 58 pairs | 0.1136 | **0.373** | 0.86 (0.96) | 0.882 | 0.052 | 0.894 | 0.49 (0.41) | 0.77 | **8/17** | 0.74 |
552
+ | pretrained + full FT, 58 pairs | 0.1134 | 0.388 | 0.87 (0.95) | 0.880 | 0.050 | 0.903 | 0.49 (0.39) | 0.75 | 6/17 | 0.66 |
553
+ | **scratch, 58 pairs** (100k steps, still improving) | 0.1154 | 0.398 | 0.86 (0.94) | 0.886 | 0.056 | 0.914 | **0.58 (0.51)** | 0.68 | 4/17 | 0.63 |
554
+ | pretrained + LoRA + recipes, 58 pairs | 0.1135 | 0.385 | 0.87 (0.95) | 0.887 | 0.054 | 0.892 | 0.45 (0.36) | **0.81** | 6/17 | 0.67 |
555
+ | **scratch + recipes, 58 pairs** (100k steps) | 0.1155 | 0.385 | **0.88 (0.95)** | 0.888 | 0.066 | 0.911 | **0.54 (0.49)** | 0.77 | 4/17 | 0.72 |
556
+
557
+ Reference rows:
558
+ - bulk broadcast logFC r 0.48;
559
+ - composition leave-one-out null 0.513;
560
+ - real-vs-real C2ST kNN AUC 0.57.
561
+
562
+ Top-50 DEG overlap is 0–1 in every arm: with 12 vs 5 donors the observed Welch + BH lists are nearly empty, so it does
563
+ not separate the arms here.
564
+
565
+ Rare states (generated / observed, depth-matched):
566
+
567
+ | state | LoRA, 5 pairs | scratch, 5 pairs | LoRA, 58 pairs | full FT, 58 pairs | scratch, 58 pairs | scratch + recipes |
568
+ |---|---:|---:|---:|---:|---:|---:|
569
+ | MS1 | 0.15 | 0.10 | 0.21 | 0.36 | 0.40 | 0.46 |
570
+ | C1Q-high | 1.07 | 1.01 | 1.05 | 0.92 | 0.47 | 0.53 |
571
+ | plasmablast | 1.87 | 1.12 | 3.47 | 3.28 | 1.24 | 1.18 |
572
+
573
+ **Reading (one fold, 17 donors).**
574
+ 1. **Cell realism and diversity do not need pretraining.**
575
+ - The model trained from scratch matches the pretrained arms on coverage, precision, C2ST, MMD and E_N.
576
+ - It does so with 58 pairs and also with only 5 pairs (35k cells).
577
+ 2. **Disease signal does not need pretraining when there are dozens of pairs.**
578
+ - With 58 pairs, scratch gives the best logFC r: 0.58 vs 0.49, higher in all four cell types (T 0.64, B 0.62,
579
+ Mono 0.59, NK 0.46).
580
+ - With 5 pairs it is close to LoRA-5 (0.18 vs 0.23; partial r 0.14 vs 0.13).
581
+ 3. **What pretraining buys is the donor-specific bulk → composition map.**
582
+ - With 5 pairs, scratch cannot tell donors apart:
583
+ - across-donor composition r is 0.17 vs 0.70;
584
+ - donor spread is 0.28 vs 0.66;
585
+ - comp L1 0.448 is as bad as zero-shot.
586
+ - With 58 pairs the gap narrows (0.68 vs 0.77).
587
+ - Recipe augmentation closes most of it (0.77; spread 0.72; comp L1 0.385).
588
+ - Recipes are in effect a small cohort-level version of pretraining.
589
+ 4. **Cost.**
590
+ - Scratch needs 66k–100k steps: 61–86 min on GB10, and the 58-pair arms were still improving at the cap.
591
+ - LoRA needs 3k–7k steps: about 5 min.
592
+ 5. **Before any claim,** folds 1–4 are needed (pooled 82 donors, as for the LoRA learning curve). Not run yet; needs
593
+ user approval.
594
+
595
+ **Storage.** The three checkpoints and NPZs are on spark-0110 at the same paths, sha-checked, with `.moved` markers.
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/queues/ye2026_sepsis_scratch_20261005.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # ye2026_sepsis no-pretraining ablation (user request 2026-10-05): same architecture, every denoiser weight randomly
2
+ # initialised as at the start of pretraining (--init random), full training at the pretraining lr 2e-4, inner-val early
3
+ # stopping (eval every 1000, patience 10, max 100k steps). Same fold-0 donors, conditions, test rows and sampling seed
4
+ # as the LoRA arms real_lora / lora_n5 / lora_recipe.
5
+ train|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0/scratch_full|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/conditions_raw_fixed.npz|0|full|2e-4|--init|random|--max-steps|100000|--eval-every|1000|--patience|10
6
+ sample|ye2_f0_scratch_full|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0/scratch_full/checkpoint_ft.pt|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/fold0/test_raw.npz|20260927|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/generated/ye2026_sepsis/fold0/scratch_full__raw.npz
7
+ train|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0/scratch_n5|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/conditions_raw_fixed.npz|0|full|2e-4|--init|random|--max-steps|100000|--eval-every|1000|--patience|10|--train-n|5|--subset-seed|1000|--strata-regex|sepsis
8
+ sample|ye2_f0_scratch_n5|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0/scratch_n5/checkpoint_ft.pt|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/fold0/test_raw.npz|20260927|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/generated/ye2026_sepsis/fold0/scratch_n5__raw.npz
9
+ train|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0/scratch_recipe|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/conditions_raw_fixed.npz|0|full|2e-4|--init|random|--max-steps|100000|--eval-every|1000|--patience|10|--recipe-frac|0.5
10
+ sample|ye2_f0_scratch_recipe|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/runs/ye2026_sepsis/fold0/scratch_recipe/checkpoint_ft.pt|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/fold0/test_raw.npz|20260927|/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927/generated/ye2026_sepsis/fold0/scratch_recipe__raw.npz
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/tools/compare_scratch.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """No-pretraining ablation table (2026-10-05): fold-0 sepsis arms from scores/ye2026_sepsis/fold0_scratch_20261005
3
+ (one score_ft.py call: comparison arms + --init random arms on the same 17 test donors) plus each fine-tuning run's
4
+ selected inner-validation loss. Partial r = mean over T/B/Monocyte/NK of partial_r_generated_given_broadcast
5
+ (mean_cp10k). Writes scores/ye2026_sepsis/fold0_scratch_20261005/ablation_table.csv and prints it.
6
+ usage: compare_scratch.py
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ import pandas as pd
14
+
15
+ TASK = Path(__file__).resolve().parents[1]
16
+ SC = TASK / "scores/ye2026_sepsis/fold0_scratch_20261005"
17
+ RUNS = TASK / "runs/ye2026_sepsis/fold0"
18
+ ORDER = [("zs__raw", None, "zero-shot (pretrained, no pairs)"),
19
+ ("lora_n5__raw", "lora_n5", "pretrained + LoRA, 5 pairs"),
20
+ ("scratch_n5__raw", "scratch_n5", "from scratch, 5 pairs"),
21
+ ("real_lora__raw", "real_lora", "pretrained + LoRA, 58 pairs"),
22
+ ("real_full__raw", "real_full", "pretrained + full FT, 58 pairs"),
23
+ ("scratch_full__raw", "scratch_full", "from scratch, 58 pairs"),
24
+ ("lora_recipe__raw", "lora_recipe", "pretrained + LoRA + recipes, 58 pairs"),
25
+ ("scratch_recipe__raw", "scratch_recipe", "from scratch + recipes, 58 pairs")]
26
+
27
+
28
+ def main() -> int:
29
+ s = json.load(open(SC / "summary.json"))
30
+ h = s["headline"]
31
+ c = pd.read_csv(SC / "contrast.csv")
32
+ c = c[(c.statistic == "mean_cp10k") & c.celltype.isin(["T cell", "B cell", "Monocyte", "NK cell"])]
33
+ rows = []
34
+ for arm, run, desc in ORDER:
35
+ if arm not in h:
36
+ continue
37
+ x = h[arm]
38
+ rj = RUNS / run / "RUN.json" if run else None
39
+ r = json.load(open(rj)) if rj and rj.exists() else {}
40
+ cc = c[c.arm == arm]
41
+ rows.append({"arm": arm, "what": desc,
42
+ "inner_val_loss": r.get("selected_inner_val_loss"), "selected_step": r.get("selected_step"),
43
+ "comp_l1": x["comp_l1"], "precision": x["precision"], "coverage": x["coverage"],
44
+ "coverage_dm": x["coverage_dm"], "pb_r_median": x["pb_r_median"], "mono_pct_gen": x["mono_pct_gen"],
45
+ "logfc_r": x["contrast_mean_cp10k_r_gen"], "partial_r": cc.partial_r_generated_given_broadcast.mean(),
46
+ "deg_top50_4type": x["deg_top50_sum_4type"]})
47
+ t = pd.DataFrame(rows)
48
+ any_arm = next(iter(h.values()))
49
+ ref = {"comp_l1_obs_loo_null": any_arm["comp_l1_obs_loo_null"], "mono_pct_obs": any_arm["mono_pct_obs"],
50
+ "logfc_r_broadcast": any_arm["contrast_mean_cp10k_r_broadcast"],
51
+ "deg_top50_broadcast": any_arm["deg_top50_sum_broadcast"]}
52
+ t.to_csv(SC / "ablation_table.csv", index=False)
53
+ with pd.option_context("display.width", 250, "display.max_columns", 20):
54
+ print(t.round(4).to_string(index=False))
55
+ print("reference:", json.dumps({k: round(v, 4) for k, v in ref.items()}))
56
+ return 0
57
+
58
+
59
+ if __name__ == "__main__":
60
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261005T063808Z-no-pretraining-ablation-f0/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/sepsis_states.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rare states on held-out donors of the Ye 2026 sepsis paired cohort (real bulk, LoRA; CPU only; 2026-10-05).
3
+
4
+ Arms: the pooled, cross-fitted arms of plans/paired_finetune_intradataset_20260927 (generated/ye2026_sepsis/pooled/
5
+ <arm>.npz on spark-0110; every donor's cells come from the fold model that never trained on it; 82 donors x 1,500
6
+ cells; real bulk at K = 1,000). No new generation. The same scANVI labels as the benchmark are reused
7
+ (scores/ye2026_sepsis/pooled/arms/<arm>/labels), so the generated counts must be the benchmark's own Poisson read-out:
8
+ one draw over the whole NPZ (poisson_readout.poisson_integerise, seed 20260916, rows in NPZ order), then the rows of
9
+ generated_cells.parquet. `extract` checks this cell by cell against the benchmark's recorded umi_scoring_genes.
10
+
11
+ [--scope pooled|fold0] (default pooled; fold0 = fold-0 test donors incl. the 2026-10-05 no-pretraining arms)
12
+ extract ARM < NPZ bytes on stdin (ssh spark-0110 cat .../pooled/ARM.npz | sepsis_states.py extract ARM)
13
+ sha256 of the stream must equal the pooled receipt (generated/ye2026_sepsis/pooled/ARM.log, output_sha256).
14
+ Writes work/sepsis/ARM.npz: per labelled cell, counts of every marker gene of tools/states.json, the library on
15
+ the dataset's measured panel genes, donor, AIFI L1/L2. Nothing large is written.
16
+ analyze ARM [ARM ...]
17
+ Observed side: every cell of the scored donors (data/ye2026_sepsis/cells_panel6k.npz, benchmark observed labels).
18
+ States, thinning and counts exactly as tools/screen.py (one thinning constant per arm and marker state: observed
19
+ parent median library -> generated parent median library on the measured panel genes; label states as they
20
+ are). Per arm and state: "X of N" on both sides, generated / observed, Spearman over donors, and contrasts
21
+ (adult sepsis vs adult HC, paediatric sepsis vs paediatric HC, all sepsis vs all controls incl. ICU controls).
22
+ Outputs: out/sepsis_{summary,contrasts,per_donor}.csv
23
+ """
24
+ from __future__ import annotations
25
+
26
+ import hashlib
27
+ import importlib.util
28
+ import io
29
+ import json
30
+ import sys
31
+ from pathlib import Path
32
+
33
+ import numpy as np
34
+ import pandas as pd
35
+ import scipy.sparse as sp
36
+ from scipy.stats import spearmanr
37
+
38
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
39
+ from screen import call_state, parent_mask, state_cols # noqa: E402
40
+
41
+ PLAN = Path(__file__).resolve().parents[1]
42
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
43
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
44
+ DATA = FT / "data/ye2026_sepsis"
45
+ # scope -> (generated dir with <arm>.npz + receipt <arm>.log, scores dirs searched in order for arms/<arm>/, work dir,
46
+ # output prefix). "pooled": the cross-fitted 82-donor arms; "fold0": the fold-0 test donors, incl. the
47
+ # no-pretraining (--init random) arms of 2026-10-05 scored in fold0_scratch_20261005.
48
+ SCOPES = {
49
+ "pooled": (FT / "generated/ye2026_sepsis/pooled", [FT / "scores/ye2026_sepsis/pooled/arms"],
50
+ PLAN / "work/sepsis", "sepsis"),
51
+ "fold0": (FT / "generated/ye2026_sepsis/fold0",
52
+ [FT / "scores/ye2026_sepsis/fold0_scratch_20261005/arms", FT / "scores/ye2026_sepsis/fold0/arms"],
53
+ PLAN / "work/sepsis/fold0", "sepsis_fold0"),
54
+ }
55
+ REF = FT / "scoring_cache/ye2026_sepsis/reference.npz"
56
+ OBS_LABELS = FT / "scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet"
57
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
58
+ "canonical_genes.tsv")
59
+ POISSON_PY = M8 / "plans/aifi_scanvi_rebuild_20260916/poisson_readout.py"
60
+ POISSON_SEED = 20260916
61
+ THIN_SEED = 20261004
62
+ CONTRASTS = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
63
+ ("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
64
+ ("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
65
+ ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
66
+
67
+
68
+ def load_poisson():
69
+ spec = importlib.util.spec_from_file_location("poisson_readout", POISSON_PY)
70
+ mod = importlib.util.module_from_spec(spec)
71
+ spec.loader.exec_module(mod)
72
+ return mod
73
+
74
+
75
+ def marker_genes(states: list[dict]) -> list[str]:
76
+ out = []
77
+ for st in states:
78
+ for g in st.get("genes", []) + [x for grp in st.get("require_any", []) for x in grp] + st.get("exclude", []):
79
+ if g not in out:
80
+ out.append(g)
81
+ return out
82
+
83
+
84
+ def panel_setup(states: list[dict]) -> tuple[np.ndarray, np.ndarray, list[str], np.ndarray]:
85
+ """6k panel ids, measured-gene mask (any sample of the dataset), marker symbols present, their panel columns."""
86
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
87
+ panel = d["panel_gene_ids"].astype(str)
88
+ measured = d["panel_measured"].any(0)
89
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
90
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
91
+ pos = {g: i for i, g in enumerate(panel)}
92
+ syms = [g for g in marker_genes(states) if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
93
+ return panel, measured, syms, np.asarray([pos[sym2id[g]] for g in syms], dtype=np.int64)
94
+
95
+
96
+ def cmd_extract(arm: str, scope: str) -> None:
97
+ gen_dir, score_dirs, work, _ = SCOPES[scope]
98
+ sdir = next((d / arm for d in score_dirs if (d / arm / "generated_cells.parquet").exists()), None)
99
+ if sdir is None:
100
+ raise SystemExit(f"{arm}: no scored labels in {score_dirs}")
101
+ states = json.loads((PLAN / "tools/states.json").read_text())
102
+ panel, measured, syms, cols = panel_setup(states)
103
+ raw = sys.stdin.buffer.read()
104
+ sha = hashlib.sha256(raw).hexdigest()
105
+ want = json.loads((gen_dir / f"{arm}.log").read_text())["output_sha256"]
106
+ if sha != want:
107
+ raise SystemExit(f"{arm}: streamed NPZ sha256 {sha[:12]} != pooled receipt {want[:12]}")
108
+ d = np.load(io.BytesIO(raw), allow_pickle=False)
109
+ del raw
110
+ if not np.array_equal(d["gene_ids"].astype(str), panel):
111
+ raise SystemExit(f"{arm}: NPZ gene_ids differ from the 6k panel")
112
+ rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
113
+ n_rows = rates.shape[0]
114
+ full = load_poisson().poisson_integerise(rates, seed=POISSON_SEED, chunk_rows=4096)
115
+ del rates
116
+ gc = pd.read_parquet(sdir / "generated_cells.parquet")
117
+ lab = pd.read_parquet(sdir / "labels/labels.parquet")
118
+ if len(gc) != len(lab) or not (lab.sample_id.astype(str).str.removesuffix("|generated").values == gc.donor.values).all():
119
+ raise SystemExit(f"{arm}: generated_cells and labels are not row-aligned")
120
+ X = full[gc.npz_row.to_numpy()].tocsr()
121
+ del full
122
+ ref = np.load(REF, allow_pickle=False)
123
+ umi = np.asarray(X[:, ref["score_idx"]].sum(1)).ravel()
124
+ if not np.array_equal(umi, gc.umi_scoring_genes.to_numpy()):
125
+ bad = int((umi != gc.umi_scoring_genes.to_numpy()).sum())
126
+ raise SystemExit(f"{arm}: Poisson read-out does not reproduce the benchmark ({bad} cells differ)")
127
+ lib = np.asarray(X[:, np.flatnonzero(measured)].sum(1)).ravel()
128
+ M = X[:, cols].toarray().astype(np.int32)
129
+ work.mkdir(parents=True, exist_ok=True)
130
+ np.savez_compressed(work / f"{arm}.npz", markers=M, marker_symbols=np.asarray(syms), lib_measured=lib,
131
+ donor=np.asarray(gc.donor, dtype=str), aifi_l1=np.asarray(lab.aifi_l1, dtype=str),
132
+ aifi_l2=np.asarray(lab.aifi_l2, dtype=str),
133
+ receipt=json.dumps({"arm": arm, "npz_sha256": sha, "npz_rows": int(n_rows),
134
+ "cells": int(len(gc)), "poisson_seed": POISSON_SEED,
135
+ "umi_scoring_genes_reproduced": True}))
136
+ print(json.dumps({"arm": arm, "sha256_ok": True, "cells": int(len(gc)), "donors": int(gc.donor.nunique()),
137
+ "poisson_reproduced": True, "median_lib_measured": float(np.median(lib))}))
138
+
139
+
140
+ def observed(states: list[dict], donors: list[str]) -> dict:
141
+ _, measured, syms, cols = panel_setup(states)
142
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
143
+ X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
144
+ obs = pd.read_parquet(DATA / "cells_obs.parquet", columns=["sample_id", "group"])
145
+ lab = pd.read_parquet(OBS_LABELS)
146
+ if len(lab) != X.shape[0] or not (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all():
147
+ raise SystemExit("observed labels not aligned with cells_panel6k.npz")
148
+ keep = np.flatnonzero(obs.sample_id.isin(donors).to_numpy())
149
+ Xk = X[keep]
150
+ return {"markers": Xk[:, cols].toarray().astype(np.int32), "marker_symbols": syms,
151
+ "lib": np.asarray(Xk[:, np.flatnonzero(measured)].sum(1)).ravel(),
152
+ "donor": obs.sample_id.to_numpy()[keep].astype(str),
153
+ "lab": lab.iloc[keep][["aifi_l1", "aifi_l2"]].reset_index(drop=True),
154
+ "groups": obs.drop_duplicates("sample_id").set_index("sample_id").group}
155
+
156
+
157
+ def cmd_analyze(arms: list[str], scope: str) -> None:
158
+ _, _, work, prefix = SCOPES[scope]
159
+ states = json.loads((PLAN / "tools/states.json").read_text())
160
+ gens = {a: np.load(work / f"{a}.npz", allow_pickle=False) for a in arms}
161
+ donors = sorted(set(gens[arms[0]]["donor"]))
162
+ for a in arms:
163
+ if sorted(set(gens[a]["donor"])) != donors:
164
+ raise SystemExit(f"{a}: scored donors differ from {arms[0]}")
165
+ ob = observed(states, donors)
166
+ groups = ob["groups"]
167
+ rng = np.random.default_rng(THIN_SEED)
168
+ per, summ, con = [], [], []
169
+ for arm in arms:
170
+ g = gens[arm]
171
+ syms = list(g["marker_symbols"].astype(str))
172
+ if syms != ob["marker_symbols"]:
173
+ raise SystemExit(f"{arm}: marker columns differ from the observed side")
174
+ sym2col = {s: i for i, s in enumerate(syms)}
175
+ lg = pd.DataFrame({"aifi_l1": g["aifi_l1"], "aifi_l2": g["aifi_l2"]})
176
+ for st in states:
177
+ po, pg = parent_mask(ob["lab"], st["parent"]), parent_mask(lg, st["parent"])
178
+ if st["kind"] == "label":
179
+ ho = ob["lab"].aifi_l2.isin(st["labels"]).to_numpy() & po
180
+ hg = lg.aifi_l2.isin(st["labels"]).to_numpy() & pg
181
+ ht, thin = ho, 1.0
182
+ else:
183
+ ident = {s: s for s in syms}
184
+ _, pcols, req, exc = state_cols(st, ident, sym2col)
185
+ c = pcols + [x for r in req for x in r] + exc
186
+ thin = min(1.0, float(np.median(g["lib_measured"][pg])) / float(np.median(ob["lib"][po])))
187
+ co = ob["markers"][:, c].astype(np.int64)
188
+ ho = call_state(co, st, len(pcols), req, exc) & po
189
+ ct = rng.binomial(co, thin) if thin < 1.0 else co
190
+ ht = call_state(ct, st, len(pcols), req, exc) & po
191
+ hg = call_state(g["markers"][:, c], st, len(pcols), req, exc) & pg
192
+ rows = []
193
+ for s in donors:
194
+ mo, mg = ob["donor"] == s, g["donor"] == s
195
+ rows.append({"arm": arm, "state": st["name"], "donor": s, "group": groups.get(s),
196
+ "obs_parent": int((po & mo).sum()), "obs_state": int((ho & mo).sum()),
197
+ "obsthin_state": int((ht & mo).sum()),
198
+ "gen_parent": int((pg & mg).sum()), "gen_state": int((hg & mg).sum())})
199
+ t = pd.DataFrame(rows)
200
+ t["obsthin_pct"] = 100 * t.obsthin_state / t.obs_parent.where(t.obs_parent > 0)
201
+ t["gen_pct"] = 100 * t.gen_state / t.gen_parent.where(t.gen_parent > 0)
202
+ per.append(t)
203
+ ok = t[["gen_pct", "obsthin_pct"]].dropna()
204
+ rho = float(spearmanr(ok.gen_pct, ok.obsthin_pct).correlation) if len(ok) > 2 else np.nan
205
+ ro = 100 * t.obsthin_state.sum() / max(t.obs_parent.sum(), 1)
206
+ rg = 100 * t.gen_state.sum() / max(t.gen_parent.sum(), 1)
207
+ summ.append({"arm": arm, "state": st["name"], "thin": round(thin, 3),
208
+ "gen": f"{int(t.gen_state.sum()):,} / {int(t.gen_parent.sum()):,}",
209
+ "obs_thinned": f"{int(t.obsthin_state.sum()):,} / {int(t.obs_parent.sum()):,}",
210
+ "obs_native_n": int(t.obs_state.sum()), "gen_pct": rg, "obs_pct": ro,
211
+ "gen_over_obs": rg / ro if ro else np.nan, "spearman_donors": rho})
212
+ for name, A, B in CONTRASTS:
213
+ ga, gb = t[t.group.isin(A)], t[t.group.isin(B)]
214
+ con.append({"arm": arm, "state": st["name"], "contrast": name, "n_a": len(ga), "n_b": len(gb),
215
+ "obs_a": f"{int(ga.obsthin_state.sum())} / {int(ga.obs_parent.sum())}",
216
+ "obs_b": f"{int(gb.obsthin_state.sum())} / {int(gb.obs_parent.sum())}",
217
+ "gen_a": f"{int(ga.gen_state.sum())} / {int(ga.gen_parent.sum())}",
218
+ "gen_b": f"{int(gb.gen_state.sum())} / {int(gb.gen_parent.sum())}",
219
+ "obs_diff": ga.obsthin_pct.mean() - gb.obsthin_pct.mean(),
220
+ "gen_diff": ga.gen_pct.mean() - gb.gen_pct.mean()})
221
+ C = pd.DataFrame(con)
222
+ C["same_direction"] = np.sign(C.obs_diff) == np.sign(C.gen_diff)
223
+ S = pd.DataFrame(summ)
224
+ out = PLAN / "out"
225
+ pd.concat(per).to_csv(out / f"{prefix}_per_donor.csv", index=False)
226
+ S.to_csv(out / f"{prefix}_summary.csv", index=False)
227
+ C.to_csv(out / f"{prefix}_contrasts.csv", index=False)
228
+ with pd.option_context("display.width", 250, "display.max_columns", 30, "display.max_rows", 500):
229
+ print(S.round(3).to_string(index=False))
230
+ print(C.round(2).to_string(index=False))
231
+
232
+
233
+ def main() -> int:
234
+ args = sys.argv[1:]
235
+ scope = "pooled"
236
+ if "--scope" in args:
237
+ i = args.index("--scope")
238
+ scope = args[i + 1]
239
+ del args[i:i + 2]
240
+ if scope not in SCOPES:
241
+ raise SystemExit(f"--scope must be one of {list(SCOPES)}")
242
+ if len(args) >= 2 and args[0] == "extract":
243
+ cmd_extract(args[1], scope)
244
+ elif len(args) >= 2 and args[0] == "analyze":
245
+ cmd_analyze(args[1:], scope)
246
+ else:
247
+ raise SystemExit(__doc__)
248
+ return 0
249
+
250
+
251
+ if __name__ == "__main__":
252
+ sys.exit(main())