In Qwen2.5-32B, 87.1% of each layer's parameters ($16.2d^2$ out of $18.6d^2$) and most of its training and prefill FLOPs sit inside the feed-forward network (FFN). Yet once generation shifts to long-context autoregressive decoding, throughput stalls on HBM reads for the attention KV cache—whose weights make up just 12.9% of the block. The asymmetry is structural: FFN weights have fixed size independent of sequence length $N$, whereas cached $K$ and $V$ tensors grow linearly with $N$ and must stream back from HBM for every generated token.
Placing the modern Decoder-only + Pre-Norm + RMSNorm + SwiGLU + GQA block beside the original 2017 Transformer (Encoder-Decoder + Post-LN + ReLU + MHA) shows that nearly every sublayer, normalization site, activation, and head layout has changed. Very few of those swaps came from isolated theoretical breakthroughs; almost all of them balance three systems constraints: keeping training and prefill parallel at $O(1)$ sequence depth, conditioning gradients across dozens of layers, and cutting decode-time KV bytes per token so long contexts fit inside single-GPU HBM.
1. Sequence Parallelism and the Autoregressive Boundary#
The split between training and inference starts with sequence dependencies. Take a 4-token sentence ["I", "love", "deep", "learning"] stacked as row vectors $X = [x_1, x_2, x_3, x_4] \in \mathbb{R}^{4\times d}$. In a recurrent neural network, hidden state $h_t = f(h_{t-1}, x_t)$ explicitly depends on the previous step, so even when the entire sentence is already known at training time, computation must march serially along $h_1 \to h_2 \to h_3 \to h_4$ for $O(m)$ steps.
A Transformer stacks all token embeddings into rows of $X$ and expresses cross-token interaction through dense matrix multiplications followed by Softmax:
$$\begin{aligned}
Q &= XW_Q,\quad K = XW_K,\quad V = XW_V, \\
\mathrm{Out} &= \mathrm{Softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}} + M_{\text{causal}}\right)V
\end{aligned}$$
Because $M_{\text{causal}}$ is an additive mask, visible lower-triangular entries must hold $0$ (leaving logits unchanged) while masked upper-triangular entries hold $-\infty$ (driving $e^{-\infty} = 0$). This produces all four next-token predictions simultaneously inside one batched matrix multiply:
Query Position
I
love
deep
learning
Target Next Token
$t=1$ · I
0
$-\infty$
$-\infty$
$-\infty$
love
$t=2$ · love
0
0
$-\infty$
$-\infty$
deep
$t=3$ · deep
0
0
0
$-\infty$
learning
$t=4$ · learning
0
0
0
0
<EOS>
Serial depth across sequence length drops from $O(m)$ to $O(1)$ during both pretraining and prompt Prefill. During autoregressive Decode, token $t+1$ still cannot run until token $t$ is sampled, so generation stays inherently step-by-step; however, caching prior $(K, V)$ projections ensures each decode step multiplies only the newest query vector $q_t$ against stored prefix keys rather than recomputing the entire prefix at every step as naive uncached decoding would.
Figure 1: RNN sequential recurrence versus parallel self-attention over the full sequence.
In the 2017 sequence-to-sequence design, Encoder and Decoder played distinct roles. Consider English-to-German translation ("I love deep learning" $\to$ "Ich liebe tiefes Lernen"): the Encoder first reads the entire English source sentence via bidirectional self-attention (no causal mask), and the Decoder generates German tokens autoregressively via causal self-attention interleaved with Cross-Attention (where queries come from the Decoder state while keys and values come from the Encoder's final hidden states). Over time, Transformer models branched into three architectural lineages:
General LM, multi-turn chat, code, In-Context Learning
⤢ Zoom
Figure 2: Original Encoder–Decoder Transformer architecture coupling bidirectional encoding with causal decoding via cross-attention (arXiv:1706.03762). (Source: Vaswani et al., 2017, Fig. 1)
Tracing Fig. 1 highlights the structural rigidity of the original layout: Positional Encoding adds directly to the input and output embeddings at the base; yellow Post-LN Add & Norm boxes cap every sublayer inside both N× stacks; and a cross-stack arrow feeds the Encoder's top output into the Decoder's middle Multi-Head Attention (Cross-Attention). Splitting a $10\text{B}$ budget evenly into a $5\text{B}$ Encoder and a $5\text{B}$ Decoder looks balanced on fixed translation pairs, yet creates four practical inefficiencies on general-purpose LLM workloads:
Task-skewed parameter utilization: On long-context extraction ("100k document, 10-token summary"), the Decoder sits largely idle after the Encoder finishes; on open-ended code synthesis from a short prompt, half of the model's weights reside inside an Encoder that executes once and never contributes to generation. A Decoder-only stack keeps 100% of weights active across reading and generation, and supports In-Context Learning natively—few-shot demonstrations, instructions, and the final query sit directly inside the same causal prefix without an artificial encoder–decoder split.
Broken multi-turn prefix caching: Concatenating user turns and assistant responses in a Decoder-only conversation leaves earlier prefix KV tensors completely valid for the next turn. In an Encoder-Decoder architecture, appending prior Decoder outputs to a new prompt typically forces bidirectional re-encoding across conversation history.
Higher supervision density during pretraining: Next-Token Prediction computes a cross-entropy loss at nearly every token position in a batch, whereas classical span-corruption Encoder objectives backpropagate gradients primarily through a masked subset (often around 15%).
Uniform distributed sharding: Repeating one homogeneous causal block simplifies Tensor Parallelism (TP), Pipeline Parallelism (PP), and kernel fusion across large multi-node clusters. Encoders did not disappear; rather, they specialized into dense retrieval embeddings and continuous vision or audio frontends where bidirectional pooling is essential.
Two smaller engineering conventions from open training recipes are also worth noting (see Hugging Face's Smol Training Playbook): LLaMA-style blocks drop linear biases everywhere, whereas Qwen-style models sometimes retain $Q, K, V$ biases for shift and length adaptation; and tying input embeddings with lm_head saves $V \cdot d$ weights at 1B–3B scale, while larger models untie them for output capacity.
3. Attention vs. FFN Roles, Gradient Flow, and Revising $12d^2$#
Inside a single Decoder block, shifting normalization from Post-LN ($H^{(l)} = \mathrm{Norm}(H^{(l-1)} + F(H^{(l-1)}))$) to Pre-Norm stabilizes initialization dynamics. As Xiong et al. (2020, arXiv:2002.04745) proved, re-normalizing the summed residual stream after every layer in Post-LN produces abnormally large expected gradients near the output (top) layers—causing early training divergence unless guarded by careful learning-rate warmups—while gradients attenuate as they propagate back toward early input layers. Pre-Norm moves normalization to the sublayer entrance so updates add directly onto an unobstructed identity highway:
This layout keeps gradient magnitudes well-conditioned from step zero without fragile warmup schedules. Output projections ($W_O$ and $W_{\text{down}}$) are often scaled by $1/\sqrt{2L}$ at initialization—a practice introduced in GPT-2 (Radford et al., 2019) for $L$ layers ($2L$ residual branches)—to curb linear variance growth along the residual stream; even so, at large effective depths, unconstrained residual-norm accumulation still degrades late layers (examined in Keeping Deep Looped Transformers Stable: Norm Growth, Sandwich Norm, and TBPTT).
⤢ Zoom
Figure 3: Comparison of LayerNorm placement inside Post-LN (a) and Pre-LN (b) Transformer residual blocks (arXiv:2002.04745). (Source: Xiong et al., 2020, Fig. 1)
Comparing the two wiring diagrams directly shows why: in Post-LN (a), green Layer Norm boxes sit squarely across the grey vertical $x_l \to x_{l+1}$ trunk, rescaling the residual stream after every sublayer; in Pre-LN (b), Layer Norm moves inside the side branches ahead of Multi-Head Attention and FFN, leaving an unobstructed grey identity trunk from $x_l$ to $x_{l+1}$ with only addition nodes along the highway.
PYTHON
importmath, torchimporttorch.nn.functional as F
defcheck_norms(prenorm, L=32, d=64):
torch.manual_seed(0)
sc = 1.0 / math.sqrt(2 * L) if prenorm else1.0
ws = [torch.randn(d, d) * sc / math.sqrt(d) for _ inrange(L)]
h = F.rms_norm(torch.randn(1, d), (d,))
w_vars = []
for w in ws:
wv = w.clone().requires_grad_(True)
w_vars.append(wv)
if prenorm:
h = h + F.rms_norm(h, (d,)) @ wv
else:
h = F.rms_norm(h + h @ wv, (d,))
loss = (F.rms_norm(h, (d,)) if prenorm else h).sum()
loss.backward()
g0 = w_vars[0].grad.norm().item()
g_top = w_vars[-1].grad.norm().item()
returnround(g0, 2), round(g_top, 2), round(g_top / g0, 2)
print("Pre-LN (L1, L32, top/bot):", check_norms(True))
print("Post-LN (L1, L32, top/bot):", check_norms(False))
With GPT-2 $1/\sqrt{2L}$ residual scaling enabled, running this 32-layer initialization check gives a top-to-bottom weight gradient ratio of 1.82 (45.62 / 25.11) for Post-LN versus 0.91 (53.95 / 58.98) for Pre-LN—confirming Post-LN's top-heavy gradient spike against Pre-LN's near-balanced deep conditioning. (Without $1/\sqrt{2L}$ scaling, unchecked residual variance growth skews Pre-LN to 0.28, which explains why deep stacks and looped models still need explicit norm control.)
Within each Pre-Norm layer, the two sublayers perform complementary work—Attention handles cross-token mixing, while FFN handles per-token channel mixing and static factual memory:
Convex combination of Value vectors across context
Key-Value memory (Geva et al., 2021): "Eiffel Tower" matches a key and promotes "Paris"
If Removed
Collapses to bag-of-words; loses order & syntax
Repeated linear averaging triggers rank collapse
Decode KV Cost
Grows linearly with context $N$ and $n_{\text{kv}}$
Zero bytes added to the KV Cache
From a systems perspective, $d_{\text{model}}$ is the persistent residual highway carried across every projection, activation buffer, and KV tensor, whereas $d_{\text{ff}}$ is a temporary per-token workbench that expands inside FFN and projects straight back down without persisting across tokens. Modern architectures therefore keep $d_{\text{model}}$ disciplined and widen $d_{\text{ff}}$—rounding widths to 128- or 256-multiples for Tensor Core alignment (such as $14336 = 56 \times 256$ in LLaMA-3 8B and $27648 = 108 \times 256$ in Qwen2.5-32B)—so static parametric knowledge resides inside weights that cost zero KV cache bytes.
Model
Layers
$d$
Q / KV
$d_{\text{ff}}$
Layer Parameter Split
Transformer Base (2017)
6+6
512
8 / 8 (MHA)
2048 (4×)
$12d^2$ · Encoder; 2017 Decoder is $16d^2$ w/ Cross-Attn
LLaMA-3.2 1B
16
2048
32 / 8 (GQA)
8192 (4×)
High FFN ratio at small scale
LLaMA-3 8B
32
4096
32 / 8 (GQA)
14336 (3.5×)
GQA savings shift to $10.5d^2$ FFN
Qwen2.5-32B
64
5120
40 / 8 (GQA)
27648 (5.4×)
Wide FFN expands static capacity
LLaMA-3 70B / 405B
80 / 126
8,192 / 16,384
64/8, 128/8
28,672 / 53,248
8× and 16× head sharing cuts KV
PYTHON
deflayer_params_ratio(d, n_q, n_kv, d_ff, swiglu=True):
attn = (2 + 2 * (n_kv / n_q)) * d * d
ffn = (3if swiglu else2) * d * d_ff
tot = attn + ffn
return tot / (d * d), attn / tot, ffn / tot
print([round(x, 3) for x in layer_params_ratio(4096, 32, 8, 14336)])
print([round(x, 3) for x in layer_params_ratio(5120, 40, 8, 27648)])
Note
Counting Parameters Beyond $12d^2$: The textbook $12d^2$ estimate only holds for a single-attention Encoder layer combining MHA ($4d^2$) with a two-matrix $4d$ ReLU FFN ($8d^2$); a 2017 Decoder layer adds Cross-Attention ($+4d^2$) to hit $16d^2$. Moving to LLaMA-3 8B ($4:1$ Q/KV shrinks $W_K, W_V$ to $0.25d^2$ each, cutting Attention to $2.5d^2$; $3.5d$ SwiGLU takes $10.5d^2$) brings the total to $13.0d^2$ (80.8% FFN), while Qwen2.5-32B ($40Q/8KV$, $d_{\text{ff}}=5.4d$) reaches $18.6d^2$ ($2.4d^2$ Attention / $16.2d^2$ FFN).
Figure 4: Per-layer parameter share shift from classic 12d² to LLaMA-3 8B (13.0d²) and Qwen2.5-32B (18.6d²).
4. The Arithmetic Behind RMSNorm, SwiGLU, and GQA#
LayerNorm requires two global reductions across the hidden dimension to compute its mean $\mu$ and variance $\sigma^2$, plus a learnable additive bias $\beta$. Even when fused into a single-pass Welford kernel, the operator must still accumulate two coupled statistics and pay mean-gradient coupling ($\partial\mu/\partial x_j = 1/d$) across every coordinate during backpropagation. RMSNorm (Zhang & Sennrich, 2019) drops both mean centering and $\beta$ after showing that re-scaling invariance captures virtually all optimization stability in residual architectures:
Why does skipping mean subtraction stay stable? Geometrically, RMSNorm projects activations onto a fixed-radius hypersphere of radius $\sqrt{d}$ (scaled per channel by $g$), while subsequent linear layers and residual additions naturally absorb any mean shift along the constant direction. In the backward pass, eliminating $\mu$ decouples the radial gradient from mean-centering terms and simplifies reduction kernels.
Testing $x = [3, 4],\; g = [1, 1]$ by hand: LayerNorm subtracts $\mu = 3.5$ to obtain $[-0.5, +0.5]$ and divides by $\sigma = 0.5$ to return $[-1, +1]$; RMSNorm divides straight by $\sqrt{(9 + 16)/2} \approx 3.536$, yielding $[0.849, 1.131]$. At the standalone operator level, dropping one global reduction and bias load makes normalization kernels ~10%–40% faster under HBM bandwidth bounds; once fused with residual additions via TorchInductor or custom CUDA kernels, however, norms only account for ~1%–3% of total 70B step time—the real win is simpler kernels and decoupled radial gradients at parity loss.
4.2 SwiGLU: Matching Parameter Count With Three Matrices#
SwiGLU (Shazeer, 2020) splits the FFN input projection into two parallel linear maps—a smooth $\mathrm{SiLU}(z) = z \cdot \sigma(z)$ gate multiplied elementwise against a linear value stream—before projecting back down. Notably, Shazeer explicitly noted lacking a first-principles explanation for why SwiGLU consistently beats ReLU and GELU, framing it as a robust empirical finding across controlled runs rather than a theoretical derivation:
importtorchimporttorch.nn.functional as F
defswiglu(x, w_gate, w_up, w_down):
return (F.silu(x @ w_gate) * (x @ w_up)) @ w_down
x = torch.tensor([[1.0, 0.0]])
wg = torch.tensor([[2.0, -2.0, 2.0], [0.0, 0.0, 0.0]])
wu = torch.tensor([[1.0, 2.0, 4.0], [0.0, 0.0, 0.0]])
wd = torch.tensor([[1.0, 0.0], [1.0, 1.0], [1.0, 1.0]])
print([round(v, 2) for v in swiglu(x, wg, wu, wd)[0].tolist()])
Adding a third linear projection increases the FFN matrix count by +50% (2A -> 3A). Keeping $d_{\text{ff}} = 4d$ would inflate FFN parameters by the same 50%, so the standard parameter-matched choice scales width down by $\frac{2}{3}$ to $\frac{8}{3}d \approx 2.67d$, keeping total weights identical at $3 \times \frac{8}{3}d^2 = 8d^2$ (at $d = 3072$, a $12288$-wide ReLU FFN and an $8192$-wide SwiGLU both contain 75.5M weights). Pushing $d_{\text{ff}}$ back up to $3.5d$ in LLaMA-3 8B deliberately reinvests the parameters freed by GQA. On the training memory side, note that without activation checkpointing, the backward pass must retain both gate and up intermediate tensors (plus the pre-SiLU activation) across the elementwise product—raising per-token FFN activation storage at matched $d_{\text{ff}}$ relative to single-branch ReLU/GELU, only roughly offset when $d_{\text{ff}}$ is scaled by $2/3$.
Why does shrinking intermediate width to $\frac{2}{3}$ not hurt expressivity? Instead of relying on simple threshold neurons (ReLU(xW)), SwiGLU trades one-third of the hidden width for a bilinear multiplicative soft logical AND gate: a feature fires strongly only when both the content pathway (up) and context gate (gate) agree. For polysemous disambiguation such as "Apple" AND "Tech", take up = [10, 8] (fruit sense vs. company sense) and context gate gate = [0.02, 0.95]: their product [0.20, 7.60] suppresses the irrelevant sense and isolates the tech concept cleanly.
Calculation
Worked Verification (4-Step Trace): Take $d_{\text{model}} = 2, d_{\text{ff}} = 3$:
Parallel lifts: Let $x W_{\text{up}} = [1, 2, 4]$ and $x W_{\text{gate}} = [2, -2, 2]$.
SiLU gating: $\mathrm{SiLU}(2) \approx 1.7616$ and $\mathrm{SiLU}(-2) \approx -0.2384$, giving $[1.7616, -0.2384, 1.7616]$.
Elementwise product: $[1\times 1.7616,\; 2\times(-0.2384),\; 4\times 1.7616] = [1.7616, -0.4768, 7.0464]$, rounding to [1.76, -0.48, 7.05] (index 1 is smoothly damped without ReLU's zero-gradient dead zone).
Down-projection: With $W_{\text{down}} = \begin{pmatrix} 1 & 0 \\ 1 & 1 \\ 1 & 1 \end{pmatrix}$, $[1.76, -0.48, 7.05] W_{\text{down}} =$ [8.33, 6.57] (matching the exact intermediate $[8.3312, 6.5696]$ to two decimals).
Figure 5: Modern Pre-Norm Decoder Block with RMSNorm and three-matrix SwiGLU.
4.3 GQA: Balancing MHA Quality Against MQA Bandwidth#
At decode time, every generated token streams cached $K$ and $V$ tensors back from HBM across all layers. Evaluate LLaMA-3 8B ($L = 32$ layers, $d_{\text{head}} = 128$, BF16 = 2 bytes/element) at $128\text{K}$ ($131{,}072$ tokens): each token per KV head stores $2 \times 128 \times 2 = 512\text{ B}$, so one KV head occupies $64\text{ MiB/head}$ (using binary $\text{MiB} = 2^{20}\text{ B}$ and $\text{GiB} = 2^{30}\text{ B}$). Comparing the three head layouts:
MHA-32($n_{\text{kv}} = 32$): $2.0\text{ GiB/layer}$, totaling $64\text{ GiB}$ of KV Cache alone across 32 layers—which pushes past a single 80 GB decimal ($\approx 79.65\text{ GiB}$ usable) H100 once ~15 GiB of BF16 weights and runtime activations are added;
GQA-8 ($n_{\text{kv}} = 8$, $4:1$ grouping, Ainslie et al., 2023): $512\text{ MiB/layer}$, totaling $16\text{ GiB}$ (-75% in both capacity and decode HBM read traffic), fitting alongside model weights on a single 80 GB H100;
MQA-1($n_{\text{kv}} = 1$): $64\text{ MiB/layer}$, totaling $2\text{ GiB}$ (-96.9%), though Ainslie et al. show pure MQA can lose quality on complex multi-fact recall without careful uptraining.
⤢ Zoom
Figure 6: Query, Key, and Value head grouping across Multi-Head (MHA), Grouped-Query (GQA), and Multi-Query Attention (MQA) (arXiv:2305.13245). (Source: Ainslie et al., 2023, Fig. 2)
Notice the exact head counts in the schematic above: the middle panel draws 8 Query heads grouped over 4 KV heads (a 2:1 ratio), whereas LLaMA-3 8B uses 32Q / 8KV = 4:1, flanked by 1-to-1 Multi-head on the left and all-to-1 Multi-query on the right. Ainslie et al. also demonstrated a practical conversion recipe: mean-pooling existing MHA key and value projection heads within each group followed by 5% uptraining compute recovers nearly full MHA quality at MQA-like decoding speeds.
Caveat
Caveat: KV-Head Replication When $\text{TP} > n_{\text{kv}}$ Under Tensor Parallelism (TP), attention heads are sharded across GPUs. If a model has $n_{\text{kv}} = 8$ KV heads and is served on $\text{TP} = 16$ ranks (or $n_{\text{kv}} = 4$ on $\text{TP} = 8$), each rank needs at least one complete KV head locally, forcing the runtime to replicate KV heads across ranks. Past $\text{TP} > n_{\text{kv}}$, per-GPU KV memory stops shrinking with additional TP degrees, requiring Context Parallelism (CP) or Data Parallelism (DP) to scale capacity further.
Still, the 2023 LLaMA template is not the end of the road. Three architectural shifts are already chipping away at it: first, pure Pre-Norm alone cannot stop deep attention-logit spikes, making QK-Norm near-universal and motivating branch-inner post-norms (as in Gemma 2 and OLMo-2); second, GQA-8 KV bandwidth remains too costly at 100K+ contexts, yielding ground to MLA and Gated DeltaNet / KDA hybrids; and third, dense FFNs remain a poor storage medium for static facts, accelerating the split toward fine-grained MoE and external lookup tables like Engram.
Figure 7: Proportional per-layer KV cache sizes across MHA, GQA-8, and MQA (LLaMA-3 8B @ 128K BF16).