flowchart LR
L[Text] --> TL[Subwords or bytes]
I[Images] --> TI[Patches or VQ codes]
A[Audio] --> TA[Frames or codec codes]
V[Video] --> TV[Tubelets or video codes]
R[Catalog items] --> TR[Atomic or semantic IDs]
TL --> E[Token embeddings + structure]
TI --> E
TA --> E
TV --> E
TR --> E
E --> M[General sequence model]
M --> O[Prediction, retrieval, generation, or control]
Tokenization Across Modalities
Core Idea
Tokenization converts a large or structured input into a sequence of units that a model can process:
\[ x \xrightarrow{\text{segment}} (u_1,\ldots,u_T) \xrightarrow{\text{encode}} (z_1,\ldots,z_T). \]
Depending on the method, \(z_t\) may be either:
- a discrete ID looked up in an embedding table, or
- a continuous vector produced by a linear layer or neural encoder.
This distinction is important. A ViT image patch is commonly called a token, but it is usually projected directly into a continuous vector rather than assigned a discrete vocabulary ID.
Why tokenization is needed beyond language
A neural network does not directly consume a word, photograph, sound, video, or catalog item. Its kernels consume finite tensors with known dimensions. The raw domains, however, have very different structure:
- text is variable-length and drawn from an effectively open symbol space
- images are dense two-dimensional arrays with millions of correlated values
- audio and video are high-rate signals that would produce enormous sequences
- recommendation catalogs contain millions or billions of sparse categorical IDs with little inherent geometry
Tokenization is the interface that reconciles this mismatch. In its broadest sense, it compiles a domain object into a bounded sequence of model-facing units:
\[ \tau(x) = \big((z_1,p_1,m_1),\ldots,(z_T,p_T,m_T)\big), \]
where \(z_t\) is a discrete ID or continuous feature, \(p_t\) describes position or structure, and \(m_t\) can identify the modality or token type. A general sequence model then operates on this interface rather than on the original representation.
This is why tokenization is not intrinsically an LLM component. It is an abstraction boundary between domain-specific perception or identity and a model that expects a sequence of vectors. The same Transformer can process different fields once their tokenizers produce compatible shapes and attach the right positional and modality information.
What the tokenizer decides
The tokenizer does more than change a data type. It makes several modeling decisions before the backbone sees the input:
| Decision | Question | Consequence |
|---|---|---|
| Units | What should count as one token? | determines the primitive patterns the model can combine |
| Compression | How much raw information enters each token? | trades sequence length and compute against lost detail |
| Parameter sharing | Which observations reuse an ID, code, or encoder? | determines how statistical strength transfers between examples |
| Structure | How are space, time, hierarchy, and modality represented? | supplies ordering and neighborhood information absent from token values |
| Reversibility | Must the original input be reconstructed? | separates semantic representations from generation-quality codecs |
The token sequence is therefore an information and compute budget. For dense attention with \(T\) tokens, the attention-score matrix costs \(O(T^2)\). Reducing image patch size, audio hop size, or video tubelet size may preserve more detail, but can make the backbone dramatically more expensive.
Tokenization also defines inductive bias. Subwords encourage reuse across related words; image patches encode locality; codec tokens favor reconstructability; semantic item IDs encourage related items to share code embeddings. A downstream model cannot reliably recover information that its tokenizer discarded.
Why large sparse IDs are a tokenization problem
An atomic recommendation ID is already a discrete token, but it is an arbitrary name. With \(N\) items and embedding dimension \(d\), a direct item table requires \(O(Nd)\) parameters, and two similar items share no representation unless the training data teaches their embeddings to be similar.
A semantic tokenizer can replace one huge categorical space with a composition of \(M\) codes drawn from codebooks of size \(K\):
\[ i \longrightarrow (c_1,\ldots,c_M), \qquad c_m\in\{1,\ldots,K\}. \]
The code embeddings require roughly \(O(MKd)\) parameters while the code tuples can represent up to \(K^M\) combinations. More importantly, rare or new items can reuse codes learned by related items. This is analogous to representing a rare word with reusable subwords, although recommendation systems must additionally preserve exact item identity and prevent invalid or colliding code sequences.
When tokenization is not necessary
Tokenization is most valuable for inputs that are variable-sized, high-dimensional, high-rate, sparse categorical, or intended to share a sequence backbone. A small, fixed-length dense feature vector can usually be fed directly to an MLP; calling every numeric feature a token adds no inherent value.
The useful first-principles question is therefore not “How do I tokenize this modality?” but:
What representation exposes the task-relevant structure at a token rate and parameter cost the model can afford?
Text Tokenization
Common methods
| Method | Unit | Strength | Weakness |
|---|---|---|---|
| Word | whole word | short, interpretable sequences | huge vocabulary and out-of-vocabulary words |
| Character | Unicode character | open vocabulary | long sequences; characters are not equally meaningful across languages |
| Byte | UTF-8 byte | fixed vocabulary of 256 and no unknown input bytes | longer sequences, especially for some scripts |
| BPE | frequent pair merges | simple and efficient subwords | greedy merge history is not a probabilistic model |
| WordPiece | subwords chosen to improve a language-model objective | useful compromise between words and characters | training details differ across implementations |
| Unigram LM | selects a segmentation from a probabilistic subword vocabulary | supports multiple candidate segmentations and subword regularization | requires vocabulary pruning and segmentation search |
BPE repeatedly merges frequent adjacent symbols. SentencePiece can learn BPE or a unigram tokenizer directly from raw text without requiring language-specific pre-tokenization.
Typical pipeline
raw text
↓
Unicode normalization
↓
optional pre-tokenization
↓
subword or byte segmentation
↓
special tokens + token IDs
Important design choices:
- vocabulary size
- byte fallback and unknown-token behavior
- whitespace representation
- Unicode normalization
- special tokens such as BOS, EOS, PAD, and modality separators
- whether segmentation is deterministic or sampled during training
BPE from first principles
Byte-pair encoding learns a vocabulary between the two extremes of characters and whole words. It begins with small symbols and repeatedly creates a new symbol for the most frequent adjacent pair. Frequent fragments become single tokens, while rare words remain compositions of smaller reusable tokens.
Suppose a pre-tokenized corpus contains word types \(w\) with counts \(c(w)\), and the current segmentation of each word is \(s(w)\). At each training step, count every adjacent pair and select
\[ (a^*,b^*) = \arg\max_{(a,b)} \sum_w c(w) \sum_i \mathbf{1} \left[ (s_i(w),s_{i+1}(w))=(a,b) \right]. \]
Then replace every non-overlapping occurrence of \((a^*,b^*)\) with the new symbol \(a^*b^*\). For example,
l o w e r
merge (l, o)
lo w e r
merge (lo, w)
low e r
The algorithm has two distinct phases:
- Training: repeatedly count pairs on the training corpus and store the selected merges in order.
- Encoding: start a new input from the base symbols and apply only those learned merges, respecting their learned priority. Pair frequencies are not relearned from the input being encoded.
The ordered merge list is therefore the tokenizer’s learned model. If merge \((a,b)\) was learned before merge \((ab,c)\), the first merge must create ab before the second can create abc.
Minimal BPE with incremental training
A useful middle ground keeps the optimization that matters at corpus scale without reproducing a production tokenizer’s internal data structures.
The trainer maintains:
| State | Purpose |
|---|---|
| pair counts | current corpus-wide frequency of each adjacent pair |
| pair-to-word index | word types affected by a selected merge |
| max-heap | retrieve the next pair without scanning every candidate |
There is one full pair-counting pass. After that, a merge revisits only word types containing the selected pair and updates their pair-count deltas. Stale heap entries are discarded lazily. This avoids rescanning the entire corpus for every learned token while leaving the BPE recurrence visible.
from collections import Counter, defaultdict
import heapq
def byte_symbols(text):
return tuple(bytes([value]) for value in text.encode("utf-8"))
def count_pairs(symbols):
return Counter(zip(symbols, symbols[1:]))
def merge_pair(symbols, target):
"""Merge non-overlapping occurrences of target from left to right."""
output = []
index = 0
while index < len(symbols):
if (
index + 1 < len(symbols)
and (symbols[index], symbols[index + 1]) == target
):
output.append(symbols[index] + symbols[index + 1])
index += 2
else:
output.append(symbols[index])
index += 1
return tuple(output)
class MinimalBPE:
def __init__(self, num_merges, min_frequency=2):
self.num_merges = num_merges
self.min_frequency = min_frequency
def fit(self, texts):
word_counts = Counter(
word
for text in texts
for word in text.split()
)
words = [byte_symbols(word) for word in word_counts]
frequencies = list(word_counts.values())
pair_counts = Counter()
pair_to_words = defaultdict(set)
# The only full pass over the corpus vocabulary.
for word_id, (symbols, frequency) in enumerate(zip(words, frequencies)):
for pair, occurrences in count_pairs(symbols).items():
pair_counts[pair] += occurrences * frequency
pair_to_words[pair].add(word_id)
# Python implements a min-heap, so counts are negated.
heap = [(-count, pair) for pair, count in pair_counts.items()]
heapq.heapify(heap)
self.merges = []
for _ in range(self.num_merges):
# Pair counts change over time. Ignore stale heap entries.
while heap:
negative_count, best_pair = heapq.heappop(heap)
if -negative_count == pair_counts.get(best_pair, 0):
break
else:
break
if pair_counts[best_pair] < self.min_frequency:
break
self.merges.append(best_pair)
changed_pairs = set()
# Only these word types can change under this merge.
for word_id in tuple(pair_to_words[best_pair]):
before = count_pairs(words[word_id])
words[word_id] = merge_pair(words[word_id], best_pair)
after = count_pairs(words[word_id])
frequency = frequencies[word_id]
for pair in before.keys() | after.keys():
pair_counts[pair] += (
after[pair] - before[pair]
) * frequency
changed_pairs.add(pair)
if after[pair]:
pair_to_words[pair].add(word_id)
else:
pair_to_words[pair].discard(word_id)
for pair in changed_pairs:
if pair_counts[pair] > 0:
heapq.heappush(heap, (-pair_counts[pair], pair))
self.merge_ranks = {
pair: rank for rank, pair in enumerate(self.merges)
}
# Byte IDs 0...255 are fixed; learned tokens follow merge order.
vocabulary = [bytes([value]) for value in range(256)]
self.token_to_id = {
token: token_id for token_id, token in enumerate(vocabulary)
}
for left, right in self.merges:
token = left + right
if token not in self.token_to_id:
self.token_to_id[token] = len(vocabulary)
vocabulary.append(token)
self.id_to_token = dict(enumerate(vocabulary))
return self
def encode_piece(self, piece):
symbols = byte_symbols(piece)
# At most len(symbols) - 1 merges can happen. Crucially, this searches
# only adjacent pairs in the piece, not every rule in the vocabulary.
while len(symbols) > 1:
candidates = [
(self.merge_ranks[pair], pair)
for pair in zip(symbols, symbols[1:])
if pair in self.merge_ranks
]
if not candidates:
break
_, best_pair = min(candidates)
symbols = merge_pair(symbols, best_pair)
return list(symbols)
def encode_tokens(self, text):
tokens = []
for word_index, word in enumerate(text.split()):
if word_index:
tokens.append(b" ")
tokens.extend(self.encode_piece(word))
return tokens
def encode(self, text):
return [self.token_to_id[token] for token in self.encode_tokens(text)]
def decode(self, token_ids):
return b"".join(self.id_to_token[i] for i in token_ids).decode("utf-8")
corpus = [
"low lower lowest",
"low lower",
"newer wider",
]
bpe = MinimalBPE(num_merges=8, min_frequency=1).fit(corpus)
tokens = bpe.encode_tokens("lowest newer")
token_ids = bpe.encode("lowest newer")
assert bpe.decode(token_ids) == "lowest newer"
print("merges:", bpe.merges)
print("tokens:", [token.decode("utf-8") for token in tokens])
print("ids:", token_ids)merges: [(b'l', b'o'), (b'lo', b'w'), (b'e', b'r'), (b'low', b'er'), (b'd', b'er'), (b'e', b's'), (b'e', b'w'), (b'es', b't')]
tokens: ['low', 'est', ' ', 'n', 'ew', 'er']
ids: [257, 263, 32, 110, 262, 258]
Let \(C\) be the initial number of symbols across distinct pre-tokenized word types, and let \(A_k\) be the total length of word types affected by merge \(k\). Training costs approximately
\[ O\left( C + \sum_{k=1}^{M} A_k + H \right), \]
where \(H\) is heap overhead. This is substantially better than the naïve \(O(MC)\) full rescan when most pairs occur in only a small part of the vocabulary.
The compact encoder repeatedly finds the learned pair with the best rank among the current adjacent pairs. It is \(O(n^2)\) in the worst case for a piece of \(n\) bytes, but it does not scan all \(M\) learned rules and pre-tokenized pieces are usually short. A production encoder replaces the list rescans with linked neighbors and a candidate heap, approaching \(O(n\log n)\), and adds caching and native parallelism.
This implementation still simplifies pre-tokenization: split() collapses whitespace, and it omits normalization and special-token handling. For production, use native libraries such as Hugging Face Tokenizers or OpenAI tiktoken.
BPE training is a greedy corpus-compression procedure. BPE encoding is a deterministic replay of the learned merge priorities. Choosing the most frequent pair in each new input would define a different tokenizer and would not produce the token IDs the model was trained on.
Minimal byte tokenizer
This is lossless for valid UTF-8 text and has no learned vocabulary. It is educational rather than a complete production tokenizer.
class ByteTokenizer:
vocab_size = 256
def encode(self, text):
return list(text.encode("utf-8"))
def decode(self, token_ids):
return bytes(token_ids).decode("utf-8")
byte_tokenizer = ByteTokenizer()
text = "Minimal ML 🤖"
text_ids = byte_tokenizer.encode(text)
assert byte_tokenizer.decode(text_ids) == text
text_ids[77, 105, 110, 105, 109, 97, 108, 32, 77, 76, 32, 240, 159, 164, 150]
Questions to fill in
- Why does increasing vocabulary size usually reduce sequence length?
- What is the difference between BPE, WordPiece, and unigram tokenization?
- Why can tokenization make arithmetic, spelling, and multilingual modeling difficult?
- What happens when the tokenizer used at inference differs from training?
- Why might byte fallback be preferable to an unknown token?
Image Tokenization
Patch tokens
Given an image
\[ X \in \mathbb{R}^{C \times H \times W}, \]
split it into non-overlapping \(P\times P\) patches. The token count is
\[ T = \frac{H}{P}\frac{W}{P}, \]
and each flattened patch has dimension \(CP^2\). A learned projection maps it to \(d_{\text{model}}\). This is the continuous-token approach used by Vision Transformer.
import torch
import torch.nn.functional as F
def patchify(images, patch_size):
"""Convert (B, C, H, W) images to (B, num_patches, patch_dim)."""
batch_size, channels, height, width = images.shape
if height % patch_size or width % patch_size:
raise ValueError("height and width must be divisible by patch_size")
patches = F.unfold(
images, kernel_size=patch_size, stride=patch_size
)
return patches.transpose(1, 2)
images = torch.randn(2, 3, 32, 32)
image_tokens = patchify(images, patch_size=8)
assert image_tokens.shape == (2, 16, 3 * 8 * 8)
image_tokens.shapetorch.Size([2, 16, 192])
Discrete visual tokens
An encoder can first produce a spatial latent grid and then quantize every latent vector to its nearest codebook entry:
\[ z_e(x)_{ij} \longrightarrow k_{ij} = \arg\min_k \left\|z_e(x)_{ij}-e_k\right\|_2^2. \]
The grid of codebook indices \((k_{ij})\) is a sequence of discrete image tokens. A decoder reconstructs pixels from the selected code vectors. This is the key idea behind VQ-VAE.
Common image units:
- pixels: maximum granularity, extremely long sequence
- fixed patches: simple continuous tokens for understanding tasks
- learned VQ codes: discrete tokens useful for generation
- region or object tokens: adaptive units intended to capture semantic objects
Learning prompt: Why might an image tokenizer optimized only for pixel reconstruction preserve texture better than semantic identity?
Audio Tokenization
Audio is a one-dimensional signal with a high sampling rate, so treating every sample as a token produces very long sequences.
Common methods
- Waveform chunks: group raw samples into fixed-length frames and project them.
- Spectrogram patches: transform the waveform into time-frequency features, then patch them like an image.
- Neural codec tokens: encode audio into a lower-rate latent sequence and quantize it with one or more codebooks.
- Semantic speech tokens: cluster hidden representations from a pretrained speech encoder; these emphasize linguistic content more than exact waveform reconstruction.
For sample rate \(f_s\), frame size \(W\), and hop size \(H_s\), the approximate number of frames in an \(L\)-sample waveform is
\[ T = 1 + \left\lfloor\frac{L-W}{H_s}\right\rfloor. \]
def frame_audio(waveforms, frame_size, hop_size):
"""Convert (B, samples) waveforms to (B, frames, frame_size)."""
if waveforms.shape[-1] < frame_size:
raise ValueError("waveform is shorter than one frame")
return waveforms.unfold(-1, frame_size, hop_size)
waveforms = torch.randn(2, 16_000) # one second at 16 kHz
audio_frames = frame_audio(waveforms, frame_size=400, hop_size=160)
assert audio_frames.shape == (2, 98, 400)
audio_frames.shapetorch.Size([2, 98, 400])
Neural codecs such as SoundStream use residual vector quantization: multiple codebooks progressively encode the residual error. At each time step, this creates several parallel discrete codes.
If the codec emits \(n_q\) codebook IDs per frame at frame rate \(f\), its token rate is
\[ n_q f \quad \text{tokens per second}. \]
Important tradeoffs:
- semantic content versus acoustic detail
- bitrate versus reconstruction quality
- causal/streamable encoding versus bidirectional encoding
- robustness to speakers, noise, and recording conditions
Video Tokenization
A video introduces a temporal dimension:
\[ X \in \mathbb{R}^{C \times T \times H \times W}. \]
Common methods
- Frame tokens: encode each frame into one vector; cheap but discards spatial detail.
- Per-frame patches: patchify every frame; preserves detail but creates long sequences.
- Tubelets: split a video into 3D blocks spanning time and space.
- Discrete video codes: quantize a learned spatiotemporal latent grid.
- Adaptive tokens: pool tracks, objects, or events into content-dependent units.
For tubelet size \(P_t\times P_h\times P_w\), the number of tokens is
\[ N = \frac{T}{P_t} \frac{H}{P_h} \frac{W}{P_w}. \]
import torch.nn as nn
class TubeletTokenizer(nn.Module):
def __init__(self, in_channels, d_model, tubelet_size, patch_size):
super().__init__()
kernel = (tubelet_size, patch_size, patch_size)
self.projection = nn.Conv3d(
in_channels,
d_model,
kernel_size=kernel,
stride=kernel,
)
def forward(self, videos):
# (B, C, T, H, W) -> (B, D, T', H', W')
tokens = self.projection(videos)
# Preserve a conventional time-major raster order.
return tokens.flatten(2).transpose(1, 2)
videos = torch.randn(2, 3, 8, 32, 32)
video_tokenizer = TubeletTokenizer(
in_channels=3, d_model=64, tubelet_size=2, patch_size=8
)
video_tokens = video_tokenizer(videos)
assert video_tokens.shape == (2, 4 * 4 * 4, 64)
video_tokens.shapetorch.Size([2, 64, 64])
Video sequence length grows across three axes. Tokenization therefore controls not only information loss but also the quadratic cost of dense attention.
Questions to fill in
- What temporal information is lost when every frame is tokenized independently?
- How does tubelet size affect motion resolution and sequence length?
- When should spatial and temporal attention be factorized?
- How should variable frame rates and video durations be handled?
Semantic IDs in Recommendation Systems
Traditional recommenders often assign every item an arbitrary atomic ID:
\[ \text{item} \longrightarrow i. \]
The ID uniquely identifies the item but says nothing about its content or its relationship to other items. A semantic ID instead maps an item embedding to a short sequence of learned discrete codes:
\[ \text{item} \xrightarrow{\text{encoder}} z \xrightarrow{\text{quantizer}} (c_1,c_2,\ldots,c_M). \]
Generative recommenders can then predict the next item’s semantic ID autoregressively. TIGER is a representative example using residual-quantized semantic IDs for generative retrieval.
Residual quantization
Starting with item embedding \(z\) and residual \(r_0=z\), codebook level \(m\) selects
\[ c_m = \arg\min_k \left\|r_{m-1}-e_k^{(m)}\right\|_2^2, \]
then updates
\[ r_m = r_{m-1}-e_{c_m}^{(m)}. \]
The quantized approximation is
\[ \widehat z = \sum_{m=1}^{M}e_{c_m}^{(m)}. \]
Early codes capture coarse structure; later codes refine the residual. Shared prefixes may therefore reflect semantic similarity, although this is an optimization outcome rather than an unconditional guarantee.
Minimal residual quantizer
def residual_quantize(vectors, codebooks):
"""
Args:
vectors: (N, D)
codebooks: (M, K, D), one K-entry codebook per level
Returns:
semantic_ids: (N, M)
quantized: (N, D)
"""
residual = vectors
quantized = torch.zeros_like(vectors)
all_ids = []
for codebook in codebooks:
distances = torch.cdist(residual.float(), codebook.float())
code_ids = distances.argmin(dim=-1)
selected = codebook[code_ids]
all_ids.append(code_ids)
quantized = quantized + selected
residual = residual - selected
return torch.stack(all_ids, dim=-1), quantized
torch.manual_seed(0)
item_embeddings = torch.randn(6, 8)
codebooks = torch.randn(3, 16, 8)
semantic_ids, reconstructed = residual_quantize(
item_embeddings, codebooks
)
assert semantic_ids.shape == (6, 3)
semantic_idstensor([[ 8, 6, 9],
[14, 7, 9],
[ 8, 11, 0],
[10, 5, 9],
[ 4, 2, 0],
[12, 6, 9]])
This function performs only nearest-code assignment. Training an RQ-VAE also requires an encoder, decoder, reconstruction objective, codebook/commitment losses, and a strategy for updating codebooks.
Why semantic IDs can help
- replace a massive item embedding table with shared code embeddings
- expose similarity through shared codes or prefixes
- let a sequence model generate and retrieve items token by token
- transfer information to rare or new items when their content embeddings can be encoded
What can go wrong
- Collisions: multiple items may receive the same complete semantic ID.
- Invalid generations: a predicted code sequence may not correspond to any catalog item.
- Quantization loss: nearby or distinct item embeddings may be distorted by codebook boundaries.
- Catalog drift: new items and changing item semantics can require re-tokenization.
- Popularity leakage: content-derived similarity may not capture collaborative preference signals.
- Longer decoding: one recommendation now requires predicting several tokens.
Practical systems may add a disambiguation token for collisions and use a catalog trie or constrained beam search so every generated prefix can lead to a valid item.
Atomic IDs versus semantic IDs
| Property | Atomic item ID | Semantic ID |
|---|---|---|
| Tokens per item | 1 | \(M\) |
| Meaning of token | arbitrary identity | learned code or cluster |
| Similar items share parameters | indirectly | explicitly through codes |
| Collision-free | yes by construction | requires handling |
| New-item support | requires a new embedding | can encode item features, subject to model design |
| Generative retrieval | one huge vocabulary | smaller vocabulary over multiple decoding steps |
Interview questions
- How are semantic IDs different from hashing item IDs?
- Why use multiple residual codebooks rather than one enormous codebook?
- Do shared semantic-ID prefixes guarantee similar user preference?
- How would you prevent the decoder from generating nonexistent items?
- How do collisions affect training targets and retrieval?
- When should the item encoder use content, collaborative signals, or both?
- How do codebook size and depth affect capacity and decoding latency?
One Framework for All Modalities
Many learned tokenizers can be summarized as
\[ x \xrightarrow{E} z_{1:T} \xrightarrow{Q} c_{1:T} \xrightarrow{D} \widehat x, \]
where:
- \(E\) segments and encodes the input,
- \(Q\) optionally quantizes continuous latents into discrete IDs,
- a sequence model processes or predicts the tokens,
- \(D\) is needed when reconstructing the original modality.
| Goal | Tokenizer should preserve |
|---|---|
| Classification/retrieval | task-relevant semantics |
| Autoregressive generation | enough detail for faithful reconstruction |
| Streaming | causal, low-latency state |
| Multimodal modeling | manageable token rate and alignment across modalities |
| Recommendation | item identity, useful similarity, and valid catalog structure |
General Interview Questions
- What makes a good tokenization?
- When must tokens be discrete, and when can they remain continuous?
- How does token rate affect Transformer compute and memory?
- What is the tradeoff between semantic abstraction and reconstruction fidelity?
- Why is token ordering obvious for text but a design choice for images and video?
- How would you combine several modality vocabularies in one autoregressive model?
- Which tokenizer components are trained jointly with the downstream model?