CS336: Language Modeling from Scratch Lecture 1 — Overview & Tokenization

Stanford University
Rebuilt 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

Challenge: how do we study frontier language modeling when we cannot run frontier-scale training jobs?

What Transfers Across Scales?

KnowledgeWhat It CoversTransfers 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

The Bitter Lesson & The Efficiency Lens

$$\text{accuracy} = \text{efficiency} \times \text{resources}$$

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)

Embracing Scale (Historical Baselines)

Historical MilestoneYearScaleKey Lesson
GPT-220191.5BFluent generation; first signs of zero-shot task transfer
Kaplan Scaling Laws2020—Smooth power-law predictability of loss with compute, data, parameters
GPT-32020175BIn-context learning via prompting without gradient updates
PaLM2022540BMassive parameter scale, but substantially undertrained for its compute
Chinchilla202270BCompute-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

Open research and technical reports make studying frontier LM design possible.

Current Frontier Open-Weight Models (Late 2026)

ModelReleasedKey Architectural & Training Highlights
DeepSeek-V4.1-FlashSept 2026552B 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.1July 20262.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.3202678 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-NextAug 2026125B / 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-M3June 2026Blockwise 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.6Oct 2026Late-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

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

Pillar 1 — Architecture: Original Transformer to 2026

ComponentOriginal Transformer (2017)Current Refinements (Late 2026)
ActivationReLUSwiGLU
PositionSinusoidalRoPE
NormalizationPost-norm LayerNormPre-norm RMSNorm, QK-Norm
AttentionFull multi-headGQA, MLA, sparse / local attention (CSA2, DSA, QSA, MiniMax)
Hybrid sequence layersNoneMamba-2, Gated DeltaNet, Kimi Delta Attention interleaved with attention
MLPDense FFNFine-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

Pillar 2 — Parallelism Across Many GPUs

DimensionWhat Is SplitPrimary Goal
DataBatch examples (and sharded optimizer/weights)Scale throughput & cut per-GPU state
TensorMatrix rows/columns within a layerFit wide layers across fast intra-node links
PipelineGroups of layers across stagesScale depth with point-to-point activation sends
SequenceToken positions along context lengthSupport long contexts (e.g., 1M tokens)
ExpertMoE experts across devicesScale 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

Pillar 3 — Scaling Laws & Predictability

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

What we want the model to do (multilingual, conversation, agentic coding) dictates both evaluation and data.

Pillar 4 — Data Curation, Processing & Stages

Raw SourcesHTML, PDF, code TransformExtract text FilterQuality & safety DeduplicateBloom / MinHash MixRegMix / OlMix RewriteSynthetic

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

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 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).

Practical Quirks of Subword Tokenizers

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))
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")

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

Comparing Tokenization Paradigms

MethodVocab Size $|V|$CompressionUnseen Text?Main Failure Mode
Character~150KLow (~1–1.5)Yes (Unicode)Huge sparse vocab + short chunks
Byte (UTF-8)2561.0AlwaysSequences too long for $O(L^2)$ attention
WordUnboundedHighNeeds <UNK>Huge vocab, rare words, broken perplexity
Byte-level BPEChosen ($|V|$)High (~4)AlwaysSeparate heuristic step (non-learned)

Byte-Pair Encoding (BPE): Core Idea

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")

From Toy BPE to Production Tokenizers

  1. 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
  2. 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)
  3. Special tokens
    • Detect and preserve control tokens (e.g., <|endoftext|>) intact before splitting or merging
  4. 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?

Tokenization is really a static, rule-based form of adaptive computation.

Lecture 1 Recap