One Forward Route: Reading Llama 3 Through GPT-2
GPT-2 and the original Llama 3 share a readable backbone: Token lookup → repeated Blocks → final normalization → vocabulary scores. Their differences concern position handling, normalization, attention-head organization, the MLP, and input/output weight sharing.
This comparison concerns OpenAI GPT-2 and Meta’s original Llama 3, not every derivative model. Small matrices are teaching values, not pretrained weights or training results. Diagrams omit training Dropout. Formulas use row vectors: an input multiplies a weight shaped [input features, output features].
Connect the whole network first
| Location | GPT-2 | Original Llama 3 |
|---|---|---|
| Model entrance | Token embeddings plus learned position embeddings | Token lookup; position enters Q/K later |
| Normalization | LayerNorm | RMSNorm |
| Position handling | Position vectors enter at the beginning | RoPE on Q/K in each layer; V is not rotated |
| Attention heads | MHA: one K/V head per Q head | GQA: several Q heads share a K/V group |
| MLP | Two projections with GELU between them | Two input projections, SiLU gating, output projection |
| Input/output tables | The same parameter E | Independent E and W_out |
This compares structures, not the measured effect of replacing one component. See the implementations of OpenAI GPT-2 and Meta Llama 3.
Use teaching dimensions B=2, T=5, D=16: two sequences, five positions each, sixteen features per position. Lookup produces [2,5,16]. A Block may expand features or split heads internally, but returns the same shape for the next layer.
Normalization: first identify the axis
For [B,T,D], both normalizations here process each Token’s D features separately. The example contains ten independent sixteen-dimensional vectors. It does not combine all ten Tokens when computing a mean. Keep this separate from BatchNorm’s cross-example statistics.
For a fixed vector x=[x₁,…,x_D]:
Mean μ = Σx_d / DVariance σ² = Σ(x_d − μ)² / DStd. dev. σ = √σ²RMS = √(Σx_d² / D)Variance measures deviations from the mean; RMS measures size relative to zero. The denominator is D, not the D−1 used in an unbiased sample variance. These statistics are computed from the current input. They are neither trainable parameters nor running averages across batches.
LayerNorm: center, then rescale
y_d = γ_d × (x_d − μ) / √(σ² + ε) + β_dSubtract the mean, divide by the stabilized standard deviation, then apply a learned scale γ and shift β per feature. Both have D parameters, shared across examples and positions within this module.
Ignoring ε, when σ is nonzero, the core (x−μ)/σ has zero mean and unit variance. With ε, its variance is σ²/(σ²+ε). After feature-specific γ and β, the final output need not have either zero mean or unit variance.
RMSNorm: rescale without centering
r_ε = √(Σx_d² / D + ε)y_d = γ_d × x_d / r_εThe Llama 3 implementation discussed here has no β. No mean subtraction does not mean no trainable parameters: γ still learns, while the denominator is computed from the current input.
Ignoring ε and γ, a nonzero vector’s x/RMS(x) has unit mean square, not necessarily unit variance. Dividing uniformly by a positive number preserves direction. The subsequent feature-specific γ can change direction, and γ is not constrained to be positive.
The same input, calculated both ways
Take x=[1,1,3,3], unit γ and zero β, temporarily ignoring ε:
μ = (1+1+3+3)/4 = 2x−μ = [−1,−1,1,1]σ² = (1+1+1+1)/4 = 1RMS² = (1+1+9+9)/4 = 5
LayerNorm core = [−1,−1,1,1]RMSNorm core = [1,1,3,3]/√5 ≈ [0.447214,0.447214,1.341641,1.341641]Adding 100 to every element leaves the LayerNorm core unchanged. RMSNorm becomes approximately [0.990148,0.990148,1.009755,1.009755]. LayerNorm removes the common offset; RMSNorm includes it in the overall size used by its denominator.
★ Why RMS² = σ² + μ²
Expand the definition of variance. No normal-distribution assumption is needed:
σ² = Σ(x_d−μ)² / D = Σx_d²/D − 2μ(Σx_d/D) + Σμ²/D = RMS² − 2μ² + μ² = RMS² − μ²
Therefore RMS² = σ² + μ².The final sum contains D identical copies of μ². After division by D it is still μ². The two cores can therefore be written as:
LN: (x_d−μ) / √(σ²+ε)RMS: x_d / √(σ²+μ²+ε)For zero mean and matching ε, the cores agree. Full modules agree only if their learned affine parameters also agree. Learning γ after controlling the scale lets the model adjust individual features; it does not restore every input’s original RMS.
Read step 03 in the full diagram: the left column centers before dividing by the standard deviation; the right divides directly by the RMS. Steps 13 and 17 repeat these rules with separate parameters. Hand calculations omit ε temporarily; the actual formulas retain it for cases such as the zero vector.
Why control scale, and why omit centering?
In bias-free projections, scaling the input by ten scales Q and K by ten and can scale their dot products by one hundred. Softmax is sensitive to this: [1,2] gives roughly [0.269,0.731], while [10,20] gives [0.000045,0.999955].
Normalization helps control this sensitivity. Ignoring ε, both cores are invariant to positive uniform scaling; only LayerNorm is invariant to a common offset. Omitting centering is a tradeoff in information processing and computation. The RMSNorm paper supports this simplification in its studied tasks; its speedup figures cannot be transferred directly to Llama 3.
Normalization is not gradient clipping and does not guarantee the absence of gradient problems. The denominator depends on x, so differentiation must include that dependence. The Pre-Norm bypass also carries the original input: removing the mean in one branch does not discard it from the entire Block.
QKV: project the whole input before splitting heads
Let U be the normalized input. Compute Q=UW_Q, K=UW_K, V=UW_V, adding biases where present. Each projected feature can use all D input features. The input is not first cut into isolated pieces for separate projections.
For B=T=1, D=4, H=2, d_h=2, the left side of the numerical diagram produces:
Q_flat = [5,6,−2,−1]K_flat = [4,7, 3, 6]V_flat = [4,5,−1,−2]After splitting:
| Head | Q | K | V |
|---|---|---|---|
| 0 | [5,6] | [4,7] | [4,5] |
| 1 | [−2,−1] | [3,6] | [−1,−2] |
# q_flat is already the projection outputq = q_flat.reshape(B, T, H, head_dim)q = q.transpose(1, 2) # [B,H,T,head_dim]Reshape splits the feature axis; transpose exchanges position and head axes. Neither changes element values nor adds parameters. A one-Token example hides the sequence-layout difference, but each head retains the full T axis. Head index, Token position, and within-head feature index are separate coordinates.
Llama 3 then rotates Q/K. The rotation acts on pairs of dimensions within a head; it does not create new heads. See the mathematical companion on rotation and RoPE.
GQA: share K/V, compute each Q head separately
MHA has H Q heads and H K/V groups. GQA has fewer K/V groups, G. For four Q heads and two groups, Q₀/Q₁ use group 0 and Q₂/Q₃ use group 1.
The mapping g(h)=floor(h/2) is fixed by the structure. Q does not compare groups to choose one. Attention weights determine how much to read from each permitted position inside the assigned group.
A^(h) = softmax_rows(Q^(h) K^(g(h))ᵀ / √d_h + M)H^(h) = A^(h) V^(g(h))For D=8, d_h=2, MHA’s W_K is [8,8], while GQA’s is [8,4]; the same holds for W_V. GQA generates only two groups from the projection onward. It does not generate four and discard two. All eight input features still participate.
Two Q vectors reading the same K/V
Consider query position 1, allowed to read positions 0 and 1. Q/K below are already past position handling, isolating the sharing relationship:
q₀ = [1,0] q₁ = [0,1]K = [[1,0], V = [[10,0], [0,1]] [0,20]]For q₀, dot products are [1,0]; dividing by √2 gives [0.707107,0]. Both positions are allowed. Exponentials are [2.028115,1], yielding:
A₀ ≈ [0.669762,0.330238]H₀ = 0.669762×[10,0] + 0.330238×[0,20] ≈ [6.697615,6.604769]q₁ reverses the score order:
A₁ ≈ [0.330238,0.669762]H₁ ≈ [3.302385,13.395231]Each position weight multiplies that position’s entire V vector. Contributions are then summed feature by feature. A’s two numbers refer to positions, not features. Q/K determine A; V supplies content in the subsequent H=AV.
In the diagram, position 0 cannot read the future, so masking makes the second weight zero. With only one allowed position, its weight must be one; that does not establish that the heads learned identical reading patterns.
Sharing K/V does not merge Q, A, or H. Fewer K/V representations can reduce the inference KV cache, but four Q heads still compute attention separately. Total attention computation does not necessarily fall in proportion to the number of K/V groups. A single group is the MQA special case. The GQA paper discusses this structural tradeoff.
Put the single-head calculation back into four heads
This diagram uses B=1, T=2, D=8, d_h=2, a different teaching configuration from the single-Token projection example. Follow head 1 through steps 03–05: MHA reads its own group 1, while GQA reads shared group 0. K, V, and the resulting output can therefore differ. Step 06 lists all four output heads. GQA group values were deliberately chosen to match selected MHA groups for comparison; this does not mean actual GQA generates four groups and discards two.
Return to the main path: concatenate, project, add
For [B,H,T,d_h]=[2,4,5,4]:
Head outputs H [2,4,5,4] → transpose [2,5,4,4] → reshape [2,5,16] = C → projection O = CW_O (+ b_O) → residual R = X + OConcatenation has no trainable parameters. W_O mixes features from different heads at each position. It does not sum over Token positions and is not the final vocabulary projection.
For two head outputs [1,2] and [3,4]:
C = [1,2,3,4]W_O = [[1,0, 1, 0], [0,1, 0, 1], [1,0,−1, 0], [0,1, 0,−1]]O = CW_O = [4,6,−2,−2]If the original Block input is X=[10,20,30,40], the first residual result is R=[14,26,28,38]. Add X, not Norm₁(X). Then:
Z = Norm₂(R)F = MLP(Z)Y = R + FThe second bypass adds R, not X again and not Z. A residual connection has the form x+F(x): F adjusts the representation; it is not a loss or prediction error. Y is the complete Block output passed to the next layer.
A gated MLP still preserves the outer shape
GPT-2 uses GELU(ZW₁+b₁)W₂+b₂. The Llama structure here uses:
a = ZW_gv = ZW_vF = (SiLU(a) ⊙ v)W_dBoth branches receive the complete Z with different parameters. Intermediate width may expand, but the output returns to D for addition to R. The MLP processes each position independently; its input already includes context read by attention. Positionwise processing does not mean context-free processing.
SiLU is an elementwise function; SwiGLU includes two projections and a product. Its gate is not restricted to 0–1. See the structural companion on SiLU and SwiGLU.
After all Blocks: final normalization and vocabulary scores
| Module | Input | Next computation | Parameters |
|---|---|---|---|
| Norm₁ | This layer’s X | QKV projections | First set in this layer |
| Norm₂ | First residual result R | MLP | Second set in this layer |
| Norm_f | Last Block output | lm_head | Separate set outside Blocks |
Repeated computation rules do not imply shared parameters. Let final normalized features be H_f:[B,T,D], with vocabulary size V:
GPT-2: logits = H_f Eᵀ E: [V,D]Llama: logits = H_f W_outᵀ W_out: [V,D]Both outputs: [B,T,V]GPT-2 uses the same E parameter for input lookup and output scoring. Gradients from both paths add. The original Llama 3 uses independent E/W_out, but row j still refers to the same Token ID. Independent parameters do not imply different vocabularies.
For h=[1,2] and E=[[1,0],[0,1],[1,1]], scores are [1,2,3]. An independent output table [[2,0],[0,3],[−1,1]] gives [2,6,1]. The weights change; the dot-product rule does not.
Sharing saves one V×D table. Independent tables provide separate learning freedom at the cost of parameters and training state. Neither formula alone proves better quality. Logits are scores: training uses them in cross-entropy; generation usually selects from the last position’s scores.
Four routes for revisiting the network
- Data: IDs → vectors → QKV → A → H → O → R → MLP → Y → logits.
- Parameters: projection weights and γ/β learn; current QKV, statistics, and attention weights are computed data.
- Positions: attention aggregates across positions; normalization and the MLP act positionwise; the causal mask defines allowed reads.
- Bypasses: preserve X for the first addition and R for the second; Norm_f and vocabulary projection follow all Blocks.
The two companion articles expand RoPE’s rotations and SwiGLU’s branches. Both remain specific components on this same network map.