Macalinao StudioLearnAll lessons ↗

TAKE THE LONGER ROUTE

Open the complete college extension →

Worked explanations, full local narration, and connected Signal Room, Workbench and Field Notes.

SIGNAL ROOM

TokensUnderstand the moving parts.

BPE, byte-level BPE, sentencepiece. The cost trade-offs that show up at scale.

Suggested preparation: None

WORKBENCH / CHANGE ONE THING

Merge a tiny vocabulary

Count adjacent symbol pairs, then apply one learned merge at a time.

Computed teaching example · fixed assumptions shown below

LISTEN & FOLLOW / GUIDED RECAP

Audio starts only when you choose.

FIELD NOTES / THE COMPLETE READING

Take the longer way.

The full lesson narrative, equations and code. Switch views without losing your place.

A slower starting point

Split a word into letters, merge a repeated pair, then count the pieces again.

Where this deserves more time

BPE training versus encoding; Unicode bytes; normalization; measure tokens across languages.

Open the complete high-school reading

Moment 01 / 10

Introduction to Tokenization

Tokenization is the compiler front end of language modeling: it maps Unicode text to a finite sequence of vocabulary indices. The choice of tokenization fixes the model's alphabet, its compression rate, and much of its exposure to morphology, spelling noise, and rare words.

Formally, a tokenizer is a deterministic encoder from strings to integer token ids, paired with a decoder that is usually lossless at the byte level. Tokens may be words, subwords, or bytes; the unit is an inductive bias, trading vocabulary size against sequence length and fertility.

Byte Pair Encoding, adapted for neural machine translation by Sennrich and colleagues in twenty sixteen, greedily merges the most frequent adjacent pair until the vocabulary budget is met. Byte level BPE, used by GPT two, starts from two hundred fifty six bytes, so every string is representable. SentencePiece, from Kudo and Richardson, trains BPE or unigram models directly on raw text without pretokenization.

After encoding, ids index rows of an embedding matrix, then enter the residual stream. A bad tokenizer inflates sequence length, fragments rare tokens, wastes context window, and can leak evaluation artifacts through inconsistent normalization or special token handling.

The takeaway: tokenization is not preprocessing hygiene; it is part of the model class. It determines effective context, compute per byte, robustness, and what the cross entropy objective is actually predicting. Before scaling parameters, inspect the vocabulary, merges, normalization, and token fertility.

Equations, code and original cards

Tokenization: From Bytes to Model Inputs

• Definition: deterministic encoder from raw text to token ids over a fixed vocabulary

• Importance: sets compression, sequence length, robustness, and effective context

• Methods:

 – BPE: greedily merge frequent adjacent pairs until vocabulary budget

 – Byte-level BPE: 256-byte base alphabet; lossless coverage of arbitrary text

 – SentencePiece: BPE or unigram trained on raw text, no pretokenization

• Role: token ids select embedding rows and define what the model predicts

Moment 02 / 10

Byte-Pair Encoding (BPE) Fundamentals

Byte-Pair Encoding is the subword tokenization behind GPT-class models, adapted by Sennrich and colleagues from Gage's 1994 compression algorithm.

The procedure is greedy and deterministic: start from a byte alphabet, repeatedly merge the most frequent adjacent pair, and stop when the target vocabulary size is reached.

The merge rule assigns the new symbol the joint count of the pair, then recomputes every affected co-occurrence count, so each step is a localized update to the pair-frequency table.

The pseudocode performs one merge: take the argmax pair, concatenate the symbols, transfer the pair count to the new token, and rebuild the frequency index over the corpus.

BPE shortens sequences by collapsing frequent pairs into single tokens, directly reducing attention cost, while guaranteeing any word stays representable as a composition of subwords.

The takeaways: iterative greedy merges, frequencies as joint counts, and a fixed ordered merge table that makes encoding deterministic, the design behind production tokenizers like GPT-2's.

Clarification: BPE merge counts must be recomputed on the updated corpus.

Equations, code and original cards

Byte-Pair Encoding (BPE) Fundamentals

• BPE Mechanics: Greedy, deterministic merges of the most frequent adjacent pair (Sennrich et al. 2016; Gage 1994)
• Merge Update: New symbol inherits the pair's joint count, then co-occurrences are recomputed:
\( f(ab) \leftarrow f(a,b) \), one merge per vocabulary step
• Sequence Impact: Longer tokens shorten sequences, cutting the \(O(n^2 d)\) attention cost while preserving open-vocabulary coverage

(a,b)=\arg\max_{(u,v)}\operatorname{count}(u,v);\quad (a,b)\mapsto ab\ ;\ \text{recount adjacent pairs}
# One greedy BPE merge

pair = argmax(freqs)

subword = a + b

freqs[subword] = freqs[pair]

recompute_pairs(corpus)

Moment 03 / 10

Tokenization Pipeline Visualization

We begin at the head of the tokenization pipeline with raw text input. The system receives an arbitrary Unicode string, which must be converted into discrete tokens before any model can consume it.

First, byte encoding maps the string to its UTF-8 byte sequence. Working at the byte level gives a fixed alphabet of 256 symbols, so arbitrary Unicode is handled without out-of-vocabulary failures.

The byte sequence then passes through byte pair encoding, or BPE, which greedily applies learned merge rules to collapse frequent byte pairs into subword tokens, trading vocabulary size against sequence length.

We then measure compression: bytes per token, the ratio of raw byte length to token count. Higher values mean a more efficient encoding and fewer tokens per document.

Finally, each token id indexes a row of the embedding matrix, yielding a dense vector in the model's hidden dimension. These embeddings are the actual input to the transformer stack.

Enter your own text and watch each stage update in real time: byte encoding, BPE merges, compression ratio, and the final embedding lookup, end to end.

Equations, code and original cards

Moment 04 / 10

Byte-Level BPE and SentencePiece

Byte-level BPE starts with a byte alphabet and learns pair merges. SentencePiece is a tokenizer framework offering BPE and unigram models; it is not synonymous with the unigram algorithm.

Unigram segmentation uses a probabilistic model. SentencePiece can train directly on raw sentences, represents whitespace explicitly, and may normalize text; exact round trips depend on normalization and byte-fallback settings.

Equations, code and original cards

Byte-Level BPE and SentencePiece: Subword Induction

• Byte alphabet: 256 symbols, full Unicode coverage

• Greedy merge of highest-count adjacent pairs

• No normalization or word boundaries required

• No OOV; risk: fragmented rare-script tokens

• Raw-text input; unigram subword language model

• EM: estimate probabilities, resegment, prune pieces

• Sampling enables subword regularization

• Better calibrated granularity; higher training cost

Objectives: Merge Counts versus Unigram Likelihood

\text{Byte-level BPE: }\mathcal{V} = \{b_i\} \quad b_i \in \{0,...,255\}
\text{SentencePiece EM objective: }\mathcal{L}(\theta) = \sum_{i=1}^N \log \sum_{z \in \mathcal{Z}(x_i)} p(z|\theta)

Scaling Trade-offs: Fertility, Coverage, Entropy

• BPE: fast, deterministic, robust; less interpretable merges

• SentencePiece: probabilistic, smoother, sampling; costlier EM

• Ablate vocab size, fertility, bits per byte, final loss

• Hybrids: byte fallback plus unigram or BPE cores

Moment 05 / 10

Mathematical Formulations in Tokenization

Let's begin with the mathematical formulations underlying tokenization. Our focus is the linear algebra and calculus that connect discrete token indices to the continuous residual stream of a transformer.

First, embedding lookup as matrix multiplication. Token indices select rows of the embedding matrix by multiplying a one-hot indicator matrix against it, mapping discrete symbols into a dense d-dimensional vector space without materializing the product.

Formally, e equals X times E, where X is the one-hot indicator matrix and E is the embedding matrix of shape vocabulary size by model dimension. In practice this is an indexed row gather, not a true matrix multiply.

Next, the gradient derivation for updating embeddings during training. We compute the gradient of the loss with respect to the embedding matrix so that backpropagation can adjust the rows that were actually selected.

That gradient, the nabla of L with respect to E, equals X transpose times the upstream gradient on the embeddings. Because X is one-hot, only the rows corresponding to observed tokens receive nonzero updates, which makes the update sparse.

Finally, the loss functions over tokenized inputs: cross-entropy between the softmax over logits and the true next-token distribution, equivalently the negative log likelihood of the correct token under teacher forcing.

In summary: embedding lookup as row selection, the sparse gradient that updates only observed rows, and the cross-entropy objective that shapes the embedding geometry. These three pieces anchor the token pipeline in modern language models.

Equations, code and original cards

Mathematical Formulations in Tokenization

Key Concepts Overview

• Embedding lookup as matrix multiplication:

X = One-hot(token indices), E ∈ R^{|V|×d}

Token embedding: \(\mathbf{e} = \mathbf{X} \mathbf{E} \) (row gather)

\mathbf{e} = \mathbf{X} \times \mathbf{E}

• Gradient derivation for embedding updates:

Sparse row-wise update via chain rule:

\(\nabla_{\mathbf{E}} L = \mathbf{X}^\top \nabla_{\mathbf{e}} L\)

\nabla_{\mathbf{E}} L = \mathbf{X}^\top \nabla_{\mathbf{e}} L

• Loss functions over tokenized inputs:

- Cross-entropy over softmax logits

- NLL: \(-\sum_t \log p(x_t \mid x_{

import torch.nn.functional as F



# Embedding lookup (row gather)

embeddings = embedding_matrix[token_indices]  # PyTorch indexing



# Cross-entropy over next-token logits

loss = F.cross_entropy(logits, labels)

Moment 06 / 10

Implementation Details: Python & PyTorch

We now move from tokenization theory to the PyTorch path: byte pair encoding, SentencePiece, and the embedding lookup that starts the residual stream. The implementation details are not clerical; they determine vocabulary entropy, sequence length, and the geometry the transformer first sees.

Byte pair encoding, from Sennrich and colleagues, and SentencePiece, from Kudo and Richardson, turn raw text into subwords. The point is not mystical semantics; it is an open vocabulary with bounded sequence length, so rare words fragment instead of becoming unknown tokens.

The byte level tokenizer first maps text to bytes, then learns merges, so any Unicode string is representable. Training chooses frequent adjacent pairs under a vocabulary budget; encoding applies those merges greedily and emits ids for a fixed matrix.

SentencePiece treats the input as a raw character stream, including whitespace as a symbol, which makes it language independent. Its unigram or byte pair objectives optimize segmentation for likelihood, not for human readable morphemes.

In PyTorch, the embedding layer is a lookup table of shape vocabulary size by model width. Integer ids select rows; there is no distance metric in index space. Those rows become the token contribution to the residual stream before position information is added.

The module allocates a trainable matrix, initialized from a standard normal unless you load pretrained vectors. A long tensor of indices returns a batch by sequence by width tensor; nonzero gradients touch only the rows that were looked up.

The pipeline is therefore deliberate: normalize bytes, learn a subword vocabulary, map ids to trainable vectors, then add position. Ablate any stage and you change token fertility, optimization, and ultimately cross entropy per byte.

Equations, code and original cards

Implementation Details: Python & PyTorch

Subwords, Lookup Tables, Residual Stream

• Byte-level BPE and SentencePiece subwords

- Open vocabulary: rare words fragment, no unknown token

- Tradeoff: lower OOV versus longer token sequences

from tokenizers import ByteLevelBPETokenizerimport sentencepiece as spm# byte-level BPE: Unicode-safe, no unknown tokenbpe_tokenizer = ByteLevelBPETokenizer()# SentencePiece: raw-stream, language-independent subwordssp = spm.SentencePieceProcessor()sp.Load("spm.model")
# raw-stream segmentation; whitespace is explicittokens = sp.EncodeAsPieces("Deep learning models")print(tokens)  # ['▁Deep', '▁learning', '▁models']

Embedding Layer: Lookup, Not Similarity

• Table shape: vocab_size × d_model; ids select rows

• nn.Embedding(num_embeddings, embedding_dim)

import torchimport torch.nn as nnembedding = nn.Embedding(num_embeddings=50257, embedding_dim=768)input_tokens = torch.LongTensor([[15496, 11, 314, 1438]])embedded_vectors = embedding(input_tokens)print(embedded_vectors.shape)  # torch.Size([1, 4, 768])

Moment 07 / 10

Scaling Laws and Cost Trade-Offs

Tokenization sits upstream of every scaling decision. Vocabulary size and sequence length jointly determine FLOPs, memory, and the effective token budget, so getting this trade-off right is a prerequisite for compute-optimal training.

The trade-off is direct: enlarging the vocabulary inflates the embedding table and the output softmax, while a smaller vocabulary expands sequence length, and self-attention cost grows quadratically in that length.

The dominant term is sequence length times vocabulary size times the model width: the output projection scores every position against the full vocabulary.

For memory, the embedding matrix alone holds vocabulary-size times model-width parameters, and the logits tensor scales with batch times sequence length times vocabulary size.

This PyTorch function instantiates that estimate: pass vocabulary size, sequence length, and model width, and it returns the leading-order cost, letting you compare tokenizer configurations before committing to a training run.

The takeaway: tokenization is a compute allocation decision, not a preprocessing afterthought. Tokenizer choice requires measuring compression, coverage, downstream quality and compute together.

Equations, code and original cards

Scaling Laws and the Tokenization Cost Trade-Off

• Vocabulary V vs. sequence length n: compression trades against softmax and embedding cost

• Attention O(n²d); output projection O(n·V·d); embedding memory V·d parameters

• Compute-optimal tokenization: maximize bytes per token at fixed vocabulary budget (Kaplan 2020; Hoffmann 2022)

\text{Compute cost} = \mathcal{O}\big( L \times V \big)
L \times \text{token_size} = \text{constant (fixed FLOPs)}
import torch

def output_projection_cost(vocab_size, seq_len, d_model):

  return seq_len * vocab_size * d_model



# Leading-order softmax cost; attention adds seq_len**2 * d_model

cost = output_projection_cost(vocab_size=32000, seq_len=512, d_model=1024)

print(f"Cost: {cost:e}")

Moment 08 / 10

Advanced Optimizations and Techniques

We turn now to advanced tokenization: dynamic vocabularies, embedding-aligned segmentation, and co-design with modern transformer blocks. These methods attack the fixed-vocabulary assumption baked into BPE since Sennrich et al. 2016.

Three optimization axes. First, dynamic tokenization with adaptive vocabularies. Second, aligning segmentation boundaries with the model's contextual embeddings. Third, integrating tokenizer choices with architectural updates such as rotary positional encoding and grouped-query attention.

Dynamic tokenization conditions the segmentation on the input distribution rather than a frozen merge table. Adaptive vocabularies update merge priorities during training, tracking the shifting statistics of the residual stream's usage patterns.

Formally, the token assignment becomes a function of the current input distribution, not a static lookup. The segmentation that minimizes expected description length under the training corpus need not minimize it under the deployment distribution, and dynamic schemes close that gap.

The context alignment loss penalizes segmentations whose token boundaries cut across semantically coherent spans in the embedding space. The objective couples the tokenizer to the encoder's representations, so tokens carve the text where the model itself finds meaningful distinctions.

Architectural integration means revising attention and normalization blocks to exploit variable-length, context-dependent tokens. The naive intuition that tokenization is a frozen preprocessing step is wrong; it is a learnable, differentiable design choice with measurable effects on downstream cross-entropy.

The takeaway: tokenization is moving from a fixed preprocessing artifact to a learned, context-aware component of the model. Expect vocabularies that adapt, boundaries that align with semantics, and architectures co-designed with their tokenizers.

Equations, code and original cards

Advanced Optimizations and Techniques

State-of-the-Art Optimizations in Tokenization (2024-2026)

Key Optimization Areas

• Dynamic Tokenization and Adaptive Vocabularies

• Alignment with Contextual Embeddings

• Integration with Emerging Transformer Architectures

\text{Dynamic Tokenization: } \quad T_t = f(\mathbf{x}_t, V_t) \quad \text{where } V_t \text{ adapts to context}
\text{Context Alignment Loss: } \mathcal{L}_{align} = \| \mathbf{E}_{token} - \mathbf{E}_{context} \|^2
\text{Transformer Update: } \mathbf{H}^{(l)} = \text{TransformerBlock}(\mathbf{H}^{(l-1)}, \theta_t) \quad \theta_t \text{ tuned by tokenizer}

Moment 09 / 10

Open Research Questions & Future Directions

Let's examine the open research questions in tokenization. This layer sits beneath everything else in the pipeline, and its weaknesses propagate directly into model quality, so it remains an active area despite decades of work.

First, the limitations of current methods. BPE and SentencePiece are fixed after training: they cannot adapt to domain shift, they fragment rare and morphologically rich languages into long token sequences, and the same string can tokenize inconsistently depending on surrounding whitespace and context.

Next, neural tokenizer approaches. Learned, end-to-end tokenizers can optimize segmentation jointly with the downstream loss, adapt vocabulary to the data distribution, and handle rare words gracefully. The catch is that a discrete segmentation inside the network blocks gradient flow, so training requires Gumbel-softmax relaxations or reinforcement-style estimators.

Open problems remain in scaling and cross-lingual coverage. Joint tokenizer-model training is expensive at frontier scale, byte-level and token-free models raise sequence length and thus attention cost, and a single multilingual vocabulary still over-fragments low-resource scripts, inflating both compute and effective context.

In summary, fixing tokenization's inductive biases and scaling learned segmenters are the key directions. Progress here compounds: better tokenization improves sample efficiency, robustness, and fairness across languages in every downstream model.

Equations, code and original cards

Open Research Questions & Future Directions

• Limitations of current tokenization methods:

- Fixed vocabularies: no adaptation to domain shift

- Over-fragmentation of rare and compound words

• Potential of neural tokenizer approaches:

- End-to-end segmentation via Gumbel-softmax relaxation

- Context-aware splitting for semantic coherence

• Open problems in scaling and cross-lingual tokenization:

- Token-free models raise sequence length, attention cost

- Unified vocabularies penalize low-resource scripts

Moment 10 / 10

Tokenization Quiz: Conceptual and Computational

Time to test your grasp of the tokenization pipeline: byte-pair encoding merges, vocabulary size trade-offs, and compression behavior. Work through each question on your own before checking anything.

When you finish, we will walk through the results together and pin down exactly where your intuition about token boundaries and merge order broke down.

Equations, code and original cards

MAKE IT YOURS

Explain the change.

References, scope & corrections

Research snapshots in the source material are not a claim of current state of the art. The reference review corrects identified errors; it is not exhaustive certification of every historical statement. Source code snippets are examples, not a tested production training system.

3 correction entries · expansion notes

Reset this lesson?

This removes only this lesson’s saved notes, experiments and progress.