Lecture guides›
✎

Lecture guide: Architectures, hyperparameters#

Lecturer: course staff · Course: Stanford CS336 Language Modeling from Scratch, Spring 2026, lecture 3 · Length: 1:30:00 Video: watch on YouTube Chapters that cite this lecture: 03. Transformer Architectures and Hyperparameters

In one sentence: Tatsu Hashimoto surveys what dozens of released language models chose at every decision point of a transformer, the norm placement, the activation, the position embedding, the hyperparameters and the stabilizers, and separates the choices that everyone converged on from the few that still move.

Before you watch#

The lecture assumes that you have seen the original transformer once. Its method is a survey: rather than derive the right architecture, it reads off what each released model did, so the long slides of model names are the point, and the earlier lecture on resource accounting supplies the recurring argument for removing small operations. The chapter Transformer Architectures and Hyperparameters condenses the survey into rules of thumb.

The lecture, part by part#

0:00–4:22 A survey instead of a theory#

Hashimoto has always found architecture inscrutable, so he tells everything, and titles the lecture accordingly: what nobody wanted to know about architectures and hyperparameters. The best way to learn is to train models and try variants, which the course cannot afford for the whole design space. The second best is to learn from what others released: which choices are fixed across all effective models, and which vary without harm. The baseline is the vanilla transformer of the original paper, with sine and cosine position embeddings, ReLU and the norm at the end of each block. Assignment 1 asks for pre-norm, RoPE and SwiGLU, largely copied from Llama, as everyone else did. Last year brought 19 new dense models, and this year's list runs from Qwen 3 and Gemma 4, released the Thursday before the lecture, to OLMo 3 and Liang's own 8-billion-parameter model trained with Marin. In this book: Transformer Architectures and Hyperparameters › The core idea.

4:22–7:27 Three requirements, and one agreed mistake#

A table lists models against vocabulary size, norm type, position embedding and the rest; it returns at the end. The plan has three steps: the building-block variations, then hyperparameters such as the feed-forward width and the vocabulary size, then low-level stability tricks, which are tied to the architecture. An architecture has to learn from data, train efficiently on GPUs and not blow up halfway through training, and all three requirements are baked into it, which is why it is messy. Historically, experimentation ran until about GPT-3; then Llama 2 made everyone train a near copy; then last year brought a turn toward stability and this year one toward long context. The one thing everyone agrees the original transformer got wrong is where the layer norm sits. In this book: Transformer Architectures and Hyperparameters › The core idea.

7:27–13:38 Post-norm, pre-norm and the residual stream#

A residual stream runs through the network, and attention and the feed-forward layer each add a delta to it. The original transformer puts a layer norm at the end of each component, inside the stream. Pre-norm puts it outside the stream, before the attention and before the feed-forward layer, and nearly every modern model does so; his one exception is OPT 350M. The early motivation was to do without learning-rate warm-up. Removing the warm-up hurt convergence, but two other benefits remained. With pre-norm the input passes straight through to the output, so gradients keep their size at initialization, whereas a norm inside the stream rescales them in every block. An early careful study showed smaller and rarer gradient spikes. A norm placed after the computation but outside the stream, as in Grok, Gemma 2 and OLMo 2, works too, and the standing advice for instability is to add layer norms in more places, even inside attention. In this book: Transformer Architectures and Hyperparameters › 1. Normalization.

13:38–20:11 RMSNorm, dropped biases and arithmetic intensity#

LayerNorm subtracts the mean, divides by the variance and scales back up. RMSNorm drops the mean subtraction and the bias, and only scales down and up. It is less expressive, nothing is lost in practice, and it is faster. The reason is the previous lecture's: in his example the norm is about 0.17% of the FLOPs and, on tiny models, can take as much as a quarter of the runtime, because it moves memory. A Google study from 2020 on a 200-million-parameter transformer found more steps per second and a better loss with RMSNorm. Biases in the linear layers are dropped for the same reason, and in some cases they can destabilize training. None of this could be reasoned out beforehand; it is collectively acquired knowledge. In this book: Transformer Architectures and Hyperparameters › 1. Normalization · Resource Accounting › 5. Find the bottleneck: arithmetic intensity.

20:11–27:16 Activation functions: gating#

There is a zoo of activations, from ReLU and GELU to SwiGLU, GeGLU and more. A plain ReLU trains a reasonable model, and Chinchilla is probably the best of that group. GELU differs by a small dip below zero, which changes the gradients there; GPT-3 used it. Nearly every credible modern model uses a gated linear unit. Take the feed-forward layer, the input times W1, ReLU, times W2, and add a gate: a second projection of the input, times V, multiplied element by element onto the ReLU output. The names combine the activation with GLU: ReGLU, GeGLU, SwiGLU. Google's models such as Gemma use GeGLU, and the Llama line, PaLM included, uses SwiGLU; among gated units the choice hardly matters. The gate adds a third matrix, so the feed-forward width is shrunk to two thirds to keep the parameter count. Shazeer's comparisons were parameter-matched, with small but consistent gains shown with error bars from repeated runs, and the 2020 Google study agreed. Gating is not necessary: GPT-3 works, and so does the Nemotron model of 340 billion parameters, which used a squared ReLU. In this book: Transformer Architectures and Hyperparameters › 3. The MLP and gating.

27:16–30:42 Serial and parallel blocks#

Normally attention and the feed-forward layer run one after the other. A systems-minded person sees a dependency and asks whether they could run in parallel, with their outputs added together. GPT-J did it and PaLM did it; done right, the norms are shared and the matrix products fused, and Cohere followed. It has fallen out of use in the past two years: the serial form is now optimized well enough that the parallel form's small gain no longer pays for its loss of representational power, effectively half the depth. His conclusion from how short this list is: apart from the norm, the biases and the gate, the original transformer has stood the test of time. Alternatives to attention wait for the next lecture. In this book: nothing beyond this guide; nearest: Transformer Architectures and Hyperparameters › What the practitioners say.

30:42–34:00 Why position has to be added, and why relative#

Attention is position-blind: it computes inner products, so shuffling the tokens changes nothing. The original transformer added sines and cosines, later models a learned vector for each position, and Google models such as T5 and Chinchilla a term added to the attention scores that depends on the distance between tokens. Most models since 2024 use RoPE, which came, unexpectedly, from GPT-J and from a little-known blog post and paper by an author in China. RoPE starts from an opinion: the inner product of two tokens' vectors should depend only on how far apart the tokens are. Sine embeddings fail this, because their inner products contain terms about absolute positions, and terms added to attention scores are not an embedding at all. In this book: Transformer Architectures and Hyperparameters › 2. Attention and position.

34:00–38:00 Rotation: the idea behind RoPE#

Inner products do not change under a common rotation, so rotate each token's vector by an angle proportional to its position. In "we know that", the second word is turned by one step. In "of course we know", both words sit two positions later and are turned further, but the angle between them is still one step. In many dimensions, cut the vector into pairs and rotate each pair at its own speed: slow pairs capture long-range dependence, fast pairs whether two tokens are neighbours. The paper motivates this with complex numbers; the geometry is the useful part. Gemma 4 rotates only the first two coordinates, which also works. In practice the rotation is a sparse multiplication by sines and cosines, applied to the queries and keys in every attention layer. Multiplying rather than adding leaves no cross terms, so no absolute position survives. In this book: Transformer Architectures and Hyperparameters › 2. Attention and position.

38:00–43:00 Implementing RoPE, and five questions#

The implementation generates cosines and sines from the position indices and applies them to the queries and the keys, as a matrix product or as an explicit rotation. The questions that follow are worth as much as the slides. Has anyone used rotations in more than two dimensions? He has not seen it; one could certainly rotate along any closed loop. How does one build this kind of knowledge? Read broadly enough to see a pattern, and try it yourself at a small scale, because no single paper gives full detail. Do parallel blocks cost accuracy? The PaLM paper reports no loss in quality and a 15% gain in utilization, but later Google models dropped them, and he knows of no controlled comparison. What separates the two RoPE variants? Only which coordinates are rotated; the slow ones barely move, so the variant suits tiny models. What is wrong with terms added to attention scores, as in ALiBi? They work reasonably well but cannot be written as an inner product, which he calls an aesthetic problem. In this book: Transformer Architectures and Hyperparameters › What the practitioners say · Building Your Own: A Roadmap Through the Assignments › The core idea.

43:00–46:44 The feed-forward ratio#

Hyperparameters appear the moment a model has to be instantiated: how wide the feed-forward layer, how many heads, how large the vocabulary, whether to regularize, deep or wide. The space looks daunting, but the space people actually try is small. The first consensus value: the feed-forward width is four times the model width. Exception one: a gated layer has three matrices, so the two-thirds correction gives roughly 2.5 to 2.67. The Llama 2 team, whose attention is cheap thanks to multi-query attention, multiplied by 1.33 and landed near 3.5. So 2.6 to 3.5 for gated models, and 4 otherwise. In this book: Transformer Architectures and Hyperparameters › 4. The hyperparameters that matter.

46:44–50:00 T5's 64, and a forgiving basin#

Most teams are boring, one change on top of Llama; Google is sometimes bold. T5 used a factor of 64, with the systems argument that larger matrix products keep the hardware busier, and Gemma 2 also pushed higher than usual. One panel of Kaplan's 2020 scaling paper, for a very small model, shows the loss flat for ratios from about 1 to about 10 and climbing steeply beyond. The standard choices therefore sit in a basin, and a radical one can work, T5 was a fine model, at a price in compute. The follow-up T5 v1.1 quietly went back to about 2.5. In this book: Transformer Architectures and Hyperparameters › 4. The hyperparameters that matter.

50:00–54:00 Head size and aspect ratio#

The convention for attention is that the number of heads times the head dimension equals the model width; T5 and LaMDA are the exceptions, and the basin around the convention is wide. The aspect ratio, model width divided by the number of layers, is one of the most critical choices. Teams fix it and scale everything together, so it settles depth against width for a whole model family. Most models sit near 100, GPT-3 and Llama included. Systems reasons push toward width: a very deep model has to be split along its depth into pipeline stages, which most people avoid, while width slices across GPUs by tensor parallelism. Expressiveness pushes toward depth. Kaplan's sweeps put the optimum near 100 at every model size, and other large-scale variation experiments found that FLOPs explain most of the difference, not the ratio. In this book: Transformer Architectures and Hyperparameters › 4. The hyperparameters that matter.

54:00–59:12 Vocabulary size, and comparing tokenizers#

Two classes of models appear. Monolingual English models have vocabularies of about 30,000 entries. Multilingual and production models since Llama, GPT-4 among them, have 100,000 to 200,000; Google's models sit higher and Llama derivatives near 100,000. Multilingual coverage needs the size, and so does scale: bigger models can handle larger vocabularies, and nobody trains large monolingual models any more. A multimodal model needs more tokens still, since images get a tokenizer of their own. Asked whether bits per byte can be compared across tokenizers, he answers yes, as long as the tokenizer does not alter the text, as older ones that dropped words did, and every model is normalized by the same number of bytes. In this book: Transformer Architectures and Hyperparameters › 4. The hyperparameters that matter.

59:12–1:04:00 Regularization that is really about optimization#

The textbook argument against regularization in language modelling: there is more internet data than FLOPs, a large run makes a single pass, and a single pass of SGD barely memorizes, so overfitting is almost never a problem in compute-constrained training. Some teams therefore look at training loss only. Yet many recent models use weight decay, and some dropout. Papers have shown that weight decay then acts on the optimizer rather than on overfitting: training and validation loss stay on the diagonal, and runs with stronger weight decay start slower but end in a much better minimum once the learning rate is decayed. At a constant learning rate it need not appear. Such interactions cannot be derived in advance, which is why the course makes students touch everything. In questions he says that he has not studied diffusion architectures enough, that weight decay may allow a higher learning rate or a faster decay, and that dropout has fallen out of use because it interacts badly with optimization. His summary of hyperparameters: a factor of four, heads that add up to the width, an aspect ratio near 100, and a few regularization settings to try. In this book: Transformer Architectures and Hyperparameters › What the practitioners say.

1:04:00–1:08:00 Stability, and the two softmaxes#

As runs get more expensive, stability matters more than raw performance: a loss curve with spikes and large gradient norms can leave a poor model, or one that cannot be trained further, after millions of dollars. One usual suspect is the softmax, which combines an exponential with a division. A language model has two, at the output and in attention, and attention is the more dangerous. For the output one, the log-probability is the logit minus the log of the normalizer. The logit behaves as long as the residual stream does; the normalizer is a sum of exponentials and can explode or vanish. The softmax is over-parameterized, since a constant added to every logit changes nothing, so the normalizer can be pushed around freely. In this book: Transformer Architectures and Hyperparameters › What the practitioners say.

1:08:00–1:14:00 z-loss, QK-norm and soft-capping#

The z-loss adds the squared log of that normalizer to the loss and pulls it to zero; he dates the trick to an older paper and names DCLM and OLMo as open models that brought it back. For attention, the rule of thumb is to throw a layer norm at the instability. QK-norm normalizes the queries and keys before their product, so the inputs of the attention softmax have a scale of about one. It comes from multimodal models, costs no visible performance, prevents attention degeneracies and is now standard; norms have moved from before each block, to after its nonlinearities, to inside attention. Logit soft-capping, a tanh that bounds the attention logits, is a harder intervention that Gemma 2, 3 and 4 use. In a systematic comparison by NVIDIA researchers, QK-norm does slightly better than the baseline because the learning rate can be raised, and soft-capping on its own loses quality, since the softmax can no longer express very confident weights; it is very safe all the same. In this book: Transformer Architectures and Hyperparameters › What the practitioners say.

1:14:00–1:18:00 Why serving changes the arithmetic#

Two attention interventions are common today: grouped-query attention, which saves inference cost, and sliding-window attention, adopted by most long-context models that avoid exotic state-space layers. Serving a model costs FLOPs and memory accesses, and both should be small. During training or prefill, when the whole prompt is processed, the arithmetic grows with the batch, the sequence length and the square of the width, while memory traffic is far smaller, so the GPUs are fully used as long as the head dimension and the batch times the sequence length are large enough. Generation is different, because tokens come one at a time, the condition of autoregressive modelling. The KV cache keeps the keys and values of the past, so each step computes only the new row of interactions. It saves arithmetic, and it changes the memory pattern. In this book: Transformer Architectures and Hyperparameters › What the practitioners say · Inference › 1. Count one decoding step.

1:18:00–1:20:00 Generation is memory-bound; multi-query attention#

The arithmetic of a step is what it was, spread over steps, but memory traffic now grows with the sequence length times the square of the width, where it used to be only the square. The arithmetic intensity comes out as roughly the sequence length over the width, plus one over the batch. Efficient serving then needs large batches and short sequences, or a large width, which is bad news for small models, and the term in the sequence length is hard to shrink. Multi-query attention keeps one key and one value for all heads and lets only the queries differ. The cache shrinks a great deal, and the intensity is multiplied by the number of heads. The price is expressive power. In this book: Inference › 3. Shrink the KV cache.

Grouped-query attention is the middle ground: fewer key and value heads than query heads, with the ratio free to choose. It controls the trade-off with one number, and in practice the trade-off is favourable. Going from multi-head to multi-query, cost falls a great deal and quality falls a great deal too; a smaller multi-head model does no better; grouped-query attention keeps nearly the full quality at low cost, and a small reduction in heads brings most of the saving. DeepSeek V2's multi-head latent attention, a different factorization, is for the next lecture. In questions: teams use a mix of rules of thumb and search, usually changing one architectural choice at a time; Google is one of the only organizations that changes many, and Gemma 4 gives every layer its own embedding to trade memory against FLOPs; weight decay is the one hyperparameter changed during training, in step with the learning rate. In this book: Transformer Architectures and Hyperparameters › What the practitioners say · Inference › 3. Shrink the KV cache.

1:24:00–1:30:00 Sliding-window attention and hybrids#

An old idea: GPT-3 alternated full attention with a banded pattern of fixed window. Over the past year it became a common answer to long context. In Cohere's Command A, one layer in four attends to everything and the three between see only a window; local information is aggregated into global as the layers go, so the cost of a long context is managed without a state-space model. Some models drop position embeddings for the long range and keep them for the short. Llama 4, Gemma 4 and OLMo 3 all mix sliding-window and full attention with full RoPE, and Qwen 3.5 alternates a state-space layer called Gated DeltaNet with one full-attention layer in four. His closing point: across the table the defaults are now clear, and the differences that remain are in context, position and tokenization. In this book: Transformer Architectures and Hyperparameters › What the practitioners say · Attention Alternatives and Mixture of Experts › 2. Mix local and global layers.

What to take away#

Sources#