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 (0swaps).- 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/10leads),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-ULPexact across 813K saved drug-cell pairs):approx. 9.3 Billion ×vs Vanilla 8K (98.8 mstotal,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:
- 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). - The Judge (
V2-Fast, strictly 100% lossless BF16) re-scores finalists and anchors active evolution to99.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)
42layers:L0..22(20slidingW = 512, D = 256+3full{5, 11, 17}, D = 512),L23(full K/V + branch Q/O/MLP/PLE),L24..41(18KV-shared layers:15sliding reusingL22,3full{29, 35, 41}reusingL23).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,Gemma4RMSNormmultiplies directly byweight(not1 + weight).- Strict Prompt Rules: Always use RDKit canonical aromatic SMILES (
canonical=True, isomericSmiles=True, kekuleSmiles=False) and unmodified field orderDrug 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 extreme1%biological tails (>100×excess kurtosis), so final scientific scoring must remain pure BF16.
- Canonical Drug-First Prompt + 1-Pass Dual-Branch (
+/-) Readout: Append[plus_id, minus_id]at positions[Lb, Lb + 1]sharingpos_id = Lbwith cross-branch attention masked (~((q == Lb+1) & (k == Lb))). - 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. - PLE Elimination: Precompute Top-19 Per-Layer Embeddings for
[plus_id, minus_id]into a single19 KiBbuffer[19, 1, 2, 256]using exactbf16scale tensors (embed_scale,proj_scale,inp_scale). - Top-19 KV-Shared Fast Path: Compute
L23..41strictly on the 2 branch tokens[B, 2, 2560], and sliceL22sliding KV to the exact 513 active window keys[Lb - 511 .. Lb + 1](8.5×less KV bandwidth on all 15 top sliding layers). - Exact
L0..L4Causal Light-Cone Shadow Cache (for same-L_drugbatches): BecauseL0..L4are 5 consecutive sliding layers (W = 512) before the first full layerL5, every tokenq > drug_end + (i+1)*(W-1)at layeri ∈ {0..4}has zero causal path from the drug. Precompute one cleanB=1shadow pass (L0..4), run onlyc_end_i = ceil64(drug_end + (i+1)*511 + 1)active tokens per layer (withscore_mod=Nonesincec_end_4 < Lb), and splice cached shadow tails up toc_end_{i+1}. Precompute all staticBlockMasks outsideforward()sotorch.compile(..., fullgraph=True)has zero graph breaks. - Exact
B=1Unpadded SDPA DMSO Helper: Compute each cell's DMSO baseline once atB=1unpadded (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)
- Cell-First Split-KV Prefix Cache: Cache
[1, H_kv, L, D]KV tensors forSource + Mean Globalonce per cell (L0..23), truncating sliding layersL0..22to their lastW - 1 = 511keys. - DFS Euler-Tour Radix-Trie Packing (
N_MAX = 3328,D_MAX = 144,B_TOP = 256):- Keep
lcp_len = 0so 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 aapprox. 3–5%sparse causalBlockMask:(k <= q) & (q <= tout[k])(BLOCK_SIZE = 64for sliding,32for 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 runL23..41in one compute-bound mega-batch (100% BF16, keeping Top-19 &lm_headunquantized!).
- Keep
S1Zero-Weight Sliding-Window Anti-Goodhart Mask (CRITICAL):- Block all Target/
+/-queries from attending to raw Drug suffix keys across all35sliding layers (~(is_tgt[q] & (~is_tgt[k]))), and reset Target/+/-sliding RoPE positions to[0 .. L_tgt]while slicingL22prefix KV to its last511 - L_tgt = 502Mean_tailkeys (score_mod=Noneon all 15 top sliding layers!).
- Block all Target/
- Native Microscaled
Mixed FP4-MLP + FP8-Attnon Bottom-23 Only (RAREBAL-LDLQ+ 0-Cost SmoothQuant):- Quantize only Bottom-23 (
L0..22) linear projections:gate_up&down_projinBlockWise1x16FP4 (E2M1+FP8 E4M3block scale + static FP32 tensor scale with1.85×headroom);qkv&o_projinBlockWise1x32FP8 (E4M3+E8M0block scale); leave Prefix, Attention, PLE, Top-19 (L23..41), andlm_headin 100% BF16. - 0-Cost SmoothQuant (
α = 0.5): Fold channel smoothing scales directly intoinput_layernorm.weight↔W_qkv,pre_feedforward_layernorm.weight↔W_gate_up, andW_uprows ↔W_downcolumns (zero runtime cost). RAREBAL-LDLQWeight 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 of16(FP4) /32(FP8) with 4-point MSE scale grid search (α ∈ {1.00, 0.94, 0.88, 0.82}), and propagate quantization error viasolve_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/FP4andGeGLU → FP8/FP4, writing scales directly into hardwareSWIZZLE_32_4_41D layout (idx = ((((r>>7)*C_tiles + (c>>2))<<5) + (r&31))<<4 | (((r&127)>>5)<<2) | (c&3)). Keep tensor scales as 0-Dfp32pointers (avoidingf64promotion in Triton IR) and wrapF.scaled_mmin@torch.library.custom_op+@register_fakefor zero-graph-breaktorch.compile.
- Quantize only Bottom-23 (
B5-AlignZero-Overhead Top-19 Distillation (0.00%Runtime Cost):- Generate approx. 300 exact
(cell, drug)teacher targets (h_top,logp, DMSO) across 6 diverse lineages usingV2-FastBF16 (mixing anonymized clinical drugs, named drugs, and mutated OOD anti-inflation probes). - Precompute frozen
B5-S1Bottom-23 +L23_KVstates 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) for360AdamW steps (lr = 3e-4 → 1e-5,B = 16paired 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}}$ applies5×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 Ain-place directly intoL23..41weights (and refresh fusedw_gate_upin-place) →0.00%inference overhead and 100% plug-and-play with pre-calibrated Bottom-23 FP4/FP8 weights!
- Generate approx. 300 exact
Recipe Step 3 — Anti-Goodhart Evolution Runtime & Track-C Multipliers
- Multi-Core Async RDKit Proposer: Persistent forked worker pool + single-parse cheapest-first filter cascade (
MW/TPSA/HBD→ vectorizedBulkTanimotoSimilarity→STRICT_SMARTS→PAINS/Brenk→QED/SAonly on<10%survivors) + pre-parsed BRICSMolcache + speculative async lookahead overlapped with GPU scoring (exposed CPU latency:7.50 s/gen → 0.11 s/gen,66×reduction!). - GPU-Native Scoring: Score pathway genes directly on GPU (
4 KBdevice-to-host transfer instead of copying40 MBlogit tensors to CPU). CL2Multi-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)$ using0.50 * K_htop_cosRBF + 0.35 * K_ECFP4_Tanimoto + 0.15 * K_desc. At Gens{0, 3, 6, 9, 12}, evaluate8Top-LCB winners +4Max-UCB high-uncertainty "trap probes" onV2-FastBF16 and rank parents by $J{\text{LCB}} = \text{B5} + \hat{\delta} - 0.75\hat{\sigma}_\delta$.- Exact
0.0-ULPArchive Rescoring (LSE Cancellation Theorem): Because $\log\text{softmax}(z)_g - \overline{\log\text{softmax}(z)} \equiv z_g - \bar{z}$, storing only FP16h_top [N, 2, 2560]+ FP32mean_z [N, 2]lets any new $K$-gene disease signature rescore all813,112archived(cell, drug)pairs in98.8 ms(2,034×faster,r = 0.99999996, approx. 0.8 ULP!) by multiplying only $K \ll 19{,}720$ rows oflm_head. - Track-C CUR Active Multi-Cell Completion: Use Rank-Revealing Pivoted QR on top-$r$ singular vectors to select
16–20anchor cell lines out of67(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
- Root Cause of Cell-First Evolution Gaming (
38.6%Sliding-Window Hijack) & Zero-WeightS1Fix:- Moving the drug to the end of the prompt (
[Source | Mean | Drug]) caused38.6%of top-15 sliding-window attention mass atTarget/+/-to be hijacked by raw Drug tokens (vs0%in canonical Drug-First Vanilla, where Drug sits> 4,000tokens outside theW = 512window). - Blocking Drug keys from sliding attention at
Target/+/-(S1) with zero trained weights jumped unseen 27-evo correlation fromr = 0.472 → 0.824and cut MAE4.15×(8.10 → 1.93).
- Moving the drug to the end of the prompt (
- Asymmetric Top-19 Distillation (
B5-Align) Breaks the Fidelity–Speed Tradeoff at0.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) with5×outer-tail weighting. In 32 seconds of training, unseen 27-evo fidelity leaped fromr = 0.824 → 0.9475(ρ = 0.386 → 0.9115, MAE8.10 → 1.15,7.0×lower error) and unseen 30-item Vanilla sanity check jumped to99.0%NDCG@10 at zero extra runtime FLOPs.
- Freezing Bottom-23 (
- 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) toBlockWise1x16FP4 while keeping sensitiveqkv/o_projinBlockWise1x32FP8 and Top-19/lm_headin BF16 proved simultaneously faster (1.66M/hrvs1.64M/hr) and more accurate (r_up = 0.99944vs0.99862) than uniform FP4 — while honoring full BF16 precision on the final Judge.
- On Bottom-23, quantizing the compute-heavy MLPs (
- Strict Prompt-Symmetry Falsification (Negative Result Worth Knowing):
- Two tempting lossless-prefix ideas failed empirical gating and were rejected: placing
ConcentrationbeforeDrug(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.
- Two tempting lossless-prefix ideas failed empirical gating and were rejected: placing
- Online
CL2Multi-Kernel GP Eliminates Residual Goodhart Drift in Live Evolution:- On a historical Goodhart-failing BBB evolution pair (
U-251 MG), combiningB5-S1 Mixed FP4/FP8+ async multi-core RDKit + 58V2-FastGP anchors ran all 15 generations in43.8 s(0.58 s/genpure evo), cut Top-5 MAE by8.2×(1.16 → 0.14), and achieved5/5finalists beating seed (0%Goodhart,+1.12verified0.0-ULPBF16 gain).
- On a historical Goodhart-failing BBB evolution pair (
- 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-2ExpressionDecoderrollouts revealed that even the OG stochastic pipeline only agrees with itself at74.7%Cross-Tier (80%Order Acc,98.4%NDCG@5) becauseapprox. 99%Dirac-zero sparsity clips Mid/Bottom drugs near0.000LFC. Our4,921×faster Scout achieved95.2%NDCG@5 and72.0%Cross-Tier — right against the OG method's own noise ceiling — while putting5/5real positive OG winners (including#1and#2) in the Top 5. - Separately, replicating the published
GPNMBthyroid case study confirmed that matching the paper's#1lead (NVP-BHG712) requires combining both modalities used in their cascade (19,880-gene virtual CRISPR knockdown concordance whereEPHA2ranked#1+ filtered compound screen + cytotoxicity exclusion), not a single low-dose compound-only screen.
- Benchmarking directly against 60 authentic unmodified 4-seed
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.