Stanford CS336: Language Modeling from Scratch
TL;DR. CS336 is Stanford’s course on building a language model yourself. It has 19 lectures and five assignments. You write a byte-level BPE tokeniser, a Transformer and AdamW. Then you write a Triton FlashAttention-2, fit a scaling law, filter Common Crawl, and do SFT and RL for math reasoning. The course says there is “minimal scaffolding”. It says you will write at least an order of magnitude more code than in other classes.
Why it matters now. Most courses explain models. This one makes you do the accounting: FLOPs, bytes, GPU-hours and dollars. That is the skill behind every design choice on this site. The Spring 2026 lectures are on YouTube. The lecture notes and assignment handouts are public on GitHub. The site also lists B200 prices for self-study.
Key idea
Section titled “Key idea”The course has five units. Each unit ends in an assignment you build. The lectures teach the tools for that build. Tatsunori Hashimoto and Percy Liang alternate lectures.
| Lecture | Topic (Spring 2026 schedule) | Read on this site |
|---|---|---|
| 1 | Overview, tokenisation | BPE, SentencePiece |
| 2 | PyTorch, resource accounting (FLOPs, memory, arithmetic intensity) | Kaplan scaling laws for 6ND, FP8 training |
| 3 | Architectures, hyperparameters | Attention, RoPE, GQA, AdamW |
| 4 | Attention alternatives, mixture of experts | Mixtral, DeepSeekMoE, Mamba, Gated DeltaNet, MLA |
| 5–6 | GPUs, TPUs; kernels, Triton | FlashAttention, FlashAttention-2, GPUs go brrr |
| 7–8 | Parallelism | DeepSeek-V3 and Llama 3 for real setups |
| 9, 11 | Scaling laws | Kaplan, Chinchilla, muP, data-constrained scaling |
| 10 | Inference | PagedAttention, speculative decoding |
| 12 | Evaluation | LLM-as-judge, contamination |
| 13–14 | Data: sources; filtering, dedup, mixing, synthetic data | FineWeb, DCLM, Dolma |
| 15 | Mid- and post-training (SFT, RLHF) | InstructGPT, DPO, PPO |
| 16 | Post-training with RLVR | GRPO, s1, test-time compute |
| 17 | Alignment, multimodality | Reward hacking |
| 18–19 | Guest lectures (Daniel Selsam, Dan Fu) | — |
The core tool is arithmetic intensity: FLOPs done per byte moved from GPU memory. An H100 does about 989 dense bf16 TFLOP/s over 3.35 TB/s of bandwidth. Lecture 10 divides these to get the threshold:
A kernel below this line waits on memory. A matmul of a batch of token vectors with a weight has intensity about when . So decoding one token at a time is memory-bound, and much of inference engineering is about raising this number.
Key results
Section titled “Key results”This is a course, so the outputs are the skills and artefacts you produce, not benchmark numbers.
- Assignment 1 trains on TinyStories, then on OpenWebText. Your perplexity goes to a public leaderboard. The handout includes resource-accounting problems: peak memory for AdamW, FLOPs per step, and training time for a GPT-2 XL-shaped model at 50% MFU.
- Assignment 2 profiles the Assignment 1 model. You replace attention with your own Triton FlashAttention-2 and make training memory-efficient and distributed.
- Assignment 3 reproduces the Chinchilla IsoFLOP method on given runs. You then spend 12 B200-hours, 25% of the big-run budget, on your own runs. You submit a predicted optimal model and its predicted loss. Part of the grade is how well the chosen model does.
- Assignments 4 and 5 turn raw Common Crawl into training data, then run SFT and RL for math reasoning. Assignment 5 has an optional second part on safety and DPO.
- The site lists self-study prices for one B200 as of 28 March 2026: 6.25 US dollars per hour on Modal and 4.99 on RunPod.
Limitations & open questions
Section titled “Limitations & open questions”- Scale gap. Ablations at 0.5 B200-hours may rank choices differently from a large run. Parallelism on a few GPUs does not show multi-node failures.
- Lectures move fast. Spring 2024, 2025 and 2026 versions all exist. Lecture numbers and assignment details change between years, so check which handout you are reading.
- Heavy workload. It is a 5-unit class. The prerequisites include strong Python, PyTorch, and systems basics such as the memory hierarchy.
- Narrow post-training. RL is taught on verifiable math rewards. Open-ended preference learning and agentic RL get less time.
Connections
Section titled “Connections”- Karpathy: Let’s build GPT is a gentler first pass at Assignment 1. CS336 adds RoPE, RMSNorm, SwiGLU and the full accounting.
- Karpathy: Deep dive into LLMs covers the same pipeline at the level of concepts, with no code.
- Chinchilla is the method behind Assignment 3. FlashAttention-2 is the kernel you write in Assignment 2.
- For the RL unit, see GRPO and Dr. GRPO.
- For IR readers: the data unit’s quality classifiers are rerankers over web documents. Compare DCLM with monoT5.
Questions to think through
These questions have no single right answer. Write or say your answer before you open the hints. Mark a question once you could defend your answer in a reading group.
- Derive / compute
Lecture 2 opens with two napkin questions. How many days does it take to train a 70B model on 15T tokens with 1,024 H100s at 50% MFU, and what is the largest model you can train with AdamW on 8 H100s of 80 GB? State every assumption.
What a strong answer covers
- Training compute is about 6ND = 6 × 70 × 10^9 × 15 × 10^12 = 6.3 × 10^24 FLOPs.
- Dense bf16 peak is about 989 TFLOP/s per H100 (the 1,979 figure assumes sparsity). At 50% MFU, 1,024 GPUs give about 4.4 × 10^22 FLOPs per day, so about 144 days.
- With bf16 parameters and gradients (2 + 2 bytes) and two fp32 Adam moments (4 + 4 bytes), each parameter costs 12 bytes, so 640 GB holds about 53B parameters.
- Keeping an fp32 master copy raises this to 16 bytes and about 40B parameters. Activations are ignored, so both are upper bounds.
- Mechanism
Using the arithmetic-intensity analysis from Lecture 10, explain why prefill is compute-bound while token-by-token generation is memory-bound, and why batching more requests helps the MLP layers but not attention.
What a strong answer covers
- Arithmetic intensity is FLOPs per byte moved. An H100 does about 989 TFLOP/s over 3.35 TB/s, so a kernel needs about 295 FLOPs per byte to be compute-bound.
- For an MLP matmul the intensity is about B × T (tokens processed per weight read). Prefill has large T, so it is compute-bound; generation has T = 1, so only a large batch B helps.
- For attention the intensity is ST / (S + T): about S/2 in prefill, but below 1 in generation.
- Batching does not help attention because every sequence reads its own KV cache, whereas all sequences share the same MLP weights.
- The fixes therefore shrink or share the KV cache (GQA, MLA, paging) or produce several tokens per weight read (speculative decoding).
- What if…
Assignment 1 asks you to ablate RMSNorm, pre-norm vs post-norm, RoPE vs NoPE, and SwiGLU vs plain SiLU. For each, say what makes the comparison fair and what you expect to see.
What a strong answer covers
- Removing RMSNorm: compare at the previous best learning rate and at a re-tuned lower one, because the usual failure is instability, not a worse optimum.
- Post-norm moves the norm after the residual add. Pre-norm keeps a clean residual path and is described as one of the few consensus changes to the 2017 design.
- NoPE: a causal mask lets a decoder infer position in principle, so the test is whether loss actually suffers without RoPE at this scale.
- SwiGLU has three matrices at d_ff ≈ 8/3 d; plain SiLU uses two at d_ff = 4d. Both are about 8d² parameters, so the comparison matches parameter count.
- Each run gets a small fixed GPU budget (0.5 B200-hours), so run-to-run noise and early-loss differences must be read with care.
- Design
Assignment 3 gives you 12 B200-hours of scaling-law runs through a training API to choose the best model for a 48 B200-hour run. Design the experiment and say how you would predict both the model size and the final loss.
What a strong answer covers
- Use IsoFLOP profiles: pick a few compute budgets, train several model sizes at each, and take the lowest-loss size per budget (the handout suggests this over a quadratic fit).
- Fit power laws N_opt(C) and D_opt(C) through those minima, with D = C / 6N, then extrapolate to the target budget.
- Spend most of the budget on the larger small budgets, where the trend is most informative, while leaving enough points to fit a slope.
- Fit loss against compute (or a parametric L(N, D)) to predict the final validation loss, and give an error bar from leaving one budget out.
- Check that hyperparameters such as learning rate and batch size transfer across sizes (for example with muP), or the fit will mix in tuning noise.
- Critique
The course compares itself to building an operating system from scratch. Critique how far a 5-unit class with small GPU budgets can teach frontier language modelling, and which lessons may not transfer to large scale.
What a strong answer covers
- It does cover the full pipeline end to end, and minimal scaffolding forces you to meet the real bugs and accounting.
- Single-node or few-GPU parallelism misses multi-node network bottlenecks, failures and pipeline scheduling at thousands of GPUs.
- Ablations and scaling fits at a few B200-hours can rank options differently than at large scale; scaling laws themselves change across the range (Kaplan vs Chinchilla).
- Data work on a sample of Common Crawl cannot reproduce the effect of filtering choices on trillions of tokens, and RL for math is a narrow slice of post-training.
- Connect
Map Lectures 3, 4 and 10 onto pages on this site, and explain how the choices taught in the architecture lectures change the inference costs taught in Lecture 10.
What a strong answer covers
- Lecture 3 (architectures): the Transformer, RoPE, pre-norm and GQA pages; AdamW for the optimiser.
- Lecture 4 (attention alternatives, MoE): Mixtral and DeepSeekMoE for experts; Mamba and Gated DeltaNet for linear-time mixers; MLA for compressed KV.
- Lecture 10 (inference): PagedAttention for memory management and speculative decoding for latency.
- GQA and MLA cut KV-cache bytes per token, which directly raises the low attention intensity in generation; MoE raises total parameters but keeps per-token FLOPs low.
- Linear-time mixers replace the growing KV cache with a fixed-size state.