CellGemma

CellGemma (google/cellgemma-e4b) is an open biological foundation model developed by Google DeepMind on the Gemma 4 E4B architecture. Given a human cell's baseline gene expression and a biological or chemical intervention, CellGemma predicts transcriptional shifts as ranked residual differentially expressed genes (+GENE for upregulated, -GENE for downregulated). A lightweight, dataset-specific ExpressionDecoder then maps those ranked gene tokens into continuous post-perturbation gene expression and log-fold change (LFC) vectors. For full architecture, benchmark, and wet-lab validation details, see the CellGemma technical report (PDF).

This document describes how to deploy and query CellGemma using Model Garden on Gemini Enterprise Agent Platform, including client-side guardrails for preprocessing, routing, batch response parsing, and Stage 2 reconstruction.

CellGemma weights are released under the Apache 2.0 license on Hugging Face and are available for open research and commercial use through Model Garden (publishers/hf-google/models/cellgemma-e4b). To run CellGemma directly in your browser without deploying an endpoint, try the CellGemma Studio applet in Google AI Studio.

Capabilities

CellGemma was pretrained on single-cell profiles from CZ CELLxGENE Discover, Human Cell Atlas (HCA), scBaseCount, and WikiCrow, then fine-tuned on 10 public perturbation datasets covering 32 held-out generalization splits. Across all 32 splits, CellGemma recovers 48.9% of achievable biological signal (Pearson delta), beating the population mean-shift baseline (32.7%).

Deploying CellGemma on Agent Platform supports four perturbation modalities from a single checkpoint:

  • Small-molecule drugs: Predicts cellular responses conditioned on drug name, canonical SMILES structure, and concentration.

  • Single and combinatorial CRISPR perturbations: Models single and pairwise CRISPRi/CRISPRa knockdowns and activations conditioned on knowledge-graph gene summaries.

  • Immune cytokines: Predicts transcriptional shifts under single and combinatorial cytokine stimulations such as IFNG, IFNB1, and TNF.

  • Clinical therapies: Models patient tumor microenvironment responses to clinical treatments.

Two-stage residual architecture

Rather than predicting full post-perturbation expression from scratch, CellGemma predicts the residual from a dataset-wide mean-shift baseline:

  • Stage 1 (CellGemma, GPU on Agent Platform): A 42-layer Gemma 4 E4B decoder (8B total parameters with Per-Layer Embeddings, 4.5B effective parameters, approximately 14.4 GiB in bfloat16, 16,384-token context) whose 282,240-token vocabulary adds 19,881 human protein-coding gene symbols. It outputs ranked +GENE and -GENE residual tokens.

  • Stage 2 (ExpressionDecoder, CPU client-side): Pretrained 3-layer MLP decoders (decoders/<dataset>/ in google/cellgemma-e4b) that convert Stage 1 ranks and baseline expression into non-negative continuous expression and LFC vectors.

Property Value
Model Garden ID publishers/hf-google/models/cellgemma-e4b (version 001)
Base architecture Gemma 4 E4B (Dense, 42 layers, Per-Layer Embeddings, 512-token sliding window and global p-RoPE attention)
Parameters 8B total / 4.5B effective (~14.4 GiB bfloat16)
Context length 16,384 tokens (up to 8,192 output tokens recommended)
Vocabulary size 282,240 (includes 19,881 human protein-coding gene symbols)
License Apache 2.0
Pretrained decoders (13) Small molecules: tahoe, l1000, emeraldbay, sciplex
CRISPR: hepg2, jurkat, k562, rpe1, vcc, norman
Cytokines and clinical: parse, dong, tisch

Considerations and required client guardrails

The default Model Garden deployment serves CellGemma on vllm.entrypoints.api_server, which accepts raw text prompts without domain validation. Account for the following constraints and apply the listed mitigations in your client or wrapper service:

  • Non-conversational serving routes: CellGemma ships without a chat_template and outputs +GENE/-GENE gene symbols only. OpenAI /chat/completions returns HTTP 400, and /completions and /models return HTTP 404. Send all requests to :predict, :rawPredict, or :streamRawPredict.

  • Dedicated endpoint DNS routing: One-click deployments enable a dedicated endpoint. Send requests to the endpoint's dedicatedEndpointDns using its named endpoint ID (mg-endpoint-...). Calling the shared aiplatform.googleapis.com domain returns HTTP 400.

  • Explicit <bos> token required: The vLLM container doesn't prepend <bos> automatically. Omitting <bos> alters gene rankings (shifting up to 42% of top-64 upregulated genes on K562 GATA1 knockdown). Always wrap prompts as <bos><|turn>user\n{prompt}<turn|>\n<|turn>model\n and pass raw_response: true and stop: ["<turn|>", "<eos>"].

  • Silent biological degradation on non-canonical SMILES or lowercase genes: The endpoint returns HTTP 200 with syntactically valid gene tokens even when formatting breaks model assumptions:

    • Canonicalize SMILES with RDKit: Passing non-canonical Kekule SMILES can degrade predictions into generic ribosomal responses. Always normalize SMILES with Chem.MolToSmiles(mol, canonical=True, isomericSmiles=True) and reject unparseable structures before calling the endpoint.
    • Uppercase HGNC gene symbols: Lowercase symbols split into subword tokens instead of gene-native tokens and drop output overlap with uppercase prompts near zero. Convert all symbols in Source: and Mean Global prediction: to uppercase HGNC format.
  • Context limit and 2-token-per-gene budget: Space-separated gene symbols consume two tokens each (space plus gene token). A standard 1,000-gene Source: and 1,000-gene Mean Global prediction: prompt uses approximately 4,127 tokens, leaving approximately 12,257 tokens for generation inside the 16,384-token window. Requests where prompt_tokens + max_tokens > 16384 fail with HTTP 400.

  • Single-request latency and timeouts: On the default 1x NVIDIA_RTX_PRO_6000 (--enforce-eager), single-request decode runs at approximately 65 tokens/second. Generating 8,192 tokens takes approximately 127 seconds, exceeding default 60-second client timeouts. Set client HTTP timeouts to at least 180 seconds, stream using :streamRawPredict (~0.20s time-to-first-token), or batch 16-32 cells in one :predict call (up to ~1,646 aggregate tokens/second).

  • Polymorphic :predict response schema: A :predict request with 1 instance returns predictions as list[str] with top-level output_token_counts and cumulative_logprobs. A request with 2 or more instances returns predictions as list[dict], nesting those fields inside each item. Always normalize both shapes in your response parser.

  • Duplicate tokens before Stage 2 reconstruction: Long generations (4,096-8,192 tokens) emit repeated gene tokens (10%-19% duplication) and occasional sign conflicts (the same gene emitted as both +GENE and -GENE). Feeding raw output into a non-deduplicating ExpressionDecoder overwrites high-rank predictions with lower-rank repeats. Always keep only the first occurrence of each gene and discard later repeats or sign conflicts before running ExpressionDecoder.

  • Validation errors returning HTTP 500: Invalid sampling parameters (temperature < 0, max_tokens <= 0), unknown fields (such as echo), a list-typed prompt, or a batch mixing valid and invalid instances return HTTP 500 instead of HTTP 400. Validate all fields client-side and avoid retrying validation errors.

  • Production architecture recommendation: For multi-team or agentic workloads, place a thin typed biological wrapper service or internal SDK in front of the raw vLLM endpoint. Enforce RDKit SMILES canonicalization, uppercase HGNC validation, <bos> prompt wrapping, parameter checks, batch schema normalization, and deduplicated Stage 2 reconstruction in that single layer so downstream callers can't trigger silent failures.

Deployment instructions

This section describes how to deploy CellGemma to an endpoint on Agent Platform in a Google Cloud project.

Before you begin

Before deploying CellGemma, verify the following prerequisites:

  • Confirm GPU serving quota in your target region (for example, europe-west4 or us-central1).
  • Configure the required Identity and Access Management (IAM) roles:
    • Model deployer: roles/aiplatform.admin (Agent Platform Administrator) to create endpoints and deploy models.
    • Model caller: roles/aiplatform.user (Agent Platform User) to send prediction requests to the deployed endpoint.
  • Install and initialize the Google Cloud CLI (gcloud), and configure Application Default Credentials (gcloud auth application-default login) for client authentication.
  • Install the google-cloud-aiplatform Python SDK (pip install google-cloud-aiplatform) if you deploy programmatically.

Resource requirements

CellGemma weights occupy approximately 14.4 GiB in bfloat16 (requiring ~18 GB VRAM at runtime) and run on a single 24 GB+ GPU. The default Model Garden 16K-context deployment (vllm-16k-context) uses:

  • Machine type: g4-standard-48
  • Accelerator: 1x NVIDIA_RTX_PRO_6000
  • Required vLLM context flag: --max-model-len=16384 (prevents truncation of standard ~4,127-token prompts plus 8,192-token generations)

Deploy CellGemma

You can deploy CellGemma with one click from Model Garden in the Google Cloud console (publishers/hf-google/models/cellgemma-e4b, task vllm-16k-context) or programmatically using the google-cloud-aiplatform Python SDK:

import vertexai
from vertexai import model_garden

PROJECT_ID = "YOUR_PROJECT_ID"
LOCATION = "europe-west4"

vertexai.init(project=PROJECT_ID, location=LOCATION)

model = model_garden.OpenModel("publishers/hf-google/models/cellgemma-e4b@001")
# Uses the verified Model Garden vllm-16k-context container spec (--max-model-len=16384).
# Call model.list_deploy_options() to inspect or override the container spec.
endpoint = model.deploy(
    machine_type="g4-standard-48",
    accelerator_type="NVIDIA_RTX_PRO_6000",
    accelerator_count=1,
    use_dedicated_endpoint=True,
)
print(f"Endpoint resource name: {endpoint.resource_name}")

After deployment completes, retrieve the dedicatedEndpointDns hostname and named endpoint ID (mg-endpoint-...):

gcloud ai endpoints list \
  --region=europe-west4 \
  --project=YOUR_PROJECT_ID \
  --format="table(name,displayName,dedicatedEndpointDns)"

API reference

This section describes the endpoint URL format, request fields, prompt templates, and response schemas for CellGemma.

HTTP requests

Send requests to the dedicated endpoint hostname (dedicatedEndpointDns):

POST https://DEDICATED_HOST/v1/projects/PROJECT_NUMBER/locations/LOCATION/endpoints/ENDPOINT_ID:predict

The endpoint also supports :rawPredict (single instance) and :streamRawPredict (NUL-delimited streaming JSON chunks) at the same base URL.

Replace the following:

  • DEDICATED_HOST: the dedicatedEndpointDns value from gcloud ai endpoints list or gcloud ai endpoints describe.
  • PROJECT_NUMBER: the numeric Google Cloud project number hosting the endpoint.
  • LOCATION: the Google Cloud region where the endpoint is deployed (such as europe-west4).
  • ENDPOINT_ID: the named endpoint ID (mg-endpoint-...). Using the numeric endpoint ID on the dedicated host returns HTTP 404.

Request body

{
  "instances": [
    {
      "prompt": "<bos><|turn>user\n...<turn|>\n<|turn>model\n",
      "max_tokens": 8192,
      "temperature": 0.7,
      "stop": ["<turn|>", "<eos>"],
      "raw_response": true
    }
  ]
}

Instance fields

Field Type Default Description
prompt string Required Non-empty prompt wrapped in <bos><|turn>user\n...<turn|>\n<|turn>model\n. Passing a non-string list triggers HTTP 500.
max_tokens integer 16 Maximum tokens to generate. Must be >= 1 and satisfy prompt_tokens + max_tokens <= 16384. Use 8192 for full residual predictions or 1024-2048 for top-ranked DEGs. Values <= 0 return HTTP 500.
temperature float 1.0 Sampling temperature (>= 0.0). Use 0.7 for standard evaluation or 0.0 for deterministic greedy decoding. Negative values return HTTP 500.
raw_response boolean false Set to true to return generated tokens only plus output_token_counts and cumulative_logprobs. Leaving false echoes the entire prompt.
stop array[string] null Stop sequences. Pass ["<turn|>", "<eos>"].
stop_token_ids array[integer] null Optional stop token IDs (for example, [1, 106]).
seed integer null Random seed for reproducible sampling when temperature > 0.
top_p float 1.0 Nucleus sampling threshold in (0, 1].
top_k integer -1 Top-k sampling limit (-1 disables).
n integer 1 Number of completion sequences to generate per instance.

Prompt template and perturbation formats

Keep the exact preamble, section order, and field labels used during training:

<bos><|turn>user
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.

PERTURBATION_BLOCK

Source: TOP_1000_UPPERCASE_CONTROL_GENES

Mean Global prediction: TOP_1000_UPPERCASE_MEAN_SHIFT_GENES
Target: <turn|>
<|turn>model

Format PERTURBATION_BLOCK by modality:

Modality Format Example
Small molecule Drug name:, Drug SMILES: (RDKit canonical isomeric), Concentration: with explicit units Drug name: Panobinostat
Drug SMILES: Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1
Concentration: 0.5 uM
Single CRISPR knockdown Gene knockdown: followed by the gene's entry from kg_sentences.json Gene knockdown: MYC\nMYC functional EP300\n...
Combinatorial CRISPR Write each Gene knockdown: entry in full, one after another Gene knockdown: <MYC KG>\nGene knockdown: <TP53 KG>
Cytokine Gene's entry from kg_sentences.json (which begins with the uppercase gene symbol) IFNG\nIFNG functional IFNGR1\n...
Clinical treatment Plain-text therapy name anti-PD-1

Response body (:predict, raw_response: true)

Client parsers must handle both single-instance and batched response shapes:

Single instance (len(instances) == 1):

{
  "deployedModelId": "DEPLOYED_MODEL_ID",
  "model": "projects/PROJECT_NUMBER/locations/europe-west4/models/MODEL_ID",
  "modelDisplayName": "cellgemma-e4b",
  "modelVersionId": "1",
  "predictions": ["+HSP90AA1 -MDM2 +H1-0 -CA12"],
  "output_token_counts": [8],
  "cumulative_logprobs": [-4.874793708300331]
}

Batched instances (len(instances) >= 2):

{
  "deployedModelId": "DEPLOYED_MODEL_ID",
  "model": "projects/PROJECT_NUMBER/locations/europe-west4/models/MODEL_ID",
  "modelDisplayName": "cellgemma-e4b",
  "modelVersionId": "1",
  "predictions": [
    {
      "predictions": ["+HSP90AA1 -MDM2 +H1-0 -CA12"],
      "output_token_counts": [8],
      "cumulative_logprobs": [-4.874793708300331]
    },
    {
      "predictions": ["+HSPA5 -EFNA5 +HSP90B1 -SMAD3"],
      "output_token_counts": [8],
      "cumulative_logprobs": [-5.120411284192011]
    }
  ]
}

Make predictions

Install the client dependencies:

pip install requests numpy torch safetensors huggingface_hub rdkit google-auth

Shared client helper

The following helper enforces RDKit SMILES canonicalization, uppercase HGNC symbols, explicit <bos> wrapping, client-side parameter validation, polymorphic batch response parsing, and deduplicated Stage 2 reconstruction:

import json
import google.auth
import google.auth.transport.requests
from huggingface_hub import hf_hub_download
import numpy as np
from rdkit import Chem
import requests
import safetensors.torch
import torch
from torch import nn

MODEL_REPO = "google/cellgemma-e4b"
DEDICATED_HOST = "https://YOUR_DEDICATED_ENDPOINT_DNS"
PROJECT_NUMBER = "YOUR_PROJECT_NUMBER"
LOCATION = "europe-west4"
ENDPOINT_ID = "YOUR_ENDPOINT_ID"

PREDICT_URL = (
    f"{DEDICATED_HOST}/v1/projects/{PROJECT_NUMBER}/locations/{LOCATION}"
    f"/endpoints/{ENDPOINT_ID}:predict"
)
STREAM_URL = (
    f"{DEDICATED_HOST}/v1/projects/{PROJECT_NUMBER}/locations/{LOCATION}"
    f"/endpoints/{ENDPOINT_ID}:streamRawPredict"
)

PREAMBLE = (
    "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 get_access_token() -> str:
  creds, _ = google.auth.default(
      scopes=["https://www.googleapis.com/auth/cloud-platform"]
  )
  creds.refresh(google.auth.transport.requests.Request())
  return creds.token


def canonicalize_smiles(smiles: str) -> str:
  mol = Chem.MolFromSmiles(smiles)
  if mol is None:
    raise ValueError(f"Invalid SMILES string: {smiles!r}")
  return Chem.MolToSmiles(mol, canonical=True, isomericSmiles=True)


def top_genes_sentence(expr: np.ndarray, genes: list[str], k: int = 1000) -> str:
  # Extended gene vocabulary requires uppercase HGNC symbols.
  upper_genes = [g.upper() for g in genes]
  ranked = [upper_genes[i] for i in np.argsort(expr)[::-1] if expr[i] > 0]
  return " ".join(ranked[:k])


def build_wrapped_prompt(
    perturbation_text: str,
    genes: list[str],
    ctrl_expr: np.ndarray,
    baseline: np.ndarray,
) -> str:
  body = (
      f"{PREAMBLE}\n\n{perturbation_text}\n\n"
      f"Source: {top_genes_sentence(ctrl_expr, genes)}\n\n"
      f"Mean Global prediction: {top_genes_sentence(baseline, genes)}\n"
      "Target: "
  )
  # Prepend <bos> explicitly because the vLLM container does not add it.
  return f"<bos><|turn>user\n{body}<turn|>\n<|turn>model\n"


def predict_batch(
    prompts: list[str],
    max_tokens: int = 8192,
    temperature: float = 0.7,
    seed: int | None = None,
    timeout_s: int = 240,
) -> list[str]:
  if not prompts:
    return []
  if max_tokens < 1:
    raise ValueError(f"max_tokens must be >= 1, got {max_tokens}")
  if temperature < 0.0:
    raise ValueError(f"temperature must be >= 0.0, got {temperature}")

  instances = []
  for p in prompts:
    if not isinstance(p, str) or not p.strip():
      raise ValueError("Each prompt must be a non-empty string.")
    inst = {
        "prompt": p,
        "max_tokens": max_tokens,
        "temperature": temperature,
        "stop": ["<turn|>", "<eos>"],
        "raw_response": True,
    }
    if seed is not None:
      inst["seed"] = seed
    instances.append(inst)

  resp = requests.post(
      PREDICT_URL,
      headers={
          "Authorization": f"Bearer {get_access_token()}",
          "Content-Type": "application/json",
      },
      json={"instances": instances},
      timeout=timeout_s,
  )
  resp.raise_for_status()
  preds = resp.json()["predictions"]

  # Normalize polymorphic schema: list[str] for batch=1, list[dict] for batch>=2.
  if isinstance(preds[0], str):
    return preds
  return [item["predictions"][0] for item in preds]


class ExpressionDecoder(nn.Module):

  def __init__(
      self, input_dim: int, hidden_dims: list[int], max_exp_arg: float = 88.0
  ):
    super().__init__()
    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(dataset: str):
  with open(hf_hub_download(MODEL_REPO, f"decoders/{dataset}/config.json")) as f:
    cfg = json.load(f)
  decoder = ExpressionDecoder(cfg["input_dim"], cfg["hidden_dims"])
  weights = hf_hub_download(
      MODEL_REPO, f"decoders/{dataset}/model.safetensors"
  )
  decoder.load_state_dict(safetensors.torch.load_file(weights))
  with open(
      hf_hub_download(MODEL_REPO, f"decoders/{dataset}/mean_delta_global.json")
  ) as f:
    mean_deltas = {k.upper(): float(v) for k, v in json.load(f).items()}
  return decoder.eval(), mean_deltas


def parse_and_deduplicate_genes(
    text: str, gene_to_idx: dict[str, int]
) -> tuple[list[str], list[str]]:
  """Keeps the first occurrence of each gene and drops repeats or sign conflicts."""
  up, down = [], []
  seen = set()
  for tok in text.split():
    if len(tok) < 2 or tok[0] not in ("+", "-"):
      continue
    gene = tok[1:].upper()
    if gene in gene_to_idx and gene not in seen:
      seen.add(gene)
      (up if tok[0] == "+" else down).append(gene)
  return up, down


def reconstruct_expression(
    stage1_text: str,
    genes: list[str],
    ctrl_expr: np.ndarray,
    baseline: np.ndarray,
    decoder: ExpressionDecoder,
) -> tuple[np.ndarray, np.ndarray]:
  gene_to_idx = {g.upper(): i for i, g in enumerate(genes)}
  up, down = parse_and_deduplicate_genes(stage1_text, gene_to_idx)
  residual_vec = np.zeros_like(baseline, dtype=np.float32)
  if up or down:
    task_oh = [0.0] * 7 + [1.0]
    feats, ctrl_vals, idxs = [], [], []
    for is_up, gene_list in ((1.0, up), (0.0, down)):
      for rank, g in enumerate(gene_list):
        idx = gene_to_idx[g]
        feats.append(
            [is_up, float(rank), float(len(up)), float(len(down))] + task_oh
        )
        ctrl_vals.append(float(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

Connectivity check

Verify authentication, dedicated endpoint routing, and prompt wrapping before running full 8,192-token generations:

out = predict_batch(
    ["<bos><|turn>user\nSource: GAPDH ACTB TP53\nTarget: <turn|>\n<|turn>model\n"],
    max_tokens=16,
    temperature=0.0,
    timeout_s=30,
)
print("Connectivity check output:", out[0])

Drug perturbation prediction with Stage 2 reconstruction

with open(hf_hub_download(MODEL_REPO, "controls_sample.json")) as f:
  controls_all = json.load(f)

decoder, mean_deltas = load_decoder("tahoe")
genes = [g.upper() for g in controls_all["tahoe"]["genes"]]
ctrl_expr = np.array(
    controls_all["tahoe"]["cells"][0]["expression"], dtype=np.float32
)
mean_vec = np.array([mean_deltas.get(g, 0.0) for g in genes], dtype=np.float32)
baseline = np.maximum(0.0, ctrl_expr + mean_vec)

smiles = canonicalize_smiles("Cc1[nH]c2ccccc2c1CCNCc1ccc(/C=C/C(=O)NO)cc1")
pert = f"Drug name: Panobinostat\nDrug SMILES: {smiles}\nConcentration: 0.5 uM"
prompt = build_wrapped_prompt(pert, genes, ctrl_expr, baseline)

stage1_text = predict_batch([prompt], max_tokens=8192, temperature=0.7, seed=42)[0]
pred_expr, pred_lfc = reconstruct_expression(
    stage1_text, genes, ctrl_expr, baseline, decoder
)

top_up = np.argsort(pred_lfc)[::-1][:10]
print(
    "Top 10 upregulated genes:",
    [(genes[i], round(float(pred_lfc[i]), 3)) for i in top_up],
)

Genetic knockdown (single and combinatorial CRISPR)

with open(hf_hub_download(MODEL_REPO, "kg_sentences.json")) as f:
  kg = json.load(f)

decoder_k562, mean_deltas_k562 = load_decoder("k562")
genes_k562 = [g.upper() for g in controls_all["k562"]["genes"]]
ctrl_k562 = np.array(
    controls_all["k562"]["cells"][0]["expression"], dtype=np.float32
)
baseline_k562 = np.maximum(
    0.0,
    ctrl_k562
    + np.array(
        [mean_deltas_k562.get(g, 0.0) for g in genes_k562], dtype=np.float32
    ),
)

# Always pass the knowledge-graph sentence rather than a bare gene symbol.
single_prompt = build_wrapped_prompt(
    f"Gene knockdown: {kg['MYC'].strip()}", genes_k562, ctrl_k562, baseline_k562
)

# Combinatorial dual knockdown.
dual_prompt = build_wrapped_prompt(
    f"Gene knockdown: {kg['MYC'].strip()}\nGene knockdown: {kg['TP53'].strip()}",
    genes_k562,
    ctrl_k562,
    baseline_k562,
)

# Submit both perturbations in one batched :predict request.
single_out, dual_out = predict_batch(
    [single_prompt, dual_prompt], max_tokens=2048, temperature=0.7
)

Streaming predictions (:streamRawPredict)

Use :streamRawPredict to read top-ranked genes within ~0.20 seconds and avoid long idle HTTP connections:

resp = requests.post(
    STREAM_URL,
    headers={
        "Authorization": f"Bearer {get_access_token()}",
        "Content-Type": "application/json",
    },
    json={
        "prompt": prompt,
        "max_tokens": 1024,
        "temperature": 0.7,
        "stop": ["<turn|>", "<eos>"],
        "stream": True,
    },
    stream=True,
    timeout=180,
)
resp.raise_for_status()

buf = b""
for chunk in resp.iter_content(chunk_size=128):
  buf += chunk
  while b"\x00" in buf:
    part, buf = buf.split(b"\x00", 1)
    token_text = json.loads(part.decode("utf-8"))["predictions"][0]
    print(token_text, end="", flush=True)

Best practices

  • Batch 16-32 cells per :predict call for virtual screening: Single-request decode runs at approximately 65 tokens/second. Batching 32 cells in a single :predict call reaches approximately 1,646 aggregate tokens/second (2.49 seconds for 32 x 128 tokens) with payloads around 406 KB.

  • Tune max_tokens to your downstream analysis: Because CellGemma ranks predictions by residual magnitude, max_tokens=1024 or 2048 (top 256-512 upregulated and downregulated genes, 15.8s-31.5s single-request) cuts latency 4x-8x compared to 8,192 tokens (~127s) and reduces duplicate tokens.

  • Match the ExpressionDecoder to your assay: Select the decoder that matches your assay technology, cell context, and normalization (for example, tahoe for cancer cell-line drug screens, k562 for K562 CRISPRi, parse for PBMC cytokines). Don't apply bulk decoders (l1000) to single-cell profiles; retrain a decoder for new assays.

  • Preprocess custom .h5ad inputs to match training: Pseudobulk raw counts, subset to protein-coding genes, library-size normalize, apply log1p, uppercase all HGNC symbols, and compute baseline = max(0, control + mean_delta_global) before taking the top 1,000 expressed genes (> 0).

  • Always include knowledge-graph sentences for genes and cytokines: Passing a bare symbol (Gene knockdown: MYC) instead of its kg_sentences.json summary degrades agreement with the full prompt (0.356 UP / 0.238 DOWN Jaccard).

Troubleshooting

Symptom Cause Resolution
HTTP 400 on aiplatform.googleapis.com citing an unresolvable hostname Dedicated endpoint called using the shared domain Run gcloud ai endpoints describe and send requests to dedicatedEndpointDns with the named endpoint ID (mg-endpoint-...).
HTTP 400: default chat template is no longer allowed Calling OpenAI /chat/completions CellGemma is non-conversational. Use :predict, :rawPredict, or :streamRawPredict.
HTTP 400: maximum context length is 16384 tokens prompt_tokens + max_tokens > 16384 Standard 1,000 + 1,000 gene prompts use ~4,127 tokens. Keep max_tokens <= 8192 and verify long combinatorial KG prompts fit within 16384 - max_tokens.
HTTP 500 on a healthy endpoint Invalid temperature < 0, max_tokens <= 0, unsupported kwarg (echo), or list-typed prompt Validate parameters client-side before sending and avoid blind retries on validation errors.
TypeError parsing predictions on batched calls :predict returns list[str] for 1 instance and list[dict] for 2+ instances Check isinstance(preds[0], str) as shown in predict_batch().
Drug predictions collapse to generic ribosomal genes Missing Drug SMILES: or non-canonical (Kekule) SMILES Canonicalize SMILES with RDKit (canonical=True, isomericSmiles=True) and include Drug SMILES:.
Unrelated genes returned despite HTTP 200 Lowercase gene symbols or missing <bos> / turn wrapper Uppercase all HGNC symbols and wrap prompts in <bos><|turn>user\n...<turn|>\n<|turn>model\n.
Top genes lose LFC magnitude after Stage 2 Duplicate Stage 1 gene tokens overwriting earlier ranks in ExpressionDecoder Deduplicate Stage 1 tokens (first occurrence wins) and drop sign conflicts before reconstruction.

Limitations

In addition to the serving constraints in Considerations and required client guardrails, CellGemma has the following modeling and usage limitations:

  • Research use only: CellGemma is intended strictly for research and isn't cleared for clinical diagnosis, patient care, or medical decision-making. All predicted gene shifts and candidate interventions require experimental validation in laboratory settings.
  • Dataset-specific Stage 2 calibration: Stage 1 outputs ranked residual gene symbols (+GENE and -GENE), not absolute expression levels. Reconstructing continuous expression and LFC requires a baseline control profile, a matching mean_delta_global.json, and a dataset-appropriate ExpressionDecoder. Pretrained decoders don't transfer across assays with different normalization or sequencing technologies (for example, bulk L1000 and single-cell RNA-seq); new assays require retraining a decoder on matched data.
  • No calibrated uncertainty or effect sizes in Stage 1: Stage 1 outputs ordered gene symbols without confidence intervals, p-values, or calibrated magnitude scores. Long generations (4,096-8,192 tokens) can emit duplicate gene symbols or conflicting signs unless deduplicated before Stage 2 reconstruction.
  • Sensitivity to input conditioning: Small-molecule conditioning depends on RDKit canonical isomeric SMILES (drug names alone or non-canonical SMILES degrade predictions), genetic and cytokine perturbations require knowledge-graph descriptions rather than bare symbols, and baseline profiles must use uppercase HGNC protein-coding gene symbols (top 1,000 expressed genes). Dose response is coarse, and out-of-range concentrations still return syntactically valid gene lists.
  • Variable cross-domain generalization: Across the 32 held-out benchmark splits, differential expression correlation (Pearson delta) ranges from 0.76 on Tahoe unseen perturbation-and-cell splits down to 0.15-0.16 on harder out-of-distribution splits (such as L1000 unseen cell lines, Parse unseen perturbations, and VCC unseen perturbations).
  • Non-conversational interface: CellGemma outputs gene symbols only. It doesn't support natural-language dialogue, system instructions, thinking mode, or mechanistic explanations.

Scientific reference directory

The following table lists primary reference materials and resources for CellGemma:

Resource type Title and link Description
Technical report Predicting Transcriptional Responses to Diverse Perturbations with CellGemma (PDF) Technical report detailing the architecture, gene-native tokenization, 32-split benchmarks, and preclinical CAR T validation.
Announcement CellGemma: Predicting cell responses to help accelerate cancer research Google DeepMind launch blog introducing CellGemma and laboratory proof-of-concept results.
Video overview CellGemma: Simulating how cells respond to drugs Official Google DeepMind YouTube video introducing how CellGemma simulates cellular responses.
Model card and inference guide CellGemma model card and inference guide Official Gemma documentation covering model specs, data preprocessing, benchmarks, and safety guidance.
Model weights and decoders google/cellgemma-e4b on Hugging Face Open Apache 2.0 checkpoint, 13 pretrained ExpressionDecoder MLPs, controls_sample.json, and kg_sentences.json.
Interactive demos and notebook AI Studio applet (run in browser), Hugging Face Space, and Colab quickstart Interactive browser demos and executable notebook for drug and CRISPR perturbation predictions.

What's next