# Fast, Exact CellGemma-E4B: Architecture Recipe, Benchmarks & Novel Findings > **TL;DR — Total Speedup vs Unmodified Vanilla CellGemma (Single Workstation GPU):** > - **Exact Final Judge (`V2-Fast`, 100% lossless BF16):** **`approx. 4,030×`** vs Vanilla 8K rollout | **`135×`** vs 4-seed OG 2-stage pipeline | **`6.2×–13.4×`** vs 1-step Vanilla HF — **`99.54%` pairwise order accuracy & `100.0%` Top-10 capture (`0` swaps)**. > - **Ultra-Fast Scout (`B5-Align + Mixed FP4/FP8`):** **`approx. 430,000×–832,000×`** vs Vanilla 8K rollout | **`4,921×`** vs 4-seed OG 2-stage pipeline | **`527×–890×`** direct vs 1-step Vanilla HF — **`99.0%` Top-10 capture (`10/10` leads), `99.7%` Top > Mid > Bot accuracy, `90%` pairwise order**. > - **Compounded Multi-Cell Screen (+ CUR Active Completion across 67 cell lines):** **`approx. 1.44M×–1.80M×`** vs Vanilla 8K (`r = 0.967–0.983`, `97%–100%` Top-1% recall). > - **Cached Archive Rescoring (`0.0-ULP` exact across 813K saved drug-cell pairs):** **`approx. 9.3 Billion ×`** vs Vanilla 8K (**`98.8 ms`** total, `29.6B pairs/hr`). --- ## 1. The Core Idea (Plain English) Standard `google/cellgemma-e4b` (42-layer Gemma-4 E4B) predicts cellular drug responses by autoregressively generating up to 8,192 `+GENE` / `-GENE` tokens across multiple random seeds and decoding them with a Stage-2 MLP. That takes minutes per drug. Our stack replaces slow rollout screening with a **two-tier Scout + Judge architecture** that reads CellGemma's **exact analytical conditional log-probabilities** at the `+` and `-` decision tokens in a single forward pass: 1. **The Scout (`B5-Align + Mixed FP4/FP8`)** screens an entire approx. 12,000-drug library in **approx. 50 seconds** (or 256 evolved analogs in **approx. 0.5 s**), putting **10/10 real Top-10 hits into the Top 10** (`99.0%` NDCG@10). 2. **The Judge (`V2-Fast`, strictly 100% lossless BF16)** re-scores finalists and anchors active evolution to **`99.54%` exact pairwise identity (`100.0%` Top-10 match)** with unmodified Vanilla Hugging Face. --- ## 2. Speedup & Accuracy Summary vs Vanilla Install ### A. Speedup Across Every Baseline Definition | Tier / Engine | Throughput (Single GPU) | vs Vanilla 8K Rollout | vs 4-Seed OG 2-Stage Pipeline | vs 1-Step Vanilla HF | |---|---:|---:|---:|---:| | **Vanilla 8K Autoregressive** *(reference)* | `approx. 3.2 sims/hr` | `1×` | — | — | | **OG 2-Stage Pipeline** *(4 seeds × 768 tok + Decoder)* | `46 sims/hr` (`78.8 s/drug`) | `14×` | `1×` | — | | **Vanilla HF 1-Step** *(unmodified stock, exact B=1)* | `962 sims/hr` (`3.74 s/drug`) | `302×` | `21×` | `1×` | | **Judge: `V2-Fast` (`100% 0.0-ULP` BF16 + LightCone)** | **`12.9K / hr`** (`9.7K` sustained) | **`approx. 4,030×`** | **`135×`** | **`6.2×–13.4×`** | | **Scout: `B5-Align` (`0.0-ULP` BF16)** | **`1.02M / hr`** (Evo) / `1.80M` (Dose) | **`approx. 321K–564K×`** | `approx. 3,100×` | **`346×–1,064×`** | | **Scout: `B5-Align + Mixed FP4/FP8`** *(Clinical 12K w/ shards)* | **`1.37M / hr`** (`857K` sustained, `50 s` lib) | **`approx. 430,000×`** | `approx. 4,100×` | **`890×`** *(full lib)* | | **Scout: `B5-Align + Mixed FP4/FP8`** *(Evo 256 / 10-Dose)* | **`1.66M / hr`** (Evo) / **`2.65M / hr`** (Dose) | **`approx. 520K–832K×`** | **`4,921×`** | **`1,723×–2,758×`** | | **Multi-Cell 67-Line Screen (+ CUR `16–20/67` anchors)** | **`4.6M–5.75M eff. / hr`** | **`approx. 1.44M–1.80M×`** | `approx. 16,500×–20,600×` | `approx. 4,800×–6,000×` | | **Cached Archive Rescorer** *(813K saved `h_top` shards)* | **`29.6B pairs/hr`** (`98.8 ms` total) | **`approx. 9.3 Billion ×`** | — | `approx. 30.8M×` | ### B. Rank Fidelity vs Unmodified Vanilla HF & OG 2-Stage Pipeline Evaluated on an **unseen held-out cell line** (`11,975`-drug library ranked by our build → **Top 10 / Mid 10 / Bottom 10** 30-item sanity check) and on an official control cell against **60 unmodified 4-seed OG rollouts + Stage-2 `ExpressionDecoder`**: | Build | Test vs Unmodified Vanilla HF (30 Items) | Test vs Full OG 4-Seed + Stage-2 Decoder (15 Items) | |---|---|---| | **Judge: `V2-Fast` (`100%` BF16)** | **Order Acc `99.54%`**, **NDCG@10 `100.0%`** (`10/10, 10/10, 10/10`), $\rho = 0.9991$ | **NDCG@5 `96.04%`** *(vs `98.38%` OG noise ceiling)*, Cross-Tier `72.0%` *(vs `74.7%` ceiling)* | | **Scout: `B5-Align + Mixed FP4/FP8`** | **Order Acc `89.89%`**, **NDCG@10 `99.03%`**, **Cross-Tier `99.67%`**, Top-10 `10/10`, $\rho = 0.9413$ | **NDCG@5 `95.21%`** *(at `4,921×` faster!)*, Cross-Tier `72.0%`, `5/5` Top-5 positive on OG | --- ## 3. Reproducible Engineering Recipe (Agent-Actionable Spec) Any agent or engineer can reproduce the full stack on a single modern FP4/FP8-capable GPU (`PyTorch >= 2.6` with `FlexAttention`, `Triton`, `torch.compile`, `transformers`) using the exact settings below. ### Model Structural Facts (`google/cellgemma-e4b`) - `42` layers: `L0..22` (`20` sliding `W = 512, D = 256` + `3` full `{5, 11, 17}, D = 512`), `L23` (full K/V + branch Q/O/MLP/PLE), `L24..41` (`18` KV-shared layers: `15` sliding reusing `L22`, `3` full `{29, 35, 41}` reusing `L23`). - `hidden_size = 2560`, `intermediate_size = 10240`, `H = 8`, `H_kv = 2`, `attn.scaling = 1.0`, `partial_rotary_factor = 0.25` (full-attention rotates ONLY 128 dims `[0:64]` & `[256:320]`), `final_logit_softcapping = 30.0`, `hidden_activation = gelu_pytorch_tanh`, `rms_norm_eps = 1e-6`, `Gemma4RMSNorm` multiplies directly by `weight` (**not** `1 + weight`). - **Strict Prompt Rules:** Always use RDKit **canonical aromatic SMILES** (`canonical=True, isomericSmiles=True, kekuleSmiles=False`) and unmodified field order `Drug name → Drug SMILES → Concentration`. Never reorder fields or re-root SMILES (see Novel Finding #4). --- ### Recipe Step 1 — Exact Final Judge (`V2-Fast`, Strictly `100% 0.0-ULP` BF16) > **Rule:** Never quantize the final Judge or Stage-2 verification. Cellular gene residuals exhibit `99%` Dirac-zero sparsity and extreme `1%` biological tails (`>100×` excess kurtosis), so final scientific scoring must remain pure BF16. 1. **Canonical Drug-First Prompt + 1-Pass Dual-Branch (`+`/`-`) Readout:** Append `[plus_id, minus_id]` at positions `[Lb, Lb + 1]` sharing `pos_id = Lb` with cross-branch attention masked (`~((q == Lb+1) & (k == Lb))`). 2. **Weight & Algebra Fusions:** Concatenate `W_qkv` (`L0..22`), `W_kv23`, `W_gate_up` (`L0..41`). Apply partial-RoPE strictly to the 128 active full-attention dims. 3. **PLE Elimination:** Precompute Top-19 Per-Layer Embeddings for `[plus_id, minus_id]` into a single `19 KiB` buffer `[19, 1, 2, 256]` using exact `bf16` scale tensors (`embed_scale`, `proj_scale`, `inp_scale`). 4. **Top-19 KV-Shared Fast Path:** Compute `L23..41` strictly on the 2 branch tokens `[B, 2, 2560]`, and slice `L22` sliding KV to the exact 513 active window keys `[Lb - 511 .. Lb + 1]` (`8.5×` less KV bandwidth on all 15 top sliding layers). 5. **Exact `L0..L4` Causal Light-Cone Shadow Cache (for same-`L_drug` batches):** Because `L0..L4` are 5 consecutive sliding layers (`W = 512`) before the first full layer `L5`, every token `q > drug_end + (i+1)*(W-1)` at layer `i ∈ {0..4}` has zero causal path from the drug. Precompute one clean `B=1` shadow pass (`L0..4`), run only `c_end_i = ceil64(drug_end + (i+1)*511 + 1)` active tokens per layer (with `score_mod=None` since `c_end_4 < Lb`), and splice cached shadow tails up to `c_end_{i+1}`. Precompute all static `BlockMask`s *outside* `forward()` so `torch.compile(..., fullgraph=True)` has zero graph breaks. 6. **Exact `B=1` Unpadded SDPA DMSO Helper:** Compute each cell's DMSO baseline once at `B=1` unpadded (`approx. 0.5–1.5 s/cell`) to remove common-mode batched BF16 rounding drift. --- ### Recipe Step 2 — Ultra-Fast Scout (`B5-RadixTrie` + `S1` + `RAREBAL-LDLQ` Mixed FP4/FP8 + `B5-Align`) 1. **Cell-First Split-KV Prefix Cache:** Cache `[1, H_kv, L, D]` KV tensors for `Source + Mean Global` once per cell (`L0..23`), truncating sliding layers `L0..22` to their last `W - 1 = 511` keys. 2. **DFS Euler-Tour Radix-Trie Packing (`N_MAX = 3328`, `D_MAX = 144`, `B_TOP = 256`):** - Keep `lcp_len = 0` so the trie automatically merges shared prefixes (`Drug name: Compound_X\nDrug SMILES:` + shared SMILES scaffolds) without hoisting Drug tokens into the cell prefix cache. - Number trie nodes in **DFS pre-order** with 1D subtree exit time `tout[u]`, yielding a `approx. 3–5%` sparse causal `BlockMask`: `(k <= q) & (q <= tout[k])` (`BLOCK_SIZE = 64` for sliding, `32` for full). - Merge Prefix attention and Tree attention via exact FP32 online-softmax LSE merging (`AuxRequest(lse=True)`). - **Decoupled Top-19 Mega-Batching:** Accumulate multiple Bottom-23 trie micro-batches up to `B_TOP = 256` (`Q_len = 512`), gather each molecule's root-to-leaf ancestor KV (`D_MAX`), and run `L23..41` in one compute-bound mega-batch (`100% BF16`, keeping Top-19 & `lm_head` unquantized!). 3. **`S1` Zero-Weight Sliding-Window Anti-Goodhart Mask (CRITICAL):** - Block all Target/`+`/`-` queries from attending to raw Drug suffix keys across all `35` sliding layers (`~(is_tgt[q] & (~is_tgt[k]))`), and reset Target/`+`/`-` sliding RoPE positions to `[0 .. L_tgt]` while slicing `L22` prefix KV to its last `511 - L_tgt = 502` `Mean_tail` keys (`score_mod=None` on all 15 top sliding layers!). 4. **Native Microscaled `Mixed FP4-MLP + FP8-Attn` on Bottom-23 Only (`RAREBAL-LDLQ` + 0-Cost SmoothQuant):** - Quantize **only Bottom-23 (`L0..22`)** linear projections: `gate_up` & `down_proj` in **`BlockWise1x16` FP4 (`E2M1` + `FP8 E4M3` block scale + static FP32 tensor scale with `1.85×` headroom)**; `qkv` & `o_proj` in **`BlockWise1x32` FP8 (`E4M3` + `E8M0` block scale)**; leave Prefix, Attention, PLE, Top-19 (`L23..41`), and `lm_head` in **100% BF16**. - **0-Cost SmoothQuant (`α = 0.5`):** Fold channel smoothing scales directly into `input_layernorm.weight` ↔ `W_qkv`, `pre_feedforward_layernorm.weight` ↔ `W_gate_up`, and `W_up` rows ↔ `W_down` columns (zero runtime cost). - **`RAREBAL-LDLQ` Weight Calibration:** Run 1 calibration pass over approx. 128 real clinical + evolved suffixes, upweighting Target/`+`/`-` tokens (`4×`) and Top-10% norm tail tokens (`2×`) when forming Hessian $H = X^\top \text{diag}(w) X + 0.01 \bar{d} I$. Factorize $H^{-1} = U^\top U$ (upper Cholesky), sweep column blocks of `16` (FP4) / `32` (FP8) with 4-point MSE scale grid search (`α ∈ {1.00, 0.94, 0.88, 0.82}`), and propagate quantization error via `solve_triangular(U_bb.T, err.T, upper=False).T @ U[c0:c1, c1:]` (**`1.75×` lower MSE** than RTN!). - **Fused Triton Kernels:** Fuse `RMSNorm → FP8/FP4` and `GeGLU → FP8/FP4`, writing scales directly into hardware `SWIZZLE_32_4_4` 1D layout (`idx = ((((r>>7)*C_tiles + (c>>2))<<5) + (r&31))<<4 | (((r&127)>>5)<<2) | (c&3)`). Keep tensor scales as 0-D `fp32` pointers (avoiding `f64` promotion in Triton IR) and wrap `F.scaled_mm` in `@torch.library.custom_op` + `@register_fake` for zero-graph-break `torch.compile`. 5. **`B5-Align` Zero-Overhead Top-19 Distillation (`0.00%` Runtime Cost):** - Generate approx. 300 exact `(cell, drug)` teacher targets (`h_top`, `logp`, DMSO) across 6 diverse lineages using `V2-Fast` BF16 (mixing anonymized clinical drugs, named drugs, and mutated OOD anti-inflation probes). - Precompute frozen `B5-S1` Bottom-23 + `L23_KV` states **once** (since Bottom-23 is frozen, cell prefixes & Bottom-23 FP4/FP8 weights remain 100% invariant!). - Train **Rank-32 LoRA (`α = 64`) on Top-19 (`L23..41`: `q, o, gate, up, down`)** for `360` AdamW steps (`lr = 3e-4 → 1e-5`, `B = 16` paired with DMSO) minimizing: $$\mathcal{L} = 2.5\,\mathcal{L}_{\text{tail-signed}} + 0.5\,\text{MSE}(\Delta h_{\text{top}}) + 0.25\,\mathcal{L}_{\text{Jeffreys-KL}}$$ where $\mathcal{L}_{\text{tail-signed}}$ applies **`5×` weight to the Top-2% outer biological tail** of the 19,720-gene differential signed response (trains in **approx. 32 seconds**!). - **Merge `ΔW = (α/r) B A` in-place** directly into `L23..41` weights (and refresh fused `w_gate_up` in-place) → **`0.00%` inference overhead** and 100% plug-and-play with pre-calibrated Bottom-23 FP4/FP8 weights! --- ### Recipe Step 3 — Anti-Goodhart Evolution Runtime & Track-C Multipliers 1. **Multi-Core Async RDKit Proposer:** Persistent forked worker pool + single-parse cheapest-first filter cascade (`MW/TPSA/HBD` → vectorized `BulkTanimotoSimilarity` → `STRICT_SMARTS` → `PAINS/Brenk` → `QED/SA` only on `<10%` survivors) + pre-parsed BRICS `Mol` cache + speculative async lookahead overlapped with GPU scoring (**exposed CPU latency: `7.50 s/gen → 0.11 s/gen`**, **`66×` reduction!**). 2. **GPU-Native Scoring:** Score pathway genes directly on GPU (`4 KB` device-to-host transfer instead of copying `40 MB` logit tensors to CPU). 3. **`CL2` Multi-Kernel Trust-Region Anti-Goodhart GP:** Fit a closed-form GP predicting $\hat{\delta}(m) = \text{V2}(m) - \text{B5}(m)$ with epistemic uncertainty $\hat{\sigma}_\delta(m)$ using `0.50 * K_htop_cosRBF + 0.35 * K_ECFP4_Tanimoto + 0.15 * K_desc`. At Gens `{0, 3, 6, 9, 12}`, evaluate `8` Top-LCB winners + `4` Max-UCB high-uncertainty "trap probes" on `V2-Fast` BF16 and rank parents by $J_{\text{LCB}} = \text{B5} + \hat{\delta} - 0.75\hat{\sigma}_\delta$. 4. **Exact `0.0-ULP` Archive Rescoring (LSE Cancellation Theorem):** Because $\log\text{softmax}(z)_g - \overline{\log\text{softmax}(z)} \equiv z_g - \bar{z}$, storing only FP16 `h_top [N, 2, 2560]` + FP32 `mean_z [N, 2]` lets any new $K$-gene disease signature rescore all `813,112` archived `(cell, drug)` pairs in **`98.8 ms`** (`2,034×` faster, `r = 0.99999996`, approx. 0.8 ULP!) by multiplying only $K \ll 19{,}720$ rows of `lm_head`. 5. **Track-C CUR Active Multi-Cell Completion:** Use Rank-Revealing Pivoted QR on top-$r$ singular vectors to select **`16–20` anchor cell lines out of `67`** (`3.35×–4.19×` speedup) and reconstruct all unseen cell responses via closed-form Ridge-CUR (`pan-cell r = 0.967–0.983`, `97%–100%` Top-1% hit recall). --- ## 4. Six Findings 1. **Root Cause of Cell-First Evolution Gaming (`38.6%` Sliding-Window Hijack) & Zero-Weight `S1` Fix:** - Moving the drug to the end of the prompt (`[Source | Mean | Drug]`) caused `38.6%` of top-15 sliding-window attention mass at `Target/+/-` to be hijacked by raw Drug tokens (vs `0%` in canonical Drug-First Vanilla, where Drug sits `> 4,000` tokens outside the `W = 512` window). - Blocking Drug keys from sliding attention at `Target/+/-` (`S1`) with **zero trained weights** jumped unseen 27-evo correlation from `r = 0.472 → 0.824` and cut MAE **`4.15×`** (`8.10 → 1.93`). 2. **Asymmetric Top-19 Distillation (`B5-Align`) Breaks the Fidelity–Speed Tradeoff at `0.00%` Cost:** - Freezing Bottom-23 (`L0..22`) keeps all cell KV caches and quantized FP4/FP8 weights 100% invariant while distilling only the 2-token branch through Top-19 (`L23..41`) with `5×` outer-tail weighting. In **32 seconds** of training, unseen 27-evo fidelity leaped from `r = 0.824 → 0.9475` (`ρ = 0.386 → 0.9115`, MAE `8.10 → 1.15`, **`7.0×` lower error**) and unseen 30-item Vanilla sanity check jumped to **`99.0%` NDCG@10** at **zero extra runtime FLOPs**. 3. **Mixed `FP4-MLP + FP8-Attn` (`RAREBAL-LDLQ`) Beats Both Uniform FP8 and Uniform FP4:** - On Bottom-23, quantizing the compute-heavy MLPs (`gate_up`, `down_proj`) to `BlockWise1x16` FP4 while keeping sensitive `qkv`/`o_proj` in `BlockWise1x32` FP8 and Top-19/`lm_head` in BF16 proved **simultaneously faster (`1.66M/hr` vs `1.64M/hr`) and more accurate (`r_up = 0.99944` vs `0.99862`)** than uniform FP4 — while honoring full BF16 precision on the final Judge. 4. **Strict Prompt-Symmetry Falsification (Negative Result Worth Knowing):** - Two tempting lossless-prefix ideas failed empirical gating and were rejected: placing `Concentration` before `Drug` (`H1`, `r = 0.82–0.90`) and re-rooting canonical aromatic SMILES onto shared anchors (`H2`, `r = 0.58–0.64`). Strict canonical aromatic SMILES and unmodified field order are mandatory. 5. **Online `CL2` Multi-Kernel GP Eliminates Residual Goodhart Drift in Live Evolution:** - On a historical Goodhart-failing BBB evolution pair (`U-251 MG`), combining `B5-S1 Mixed FP4/FP8` + async multi-core RDKit + 58 `V2-Fast` GP anchors ran all 15 generations in **`43.8 s`** (`0.58 s/gen` pure evo), cut Top-5 MAE by **`8.2×`** (`1.16 → 0.14`), and achieved **`5/5` finalists beating seed (`0%` Goodhart, `+1.12` verified `0.0-ULP` BF16 gain)**. 6. **Analytical 1-Step Scoring vs OG Stochastic 2-Stage Rollouts (`99%` Sparsity Ceiling):** - Benchmarking directly against 60 authentic unmodified 4-seed `model.generate(T=0.7)` + Stage-2 `ExpressionDecoder` rollouts revealed that even the OG stochastic pipeline only agrees with *itself* at `74.7%` Cross-Tier (`80%` Order Acc, `98.4%` NDCG@5) because `approx. 99%` Dirac-zero sparsity clips Mid/Bottom drugs near `0.000` LFC. Our `4,921×` faster Scout achieved **`95.2%` NDCG@5** and **`72.0%` Cross-Tier** — right against the OG method's own noise ceiling — while putting `5/5` real positive OG winners (including `#1` and `#2`) in the Top 5. - Separately, replicating the published `GPNMB` thyroid case study confirmed that matching the paper's `#1` lead (`NVP-BHG712`) requires combining **both** modalities used in their cascade (`19,880`-gene virtual CRISPR knockdown concordance where `EPHA2` ranked `#1` + filtered compound screen + cytotoxicity exclusion), not a single low-dose compound-only screen. --- > **Research-only disclaimer:** This engineering specification is provided "as is" for computational biology research and systems benchmarking only. Predictions generated by virtual-cell models are unvalidated *in silico* hypotheses, not medical advice, clinical evidence, or treatment recommendations.