Hugging Face |
GitHub |
Launch Blog |
Documentation
License: Apache 2.0 | Authors: Google DeepMind
CellGemma is a lightweight, open model built by Google DeepMind on the Gemma 4 E4B architecture, fine-tuned for predicting cellular responses to perturbations. CellGemma is designed to process baseline gene expression together with perturbational information.
CellGemma is a non-conversational model. It uses the Gemma 4 E4B architecture and extends the base tokenizer vocabulary with human protein-coding gene symbols. It was pre-trained on non-perturbation single-cell RNA-seq data from scBaseCount, HCA, and CellxGene on tasks such as cell type annotation, then fine-tuned on 10 public perturbation datasets spanning small-molecule treatments, single and combinatorial CRISPR perturbations, cytokines, and clinical studies.
Rather than predicting the full response, CellGemma predicts the residual from a mean-shift baseline. The mean shift captures responses shared across perturbations, so CellGemma only needs to predict the perturbation-specific responses that are not shared. A single CellGemma checkpoint covers all datasets and perturbation types, while the ExpressionDecoders are dataset-specific. CellGemma operates as a two-stage system:
CellGemma): A decoder-only language model with an extended gene-native vocabulary that predicts ranked residual differentially expressed genes (+GENE for upregulated, -GENE for downregulated).ExpressionDecoder): Lightweight dataset-specific MLP decoders (decoders/<dataset>/) that map Stage 1 ranked gene outputs and baseline expression into continuous post-perturbation gene expression and log-fold change (LFC) vectors. This repository includes pretrained decoders for:tahoe, l1000, emeraldbay, sciplexnadig/replogle, vcc, normanparse, dong, tischSource:)Mean Global prediction:).+GENE for upregulated, -GENE for downregulated).CellGemma is built on Gemma 4 E4B and extends the base tokenizer with 20K human protein-coding gene symbols. Each gene is encoded as a single token instead of being split into subword pieces.
The "E" in E4B stands for effective parameters. E4B uses Per-Layer Embeddings (PLE), which gives each decoder layer its own small embedding for every token. These tables are large but are only used for fast lookups, so the effective parameter count is much smaller than the total. CellGemma also inherits E4B's hybrid attention, which interleaves local sliding window attention with global attention to keep inference fast and memory-efficient. To optimize memory for long contexts, global layers feature unified Keys and Values, and apply Proportional RoPE (p-RoPE).
| Property | Value |
|---|---|
| Base Architecture | Gemma 4 E4B (Dense) |
| Total Parameters | 8B with embeddings |
| Effective Parameters | 4.5B |
| Layers | 42 |
| Sliding Window | 512 tokens |
| Context Length | 16K tokens |
| Vocabulary Size | 282K |
| Supported Modalities | Text |
| Output | Ranked residual DEGs (+GENE / -GENE) |
During inference, CellGemma generates a ranked list of genes (+GENE / -GENE) relative to the mean-shift baseline. A lightweight, dataset-specific ExpressionDecoder then converts this list into continuous expression and log-fold change (LFC) vectors.
CellGemma's performance has been validated across 10 perturbation benchmarks spanning 32 held-out generalization splits (including unseen perturbations, unseen drug mechanisms of action, unseen donors, unseen cell lines, and unseen combinations). In the table below, the metric is Pearson Δ. See Model Data section for the details on benchmark datasets.
| Dataset | Split | CellGemma | Mean Shift Baseline |
|---|---|---|---|
| Tahoe | Unseen Pert./Cell | 0.76 ± 0.01 | 0.56 ± 0.02 |
| Tahoe | Unseen Perturbation | 0.56 ± 0.02 | 0.26 ± 0.02 |
| Tahoe | Unseen Mechanism | 0.56 ± 0.01 | 0.30 ± 0.02 |
| Tahoe | Unseen Cell Line | 0.73 ± 0.01 | 0.59 ± 0.02 |
| EmeraldBay | Unseen Pert./Cell | 0.48 ± 0.02 | 0.30 ± 0.02 |
| EmeraldBay | Unseen Perturbation | 0.25 ± 0.01 | 0.05 ± 0.01 |
| EmeraldBay | Unseen Mechanism | 0.34 ± 0.02 | 0.08 ± 0.01 |
| EmeraldBay | Unseen Cell Line | 0.43 ± 0.02 | 0.25 ± 0.02 |
| SciPlex | Unseen Pert./Cell | 0.23 ± 0.02 | 0.09 ± 0.02 |
| SciPlex | Unseen Perturbation | 0.28 ± 0.02 | 0.10 ± 0.01 |
| SciPlex | Unseen Mechanism | 0.24 ± 0.04 | 0.11 ± 0.03 |
| L1000 | Unseen Pert./Cell | 0.38 ± 0.01 | 0.28 ± 0.01 |
| L1000 | Unseen Perturbation | 0.34 ± 0.01 | 0.18 ± 0.01 |
| L1000 | Unseen Cell Line | 0.15 ± 0.01 | 0.13 ± 0.01 |
| Parse | Unseen Pert./Cell | 0.30 ± 0.01 | 0.20 ± 0.01 |
| Parse | Unseen Perturbation | 0.16 ± 0.01 | 0.06 ± 0.01 |
| Parse | Unseen Donor | 0.20 ± 0.02 | 0.16 ± 0.01 |
| Parse | Unseen Cell Type | 0.29 ± 0.02 | 0.21 ± 0.02 |
| Dong | Unseen Pert./Cell | 0.56 ± 0.10 | 0.39 ± 0.11 |
| Dong | Unseen Perturbation | 0.47 ± 0.06 | 0.36 ± 0.06 |
| Dong | Unseen Donor | 0.58 ± 0.05 | 0.47 ± 0.06 |
| Dong | Unseen Cell Type | 0.53 ± 0.06 | 0.50 ± 0.06 |
| Nadig/Replogle HepG2 | Unseen Perturbation | 0.57 ± 0.01 | 0.44 ± 0.01 |
| Nadig/Replogle Jurkat | Unseen Perturbation | 0.45 ± 0.02 | 0.35 ± 0.01 |
| Nadig/Replogle K562 | Unseen Perturbation | 0.45 ± 0.02 | 0.34 ± 0.01 |
| Nadig/Replogle RPE1 | Unseen Perturbation | 0.61 ± 0.02 | 0.54 ± 0.02 |
| VCC | Unseen Perturbation | 0.16 ± 0.02 | 0.11 ± 0.01 |
| Norman | Both Genes Seen | 0.74 ± 0.02 | 0.53 ± 0.05 |
| Norman | One Gene Seen | 0.49 ± 0.02 | 0.46 ± 0.02 |
| Norman | Both Genes Unseen | 0.55 ± 0.03 | 0.48 ± 0.05 |
| TISCH | Within-Study | 0.53 ± 0.01 | 0.22 ± 0.01 |
| TISCH | Cross-Study | 0.28 ± 0.02 | 0.05 ± 0.01 |
Below is an example showing how to load both CellGemma and an ExpressionDecoder to predict transcriptional changes for a drug perturbation and a genetic knockdown.
To get started, install the necessary dependencies in your environment:
pip install -U transformers torch accelerate safetensors huggingface_hub
CellGemma and ExpressionDecoderimport 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()
def load_hf_json(filename: str):
"""Download a JSON file from the CellGemma Hub repo."""
with open(hf_hub_download(MODEL_ID, filename), encoding="utf-8") as f:
return json.load(f)
class ExpressionDecoder(nn.Module):
"""MLP decoder that predicts the expression change relative to baseline.
The raw output goes through an ELU-like activation scaled by the control
expression. This keeps negative deltas above baseline, so the predicted
expression (baseline + delta) is never negative.
Args:
input_dim: Size of the input feature vector.
hidden_dims: Hidden layer widths.
max_exp_arg: Clamp on the exponent to avoid overflow.
"""
def __init__(self, input_dim, hidden_dims, max_exp_arg=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, control_expression):
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):
"""Load the named 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
CellGemma Generation and ExpressionDecoder ReconstructionPREAMBLE = (
"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."
)
controls_all = load_hf_json("controls_sample.json")
def load_control_cell(dataset: str, cell_idx: int, mean_deltas: dict):
"""Returns genes, control expression and mean-shift baseline."""
controls = controls_all[dataset]
genes = [g.upper() for g in controls["genes"]]
cell = controls["cells"][cell_idx]
ctrl_expr = np.array(cell["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 top_genes(v: np.ndarray, genes: list[str], k: int = 1000) -> str:
"""Formats the top-k expressed genes, highest first, as a sentence."""
ranked = [genes[i] for i in np.argsort(v)[::-1] if v[i] > 0]
return " ".join(ranked[:k])
def build_prompt(perturbation_text, genes, ctrl_expr, baseline) -> str:
return (
f"{PREAMBLE}\n\n{perturbation_text}\n\n"
f"Source: {top_genes(ctrl_expr, genes)}\n\n"
f"Mean Global prediction: {top_genes(baseline, genes)}\n"
"Target: "
)
def generate(
prompt: str, temperature: float = 0.7, max_new_tokens: int = 8192
) -> str:
"""Generates ranked residual DEGs (+GENE / -GENE) with CellGemma."""
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],
)
return tokenizer.decode(
outputs[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
).strip()
def parse_genes(text: str, gene_to_idx: dict) -> tuple[list, list]:
"""Splits model output into known upregulated and downregulated genes."""
tokens = text.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(text, genes, ctrl_expr, baseline, decoder):
"""Returns (predicted_expr, predicted_lfc) using the ExpressionDecoder."""
gene_to_idx = {g: i for i, g in enumerate(genes)}
up, down = parse_genes(text, gene_to_idx)
residual_vec = np.zeros_like(baseline)
if up or down:
task_oh = [0.0] * 7 + [1.0] # mean_global residual task
feats, ctrl_vals, idxs = [], [], []
for is_up, g_list in ((1.0, up), (0.0, down)):
for rank, g in enumerate(g_list):
idx = gene_to_idx[g]
feats.append(
[is_up, float(rank), float(len(up)), float(len(down))]
+ task_oh
)
ctrl_vals.append(baseline[idx])
idxs.append(idx)
with torch.no_grad():
deltas = decoder(torch.tensor(feats), torch.tensor(ctrl_vals))
residual_vec[idxs] = deltas.cpu().numpy().flatten()
predicted_expr = baseline + residual_vec
return predicted_expr, predicted_expr - ctrl_expr
def predict(
dataset: str,
perturbation_text: str,
cell_idx: int = 0,
max_new_tokens: int = 8192,
):
"""Returns (text_output, predicted_expr, predicted_lfc) for one cell."""
decoder, mean_deltas = load_decoder(dataset)
genes, ctrl_expr, baseline = load_control_cell(
dataset, cell_idx, mean_deltas
)
prompt = build_prompt(perturbation_text, genes, ctrl_expr, baseline)
text = generate(prompt, max_new_tokens=max_new_tokens)
predicted_expr, predicted_lfc = reconstruct(
text, genes, ctrl_expr, baseline, decoder
)
return text, predicted_expr, predicted_lfc
# Drug perturbation (Tahoe)
drug_text, drug_expr, drug_lfc = predict(
"tahoe",
"Drug name: Panobinostat\n"
"Drug SMILES: Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1\n"
"Concentration: 0.5 uM",
)
# Genetic knockdown (K562), described with its knowledge-graph sentence
kg = load_hf_json("kg_sentences.json")
myc_kg = kg["MYC"].strip()
ko_text, ko_expr, ko_lfc = predict("k562", f"Gene knockdown: {myc_kg}")
print(f"Panobinostat text output: {drug_text[:200]}...")
print(f"Predicted expression shape: {drug_expr.shape}")
print(f"MYC knockdown text output: {ko_text[:200]}...")
print(f"Predicted expression shape: {ko_expr.shape}")
For the best performance, use these configurations and best practices:
Use the following sampling configuration, which matches the evaluation setup:
do_sample=Truetemperature=0.7max_new_tokens=8192CellGemma was trained on a fixed prompt template, and changing it can degrade predictions.
<bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n. Tokenize with add_special_tokens=False so <bos> isn't added twice.Source: → Mean Global prediction: → Target:.<|think|> token, or free-form questions. CellGemma is non-conversational and doesn't support thinking mode.Baseline expression should be processed the same way as the training data:
log1p.Source:, list the top 1,000 genes with expression above zero, ranked from highest to lowest.Mean Global prediction:, compute max(0, control + mean_delta_global) using the mean_delta_global.json that belongs to the decoder you're using. Then rank its top 1,000 genes the same way.Use the field formats seen in training:
Drug name:, Drug SMILES:, and Concentration: with explicit units, e.g. 0.5 uM.Gene knockdown: followed by the gene's knowledge-graph sentence from kg_sentences.json, rather than the bare gene symbol.kg_sentences.json. For example, write IFN-γ as IFNG plus its sentence.Gene knockdown: entries in a row, each with its own knowledge-graph sentence.tahoe for single-cell drug screens in cancer lines and k562 for K562 CRISPRi.+ (upregulated) or - (downregulated). Discard tokens that aren't in the gene list for your dataset.Data used for model training and how the data was processed.
CellGemma training datasets are divided into two categories: pre-training datasets containing unperturbed single-cell expression profiles, and fine-tuning datasets spanning small molecules, single and combinatorial CRISPR screens, immune cytokines, and clinical patient cohorts. All fine tuning perturbation datasets are publicly available. See the Benchmark Results section for CellGemma performance on each of the perturbation datasets.
Several data cleaning and filtering methods were applied to the training data:
CellGemma is a specialized biological model fine-tuned for predicting cellular responses to perturbations. Unlike general-purpose language models, it does not undergo conversational alignment, instruction-following safety tuning, or dialogue-level moderation. CellGemma is strictly non-conversational and cannot be made conversational through prompt engineering, as its learned behavior and outputs are dedicated exclusively to gene symbols. Safety mitigations during development were focused on data filtering to reduce exposure to harmful content, personal information, and low-quality data, in alignment with Google's AI Principles.
Since CellGemma produces lists of genes rather than open-ended, user-facing conversational text, conventional conversational safety risks do not manifest in its direct outputs. Instead, safety and reliability considerations manifest downstream in how those biological predictions are interpreted and applied.
Developers and deployers are responsible for evaluating and implementing application-level safeguards, such as laboratory validation and verification against biological baseline controls, appropriate to their specific research use case.
CellGemma has certain limitations that users should be aware of.
CellGemma is a specialized biological prediction model and is not intended for general-purpose natural language dialogue. CellGemma generates lists of genes from input content about baseline cell expression and perturbation, which can be used for a number of downstream applications. The following list of potential uses is not comprehensive. The purpose of this list is to provide contextual information about the possible use-cases that the model creators considered as part of model training and development.
Preclinical Discovery and Translational Research
Computational Biology and Foundation Model Research
In creating an open language model, we have carefully considered the following:
CellGemma is a lightweight, open model that predicts transcriptional responses to diverse perturbations. We are excited to see how developers will use and adapt this model for in silico compound screening, genetic target prioritization, and exploring novel cellular mechanisms.
The model is designed from the ground up for responsible AI development, like other Gemma-family models.
model-00002-of-00003.safetensors 5.7 GiBmodel-00001-of-00003.safetensors 4.6 GiBmodel-00003-of-00003.safetensors 4.1 GiBdecoders/dong/model.safetensors 11.8 KiBdecoders/emeraldbay/model.safetensors 11.8 KiBdecoders/hepg2/model.safetensors 11.8 KiBdecoders/jurkat/model.safetensors 11.8 KiBdecoders/k562/model.safetensors 11.8 KiBdecoders/l1000/model.safetensors 11.8 KiBdecoders/norman/model.safetensors 11.8 KiBdecoders/parse/model.safetensors 11.8 KiBdecoders/rpe1/model.safetensors 11.8 KiBdecoders/sciplex/model.safetensors 11.8 KiBdecoders/tahoe/model.safetensors 11.8 KiBdecoders/tisch/model.safetensors 11.8 KiBdecoders/vcc/model.safetensors 11.8 KiB