Stanford CS336 Explained: The Five Pillars and Efficiency Laws of Building an LLM from Scratch

Building language models from scratch, with the efficiency equation threading through five pillars: mechanisms, systems, scaling, data, and alignment.
Using Stanford's CS336 course as its thread, the article argues that building language models from scratch still matters in the API era: deep learning's abstraction is 'deeply leaky,' and only breaking open the stack yields complete understanding. Percy Liang divides knowledge into mechanisms, mindset, and empirical intuition—the first two transfer across scale, the third may break. The core is the efficiency equation 'accuracy = efficiency × resources,' where a 5% efficiency gain saves millions in a frontier run. Five pillars map to five assignments: the modern Transformer is no longer the 2017 original; systems hit the memory wall, demanding operator fusion, FlashAttention, and five types of parallelism; scaling laws turn power laws into an active recipe; data needs five-step refinement; alignment relies on a weak-supervision feedback loop. Finally, tokenizers reveal how spelling, arithmetic, the multilingual tax, and glitch tokens stem from tokenization resolution.
Why Build a Language Model from Scratch in 2026
Over the past decade, AI research has climbed the ladder of abstraction at a remarkable pace. According to the opening review in Stanford's CS336 course, around 2016 researchers were still hand-writing training loops and training neural networks from the ground up; by 2018, downloading BERT checkpoints and fine-tuning them had become standard practice; and today, most workflows simply call frontier APIs, with coding agents even able to generate a language model zero-shot. Abstraction boosts productivity, but the abstraction of language models is "deeply leaky"—when a model fails on a simple instruction, you have no recourse inside the sealed text box. Treating the model as a sealed oracle leaves the research design space with nothing but prompt wording.
This is precisely why CS336 exists: to break open the entire stack and gain complete understanding by building from scratch. The course confronts a sharp contradiction—frontier training has evolved from academic codebases into massive capital projects. Citing the course, GPT-4 reportedly has around 1.8 trillion parameters and training costs of $100 million; by 2026, frontier budgets approach the $1 billion mark, with supercomputing clusters like xAI's 200,000 H100s. On the other side, OpenAI's GPT-4 technical report explicitly declines to disclose architecture, model size, hardware, training compute, and training data. University clusters can only train models under 1 billion parameters, and small models are not miniature versions of frontier models.
Three Layers of Knowledge: What Transfers Across Scale
Percy Liang divides deep learning knowledge into three layers. The first is mechanisms: precise Transformer tensor math, custom GPU kernels, distributed model parallelism. The second is mindset: dissecting every bottleneck, squeezing maximum throughput from silicon, taking scaling laws seriously. These two layers are 100% transferable to any frontier cluster on Earth. Only the third layer—empirical intuition about which architectural changes or data mixes improve accuracy—may break across scale and requires full-size experimental validation.
The course uses two cases to illustrate the value of "mindset." Stephen Roller's analysis shows that at small scale, feed-forward MLP layers account for about 44% of compute, with attention taking the lion's share; scaled up to 175 billion parameters, dense MLP matrices devour 80% of flops, and attention speedups at small scale may fail at frontier scale. Noam Shazeer's paper introducing SwigLU is known for its candor: after testing a batch of variants, he wrote, "We do not provide an explanation, attributing their success to divine grace." Many highly regarded modeling intuitions cannot be derived from first principles—they come purely from trial and error.
The Efficiency Equation: Accuracy = Efficiency × Resources
Rich Sutton's "The Bitter Lesson" is often misread as "scale is everything, algorithms don't matter." Percy emphasizes that this completely inverts history: what Sutton actually showed is that scalable algorithms matter—fragile hand-crafted tricks hit ceilings early, while general algorithms that convert compute into capability win exponentially. Written as an equation: Accuracy = Efficiency × Resources. Losing half your efficiency on a weekend campus run just means waiting twice as long; in a $100 million frontier run, a 5% efficiency gain saves $5 million in cash. According to OpenAI's Hernandez and Brown's 2020 research, algorithmic efficiency on ImageNet improved 44x between 2012 and 2019, outpacing Moore's Law—this defines CS336's core pursuit: maximum efficiency.
Five Pillars Corresponding to Five From-Scratch Assignments
The course provides no starter scaffolding whatsoever. A well-known assessment holds that Assignment 1 alone rivals the sum of all five CS224N assignments. Strict unit tests and adapter interfaces let you verify each piece locally, then compete on a GPU cluster: a 90-minute H100 leaderboard minimizing perplexity, with coding assistants prompted as Socratic tutors rather than crutches. The five interwoven pillars—foundations, systems, scaling laws, data, and alignment—correspond to five from-scratch assignments. Imagine someone hands you a raw Common Crawl dump and 32 H100s with two weeks to train the strongest model possible. Within two weeks, "foundations" gets a complete pipeline running, but reaching the frontier requires squeezing silicon in "systems," predicting optimal budgets with "scaling laws," filtering noisy web text, and aligning a raw predictor into a reasoning assistant.
Foundations: The Modern Transformer Is No Longer the 2017 Original
After a BPE tokenizer compresses raw UTF-8 bytes into integer tokens, they enter the Transformer. Today almost no production LLM uses the 2017 design unchanged: normalization moved off the main residual path into pre-norm RMS norm, dropping the mean subtraction to save memory traffic; ReLU layers gave way to gated SwigLU networks; sinusoidal positional encodings became RoPE rotary embeddings. Two bottlenecks emerge as context and models grow: full attention grows quadratically with sequence length, and modern models use sliding windows, grouped-query attention sharing KV heads, and DeepSeekAd's multi-head latent attention compressing caches into low-dimensional vectors, plus linear hybrid approaches like Mamba and gated DeltaNet; inside the MLP, mixture-of-experts routes each token to a few active experts, expanding capacity without multiplying flops.
Defining the network is only half the battle—if training explodes, it's all meaningless. Cross-entropy predicts the next token, and multi-token prediction often sharpens representations; for optimizers, AdamW remains classic, but frontier open models like Kimi-K2 increasingly adopt Muon, orthogonalizing the entire weight update matrix. All choices serve one subtle goal: keeping parameter and gradient norms in the "Goldilocks zone" that balances expressiveness, stability, and hardware speed.
Systems: The Memory Wall and Five Types of Parallelism
Systems begins with strict resource accounting: training a dense Transformer with n parameters on d tokens requires roughly 6nd flops—2nd for the forward pass, 4nd for activation and weight gradients in backprop. Training a 7-billion-parameter model on 1 trillion tokens totals about 4.2×10²² flops. But chips execute quadrillions of operations per second—why isn't raw math the bottleneck? The answer lies inside the GPU: memory is physically far from compute.

Think of off-chip HBM as a giant warehouse, and the small on-chip SRAM beside the Tensor Cores as the factory floor. Per course data, an NVIDIA B200 delivers 2.25 petaflops of BF16 compute, while the HBM bus moves 8 TB per second—doing roofline analysis, each byte fetched needs about 280 flops, otherwise cores idle behind the memory wall. The way through is operator fusion: naive PyTorch launches a separate kernel for each basic operation, repeatedly reading and writing HBM; custom Triton kernels load slices into fast SRAM, fuse multiplication, reduction, and RMS norm on-chip, then write back once. Pushed to tiled computation, this becomes FlashAttention, streaming compact QK tiles through SRAM without ever materializing the giant N² matrix.
When a single card can't hold the model, training state spans four heavy consumers: parameters, gradients, activations, and optimizer moments. Shard along five axes: data parallelism splits batches and optimizer states, tensor parallelism splits intra-layer weight matrices, pipeline parallelism distributes consecutive layers across devices, sequence parallelism divides long contexts, and expert parallelism scatters MoE blocks. Mapping follows physical topology: within a DGX-B200 node, 8 GPUs interconnect via ultra-fast NVLink, forming a tight island suited to high-communication tensor parallelism; across thousands of GPUs, many 8-card nodes connect via slower InfiniBand or Ethernet, where pipeline and data parallelism belong. Underneath, three collective primitives—all-gather, reduce-scatter, all-reduce—orchestrate every hop.
Inference consumes even more compute than training. In the pre-fill phase, all prompt tokens arrive at once, the GPU processes them in parallel and builds KV state, compute-bound like training; autoregressive decoding emits one token at a time, streaming billions of weights for a single word, severely memory-bound. Countermeasures include KV caching, continuous batching, quantization/pruning/distillation, and speculative decoding—a small draft model guesses K candidate tokens, and the target model verifies all K in one parallel forward pass, preserving the exact output distribution.
Roofline analysis is the quantitative tool for understanding the memory wall. It plots "operational intensity" (flops per byte of memory traffic, flops/byte) on the horizontal axis and achievable performance on the vertical axis, drawing two upper bounds: a horizontal compute roof (chip peak flops) and a bandwidth roof with slope equal to memory bandwidth. Their intersection is the "ridge point"—below it, performance is locked by memory bandwidth; above it, you can approach peak compute. For the B200, 2.25 petaflops divided by 8 TB/s bandwidth puts the ridge point at about 280 flops per byte, matching the figure in the text. This explains why naive PyTorch per-operator implementations often fall far below peak: every basic operation writes intermediate results back to HBM and reads them again, yielding extremely low operational intensity. The essence of operator fusion is merging multiple operators so data lingers in SRAM a bit longer, pushing the operating point past the ridge.
Scaling Laws: A One-Shot Bet
Suppose someone gives you 10²⁵ flops and a cluster worth tens of millions of dollars to train a frontier model—how do you choose depth, width, batch size, and learning rate? Small scale allows grid search; frontier scale offers one shot, and an unstable learning rate burns millions. Percy turns descriptive power laws into an active scaling recipe: map directly from any flop budget to a configuration profile. Scaling laws are not natural laws; they must be "made to exist by will"—parameterizations like muP let hyperparameters transfer from tiny sweeps to larger budgets, making predictability trump luck.
Distributing about 6nd flops between parameters n and tokens d, the bottom of the equal-flop parabola yields the Chinchilla rule: optimal d ≈ 20n, e.g., 70 billion parameters with 1.4 trillion tokens. But Chinchilla ignores inference—serving runs millions of times while training happens once, so Llama 3 and Qwen deliberately over-train 8-billion-parameter models on over 15 trillion tokens, making every future decode cheaper. Does extrapolation hold on real GPUs? Stanford's open-source Marin project fits equal-flop curves on small budgets, publicly pre-registers a loss prediction at 10²² flops while the target run is still training, and two days later the model completes within 0.05 loss of the prediction. Assignment 3 puts you in the same hot seat: query a cached training API under a strict flop cap and predict your own frontier run.
muP (Maximal Update Parametrization) is the key technique for transferring hyperparameters across scale. Under standard parameterization, optimal learning rates and initialization variances drift with width and depth, and configurations tuned on small models often diverge when moved directly to large ones. muP scales initialization and learning rates by layer width (with separate handling for the output layer), keeping these hyperparameters stable as width goes to infinity, so you can sweep hyperparameters on a tiny proxy model and transfer them zero-shot to the target scale. Experiments from Microsoft and others show muP makes hyperparameter transfer reliable across multiple scales—this is the technical basis for "making scaling laws exist by will": scaling laws are not passively observed power laws but predictability actively constructed through parameterization design.
Data: From Web Sludge to High-Octane Tokens
Data defines every capability a model learns. Internal engineers track perplexity on clean held-out text as a smooth, sensitive signal; external users care about ecological validity benchmarks like MMLU and GSM8K. Percy warns that data doesn't fall from the sky—open 300 random Common Crawl pages and you see a wasteland of navigation menus, template banners, spam, and broken HTML. Mixing web dumps with papers, books, and GitHub repos, as EleutherAI's Pile pioneered in 2021, also triggers legal entanglements around copyright fair use, paid Reddit licensing, and unauthorized code repositories.
Refining raw web sludge into tokens takes five steps: text extraction strips HTML and PDF layout; fast quality classifiers filter spam and toxic pages; fuzzy MinHash deduplication removes near-duplicate documents; domain mixing boosts scarce math and code sources; synthetic rewriting turns messy paragraphs into textbook-grade explanations. Refined tokens are not a uniform soup: modern labs arrange a three-stage data curriculum—broad pre-training for one pass over trillions of web tokens, annealing at the end of pre-training on concentrated high-quality math, code, and long-context documents, then post-training shifting to curated instruction dialogues and agentic tool-calling trajectories.
Alignment: A Feedback Loop of Weak Supervision
Pre-training applies full supervision to predict every next token; SFT applies the same imitation loss to structured chat templates, unlocking instruction following, style, and safety refusals. LIMA shows that a tiny amount of clean demonstrations can elicit skills the base model already harbors. Going beyond imitation requires weak supervision rooted in P vs. NP intuition: generating a perfect proof or patch from scratch is hard, but judging or verifying an answer is far easier. Sample candidate responses, score them, and push probability mass toward the winners—feedback comes from human pairwise preferences, LLM judges, or deterministic code and math verifiers, i.e., reinforcement learning with verifiable rewards. DPO directly updates weights on offline preference pairs, PPO trains a separate critic network on live rollouts, and critic-free GRPO normalizes rewards within each sampled group, discarding the memory-heavy value model entirely.
Percy admits he stays with supervised learning as long as possible before touching RL: beyond the well-known tuning instability, RL post-training is secretly a distributed systems nightmare—inference servers generate asynchronous long-tail rollouts, isolated sandboxes execute untrusted code, and training servers update policy weights. When a straggling worker is stuck on a marathon reasoning chain or a slow test suite, the trainer moves ahead, making trajectories off-policy and stale. Scaling RL becomes a continuous orchestration battle between on-policy freshness and cluster throughput.
DPO, PPO, and GRPO represent three routes for learning a policy from preference data. PPO is the classic policy gradient method, requiring simultaneous training of a policy network and a value network (critic) to estimate advantages, with high memory and tuning costs. DPO bypasses the explicit reward model and online rollouts, constructing a closed-form loss directly from pairwise preference data and expressing the policy update analytically as an implicit reward offset from the reference model—simple and stable to train, but dependent on a fixed offline preference set. GRPO (Group Relative Policy Optimization), proposed by DeepSeek, targets verifiable-reward settings: sample a group of responses to the same prompt, normalize rewards by the group's mean and standard deviation to obtain advantages, eliminating the value network and greatly reducing memory footprint, especially suited to tasks with deterministic verifiers like math and code. The trade-offs among the three are essentially a triangular balance of "online freshness vs. implementation complexity vs. memory cost."
Tokenizers: The Resolution at Which Models Perceive Language
Ask a frontier model how many R's are in strawberry and it stumbles; ask it to compute 127 plus 677 and carry arithmetic wobbles. Percy Liang and Andrej Karpathy both emphasize that these are not deep reasoning failures—every quirk traces back to tokenization. Inside the Transformer, raw strings never touch the neural network: human text is a Unicode string, and a language model is strictly defined as a probability distribution over sequences of discrete integer IDs, with the tokenizer as the bridge between two worlds. Tokenizers have three core metrics: lossless round-trip, vocabulary size V, and compression ratio (raw UTF-8 byte length divided by token count).
Three baselines each have fatal flaws: character tokenization blows the vocabulary up to around 150,000, and Unicode is a living standard adding emoji every year; byte tokenization has a fixed 256 vocabulary with zero unknown tokens, but its compression ratio is locked at 1.0, stretching sequences about 2.5x and amplifying N² attention costs about 6x; classic word tokenization has a high compression ratio, but the vocabulary has no fixed upper bound, and all novel words at test time collapse into unknown tokens. BPE's answer is simple and elegant: start from single bytes, count adjacent pairs, mint a new token ID for the most frequent pair and replace it—common patterns merge, rare fragments stay split. Philip Gage invented it in 1994 for lossless file compression, Sennrich et al. introduced it to neural machine translation in 2016, and Radford et al. ran BPE on raw UTF-8 bytes for GPT-2 in 2019.

There's a crucial distinction between training and inference: after BPE training, the tokenizer is frozen with an ordered merge table. When encoding a new sentence, different adjacent pairs may simultaneously appear in the merge table—you can't go left-to-right, nor by test-string frequency; you must replay history strictly by the learned merge table's priority, merging the lowest-ranked pair. The reason is causal dependency: if a later rule fires first, it steals the constituent bytes of earlier rules, making them forever unable to fire and feeding corrupted token IDs to the model. Decoding seems simple—traverse the vocab dict in insertion order and concatenate byte slices—but hides traps: decoding byte 128 alone crashes due to UTF-8 start-byte rules, so production tokenizers set errors to replace, turning malformed bytes into replacement diamond characters.
Production tokenizers also add a regex pre-tokenization barrier before BPE: GPT-2's pattern splits raw text left-to-right, BPE runs independently within each chunk, and merges never cross category walls. This pattern deliberately glues a single leading space to each word, and also explains the famous trailing-space warning—an isolated space becomes its own token, shuffling all subsequent token IDs. CL100K doubled the vocabulary from about 50,000 to about 100,000, fixing case-insensitive contractions, capping numbers at 1 to 3 digits, and merging newlines and Python indentation.
Failure Cases: Tokenizer X-Ray Glasses
- Spelling reversal: GPT-2 splits strawberry into three chunks, with three R's hidden in invisible vectors; split each character into its own token and the model easily reverses it.
- Arithmetic: BPE merges digits by corpus accident, so a four-digit number may split as 12 and 77, 1 and 277, or as a whole, disrupting column alignment.
- Code indentation: GPT-2 refuses to merge consecutive spaces, each space is its own token 220, four-space indentation burns four tokens, starving the 1024 context window; GPT-4 groups whitespace runs into single tokens.
- Multilingual tax: UTF-8 expands non-ASCII scripts into multiple bytes, English-heavy BPE leaves them fragmented, and the same meaning burns two to four times the context, latency, and API cost in Chinese, Korean, Hindi, and Burmese.
- Glitch tokens: Researchers Rumbelow and Watkins found a handful of outlier tokens in GPT-J and GPT-2 embedding tables with norms abnormally close to the origin, led by SolidGoldMagikarp—a prolific user of a Reddit marathon counting thread, fused by BPE into a dedicated token ID, but pre-training data excluded that Reddit data, so this row never received gradient updates and remained frozen at random initialization.
Karpathy ran an experiment with the same T-shirt product record: JSON's repeated braces, quotes, and commas consumed 116 tokens, while clean YAML with the same payload dropped to 99, saving nearly 15% with zero data loss. Smarter serialization directly stretches context windows and cuts API bills. So why not throw away the tokenizer and feed raw UTF-8 bytes directly into a standard Transformer? From an efficiency lens: without BPE's roughly 4x compression, raw byte sequences stretch 4x, and quadratic self-attention balloons 16x. Architectures like ByteT5, Megabyte, Meta's BLT, and hierarchical HNet already run directly on raw bytes, but none has yet replaced BPE at frontier scale. Percy notes that any post-tokenizer architecture must still learn two things inside the network: lifting noisy raw bytes, video pixels, or DNA bases into sequence abstractions, and routing adaptive compute across variable chunks.
Glitch tokens deserve understanding through the lens of optimization dynamics. Each row in the embedding table receives gradients only when that token appears in the training corpus; if a token ID was minted by BPE during tokenizer training (often based on text not perfectly aligned with the pre-training corpus, such as Reddit data) but is filtered out or never appears in actual pre-training data, that row stays frozen near random initialization. Randomly initialized vectors typically have norms far from the converged post-training embedding distribution, so these tokens become isolated outliers in representation space, and model behavior around them is unpredictable: they may trigger anomalous outputs, bypass safety alignment, or even serve as jailbreak entry points. This suggests tokenizer training corpora must be strictly consistent with model pre-training corpora, and shows that tokenizers are not merely preprocessing tools but components that affect model behavior.
One-line Summary
Building a language model from scratch, with the efficiency equation threading through five pillars: mechanisms, systems, scaling, data, and alignment.
Paragraph Summary
Using Stanford's CS336 course as its thread, the article argues that building language models from scratch still matters in the API era: deep learning's abstraction is "deeply leaky," and only breaking open the stack yields complete understanding. Percy Liang divides knowledge into mechanisms, mindset, and empirical intuition—the first two transfer across scale, the third may break. The core is the efficiency equation "accuracy = efficiency × resources," where a 5% efficiency gain saves millions in a frontier run. Five pillars map to five assignments: the modern Transformer is no longer the 2017 original; systems hit the memory wall, demanding operator fusion, FlashAttention, and five types of parallelism; scaling laws turn power laws into an active recipe, with Chinchilla and over-training strategies each trading off; data needs five-step refinement and a three-stage curriculum; alignment relies on a weak-supervision feedback loop. Finally, the tokenizer illustrates how spelling, arithmetic, the multilingual tax, and glitch tokens all stem from tokenization resolution.
Related articles

World of Warcraft Infinite Open Beta Review: How Does Slow-Paced Design Satisfy Millions of Players?
World of Warcraft Infinite's open beta drew a million players. We analyze its slow-paced design philosophy, the new Skywing race's leveling advantages, and class changes.

Pstack: An Open-Source Skill Library That Makes AI Coding More Rigorous
Pstack is an MIT-licensed open-source agent skill library with 5,000+ GitHub stars, offering test-driven development, TypeScript best practices, and potato mode for more rigorous AI coding.

The Bitter Lesson for Agent Memory: Why Complex Memory Systems Will Eventually Lose to General Methods
A Hacker News hot post, "The Bitter Lesson for agent memory," sparks debate: the complex handcrafted design of AI Agent memory systems may be repeating the history of being overtaken by general methods. This article analyzes the engineering dilemmas of memory architectures, community disagreements, and practical implications.