junidude14 commited on
Commit
fe8b7aa
·
verified ·
1 Parent(s): 0af4127

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261005T143721Z-rare-states-scratch-masked/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/README.md ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rare disease-associated states beyond C1Q-high monocytes (2026-10-04/05)
2
+
3
+ **Question (user).** The model seems to follow the rise of C1Q-high monocytes to some degree. Which other rare,
4
+ disease-specific subtypes would be worth testing the same way?
5
+
6
+ **Two parts.**
7
+ 1. A literature survey of rare PBMC states.
8
+ - 14 candidates, with key papers and marker genes.
9
+ - 43 PDFs in `paper-release-20260928/reference-papers/rare-disease-states/`, listed in the `INDEX.md` there.
10
+ 2. A screen of the zero-shot arms we already had, with no new generation:
11
+ - The arms are DRESS (in the corpus), and Kawasaki and SLE GSE135779 (not in the corpus).
12
+ - Model: final f01 6k E16. Each sample's own pseudobulk is the condition at K = 1,000, with seed 20260913.
13
+ - Read-out: Poisson, seed 20260916. Labels: frozen f01common scANVI.
14
+ - Each state was scored on generated and observed cells with the paper-based marker rules in
15
+ `tools/states.json`.
16
+ - Observed parent cells are binomially thinned to the generated median library, as in `c1q_crossdisease`.
17
+
18
+ ## Results (counts: state cells / parent cells; observed thinned)
19
+
20
+ | state (rule) | dataset | generated | observed | gen/obs | Spearman | disease direction |
21
+ |---|---|---|---|---:|---:|---|
22
+ | **MS1 monocyte** (IL1R2 + ≥ 2 of RETN ALOX5AP CYP1B1 MCEMP1 PLAC8 CLU CD163) | Kawasaki | KD before 317 / 4,450; HC 0 / 798; after IVIG 28 / 2,679 | 697 / 5,923; 1 / 1,123; 16 / 4,004 | 0.67 | 0.55 | **both kept** |
23
+ | | SLE | 21 / 21,833 | 3,105 / 70,901 | 0.02 | −0.03 | lost |
24
+ | **ISG-high T** (≥ 4 of 10 ISGs) | SLE | aSLE 746 / 12,979; aHD 29 / 10,265; cSLE 4,989 / 60,156; cHD 55 / 23,121 | 3,767 / 20,730; 175 / 27,704; 21,953 / 111,977; 450 / 56,080 | 0.45 | **0.86** | **both kept** |
25
+ | ISG-high monocyte (positive control) | SLE | 7,372 / 21,833 | 27,715 / 70,901 | 0.86 | 0.86 | both kept |
26
+ | **Cycling T/NK** (≥ 2 of MKI67 TOP2A TYMS CENPF UBE2C BIRC5) | SLE | 688 / 124,845 | 1,553 / 238,992 | 0.85 | 0.68 | both kept |
27
+ | | DRESS | patient 32 / 3,857; HV 1 / 3,370 | 882 / 5,633; 20 / 5,650 | 0.32 | 0.78 | kept, compressed |
28
+ | | Kawasaki | 92 / 45,425 | 1,163 / 63,360 | 0.11 | 0.34 | mixed |
29
+ | **Plasmablast** (scANVI 'Plasma cell') | Kawasaki | 206 / 75,000 | 1,837 / 103,362 | 0.16 | 0.56 | kept (KD vs HC, before vs after) |
30
+ | | SLE | 85 / 168,000 | 1,526 / 358,235 | 0.12 | 0.19 | child kept, adult reversed |
31
+ | C1Q-high monocyte (reference) | Kawasaki / SLE / DRESS | 43 / 7,927; 109 / 21,833; 110 / 3,793 | 603 / 11,050; 1,800 / 70,901; 529 / 4,485 | 0.10 / 0.20 / 0.25 | 0.17 / 0.43 / 0.96 | mixed |
32
+ | **DN2 / ABC B** (ITGAX or TBX21 + ≥ 2 of 7, CR2 absent) | SLE | 40 / 19,311 | 931 / 35,488 | 0.08 | 0.04 | adult weak, child reversed |
33
+ | HSPC (≥ 2 of CD34 PRSS57 SPINK2 SMIM24) | SLE | 12 / 168,000 | 265 / 358,235 | 0.10 | 0.13 | too rare to judge |
34
+ | **Granulocyte-like / LDG** (≥ 2 of 9 granule and neutrophil genes) | Kawasaki | 16 / 75,000 | 2,974 / 103,362 | **0.007** | 0.85 | not generated |
35
+
36
+ The full tables are in `out/summary.csv`, `out/contrasts.csv` and `out/per_sample.csv`. The v1 run used provisional
37
+ marker rules; its tables are kept in `out/v1_provisional_markers/`.
38
+
39
+ **Corpus frequency** (`out/corpus_states.csv`; corpus sample of 179,750 cells, native depth):
40
+ - MS1 (IL1R2+) is 6.9 % of monocytes, mostly from the COVID datasets.
41
+ - ISG-high T is 5.2 % of T cells.
42
+ - DN2 / ABC is 5.2 % of B cells.
43
+ - Granulocyte-like cells are 2.4 % of all cells.
44
+ - Plasmablasts (label) are 0.47 % of all cells.
45
+
46
+ So the poorly generated states, DN2 and LDG, are **present in the corpus**. Corpus absence does not explain them.
47
+
48
+ ## Reading
49
+
50
+ 1. **What is reproduced, even outside the corpus.** These are states carried by a strong, broad program in the bulk:
51
+ - Kawasaki MS1 monocytes: present before IVIG, absent in controls, gone after IVIG.
52
+ - SLE ISG-high T cells, a rare state in healthy donors.
53
+ - Cycling T cells in SLE.
54
+
55
+ Direction and sample ranking are kept. Kawasaki MS1 matches the Gold 2026 reanalysis of the same cohort.
56
+ 2. **What is compressed but directional.** Plasmablasts and C1Q-high monocytes come out at 0.1–0.25× and follow the
57
+ disease direction only in some contrasts.
58
+ 3. **What fails.**
59
+ - DN2 / ABC B cells: 0.08×, no sample tracking.
60
+ - Granulocyte-like / LDG cells: essentially never generated, although present in the corpus.
61
+ - HSPC: too rare to judge at these cell numbers.
62
+ 4. **Caveats.**
63
+ - Zero-shot and pseudobulk-conditioned, one seed, marker-rule states.
64
+ - The DRESS samples were training samples.
65
+ - The Kawasaki data are 10x 5′.
66
+ - SLE MS1 in observed cSLE (6.5 %) may partly reflect granulocyte contamination; it is not reproduced.
67
+
68
+ ## Ye 2026 sepsis: real bulk, LoRA, held-out donors (2026-10-05; user approved)
69
+
70
+ **Design.**
71
+ - Arms: the pooled, cross-fitted arms of `paired_finetune_intradataset_20260927`. Each of the 82 donors gets 1,500
72
+ cells from the fold model that never trained on it, conditioned on its real PBMC bulk at K = 1,000.
73
+ - Arms scored:
74
+ - zero-shot (`zs__raw`);
75
+ - LoRA with 5, 10, 20 and 40 training pairs (`lora_n*`, nested subsets per fold);
76
+ - LoRA with all 58 training pairs (`real_lora__raw`);
77
+ - zero-shot from the sc pseudobulk (`zs__pseudo`).
78
+ - No new generation.
79
+ - The benchmark's own labels are reused:
80
+ - Each pooled NPZ was streamed from spark-0110 and checked against its pooled receipt sha.
81
+ - It was read out once with the benchmark's Poisson draw (seed 20260916, whole NPZ).
82
+ - Every cell's UMI on the scoring genes reproduces the benchmark's record exactly, for all 7 arms × 123,000 cells.
83
+ - Observed side: all 589,478 cells of the 82 scored donors. Same state rules and depth matching as above.
84
+ - Tool: `tools/sepsis_states.py`. Outputs: `out/sepsis_{summary,contrasts,per_donor}.csv`.
85
+
86
+ **Counts: state cells / parent cells, all 82 donors; observed thinned to each arm's depth.**
87
+
88
+ | state | zero-shot real bulk | LoRA 5 pairs | LoRA 20 pairs | LoRA all 58 pairs | zero-shot sc pseudobulk |
89
+ |---|---|---|---|---|---|
90
+ | **MS1 monocyte (IL1R2+)** gen | 403 / 45,474 | 2,129 / 21,211 | 2,024 / 24,014 | 2,507 / 22,723 | 1,949 / 29,005 |
91
+ | observed | 12,363 / 111,269 | 17,344 / 111,269 | 17,768 / 111,269 | 17,348 / 111,269 | 16,859 / 111,269 |
92
+ | gen / obs; Spearman over donors | **0.08**; 0.53 | **0.64**; 0.46 | 0.53; 0.44 | **0.71**; 0.57 | 0.44; 0.40 |
93
+ | **C1Q-high monocyte** gen | 63 / 45,474 | 669 / 21,211 | 1,023 / 24,014 | 676 / 22,723 | 101 / 29,005 |
94
+ | observed | 5,908 / 111,269 | 6,599 / 111,269 | 6,665 / 111,269 | 6,595 / 111,269 | 6,520 / 111,269 |
95
+ | gen / obs | **0.03** | 0.53 | **0.71** | 0.50 | 0.06 |
96
+ | **Cycling monocyte (Ye)** gen / obs | 0.10 | 0.31 | 0.15 | 0.23 | 0.13 |
97
+ | **Plasmablast (label)** gen / obs | 0.39 | 0.41 | 1.04 | 0.76 | 0.46 |
98
+ | ISG-high T / Proliferating T (label) gen / obs | 1.74 / 1.96 | 0.39 / 0.62 | 0.52 / 0.75 | 0.57 / 0.78 | 0.60 / 0.70 |
99
+ | DN2 / ABC B; granulocyte-like gen / obs | 1.49; 0.24 | 0.42; 0.04 | 0.39; 0.05 | 0.31; 0.07 | 0.18; 0.03 |
100
+
101
+ **Disease contrasts, LoRA with all 58 pairs** (generated vs observed):
102
+ - MS1:
103
+ - adult sepsis 1,627 / 14,056 vs adult HC 2 / 1,543. Observed: 11,187 / 57,131 vs 39 / 8,702.
104
+ - paediatric sepsis 554 / 3,325 vs paediatric HC 1 / 524. Observed: 2,557 / 15,430 vs 5 / 4,363.
105
+ - All three contrasts keep their direction in every arm.
106
+ - C1Q-high:
107
+ - adult sepsis 481 / 14,056 vs adult HC 18 / 1,543. Observed: 3,687 / 57,131 vs 137 / 8,702.
108
+ - paediatric sepsis 122 / 3,325 vs paediatric HC 1 / 524. Observed: 2,294 / 15,430 vs 35 / 4,363.
109
+ - Directions are kept from 10 pairs on.
110
+ - LoRA with 5 pairs reverses the adult contrast (47 / 1,245 in HC).
111
+ - Zero-shot from pseudobulk loses all three contrasts.
112
+ - Cycling monocytes, paediatric: 33 / 3,325 vs 1 / 524. Observed: 1,645 / 15,430 vs 44 / 4,363. The direction is kept
113
+ in every LoRA arm but strongly compressed; zero-shot from real bulk loses the adult contrast.
114
+ - Plasmablasts:
115
+ - adult sepsis 704 / 69,000 vs HC 21 / 10,500. Observed: 3,601 / 310,451 vs 90 / 59,344. Kept.
116
+ - The paediatric observed contrast is flat: 2,779 / 98,395 vs 1,000 / 35,572.
117
+
118
+ **Reading.**
119
+ 1. **LoRA on paired donors is what brings the rare monocyte states out.**
120
+ - Zero-shot from real bulk generates MS1 at 0.08× and C1Q-high at 0.03×.
121
+ - Five pairs already lift them to 0.64× and 0.53×.
122
+ - With 10+ pairs the disease directions hold for both.
123
+ - Zero-shot from the sc pseudobulk does not get C1Q-high either (0.06×). The gain comes from fine-tuning, not from a
124
+ better condition.
125
+ - For Behçet this suggests the 0.10–0.18× after LoRA-3 is a pair-count / cohort-specific limit, not a hard ceiling of
126
+ the generator. The sepsis training donors carry many C1Q-high cells; Behçet LoRA-3 had 3 BD pairs and was scored on
127
+ unpaired bulk donors.
128
+ 2. **Still compressed with LoRA:**
129
+ - cycling monocytes, 0.15–0.31×;
130
+ - granulocyte-like cells, ≤ 0.07×;
131
+ - DN2 B cells, 0.3–0.4×.
132
+ 3. **Zero-shot overshoots the lymphoid activation states** (ISG-high T 1.7×, proliferating T 2.0×). LoRA brings them
133
+ below 1×.
134
+ 4. **Caveats.**
135
+ - Generated depth differs by arm: median library on measured genes is 973 for zero-shot real bulk and about 1,800–2,000
136
+ for the others. Observed cells are thinned to each arm's depth, so compare generated vs observed within an arm.
137
+ - Spearman over donors stays moderate (MS1 0.44–0.57; C1Q 0.15–0.32).
138
+
139
+ ## From scratch vs pretrained: rare states (2026-10-05; user question)
140
+
141
+ **Question.** Given the same training pairs, how well does a model trained from scratch (random init, no corpus
142
+ pretraining) generate rare states, compared with the pretrained model + LoRA / full FT? No new generation.
143
+
144
+ **Arms.**
145
+ - **Within the cohort:** fold 0, 17 donors, `--scope fold0`. Scratch vs pretrained with 5 pairs, 58 pairs, and 58
146
+ pairs + recipes.
147
+ - **Across cohorts:** all 82 sepsis donors held out, new `--scope loco` (split `hoL_ye2026_sepsis` of
148
+ `plans/paired_crosscohort_20261002`). Trained on ImMicro + Imperial + Giroux + Liu pairs only.
149
+ - Pretrained arms: LoRA r16 / r64 and full FT, all step-saturated, and calibration-only `xcal`.
150
+ - Scratch arms: the milestones at 50k, 100k, 150k and 162k steps (final).
151
+ - Own-cohort pooled LoRA-5 / LoRA-58 and zero-shot extracts are hard-linked in as references.
152
+ - **Extraction:** `tools/run_loco_extract.sh` streamed each NPZ from spark-0110. Every sha matched, and the
153
+ benchmark's Poisson read-out was reproduced cell by cell for all 9 arms.
154
+ - **Outputs:** `out/sepsis_loco_{summary,contrasts,per_donor}.csv`.
155
+ - **Analysis:** a multi-agent workflow ran a donor bootstrap, a confound audit and two independent verification
156
+ passes (recompute and confound lenses) over 16 claims: 3 confirmed, 13 kept with qualifications, 0 refuted. All files
157
+ are in `out/scratch_vs_lora_20261005/`, and `REPORT.md` is the full report.
158
+
159
+ **Unmeasured-gene artefact (cross-cohort scratch).** Read the cross-cohort scratch arms in the masked version.
160
+ - 46 panel genes are measured in sepsis but in none of the training cohorts. A scratch model never gets a loss on them
161
+ and puts about 91 % of its UMI there (`plans/paired_crosscohort_20261002/tools/mask_rescore.py`).
162
+ - Unmasked, its cells have a 20,606-UMI median library, and the screen's library-based thinning left the observed side
163
+ unthinned (thin 1.0). That biased its marker-state ratios down by 1.1–2×.
164
+ - **`--scope loco_masked`** (`tools/run_loco_masked_extract.sh`) zeroes the same 46 genes in every arm.
165
+ - It uses the masked scoring's labels, and the Poisson read-out was reproduced cell by cell for all 11 arms.
166
+ - Scratch then has a 1,040-UMI library and thin 0.40, in line with the pretrained arms (1,012–1,135; 0.37–0.40).
167
+ - Outputs: `out/sepsis_loco_masked_*`, bootstrap `out/scratch_vs_lora_20261005/masked_cross_bootstrap.csv`.
168
+ - The masked benchmark (`scores_masked/`) reverses the earlier "collapse" reading: scratch L1 0.50, coverage 0.33,
169
+ logFC r 0.23, against LoRA r16 at 0.49 / 0.34 / 0.11.
170
+ - The workflow analysis below used the unmasked extracts with depth matching; its cross-cohort conclusions are
171
+ re-checked on the masked data.
172
+
173
+ **Within the cohort** (gen/obs; LoRA / scratch at the same pairs):
174
+
175
+ | State | 5 pairs | 58 pairs | 58 pairs + recipes |
176
+ |---|---|---|---|
177
+ | C1Q-high | 1.07 / 1.01 | 1.05 / 0.47 | 0.63 / 0.53 |
178
+ | MS1 | 0.15 / 0.10 | 0.21 / 0.40 | 0.30 / 0.46 |
179
+ | Cycling T/NK | 1.15 / 0.51 | 0.93 / 0.42 | 0.99 / 0.48 |
180
+ | ISG-high T | 0.46 / 0.15 | 0.37 / 0.17 | 0.53 / 0.18 |
181
+ | DN2 B | 1.11 / 1.63 | 0.35 / 0.63 | 0.28 / 0.46 |
182
+ | Plasmablast (label) | 1.87 / 1.12 | 3.47 / 1.24 | 2.30 / 1.18 |
183
+ | LDG, cycling monocyte | both fail | ≤ 0.13 | |
184
+
185
+ - **Average over the 13 rare states:** no significant difference at 5, 58 or 58+recipe pairs. The CIs span about
186
+ ±0.3 log2, so this is not a demonstrated equivalence.
187
+ - **Pretrained is closer on T/NK cycling and interferon states**, in direction in 12 of 12 matched comparisons:
188
+ - the T/NK block is significant at 58 pairs;
189
+ - scratch also under-generates the ISG positive control.
190
+ - **Scratch is closer mainly where pretrained over-calls scANVI labels:** proliferating T and plasmablast. This is
191
+ specific to fold 0; pooled, LoRA-58 is 0.78× and 0.76×.
192
+ - **Scratch is also closer on DN2 at 58 pairs.**
193
+ - **C1Q-high and MS1:** neither initialisation wins consistently. C1Q-high favours pretrained at 58 pairs and MS1
194
+ favours scratch, both only under the bias-corrected interval.
195
+ - **5-pair scratch is donor-collapsed** (composition r 0.17), so its pooled ratios overstate it.
196
+ - **Disease directions kept** (25 eligible pairs, LoRA / scratch): 23 / 17 at 5 pairs, 20 / 19 at 58 pairs, 23 / 16
197
+ with recipes. Only the recipe gap is significant (7 vs 0 discordant pairs). The controls are tiny (1–2 donors per
198
+ group).
199
+
200
+ **Across cohorts, masked** (gen/obs; 82 donors; 46 never-trained genes zeroed in every arm):
201
+
202
+ | Arm | C1Q-high | MS1 | Cycling T/NK | ISG-high T | Plasmablast (label) |
203
+ |---|---|---|---|---|---|
204
+ | Own-cohort LoRA-58 | 0.51 | 0.72 | 0.52 | 0.58 | 0.76 |
205
+ | xcal (no training) | 0.08 | 0.73 | 0.48 | 1.54 | 0.78 |
206
+ | LoRA r16 | 0.04 | 0.12 | 0.13 | 1.71 | 1.38 |
207
+ | LoRA r64 | 0.06 | 0.13 | 0.19 | 1.93 | 1.01 |
208
+ | full FT | 0.08 | 0.27 | 0.36 | 1.98 | 2.21 |
209
+ | scratch, 50k | 0.10 | 0.22 | 0.10 | 1.15 | 0.49 |
210
+ | scratch, final (162k) | 0.07 | 0.16 | 0.08 | 1.10 | 0.87 |
211
+
212
+ Donor bootstrap of D = |log2| scratch − |log2| pretrained (2,000 reps):
213
+ - **Average over 13 rare states:**
214
+ - Scratch final ties LoRA r16 (−0.04 [−0.20, 0.18]) and r64 (+0.06 [−0.08, 0.22]).
215
+ - It is worse than full FT (+0.30 [0.07, 0.57]) and xcal (+0.72 [0.57, 0.95]).
216
+ - The 50k checkpoint beats r16 (−0.31 [−0.45, −0.11]) and r64 (−0.21) and ties full FT. So longer scratch training
217
+ makes the rare states worse.
218
+ - **The sepsis monocyte states fail in every model trained on other cohorts' pairs** (C1Q-high ≤ 0.10×, MS1 ≤ 0.27×).
219
+ - Only own-cohort LoRA recovers C1Q-high.
220
+ - MS1 is also recovered by xcal, with no sepsis pairs and no training.
221
+ - **Pretrained beats scratch on cycling states in every comparison:** cycling T/NK 0.08× vs 0.13–0.48× and cycling
222
+ monocytes 0.04× vs 0.06–0.26×, all CIs excluding 0. This is the one state family where pretraining clearly helps
223
+ across cohorts.
224
+ - **Scratch is closer where pretrained cross-cohort arms over-generate:** cytotoxic CD4 T, HSPC, plasmablast (label) vs
225
+ full FT, and DN2 vs LoRA. ISG-high T (1.10× vs 1.5–2.0×) points the same way but is n.s.
226
+
227
+ **Reading.** The rare states that matter for sepsis (C1Q-high, MS1) come from the target cohort's own pairs, not from
228
+ the initialisation. With those pairs, scratch matches pretrained on average, but the pretrained model:
229
+ - keeps T/NK cycling and interferon states,
230
+ - keeps donor-specific composition with 5 pairs,
231
+ - keeps more disease directions with recipes,
232
+ - trains 15–19× faster.
233
+
234
+ Without those pairs, pretrained LoRA trained on other cohorts ties scratch on average (masked) and beats it only on
235
+ cycling states. Full FT and especially calibration are better than both, and calibration needs no training.
236
+
237
+ **Limits:** one fold within the cohort, one held-out cohort across cohorts, one seed, marker-rule states, 52 + 52
238
+ state-level tests without multiplicity correction.
239
+
240
+ ## Files
241
+
242
+ - `tools/screen.py`: generated vs observed per state.
243
+ - `tools/corpus_states.py`: corpus frequency, using the same rules.
244
+ - `tools/sepsis_states.py`: Ye 2026 sepsis held-out donors (`extract` per arm from a streamed pooled NPZ, `analyze`);
245
+ per-arm marker extracts in `work/sepsis/` (small), logs in `logs/`.
246
+ - `tools/states.json`: the state rules.
247
+ - `tools/run_loco_extract.sh`: sequential bounded extracts for `--scope loco` (2026-10-05).
248
+ - `tools/run_loco_masked_extract.sh`: the same for `--scope loco_masked` (46 never-trained genes zeroed; 2026-10-05).
249
+ - `out/scratch_vs_lora_20261005/`: scratch-vs-pretrained analysis.
250
+ - `REPORT.md`
251
+ - `within_*`, `cross_*`: analyses
252
+ - `confound_*`: confound audit
253
+ - `verify_*`: two verifier passes
254
+ - `workflow_result.json`: tables and claim verdicts
255
+ - Runs were bounded `systemd-run --user` CPU units (MemoryMax 28G, no swap); logs are in `work/`.
256
+ - The generated read-out h5ads were copied back from spark-0110 to a scratch directory for the run, sha-checked
257
+ against their `.moved` markers, and deleted afterwards. So were the corpus sample h5ad and the `behcet_c1q_lora3`
258
+ corpus sample. The originals remain on spark-0110.
paper-releases/pbisc-diffusion/updates/20261005T143721Z-rare-states-scratch-masked/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/REPORT.md ADDED
@@ -0,0 +1,427 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Rare-state generation: from scratch vs pretrained (LoRA / full FT)
2
+
3
+ PBISC-Diffusion, Model 8. Ye 2026 paired sepsis cohort (paediatric + adult PBMC bulk/sc). 2026-10-05.
4
+
5
+ Sources:
6
+ - Screen outputs in `out/`: `sepsis_fold0_*.csv` and `sepsis_loco_*.csv` (method `tools/sepsis_states.py`, rules `tools/states.json`).
7
+ - Derived analyses (`within_*`, `cross_*`), the confound audit (`confound_*`) and two verifier passes (`verify_recompute_*`, `verify_confound_*`), all in `out/scratch_vs_lora_20261005/`.
8
+
9
+ The synthesis ran on CPU only and changed no existing file.
10
+
11
+ ## 1. Question
12
+
13
+ Given the same training pairs, how well does a model trained from scratch generate rare cell states? "From scratch" means random initialisation with no corpus pretraining. The comparison is the pretrained model fine-tuned with LoRA or with full fine-tuning.
14
+
15
+ ## 2. Data, metric and arms
16
+
17
+ **Metric.**
18
+ - For each arm and state, ratio = generated state % of parent / observed state % of parent.
19
+ - Observed cells are binomially thinned to the arm's generated parent median library, with one constant per arm and marker state. The two scANVI-label states are not thinned.
20
+ - A ratio of 1.00 means the observed frequency. Fidelity is |log2 ratio|.
21
+ - For a scratch-pretrained pair, D = fidelity(scratch) - fidelity(pretrained). D > 0 means pretrained is closer.
22
+ - Brackets are 95% donor-bootstrap intervals (2,000 resamples, seed 20261005). "BC" is the bias-corrected sensitivity interval.
23
+ - 15 states: 13 rare states, one positive control (ISG-high monocyte) and one negative control (platelet signal in monocytes).
24
+ - All 15 are informative in both settings; the smallest observed-thinned count is 117 within the cohort and 629 across cohorts.
25
+ - No arm generated zero cells of any state, so there are no complete misses.
26
+
27
+ **Within the cohort.** Fold 0, with 17 held-out donors: 9 adult and 3 paediatric sepsis, 2 adult and 1 paediatric healthy control, and 1 adult and 1 paediatric ICU control. Each arm generated 1,500 cells per donor from real bulk, K = 1,000.
28
+
29
+ | Arm | Initialisation | Pairs | Training time |
30
+ |---|---|---|---|
31
+ | zs__raw | pretrained, zero-shot | 0 | none |
32
+ | lora_n5__raw | pretrained + LoRA | 5 | 3.2 min |
33
+ | scratch_n5__raw | scratch | 5 | 61 min |
34
+ | real_lora__raw | pretrained + LoRA | 58 | 5.4 min |
35
+ | real_full__raw | pretrained + full FT | 58 | 4.7 min |
36
+ | scratch_full__raw | scratch | 58 | 79 min (100k-step cap) |
37
+ | lora_recipe__raw | pretrained + LoRA + recipes | 58 | 4.5 min |
38
+ | scratch_recipe__raw | scratch + recipes | 58 | 86 min |
39
+
40
+ Scratch needs 15-19x the training time of the matched pretrained arm.
41
+
42
+ **Across cohorts.** All 82 usable sepsis donors were held out: 46 adult and 15 paediatric sepsis, 7 adult and 4 paediatric healthy controls, and 6 adult and 4 paediatric ICU controls. Models were trained on ImMicro, Imperial, Giroux and Liu pairs only. Each arm generated 1,500 cells per donor.
43
+
44
+ | Arm | Initialisation / method | Training time |
45
+ |---|---|---|
46
+ | zs__raw | pretrained, zero-shot | none |
47
+ | xcalL_K1000 | pretrained zero-shot + cross-cohort calibration | none |
48
+ | locoL_lora16sat_s26750_K1000 | pretrained + LoRA r16, step-saturated | 20 min |
49
+ | locoL_lora64sat_s59000_K1000 | pretrained + LoRA r64 | 44 min |
50
+ | locoL_fullsat_s108500_K1000 (and s20000) | pretrained + full FT, saturated at 108.5k steps | 93 min |
51
+ | locoL_scratchsat_s162000_K1000 (milestones s50000/s100000/s150000) | scratch; s162000 is the selected final state (step-152,000 weights, chosen by inner-validation loss) | 127 min |
52
+ | real_lora__raw, lora_n5__raw | own-cohort references: pretrained LoRA on the sepsis cohort's own pairs, cross-fitted 5-fold (~58 or 5 pairs per fold) | fold 0: 5.4 / 3.2 min |
53
+
54
+ Scratch needs 1.4-6.4x the training time of the pretrained cross-cohort arms.
55
+
56
+ **Benchmark context.** These numbers come from the paired cross-cohort benchmark and were not re-derived here.
57
+ - The cross-cohort scratch model has precision 1.00 but coverage 0.03-0.06. LoRA r16 has coverage 0.34 and own-cohort LoRA 0.83.
58
+ - Within the cohort, scratch matched pretrained on coverage and precision. With 5 pairs, however, it lost donor-specific composition: across-donor composition r was 0.17 vs 0.70.
59
+
60
+ **Verdict rule** (both result tables).
61
+ - **pretrained** or **scratch**: that initialisation is closer in most matched comparisons. At least one difference is significant (percentile or BC interval), none is significant the other way by the percentile interval, and the ordering survives the depth and composition checks.
62
+ - **both-fail**: scratch and every pretrained fine-tuned comparator are at 0.30x or less, so any ordering compares two failures.
63
+ - **tie**: everything else.
64
+
65
+ The matched comparisons are:
66
+ - Within the cohort: 5 pairs, 58 pairs vs LoRA, 58 pairs vs full FT, and 58 pairs with recipes.
67
+ - Across cohorts: final scratch vs LoRA r16, LoRA r64, full FT 108.5k and xcal.
68
+
69
+ ## 3. Within-cohort result (same pairs, fold 0)
70
+
71
+ Values are generated/observed ratios; 1.00 is the observed frequency.
72
+
73
+ | State | zero-shot | LoRA-5 | scratch-5 | LoRA-58 | full FT-58 | scratch-58 | LoRA+recipe-58 | scratch+recipe-58 | Verdict |
74
+ |---|---|---|---|---|---|---|---|---|---|
75
+ | C1Q-high monocyte (reference) | 0.02 | 1.07 | 1.01 | 1.05 | 0.92 | 0.47 | 0.63 | 0.53 | pretrained |
76
+ | MS1 monocyte (IL1R2+) | 0.08 | 0.15 | 0.10 | 0.21 | 0.36 | 0.40 | 0.30 | 0.46 | scratch |
77
+ | Cycling monocyte (Ye 2026) | 0.09 | 0.11 | 0.06 | 0.09 | 0.11 | 0.09 | 0.10 | 0.09 | both-fail |
78
+ | Cycling T/NK | 2.52 | 1.15 | 0.51 | 0.93 | 1.34 | 0.42 | 0.99 | 0.48 | pretrained |
79
+ | Cycling activated T (CD38/HLA-DR) | 0.65 | 0.44 | 0.40 | 0.41 | 0.58 | 0.31 | 0.46 | 0.28 | tie |
80
+ | Proliferating T (label) | 3.88 | 2.49 | 1.37 | 1.49 | 1.85 | 1.13 | 1.76 | 0.98 | scratch |
81
+ | ISG-high T | 2.71 | 0.46 | 0.15 | 0.37 | 0.45 | 0.17 | 0.53 | 0.18 | pretrained |
82
+ | Cytotoxic CD4 T | 0.47 | 1.79 | 1.52 | 0.90 | 1.32 | 0.80 | 1.23 | 1.19 | tie |
83
+ | Plasmablast (label) | 1.51 | 1.87 | 1.12 | 3.47 | 3.28 | 1.24 | 2.30 | 1.18 | scratch |
84
+ | Plasmablast (markers) | 0.78 | 0.50 | 0.35 | 1.04 | 1.15 | 0.64 | 0.71 | 0.73 | tie |
85
+ | DN2 / ABC B | 1.27 | 1.11 | 1.63 | 0.35 | 0.37 | 0.63 | 0.28 | 0.46 | scratch |
86
+ | HSPC | 0.88 | 0.96 | 0.48 | 0.57 | 0.78 | 1.34 | 0.71 | 0.96 | tie |
87
+ | Granulocyte-like (LDG) | 0.14 | 0.05 | 0.13 | 0.04 | 0.04 | 0.04 | 0.03 | 0.06 | both-fail |
88
+ | (control) ISG-high monocyte, positive | 2.63 | 0.32 | 0.32 | 0.44 | 0.58 | 0.31 | 0.60 | 0.26 | tie |
89
+ | (control) Platelet signal in monocytes, negative | 0.36 | 0.84 | 0.60 | 0.55 | 0.70 | 0.39 | 0.54 | 0.45 | pretrained |
90
+ | Mean abs log2, 13 rare states | 1.76 | 1.30 | 1.52 | 1.39 | 1.27 | 1.41 | 1.39 | 1.31 | |
91
+
92
+ ### Per-state notes
93
+
94
+ **C1Q-high (pretrained, weak).**
95
+ - At 5 pairs both reach the observed level (1.01x vs 1.07x). Scratch-5, however, is donor-collapsed and over-generates CD16 monocytes; composition-standardised, the ratios are 0.61x vs 0.85x.
96
+ - At 58 pairs scratch falls to 0.47x, against LoRA 1.05x (D +1.01 [-0.26, 1.34]) and full FT 0.92x (D +0.97 [-0.10, 1.25]).
97
+ - These differences are significant only by BC and after composition standardisation (+0.82 [0.24, 1.20]; +0.83 [0.35, 1.33]). They are robust to the depth scheme.
98
+ - Fold 0 is this LoRA's best C1Q fold: 1.04x vs 0.27-0.76x in folds 1-4, and 0.50x pooled. A fold-0 LoRA trained on 40 pairs gives only 0.44x.
99
+
100
+ **MS1 (scratch, weak).**
101
+ - Both are near 0.1x at 5 pairs.
102
+ - At 58 pairs scratch is 0.40x vs LoRA 0.21x (D -0.97 [-1.44, 0.04]); this is BC-significant in every depth scheme.
103
+ - Scratch ties full FT (0.36x). With recipes it is 0.46x vs 0.30x, n.s.
104
+ - Fold 0 is this LoRA's worst MS1 fold: 0.72-1.21x elsewhere, 0.71x pooled.
105
+
106
+ **Cycling monocyte (both-fail).** 0.06-0.11x in every trained arm. No difference is significant.
107
+
108
+ **Cycling T/NK (pretrained).**
109
+ - Pretrained 0.93-1.34x vs scratch 0.42-0.51x. D > 0 in 4 of 4 comparisons.
110
+ - Significant vs 58-pair LoRA (+1.15 [0.20, 1.78]), and still significant after T-subtype composition standardisation (+1.00 [0.15, 1.59]).
111
+ - Fold 0 has the lowest observed level of the five folds. The same LoRA gives 0.34-0.66x in the other folds.
112
+
113
+ **Cycling activated T (tie).**
114
+ - Every arm under-generates (0.28-0.58x).
115
+ - Under the screen's scoring, pretrained is closer and significantly so vs full FT (+0.87 [0.24, 1.40]).
116
+ - However, 82-94% of the pretrained arms' cycling-rule T cells sit inside their over-generated proliferating-T label (observed 72-74%).
117
+ - After composition standardisation, scratch is significantly closer at 5 pairs (-0.59 [-1.03, -0.17]) and the full-FT advantage is gone (+0.36 [-0.14, 0.75]).
118
+
119
+ **Proliferating T, label (scratch, specific to fold 0).**
120
+ - The pretrained models over-generate this label: 1.49-2.49x vs 0.98-1.37x for scratch. Scratch is significantly closer in 3 of 4 comparisons.
121
+ - This is not better biology. Fewer scratch label cells pass the cycling-marker rule (16-23% vs 23-28%; observed 36-37%). That gap is significant only at 58 pairs.
122
+ - In folds 1-4 the same 58-pair LoRA under-generates the label (0.49-1.09x; 0.78x pooled).
123
+
124
+ **ISG-high T (pretrained).**
125
+ - Pretrained 0.37-0.53x vs scratch 0.15-0.18x. D > 0 in 4 of 4; significant with recipes (+1.52 [0.08, 2.49]).
126
+ - The ordering holds in every depth scheme and after composition standardisation.
127
+ - Both under-generate. Scratch also under-generates the ISG positive control and loses its disease directions, so this is a general interferon gap in scratch.
128
+
129
+ **Cytotoxic CD4 T (tie).**
130
+ - 0.80-1.79x in every trained arm, with no fidelity difference.
131
+ - Scratch-5 loses donor tracking (Spearman -0.40 vs 0.74) and reverses two contrasts.
132
+
133
+ **Plasmablast, label (scratch, specific to fold 0).**
134
+ - Pretrained over-generates (1.87-3.47x vs 1.12-1.24x) because it makes too many plasma cells: 1.25-1.89% of cells vs 0.64% observed, against 0.61-0.67% for scratch.
135
+ - The difference is significant only vs full FT (-1.40 [-2.02, -0.13]), and that significance is lost under donor-mean weighting.
136
+ - Pooled over all 82 donors, the 58-pair LoRA gives 0.76x.
137
+
138
+ **Plasmablast, markers (tie).**
139
+ - Under the screen's scoring, pretrained is closer at 58 pairs (1.04-1.15x vs 0.64x).
140
+ - Once depth is matched, pretrained overshoots (1.49-1.90x) and scratch becomes closer.
141
+ - At 5 pairs pretrained is robustly closer.
142
+
143
+ **DN2 / ABC B (scratch at 58 pairs).**
144
+ - At 58 pairs scratch is 0.46-0.63x vs pretrained 0.28-0.37x. This is robust in every depth scheme and significant with recipes (-0.70 [-1.21, -0.08]).
145
+ - At 5 pairs LoRA is closer (BC only), and scratch-5 strongly reverses the adult contrast.
146
+
147
+ **HSPC (tie).** Each arm generated only 13-35 cells, so the intervals are wide.
148
+
149
+ **LDG (both-fail).** 0.03-0.13x in every trained arm. The two significant "scratch closer" calls compare two failures.
150
+
151
+ **Controls.**
152
+ - ISG-high monocyte: no significant difference.
153
+ - Platelet signal: pretrained is closer in 4 of 4, significantly vs full FT (+0.83 [0.45, 1.19]). This is a technical signal, so being closer is not a biological win.
154
+
155
+ ### Aggregate
156
+
157
+ The pre-specified 13-state mean shows no significant difference:
158
+ - 5 pairs: D +0.22 [-0.08, 0.41] (BC [0.01, 0.46]).
159
+ - 58 pairs: +0.02 [-0.35, 0.25] vs LoRA and +0.14 [-0.14, 0.41] vs full FT.
160
+ - Recipes: -0.09 [-0.38, 0.18].
161
+ - State-level tests: 3 of 52 favour pretrained, 7 favour scratch and 42 are n.s.; with BC intervals it is 9 vs 11.
162
+
163
+ This is weaker than "equally faithful", for four reasons:
164
+ - **Non-significance, not equivalence.** The intervals span about +-0.3 log2.
165
+ - **The mean hides a T/NK advantage for pretrained.** Over the five T/NK states, pretrained is significantly closer at 58 pairs:
166
+ - vs LoRA +0.48 [0.07, 0.88], significant in all 7 scoring variants;
167
+ - vs full FT +0.45 [0.01, 1.02];
168
+ - with recipes +0.48 [0.01, 0.91].
169
+ Over the 11 marker states, full FT is significantly closer (+0.35 [0.02, 0.62]) in 4 of 7 variants.
170
+ - **The 5-pair BC result is a depth/composition artifact.** At common depth D is +0.10 [-0.23, 0.35]; after composition standardisation it is -0.00.
171
+ - **Fold 0 is LoRA-5's best fold.** Its mean abs log2 is 1.26-1.30 here vs 1.53-2.94 in folds 1-4.
172
+
173
+ Zero-shot (1.76) is the least faithful arm. The two 58-pair scratch arms beat it (D -0.35 [-0.66, -0.13] and -0.46 [-0.73, -0.24]), and the gain comes mostly from C1Q-high. Scratch-5 does not beat it significantly (D -0.24 [-0.52, 0.01]).
174
+
175
+ **Donor tracking.** Mean Spearman, pretrained vs scratch:
176
+
177
+ | Comparison | Pretrained | Scratch | Difference |
178
+ |---|---|---|---|
179
+ | 5 pairs | 0.30 | 0.19 | n.s. |
180
+ | LoRA-58 | 0.29 | 0.27 | n.s. |
181
+ | Full FT-58 | 0.43 | 0.27 | +0.15, BC [0.003, 0.33] |
182
+ | Recipes | 0.40 | 0.36 | n.s. |
183
+
184
+ No difference is detectable, both track poorly, and there is a small tilt towards pretrained. A perfect generator would reach 0.78-0.85.
185
+
186
+ ## 4. Cross-cohort result (no sepsis pairs in training)
187
+
188
+ Values are generated/observed ratios. The column "scratch 162k at r16 depth" scores the same scratch cells against observed cells thinned for LoRA r16.
189
+
190
+ | State | own LoRA-58 | own LoRA-5 | zero-shot | xcal | LoRA r16 | LoRA r64 | full FT 108.5k | scratch 162k | scratch 162k at r16 depth | scratch 50k | Verdict |
191
+ |---|---|---|---|---|---|---|---|---|---|---|---|
192
+ | C1Q-high monocyte (reference) | 0.50 | 0.53 | 0.03 | 0.07 | 0.03 | 0.06 | 0.09 | 0.07 | 0.08 | 0.09 | both-fail |
193
+ | MS1 monocyte (IL1R2+) | 0.71 | 0.64 | 0.08 | 0.72 | 0.12 | 0.11 | 0.27 | 0.10 | 0.16 | 0.16 | both-fail |
194
+ | Cycling monocyte (Ye 2026) | 0.23 | 0.30 | 0.10 | 0.25 | 0.06 | 0.07 | 0.11 | 0.02 | 0.04 | 0.06 | both-fail |
195
+ | Cycling T/NK | 0.54 | 0.29 | 0.83 | 0.46 | 0.15 | 0.17 | 0.36 | 0.05 | 0.06 | 0.06 | pretrained |
196
+ | Cycling activated T (CD38/HLA-DR) | 0.30 | 0.16 | 0.36 | 0.25 | 0.10 | 0.14 | 0.23 | 0.05 | 0.07 | 0.08 | both-fail |
197
+ | Proliferating T (label) | 0.78 | 0.62 | 1.96 | 0.64 | 0.79 | 1.04 | 1.13 | 0.53 | 0.53 | 0.44 | pretrained |
198
+ | ISG-high T | 0.57 | 0.39 | 1.74 | 1.59 | 1.66 | 1.93 | 2.05 | 0.60 | 1.00 | 0.70 | tie |
199
+ | Cytotoxic CD4 T | 1.35 | 1.06 | 0.43 | 2.02 | 1.41 | 1.70 | 1.61 | 0.94 | 1.07 | 0.86 | scratch |
200
+ | Plasmablast (label) | 0.76 | 0.41 | 0.39 | 0.78 | 1.38 | 1.01 | 2.21 | 0.87 | 0.87 | 0.49 | scratch |
201
+ | Plasmablast (markers) | 0.33 | 0.19 | 0.28 | 0.37 | 0.78 | 0.69 | 1.47 | 0.34 | 0.53 | 0.26 | pretrained |
202
+ | DN2 / ABC B | 0.31 | 0.42 | 1.49 | 0.30 | 0.17 | 0.18 | 0.28 | 0.16 | 0.24 | 0.16 | both-fail |
203
+ | HSPC | 0.40 | 0.71 | 0.55 | 1.68 | 1.62 | 2.96 | 2.97 | 1.31 | 1.47 | 0.96 | scratch |
204
+ | Granulocyte-like (LDG) | 0.07 | 0.04 | 0.24 | 0.06 | 0.01 | 0.02 | 0.02 | 0.01 | 0.02 | 0.04 | both-fail |
205
+ | (control) ISG-high monocyte, positive | 0.61 | 0.55 | 1.80 | 1.42 | 1.31 | 1.45 | 1.77 | 0.47 | 0.95 | 0.53 | tie |
206
+ | (control) Platelet signal in monocytes, negative | 0.56 | 0.57 | 0.28 | 0.19 | 0.18 | 0.18 | 0.36 | 0.08 | 0.17 | 0.13 | pretrained |
207
+ | Mean abs log2, 13 rare states | 1.29 | 1.54 | 1.82 | 1.53 | 2.32 | 2.21 | 1.92 | 2.62 | 2.21 | 2.33 | |
208
+
209
+ ### Per-state notes
210
+
211
+ **C1Q-high (both-fail).** Every cross-cohort arm is at 0.03-0.09x, while own-cohort LoRA reaches 0.50-0.53x. Scratch (0.07x) is significantly closer than r16 (0.03x), but both fail.
212
+
213
+ **MS1 (both-fail).**
214
+ - Scratch (0.10x), r16 (0.12x) and r64 (0.11x) do not differ; after marker-depth matching it is 0.14x vs 0.13x.
215
+ - Full FT is modestly but robustly higher (0.27x).
216
+ - xcal reaches 0.72x [0.55, 1.05] with no sepsis pairs and no training. That is as high as own-cohort LoRA.
217
+
218
+ **Cycling monocyte (both-fail).**
219
+ - 0.02-0.30x in every arm, own-cohort LoRA included.
220
+ - Scratch is lowest: 21 of 20,808 monocytes.
221
+ - At matched depth, pretrained stays closer only vs full FT and xcal.
222
+
223
+ **Cycling T/NK (pretrained; confirmed).**
224
+ - Scratch makes 35 cycling cells among 72,018 T/NK cells (0.05x), vs 0.15-0.46x in every pretrained arm.
225
+ - Pretrained is significantly closer in all 4 comparisons. This survives matched depth (vs r16, D +1.23 [0.61, 1.91]), detection-matched depth and every leave-one-donor-out run.
226
+
227
+ **Cycling activated T (both-fail; pretrained less bad).** Scratch is at 0.05x vs 0.10-0.25x for the pretrained arms. At matched depth, the pretrained arms are significantly closer vs r64, full FT and xcal.
228
+
229
+ **Proliferating T, label (pretrained, weak).**
230
+ - Scratch 0.53x vs r16 0.79x (D +0.57 [0.09, 0.80]). Differences vs r64, full FT and xcal are n.s.
231
+ - About 5% of label cells carry 2+ cycling genes in scratch or r16, vs 37% of observed cells. This is a label-frequency result, not cycling evidence.
232
+
233
+ **ISG-high T (tie).**
234
+ - Pretrained over-generates (1.35-2.05x) and scratch is at 0.60x.
235
+ - At r16 depth scratch is 1.00x; detection-matched it is 0.67x.
236
+ - All differences are n.s.
237
+
238
+ **Cytotoxic CD4 T (scratch).**
239
+ - Scratch (0.94x) is significantly closer than xcal (2.02x), and at matched depth closer than r64 (1.70x) and full FT (1.61x).
240
+ - But scratch, r16, r64 and full FT all reverse the adult and all-vs-all contrasts.
241
+ - Scratch also tracks donors worse than full FT (Spearman 0.40 vs 0.62).
242
+
243
+ **Plasmablast, label (scratch, weak).**
244
+ - Scratch (0.87x) is as close as r64 (1.01x).
245
+ - It is significantly closer only than the over-generating full FT (2.21x), and that call holds in only 61 of 82 leave-one-donor-out runs.
246
+
247
+ **Plasmablast, markers (pretrained).**
248
+ - Scratch 0.34x vs r16 0.78x, r64 0.69x and full FT 1.47x. This survives marker-depth matching (0.47x vs 0.58-1.21x).
249
+ - xcal (0.37x) is no better than scratch, and own-cohort LoRA-58 is also low (0.33x).
250
+
251
+ **DN2 / ABC B (both-fail).** All cross-cohort arms are at 0.16-0.30x (own-cohort 0.31-0.42x). The ordering flips with the depth reference.
252
+
253
+ **HSPC (scratch).**
254
+ - Scratch (1.31x) is significantly closer than r64 and full FT (both about 2.96x) at both depth references.
255
+ - The difference is n.s. vs r16 (1.62x) and xcal (1.68x).
256
+ - It depends on the checkpoint: s100000 was at 2.58x.
257
+
258
+ **LDG (both-fail).** Fine-tuned cross-cohort arms are at 0.01-0.02x; scratch generated 35 of 123,000 cells.
259
+
260
+ **Controls.**
261
+ - ISG-high monocyte: n.s. Scratch is 0.95x at r16 depth.
262
+ - Platelet signal: pretrained is closer, robust to depth matching. This is a technical signal.
263
+
264
+ ### Aggregate (confirmed)
265
+
266
+ Under the screen's scoring, scratch is further from observed than every pretrained cross-cohort arm:
267
+
268
+ | Comparison | D, screen scoring | D, matched depth |
269
+ |---|---|---|
270
+ | vs LoRA r16 | +0.30 [0.09, 0.52] | -0.11 [-0.24, 0.11] |
271
+ | vs LoRA r64 | +0.41 [0.17, 0.62] | -0.04 [-0.21, 0.13] |
272
+ | vs full FT | +0.69 [0.42, 1.00] | +0.25 [0.03, 0.54] |
273
+ | vs xcal | +1.08 [0.92, 1.29] | +0.68 [0.55, 0.89] |
274
+
275
+ - At matched depth the gap to LoRA vanishes.
276
+ - The deficit vs full FT is marginal and carried by the cycling and MS1 states.
277
+ - xcal has the lowest mean error of any cross-cohort arm (1.53, vs 1.75-2.62 for the others).
278
+
279
+ ### Scratch training length
280
+
281
+ The final checkpoint is further from observed than the 50k checkpoint: D +0.29 [0.15, 0.43].
282
+ - Longer training moved C1Q-high, MS1, cycling monocytes, cycling activated T and LDG further away.
283
+ - It improved only the two plasmablast states and proliferating T (label).
284
+ - At matched depth, s50000 beats r16 (D -0.39 [-0.54, -0.17]) while s162000 only ties it.
285
+ - Over the same steps the library inflated from 13,891 to 20,606 UMIs and coverage fell from 0.063 to 0.032. This is a co-trend across four checkpoints, not a tested cause.
286
+
287
+ ### Donor tracking
288
+
289
+ - No state differs between scratch and r16 or r64 (0 of 13 each), but this is a low-power null.
290
+ - Full FT and xcal each track 2 states better than scratch.
291
+ - Own-cohort LoRA-58 tracks best on average (mean rho 0.36), although xcal tracks MS1 better.
292
+
293
+ ## 5. Contrasts
294
+
295
+ ### Within the cohort (anecdotal: 2 adult and 1 paediatric healthy control)
296
+
297
+ Directions kept, out of 25 eligible state-contrast pairs:
298
+
299
+ | Setting | Pretrained | Scratch |
300
+ |---|---|---|
301
+ | 5 pairs | LoRA-5: 23 | 17 |
302
+ | 58 pairs | LoRA-58: 20; full FT-58: 20 | 19 |
303
+ | 58 pairs + recipes | 23 | 16 |
304
+
305
+ Zero-shot keeps 21.
306
+
307
+ - Only the recipe gap is significant: 7 vs 0 discordant pairs, p = 0.016, uncorrected and not independent.
308
+ - At 58 pairs the gap is 2 vs 1 and 3 vs 2 discordant pairs (p = 1).
309
+ - At 5 pairs, scratch has 3 strong reversals: DN2 adult (+4.74 vs observed -3.16 pp) and cytotoxic CD4 T adult and all-sepsis. LoRA-5 has 2.
310
+ - Eight of the 25 pairs rest on a single paediatric control.
311
+
312
+ ### Across cohorts (control groups of 7, 4 and 21)
313
+
314
+ Directions kept, out of 21 common pairs:
315
+
316
+ | Arm | Kept |
317
+ |---|---|
318
+ | Scratch | 14 |
319
+ | LoRA r16 | 11 |
320
+ | LoRA r64 | 10 |
321
+ | Full FT | 16 |
322
+ | xcal | 19 |
323
+ | Own-cohort LoRA-58 | 19 |
324
+
325
+ Scratch, r16 and r64 are not distinguishable from coin flipping.
326
+
327
+ Kept effects are compressed. The share of the observed difference that the median kept pair reproduces is:
328
+
329
+ | Arm | Share reproduced |
330
+ |---|---|
331
+ | Scratch | 4% (7% at r16 depth) |
332
+ | LoRA and full FT | 13-15% |
333
+ | xcal | 23% |
334
+ | Own-cohort LoRA-58 | 34% |
335
+
336
+ - On pairs kept by both arms, at matched depth, scratch is only about 1.3x more compressed than LoRA (n.s.).
337
+ - Compression relative to full FT, xcal and own-cohort LoRA is robust.
338
+ - MS1, adult sepsis vs healthy control: scratch reproduces 6%, r16 10%, full FT 25%, xcal 50% and own-cohort LoRA-58 62%.
339
+ - C1Q-high: scratch reproduces 1-4%, r16 reverses all three contrasts, and own-cohort LoRA-58 reproduces 30-34%.
340
+
341
+ ## 6. Confounds and caveats
342
+
343
+ 1. **Cross-cohort depth confound (high).**
344
+ - Scratch cells carry 20,606-UMI libraries but only 236 detected genes, and about 0.1% of their counts fall on marker genes. Their marker detection matches the ~1,000-UMI pretrained arms.
345
+ - The screen compared scratch with unthinned observed cells, so its marker-state ratios are biased down by 1.1-2.0x (up to 3.2x with detection matching).
346
+ - Library thinning is also imperfect for the pretrained arms. Every absolute cross-cohort ratio therefore carries a shared bias.
347
+ 2. **V1 thinning is invalid for cross-cohort scratch.** It removes ~95% of marker counts. Its "complete misses" are artifacts and should not be quoted.
348
+ 3. **Cross-cohort scratch count profiles are unrealistic.** Libraries inflate, cell-to-cell spread is compressed (q90/q10 2.0 vs 7.3 observed) and coverage is 0.03. The full generated matrices were not examined.
349
+ 4. **Scratch-5 is donor-collapsed** (composition r 0.17 vs 0.70). Its pooled ratios overstate donor-level fidelity.
350
+ 5. **One fold, one model and one seed within the cohort.**
351
+ - Fold 0 favours LoRA-5, and LoRA-58 on C1Q-high, but disfavours LoRA-58 on MS1.
352
+ - It also has the lowest observed cycling-T and plasmablast levels.
353
+ - Scratch exists only for fold 0.
354
+ 6. **Label states depend on scANVI calls.** The pretrained arms over-generate plasma cells and proliferating-labelled T cells.
355
+ 7. **Controls.**
356
+ - Scratch's ISG deficit reflects a general interferon gap.
357
+ - "Closer to observed" also rewards technical signal, as the platelet control shows.
358
+ 8. **Zero-shot ISG overshoot is mostly depth.** ISG-high T goes from 2.71x to 0.76x after matching.
359
+ 9. **Statistics.**
360
+ - 17 donors within the cohort.
361
+ - 104 state-level tests with no multiplicity correction.
362
+ - Within-cohort contrasts rest on 1-2 controls.
363
+ 10. **Checkpoints.** The scratch checkpoint was chosen by validation loss, and the 50k checkpoint is closer. The within-cohort 58-pair scratch run hit its 100k-step cap.
364
+
365
+ ### Statements dropped after verification
366
+
367
+ - **"Pairs on the pretrained model, not pretraining alone, recover the monocyte states."** False for MS1, since xcal reaches 0.72x. The pretrained model is also not shown to be necessary: within the cohort, scratch with 58 pairs reaches C1Q 0.47x and MS1 0.40-0.46x.
368
+ - **"Scratch compression is 3-4x worse than LoRA."** It is about 1.3x on shared pairs at matched depth, and n.s.
369
+ - **"Only plasmablasts improve with longer scratch training."** Proliferating T (label) improves too.
370
+ - **"The only significant scratch wins are HSPC, cytotoxic CD4 T and plasmablast label."** Plasmablast markers vs xcal at matched depth is another.
371
+ - **"Zero-shot is closer for cycling activated T."** This is a depth/composition artifact.
372
+ - **"Pretrained is better on T cycling and interferon states in every comparison."** This fails for cycling activated T after composition standardisation.
373
+ - **"Donor tracking is similar."** The data support only "no detectable difference".
374
+ - **"Corrected ISG states are about 1.0x."** True only at the r16 reference.
375
+
376
+ ## 7. Verdict
377
+
378
+ **With the same target-cohort pairs, scratch matches pretrained on the pre-specified 13-state average, but not everywhere.**
379
+ - The difference on the average is not significant at 5 or 58 pairs, and equivalence is not shown.
380
+ - Pretrained is better on proliferating and interferon T/NK states: cycling T/NK and ISG-high T, with the T/NK block significantly closer at 58 pairs.
381
+ - Scratch collapses donors with 5 pairs and needs 15-19x the training time.
382
+ - Scratch is closer mainly where the pretrained models over-call fold-0 scANVI labels, and on DN2 and the fold-specific MS1 result at 58 pairs.
383
+ - Both fail LDG and cycling monocytes.
384
+
385
+ **Without target-cohort pairs, initialisation is not the main factor.**
386
+ - Every cross-cohort fine-tuned model, scratch or pretrained, fails the sepsis monocyte states: C1Q-high at 0.09x or less and MS1 at 0.27x or less. Own-cohort LoRA reaches about 0.5x and 0.7x.
387
+ - After the depth correction, scratch ties LoRA on the aggregate.
388
+ - Scratch is clearly worse on cycling T/NK (0.05x vs 0.15-0.46x; confirmed). It also trails full FT and xcal; xcal has the lowest error of any cross-cohort arm and brings MS1 to 0.72x.
389
+ - Scratch is closer only where the pretrained arms over-generate (HSPC, cytotoxic CD4 T).
390
+ - The scratch generator drifts with longer training: libraries inflate, coverage reaches 0.03 and the monocyte states get worse.
391
+
392
+ **Bottom line.**
393
+ - Pretraining alone does not produce the sepsis monocyte states: zero-shot gives C1Q-high 0.03x and MS1 0.08x.
394
+ - Within the cohort, its own pairs recover C1Q-high under either initialisation.
395
+ - Across cohorts, only own-cohort pairs recover C1Q-high. MS1 is also recovered by calibrating the pretrained model.
396
+ - For rare states, pretraining adds four things:
397
+ - better proliferating T/NK states;
398
+ - donor-specific composition with few pairs;
399
+ - 15-19x shorter training;
400
+ - when there are no target pairs, a training-free calibrated model with the lowest average error of any cross-cohort arm.
401
+
402
+ **Open points.** No new runs were made. These remain untested:
403
+ - scratch on folds 1-4 and with a second seed;
404
+ - scratch checkpoint selection by rare-state fidelity;
405
+ - scratch combined with the xcal calibration.
406
+
407
+ **Archive.** No pbisc-diffusion delta was published by this subagent.
408
+
409
+
410
+ ## Addendum (coordinator, 2026-10-05): masked cross-cohort re-analysis supersedes the unmasked cross-cohort numbers
411
+
412
+ The cross-cohort scratch model puts ~91 % of its UMI on 46 genes that no training cohort measured (it is never trained
413
+ on them; plans/paired_crosscohort_20261002/tools/mask_rescore.py). That is the source of its 20,606-UMI library, its
414
+ unthinned observed side (thin 1.0) and the 'coverage 0.03' benchmark reading. `tools/sepsis_states.py --scope
415
+ loco_masked` re-extracted all 11 cross-cohort arms with those genes zeroed (labels from the masked scoring, Poisson
416
+ read-out reproduced cell by cell); scratch then has a 1,040-UMI library and thin 0.40 like the pretrained arms.
417
+ Bootstrap on the masked per-donor table (masked_cross_bootstrap.csv; same estimator as above):
418
+ - 13-state mean |log2|: scratch final 2.24 vs LoRA r16 2.28 (D -0.04 [-0.20, 0.18]), r64 2.18 (+0.06 [-0.08, 0.22]),
419
+ full FT 1.95 (+0.30 [0.07, 0.57]), xcal 1.52 (+0.72 [0.57, 0.95]); scratch 50k beats r16 (-0.31 [-0.45, -0.11]) and
420
+ r64 (-0.21 [-0.37, -0.03]) and ties full FT.
421
+ - Cycling T/NK: scratch 0.08x vs r16 0.13x, r64 0.19x, full 0.36x, xcal 0.48x - pretrained closer in all four (CIs
422
+ exclude 0); cycling monocytes likewise (0.04x vs 0.06-0.26x).
423
+ - C1Q-high <= 0.10x and MS1 <= 0.27x in every cross-cohort fine-tuned arm; xcal recovers MS1 (0.73x) with no training.
424
+ - Scratch is closer for cytotoxic CD4 T, HSPC, DN2 (vs LoRA) and plasmablast label (vs full FT); ISG-high T 1.10x vs
425
+ 1.5-2.0x (n.s.).
426
+ These agree with the depth-matched conclusions of the verified claims (cross-2, cross-3) and replace the screen-scoring
427
+ cross-cohort numbers in the tables above.
paper-releases/pbisc-diffusion/updates/20261005T143721Z-rare-states-scratch-masked/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/run_loco_masked_extract.sh ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Rare-state extracts for the masked cross-cohort arms (scope loco_masked of tools/sepsis_states.py), CPU only, one
3
+ # bounded unit per arm in sequence (MemoryMax 28G, no swap; waits for MemAvailable >= 60 GiB). The source NPZ named
4
+ # by each masked receipt (derived_from) is read locally when present, else streamed from spark-0110; the tool checks
5
+ # its sha against source_sha256, zeroes the masked genes and reproduces the masked scoring's Poisson read-out.
6
+ # usage: run_loco_masked_extract.sh ARM [ARM ...] (2026-10-05)
7
+ set -uo pipefail
8
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
9
+ R=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004
10
+ GM=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002/generated_masked/ye2026_sepsis/hoL_ye2026_sepsis
11
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
12
+ fail=0
13
+ for arm in "$@"; do
14
+ if [[ -s $R/work/sepsis/loco_masked/$arm.npz ]]; then echo "$(date -Is) $arm: extract exists; skipped"; continue; fi
15
+ src=$(python3 -c "import json,sys;print(json.load(open(sys.argv[1]))['derived_from'])" "$GM/$arm.log")
16
+ if [[ -f $src ]]; then reader="cat $src"; else reader="ssh spark-0110 cat $src"; fi
17
+ until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 60 )); do sleep 60; done
18
+ unit=rare-locom-extract-$(echo "$arm" | tr '_' '-' | cut -c1-50)
19
+ echo "$(date -Is) $arm: $reader"
20
+ systemd-run --user --unit="$unit" --wait --collect --quiet --working-directory="$R" \
21
+ -p MemoryMax=28G -p MemorySwapMax=0 -p CPUQuota=400% -p Nice=10 \
22
+ -p StandardOutput=file:"$R/logs/locom_extract_$arm.log" -p StandardError=file:"$R/logs/locom_extract_$arm.err" \
23
+ --setenv=CUDA_VISIBLE_DEVICES= --setenv=PYTHONNOUSERSITE=1 --setenv=PYTHONDONTWRITEBYTECODE=1 \
24
+ --setenv=OMP_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
25
+ /bin/bash -c "set -o pipefail; $reader | $PY tools/sepsis_states.py --scope loco_masked extract $arm" \
26
+ && echo "$(date -Is) $arm: $(cat "$R/logs/locom_extract_$arm.log")" \
27
+ || { echo "$(date -Is) $arm: FAILED (see logs/locom_extract_$arm.err)"; fail=$((fail+1)); }
28
+ done
29
+ echo "$(date -Is) done; failed=$fail"
paper-releases/pbisc-diffusion/updates/20261005T143721Z-rare-states-scratch-masked/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/sepsis_states.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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|loco] (default pooled; fold0 = fold-0 test donors incl. the 2026-10-05 no-pretraining arms;
12
+ loco = the 82 donors as held-out cohort of plans/paired_crosscohort_20261002, split hoL_ye2026_sepsis: arms
13
+ locoL_<tag>_K1000 / xcalL_K1000, receipts generated/ye2026_sepsis/hoL_ye2026_sepsis/K1000_<tag>.log /
14
+ xcal_K1000.log, labels scores/ye2026_sepsis/<arm>/arms/<arm>/; added 2026-10-05 for scratch vs pretrained;
15
+ loco_masked = the same arms rescored with the 46 never-trained genes zeroed, see SCOPES)
16
+ extract ARM < NPZ bytes on stdin (ssh spark-0110 cat .../pooled/ARM.npz | sepsis_states.py extract ARM)
17
+ sha256 of the stream must equal the pooled receipt (generated/ye2026_sepsis/pooled/ARM.log, output_sha256).
18
+ Writes work/sepsis/ARM.npz: per labelled cell, counts of every marker gene of tools/states.json, the library on
19
+ the dataset's measured panel genes, donor, AIFI L1/L2. Nothing large is written.
20
+ analyze ARM [ARM ...]
21
+ Observed side: every cell of the scored donors (data/ye2026_sepsis/cells_panel6k.npz, benchmark observed labels).
22
+ States, thinning and counts exactly as tools/screen.py (one thinning constant per arm and marker state: observed
23
+ parent median library -> generated parent median library on the measured panel genes; label states as they
24
+ are). Per arm and state: "X of N" on both sides, generated / observed, Spearman over donors, and contrasts
25
+ (adult sepsis vs adult HC, paediatric sepsis vs paediatric HC, all sepsis vs all controls incl. ICU controls).
26
+ Outputs: out/sepsis_{summary,contrasts,per_donor}.csv
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import hashlib
31
+ import importlib.util
32
+ import io
33
+ import json
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+ import pandas as pd
39
+ import scipy.sparse as sp
40
+ from scipy.stats import spearmanr
41
+
42
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
43
+ from screen import call_state, parent_mask, state_cols # noqa: E402
44
+
45
+ PLAN = Path(__file__).resolve().parents[1]
46
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
47
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
48
+ DATA = FT / "data/ye2026_sepsis"
49
+ # scope -> (generated dir with <arm>.npz + receipt <arm>.log, scores dirs searched in order for arms/<arm>/, work dir,
50
+ # output prefix). "pooled": the cross-fitted 82-donor arms; "fold0": the fold-0 test donors, incl. the
51
+ # no-pretraining (--init random) arms of 2026-10-05 scored in fold0_scratch_20261005.
52
+ SCOPES = {
53
+ "pooled": (FT / "generated/ye2026_sepsis/pooled", [FT / "scores/ye2026_sepsis/pooled/arms"],
54
+ PLAN / "work/sepsis", "sepsis"),
55
+ "fold0": (FT / "generated/ye2026_sepsis/fold0",
56
+ [FT / "scores/ye2026_sepsis/fold0_scratch_20261005/arms", FT / "scores/ye2026_sepsis/fold0/arms"],
57
+ PLAN / "work/sepsis/fold0", "sepsis_fold0"),
58
+ "loco": (M8 / "plans/paired_crosscohort_20261002/generated/ye2026_sepsis/hoL_ye2026_sepsis",
59
+ [M8 / "plans/paired_crosscohort_20261002/scores/ye2026_sepsis/{arm}/arms"],
60
+ PLAN / "work/sepsis/loco", "sepsis_loco"),
61
+ # loco_masked (2026-10-05): the same held-out arms after tools/mask_rescore.py of the cross-cohort plan zeroed the 46
62
+ # genes measured in sepsis but in no training cohort (a scratch model is never trained on them and puts ~91 % of its
63
+ # UMI there). Receipt = generated_masked/.../<arm>.log (source sha + masked gene ids); the source NPZ is streamed,
64
+ # sha-checked against source_sha256, the masked genes are zeroed, and the Poisson read-out must reproduce the masked
65
+ # scoring's umi_scoring_genes cell by cell; labels from scores_masked/ye2026_sepsis/<arm>/arms/<arm>/.
66
+ "loco_masked": (M8 / "plans/paired_crosscohort_20261002/generated_masked/ye2026_sepsis/hoL_ye2026_sepsis",
67
+ [M8 / "plans/paired_crosscohort_20261002/scores_masked/ye2026_sepsis/{arm}/arms"],
68
+ PLAN / "work/sepsis/loco_masked", "sepsis_loco_masked"),
69
+ }
70
+
71
+
72
+ def npz_stem(arm: str, scope: str) -> str:
73
+ """File stem of an arm's generated NPZ / receipt. pooled, fold0: the arm name. loco: the cross-cohort scorer's
74
+ naming (score_pending.sh): locoL_<tag>_K<K> <- K<K>_<tag>.npz, xcalL_K<K> <- xcal_K<K>.npz."""
75
+ if scope != "loco":
76
+ return arm # pooled, fold0, loco_masked (generated_masked receipts are named after the arm)
77
+ if arm.startswith("xcalL_K"):
78
+ return "xcal_" + arm[len("xcalL_"):]
79
+ if arm.startswith("locoL_") and "_K" in arm:
80
+ tag, k = arm[len("locoL_"):].rsplit("_K", 1)
81
+ return f"K{k}_{tag}"
82
+ raise SystemExit(f"{arm}: not a hoL arm name (locoL_<tag>_K<K> or xcalL_K<K>)")
83
+ REF = FT / "scoring_cache/ye2026_sepsis/reference.npz"
84
+ OBS_LABELS = FT / "scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet"
85
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
86
+ "canonical_genes.tsv")
87
+ POISSON_PY = M8 / "plans/aifi_scanvi_rebuild_20260916/poisson_readout.py"
88
+ POISSON_SEED = 20260916
89
+ THIN_SEED = 20261004
90
+ CONTRASTS = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
91
+ ("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
92
+ ("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
93
+ ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
94
+
95
+
96
+ def load_poisson():
97
+ spec = importlib.util.spec_from_file_location("poisson_readout", POISSON_PY)
98
+ mod = importlib.util.module_from_spec(spec)
99
+ spec.loader.exec_module(mod)
100
+ return mod
101
+
102
+
103
+ def marker_genes(states: list[dict]) -> list[str]:
104
+ out = []
105
+ for st in states:
106
+ for g in st.get("genes", []) + [x for grp in st.get("require_any", []) for x in grp] + st.get("exclude", []):
107
+ if g not in out:
108
+ out.append(g)
109
+ return out
110
+
111
+
112
+ def panel_setup(states: list[dict]) -> tuple[np.ndarray, np.ndarray, list[str], np.ndarray]:
113
+ """6k panel ids, measured-gene mask (any sample of the dataset), marker symbols present, their panel columns."""
114
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
115
+ panel = d["panel_gene_ids"].astype(str)
116
+ measured = d["panel_measured"].any(0)
117
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
118
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
119
+ pos = {g: i for i, g in enumerate(panel)}
120
+ syms = [g for g in marker_genes(states) if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
121
+ return panel, measured, syms, np.asarray([pos[sym2id[g]] for g in syms], dtype=np.int64)
122
+
123
+
124
+ def cmd_extract(arm: str, scope: str) -> None:
125
+ gen_dir, score_dirs, work, _ = SCOPES[scope]
126
+ score_dirs = [Path(str(d).replace("{arm}", arm)) for d in score_dirs]
127
+ sdir = next((d / arm for d in score_dirs if (d / arm / "generated_cells.parquet").exists()), None)
128
+ if sdir is None:
129
+ raise SystemExit(f"{arm}: no scored labels in {score_dirs}")
130
+ states = json.loads((PLAN / "tools/states.json").read_text())
131
+ panel, measured, syms, cols = panel_setup(states)
132
+ raw = sys.stdin.buffer.read()
133
+ sha = hashlib.sha256(raw).hexdigest()
134
+ rec = json.loads((gen_dir / f"{npz_stem(arm, scope)}.log").read_text())
135
+ want = rec["source_sha256"] if scope == "loco_masked" else rec["output_sha256"]
136
+ if sha != want:
137
+ raise SystemExit(f"{arm}: streamed NPZ sha256 {sha[:12]} != receipt {want[:12]}")
138
+ d = np.load(io.BytesIO(raw), allow_pickle=False)
139
+ del raw
140
+ if not np.array_equal(d["gene_ids"].astype(str), panel):
141
+ raise SystemExit(f"{arm}: NPZ gene_ids differ from the 6k panel")
142
+ rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
143
+ masked = []
144
+ if scope == "loco_masked": # zero exactly the genes tools/mask_rescore.py zeroed before scoring
145
+ masked = list(rec["masked_gene_ids"])
146
+ mcols = np.flatnonzero(np.isin(panel, masked))
147
+ if len(masked) != int(rec["n_masked"]) or mcols.size != len(masked):
148
+ raise SystemExit(f"{arm}: masked gene list does not match the panel")
149
+ rates[:, mcols] = 0
150
+ n_rows = rates.shape[0]
151
+ full = load_poisson().poisson_integerise(rates, seed=POISSON_SEED, chunk_rows=4096)
152
+ del rates
153
+ gc = pd.read_parquet(sdir / "generated_cells.parquet")
154
+ lab = pd.read_parquet(sdir / "labels/labels.parquet")
155
+ if len(gc) != len(lab) or not (lab.sample_id.astype(str).str.removesuffix("|generated").values == gc.donor.values).all():
156
+ raise SystemExit(f"{arm}: generated_cells and labels are not row-aligned")
157
+ X = full[gc.npz_row.to_numpy()].tocsr()
158
+ del full
159
+ ref = np.load(REF, allow_pickle=False)
160
+ umi = np.asarray(X[:, ref["score_idx"]].sum(1)).ravel()
161
+ if not np.array_equal(umi, gc.umi_scoring_genes.to_numpy()):
162
+ bad = int((umi != gc.umi_scoring_genes.to_numpy()).sum())
163
+ raise SystemExit(f"{arm}: Poisson read-out does not reproduce the benchmark ({bad} cells differ)")
164
+ lib = np.asarray(X[:, np.flatnonzero(measured)].sum(1)).ravel()
165
+ M = X[:, cols].toarray().astype(np.int32)
166
+ work.mkdir(parents=True, exist_ok=True)
167
+ np.savez_compressed(work / f"{arm}.npz", markers=M, marker_symbols=np.asarray(syms), lib_measured=lib,
168
+ donor=np.asarray(gc.donor, dtype=str), aifi_l1=np.asarray(lab.aifi_l1, dtype=str),
169
+ aifi_l2=np.asarray(lab.aifi_l2, dtype=str),
170
+ receipt=json.dumps({"arm": arm, "scope": scope, "npz_sha256": sha, "npz_rows": int(n_rows),
171
+ "cells": int(len(gc)), "poisson_seed": POISSON_SEED,
172
+ "masked_gene_ids": masked, "umi_scoring_genes_reproduced": True}))
173
+ print(json.dumps({"arm": arm, "sha256_ok": True, "cells": int(len(gc)), "donors": int(gc.donor.nunique()),
174
+ "poisson_reproduced": True, "median_lib_measured": float(np.median(lib))}))
175
+
176
+
177
+ def observed(states: list[dict], donors: list[str]) -> dict:
178
+ _, measured, syms, cols = panel_setup(states)
179
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
180
+ X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
181
+ obs = pd.read_parquet(DATA / "cells_obs.parquet", columns=["sample_id", "group"])
182
+ lab = pd.read_parquet(OBS_LABELS)
183
+ if len(lab) != X.shape[0] or not (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all():
184
+ raise SystemExit("observed labels not aligned with cells_panel6k.npz")
185
+ keep = np.flatnonzero(obs.sample_id.isin(donors).to_numpy())
186
+ Xk = X[keep]
187
+ return {"markers": Xk[:, cols].toarray().astype(np.int32), "marker_symbols": syms,
188
+ "lib": np.asarray(Xk[:, np.flatnonzero(measured)].sum(1)).ravel(),
189
+ "donor": obs.sample_id.to_numpy()[keep].astype(str),
190
+ "lab": lab.iloc[keep][["aifi_l1", "aifi_l2"]].reset_index(drop=True),
191
+ "groups": obs.drop_duplicates("sample_id").set_index("sample_id").group}
192
+
193
+
194
+ def cmd_analyze(arms: list[str], scope: str) -> None:
195
+ _, _, work, prefix = SCOPES[scope]
196
+ states = json.loads((PLAN / "tools/states.json").read_text())
197
+ gens = {a: np.load(work / f"{a}.npz", allow_pickle=False) for a in arms}
198
+ donors = sorted(set(gens[arms[0]]["donor"]))
199
+ for a in arms:
200
+ if sorted(set(gens[a]["donor"])) != donors:
201
+ raise SystemExit(f"{a}: scored donors differ from {arms[0]}")
202
+ ob = observed(states, donors)
203
+ groups = ob["groups"]
204
+ rng = np.random.default_rng(THIN_SEED)
205
+ per, summ, con = [], [], []
206
+ for arm in arms:
207
+ g = gens[arm]
208
+ syms = list(g["marker_symbols"].astype(str))
209
+ if syms != ob["marker_symbols"]:
210
+ raise SystemExit(f"{arm}: marker columns differ from the observed side")
211
+ sym2col = {s: i for i, s in enumerate(syms)}
212
+ lg = pd.DataFrame({"aifi_l1": g["aifi_l1"], "aifi_l2": g["aifi_l2"]})
213
+ for st in states:
214
+ po, pg = parent_mask(ob["lab"], st["parent"]), parent_mask(lg, st["parent"])
215
+ if st["kind"] == "label":
216
+ ho = ob["lab"].aifi_l2.isin(st["labels"]).to_numpy() & po
217
+ hg = lg.aifi_l2.isin(st["labels"]).to_numpy() & pg
218
+ ht, thin = ho, 1.0
219
+ else:
220
+ ident = {s: s for s in syms}
221
+ _, pcols, req, exc = state_cols(st, ident, sym2col)
222
+ c = pcols + [x for r in req for x in r] + exc
223
+ thin = min(1.0, float(np.median(g["lib_measured"][pg])) / float(np.median(ob["lib"][po])))
224
+ co = ob["markers"][:, c].astype(np.int64)
225
+ ho = call_state(co, st, len(pcols), req, exc) & po
226
+ ct = rng.binomial(co, thin) if thin < 1.0 else co
227
+ ht = call_state(ct, st, len(pcols), req, exc) & po
228
+ hg = call_state(g["markers"][:, c], st, len(pcols), req, exc) & pg
229
+ rows = []
230
+ for s in donors:
231
+ mo, mg = ob["donor"] == s, g["donor"] == s
232
+ rows.append({"arm": arm, "state": st["name"], "donor": s, "group": groups.get(s),
233
+ "obs_parent": int((po & mo).sum()), "obs_state": int((ho & mo).sum()),
234
+ "obsthin_state": int((ht & mo).sum()),
235
+ "gen_parent": int((pg & mg).sum()), "gen_state": int((hg & mg).sum())})
236
+ t = pd.DataFrame(rows)
237
+ t["obsthin_pct"] = 100 * t.obsthin_state / t.obs_parent.where(t.obs_parent > 0)
238
+ t["gen_pct"] = 100 * t.gen_state / t.gen_parent.where(t.gen_parent > 0)
239
+ per.append(t)
240
+ ok = t[["gen_pct", "obsthin_pct"]].dropna()
241
+ rho = float(spearmanr(ok.gen_pct, ok.obsthin_pct).correlation) if len(ok) > 2 else np.nan
242
+ ro = 100 * t.obsthin_state.sum() / max(t.obs_parent.sum(), 1)
243
+ rg = 100 * t.gen_state.sum() / max(t.gen_parent.sum(), 1)
244
+ summ.append({"arm": arm, "state": st["name"], "thin": round(thin, 3),
245
+ "gen": f"{int(t.gen_state.sum()):,} / {int(t.gen_parent.sum()):,}",
246
+ "obs_thinned": f"{int(t.obsthin_state.sum()):,} / {int(t.obs_parent.sum()):,}",
247
+ "obs_native_n": int(t.obs_state.sum()), "gen_pct": rg, "obs_pct": ro,
248
+ "gen_over_obs": rg / ro if ro else np.nan, "spearman_donors": rho})
249
+ for name, A, B in CONTRASTS:
250
+ ga, gb = t[t.group.isin(A)], t[t.group.isin(B)]
251
+ con.append({"arm": arm, "state": st["name"], "contrast": name, "n_a": len(ga), "n_b": len(gb),
252
+ "obs_a": f"{int(ga.obsthin_state.sum())} / {int(ga.obs_parent.sum())}",
253
+ "obs_b": f"{int(gb.obsthin_state.sum())} / {int(gb.obs_parent.sum())}",
254
+ "gen_a": f"{int(ga.gen_state.sum())} / {int(ga.gen_parent.sum())}",
255
+ "gen_b": f"{int(gb.gen_state.sum())} / {int(gb.gen_parent.sum())}",
256
+ "obs_diff": ga.obsthin_pct.mean() - gb.obsthin_pct.mean(),
257
+ "gen_diff": ga.gen_pct.mean() - gb.gen_pct.mean()})
258
+ C = pd.DataFrame(con)
259
+ C["same_direction"] = np.sign(C.obs_diff) == np.sign(C.gen_diff)
260
+ S = pd.DataFrame(summ)
261
+ out = PLAN / "out"
262
+ pd.concat(per).to_csv(out / f"{prefix}_per_donor.csv", index=False)
263
+ S.to_csv(out / f"{prefix}_summary.csv", index=False)
264
+ C.to_csv(out / f"{prefix}_contrasts.csv", index=False)
265
+ with pd.option_context("display.width", 250, "display.max_columns", 30, "display.max_rows", 500):
266
+ print(S.round(3).to_string(index=False))
267
+ print(C.round(2).to_string(index=False))
268
+
269
+
270
+ def main() -> int:
271
+ args = sys.argv[1:]
272
+ scope = "pooled"
273
+ if "--scope" in args:
274
+ i = args.index("--scope")
275
+ scope = args[i + 1]
276
+ del args[i:i + 2]
277
+ if scope not in SCOPES:
278
+ raise SystemExit(f"--scope must be one of {list(SCOPES)}")
279
+ if len(args) >= 2 and args[0] == "extract":
280
+ cmd_extract(args[1], scope)
281
+ elif len(args) >= 2 and args[0] == "analyze":
282
+ cmd_analyze(args[1:], scope)
283
+ else:
284
+ raise SystemExit(__doc__)
285
+ return 0
286
+
287
+
288
+ if __name__ == "__main__":
289
+ sys.exit(main())