Tokenization Strategies

Translating Biology into AI-Readable Language

Understanding how biological data is converted into tokens is fundamental to building effective foundation models. This guide explores the major tokenization strategies used in single-cell multi-omics, protein modeling, and DNA sequence analysis, using intuitive LEGO analogies to make these concepts accessible.

11
Tokenization Strategies
23
Curated Papers
2021–2026
Publication Years
3
Modalities: scRNA, DNA, Protein
Healshu as a LEGO master builder: snapping three bricks into one, picking a brick from the sorting tray, and pointing at an offset brick wall
LEGO lens · sort & snap

No castle without a parts list.

Every LEGO castle begins before the first brick snaps in — with someone deciding which pieces exist and in what order. Tokenization is that decision for AI: how a messy bucket of biology becomes a neat line of parts a model can build with.

Healshu as a LEGO master builder at a workbench, pressing a red brick into a brick-built DNA helix with color-sorted trays and an instruction booklet nearby

Split, Then Snap.

「先分件,再拼装。」— Every LEGO build starts with sorting the bucket.

No builder dumps the bucket straight onto the table and hopes for a castle. You sort first: decide which units exist, in what order, at what size. Tokenization is exactly that sorting step for AI — six scenes from the workbench, re-read as tokenization strategies.

Scene 1 · 说明书第一页

No build without a plan

Every LEGO set opens with the instruction booklet: before a single brick is placed, someone has already decided which pieces exist and in what order they connect.

Tokenization itself. The plan that turns a messy bucket into a buildable sequence — without it, the model has a pile, not a project.

Scene 2 · 三块砖按成一块

Three bricks, one click

Three small bricks click together and hold as one larger piece. The wall no longer cares about the three — only about the unit they became.

Codon-level tokenization. Three nucleotides snapped as one codon, read as a single functional unit. See the codon strategy ↓

Scene 3 · 分选盘挑高频件

Pick from the tray, don't mold new bricks

A master builder rarely molds custom pieces. They reach into the sorting tray and reuse the common bricks that fit everywhere — cheaper, faster, and the castle stands the same.

BPE / subword units. Don't mint a token for every word; pick the frequent reusable pieces already lying in the corpus. See BPE ↓

Scene 4 · 拿错一页说明书

The wrong page of instructions

You follow the booklet faithfully, step by step — but it is the page from a different set. Every brick clicks perfectly, and the wrong castle rises anyway.

Garbage tokens in, garbage out. A wrongly segmented unit poisons everything downstream — tokenize wrong, and the model builds confidently on a false plan.

Scene 5 · 错缝重叠的砖墙

A wall laid with offset bricks

Each course overlaps the last by half a brick: stronger than stacked columns — but you spend far more bricks to cover the same wall.

K-mer tokenization. Overlapping windows chained across the sequence: continuous coverage, redundancy that burns budget. See k-mer ↓

Scene 6 · 缺件与万能小砖

When a piece is missing

One big custom piece missing stops the whole build. The tiniest universal brick is never out of stock — slow, but it always fits.

Byte-level tokenization. The smallest unit never goes OOV: full coverage and zero missing pieces, at the price of very long builds. See trade-offs ↓

Four-panel LEGO comic of tokenization: the instruction booklet opens to page one, three bricks snap into a single unit, frequent pieces are picked from the sorting tray, and the wrong instruction page is picked up by mistake
Four scenes, one parts list: plan before building, merge frequent pieces, pick from the tray rather than molding new bricks — and note what breaks when the vocabulary does not match the task.

按任务选套装:没有最好的粒度,只有合适的套装 —— the right tokenization is the set your task can build with.

The Problem: Biology is Messy, AI Needs Order

The LEGO Analogy: Imagine a single cell as a giant bucket full of unsorted LEGO bricks.
Each type of brick (color/shape) represents a different Gene.
The number of bricks of that specific type represents its Expression Level (how active that gene is).

An AI model (like a Transformer) is a master builder, but it can't just grab a handful from the messy bucket. It needs the bricks sorted, labeled, and handed to it in a specific sequence. Tokenization is the process of organizing that messy bucket into a neat line of inputs the builder can use.

Depending on what we want the model to learn, we use different strategies to sort and present these "bricks".

Visual Guide to Core Tokenization Concepts

Before diving into the details, let's understand the core concepts visually using our LEGO analogy.

Navigation Map — 12 Strategies, 4 Biological Domains

These strategies answer different questions depending on what type of data you're working with. The LEGO analogy stays the same — what changes is which property of the brick matters.

DomainStrategyThe core questionModels
scRNA-seq
Gene expression in single cells
The BasicsHow do I combine gene identity + expression value into one token?
Rank-BasedWhich genes are relatively more active? (ignore absolute counts)Geneformer, iSEEEK
Expression BinningWhich expression level category is this gene in?scGPT, scBERT
Read-Depth-AwareWhat would expression look like at full sequencing depth?scFoundation, AIDO.Cell
Cell2SentenceCan I turn cell data into a plain text sentence for a standard LLM?C2S-Scale (27B)
DNA / Genomics
Nucleotide sequences
K-merWhat are the overlapping short motifs in this sequence?DNABERT, Nucleotide Transformer
BPE + IUPACHow do I encode personal diploid variants efficiently?VariantFormer
Codon-LevelDoes the specific triplet (not just the amino acid) matter?CodonFM, EnCodon
Single-Nucleotide + SSMCan I skip k-mer vocabulary entirely and scan 1M+ bp in linear time?HyenaDNA, Evo, Evo 2
ATAC-seq / Chromatin
Open chromatin
Genome CoordinatesWhere on the genome is this accessible region? (location = identity)ChromFound
Protein
Amino acid sequences
Amino AcidWhich of the 20 building blocks is at each position?ESM3, ProGen2
Cross-species
Multi-organism integration
MacrogeneCan I group orthologous genes across species into one shared token?SATURN
Gene Identity vs Expression Level A diagram showing different colored LEGO bricks representing gene identities, and stacks of different heights representing expression levels. 1. Raw Data (The Bucket) Gene A Count: 50 Gene B Count: 5 Tokenize 2. Tokens (AI Inputs) Gene A value: 50 (high) Gene B value: 5 (low)

The Basics: Identity & Count

A token is a single unit of information for the model. In single-cell data, we usually need two pieces of information combined:

  1. What is it? (The Gene Identity, e.g., "TP53" or a red brick).
  2. How much? (The Expression Value, e.g., "50 counts" or a stack of 50 bricks).

The challenge is how to combine these two very different types of information into a single vector representing the token.

Rank-Based Tokenization Analogy Two panels showing different cells with different stack heights but same relative ordering, resulting in identical token sequences. Cell 1: Good Quality A (100) 1st B (60) 2nd C (30) 3rd Cell 2: Batch Effect A (10) 1st B (5) 2nd C (2) 3rd Same Token Sequence! Gene A -> Gene B -> Gene C

Strategy: Rank-Based Tokenization

The Problem: Sometimes we have "technical noise" (batch effects). One experiment might yield giant stacks of bricks (high sequencing depth), and another yields tiny stacks, even for the same biological cell type.

The Solution: Ignore the exact height. Just line them up from tallest to shortest. As long as the relative order is preserved (Red is taller than Blue), the resulting sequence of tokens is the same, making the model immune to batch differences in sequencing depth.

Used in: iSEEEK, Geneformer
Full rank All expressed genes ranked, sequence length = # genes expressed in that cell
Top-N truncated Only top N genes kept (e.g. N≈2,048) to fit a fixed context window — Geneformer default
Fails when: Many genes tie at zero counts — rank order among the unexpressed tail is arbitrary and adds noise, not signal.
Expression Binning Analogy Continuous stacks of bricks of varying heights being sorted into three distinct buckets labeled Low, Medium, and High. Discretizing Continuous Values into Buckets Raw Expression Counts 5 45 120 LOW (1-20) MEDIUM (21-80) HIGH (81+)

Strategy: Expression Binning

The Problem: Standard language models work best with a fixed dictionary of words (categorical data). Actual expression counts are continuous numbers (1, 2, 50, 1000...).

The Solution: We create buckets (bins) for different ranges of heights. Instead of saying "Height 45", we throw it into the "Medium Height Bucket". Now, the token isn't a number, it's a category: [GeneID] + [MediumBin].

Used in: scGPT, scBERT
Equal-width bins Fixed count ranges (e.g. 0–20, 21–80, 81+) — simple, but bins can be very imbalanced in size
Equal-frequency (quantile) bins Each bin holds the same number of genes — scGPT's default, ~51 bins
Fails when: Bin edges fit on one dataset don't transfer cleanly to a batch with a different expression distribution — genes get mis-binned under domain shift.
Read-Depth-Aware Tokenization Analogy Two cells with different sequencing depths, showing how depth tokens help the model understand and recover the original expression levels. Continuous Values + Depth Tokens Original Cell (Deep Sequencing) Total counts: 10,000 Gene A 100 Gene B 60 Gene C 20 Sampled Cell (Shallow) Sampled counts: 1,000 Gene A 10 Gene B 6 Gene C 2 Add depth tokens RDA Token Format Continuous Values [10, 6, 2, 0, ...] + T token 10,000 S token 1,000 Model learns to predict original (T=10,000) from sampled (S=1,000) data!

Strategy: Read-Depth-Aware (RDA) Tokenization

The Problem: Different cells have different sequencing depths—some have 10,000 total counts, others only 1,000. This makes expression values hard to compare directly.

The Solution: Keep the continuous expression values (don't discretize!), but add special "depth tokens" that tell the model: "This cell was supposed to have T=10,000 counts, but we only sampled S=1,000." The model learns to mentally "scale up" the values during pretraining.

Key Benefit: Enables expression enhancement—the model can predict what gene expression would look like at higher sequencing depth, effectively denoising sparse data.

Used in: scFoundation, AIDO.Cell
T token Target/original total UMI count the cell was meant to have
S token Sampled/observed total UMI count actually sequenced
Fails when: Sampled depth S is extremely low (heavy dropout) — the T/S ratio the model must invert becomes unreliable when there's almost nothing to scale up from.
Cell2Sentence Tokenization Analogy Stacks of bricks transformed into horizontal sequences where height becomes repetition count. Expression Level to Token Repetition Traditional: Stack Height Gene A (high: 5) Gene B (low: 2) C2S Cell2Sentence: Repeat by Expression Gene A repeated 5x B x 2 "GeneA GeneA GeneA GeneA GeneA GeneB GeneB ..." Key Insight Higher expression = More token repeats in the "sentence" This lets standard LLMs (GPT, LLaMA) process cell data! C2S-Scale: Up to 27B parameters, 8,192 token context

Strategy: Cell2Sentence (C2S)

The Idea: Instead of stacking bricks to show expression level, lay them out in a horizontal line. High expression? Repeat that brick many times. Low expression? Just one or two repeats.

Why It Matters: This transforms cell data into text-like "sentences" that standard large language models (GPT, LLaMA) can understand. You can even ask natural language questions about cells!

Used in: C2S-Scale (27B params)
Repeat encoding Gene token repeated proportional to (rank-transformed) expression count
Context cap Max repeats / sequence-length truncation — controls how much the "sentence" can grow
Fails when: A handful of highly expressed housekeeping genes can dominate the token budget, crowding out rare but biologically important marker genes.

Choosing Among the 4 scRNA Tokenization Strategies

All four apply to scRNA-seq data. What they preserve — and sacrifice — is different.

StrategyAbsolute counts preserved?Batch / depth robust?Sequence lengthWorks with standard LLMs?Best when…
Rank-Based✗ (discarded)✓✓ (best)= # expressed genes✓ (integer position)Cross-batch cell-type classification; depth varies wildly across batches
BinningPartial (quantized)✓ (quantization absorbs depth noise)= # expressed genes✓ (categorical token)Moderate depth variation; need to retain some expression magnitude
Read-Depth-Aware✓✓ (continuous)✓ (via depth tokens T, S)= # expressed genes + 2Needs custom embeddingExpression enhancement / denoising; want to predict full-depth values
Cell2Sentence✓ (repetition count)✗ (absolute counts used) (high-expression genes repeat many times)✓✓ (plain text, any LLM)Natural language Q&A about cells; leverage GPT/LLaMA directly

Genomic DNA Strategies

DNA doesn't come pre-segmented into "genes" the way transcriptomes do — these four strategies address how to carve a continuous 4-letter sequence (or a diploid, ambiguity-coded one) into learnable units.

K-mer Tokenization Analogy A sliding window of 6 DNA bricks moving along a sequence, treating each window as one compound token. K-mer: Sliding Window of K Nucleotides DNA Sequence (Single Nucleotides) A T G C A T 6-mer Window ... Slide & Extract 6-mer Tokens (4^6 = 4,096 possible combinations) ATGCAT -> TGCATG -> ... Why Overlapping K-mers? Captures local sequence context that single nucleotides miss.

Strategy: K-mer Tokenization

The Idea: Instead of reading DNA one letter at a time (A, T, G, C), slide a window of K letters along the sequence. Each window position becomes one token. For 6-mers, there are 4^6 = 4,096 possible tokens.

Why It Works: It's like reading words instead of individual letters. "ATGCAT" carries more biological meaning than six separate letters, capturing local motifs and regulatory elements.

Used in: Nucleotide Transformer, DNABERT
k = 3 64 tokens — codon-scale, loses local context
k = 6 4,096 tokens — DNABERT default, good motif capture
k = 1 4 tokens — byte-level baseline, max OOV safety, no context
Fails when: Vocabulary explodes with large k, and overlapping k-mers cause position confusion in non-causal attention.
BPE + IUPAC Tokenization for Personalized Genomes A reference genome sequence with variants being encoded using IUPAC ambiguity codes, then tokenized using BPE into learned subword units. BPE + IUPAC: Personalized Diploid Genome Encoding Reference Genome (Generic) A T G C A T G ... Het SNP Het SNP IUPAC Encoding Personalized Diploid Genome (with IUPAC codes) A T G Y A T R ... Y = C/T (het) R = A/G (het) BPE Tokenization BPE Tokens (Learned Subwords, 500 vocab) ATG YAT R... Variable-length tokens Native Diploid Modeling Heterozygous variants (C/T, A/G) encoded directly via IUPAC codes (Y, R)

Strategy: BPE + IUPAC Encoding for Diploid Genomes

The Problem: Reference genome models ignore individual genetic variation. How do you encode personalized genomes with heterozygous variants (where you inherited different alleles from each parent)?

The Solution: Use IUPAC ambiguity codes to represent heterozygous sites directly in the sequence (e.g., Y for C/T, R for A/G). Then apply Byte-Pair Encoding (BPE) to learn variable-length subword tokens that capture regulatory motifs.

Why It Works: This enables native diploid genome modeling without separate haplotype processing. The model learns the biological significance of both homozygous and heterozygous positions.

Used in: VariantFormer
Vocab size Learned BPE merges, typically 500–32k subword tokens
IUPAC coverage 2-way ambiguity codes (Y, R, ...) capture biallelic heterozygous SNPs only
Fails when: Structural variants — indels, triallelic sites — aren't representable: IUPAC ambiguity codes only cover single-base substitutions.
Codon-Level Tokenization Analogy Single nucleotide bricks grouped into triplets, showing how multiple triplet combinations can code for the same amino acid. Codons: 3-Brick Combos (64 Possible) Single Nucleotides (mRNA, 4 types) A U G C Group by 3 Codon Tokens (4^3 = 64 types) A U G Key Insight: Multiple Codons -> Same Amino Acid Leucine (L) can be coded by: UUA UUG ... All produce Leucine, but choice matters for translation speed! Why Codon Choice Matters "Silent" mutations (same amino acid) can still cause disease! Codon-level models capture translation efficiency & mRNA stability

Strategy: Codon-Level Tokenization

The Idea: Instead of tokenizing single mRNA letters (A, U, G, C), group them into triplets called codons. There are 64 possible triplet combinations (4^3).

Why It Matters: Multiple codons can code for the same amino acid (synonymous codons), but the choice affects translation speed and mRNA stability. "Silent" mutations can still cause disease!

Used in: CodonFM, EnCodon
Reading frame Codon identity shifts entirely if the frame is off by even 1 base
Vocabulary 64 codon tokens; sequence is 3× shorter than single-nucleotide tokenization
Fails when: Non-coding regions (introns, UTRs) — codon framing only applies inside an open reading frame.
Single-Nucleotide + State-Space-Model Tokenization Analogy A long unbroken line of single-nucleotide bricks scanned one at a time by a moving state-space model, which carries a fixed-size summary forward instead of attending back over every prior brick. Single Nucleotide: One Brick, One Token (No Merging) 1M+ bp genome, scanned one base at a time — vocabulary = {A, T, G, C} only A T G C A A C T G ... ... 1,000,000 more bricks ... Scan left to right, no lookback State-Space Model (Hyena / Mamba): a moving tape-measure, not a rear-view mirror fixed-size state vector updated state vector ... O(1) memory per step vs. attention's O(n) lookback over every prior brick Why This Beats K-mer at Genome Scale 4 tokens total (A/T/G/C), zero OOV — vs. 4^6 = 4,096 for 6-mers Linear-time scan handles 1M+ bp context; attention cannot afford that lookback Trade-off: needs an SSM backend (Hyena/Mamba), not a plain Transformer

Strategy: Single-Nucleotide + State-Space-Model Tokenization

The Idea: Stop compressing bases into k-mers or codons at all — tokenize every single nucleotide (vocabulary = 4). What used to make this impractical was the transformer: single-base tokens over a megabase context means millions of positions, and full attention over that is quadratically unaffordable. Swap the attention operator for a state-space model (Hyena/Mamba), and the sequence is scanned once, left to right, carrying a fixed-size "state" forward instead of looking back at everything.

Why It Works: No k-mer vocabulary to size (no 4^6 = 4,096 explosion), no out-of-vocabulary sequences, and near-linear compute in sequence length — the combination that finally makes million-base-pair genomic context tractable in a single forward pass.

Used in: HyenaDNA, Evo, Evo 2
HyenaDNA Up to ~450kb context, single-nucleotide vocabulary
Evo / Evo 2 Up to ~1Mb context, adds generative genome design on top
Fails when: A task needs precise, content-based attention between two specific far-apart positions — the SSM's fixed-size state can dilute a signal from very far back.

Chromatin / ATAC-seq Strategies

Open-chromatin data has no fixed vocabulary at all — accessible regions vary by cell type, so a token's identity has to come from where it sits on the genome, not from a gene name.

Genome Coordinate Tokenization Analogy A long green LEGO baseplate acting as a ruler with numbers. Clusters of bricks are placed at specific coordinate ranges, representing open chromatin regions. Location as Identity (Chromatin/ATAC-seq) Chr 1 0 200 400 600 800 1000 Region A Region B Resulting Tokens (Location-Based) Token A: [Chr1, 100, 180] Token B: [Chr1, 700, 760] No fixed gene vocabulary needed - regions can vary by cell type!

Strategy: Genome-Coordinate Tokenization

The Problem: In chromatin data (ATAC-seq), we don't have predefined "genes". We just have regions on the genome that are "open" (accessible). These regions change depending on the cell type.

The Solution: Imagine the genome as a giant LEGO baseplate ruler. We don't define the brick type; we define where the bricks are placed. The token isn't a name, it's a set of coordinates: Chromosome number, Start position on the ruler, and End position.

Used in: ChromFound
Fixed-bin tiling Genome chopped into equal-size bins (e.g. 500bp–5kb) regardless of activity
Peak-called regions Variable-width regions from accessibility peak calling — matches biology, uneven token size
Fails when: Coordinates come from different genome builds (hg19 vs hg38) without liftover — the same token no longer points at the same base pairs.

Protein Strategies

Proteins are built from a small, fixed alphabet of 20 amino acids — a far smaller vocabulary problem than DNA or expression data, but one where chemical similarity between residues still matters.

Amino Acid Tokenization Analogy 20 different colored LEGO bricks representing the amino acid alphabet, chained together to form a protein sequence. Protein = Chain of 20 Amino Acid "Bricks" The Vocabulary: 20 Amino Acid Types (8 shown, grouped by chemistry) A L S N K R D E Nonpolar Polar Positive Negative A Protein Sequence (Chain of Bricks) M A V ... Simple but Powerful Each amino acid = 1 token. The model learns which "bricks" tend to appear together, like grammar in language.

Strategy: Amino Acid Tokenization

The Idea: Proteins are chains of just 20 different building blocks (amino acids). Each amino acid is one token - like having 20 different LEGO brick types that snap together in a chain. The 20 types cluster into chemistry groups - nonpolar, polar, positively charged, negatively charged - and substitutions within a group are usually less disruptive to protein function than substitutions across groups.

Why It Works: Just like language models learn word patterns ("the" often follows "in"), protein models learn amino acid patterns that determine protein function and structure.

Used in: ESM3, ProGen2
Standard 20 One token per canonical amino acid — ESM3, ProGen2 default
20 + special tokens Adds X (unknown) / gap tokens for MSA-based and alignment-aware models
Fails when: Post-translational modifications (phosphorylation, glycosylation, ...) aren't representable — the 20-letter vocabulary has no token for a modified residue.

Cross-Species Strategies

Integrating cells or genes across species hits the vocabulary problem in yet another way: gene names and IDs simply don't align across hundreds of millions of years of divergence.

Macrogene Tokenization Analogy Genes from different species grouped into functional clusters (macrogenes) based on protein similarity, enabling cross-species integration. Macrogene: Protein-Function-Based Gene Groups Human Genes CD4 MYOC Mouse Genes Cd4 Myoc Frog Genes cd4 myoc ESM2 Protein Language Model Encode protein sequences → 5120-dim embeddings K-means Clustering Macrogene 1: T-cell CD4 Cd4 cd4 Macrogene 2: Eye MYOC Myoc myoc Cross-Species Integration Without Homologs Genes grouped by protein function, not genomic position. Works even for species 350M years apart (frog ↔ zebrafish)!

Strategy: Macrogene Tokenization

The Idea: Instead of using individual genes as tokens, group genes from ALL species into "macrogenes" based on protein sequence similarity (via ESM2). This creates a universal vocabulary that works across species.

Why It Works: Genes with similar protein functions cluster together regardless of species, enabling cross-species integration WITHOUT requiring one-to-one homolog mappings. Human CD4 and mouse Cd4 end up in the same macrogene!

Used in: SATURN
Protein-similarity clustering K-means over ESM2 embeddings — SATURN's approach, no homolog table needed
Ortholog-table grouping Pre-computed 1:1 orthology mapping — precise but fails for genes without a clean ortholog
Macrogene count (k) Number of clusters trades resolution against how well cross-species structure generalizes
Fails when: A gene is a species-specific innovation with no protein-similarity match elsewhere — it either sits alone in a singleton macrogene or gets force-merged with unrelated genes.

Full-Diagram Deep Dives

Three of the strategies above don't reduce to a single hand-drawn LEGO panel — they combine multiple embeddings per token (scPRINT-2) or move the token itself up a level, from gene to whole cell (STATE, STACK). Full walkthroughs below.

STATE tokenization diagram: Stage 1 State Embedding encoder compresses one cell's ~20,000-gene expression profile into a single cell-embedding token (pretrained on 167M observational cells); Stage 2 State Transition applies bidirectional set attention across a population of control and perturbation-context cell tokens to predict a perturbed embedding (pretrained on 100M perturbation-paired cells). Right column states the problem (gene-level tokenization can't model population-level shifts), solution (compress each cell to one vector, then attend across cells), and key benefit (perturbation prediction generalizes across cell types without retraining).
scPRINT-2 tokenization diagram: each gene token is the sum of three embeddings — an ESM3 protein embedding (with a fine-tuning adaptor layer), an MLP encoding of continuous log-expression, and a genomic-location embedding — shown for an expressed gene G1 and an unexpressed/padding gene G2, then assembled into a 2,200-gene token sequence fed to the XPressor bidirectional transformer. Right column states the problem (a gene needs identity, level, and location, and none should be discarded), solution (sum three separate embeddings instead of picking one), and key benefit (upgrading ESM2→ESM3 with an adaptor beat learning gene tokens from scratch).
STACK tokenization diagram: the cell-by-gene expression matrix is treated as a table, with within-row attention across genes (co-expression) and across-row attention across cells (comparing cell states), pretrained on 149M cells from the Perturb Sapiens corpus. At inference, labeled context rows (e.g. a control-cell row paired with its drug-treated row) are prepended so the model reads the control-to-perturbed pattern and applies it to a new query cell with no gradient update. Right column states the problem (models can't predict genuinely new conditions without retraining), solution (tabular attention plus in-context example rows), and key benefit (zero-shot perturbation prediction used to build the Perturb Sapiens atlas).

Key Papers Implementing These Strategies

Geneformer: Transfer Learning Enables Predictions in Network Biology

Theodoris et al. | Nature 2023
scRNA-seq BERT Encoder Rank-Based
The field-defining rank-value tokenization model. Pretrained on 29.9M single-cell transcriptomes (Genecorpus-30M), it enables zero- and few-shot network biology predictions — including in-silico perturbation and dosage-sensitivity prediction — with attention heads that recover transcription-factor hierarchy unsupervised.
Tokenization Strategy

Each gene's count is divided by its corpus-wide non-zero median (down-weighting ubiquitous housekeeping genes), then genes are ranked high→low and truncated to the top 2,048 — magnitude lives entirely in token position, not in a value token.

Scale: 29.9M cells | Context: 2,048 | Params: 10.3M (original, 6-layer/256-dim; later checkpoints scale to 316M)

iSEEEK: Integration via Gene Rankings

Shen et al. | Briefings in Bioinformatics 2022
scRNA-seq Transformer Rank-Based
Pioneered gene rank-based tokenization treating single-cell transcriptomes as "sentences" of ranked genes. Processes 11.9M cells without explicit batch correction by focusing on relative gene rankings.
Tokenization Strategy

Top 126 expressing genes per cell, ranked by expression level (128 total tokens = 1 [CLS] + 126 genes + 1 [SEP] — a full BERT-base-style 128-token context, not "all genes"). Uses [CLS] and [SEP] tokens with MLM objective. Vocabulary: 20,706 protein-coding genes.

Scale: 11.9M cells | Context: 128 tokens | Params: ~10M

scGPT: Multi-task Foundation Model

Cui et al. | Nature Methods 2024
scRNA-seq Transformer Binning + Special Tokens
Combines gene tokens with expression value tokens in a generative framework. Supports multiple tasks including batch correction, perturbation prediction, and multi-omics integration.
Tokenization Strategy

Gene tokens paired with binned expression values (51 bins). Special condition tokens for perturbation modeling. Context limited to ~1,200 most variable genes.

Scale: 33M cells | Context: 1,200 | Params: ~100M

scBERT: Large-Scale Pretrained Deep Language Model for Cell Type Annotation

Yang et al. | Nature Machine Intelligence 2022
scRNA-seq Performer (BERT-style) Binning + Special Tokens
Predates scGPT as the first BERT-style scRNA-seq foundation model to combine a fixed gene identity embedding (gene2vec) with discretized, binned expression — enabling long-context (full-transcriptome) cell-type annotation via a Performer backbone.
Tokenization Strategy

Gene embeddings from gene2vec (fixed gene identity, not learned jointly); continuous expression values discretized into bins and embedded via term-frequency-style binning. Full-length gene input handled by a Performer (linear-attention) backbone instead of truncating to a subset.

Scale: ~1.1M cells (PanglaoDB) | Context: ~16,906 genes (full) | Architecture: 200-dim embedding, 6 Performer layers, 10 heads

Nicheformer: Spatial-Aware Foundation Model

Tejada-Lapuerta et al. | Nature Methods 2025
scRNA-seq + Spatial Transformer Contextual Tokens
First foundation model jointly learning from dissociated (57M) and spatial (53M) transcriptomics. Technology-specific normalization handles modality differences.
Tokenization Strategy

Rank-based with technology-specific mean normalization. Contextual tokens: <ORGANISM>, <ASSAY>, <MODALITY>. Cross-species gene mapping via orthologs.

Scale: 110M cells | Context: 1,500 | Params: 49.3M

ChromFound: scATAC-seq Foundation Model

Jiao et al. | NeurIPS 2025
scATAC-seq Mamba-Transformer Genome-Coordinate
First foundation model for chromatin accessibility. Uses genome-coordinate tokenization instead of fixed vocabularies, enabling representation of tissue-specific OCRs.
Tokenization Strategy

Chromosome embedding + sinusoidal positional encoding of genomic coordinates (start/end). Linear accessibility embedding. Vocabulary-free approach for dynamic OCR landscapes.

Scale: 1.97M cells | Context: 440K OCRs | Params: ~450K (confirmed against the paper's own ablation table — a genuinely compact 4-layer, 128-dim hybrid, not a typo)

DNABERT: Pre-trained Bidirectional Encoder Representations for DNA-Language in Genome

Ji et al. | Bioinformatics 2021
DNA (human genome) BERT (12-layer) K-mer
The first BERT-style DNA language model, establishing k-mer tokenization as the default for genomic sequence pretraining. Captures local sequence context (promoters, splice sites, transcription-factor binding motifs) that single-nucleotide tokenization misses.
Tokenization Strategy

Overlapping sliding-window k-mers (3- to 6-mer variants tested, 4^k possible tokens), masking contiguous k-mers rather than single tokens during pretraining to prevent trivial inference from immediately adjacent, overlapping windows.

Scale: Human reference genome | Context: 512 tokens | Params: ~86-90M (12-layer BERT-base, varies by k)

DNABERT-2: Efficient Foundation Model and Benchmark for Multi-Species Genome

Zhou et al. | ICLR 2024
DNA (135 species) BERT + ALiBi BPE
Replaces DNABERT's fixed k-mer windows with a learned Byte-Pair Encoding vocabulary, eliminating the overlapping-window redundancy that inflates k-mer sequence length. Swaps learned positional embeddings for ALiBi to remove the fixed input-length ceiling, and adds FlashAttention for efficiency.
Tokenization Strategy

Byte-Pair Encoding merges the most frequent co-occurring subsequences into variable-length tokens (rather than fixed-width overlapping k-mer windows), so each base is covered exactly once — no k-mer overlap redundancy — while common motifs still collapse into single tokens.

Scale: Genomes from 135 species | Context: ALiBi — no fixed ceiling | Params: 117M

Evo 2: Genome Modeling and Design Across All Domains of Life

Brixi et al. (Arc Institute) | bioRxiv 2025
DNA (128,000+ species) StripedHyena 2 (SSM) Single-Nucleotide + SSM
Replaces attention with a state-space (Hyena-family) operator, making single-nucleotide-resolution tokenization tractable at genome scale — near-linear compute/memory scaling lets the model read up to 1 million bases at once with a 4-symbol vocabulary and zero OOV.
Tokenization Strategy

Every base (A/T/G/C) is its own token — no k-mer merging, no BPE vocabulary to learn or run out of. The StripedHyena 2 operator maintains a fixed-size running state instead of attending back over the full context, which is what makes single-base-per-token viable at 1Mb+ length.

Scale: 9.3T nucleotides, 128,000+ species | Context: up to 1M tokens | Params: 7B & 40B

ESM3: Multimodal Protein Language Model

Hayes et al. | Science 2025
Protein Seq + Structure + Function Masked Transformer Multimodal Tokens
Frontier multimodal generative model reasoning over sequence, structure, and function. Generated esmGFP—a novel fluorescent protein equivalent to 500M years of evolution from known proteins.
Tokenization Strategy

Separate token tracks for sequence (amino acids), structure (discrete autoencoder), and function (keywords from InterPro/GO). All modalities fused in shared latent space with masked language modeling.

Scale: 2.78B proteins | Context: Sequence + 3D Structure | Params: 1.4B-98B

C2S-Scale: LLM-Scale Single-Cell Foundation

Rizvi et al. | bioRxiv 2025
scRNA-seq Decoder-only LLM Cell2Sentence
Scales single-cell foundation models to 27B parameters using Cell2Sentence representation. Enables natural language question answering and experimentally validated drug discovery.
Tokenization Strategy

Cell2Sentence: expression encoded via token repetition (high expr = more repeats). GRPO refinement for biological task optimization. 8,192 token context.

Scale: 5.7M cells | Context: 8,192 | Params: 157M-27B

ProGen2: Protein Language Model Scaling

Nijkamp et al. | Cell Systems 2023
Protein Sequences Autoregressive Transformer Amino Acid
Scales protein language models to 6.4B parameters, demonstrating that data distribution matters more than model size for fitness prediction. Generated sequences adopt natural folds.
Tokenization Strategy

Standard amino acid tokenization with rotary positional encodings. Causal language modeling with next-token prediction. Context: 1,024-2,048 tokens.

Scale: UniRef90+BFD | Context: 2,048 AAs | Params: 151M-6.4B

VariantFormer: Personalized Gene Expression from Diploid Genomes

Ghosal et al. | bioRxiv 2025
DNA + Variants Hierarchical Transformer BPE + IUPAC
First foundation model to predict tissue-specific gene expression from personalized diploid genomes by integrating individual genetic variants directly into DNA sequences using IUPAC ambiguity codes.
Tokenization Strategy

IUPAC ambiguity codes for heterozygous sites (R=A/G, Y=C/T, etc.) embedded into reference genome. BPE tokenizer with a deliberately small 500-token vocabulary trained on cCREs (near-character-level — minimal merging — versus the 30K–50K vocabularies typical of NLP BPE, since regulatory DNA doesn't have "words" that benefit from heavy merging). Hierarchical cross-attention between CRE (±1Mb) and gene body windows.

Scale: 2,330 donors, 50K genes | Context: >2Mb | Params: 1.2B

SATURN: Universal Cross-Species Embeddings

Rosen et al. | Nature Methods 2024
scRNA-seq (Multi-Species) Autoencoder + Metric Learning Macrogene
Universal cell embeddings via protein language models (ESM2) coupled with RNA expression. Enables cross-species integration WITHOUT one-to-one gene homologs by grouping genes into macrogenes.
Tokenization Strategy

Genes clustered into ~2000 macrogenes via k-means on ESM2 protein embeddings (5120-dim). Gene-to-macrogene weights learned from protein similarity. Enables 350M-year divergent species integration.

Scale: 335K cells (3 species) | Context: ~2,000 macrogenes | Params: ~10M

State: A Scalable Virtual Cell Model Predicting Cellular Responses Across Diverse Contexts

Brixi et al. (Arc Institute) | bioRxiv June 2025
scRNA-seq Set Transformer Cell-as-Token
State breaks perturbation prediction into two stages: a State Embedding (SE) model pretrained on 167M observational cells that maps any cell's transcriptome to a single embedding vector, and a State Transition (ST) model pretrained on 100M perturbation-paired cells that maps a set of control embeddings to their perturbed state. The token is the whole cell, not the gene — bidirectional set attention runs across a population of cell vectors.
Tokenization Strategy

Cell-as-token: each cell's full transcriptome (gene identities + expression values) is compressed into one embedding vector by SE — the gene-level tokens are upstream inputs to that encoder, not the model's sequence elements. ST then applies set attention across a batch of such cell vectors, treating each cell embedding as a "token" in the context of the cell population. Granularity is one level up from every gene-level strategy on this page. See the full diagram ↓

Scale: 167M observational + 100M perturbation cells | Context: Set-based (variable cell count) | Params: not disclosed

STACK: In-Context Learning of Single-Cell Biology

Brixi et al. (Arc Institute) | preprint 2026
scRNA-seq Tabular Transformer (ICL) Cell-as-Token
STACK treats the cell × gene expression matrix as a table and applies tabular attention — attending within each row (across genes per cell) and across rows (across cells in the batch). At inference, labeled "example" cells are prepended as context rows; the model reads the control→perturbed pattern from those rows without any weight update, enabling true zero-shot perturbation prediction across new conditions, tissues, and donors.
Tokenization Strategy

Tabular cell-as-token: the input is a cell × gene matrix, not a sequence of gene tokens. Within-cell attention (along gene columns) captures co-expression; across-cell attention (along the row dimension) compares cell states. At inference, labeled context cells are appended as additional rows — the model treats them as "few-shot examples" read directly from the table, no gradient required. Pretrained on 149M cells from the Perturb Sapiens atlas. See the full diagram ↓

Scale: 149M cells (Perturb Sapiens atlas) | Context: Tabular (variable cell count × gene count) | Params: not disclosed

tGPT: Generative Pretraining from Large-Scale Transcriptomes

Shen et al. | iScience 2023
scRNA-seq Autoregressive Transformer (GPT) Rank-Based
Predates Geneformer's popularization of rank tokenization, but trains it causally rather than with masked language modeling — an early, widely-cited demonstration that a cell can be read as a rank-ordered "sentence" of genes even in a decoder-only, next-token-prediction setting.
Tokenization Strategy

Genes within a cell are sorted into a list by expression level, the same core move as Geneformer — no explicit expression-value token, magnitude lives in rank position. The model is then trained autoregressively (predict the next gene in the ranked list), closer to GPT-style pretraining than scBERT/Geneformer's BERT-style masking.

Scale: 22.3M cells | Context: not disclosed in this literature set | Params: not disclosed

CellPLM: Pre-training of Cell Language Model Beyond Single Cells

Wen et al. | bioRxiv 2023
scRNA-seq + Spatial Transformer Cell-as-Token
First single-cell pretrained transformer to explicitly model cell–cell relationships within a tissue rather than only gene–gene relationships within a cell — the same "cell-as-token" move STATE and STACK make years later, here paired with spatial transcriptomics as a pretraining prior on which cells should end up nearby.
Tokenization Strategy

Inverts the usual gene-token paradigm — "cells as tokens, tissues as sentences": each cell (itself encoded from its gene expression) becomes one token in a sequence of cells drawn from the same tissue or spatial neighborhood, letting the transformer attend across cells the way a language model attends across words. A learned Gaussian-mixture prior regularizes the cell-token embedding space to offset scRNA-seq's data scarcity relative to text corpora.

Scale: not fully disclosed in this literature set | Context: gene tokens + cell-level batch structure | Params: not disclosed

GeneCompass: Knowledge-Informed Cross-Species Foundation Model

Yang et al. | Cell Research 2024
scRNA-seq (human + mouse) BERT Encoder Rank-Based + Knowledge Tokens
Cross-species (human + mouse) model that injects four kinds of prior biological knowledge — promoter sequence, gene family, co-expression, and gene regulatory relationships — directly into pretraining, rather than leaving the model to rediscover them purely from expression statistics. Pretrained on over 120M collected single-cell transcriptomes (101.8M after preprocessing).
Tokenization Strategy

Rank-based gene tokenization in the Geneformer lineage, extended with parallel "prior-knowledge encodings" per gene — promoter-sequence, gene-family/ortholog, co-expression, and TF-target embeddings — summed alongside the expression-rank token, plus species tokens so a single shared vocabulary spans human and mouse genes via orthology mapping.

Scale: 101.8M cells (human + mouse) | Context: rank-based, Geneformer-style | Params: not disclosed

scFoundation: Large-Scale Foundation Model on Single-Cell Transcriptomics

Hao et al. | Nature Methods 2024
scRNA-seq Asymmetric Transformer (xTrimoGene) Read-Depth-Aware
Reference exemplar of Read-Depth-Aware tokenization (see the RDA strategy above). Pretrained on 50M cells across the full ~19,264-gene transcriptome — no highly-variable-gene subsetting — using the xTrimoGene architecture, whose asymmetric encoder-decoder skips non-expressed genes to keep genome-wide input tractable despite scRNA-seq's ~95% sparsity.
Tokenization Strategy

Each gene's continuous, unbinned expression is embedded directly (not ranked or binned), and two extra tokens — the cell's total read count and a target read count — are added alongside the gene tokens, letting the model be told at inference time what sequencing depth to "imagine" reading at. Trained with a mixed downsampling-and-masking objective rather than plain MLM; denoising happens only at the cell-embedding level, a design later contrasted against scPRINT's per-gene denoising.

Scale: 50M cells | Context: genome-wide (~19,264 genes) | Params: ~100M (xTrimoGene encoder-decoder)

UCE: Universal Cell Embedding

Rosen, Roohani et al. | Nature 2026
scRNA-seq (cross-species) 33-layer Transformer Protein-Embedding Gene Tokens
Builds one "universal" embedding space across species with zero fine-tuning by representing every gene as its encoded protein rather than a learned, species-specific ID — so the same model can zero-shot embed a species it never trained on. Trained self-supervised (predict whether a sampled gene was expressed) on the 36M-cell Integrated Mega-scale Atlas (IMA) spanning 300+ datasets.
Tokenization Strategy

Each cell is a weighted, with-replacement sample of 1,024 of its expressed genes — higher-expression genes are sampled more often, so expression lives in sampling frequency rather than a value token. Each gene token is the ESM2 (15B-parameter protein language model) embedding of its encoded protein, not a learned lookup — genes and species absent from training still get a meaningful token via protein-sequence homology. Gene tokens are grouped by chromosome, ordered by genomic position, and delimited by chromosome-specific start/end tokens, with a prepended CLS token whose final-layer output becomes the cell embedding.

Scale: 36M cells (IMA), 300+ datasets, cross-species | Context: 1,024 sampled gene tokens | Params: 650M (33 layers, built on frozen ESM2-15B gene tokens)

scPRINT: Pre-training on 50 Million Cells Allows Robust Gene Network Predictions

Kalfon et al. | Nature Communications 2025
scRNA-seq Bidirectional Transformer Multi-Embedding Sum Tokens
Combines a denoising task, a bottleneck task (reconstructing expression from the cell embedding alone, with no gene-level input), and hierarchical label prediction so one model yields disentangled cell-type/disease/species embeddings and cell-specific gene regulatory networks read directly off its attention heads.
Tokenization Strategy

Each gene token is the sum of three embeddings: (1) an ESM2 protein embedding of the gene's identity — following UCE, this lets the model generalize to unseen genes and species — (2) an MLP encoding of the gene's continuous log-normalized expression (not binned or ranked, unlike scGPT/Geneformer), and (3) a genomic-location embedding. Pretrained on 2,200 randomly selected expressed genes per cell, padded with unexpressed genes when a cell has fewer — the padding lets a zero-inflated negative-binomial decoder learn to tell true biological zeros from sequencing dropout.

Scale: 50M cells (cellxgene) | Context: 2,200 genes | Params: multiple scales released

scPRINT-2: Towards the Next Generation of Cell Foundation Models and Benchmarks

Kalfon et al. | bioRxiv 2026
scRNA-seq (16 organisms) XPressor Transformer ESM3 Multi-Embedding Sum
An "additive benchmark" that adds one scFM design choice at a time — tokenization, loss, sampling, architecture — to isolate what actually helps, then bundles the winners into scPRINT-2, pretrained on a new 350M-cell, 16-organism corpus, the largest cross-organism scRNA-seq dataset assembled to date.
Tokenization Strategy

Keeps scPRINT-1's three-way summed gene token (identity + expression + genomic location) but upgrades the identity embedding from ESM2 to ESM3, adding a fine-tuning adaptor layer after mean-pooling the protein embedding — the paper reports this beats learning gene tokens from scratch. Adds variable-context-length training and KNN-averaged "meta-cell" augmentation, plus a cell-level XPressor sub-architecture that makes the model directly generative for expression imputation and counterfactual reasoning. See the full diagram ↓

Scale: 350M cells, 16 organisms | Context: variable-length (data-augmented) | Params: not disclosed

2025–2026 developments:

· Evo 2 (2025) — single-nucleotide + StripedHyena 2 (SSM), 128,000+ species, 9.3T nucleotides, up to 1M-token context, zero k-mer OOV.

· DNABERT-2 (ICLR 2024) — BPE replaces fixed k-mer windows, eliminating overlapping-window redundancy and the fixed input-length ceiling (via ALiBi).

· Cell-level tokenization paradigm (STACK + STATE, see the Side-by-Side comparison below) — the token graduates from "gene within a cell" to "cell within a set," attending across whole cell populations rather than genes within one cell.

· VariantFormer (2025) — the first foundation model to predict tissue-specific gene expression directly from personalized diploid genomes.

· UCE (Nature 2026) — genes tokenized as ESM2 protein embeddings instead of learned IDs, giving zero-shot cross-species cell embeddings without fine-tuning.

· scPRINT / scPRINT-2 (2025–2026) — summed identity+expression+location gene tokens (ESM2 → ESM3), scaling the pretraining corpus from 50M to 350M cells across 16 organisms via an additive, one-feature-at-a-time benchmark.

Comparisons & Trade-offs

Every granularity level buys something and pays for something:

1×1 小颗粒 · Smaller units char / byte / base

✓ Zero OOV — every sequence is coverable; compositional generalization

✗ Very long sequences; almost no meaning per token; attention gets expensive

2×4 标准砖 · Middle units subword / codon / k-mer

✓ The working balance: coverage, real semantics, manageable vocabulary

✗ You must tune the knobs — merge count, k, overlapping redundancy

大板与定制件 · Larger units word / gene / macrogene

✓ Short sequences; every token carries real meaning

✗ OOV and batch-dependence; rare or novel units silently vanish

底板格点与塔高 · Value-free units rank / coordinate

✓ Batch-proof and vocabulary-free; robust across datasets

✗ Absolute magnitude is gone — 50 vs 5 becomes just 1st vs 2nd

连接件与底板 · Special tokens [CLS] / [SEP] / [MASK]

Content tokens carry meaning; special tokens carry the structure that makes meaning readable — invisible in the castle photo, but nothing snaps together without them:

[CLS] = 说明书封面的总览图 — the single overview picture that summarizes the whole build (classification & sequence embedding)

[SEP] = 房间隔断砖 — divider bricks that split one build into readable rooms (segment boundaries)

[MASK] = 被遮住的那一格 — a covered slot the model must guess from the surrounding bricks (where the learning signal comes from)

The table below is the same trade-off, one strategy at a time:

Tokenization Strategy Comparison

Strategy Data Type Key Advantage Limitation Representative Model
Gene Rank-Based scRNA-seq Batch-insensitive, captures relative expression patterns Loses absolute expression magnitude iSEEEK, Geneformer
Expression Binning scRNA-seq Preserves expression magnitude, compatible with NLP architectures Information loss from discretization scGPT, scBERT
Genome-Coordinate scATAC-seq Vocabulary-free, handles novel regions Requires reference genome alignment ChromFound
K-mer Tokenization DNA sequences Captures local sequence patterns Large vocabulary (4^k tokens) Nucleotide Transformer
BPE + IUPAC Diploid DNA + Variants Native heterozygous encoding; personalized genome modeling Requires phased VCF; expanded alphabet VariantFormer
Amino Acid + Multimodal Protein sequences + structure + function Simple sequence tokens; multimodal enables structure/function reasoning Ignores codon usage effects ESM3, ProGen2
Cell2Sentence scRNA-seq Compatible with standard LLMs, enables NL queries Long sequences from repetition encoding C2S-Scale
Macrogene scRNA-seq (cross-species) Enables cross-species integration without homologs via protein embeddings Requires reference proteomes; loses gene-level resolution SATURN
Single-Nucleotide + SSM DNA (genomic, long-context) Zero OOV (4-symbol vocabulary); no k-mer overlap redundancy; linear-time scan to 1M+ bp Requires a state-space architecture (Hyena/Mamba), not a plain Transformer Evo 2, HyenaDNA
Cell-as-Token (Set / Tabular) scRNA-seq Attends across whole cell populations; enables in-context perturbation prediction without fine-tuning Token is an entire cell — requires a cell-level encoder upstream of the set/tabular operator State, STACK

Context Length vs Model Scale Trade-offs

Different tokenization strategies and architectures dictate the maximum sequence length (context window) a model can handle, which impacts the biological scope it can capture.

Model Tokenization Strategy Context Length Parameters
iSEEEK Rank-Based (Top-K) 128 tokens ~10M
scGPT Binning (High Variance Genes) ~1,200 genes ~100M
Nicheformer Rank-Based (Top-K) 1,500 tokens 49.3M
AIDO.Cell Auto-Discretization (Full Transcriptome) 19,264 (full) 650M
ChromFound Genome-Coordinate (OCRs) 440K OCRs (via Mamba) 450K
ESM3 Amino Acid + Structure + Function Full protein (multimodal) 98B
VariantFormer BPE + IUPAC (Diploid) >2 Mb (CRE ±1Mb + gene body) 1.2B
C2S-Scale Cell2Sentence (Repetition) 8,192 tokens 27B
SATURN Macrogene (ESM2-based) ~2,000 macrogenes ~10M
Evo 2 Single-Nucleotide (StripedHyena 2 SSM) up to 1M tokens 7B / 40B
State Cell-as-Token (Set Transformer) Set-based (variable — whole cell population) not disclosed
STACK Cell-as-Token (Tabular ICL) Tabular (variable cells × ~20K genes) not disclosed

Choosing the Right Tokenization Strategy

Use Case Recommended Strategy Why
Large-scale integration (>1M cells) across many labs Gene Rank-Based Naturally batch-insensitive; focuses on robust relative signals.
Perturbation modeling (predicting gene knockout effects) Expression Binning Preserves the absolute expression magnitude needed to model dosage changes.
Chromatin accessibility analysis (scATAC-seq) Genome-Coordinate Tokenization Handles dynamic open chromatin regions varying across cell types without a fixed vocabulary.
Protein fitness or structure prediction Amino Acid Tokenization Standard approach that effectively captures evolutionary constraints in protein sequences.
Personalized gene expression prediction from WGS BPE + IUPAC Encodes heterozygous variants natively; enables variant effect prediction from individual genomes.
Interacting with cell data using natural language Cell2Sentence Converts biological data into a format understood by standard Large Language Models.
Whole-genome or chromosome-scale long-sequence analysis Single-Nucleotide + SSM K-mer vocabularies explode at 1M+ context; a state-space model's linear scaling is the only tractable path at that length.
Cross-species comparative genomics without 1:1 orthologs Macrogene Clustering by protein-embedding similarity bridges species separated by hundreds of millions of years of divergence.
Perturbation prediction across new conditions / tissues without fine-tuning Cell-as-Token (STACK) Tabular in-context learning reads labeled example cells at inference — no gradient update needed for new perturbations or donors.

⚖️ Side-by-Side: Encoding Expression — Rank Ordering vs Value Binning

Geneformer and scGPT both turn a single cell's expression vector into a token sequence a transformer can read, but they diverge on the fundamental question: should a gene's expression level be encoded implicitly by its rank among the other genes (Geneformer), or explicitly as a discrete value token paired with the gene (scGPT)?

The same starting point — one cell's gene-by-count vector — becomes two very different token streams depending on how expression magnitude is represented:

Geneformer
rank-value encoding (2023)
Normalize each gene by its non-zero median
divide by the corpus-wide median so ubiquitously high housekeeping genes are down-weighted
Rank genes high → low
keep the ordered gene list, drop zeros, truncate to 2,048; magnitude is carried by position
rank_ordered_genes [gene tokens]
value-free · magnitude → position · single token stream · Ensembl IDs · BERT-style encoder
scGPT
value binning (2024)
Normalize + log1p, then bin non-zero values
each cell's expression is split into N relative bins (typically 51) by within-cell quantile
Emit aligned (gene, value-bin) pairs
two parallel streams — gene identity plus an explicit binned-magnitude token per gene
gene_tokens value_bins
value-explicit · magnitude preserved · gene + value tokens · condition tokens · GPT-style generative

The split traces back to one root decision — rank ordering vs value binning. Geneformer discards absolute magnitude (50 vs 5 collapses to just 1st vs 2nd), which makes it naturally depth- and batch-robust but blind to dosage; scGPT keeps magnitude as an explicit token, which is exactly what perturbation and dosage modeling need but leaves it sensitive to normalization and batch. Vocabulary size, sequence length, and out-of-vocabulary behavior all follow from that one choice.

Up a Level: Cells as Tokens — STACK vs STATE

The two models above tokenize genes within a cell. STACK and STATE (both from the Arc Institute) move up a granularity — the token is the whole cell, and attention runs over a set or table of cells. They diverge on how a set of cells becomes a perturbation prediction: STACK learns in context from unlabeled example cells at inference, while STATE trains an explicit embedding-plus-transition pipeline.

The same set of cells becomes a perturbation prediction two different ways — by learning in context at inference, or by a separately trained transition operator:

STACK
tabular in-context learning (2025)
Tabular attention over a cell × gene table
attend within a cell (across genes) and across cells (inter-cell), treating the matrix as a table
Learn in context at inference
unlabeled example cells (conditions, donors) guide the prediction — no task-specific fine-tuning
context_cells predicted_effect
149M cells · cell-as-token · in-context · no fine-tuning · Perturb Sapiens atlas
STATE
embedding + set transition (2025)
State Embedding (SE): one vector per cell
trained on 167M observational cells to represent each cell independently
State Transition (ST): trained set operator
maps a set of control cells → their perturbed state, trained on 100M perturbation cells
SE_embedding ST_prediction
167M + 100M cells · cell-as-token · trained transition · set-based attention · perturbation-specialized

The root decision here is in-context learning from example cells vs a separately trained embedding-and-transition pipeline. Both treat the cell (not the gene) as the token and attend across a set of cells — a step up in granularity from the gene-level tokens above. STACK trades a training step for flexible, fine-tuning-free generalization to new conditions; STATE's dedicated transition model gives an explicit control→perturbed operator built specifically for perturbation-effect prediction.

🛠️ Hands-On Practice

The steps below walk through tokenizing a single-cell dataset for a transformer foundation model — from an AnnData count matrix to two model-ready token streams: a rank-ordered sequence (Geneformer-style) and a (gene, value-bin) sequence (scGPT-style). The core logic is shown from scratch in NumPy so the mechanics are transparent, then mapped to the real library call.

Environment & packages

Install a minimal tokenization stack. scanpy/anndata hold the matrix; the model-specific tokenizers (Geneformer's TranscriptomeTokenizer, scGPT's GeneVocab) emit the final token IDs and handle the gene vocabulary, special tokens, and truncation.

# conda / mamba recommended
conda create -n tok python=3.10 -y
conda activate tok

pip install scanpy anndata numpy datasets
# model-specific tokenizers:
pip install geneformer          # rank-value encoding (expects Ensembl IDs)
# pip install scgpt             # value binning (GeneVocab tokenizer)

Hardware. Tokenization is CPU-bound and cheap — a laptop handles 100k+ cells. A GPU is only needed for the downstream model forward pass, not for building the token streams.

Data structures & formats

  • AnnData — input: adata.X (raw counts), adata.var["ensembl_id"] (Geneformer keys on Ensembl IDs, not symbols), adata.obs["n_counts"] (total counts per cell)
  • Token dictionary — a fixed gene → integer ID vocabulary; genes absent from it are out-of-vocabulary and silently dropped
  • Rank-encoded sequence — an ordered list of gene token IDs per cell (no value tokens), truncated to the model context length (2,048 for Geneformer)
  • Value-binned sequence — aligned arrays of gene token IDs and discrete value-bin IDs (e.g. 51 bins) per cell
  • Special tokens<cls> (cell-level embedding), <pad> (padding to a fixed length), <mask> (masked-token pretraining objective)
  • Output — Geneformer emits a HuggingFace .dataset (Arrow) of token IDs; scGPT works from tensors of (gene_ids, values)

Minimal code walkthrough

Encode a toy count matrix with both strategies to expose the mechanics, then map to the real Geneformer tokenizer.

import numpy as np

# Toy: 3 cells x 6 genes (raw UMI counts). In practice: adata = sc.read_h5ad(...)
genes  = np.array(["CD3D", "MS4A1", "GAPDH", "NKG7", "LYZ", "ACTB"])
counts = np.array([[12,  0, 40, 3,  0, 30],
                   [ 0, 25, 35, 1, 18, 22],
                   [ 5,  0, 50, 9,  2, 28]], dtype=float)

# ---------- Strategy A: rank-value encoding (Geneformer-style) ----------
# 1. Normalize each gene by its NON-ZERO median across the corpus. This
#    down-weights housekeeping genes that are uniformly high (GAPDH, ACTB).
nz          = np.where(counts > 0, counts, np.nan)
gene_median = np.nanmedian(nz, axis=0)
norm        = counts / gene_median

# 2. Per cell, rank genes by normalized expression high -> low; drop zeros.
def rank_encode(cell):
    idx = np.where(cell > 0)[0]
    return genes[idx[np.argsort(-cell[idx])]].tolist()

for i in range(counts.shape[0]):
    print(f"cell {i} rank tokens:", rank_encode(norm[i]))
# -> ordered gene tokens only; magnitude lives in POSITION, no value token.

# ---------- Strategy B: value binning (scGPT-style) ----------
N_BINS = 5   # scGPT uses ~51 in practice
def value_bin(cell):
    idx   = np.where(cell > 0)[0]
    vals  = np.log1p(cell[idx])
    ranks = vals.argsort().argsort()                 # per-cell quantile rank
    bins  = np.floor(ranks / len(idx) * N_BINS).astype(int)
    bins  = np.clip(bins, 0, N_BINS - 1)              # guard the top-rank edge case
    return list(zip(genes[idx].tolist(), bins.tolist()))

for i in range(counts.shape[0]):
    print(f"cell {i} (gene, bin):", value_bin(counts[i]))
# -> aligned (gene token, value-bin token) pairs; magnitude is explicit.

In production you would not hand-roll this — the model ships a tokenizer that also handles the gene vocabulary, special tokens, and truncation:

# tested against geneformer>=1.0 — the TranscriptomeTokenizer constructor
# signature has changed across major versions; pin your version and check
# the CHANGELOG before upgrading an existing tokenization pipeline.
from geneformer import TranscriptomeTokenizer

# adata must carry raw counts, adata.var["ensembl_id"], adata.obs["n_counts"].
tk = TranscriptomeTokenizer({"cell_type": "cell_type"}, nproc=4)
tk.tokenize_data(
    "data_dir/",        # folder of .h5ad / .loom files
    "output_dir/",
    "tokenized",        # output prefix
    file_format="h5ad",
)
# -> output_dir/tokenized.dataset : rank-ordered token IDs per cell,
#    median-normalized internally and truncated to 2,048 genes.

Strategy C: single-nucleotide tokenization (Evo/HyenaDNA-style). For DNA rather than expression data, the same "hand-roll it first" approach looks like this — no gene vocabulary, no binning, just one token per base:

# Vocab = 5 (4 bases + N for ambiguous/unknown); no merge operations at all.
nuc_vocab = {"A": 0, "T": 1, "G": 2, "C": 3, "N": 4}

def nucleotide_tokenize(seq: str) -> list[int]:
    return [nuc_vocab.get(c.upper(), 4) for c in seq]

seq = "ATGCATGCN..."   # in practice: a 1Mb+ window read from a reference/FASTA
tokens = nucleotide_tokenize(seq)
# -> every character becomes a token; zero OOV by construction, but the
#    context length equals len(seq) exactly — at genome scale this is only
#    tractable with a linear-time backend (Hyena/Mamba), not full attention.

Common pitfalls & tips

  • Gene ID system mismatch. Geneformer's vocabulary is keyed on Ensembl IDs, not gene symbols — map symbols → Ensembl before tokenizing, or most genes become OOV and vanish.
  • Wrong normalization state. Geneformer expects raw counts and median-normalizes internally; scGPT expects normalized/log1p input. Double-normalizing (feeding already-log-normed data to Geneformer) corrupts the ranking.
  • Check vocabulary coverage. Any gene not in the token dictionary is dropped silently; a low-overlap panel (targeted or non-human data) can lose most of its signal before the model sees a single token. Log the fraction of counts retained.
  • Sequence-length truncation drops the tail. Rank encoding keeps only the top ~2,048 genes; lowly expressed but biologically important genes fall off the end, and sparse cells yield short, padding-heavy sequences.
  • Value bins are per-cell and relative. "Bin 50" in one cell is not the same absolute expression as "bin 50" in another — binning is computed within each cell, so depth and batch effects shift the mapping; don't compare raw bin IDs across cells.
  • Don't forget special tokens. The <cls> position carries the cell-level embedding and <pad> must be masked in attention; omitting or mis-placing them silently degrades every downstream readout.