Architectures & Hyperparameters

Six years of experiments turned the 2017 Transformer block into the LLaMA block: pre-norm, RMSNorm, SwiGLU, RoPE and grouped-query attention. At LLaMA-2 70B's size the weights barely move: 130 GB to 138 GB. The memory for one 4,096-token conversation falls from 10.7 GB to 1.3 GB.

Flip each switch from 2017 to modern. Watch the block redraw and the two bars move. Then we take each switch apart: what it changes, what it costs, and the evidence for it.

You need a Transformer block (attention, then a feed-forward layer, each with a residual add) and parameter counting from Lecture 2. We build the rest from zero.

Lecture 3 of Stanford CS336, Language Modeling from Scratch (Spring 2025, Percy Liang and Tatsunori Hashimoto). Previous: Lecture 2, PyTorch and Resource Accounting. Next: Lecture 4, Mixture of Experts.

Upgrade the 2017 block

Computed from the shapes: width 8,192, 80 blocks, 64 query heads of size 128, a 32,000-token vocabulary, bf16 (2 bytes a number), no biases. Modern = LLaMA-2 70B's choices (feed-forward width 28,672, 8 key-value heads). The 2017 side keeps that size and swaps in the 2017 choices.

Chapter 0

Two Transformers, Six Years Apart

Lay the 2017 block beside today's, and sort what everyone agrees on from what still varies

Open the 2017 Transformer paper and the LLaMA 2 paper side by side. The skeleton is the same: token embeddings, a stack of blocks, a projection back to the vocabulary. Each block still has attention, then a feed-forward layer (two matrix products with a nonlinearity between them), each wrapped in a residual add.

Almost everything inside the block changed: where the norm sits, the norm itself, the nonlinearity, how position enters, and how many heads keep keys and values. Which changes matter, and which are fashion?

You cannot afford to test them all. Lecture 3's method: "the best way to learn is hands-on experience; the second best way is to try to learn from others' experience". It reads the published models. In the year since the previous run of the course, it counts over 19 new dense model releases, many with small architecture tweaks.

Read the family table

Columns are models in time order. Purple cells made the choice LLaMA later made; grey cells did not. Pick a row.

From the lecture's slides (which model uses which norm, activation and position scheme) and each model's paper. "T5" is the 2019 model; its norm drops the mean and the bias, so the lecture files it under RMSNorm.

Pre-norm is in 7 of the 8 columns, and every model after 2017 has it. The other rows stay mixed until about 2023. The lecture's summary: low consensus, except pre-norm, and a trend toward LLaMA-like designs. The block you build in Assignment 1 is that trend: the norm in front of each sub-layer, RoPE, SwiGLU, and no bias terms.

Symptom: you copy one model's config, change two things, and the run diverges.

Measure: check each choice against the table. Is it one everyone makes, or one that still varies?

Fix: start from the consensus recipe. Change one choice at a time, at a small scale, against the same baseline.

The road

  1. Pre-norm: keep the norm off the residual stream, so gradients reach every layer.
  2. RMSNorm: drop the mean and the bias, because data movement costs time.
  3. SwiGLU: gate the feed-forward layer, and shrink it to keep the parameter count.
  4. RoPE: tell position by rotating queries and keys, so only the offset counts.
  5. GQA: share keys and values between heads, and shrink the cache.
  6. Ratios: the boring numbers almost every model picks.
  7. Stability: z-loss, QK-norm and soft caps tame the softmax.
  8. Showcase: size any model and its cache from its config.
  9. Field guide: the table, the block in code, the checks.
What does the lecture conclude after reading many published models?

Chapter 1

Pre-Norm: Keep the Residual Stream Clean

Move the norm off the main path, and gradients reach the bottom layers at full strength

Picture the residual stream: one vector per token, from the embedding to the output. Each sub-layer reads it and adds its result back. A LayerNorm rescales a vector to mean 0 and spread 1. Where should it sit?

The 2017 Transformer put it on the stream, after each add. That is post-norm. Every gradient that travels from the loss to the first layer must pass through every norm on the way. Pre-norm moves the norm onto the branch, so the stream itself is never rescaled.

Call the stream entering block l xl, the sub-layer F and the norm Norm. Pre-norm is:

Say it aloud

x-l-plus-one equals x-l plus F of Norm of x-l.

xl+1
x-l-plus-one the stream after block l: one vector of width d per token.
xl
x-l the stream entering block l. The add copies it straight through.
F
F the sub-layer: attention or the feed-forward layer.
Norm
Norm LayerNorm or RMSNorm, applied only to the copy that F reads.
In plain words

Normalize a copy of x-l. Feed the copy to F. Add F's output to the untouched x-l. Post-norm instead normalizes the sum: x-l-plus-one = Norm(x-l + F(x-l)).

With numbers

From the toy below, 24 blocks of width 16: under pre-norm the stream's size grows from 5.0 to 14.3, because nothing rescales it. So pre-norm models add one final norm before the output layer. Under post-norm it stays at 4.0, the size of a normalized vector of width 16.

Send a gradient down the stack

Each bar is the size of the gradient reaching one block's first weight matrix, bottom block on the left. Switch the norm placement, then add depth.

24 blocks

Illustrative toy, computed live by backpropagation in your browser: width 16, ReLU feed-forward sub-layers, random weights scaled by 1/√fan-in, 32 random inputs, averaged over 4 seeds. We checked the gradients against PyTorch to 15 digits.

At 24 blocks, post-norm sends the top three blocks gradients 4.9 times larger than the bottom three. Pre-norm keeps them level: 0.76 times. Xiong et al. (2020) proved the same shape at initialization. Large gradients near the output are why post-norm needs a learning-rate warmup.

Pre-norm was first sold as "no warmup needed". Today the lecture's reason is stability and larger learning rates. Nguyen and Salazar (2019) also saw gradient spikes under post-norm. BERT was post-norm; the one odd modern exception is OPT-350M.

Two newer twists. A double norm also normalizes the sub-layer's output, before the add (Grok, Gemma 2). OLMo 2 keeps only that outer norm. Parallel layers (GPT-J, PaLM, GPT-NeoX) feed one normed copy to attention and the feed-forward layer at once. PaLM reports about 15% faster training at large scale.

Symptom: the loss spikes or diverges in the first steps unless you add a long warmup.

Measure: log each block's gradient size at step 0. Growth toward the output is the post-norm signature.

Fix: put the norm on the branch, and add one final norm before the output layer.

In pre-norm, what does the norm act on?

Chapter 2

RMSNorm: Drop the Mean, Save the Memory Trips

Rescale by the root mean square alone, because the norm's cost is data movement, not arithmetic

LayerNorm does three things to a vector of width d. It subtracts the mean. It divides by the spread. Then it multiplies each entry by a learned gain and adds a learned bias. RMSNorm (Zhang and Sennrich, 2019) keeps only the divide and the gain.

Call the input vector x, its width d, the learned gain g, and a tiny constant ε that prevents a divide by zero. Entry i of the output is:

Say it aloud

y-i equals g-i times x-i, divided by the square root of one over d times the sum over j of x-j squared, plus epsilon.

yi
y-i entry i of the normalized vector.
gi
g-i the learned gain for entry i. It starts at 1. There is no bias.
xi
x-i entry i of the input, one of d numbers.
√(…)
the root mean square square every entry and take the mean over all d entries: one over d times the sum over j. Add epsilon, about 10−5. Take the square root.
In plain words

Square every entry of x, average the squares, and take the root: that is the RMS. Divide each x-i by the RMS and multiply by its gain g-i. RMSNorm subtracts nothing.

With numbers

With made-up numbers: x = [1, 2, 3, 6], g = 1, ε = 0. The squares average to 50 / 4 = 12.5, so the RMS is 3.54. y = [0.28, 0.57, 0.85, 1.70]. LayerNorm subtracts the mean 3 first and gives [−1.07, −0.53, 0, 1.60].

Shift the input, compare the norms

Left: the input x. Right: the output. The yellow line is the mean. Drag the shift to add the same amount to every entry.

+0

Illustrative: x = [1, 2, 3, 6] plus the shift, gains of 1, ε = 0. Same numbers as PyTorch's layer_norm and rms_norm.

Why bother? The norm does almost no arithmetic. Ivanov et al. (2021) profiled a BERT encoder layer in PyTorch: normalization was 0.17% of the FLOPs but 25.5% of the runtime. FLOPs are not runtime. A norm reads the whole vector from memory and writes it back, and moving bytes is the slow part.

RMSNorm makes fewer passes and stores no bias. Zhang and Sennrich report comparable quality and 7% to 64% less running time across models. The same logic removed bias terms from the linear layers: a modern feed-forward layer is σ(xW1)W2, with no added constants. The lecture gives two reasons: memory and optimization stability.

Symptom: a norm kernel takes a large share of step time, though it does almost no math.

Measure: profile runtime per operator, not FLOPs. Count bytes moved per FLOP.

Fix: use RMSNorm, drop biases, and fuse the norm into its neighbours (a kernel topic in Lecture 6).

Normalization is 0.17% of a BERT layer's FLOPs. Why can RMSNorm still save real time?

Chapter 3

SwiGLU: A Gate in the Feed-Forward Layer

Multiply the activation by a second learned projection, then shrink the layer to pay for the extra matrix

The feed-forward layer widens the vector from d to dff, applies a nonlinearity, and narrows it back. The 2017 model used ReLU, max(0, z). GPT-1, 2 and 3 used GELU: z times the chance that a standard normal falls below z, a smooth ReLU.

A gated linear unit (GLU) multiplies the activation, entry by entry, by a second projection of the same input: the gate. SwiGLU uses Swish (also called SiLU), z times sigmoid(z), as the activation.

Call the input x, the three weight matrices W1, V and W2, and entry-by-entry multiplication ⊙. The layer is:

Say it aloud

FFN of x equals Swish of x W-one, times entrywise x V, all times W-two.

FFN(x)
F F N of x the feed-forward output: width d, added to the stream.
Swish(xW1)
Swish of x W-one project x to width d-ff with W-one (d by d-ff), then apply z times sigmoid of z to each entry.
⊙
times entrywise multiply matching entries of two vectors of width d-ff.
xV
x V the gate: a second projection to width d-ff, with no nonlinearity.
W2
W-two the d-ff by d matrix that narrows the result back to width d.
In plain words

Project x twice. Pass the first projection through Swish. Multiply it, entry by entry, by the second projection. Project the product back down with W-two.

With numbers

With made-up numbers, one hidden entry: x W-one gives 1.5, and Swish(1.5) = 1.5 × 0.818 = 1.23. If x V gives 2.0, the entry is 2.45. If x V gives −0.5, it is −0.61: the gate sets its sign and size.

Plot the activation, then gate it

The warm curve is the activation you pick. The purple curve is Swish(z) times the gate value. Drag the gate.

2.0

Exact curves: GELU uses the error function, not the tanh shortcut. The gated curve shows one hidden entry; a real layer has d-ff of them, each with its own gate.

The gate costs a third matrix. For a fair test, keep the parameter count. A plain layer has two matrices of d by 4d. A gated layer has three of d by dff:

Say it aloud

Three times d times d-ff equals two times d times four d, so d-ff equals eight thirds of d.

3
three the gated layer's matrices: W-one, V and W-two.
d
d the model width.
dff
d-ff the gated layer's hidden width, the unknown.
2
two the plain layer's matrices.
4d
four d the plain layer's hidden width, the 2017 default.
In plain words

Set the gated layer's weights equal to the plain layer's. Divide both sides by 3d. d-ff comes out at 8/3 of d, about 2.67 d.

With numbers

d = 4,096: 8/3 × 4,096 = 10,923, and both layers hold 134 million weights. LLaMA-2 7B rounds up to 11,008, a multiple of 256. LLaMA-2 70B chose a wider 28,672 = 3.5 d.

Does gating help? Shazeer (2020) found consistent gains at equal parameters, and Narang et al. (2021) agree. It is not required: GPT-3 used GELU, and Nemotron 340B uses squared ReLU. GeGLU, the GELU version, is in T5 v1.1 and Gemma 2 and 3.

Symptom: your SwiGLU model beats the baseline, but its feed-forward layers hold 1.5 times the weights.

Measure: count 3 × d × dff against 2 × d × 4d.

Fix: set dff near 8d/3, rounded to a multiple of 64 or 256, before you compare.

A ReLU feed-forward layer has d = 2,048 and dff = 8,192. For a SwiGLU layer with the same parameter count, what is dff?

Chapter 4

RoPE: Position as a Rotation

Rotate each query and key by an angle set by its position, so the score sees only the distance between them

Attention compares a query (what this token looks for) with a key (what another token offers) by a dot product. Nothing in a dot product knows order, so the model needs a separate signal for position. Ideally the score depends only on the offset: "the word three tokens back", wherever the pair sits.

The older schemes miss that. Sinusoidal (2017) and learned absolute (GPT-1, 2 and 3, OPT) embeddings add a position vector to the token vector. The dot product then has cross terms that depend on each absolute position. Relative schemes (T5, Gopher, Chinchilla) add a bias to the scores, which is not a dot product.

RoPE (Su et al., 2021) uses one fact: rotating two vectors by the same angle leaves their dot product unchanged. Split each query and key into pairs of numbers. Rotate each pair by its position times a fixed angle θ. Call the query q at position i, the key k at position j, and a rotation by angle a R(a):

Say it aloud

R of i-theta times q, dot R of j-theta times k, equals q dot R of j-minus-i times theta, times k.

R(iθ) q
R of i-theta times q the query pair, turned by angle i times theta.
R(jθ) k
R of j-theta times k the key pair, turned by angle j times theta.
·
dot the dot product: this pair's share of the attention score.
q
q two numbers of the query, from the token and the learned query weights.
k
k the matching two numbers of the key.
R((j−i)θ)
R of j-minus-i times theta one rotation by the offset alone. Theta for pair m of a head of size d-head is 10,000 to the power minus 2m over d-head.
In plain words

Turn the query by i steps of theta and the key by j steps. Turning both back by i steps changes nothing, so the score equals the unturned query against the key turned by j minus i steps. Only the offset survives.

With numbers

With made-up numbers: q = (1, 0.5), k = (0.8, −0.2), θ = 0.5. At positions 3 and 7 the score is 0.2543. At 10 and 14 it is 0.2543 again: same offset of 4. At 3 and 8 it is −0.2017.

Rotate a query and a key

Warm is the query, purple the key; faint arrows are before rotation. Move either position, or shift both by 5 and watch the score.

3
7

Illustrative: one pair, θ = 0.5 radian per position. A real head of size 128 has 64 pairs. Pair 0 turns 1 radian per token, a full turn every 6.3 tokens; the last pair takes about 54,000 tokens.

The fast pairs resolve nearby positions; the slow pairs carry long distances. RoPE acts inside every attention layer, on queries and keys only; nothing goes into the embedding. GPT-J, PaLM and LLaMA use it, and the lecture counts most 2024 and later models.

Symptom: a checkpoint you load gives fluent nonsense, though the shapes match.

Measure: check how your code pairs numbers: neighbours (0, 1), (2, 3), or the first half with the second half.

Fix: use the pairing the checkpoint used in training. Both work; mixing them does not.

Why does the RoPE score depend only on j − i?

Chapter 5

GQA: Share Keys and Values, Shrink the Cache

Let groups of query heads read the same key and value head, and the memory for every conversation drops

A model writes one token at a time. Each new token's queries must see the keys and values of every earlier token. Recomputing them each step would waste work, so the model stores them: the KV cache. In multi-head attention (MHA), each of the h heads keeps its own keys and values.

The lecture works out why this hurts. Training processes a whole sequence at once, so each byte of weights read feeds many FLOPs. Generation does one token per step but reads the whole cache, so the GPU waits on memory. Fewer bytes in the cache means faster steps and bigger batches.

Call the number of blocks L, the key-value heads per block nkv and the head size dhead. Call the tokens so far T and the bytes per number b. The cache for one sequence is:

Say it aloud

Cache equals two times L times n-kv times d-head times T times b.

cache
cache bytes held for one sequence.
2
two one key and one value per head.
L
L the number of blocks; each has its own cache.
nkv
n-kv key-value heads per block: h for MHA, 1 for MQA, a few for GQA.
dhead
d-head numbers per head, usually 128.
T
T tokens in the sequence so far.
b
b bytes per number: 2 in bf16.
In plain words

For every block, every key-value head and every past token, store a key and a value of d-head numbers. Multiply the counts, then multiply by b bytes.

With numbers

LLaMA-2 70B: L = 80, d-head = 128, T = 4,096, b = 2. With MHA's 64 heads: 2 × 80 × 64 × 128 × 4,096 × 2 = 10.7 GB. With its 8 key-value heads: 1.34 GB, 8 times less. A batch of 16 sequences: 172 GB against 21.5 GB.

Group the heads, size the cache

Top: query heads (warm) wired to the key-value heads they read (blue). Bottom: the cache for one sequence against one GPU's 80 GB. Pick a model, a grouping and a length.

4,096

Computed from the formula with each model's published shape, head size 128, bf16, one sequence. 80 GB is one H100's memory. The model's own weights are not in the bar.

Multi-query attention (MQA, Shazeer 2019) keeps every query head but gives them one shared key and value head; Shazeer saw a small perplexity cost. Grouped-query attention (GQA, Ainslie et al. 2023) sits between: groups of query heads share a key-value head. Ainslie et al. report quality close to MHA at a speed close to MQA, after converting an MHA checkpoint with about 5% of its pretraining compute.

Symptom: generation runs out of memory at long contexts or large batches, though the weights fit.

Measure: cache bytes per token = 2 × L × nkv × dhead × b. For LLaMA-2 70B with MHA that is 2.6 MB per token.

Fix: fewer key-value heads (GQA), a shorter context, or a lower-precision cache.

LLaMA-3 8B has 32 blocks, 8 key-value heads of size 128. What is its KV cache for one 4,096-token sequence in bf16?

Chapter 6

Hyperparameters: The Boring Consensus

Read four ratios off published models, and find that almost all of them pick the same numbers

With the block fixed, you still choose numbers: the feed-forward width, the heads, the depth, the vocabulary. The lecture's surprise is how much models agree. Four ratios carry it.

  1. Feed-forward ratio dff/d: 4 for plain layers, about 8/3 for gated ones. Kaplan et al. (2020) found a wide basin from about 1 to 10. T5 11B used 64; its successor T5 v1.1 went back to 2.5.
  2. Head ratio h × dhead/d: almost always 1, so the heads split the width. Bhojanapalli et al. (2020) argued against it, but the lecture sees no low-rank bottleneck in practice.
  3. Aspect ratio d/L: most models sit between 100 and 200. Deep, narrow models are harder to parallelize and slower per token.
  4. Vocabulary: 30,000 to 50,000 tokens for one language; 100,000 to 250,000 for many.

Place real models on each ratio

Each dot is a published model; the yellow band is the consensus. Pick a ratio. The axis is logarithmic.

From the lecture's tables, checked against the configs where we have them. PaLM's heads are 48 of size 256 at width 18,432 (the PaLM paper), a ratio of 0.67. GPT-4's tokenizer (cl100k) has 100,277 ids.

Why do these ratios matter for size? Call the width d and the query heads h. Call the key-value heads nkv, the head size dhead and the feed-forward width dff. Let m count its matrices: 2 plain, 3 gated. The weights in one block are:

Say it aloud

P-block equals two d times h d-head, plus two d times n-kv d-head, plus m d d-ff.

Pblock
P-block weights in one block, without the two small norm gains.
2d(h dhead)
two d times h d-head the query matrix and the output matrix.
2d(nkv dhead)
two d times n-kv d-head the key and value matrices, smaller under GQA.
m d dff
m d d-ff the feed-forward layer: m matrices of d by d-ff.
In plain words

Count four attention matrices and m feed-forward matrices, each as rows times columns. With the consensus ratios (h d-head = d, n-kv = h, and d-ff = 4d plain or 8d/3 gated) every block is 12 d².

With numbers

d = 4,096: 12 × 4,096² = 201.3 million. LLaMA-2 7B's real block (d-ff = 11,008, gated, 32 key-value heads) is 67.1 + 135.3 = 202.4 million. That is why Lecture 2's 12 L d² works for both recipes.

Last, regularization. Older models used dropout 0.1; newer ones mostly use none, with Qwen an exception. Weight decay of 0.1 stayed. Andriushchenko et al. (2023) argue it is not there to stop overfitting, since a model sees each token about once. It changes the optimization, together with the cosine learning-rate schedule.

Symptom: a deep, narrow model trains fine but is slow per token and hard to split across GPUs.

Measure: compute d/L. GPT-2's largest model is 1,600 / 48 = 33.

Fix: keep d/L near 100 to 200 unless a systems reason says otherwise.

A model has d = 4,096 and 32 heads, with SwiGLU. What are dhead and the parameter-matched dff?

Chapter 7

Stability: Tame the Softmax

Find the two softmaxes that blow up, and pin them with z-loss, QK-norm and soft caps

A loss curve that spikes, or climbs and never returns, wastes a run. The lecture's warning: "Beware of softmaxes". A softmax exponentiates, and exponentials overflow. A Transformer has two: the output softmax and the attention softmax in every head.

Start with the output. The model gives a logit (a raw score) zi for each token i. Softmax divides ezi by their sum, Z. Adding the same number to every logit changes no probability, so the loss cannot stop the logits from drifting up together.

The z-loss fixes that drift. Call the cross-entropy loss CE, the log of the sum log Z, and a small weight α:

Say it aloud

Loss equals C E plus alpha times log Z, squared.

loss
loss what training minimizes at one position.
CE
C E the cross-entropy: minus the log probability of the true next token.
α
alpha the z-loss weight. PaLM used 10−4.
log Z
log Z the log of the sum of e to each logit. It is 0 when the probabilities need no rescaling.
In plain words

Compute log Z from the logits. Square it, multiply by alpha, and add it to CE. The penalty grows as the logits drift, so training holds log Z near 0.

With numbers

With made-up logits [2, 1, 0.5, −1] and the first token true: log Z = 2.50 and CE = 0.495. Add 10 to every logit: CE is still 0.495, but log Z = 12.50 and the z-loss is 0.0156. Add 50: the z-loss is 0.28, half the size of CE.

Push the softmax until it breaks

Left: four logits. Right: their probabilities. Shift moves every logit (what z-loss sees); scale grows them (what QK-norm undoes). Switch on the fixes.

+0
1.0×

Illustrative: one softmax over four made-up logits. Scaling the query and key by s multiplies every logit by s², so the slider goes up to 64 times. z-loss weight 10−4, as in PaLM.

Now attention. If queries and keys grow, their dot products grow with the square. At scale 2 the logits become [8, 4, 2, −4] and the top probability is 0.98. The softmax is close to one-hot, and its gradient vanishes. QK-norm normalizes each query and key before the dot product, so their size cannot grow. It came from vision models (Dehghani et al., 2023); DCLM, OLMo 2 and Gemma 2 use it.

Soft-capping squashes a logit x to c × tanh(x / c), so it never passes c. Gemma 2 caps attention logits at 50 and final logits at 30: a logit of 60 becomes 28.9. It may cost some quality. The z-loss goes back to Devlin (2014); PaLM, Baichuan 2, DCLM and OLMo 2 use it.

Symptom: the loss spikes, recovers, and spikes again; or it diverges late in training.

Measure: log log Z at the output and the largest attention logit per layer over training.

Fix: add z-loss and QK-norm; both are cheap. Then lower the learning rate if spikes remain.

What does the z-loss penalize, and why can cross-entropy alone not do it?

Chapter 8

Showcase: Size a Model and Its Cache

Load a published config, then turn its width, depth, heads and vocabulary and watch every count move

Every chapter's formula, in one counter. Start from a preset and check the total against the published size. Then break the consensus on purpose and see what it costs.

Count a model from its config

Top: where the weights live. Middle: the four ratios against their bands. Bottom: weights and cache in GB. Load a preset, then drag.

4,096
32
32
32
2.69
32,000
4,096

Formula: L × Pblock + 2 norm gains per block + embeddings (V × d, twice unless tied) + a final norm. No biases, no position table. Presets use each model's published shape; a preset's exact dff holds until you drag that slider. bf16 for weights and cache.

Things to try. Load LLaMA-2 70B, then set key-value heads to 64. The cache for 4,096 tokens jumps from 1.3 GB to 10.7 GB; the weights grow 14%. Load LLaMA-3 8B and compare it with Mistral 7B: the same blocks, but the 128,256-token vocabulary adds 0.79 billion weights. Drop the blocks of LLaMA-2 7B to 8 and watch d/L leave its band.

Check yourself. Without the counter, estimate GPT-3 with 12 L d². Then load it: 12 × 96 × 12,288² = 174 billion, plus 0.6 billion of tied embeddings.

Chapter 9

Field Guide

Keep the checklist, the block in code, and where each choice comes from

The modern block keeps the 2017 skeleton and changes five parts. Pre-norm is universal. RMSNorm, SwiGLU, RoPE and GQA are the LLaMA-style defaults, each with evidence but with exceptions. The ratios are boring on purpose, and the stability tricks all guard a softmax.

ChoiceModern defaultWhyExceptions
Norm placementpre-normgradients reach every layer; stable at larger learning ratesBERT and the 2017 model (post); OPT-350M
Norm typeRMSNorm, no biasesfewer bytes moved, same qualityGPT-1, 2, 3, OPT, BLOOM (LayerNorm)
Feed-forwardSwiGLU at dff ≈ 8d/3small, consistent gains at equal weightsGPT-3 (GELU), Nemotron 340B (squared ReLU)
PositionRoPE on queries and keysthe score depends only on the offsetT5 (relative bias), GPT-3 (learned absolute)
AttentionGQA8 key-value heads: 8 times less cache for LLaMA-2 70BGPT-3, LLaMA-2 7B (MHA); PaLM (MQA)
Ratiosdff = 4d or 8d/3; h dhead = d; d/L 100 to 200wide basins; systems limitsT5 11B (64 times, ratio 16, d/L 43)
Regularizationno dropout; weight decay 0.1one pass over the data; decay shapes optimizationQwen 14B (dropout 0.1)
Stabilityz-loss, QK-normkeep both softmaxes in rangesoft caps instead (Gemma 2)

The block, as Assignment 1 builds it, with GQA added. We ran it: the output shape is (2, 16, 512) and the parameter count matches Pblock plus two norm gains, 2,769,920.

python
import torch, torch.nn as nn, torch.nn.functional as F

class RMSNorm(nn.Module):
    def __init__(self, d, eps=1e-5):
        super().__init__(); self.eps = eps; self.g = nn.Parameter(torch.ones(d))   # gain only, no bias
    def forward(self, x):                                   # x: (B, T, d)
        return self.g * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)

def rope(x, base=10000.0):                                  # x: (B, heads, T, dh), pairs (0,1), (2,3), ...
    T, dh = x.shape[-2], x.shape[-1]
    theta = base ** (-torch.arange(0, dh, 2, dtype=torch.float32) / dh)     # (dh/2,)
    ang = torch.arange(T, dtype=torch.float32)[:, None] * theta            # (T, dh/2)
    c, s = ang.cos(), ang.sin()
    x0, x1 = x[..., 0::2], x[..., 1::2]
    return torch.stack((x0 * c - x1 * s, x0 * s + x1 * c), -1).flatten(-2)

class Block(nn.Module):
    def __init__(self, d, h, n_kv, d_ff):
        super().__init__()
        self.h, self.n_kv, self.dh = h, n_kv, d // h
        self.n1, self.n2 = RMSNorm(d), RMSNorm(d)
        self.wq = nn.Linear(d, h * self.dh, bias=False)
        self.wkv = nn.Linear(d, 2 * n_kv * self.dh, bias=False)   # fewer key/value heads (GQA)
        self.wo = nn.Linear(h * self.dh, d, bias=False)
        self.w1 = nn.Linear(d, d_ff, bias=False)                  # gate branch, goes through Swish
        self.v = nn.Linear(d, d_ff, bias=False)                   # linear branch
        self.w2 = nn.Linear(d_ff, d, bias=False)
    def attn(self, x):
        B, T, _ = x.shape
        q = self.wq(x).view(B, T, self.h, self.dh).transpose(1, 2)
        k, v = self.wkv(x).view(B, T, 2, self.n_kv, self.dh).permute(2, 0, 3, 1, 4)
        q, k = rope(q), rope(k)                                   # rotate queries and keys only
        k = k.repeat_interleave(self.h // self.n_kv, dim=1)      # each KV head serves a group
        v = v.repeat_interleave(self.h // self.n_kv, dim=1)
        y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
        return self.wo(y.transpose(1, 2).reshape(B, T, -1))
    def forward(self, x):                                         # pre-norm: the stream x is never normalized
        x = x + self.attn(self.n1(x))
        u = self.n2(x)
        return x + self.w2(F.silu(self.w1(u)) * self.v(u))

blk = Block(d=512, h=8, n_kv=2, d_ff=1376)                        # 8/3 x 512 = 1365, rounded up to a multiple of 32
print(blk(torch.randn(2, 16, 512)).shape)                            # torch.Size([2, 16, 512])
print(sum(p.numel() for p in blk.parameters()))                   # 2769920

Where it goes next. The lecture also covers sparse and sliding-window attention (GPT-3, Mistral), and newer models that mix full-attention layers with sliding-window ones. Lecture 4 replaces the dense feed-forward layer with many experts.

Keep going

Read next

The habit. For any new model card, read five switches and four ratios. Then compute its cache per token: 2 × L × nkv × dhead × 2 bytes.
Which set of choices does LLaMA-2 70B make?

Now teach it: press Present or Teach. Explain why the norm moved off the stream, what the gate costs, and why the KV cache fell eight times. Then go back to the 2017 block and predict which switch moves a bar before you flip it.

Architectures & Hyperparameters · Stanford CS336, Lecture 3
Previous: PyTorch and Resource Accounting · Next: Mixture of Experts · Course site · Back to Gleams