CS336: Language Modeling from Scratch
Lecture 1 — Overview & Tokenization
Stanford UniversityRebuilt for Late 2026
Why Build Language Models from Scratch?
Today: Prompt API Models
GPT / Claude / Gemini endpoints
2018: Download & Fine-Tune
BERT, pretrained checkpoints
2016: Train Your Own Model
Full control of data, architecture, loop
CS336: Tear Up the Whole Stack
Researchers are growing disconnected from the underlying technology
Higher abstractions boost productivity, but LM abstractions are leaky
Unlike programming languages or OS kernels, boundaries are not settled
Fundamental research still requires modifying tokenization, architectures, kernels, data, and RL together
Core philosophy: understanding via building
Full-stack literacy is required to diagnose failure modes and push the frontier.
The Industrialization of Frontier Models
Frontier training runs are out of reach for academic budgets:
2023: GPT-4 reportedly cost $100M to train
2025: xAI built a 230K-GPU cluster to train Grok
Closed technical reports withhold architecture, data, and training recipes
Small models ($<1\text{B}$ parameters) do not always mirror frontier behavior:
Compute mix shifts: the fraction of FLOPs spent in attention vs. MLP changes with model width and sequence length
Emergent behaviors: capabilities can remain near zero at small scale before rising sharply at large scale
Challenge: how do we study frontier language modeling when we cannot run frontier-scale training jobs?
What Transfers Across Scales?
Knowledge What It Covers Transfers to Frontier?
Mechanics
How components work: BPE, Transformers, attention, kernels, parallelism, scaling laws, RL
Yes
Mindset
Squeezing the most out of hardware; taking resource accounting and scaling laws seriously
Yes
Intuitions
Which specific data mixes or architectural tweaks maximize accuracy
Partially
Many empirical modeling choices lack clean theoretical justification
Example: Shazeer (2020) introduced SwiGLU based on experimental gains rather than first-principles proof
Focus on transferable mechanics and mindset while treating small-scale intuitions with care
The Bitter Lesson & The Efficiency Lens
Wrong reading of the Bitter Lesson: "only scale matters; algorithms do not"
Right reading: algorithms that scale are what matter
$$\text{accuracy} = \text{efficiency} \times \text{resources}$$
Efficiency matters more at larger scale — waste multiplies with cluster size
Historical precedent: 44× algorithmic efficiency gain on ImageNet between 2012 and 2019
Central framing: what is the best model we can build for a fixed compute and data budget?
Maximizing capability under fixed resources means maximizing efficiency at every layer of the stack.
Efficiency Unifies the Entire Stack
Fixed Resources
Compute · Memory · BW · Data
Tokenization
Architecture
Systems
Scaling Laws
Data Filtering
Today: compute-constrained → Tomorrow: data-constrained
Tokenization: raw bytes are elegant, but compute-inefficient with quadratic attention
Architecture: KV sharing, sparse attention, and MoE cut memory and FLOPs per token
Systems: kernels, parallelism, and inference serving minimize data movement
Scaling laws: tune hyperparameters cheaply on small models
Data filtering: avoid burning FLOPs on low-quality or duplicate tokens
Historical Foundations of Language Modeling
Pre-Neural (<2010s)
Shannon (1950) · N-grams (2007)
Neural Ingredients (1997–2019)
LSTM · Bengio · seq2seq · Adam · Attention
Transformer · MoE · GPipe/ZeRO/Megatron
Early Pretraining (2018–19)
ELMo · BERT · T5 (11B)
Pre-neural: Shannon (1950) measured English entropy; n-gram models powered classic MT and ASR
Neural building blocks: LSTM (1997), neural LMs (2003), seq2seq + Adam (2014), attention (2015), Transformer & MoE (2017), and model parallelism (2018–2019)
Pretrain + fine-tune: ELMo (LSTM), BERT (Transformer), and T5 (11B, unified text-to-text) established transfer learning
Embracing Scale (Historical Baselines)
Historical Milestone Year Scale Key Lesson
GPT-2 2019 1.5B Fluent generation; first signs of zero-shot task transfer
Kaplan Scaling Laws 2020 — Smooth power-law predictability of loss with compute, data, parameters
GPT-3 2020 175B In-context learning via prompting without gradient updates
PaLM 2022 540B Massive parameter scale, but substantially undertrained for its compute
Chinchilla 2022 70B Compute-optimal scaling: train smaller models on far more tokens ($D \approx 20N$)
All models above are historical baselines — modern 2026 frontier models combine sparse MoE, hybrid/sparse attention, and tens of trillions of training tokens.
Openness in Language Modeling
Early open replications (historical): EleutherAI's The Pile & GPT-J, Meta's OPT (175B, plagued by hardware failures), BigScience's BLOOM (176B)
Earlier open-weight waves (2023–2025, historical): Llama 1/2/3 (Llama 3: 15T tokens), Mistral / Mixtral, DeepSeek-V3 (671B/37B active) & R1, Qwen3 (36T tokens), Kimi K1.5 & K2
Current open-weight frontier (late 2026): weights + technical report, approaching closed models (GPT, Claude, Gemini)
Fully open-source models (weights + paper + code + training data):
AI2 Olmo 2 / Olmo 3 , NVIDIA Nemotron 3 , and Marin (open development)
Note: Nemotron 3.5 releases weights and report, not training data, so it is open-weight rather than fully open-source
Open research and technical reports make studying frontier LM design possible.
Current Frontier Open-Weight Models (Late 2026)
Model Released Key Architectural & Training Highlights
DeepSeek-V4.1-Flash Sept 2026 552B backbone (16B decode / 8B prefill active); 384 routed + 1 shared expert; 1M ctx; CSA2 sparse attn + cross-layer KV reuse + FP4 KV (890 B/tok); 3 MTP layers; 45T tokens
Kimi K3 / K3.1 July 2026 2.8T total / 104B active; 896 routed + 2 shared experts (Stable LatentMoE, MXFP4 QAT); 1M ctx; 3 Kimi Delta Attention + 1 gated MLA per block; Attention Residuals, Per-Head Muon
GLM-5.3 2026 78 layers, hidden 6144, 64 heads; MLA (kv_lora_rank 512, RoPE dim 64) + DSA sparse attn (top-$k$ 2048); 256 experts (8 active + 1 shared); 1 MTP layer
Qwen3.8-Flash-Next Aug 2026 125B / 6B active; 3:1 Gated DeltaNet to full attn (replaced by QSA sparse attn in continued pretraining); 512 experts (10 active + 1 shared); 51B n-gram table in host RAM
MiniMax-M3 June 2026 Blockwise top-$k$ MiniMax Sparse Attention on GQA; matches GQA on 109B model while cutting per-token attention compute by 28.4× at 1M context
Xiaomi MiMo-V2.6 Oct 2026 Late-2026 open-weight frontier release (also alongside DeepSeek-V4, Nemotron 3.5, Ling/Ring 2.6)
Shared 2026 pattern: fine-grained sparse MoE + hybrid linear/sparse attention + 1M context + multi-token prediction.
What Is a Language Model? Evolving Specs
2018 (BERT)
Something you
fine-tune
2020 (GPT-3)
Something you
prompt
2022 (ChatGPT)
Something you
talk to
2026 (Agents)
Something that
acts autonomously
Fundamentals remain the same: attention, recurrence, kernels, distributed training, optimization
System specs have shifted sharply:
Much longer contexts (up to 1M tokens for codebases and multi-turn tool trajectories)
Inference efficiency now dominates both serving cost and reinforcement learning rollouts
Roadmap: Five Technical Pillars of Building an LM
1. Basics
Tokenization
Architecture
Training loop
2. Systems
Kernels
Parallelism
Inference
3. Scaling
Scaling recipes
IsoFLOP laws
μP transfer
4. Data
Evaluation
Filter & dedup
Mixing & synth
5. Alignment
Weak sup.
PPO / DPO
GRPO & RL
First, a high-level tour of all five pillars so every detail fits the whole system
Then we dive into our first technical unit: Tokenization (highlighted in yellow)
Pillar 1 — Architecture: Original Transformer to 2026
Component Original Transformer (2017) Current Refinements (Late 2026)
Activation ReLU SwiGLU
Position Sinusoidal RoPE
Normalization Post-norm LayerNorm Pre-norm RMSNorm, QK-Norm
Attention Full multi-head GQA, MLA, sparse / local attention (CSA2, DSA, QSA, MiniMax)
Hybrid sequence layers None Mamba-2, Gated DeltaNet, Kimi Delta Attention interleaved with attention
MLP Dense FFN Fine-grained sparse Mixture of Experts (MoE) + shared experts
Architecture shape (hidden dim, depth, heads, experts) is co-designed with memory and KV-cache budgets.
Pillar 1 — Training & Core Design Tension
Loss: next-token cross-entropy + multi-token prediction (MTP)
Optimizers: AdamW, SOAP, Muon
Init & schedule: Xavier / $\mu$P; cosine or WSD (warmup-stable-decay)
Regularization & batching: weight decay, dropout, critical batch size
MoE stability: auxiliary-loss-free load balancing
Expressivity
Stability
norms in Goldilocks zone
Efficiency
training + inference speed
Every choice
balances all three
Pillar 2 — Systems Overview: Compute vs. Memory
Compute (SMs)
NVIDIA B200: 2.25 PFLOP/s (BF16)
Fast on-chip SRAM & tensor cores
8 TB/s
GPU Memory (HBM)
Weights, activations, KV cache, optimizer
Resource accounting: training cost is roughly $C = 6 N D$
70B params on 1T tokens $\Rightarrow 4.2 \times 10^{23}$ FLOPs
Parameters must move from HBM to SMs before arithmetic happens
Roofline analysis: tells whether an operation is compute-bound or memory-bound
Benchmarking & profiling (Nsight) verifies bottlenecks in practice
Pillar 2 — Kernels: Minimize Data Movement
Naive (2 kernels, 4 HBM trips):
HBM
Compute A
HBM
Compute B
HBM
Fused (1 kernel, 2 HBM trips):
HBM
Compute A + B (on-chip)
HBM
Each primitive PyTorch op launches a separate GPU kernel, causing redundant HBM round-trips
Key strategies: operator fusion (e.g., matmul + activation) and tiling (FlashAttention)
Custom kernels are written in CUDA , Triton , CUTLASS , and CuTe DSL
Pillar 2 — Parallelism Across Many GPUs
Scaling to 1,024+ GPUs hits an even steeper data-movement wall between chips
Same governing principle: minimize inter-GPU communication
Built on collective communication primitives: gather, reduce, all-reduce
Shard memory (parameters, activations, gradients, optimizer states) and split work along five axes:
Dimension What Is Split Primary Goal
Data Batch examples (and sharded optimizer/weights) Scale throughput & cut per-GPU state
Tensor Matrix rows/columns within a layer Fit wide layers across fast intra-node links
Pipeline Groups of layers across stages Scale depth with point-to-point activation sends
Sequence Token positions along context length Support long contexts (e.g., 1M tokens)
Expert MoE experts across devices Scale sparse parameter count cleanly
Pillar 2 — Inference: Prefill vs. Decode
Phase 1: Prefill (Compute-Bound)
All prompt tokens processed in parallel
t1
t2
t3
…
tL
Phase 2: Decode (Memory-Bound)
Generate one token at a time sequentially
y1
y2
y3
Inference powers deployment, evaluation, test-time compute, and RL rollouts
Speeding up memory-bound decoding:
Cheaper models: pruning, quantization, distillation
Speculative decoding: cheap draft model proposes multiple tokens; full model verifies in parallel (exact output distribution)
Serving systems: fused kernels and continuous batching
Pillar 3 — Scaling Laws & Predictability
Target setting: given a $10^{25}$ FLOPs budget, what hyperparameters yield the best model?
Tuning directly at full scale is prohibitively expensive
Key conceptual shift: design a scaling recipe ($\text{FLOPs} \to \text{hyperparameters}$)
Measure loss across smaller compute scales (e.g., up to $10^{24}$ FLOPs)
Fit a scaling law to optimize the recipe and predict loss at the target scale before running it
Scaling laws are not automatic — they require parameterizations with hyperparameter transfer (e.g., $\mu$P)
At frontier scale, predictability is at least as important as optimality.
Pillar 3 — Compute-Optimal Allocation ($N$ vs. $D$)
Model parameters N (log scale)
Training loss
C1
C2
C3
N*(C) fit
Fixed compute $C = 6 N D$: spend FLOPs on a bigger model ($N$) or more tokens ($D$)?
IsoFLOP curves (Kaplan 2020; Chinchilla 2022): find optimal $N^*(C)$ at small $C$ and extrapolate
Chinchilla rule of thumb: $D \approx 20 N$
Example: 70B parameters $\Rightarrow \sim 1.4\text{T}$ tokens
Inference caveat: ignores serving cost — modern models deliberately over-train smaller active sizes (e.g., DeepSeek-V4.1-Flash trains on 45T tokens)
Pillar 4 — Evaluation: Guiding & Measuring Quality
Evaluation serves two distinct purposes:
Internal evaluation: guide model iteration — needs smoothness across scales and reliable relative ordering
External evaluation: measure real-world utility — needs ecological validity and absolute quality
Core evaluation families:
Perplexity on private, non-web documents to prevent benchmark contamination
Frontier capability benchmarks: GPQA, HLE, SWE-Bench, Terminal-Bench
Because LMs are general-purpose, no single metric suffices — evaluation requires a diverse suite
What we want the model to do (multilingual, conversation, agentic coding) dictates both evaluation and data.
Pillar 4 — Data Curation, Processing & Stages
Raw Sources HTML, PDF, code
Transform Extract text
Filter Quality & safety
Deduplicate Bloom / MinHash
Mix RegMix / OlMix
Rewrite Synthetic
Sourcing: web crawls, books, arXiv, GitHub — plus copyright fair-use questions and licensing deals (e.g., Reddit)
Deduplication saves compute and reduces memorization; rewriting / synthetic data (e.g., WRAP) aligns text with downstream tasks
Three curriculum stages:
Pretraining: large and diverse | Mid-training: high-quality & long-context | Post-training: SFT conversations and agentic tool-calling traces
Pillar 5 — Alignment & Post-Training
1. Generate Responses
Sample rollouts from model
2. Score Responses
Human · Verifier · LM judge
3. Update Policy
Prefer higher-scoring outputs
Moves from full supervision (next-token prediction) to weak supervision : it is often easier to critique than generate
Core algorithms: PPO (classic RL), DPO (offline preference pairs), GRPO (removes value function)
Late-2026 pipelines chain SFT, asynchronous RL / RLVR, and on-policy distillation (e.g., DeepSeek-V4.1-Flash, Nemotron 3.5)
Key challenge: RL instability and the systems trade-off between async rollout throughput and on-policyness
Unit 1 — Tokenization: Raw Text to Model Atoms
Unicode String
"Hello, 🌍! 你好!"
encode()
decode()
Token Sequence (ints)
[13225, 11, 130321, …]
Language Model
p(x1 , …, xL )
class Tokenizer(ABC):
def encode(self, string: str) -> list[int]: ...
def decode(self, indices: list[int]) -> str: ...
A tokenizer translates between raw inputs (bytes / Unicode strings) and integer token IDs
Efficiency wins: shrinks sequence length ($1000\text{ bytes} \to \sim 250\text{ tokens}$) and allocates more capacity to complex chunks
A Modern Tokenizer in Action (o200k_base)
tokenizer = tiktoken.get_encoding("o200k_base")
string = "Hello, 🌍! 你好!" # 20 UTF-8 bytes
indices = tokenizer.encode(string)
# [13225, 11, 130321, 235, 0, 220, 177519, 0] # 8 tokens
assert tokenizer.decode(indices) == string
8 token IDs produced by o200k_base (compression ratio = 20 / 8 = 2.5 bytes/token):
13225
11
130321
235
0
220
177519
0
Notice: a single 4-byte emoji (🌍) splits across two byte-level tokens (130321, 235), while "你好" (6 bytes) merges into one token (177519).
encode() and decode() must round-trip losslessly for arbitrary Unicode strings
Practical Quirks of Subword Tokenizers
Leading whitespace attaches to the word:
" world" is typically one token, not " " + "world"
Position changes representation:
In "hello hello", the first "hello" (no space) and second " hello" (with space) map to different token IDs
Numbers split into arbitrary digit chunks:
Digits are grouped every few characters rather than aligned to decimal place value
Multilingual & rare-symbol asymmetry:
Frequent scripts pack many bytes per token; rare symbols fall back to multi-token byte fragments
Many surprising LM quirks (spelling, digit arithmetic, trailing spaces) originate directly in tokenization.
Core Trade-Off: Compression Ratio vs. Vocab Size
Vocabulary size |V| (log scale)
Compression (bytes / token)
Byte (|V|=256, 1.0)
Character (~150K)
Word (unbounded)
BPE sweet spot
$$\text{compression ratio} = \frac{\text{UTF-8 bytes}}{\text{number of tokens}}$$
Higher compression $\Rightarrow$ shorter sequences $L$
Critical because standard attention scales as $O(L^2)$
Larger vocabulary $|V|$ raises compression, but introduces sparsity :
Rare tokens get few gradient updates
Embedding and output-head matrices grow linearly with $|V|$
Approach 1: Character-Based Tokenization
class CharacterTokenizer(Tokenizer):
def encode(self, string: str) -> list[int]:
return list(map(ord, string))
def decode(self, indices: list[int]) -> str:
return "".join(map(chr, indices))
Maps each Unicode character to its code point: ord("a") == 97, ord("🌍") == 127757
Round-trips cleanly, but suffers from two fatal flaws :
Huge vocabulary: $\approx 150\text{K}$ Unicode characters
Severe sparsity & low compression: many rare code points (e.g., 🌍), only $20/13 \approx 1.54$ bytes/token on "Hello, 🌍! 你好!"
Verdict: the worst of both worlds — very large vocabulary and poor compression.
Approach 2: Byte-Based Tokenization
class ByteTokenizer(Tokenizer):
def encode(self, string: str) -> list[int]:
return list(map(int, string.encode("utf-8")))
def decode(self, indices: list[int]) -> str:
return bytes(indices).decode("utf-8")
UTF-8 represents any Unicode string as a stream of bytes in $0 \dots 255$
"a" $\to$ 1 byte (b"a"); "🌍" $\to$ 4 bytes (b"\xf0\x9f\x8c\x8d")
Huge advantage: tiny, fixed vocabulary of 256 — zero out-of-vocabulary tokens
Fatal flaw: compression ratio is always 1.0 byte/token
Sequences become far too long for quadratic attention layers
Byte-level encoding gives us a universal base alphabet, even if raw bytes are too fine-grained alone.
Approach 3: Word-Based Tokenization
string = "I'll say supercalifragilisticexpialidocious!"
chunks = regex.findall(r"\w+|.", string)
# ['I', "'", 'll', ' ', 'say', ' ',
# 'supercalifragilisticexpialidocious', '!'] # 8 tokens, 44 bytes
Advantages: semantically meaningful units and strong compression ($44/8 = 5.5$ bytes/token above)
Fatal flaws:
Unbounded vocabulary: every distinct word in the corpus needs an ID
Rare-word sparsity: tail words appear too rarely to learn good embeddings
<UNK> tokens: unseen test words collapse to unknown, breaking lossless round-tripping and distorting perplexity comparisons
Comparing Tokenization Paradigms
Method Vocab Size $|V|$ Compression Unseen Text? Main Failure Mode
Character ~150K Low (~1–1.5) Yes (Unicode) Huge sparse vocab + short chunks
Byte (UTF-8) 256 1.0 Always Sequences too long for $O(L^2)$ attention
Word Unbounded High Needs <UNK> Huge vocab, rare words, broken perplexity
Byte-level BPE Chosen ($|V|$) High (~4) Always Separate heuristic step (non-learned)
We want the universal coverage of bytes, the compression of words, and a fixed, controllable $|V|$
Solution: train a subword vocabulary directly from data using Byte-Pair Encoding
Byte-Pair Encoding (BPE): Core Idea
Origins: introduced by Gage (1994) for data compression; adapted to NMT by Sennrich et al. (2016); made byte-level in GPT-2 (2019)
Data-driven vocabulary: train the tokenizer on raw corpus text instead of hand-crafting word rules
Frequent byte sequences merge into single tokens
Rare sequences stay decomposed into shorter subwords or raw bytes (never <UNK>)
Greedy training procedure:
Initialize vocabulary with all 256 single-byte tokens ($0 \dots 255$)
Count every adjacent pair of tokens in the corpus
Merge the most frequent pair into a new token ID ($256 + i$) and repeat
BPE Training Implementation
@dataclass(frozen=True)
class BPETokenizerParams:
vocab: dict[int, bytes] # index -> bytes
merges: dict[tuple[int, int], int] # (id1, id2) -> new_id
def train_bpe(string: str, num_merges: int) -> BPETokenizerParams:
indices = list(map(int, string.encode("utf-8")))
merges: dict[tuple[int, int], int] = {}
vocab: dict[int, bytes] = {x: bytes([x]) for x in range(256)}
for i in range(num_merges):
counts = count_adjacent_pairs(indices)
pair = max(counts, key=counts.get)
new_index = 256 + i
merges[pair] = new_index
vocab[new_index] = vocab[pair[0]] + vocab[pair[1]]
indices = merge(indices, pair, new_index)
return BPETokenizerParams(vocab=vocab, merges=merges)
The helper merge(indices, pair, new_index) scans left-to-right and replaces every occurrence of pair with new_index.
BPE Training: Worked Trace
Input: "the cat in the hat" (18 UTF-8 bytes), num_merges = 3
Init (18 tokens, ratio 1.00):
t
h
e
␣
c
a
t
␣
i
n
␣
t
h
e
␣
h
a
t
Merge 1: (116, 104) "t"+"h" → 256 ("th"), count = 2 → 16 tokens
th
e
␣
c
a
t
␣
i
n
␣
th
e
␣
h
a
t
Merge 2: (256, 101) "th"+"e" → 257 ("the"), count = 2 → 14 tokens
the
␣
c
a
t
␣
i
n
␣
the
␣
h
a
t
Merge 3: (257, 32) "the"+"␣" → 258 ("the␣"), count = 2 → 12 tokens (ratio 1.50)
the␣
c
a
t
␣
i
n
␣
the␣
h
a
t
Each merge creates one higher-level token out of previously created tokens, growing hierarchically from bytes.
BPE Encoding and Decoding
class BPETokenizer(Tokenizer):
def __init__(self, params: BPETokenizerParams):
self.params = params
def encode(self, string: str) -> list[int]:
indices = list(map(int, string.encode("utf-8")))
for pair, new_index in self.params.merges.items():
indices = merge(indices, pair, new_index)
return indices
def decode(self, indices: list[int]) -> str:
bytes_list = list(map(self.params.vocab.get, indices))
return b"".join(bytes_list).decode("utf-8")
Example using our 3 learned merges on "the quick brown fox" (19 bytes):
encode applies (t,h)→256, (256,e)→257, (257,␣)→258 $\Rightarrow$ [258, 113, 117, 105, …] (16 tokens)
Unseen words ("quick", "brown", "fox") decompose gracefully into raw bytes — lossless round-trip!
From Toy BPE to Production Tokenizers
Avoid scanning all merges during encode()
The naive loop checks every merge in $|V|$ even when absent; instead, merge only pairs present in the text in merge-rank order
Pre-tokenization (e.g., GPT-2 regex)
Split text into coarse chunks before running BPE so merges do not cross word/punctuation boundaries (e.g., preventing "dog." and "dog!" duplicates)
Special tokens
Detect and preserve control tokens (e.g., <|endoftext|>) intact before splitting or merging
Fast training
Maintain pair-count indices incrementally around merged sites rather than recounting the entire corpus at every step
Looking Ahead: Can We Eliminate Tokenization?
BPE is an effective, data-driven heuristic — yet it remains a separate, non-learned preprocessing stage
The dream: end-to-end tokenizer-free models operating directly on raw bytes
Research lineage: ByT5 , MegaByte , BLT , T-FREE , H-Net
Promising ideas, but not yet scaled to replace subword tokenizers at the frontier
Whatever future solution replaces BPE must satisfy two core properties:
The model operates on higher-level chunks (abstractions) across modalities (text, video, DNA)
Chunks are variable-length , allocating more compute to harder, information-dense regions
Tokenization is really a static, rule-based form of adaptive computation.
Lecture 1 Recap
Why from scratch: LM abstractions are leaky; mechanics and an efficiency mindset transfer across scales ($\text{accuracy} = \text{efficiency} \times \text{resources}$)
Late-2026 landscape: open-weight frontier models (DeepSeek-V4.1-Flash, Kimi K3, GLM-5.3, Qwen3.8-Flash-Next, MiniMax-M3, MiMo-V2.6) converge on sparse MoE, hybrid linear/sparse attention, and 1M context
Five pillars: Basics (tokenization, architecture, training), Systems (kernels, parallelism, inference), Scaling Laws, Data & Evaluation, and Alignment
Tokenization: byte, character, and word schemes fail on sequence length, sparsity, or <UNK>; byte-level BPE learns a fixed, lossless vocabulary balancing compression and $|V|$
Next up: resource accounting (FLOPs, memory, and bandwidth in detail)