Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/README.md +246 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/within_label_marker_check.py +75 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/run_loco_extract.sh +27 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/sepsis_states.py +272 -0
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/README.md
ADDED
|
@@ -0,0 +1,246 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
**Depth caveat (cross-cohort scratch).**
|
| 160 |
+
- Its cells have a 20,606-UMI median library on measured genes, against 1,135 for LoRA r16 and about 2,000 observed.
|
| 161 |
+
Only 236 genes are detected and 0.18 % of the UMI are on marker genes (2.1 % for LoRA r16).
|
| 162 |
+
- So the screen's library-based thinning left the observed side unthinned (thin 1.0, vs 0.34–0.62 for the pretrained
|
| 163 |
+
arms). That biases scratch marker-state ratios down by 1.1–2×.
|
| 164 |
+
- The comparisons below quote the matched-depth results where it matters.
|
| 165 |
+
|
| 166 |
+
**Within the cohort** (gen/obs; LoRA / scratch at the same pairs):
|
| 167 |
+
|
| 168 |
+
| State | 5 pairs | 58 pairs | 58 pairs + recipes |
|
| 169 |
+
|---|---|---|---|
|
| 170 |
+
| C1Q-high | 1.07 / 1.01 | 1.05 / 0.47 | 0.63 / 0.53 |
|
| 171 |
+
| MS1 | 0.15 / 0.10 | 0.21 / 0.40 | 0.30 / 0.46 |
|
| 172 |
+
| Cycling T/NK | 1.15 / 0.51 | 0.93 / 0.42 | 0.99 / 0.48 |
|
| 173 |
+
| ISG-high T | 0.46 / 0.15 | 0.37 / 0.17 | 0.53 / 0.18 |
|
| 174 |
+
| DN2 B | 1.11 / 1.63 | 0.35 / 0.63 | 0.28 / 0.46 |
|
| 175 |
+
| Plasmablast (label) | 1.87 / 1.12 | 3.47 / 1.24 | 2.30 / 1.18 |
|
| 176 |
+
| LDG, cycling monocyte | both fail | ≤ 0.13 | |
|
| 177 |
+
|
| 178 |
+
- **Average over the 13 rare states:** no significant difference at 5, 58 or 58+recipe pairs. The CIs span about
|
| 179 |
+
±0.3 log2, so this is not a demonstrated equivalence.
|
| 180 |
+
- **Pretrained is closer on T/NK cycling and interferon states**, in direction in 12 of 12 matched comparisons:
|
| 181 |
+
- the T/NK block is significant at 58 pairs;
|
| 182 |
+
- scratch also under-generates the ISG positive control.
|
| 183 |
+
- **Scratch is closer mainly where pretrained over-calls scANVI labels:** proliferating T and plasmablast. This is
|
| 184 |
+
specific to fold 0; pooled, LoRA-58 is 0.78× and 0.76×.
|
| 185 |
+
- **Scratch is also closer on DN2 at 58 pairs.**
|
| 186 |
+
- **C1Q-high and MS1:** neither initialisation wins consistently. C1Q-high favours pretrained at 58 pairs and MS1
|
| 187 |
+
favours scratch, both only under the bias-corrected interval.
|
| 188 |
+
- **5-pair scratch is donor-collapsed** (composition r 0.17), so its pooled ratios overstate it.
|
| 189 |
+
- **Disease directions kept** (25 eligible pairs, LoRA / scratch): 23 / 17 at 5 pairs, 20 / 19 at 58 pairs, 23 / 16
|
| 190 |
+
with recipes. Only the recipe gap is significant (7 vs 0 discordant pairs). The controls are tiny (1–2 donors per
|
| 191 |
+
group).
|
| 192 |
+
|
| 193 |
+
**Across cohorts** (gen/obs):
|
| 194 |
+
|
| 195 |
+
| Arm | C1Q-high | MS1 | Cycling T/NK |
|
| 196 |
+
|---|---|---|---|
|
| 197 |
+
| Own-cohort LoRA-58 | 0.50 | 0.71 | 0.54 |
|
| 198 |
+
| xcal (no training) | 0.07 | 0.72 | 0.46 |
|
| 199 |
+
| LoRA r16 | 0.03 | 0.12 | 0.15 |
|
| 200 |
+
| LoRA r64 | 0.06 | 0.11 | 0.17 |
|
| 201 |
+
| full FT | 0.09 | 0.27 | 0.36 |
|
| 202 |
+
| scratch, final | 0.07 | 0.10 | 0.05 |
|
| 203 |
+
|
| 204 |
+
- **Sepsis monocyte states fail in every model trained on other cohorts' pairs, scratch or pretrained.** Only
|
| 205 |
+
own-cohort LoRA recovers C1Q-high. MS1 is also recovered by xcal, with no sepsis pairs (0.72× [0.55, 1.05]).
|
| 206 |
+
- **Confirmed:** the scratch model almost never makes cycling T/NK cells (35 of 72,018 T/NK cells; 0.05× vs 0.15–0.46×
|
| 207 |
+
for every pretrained arm). This holds at matched depth and in every leave-one-donor-out run.
|
| 208 |
+
- **Average:**
|
| 209 |
+
- Scratch is further from observed than every pretrained arm under the screen's scoring.
|
| 210 |
+
- At matched depth the gap to LoRA r16 / r64 vanishes.
|
| 211 |
+
- A deficit remains vs full FT (+0.25 log2) and vs xcal (+0.68).
|
| 212 |
+
- **Scratch is closer only where pretrained over-generates:** HSPC and cytotoxic CD4 T.
|
| 213 |
+
- **Longer scratch training is worse:** s162k vs s50k +0.29 [0.15, 0.43], while its library inflates 13.9k → 20.6k UMI
|
| 214 |
+
and coverage falls 0.063 → 0.032.
|
| 215 |
+
|
| 216 |
+
**Reading.** The rare states that matter for sepsis (C1Q-high, MS1) come from the target cohort's own pairs, not from
|
| 217 |
+
the initialisation. With those pairs, scratch matches pretrained on average, but the pretrained model:
|
| 218 |
+
- keeps T/NK cycling and interferon states,
|
| 219 |
+
- keeps donor-specific composition with 5 pairs,
|
| 220 |
+
- keeps more disease directions with recipes,
|
| 221 |
+
- trains 15–19× faster.
|
| 222 |
+
|
| 223 |
+
Without them, pretrained models fine-tuned on other cohorts beat scratch only on cycling states. The best
|
| 224 |
+
cohort-transfer option for MS1 is calibration, which needs no training.
|
| 225 |
+
|
| 226 |
+
**Limits:** one fold within the cohort, one held-out cohort across cohorts, one seed, marker-rule states, 52 + 52
|
| 227 |
+
state-level tests without multiplicity correction.
|
| 228 |
+
|
| 229 |
+
## Files
|
| 230 |
+
|
| 231 |
+
- `tools/screen.py`: generated vs observed per state.
|
| 232 |
+
- `tools/corpus_states.py`: corpus frequency, using the same rules.
|
| 233 |
+
- `tools/sepsis_states.py`: Ye 2026 sepsis held-out donors (`extract` per arm from a streamed pooled NPZ, `analyze`);
|
| 234 |
+
per-arm marker extracts in `work/sepsis/` (small), logs in `logs/`.
|
| 235 |
+
- `tools/states.json`: the state rules.
|
| 236 |
+
- `tools/run_loco_extract.sh`: sequential bounded extracts for `--scope loco` (2026-10-05).
|
| 237 |
+
- `out/scratch_vs_lora_20261005/`: scratch-vs-pretrained analysis.
|
| 238 |
+
- `REPORT.md`
|
| 239 |
+
- `within_*`, `cross_*`: analyses
|
| 240 |
+
- `confound_*`: confound audit
|
| 241 |
+
- `verify_*`: two verifier passes
|
| 242 |
+
- `workflow_result.json`: tables and claim verdicts
|
| 243 |
+
- Runs were bounded `systemd-run --user` CPU units (MemoryMax 28G, no swap); logs are in `work/`.
|
| 244 |
+
- The generated read-out h5ads were copied back from spark-0110 to a scratch directory for the run, sha-checked
|
| 245 |
+
against their `.moved` markers, and deleted afterwards. So were the corpus sample h5ad and the `behcet_c1q_lora3`
|
| 246 |
+
corpus sample. The originals remain on spark-0110.
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/within_label_marker_check.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Within-cohort (sepsis fold 0, 17 held-out donors): do generated cells labelled 'Proliferating T cell' carry the
|
| 3 |
+
cycling program? CPU only, read-only inputs, 2026-10-05.
|
| 4 |
+
|
| 5 |
+
Why: scratch arms match the observed frequency of the scANVI label state 'Proliferating T (label)' (0.98-1.37x) but
|
| 6 |
+
under-generate the marker state 'Cycling T/NK' (0.42-0.51x); pretrained arms do the reverse (label 1.5-2.5x, markers
|
| 7 |
+
0.93-1.34x). This checks, per arm, the share of label-called proliferating T cells that also pass the cycling rule of
|
| 8 |
+
tools/states.json (>= 2 of MKI67 TOP2A TYMS CENPF UBE2C BIRC5 detected).
|
| 9 |
+
|
| 10 |
+
Generated: ../../work/sepsis/fold0/<arm>.npz (marker counts of the benchmark's Poisson read-out, scANVI labels).
|
| 11 |
+
Observed: the same 17 donors, via tools/sepsis_states.observed() (cells_panel6k.npz + benchmark observed labels),
|
| 12 |
+
binomially thinned per arm to the arm's T-cell thinning constant (summary column `thin` of 'ISG-high T', parent
|
| 13 |
+
'T cell'); seed 20261005. Run with PYTHONDONTWRITEBYTECODE=1 so nothing is written under tools/.
|
| 14 |
+
Output: within_label_marker_check.csv
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
|
| 25 |
+
OUT = Path(__file__).resolve().parent
|
| 26 |
+
PLAN = OUT.parents[1]
|
| 27 |
+
sys.path.insert(0, str(PLAN / "tools"))
|
| 28 |
+
from sepsis_states import observed # noqa: E402
|
| 29 |
+
|
| 30 |
+
ARMS = ["zs__raw", "lora_n5__raw", "scratch_n5__raw", "real_lora__raw", "real_full__raw", "scratch_full__raw",
|
| 31 |
+
"lora_recipe__raw", "scratch_recipe__raw"]
|
| 32 |
+
CYC = ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"]
|
| 33 |
+
K = 2
|
| 34 |
+
SEED = 20261005
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def stats(markers, syms, l1, l2):
|
| 38 |
+
cols = [list(syms).index(g) for g in CYC if g in syms]
|
| 39 |
+
cyc = (markers[:, cols] > 0).sum(1) >= K
|
| 40 |
+
t = (l1 == "T cell") | (l2 == "T cell")
|
| 41 |
+
pt = t & (l2 == "Proliferating T cell")
|
| 42 |
+
return {"t_cells": int(t.sum()), "pt_label_cells": int(pt.sum()),
|
| 43 |
+
"pt_label_pct_of_T": 100 * pt.sum() / max(t.sum(), 1),
|
| 44 |
+
"cycling_rule_pct_of_T": 100 * (cyc & t).sum() / max(t.sum(), 1),
|
| 45 |
+
"pct_of_pt_label_passing_cycling_rule": 100 * (cyc & pt).sum() / pt.sum() if pt.sum() else np.nan,
|
| 46 |
+
"pct_of_nonpt_T_passing_cycling_rule": 100 * (cyc & t & ~pt).sum() / max((t & ~pt).sum(), 1),
|
| 47 |
+
"n_cycling_rule_T": int((cyc & t).sum())}
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main():
|
| 51 |
+
S = pd.read_csv(PLAN / "out/sepsis_fold0_summary.csv").set_index(["arm", "state"])
|
| 52 |
+
states = json.loads((PLAN / "tools/states.json").read_text())
|
| 53 |
+
work = PLAN / "work/sepsis/fold0"
|
| 54 |
+
donors = sorted(set(np.load(work / f"{ARMS[0]}.npz", allow_pickle=False)["donor"].astype(str)))
|
| 55 |
+
ob = observed(states, donors)
|
| 56 |
+
syms_o = list(ob["marker_symbols"])
|
| 57 |
+
l1o, l2o = ob["lab"].aifi_l1.to_numpy(str), ob["lab"].aifi_l2.to_numpy(str)
|
| 58 |
+
rng = np.random.default_rng(SEED)
|
| 59 |
+
rows = [{"side": "observed native", "arm": "", "thin": 1.0, **stats(ob["markers"], syms_o, l1o, l2o)}]
|
| 60 |
+
for arm in ARMS:
|
| 61 |
+
g = np.load(work / f"{arm}.npz", allow_pickle=False)
|
| 62 |
+
rows.append({"side": "generated", "arm": arm, "thin": None,
|
| 63 |
+
**stats(g["markers"], list(g["marker_symbols"].astype(str)), g["aifi_l1"].astype(str),
|
| 64 |
+
g["aifi_l2"].astype(str))})
|
| 65 |
+
thin = float(S.loc[(arm, "ISG-high T")].thin)
|
| 66 |
+
mt = rng.binomial(ob["markers"].astype(np.int64), thin) if thin < 1 else ob["markers"]
|
| 67 |
+
rows.append({"side": "observed thinned to arm", "arm": arm, "thin": thin, **stats(mt, syms_o, l1o, l2o)})
|
| 68 |
+
R = pd.DataFrame(rows)
|
| 69 |
+
R.to_csv(OUT / "within_label_marker_check.csv", index=False)
|
| 70 |
+
with pd.option_context("display.width", 250, "display.max_columns", 30):
|
| 71 |
+
print(R.round(2).to_string(index=False))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/run_loco_extract.sh
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Rare-state extracts for the cross-cohort arms with sepsis held out (scope loco of tools/sepsis_states.py), CPU only,
|
| 3 |
+
# one bounded unit per arm in sequence (MemoryMax 28G, no swap; waits for MemAvailable >= 32 + 28 GiB, the trainer
|
| 4 |
+
# floor rule). NPZs are streamed from spark-0110 (moved there after scoring) and sha-checked by the tool.
|
| 5 |
+
# usage: run_loco_extract.sh ARM [ARM ...] (2026-10-05, scratch vs pretrained rare states)
|
| 6 |
+
set -uo pipefail
|
| 7 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 8 |
+
R=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004
|
| 9 |
+
G=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002/generated/ye2026_sepsis/hoL_ye2026_sepsis
|
| 10 |
+
PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
|
| 11 |
+
fail=0
|
| 12 |
+
for arm in "$@"; do
|
| 13 |
+
if [[ -s $R/work/sepsis/loco/$arm.npz ]]; then echo "$(date -Is) $arm: extract exists; skipped"; continue; fi
|
| 14 |
+
stem=$("$PY" -c "import sys; sys.path.insert(0, '$R/tools'); from sepsis_states import npz_stem; print(npz_stem('$arm', 'loco'))")
|
| 15 |
+
until (( $(awk '/MemAvailable/ {print int($2/1048576)}' /proc/meminfo) >= 60 )); do sleep 60; done
|
| 16 |
+
unit=rare-loco-extract-$(echo "$arm" | tr '_' '-' | cut -c1-50)
|
| 17 |
+
echo "$(date -Is) $arm: extracting from spark-0110:$G/$stem.npz"
|
| 18 |
+
systemd-run --user --unit="$unit" --wait --collect --quiet --working-directory="$R" \
|
| 19 |
+
-p MemoryMax=28G -p MemorySwapMax=0 -p CPUQuota=400% -p Nice=10 \
|
| 20 |
+
-p StandardOutput=file:"$R/logs/loco_extract_$arm.log" -p StandardError=file:"$R/logs/loco_extract_$arm.err" \
|
| 21 |
+
--setenv=CUDA_VISIBLE_DEVICES= --setenv=PYTHONNOUSERSITE=1 --setenv=PYTHONDONTWRITEBYTECODE=1 \
|
| 22 |
+
--setenv=OMP_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
|
| 23 |
+
/bin/bash -c "set -o pipefail; ssh spark-0110 cat $G/$stem.npz | $PY tools/sepsis_states.py --scope loco extract $arm" \
|
| 24 |
+
&& echo "$(date -Is) $arm: $(cat "$R/logs/loco_extract_$arm.log")" \
|
| 25 |
+
|| { echo "$(date -Is) $arm: FAILED (see logs/loco_extract_$arm.err)"; fail=$((fail+1)); }
|
| 26 |
+
done
|
| 27 |
+
echo "$(date -Is) done; failed=$fail"
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/sepsis_states.py
ADDED
|
@@ -0,0 +1,272 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
extract ARM < NPZ bytes on stdin (ssh spark-0110 cat .../pooled/ARM.npz | sepsis_states.py extract ARM)
|
| 16 |
+
sha256 of the stream must equal the pooled receipt (generated/ye2026_sepsis/pooled/ARM.log, output_sha256).
|
| 17 |
+
Writes work/sepsis/ARM.npz: per labelled cell, counts of every marker gene of tools/states.json, the library on
|
| 18 |
+
the dataset's measured panel genes, donor, AIFI L1/L2. Nothing large is written.
|
| 19 |
+
analyze ARM [ARM ...]
|
| 20 |
+
Observed side: every cell of the scored donors (data/ye2026_sepsis/cells_panel6k.npz, benchmark observed labels).
|
| 21 |
+
States, thinning and counts exactly as tools/screen.py (one thinning constant per arm and marker state: observed
|
| 22 |
+
parent median library -> generated parent median library on the measured panel genes; label states as they
|
| 23 |
+
are). Per arm and state: "X of N" on both sides, generated / observed, Spearman over donors, and contrasts
|
| 24 |
+
(adult sepsis vs adult HC, paediatric sepsis vs paediatric HC, all sepsis vs all controls incl. ICU controls).
|
| 25 |
+
Outputs: out/sepsis_{summary,contrasts,per_donor}.csv
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import annotations
|
| 28 |
+
|
| 29 |
+
import hashlib
|
| 30 |
+
import importlib.util
|
| 31 |
+
import io
|
| 32 |
+
import json
|
| 33 |
+
import sys
|
| 34 |
+
from pathlib import Path
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
import pandas as pd
|
| 38 |
+
import scipy.sparse as sp
|
| 39 |
+
from scipy.stats import spearmanr
|
| 40 |
+
|
| 41 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 42 |
+
from screen import call_state, parent_mask, state_cols # noqa: E402
|
| 43 |
+
|
| 44 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 45 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 46 |
+
FT = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 47 |
+
DATA = FT / "data/ye2026_sepsis"
|
| 48 |
+
# scope -> (generated dir with <arm>.npz + receipt <arm>.log, scores dirs searched in order for arms/<arm>/, work dir,
|
| 49 |
+
# output prefix). "pooled": the cross-fitted 82-donor arms; "fold0": the fold-0 test donors, incl. the
|
| 50 |
+
# no-pretraining (--init random) arms of 2026-10-05 scored in fold0_scratch_20261005.
|
| 51 |
+
SCOPES = {
|
| 52 |
+
"pooled": (FT / "generated/ye2026_sepsis/pooled", [FT / "scores/ye2026_sepsis/pooled/arms"],
|
| 53 |
+
PLAN / "work/sepsis", "sepsis"),
|
| 54 |
+
"fold0": (FT / "generated/ye2026_sepsis/fold0",
|
| 55 |
+
[FT / "scores/ye2026_sepsis/fold0_scratch_20261005/arms", FT / "scores/ye2026_sepsis/fold0/arms"],
|
| 56 |
+
PLAN / "work/sepsis/fold0", "sepsis_fold0"),
|
| 57 |
+
"loco": (M8 / "plans/paired_crosscohort_20261002/generated/ye2026_sepsis/hoL_ye2026_sepsis",
|
| 58 |
+
[M8 / "plans/paired_crosscohort_20261002/scores/ye2026_sepsis/{arm}/arms"],
|
| 59 |
+
PLAN / "work/sepsis/loco", "sepsis_loco"),
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def npz_stem(arm: str, scope: str) -> str:
|
| 64 |
+
"""File stem of an arm's generated NPZ / receipt. pooled, fold0: the arm name. loco: the cross-cohort scorer's
|
| 65 |
+
naming (score_pending.sh): locoL_<tag>_K<K> <- K<K>_<tag>.npz, xcalL_K<K> <- xcal_K<K>.npz."""
|
| 66 |
+
if scope != "loco":
|
| 67 |
+
return arm
|
| 68 |
+
if arm.startswith("xcalL_K"):
|
| 69 |
+
return "xcal_" + arm[len("xcalL_"):]
|
| 70 |
+
if arm.startswith("locoL_") and "_K" in arm:
|
| 71 |
+
tag, k = arm[len("locoL_"):].rsplit("_K", 1)
|
| 72 |
+
return f"K{k}_{tag}"
|
| 73 |
+
raise SystemExit(f"{arm}: not a hoL arm name (locoL_<tag>_K<K> or xcalL_K<K>)")
|
| 74 |
+
REF = FT / "scoring_cache/ye2026_sepsis/reference.npz"
|
| 75 |
+
OBS_LABELS = FT / "scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet"
|
| 76 |
+
CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
|
| 77 |
+
"canonical_genes.tsv")
|
| 78 |
+
POISSON_PY = M8 / "plans/aifi_scanvi_rebuild_20260916/poisson_readout.py"
|
| 79 |
+
POISSON_SEED = 20260916
|
| 80 |
+
THIN_SEED = 20261004
|
| 81 |
+
CONTRASTS = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
|
| 82 |
+
("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
|
| 83 |
+
("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
|
| 84 |
+
["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def load_poisson():
|
| 88 |
+
spec = importlib.util.spec_from_file_location("poisson_readout", POISSON_PY)
|
| 89 |
+
mod = importlib.util.module_from_spec(spec)
|
| 90 |
+
spec.loader.exec_module(mod)
|
| 91 |
+
return mod
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def marker_genes(states: list[dict]) -> list[str]:
|
| 95 |
+
out = []
|
| 96 |
+
for st in states:
|
| 97 |
+
for g in st.get("genes", []) + [x for grp in st.get("require_any", []) for x in grp] + st.get("exclude", []):
|
| 98 |
+
if g not in out:
|
| 99 |
+
out.append(g)
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def panel_setup(states: list[dict]) -> tuple[np.ndarray, np.ndarray, list[str], np.ndarray]:
|
| 104 |
+
"""6k panel ids, measured-gene mask (any sample of the dataset), marker symbols present, their panel columns."""
|
| 105 |
+
d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
|
| 106 |
+
panel = d["panel_gene_ids"].astype(str)
|
| 107 |
+
measured = d["panel_measured"].any(0)
|
| 108 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 109 |
+
sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
|
| 110 |
+
pos = {g: i for i, g in enumerate(panel)}
|
| 111 |
+
syms = [g for g in marker_genes(states) if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
|
| 112 |
+
return panel, measured, syms, np.asarray([pos[sym2id[g]] for g in syms], dtype=np.int64)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def cmd_extract(arm: str, scope: str) -> None:
|
| 116 |
+
gen_dir, score_dirs, work, _ = SCOPES[scope]
|
| 117 |
+
score_dirs = [Path(str(d).replace("{arm}", arm)) for d in score_dirs]
|
| 118 |
+
sdir = next((d / arm for d in score_dirs if (d / arm / "generated_cells.parquet").exists()), None)
|
| 119 |
+
if sdir is None:
|
| 120 |
+
raise SystemExit(f"{arm}: no scored labels in {score_dirs}")
|
| 121 |
+
states = json.loads((PLAN / "tools/states.json").read_text())
|
| 122 |
+
panel, measured, syms, cols = panel_setup(states)
|
| 123 |
+
raw = sys.stdin.buffer.read()
|
| 124 |
+
sha = hashlib.sha256(raw).hexdigest()
|
| 125 |
+
want = json.loads((gen_dir / f"{npz_stem(arm, scope)}.log").read_text())["output_sha256"]
|
| 126 |
+
if sha != want:
|
| 127 |
+
raise SystemExit(f"{arm}: streamed NPZ sha256 {sha[:12]} != pooled receipt {want[:12]}")
|
| 128 |
+
d = np.load(io.BytesIO(raw), allow_pickle=False)
|
| 129 |
+
del raw
|
| 130 |
+
if not np.array_equal(d["gene_ids"].astype(str), panel):
|
| 131 |
+
raise SystemExit(f"{arm}: NPZ gene_ids differ from the 6k panel")
|
| 132 |
+
rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
|
| 133 |
+
n_rows = rates.shape[0]
|
| 134 |
+
full = load_poisson().poisson_integerise(rates, seed=POISSON_SEED, chunk_rows=4096)
|
| 135 |
+
del rates
|
| 136 |
+
gc = pd.read_parquet(sdir / "generated_cells.parquet")
|
| 137 |
+
lab = pd.read_parquet(sdir / "labels/labels.parquet")
|
| 138 |
+
if len(gc) != len(lab) or not (lab.sample_id.astype(str).str.removesuffix("|generated").values == gc.donor.values).all():
|
| 139 |
+
raise SystemExit(f"{arm}: generated_cells and labels are not row-aligned")
|
| 140 |
+
X = full[gc.npz_row.to_numpy()].tocsr()
|
| 141 |
+
del full
|
| 142 |
+
ref = np.load(REF, allow_pickle=False)
|
| 143 |
+
umi = np.asarray(X[:, ref["score_idx"]].sum(1)).ravel()
|
| 144 |
+
if not np.array_equal(umi, gc.umi_scoring_genes.to_numpy()):
|
| 145 |
+
bad = int((umi != gc.umi_scoring_genes.to_numpy()).sum())
|
| 146 |
+
raise SystemExit(f"{arm}: Poisson read-out does not reproduce the benchmark ({bad} cells differ)")
|
| 147 |
+
lib = np.asarray(X[:, np.flatnonzero(measured)].sum(1)).ravel()
|
| 148 |
+
M = X[:, cols].toarray().astype(np.int32)
|
| 149 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 150 |
+
np.savez_compressed(work / f"{arm}.npz", markers=M, marker_symbols=np.asarray(syms), lib_measured=lib,
|
| 151 |
+
donor=np.asarray(gc.donor, dtype=str), aifi_l1=np.asarray(lab.aifi_l1, dtype=str),
|
| 152 |
+
aifi_l2=np.asarray(lab.aifi_l2, dtype=str),
|
| 153 |
+
receipt=json.dumps({"arm": arm, "npz_sha256": sha, "npz_rows": int(n_rows),
|
| 154 |
+
"cells": int(len(gc)), "poisson_seed": POISSON_SEED,
|
| 155 |
+
"umi_scoring_genes_reproduced": True}))
|
| 156 |
+
print(json.dumps({"arm": arm, "sha256_ok": True, "cells": int(len(gc)), "donors": int(gc.donor.nunique()),
|
| 157 |
+
"poisson_reproduced": True, "median_lib_measured": float(np.median(lib))}))
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def observed(states: list[dict], donors: list[str]) -> dict:
|
| 161 |
+
_, measured, syms, cols = panel_setup(states)
|
| 162 |
+
d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
|
| 163 |
+
X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
|
| 164 |
+
obs = pd.read_parquet(DATA / "cells_obs.parquet", columns=["sample_id", "group"])
|
| 165 |
+
lab = pd.read_parquet(OBS_LABELS)
|
| 166 |
+
if len(lab) != X.shape[0] or not (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all():
|
| 167 |
+
raise SystemExit("observed labels not aligned with cells_panel6k.npz")
|
| 168 |
+
keep = np.flatnonzero(obs.sample_id.isin(donors).to_numpy())
|
| 169 |
+
Xk = X[keep]
|
| 170 |
+
return {"markers": Xk[:, cols].toarray().astype(np.int32), "marker_symbols": syms,
|
| 171 |
+
"lib": np.asarray(Xk[:, np.flatnonzero(measured)].sum(1)).ravel(),
|
| 172 |
+
"donor": obs.sample_id.to_numpy()[keep].astype(str),
|
| 173 |
+
"lab": lab.iloc[keep][["aifi_l1", "aifi_l2"]].reset_index(drop=True),
|
| 174 |
+
"groups": obs.drop_duplicates("sample_id").set_index("sample_id").group}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def cmd_analyze(arms: list[str], scope: str) -> None:
|
| 178 |
+
_, _, work, prefix = SCOPES[scope]
|
| 179 |
+
states = json.loads((PLAN / "tools/states.json").read_text())
|
| 180 |
+
gens = {a: np.load(work / f"{a}.npz", allow_pickle=False) for a in arms}
|
| 181 |
+
donors = sorted(set(gens[arms[0]]["donor"]))
|
| 182 |
+
for a in arms:
|
| 183 |
+
if sorted(set(gens[a]["donor"])) != donors:
|
| 184 |
+
raise SystemExit(f"{a}: scored donors differ from {arms[0]}")
|
| 185 |
+
ob = observed(states, donors)
|
| 186 |
+
groups = ob["groups"]
|
| 187 |
+
rng = np.random.default_rng(THIN_SEED)
|
| 188 |
+
per, summ, con = [], [], []
|
| 189 |
+
for arm in arms:
|
| 190 |
+
g = gens[arm]
|
| 191 |
+
syms = list(g["marker_symbols"].astype(str))
|
| 192 |
+
if syms != ob["marker_symbols"]:
|
| 193 |
+
raise SystemExit(f"{arm}: marker columns differ from the observed side")
|
| 194 |
+
sym2col = {s: i for i, s in enumerate(syms)}
|
| 195 |
+
lg = pd.DataFrame({"aifi_l1": g["aifi_l1"], "aifi_l2": g["aifi_l2"]})
|
| 196 |
+
for st in states:
|
| 197 |
+
po, pg = parent_mask(ob["lab"], st["parent"]), parent_mask(lg, st["parent"])
|
| 198 |
+
if st["kind"] == "label":
|
| 199 |
+
ho = ob["lab"].aifi_l2.isin(st["labels"]).to_numpy() & po
|
| 200 |
+
hg = lg.aifi_l2.isin(st["labels"]).to_numpy() & pg
|
| 201 |
+
ht, thin = ho, 1.0
|
| 202 |
+
else:
|
| 203 |
+
ident = {s: s for s in syms}
|
| 204 |
+
_, pcols, req, exc = state_cols(st, ident, sym2col)
|
| 205 |
+
c = pcols + [x for r in req for x in r] + exc
|
| 206 |
+
thin = min(1.0, float(np.median(g["lib_measured"][pg])) / float(np.median(ob["lib"][po])))
|
| 207 |
+
co = ob["markers"][:, c].astype(np.int64)
|
| 208 |
+
ho = call_state(co, st, len(pcols), req, exc) & po
|
| 209 |
+
ct = rng.binomial(co, thin) if thin < 1.0 else co
|
| 210 |
+
ht = call_state(ct, st, len(pcols), req, exc) & po
|
| 211 |
+
hg = call_state(g["markers"][:, c], st, len(pcols), req, exc) & pg
|
| 212 |
+
rows = []
|
| 213 |
+
for s in donors:
|
| 214 |
+
mo, mg = ob["donor"] == s, g["donor"] == s
|
| 215 |
+
rows.append({"arm": arm, "state": st["name"], "donor": s, "group": groups.get(s),
|
| 216 |
+
"obs_parent": int((po & mo).sum()), "obs_state": int((ho & mo).sum()),
|
| 217 |
+
"obsthin_state": int((ht & mo).sum()),
|
| 218 |
+
"gen_parent": int((pg & mg).sum()), "gen_state": int((hg & mg).sum())})
|
| 219 |
+
t = pd.DataFrame(rows)
|
| 220 |
+
t["obsthin_pct"] = 100 * t.obsthin_state / t.obs_parent.where(t.obs_parent > 0)
|
| 221 |
+
t["gen_pct"] = 100 * t.gen_state / t.gen_parent.where(t.gen_parent > 0)
|
| 222 |
+
per.append(t)
|
| 223 |
+
ok = t[["gen_pct", "obsthin_pct"]].dropna()
|
| 224 |
+
rho = float(spearmanr(ok.gen_pct, ok.obsthin_pct).correlation) if len(ok) > 2 else np.nan
|
| 225 |
+
ro = 100 * t.obsthin_state.sum() / max(t.obs_parent.sum(), 1)
|
| 226 |
+
rg = 100 * t.gen_state.sum() / max(t.gen_parent.sum(), 1)
|
| 227 |
+
summ.append({"arm": arm, "state": st["name"], "thin": round(thin, 3),
|
| 228 |
+
"gen": f"{int(t.gen_state.sum()):,} / {int(t.gen_parent.sum()):,}",
|
| 229 |
+
"obs_thinned": f"{int(t.obsthin_state.sum()):,} / {int(t.obs_parent.sum()):,}",
|
| 230 |
+
"obs_native_n": int(t.obs_state.sum()), "gen_pct": rg, "obs_pct": ro,
|
| 231 |
+
"gen_over_obs": rg / ro if ro else np.nan, "spearman_donors": rho})
|
| 232 |
+
for name, A, B in CONTRASTS:
|
| 233 |
+
ga, gb = t[t.group.isin(A)], t[t.group.isin(B)]
|
| 234 |
+
con.append({"arm": arm, "state": st["name"], "contrast": name, "n_a": len(ga), "n_b": len(gb),
|
| 235 |
+
"obs_a": f"{int(ga.obsthin_state.sum())} / {int(ga.obs_parent.sum())}",
|
| 236 |
+
"obs_b": f"{int(gb.obsthin_state.sum())} / {int(gb.obs_parent.sum())}",
|
| 237 |
+
"gen_a": f"{int(ga.gen_state.sum())} / {int(ga.gen_parent.sum())}",
|
| 238 |
+
"gen_b": f"{int(gb.gen_state.sum())} / {int(gb.gen_parent.sum())}",
|
| 239 |
+
"obs_diff": ga.obsthin_pct.mean() - gb.obsthin_pct.mean(),
|
| 240 |
+
"gen_diff": ga.gen_pct.mean() - gb.gen_pct.mean()})
|
| 241 |
+
C = pd.DataFrame(con)
|
| 242 |
+
C["same_direction"] = np.sign(C.obs_diff) == np.sign(C.gen_diff)
|
| 243 |
+
S = pd.DataFrame(summ)
|
| 244 |
+
out = PLAN / "out"
|
| 245 |
+
pd.concat(per).to_csv(out / f"{prefix}_per_donor.csv", index=False)
|
| 246 |
+
S.to_csv(out / f"{prefix}_summary.csv", index=False)
|
| 247 |
+
C.to_csv(out / f"{prefix}_contrasts.csv", index=False)
|
| 248 |
+
with pd.option_context("display.width", 250, "display.max_columns", 30, "display.max_rows", 500):
|
| 249 |
+
print(S.round(3).to_string(index=False))
|
| 250 |
+
print(C.round(2).to_string(index=False))
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def main() -> int:
|
| 254 |
+
args = sys.argv[1:]
|
| 255 |
+
scope = "pooled"
|
| 256 |
+
if "--scope" in args:
|
| 257 |
+
i = args.index("--scope")
|
| 258 |
+
scope = args[i + 1]
|
| 259 |
+
del args[i:i + 2]
|
| 260 |
+
if scope not in SCOPES:
|
| 261 |
+
raise SystemExit(f"--scope must be one of {list(SCOPES)}")
|
| 262 |
+
if len(args) >= 2 and args[0] == "extract":
|
| 263 |
+
cmd_extract(args[1], scope)
|
| 264 |
+
elif len(args) >= 2 and args[0] == "analyze":
|
| 265 |
+
cmd_analyze(args[1:], scope)
|
| 266 |
+
else:
|
| 267 |
+
raise SystemExit(__doc__)
|
| 268 |
+
return 0
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
if __name__ == "__main__":
|
| 272 |
+
sys.exit(main())
|