Predict cellular perturbations with CellGemma¶
CellGemma is an open biological foundation model built on Gemma 4 E4B. Unlike conversational Gemma models, it does not chat or answer open-ended questions. Instead, it takes a cell's baseline gene expression and a perturbation—such as a small-molecule drug or a genetic knockdown—and predicts how the cell's transcriptome shifts in response.
To make gene-level modeling work cleanly inside a language model, CellGemma extends the Gemma 4 tokenizer with 20K human protein-coding gene symbols so that each gene is a single token.
Try CellGemma in your browser
Want to explore CellGemma before writing any code? Try drug and genetic knockdown predictions interactively in the CellGemma Hugging Face Space.
How the two-stage pipeline works¶
When cells are perturbed, a large part of their transcriptional response is shared across many treatments in a dataset. Rather than predicting the entire post-perturbation expression profile from scratch, CellGemma predicts only the residual—the perturbation-specific shift beyond a dataset-wide mean-shift baseline.
Inference runs in two stages:
- Stage 1 (
CellGemma): A single Gemma 4 E4B checkpoint takes the control cell's baseline expression (Source:) alongside the dataset mean-shift baseline (Mean Global prediction:), both formatted as ranked lists of their top 1,000 expressed genes. It outputs a ranked list of residual differentially expressed genes (+GENEfor upregulated,-GENEfor downregulated), ordered by magnitude. - Stage 2 (
ExpressionDecoder): A lightweight, dataset-specific MLP decoder (decoders/<dataset>/) converts those ranked+GENE/-GENEtokens and the baseline expression back into continuous post-perturbation gene expression and log-fold change (LFC) vectors.
Match the decoder to your assay and cell context. The Hugging Face repository ships pretrained decoders across small-molecule screens (such as tahoe), CRISPR knockdowns (such as k562), cytokines, and clinical cohorts.
1. Load CellGemma and ExpressionDecoders¶
Load the tokenizer and weights for google/cellgemma-e4b in bfloat16 using Hugging Face Transformers:
import json
from huggingface_hub import hf_hub_download
import numpy as np
import safetensors.torch
import torch
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer
MODEL_ID = "google/cellgemma-e4b"
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
device_map="auto",
dtype=torch.bfloat16,
).eval()
print(f"Loaded {MODEL_ID} on {model.device}.")
Running on a smaller GPU
Running CellGemma in full bfloat16 takes roughly 18 GB of VRAM. If you are on a smaller GPU (such as a 16 GB T4), you can install bitsandbytes and load the weights in 4-bit precision with BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16). Note that 4-bit quantization is intended for lightweight demos—its accuracy has not been formally benchmarked.
Next, define the ExpressionDecoder architecture and load the bundled helper files from the Hub repository:
controls_sample.json— sample unperturbed control cells for each supported dataset.kg_sentences.json— knowledge-graph functional descriptions for target genes (used to describe CRISPR knockdowns and cytokines).decoders/<dataset>/— the pretrained MLP weights and dataset-widemean_delta_global.jsonshifts.
Notice how ExpressionDecoder.forward() applies an exponential soft-clamp to negative deltas scaled by the control expression—this guarantees that predicted expression (baseline + delta) can never drop below zero.
def load_hf_json(filename: str, repo_id: str = MODEL_ID):
"""Download and parse a JSON file from the CellGemma Hub repository."""
with open(hf_hub_download(repo_id, filename), encoding="utf-8") as f:
return json.load(f)
controls_data = load_hf_json("controls_sample.json")
kg_sentences = load_hf_json("kg_sentences.json")
class ExpressionDecoder(nn.Module):
"""MLP that reconstructs expression deltas from rank features and baseline expression.
Concatenates the baseline `control_expression` to the feature vector (`input_dim + 1`),
applies `BatchNorm1d`, passes the result through the MLP, and softly clamps negative
deltas so that `baseline + delta >= 0`.
"""
def __init__(
self,
input_dim: int,
hidden_dims: list[int],
max_exp_arg: float = 88.0,
):
super().__init__()
self.input_dim = input_dim
self.max_exp_arg = max_exp_arg
self.bn0 = nn.BatchNorm1d(input_dim + 1)
layers, d = [self.bn0], input_dim + 1
for h in hidden_dims:
layers += [nn.Linear(d, h), nn.ReLU()]
d = h
self.mlp = nn.Sequential(*layers, nn.Linear(d, 1))
def forward(
self, features: torch.Tensor, control_expression: torch.Tensor
) -> torch.Tensor:
eps, ctrl = 1e-6, control_expression.view(-1, 1)
x = self.mlp(torch.cat([features, ctrl], dim=1))
ctrl_safe = ctrl - torch.where(x >= 0, eps, -eps)
exp_term = (x / ctrl_safe).clamp(max=self.max_exp_arg)
neg_delta = ctrl_safe * (torch.exp(exp_term) - 1.0)
return torch.where(x > 0, x, neg_delta) + eps
def load_decoder(name: str) -> tuple[ExpressionDecoder, dict[str, float]]:
"""Load a dataset-specific ExpressionDecoder and its global mean deltas."""
cfg = load_hf_json(f"decoders/{name}/config.json")
decoder = ExpressionDecoder(cfg["input_dim"], cfg["hidden_dims"])
weights = hf_hub_download(MODEL_ID, f"decoders/{name}/model.safetensors")
decoder.load_state_dict(safetensors.torch.load_file(weights))
mean_deltas = load_hf_json(f"decoders/{name}/mean_delta_global.json")
return decoder.eval(), mean_deltas
tahoe_decoder, tahoe_mean_deltas = load_decoder("tahoe")
k562_decoder, k562_mean_deltas = load_decoder("k562")
print("Loaded `tahoe` (drug) and `k562` (genetic) ExpressionDecoders.")
2. Format perturbation prompts¶
CellGemma was trained on a strict prompt structure. Keep the sections in order and leave the instruction preamble unchanged—rewording it, adding a system prompt, or inserting a <|think|> token can degrade predictions.
| Section | What it contains |
|---|---|
| Instruction | Fixed preamble describing the residual perturbation prediction task. |
| Perturbation metadata | For drugs: Drug name:, Drug SMILES:, and Concentration: (with explicit units). For genetic knockdowns: Gene knockdown: followed by the target gene's knowledge-graph sentence from kg_sentences.json. |
Source: |
Top 1,000 positively expressed genes in the control cell, ordered from highest to lowest expression. |
Mean Global prediction: |
Top 1,000 genes of max(0, control_expr + mean_delta_global), giving CellGemma the baseline to predict residuals against. |
Define helper functions to load a control cell, rank its top genes, and assemble prompts for both small molecules and genetic knockdowns:
PROMPT_INSTRUCTION = (
"Examine how the single-cell sample, captured in 'Source:', responds"
" transcriptionally to the perturbation under the stated experimental"
" conditions. You are given the dataset-wide average prediction in 'Mean"
" Global prediction:' and you need to predict the residual from that mean"
" to the true final expression."
)
def load_control_cell(
dataset: str, cell_idx: int, mean_deltas: dict[str, float]
) -> tuple[list[str], np.ndarray, np.ndarray]:
"""Return (genes, control expression, mean-shift baseline) for one cell."""
controls = controls_data[dataset]
genes = [g.upper() for g in controls["genes"]]
ctrl_expr = np.array(
controls["cells"][cell_idx]["expression"], dtype=np.float32
)
mean_deltas = {k.upper(): float(v) for k, v in mean_deltas.items()}
mean_vec = np.array([mean_deltas[g] for g in genes], dtype=np.float32)
baseline = np.maximum(0.0, ctrl_expr + mean_vec)
return genes, ctrl_expr, baseline
def build_source_sentence(
expr: np.ndarray, gene_names: list[str], top_k: int = 1000
) -> str:
"""Format an expression vector into a rank-ordered top-K gene sentence."""
ranked = [gene_names[i] for i in np.argsort(expr)[::-1] if expr[i] > 0]
return " ".join(ranked[:top_k])
def build_prompt(
perturbation_text: str,
gene_names: list[str],
ctrl_expr: np.ndarray,
baseline: np.ndarray,
) -> str:
"""Assemble the fixed CellGemma perturbation prompt template."""
return (
f"{PROMPT_INSTRUCTION}\n\n"
f"{perturbation_text}\n\n"
f"Source: {build_source_sentence(ctrl_expr, gene_names)}\n\n"
f"Mean Global prediction: {build_source_sentence(baseline, gene_names)}\n"
"Target: "
)
def drug_perturbation_text(
drug_name: str, smiles: str, concentration_um: float
) -> str:
"""Format small-molecule perturbation metadata."""
return (
f"Drug name: {drug_name}\n"
f"Drug SMILES: {smiles}\n"
f"Concentration: {concentration_um} uM"
)
def knockdown_perturbation_text(target_gene: str) -> str:
"""Format a genetic knockdown using the target's knowledge-graph sentence."""
return f"Gene knockdown: {kg_sentences[target_gene].strip()}"
Let's select a single control cell from the tahoe dataset and build a drug perturbation prompt for Panobinostat at 0.5 uM:
tahoe_genes, tahoe_ctrl_expr, tahoe_baseline = load_control_cell(
"tahoe", cell_idx=0, mean_deltas=tahoe_mean_deltas
)
DRUG_PROMPT = build_prompt(
drug_perturbation_text(
drug_name="Panobinostat",
smiles="Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1",
concentration_um=0.5,
),
tahoe_genes,
tahoe_ctrl_expr,
tahoe_baseline,
)
print(DRUG_PROMPT[:500] + "...")
3. Predict a drug perturbation¶
Now we run Stage 1. Wrap the prompt in Gemma 4's turn tokens (<bos><|turn>user\n...<turn|>\n<|turn>model\n) and tokenize with add_special_tokens=False so <bos> is not added twice. CellGemma is sampled with temperature=0.7, so individual gene lists will vary slightly across runs.
Quickstart token limit
MAX_NEW_TOKENS is set to 50 below so this walkthrough completes quickly. For full predictions matching the model card benchmarks, increase MAX_NEW_TOKENS to 8192 so CellGemma can finish its complete ranked gene list.
MAX_NEW_TOKENS = 50
TEMPERATURE = 0.7
def generate_cellgemma_response(
prompt: str,
temperature: float = TEMPERATURE,
max_new_tokens: int = MAX_NEW_TOKENS,
) -> str:
"""Generate ranked residual DEGs (+GENE / -GENE) for a CellGemma prompt."""
inputs = tokenizer(
f"<bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n",
return_tensors="pt",
add_special_tokens=False,
).to(model.device)
eot_id = tokenizer.convert_tokens_to_ids("<turn|>")
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=True,
temperature=temperature,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=[tokenizer.eos_token_id, eot_id],
)
gen_tokens = outputs[0, inputs["input_ids"].shape[1] :]
return tokenizer.decode(gen_tokens, skip_special_tokens=True).strip()
drug_response = generate_cellgemma_response(DRUG_PROMPT)
print(drug_response)
4. Reconstruct continuous gene expression¶
Stage 2 turns those discrete +GENE and -GENE tokens back into continuous expression numbers.
First, we split the generated tokens into upregulated (+) and downregulated (-) lists, discarding any token not present in the dataset's gene vocabulary while preserving rank order—genes predicted earlier correspond to larger residual shifts. Then we pass each gene's direction, rank, list lengths, task indicator, and baseline expression into tahoe_decoder to obtain per-gene residual deltas (residual_vec).
Adding residual_vec to baseline gives the predicted post-perturbation expression, and subtracting ctrl_expr yields the predicted log-fold change (LFC):
# Task one-hot encoding for the `mean_global` residual task
_MEAN_GLOBAL_TASK_ONE_HOT = [0.0] * 7 + [1.0]
def parse_output_sentence(
sentence: str, gene_to_idx: dict[str, int]
) -> tuple[list[str], list[str]]:
"""Split model output into known upregulated and downregulated genes."""
tokens = sentence.split()
up = [t[1:].upper() for t in tokens if t.startswith("+")]
down = [t[1:].upper() for t in tokens if t.startswith("-")]
up = [g for g in up if g in gene_to_idx]
down = [g for g in down if g in gene_to_idx]
return up, down
def reconstruct_expression(
response_text: str,
gene_names: list[str],
ctrl_expr: np.ndarray,
baseline: np.ndarray,
decoder: ExpressionDecoder,
) -> tuple[np.ndarray, np.ndarray]:
"""Return (predicted_expr, predicted_lfc) using the ExpressionDecoder."""
gene_to_idx = {g: i for i, g in enumerate(gene_names)}
up, down = parse_output_sentence(response_text, gene_to_idx)
residual_vec = np.zeros_like(baseline)
if up or down:
features, ctrl_vals, indices = [], [], []
for is_up, genes in ((1.0, up), (0.0, down)):
for rank, gene in enumerate(genes):
idx = gene_to_idx[gene]
features.append(
[is_up, float(rank), float(len(up)), float(len(down))]
+ _MEAN_GLOBAL_TASK_ONE_HOT
)
ctrl_vals.append(baseline[idx])
indices.append(idx)
with torch.no_grad():
deltas = decoder(
torch.tensor(features, dtype=torch.float32),
torch.tensor(ctrl_vals, dtype=torch.float32),
)
residual_vec[indices] = deltas.cpu().numpy().flatten()
predicted_expr = baseline + residual_vec
return predicted_expr, predicted_expr - ctrl_expr
pred_drug_expr, drug_lfc_vec = reconstruct_expression(
response_text=drug_response,
gene_names=tahoe_genes,
ctrl_expr=tahoe_ctrl_expr,
baseline=tahoe_baseline,
decoder=tahoe_decoder,
)
print(f"Control expression shape: {tahoe_ctrl_expr.shape}")
print(f"Predicted expression shape: {pred_drug_expr.shape}")
print(f"Predicted LFC vector shape: {drug_lfc_vec.shape}")
5. Predict a genetic knockdown¶
The same CellGemma checkpoint handles CRISPR perturbations without changing weights. Only two pieces swap out:
- Describe the target gene (
MYC) using its knowledge-graph sentence fromkg_sentences.jsonviaknockdown_perturbation_text("MYC"), rather than passing a bare gene symbol. - Pair the
k562control cell with the matchedk562ExpressionDecoder.
k562_genes, k562_ctrl_expr, k562_baseline = load_control_cell(
"k562", cell_idx=0, mean_deltas=k562_mean_deltas
)
GENETIC_PROMPT = build_prompt(
knockdown_perturbation_text("MYC"),
k562_genes,
k562_ctrl_expr,
k562_baseline,
)
genetic_response = generate_cellgemma_response(GENETIC_PROMPT)
print(genetic_response)
pred_ko_expr, ko_lfc_vec = reconstruct_expression(
response_text=genetic_response,
gene_names=k562_genes,
ctrl_expr=k562_ctrl_expr,
baseline=k562_baseline,
decoder=k562_decoder,
)
print(f"Control expression shape: {k562_ctrl_expr.shape}")
print(f"Predicted expression shape: {pred_ko_expr.shape}")
print(f"Predicted LFC vector shape: {ko_lfc_vec.shape}")
What's next¶
Explore drug and CRISPR perturbation predictions interactively in your browser.
Download the E4B weights, pretrained dataset decoders, and helper files.
Full architecture details, 32 benchmark splits, preprocessing rules, and limitations.