LLM Field Guide 02 — Inside the Transformer: Position, Attention, and Feed-Forward Layers¶
Every LLM you'll deploy in 2026 is the same machine: one decoder block, copied 28 to 100+ times, with an embedding table on one end and a vocabulary-sized classifier on the other. Inside each block, attention lets tokens read each other and a feed-forward network rewrites each token on its own, while RoPE tells attention who sits where. Learn the block once and you can read any model's config.json, predict its memory footprint, and say where its 8 billion parameters live.
In this post:
- Position — why attention is blind to word order, and how RoPE fixes it with real numbers
rope_thetaand context extension — PI, YaRN, Llama 3 scaling, and the vLLM flag- The decoder block — residual stream, RMSNorm, pre-norm, causal mask
- Attention with real numbers — Q, K, V, multi-head, the n² cost, FlashAttention
- The feed-forward network — expand, activate, contract; ReLU to SwiGLU; what it stores and costs
- Where 8 billion parameters live — counted from the config, then built in 40 lines
- 2017 vs 2026, and reading any config.json
LLM Field Guide — all 12 posts
Attention is blind to word order¶
Post 01 ended with the matrix X: one vector per token for "The cat sat". Those vectors say what each token is, nothing about where it sits. Attention scores tokens against each other with dot products, and a dot product doesn't care where the vectors came from. Shuffle the input and you get the same outputs, just shuffled.
Proof in ten lines, using bare self-attention (no positions, no mask) on the toy X:
import torch
X = torch.tensor([[1.0, 0.0, 0.5, 0.2], # "The"
[0.5, 1.0, 0.2, 0.8], # " cat"
[0.2, 0.5, 1.0, 0.3]]) # " sat"
def attend(X): # bare self-attention, no positions, no mask
w = torch.softmax(X @ X.T / X.shape[1] ** 0.5, dim=-1)
return w @ X
a = attend(X) # "The cat sat"
b = attend(X[[2, 1, 0]]) # "sat cat The"
print(a[1]) # tensor([0.5393, 0.6008, 0.5093, 0.5021])
print(b[1]) # tensor([0.5393, 0.6008, 0.5093, 0.5021])
print(torch.allclose(a[1], b[1])) # True
" cat" gets exactly the same representation in both orders. To the model, the sentence is a bag of tokens until you add position.
(The causal mask, covered below, leaks a weak position signal: Kazemnejad et al. showed decoder-only models learn some order with no explicit encoding, "NoPE"1. That's why some 2026 models mix in NoPE layers.)
From added vectors to RoPE: four generations of position signals¶
| Generation | Method | Used by | Extrapolates past training length? |
|---|---|---|---|
| 2017 | Sinusoidal absolute: add fixed sin/cos waves to the embedding | Original Transformer2 | Poorly |
| 2018–2020 | Learned absolute: add a learned row per position | GPT-2 (1,024 × 768 table)3, BERT | No: position 1,025 has no row |
| 2020–2022 | Relative bias: distance-based bias on attention scores | T54, ALiBi5 | ALiBi: yes, by design |
| 2021→today | RoPE: rotate Q and K by a position-dependent angle | Llama, Qwen, DeepSeek, Gemma, gpt-oss | With scaling (PI, YaRN) |
Absolute schemes faded because they mix "what" and "where" in the same numbers, and because language cares about relative distance, not absolute index. "The adjective right before this noun" matters; "the token at index 4,817" doesn't. RoPE won: every open-weight family in this series uses it.
RoPE: rotate, don't add¶
Rotary Position Embedding (RoPE), from Su et al.'s RoFormer paper6, doesn't add anything. It rotates. Split a vector into pairs of dimensions, treat each pair as a point on a 2D plane, and rotate it by an angle proportional to the token's position m:
x' = x·cos(φ) − y·sin(φ) φ = m · θᵢ
y' = x·sin(φ) + y·cos(φ) θᵢ = 1 / base^(2i/d) (base = 10,000 originally)
Worked example: " cat" at position 2¶
Take " cat" = [0.5, 1.0, 0.2, 0.8] with d = 4: pair 0 is (0.5, 1.0), pair 1 is (0.2, 0.8). Base frequencies are θ₀ = 1/10000^0 = 1.000 rad and θ₁ = 1/10000^(2/4) = 0.010 rad.
Pair 0, angle 2 × 1.000 = 2.000 rad cos = −0.416, sin = 0.909
x' = 0.5×(−0.416) − 1.0×0.909 = −1.117
y' = 0.5×0.909 + 1.0×(−0.416) = 0.038
Pair 1, angle 2 × 0.010 = 0.020 rad cos ≈ 0.9998, sin ≈ 0.020
x' = 0.2×0.9998 − 0.8×0.020 = 0.184
y' = 0.2×0.020 + 0.8×0.9998 = 0.804
After RoPE, " cat" at position 2 is [−1.117, 0.038, 0.184, 0.804]. Pair 0 swung almost 115 degrees; pair 1 barely moved (about 1 degree).
Rotation preserves length (the norm is 1.389 before and after), so RoPE never distorts what the embedding encodes.
The payoff: dot products depend only on distance¶
Rotate a query at position m and a key at position n, and their dot product depends only on the gap m − n. Rotating both by the same extra amount cancels out. Verify it with a 128-dim head (the size Llama 3.1 and Qwen3 use):
import torch
def rope(x, pos, base=10_000):
d = x.shape[-1]
inv_freq = 1.0 / (base ** (torch.arange(0, d, 2).float() / d))
ang = pos * inv_freq
x1, x2 = x[..., 0::2], x[..., 1::2] # interleaved pairs
out = torch.empty_like(x)
out[..., 0::2] = x1 * torch.cos(ang) - x2 * torch.sin(ang)
out[..., 1::2] = x1 * torch.sin(ang) + x2 * torch.cos(ang)
return out
torch.manual_seed(0)
q, k = torch.randn(128), torch.randn(128)
for m, n in [(5, 3), (105, 103), (10005, 10003), (3, 5)]:
print(f"q@{m} · k@{n} = {rope(q, m) @ rope(k, n):.4f}")
Same gap, same score (to float32 precision); flip the direction and it changes, so the model also knows which token came first. That's relative position for free: no extra parameters, no change to the attention formula.
Where RoPE actually goes¶
In a real model, RoPE is applied to queries and keys inside every attention layer, after their projections, and never to values. Position should affect who attends to whom, not what gets passed along.
Two RoPE layouts: interleaved vs half-split
The code above rotates interleaved pairs (d₀,d₁), (d₂,d₃), … as in RoFormer. Hugging Face's Llama implementation uses rotate_half, pairing dimension i with i + d/2. Both are valid, but weights trained with one layout produce garbage with the other. If a checkpoint ported between frameworks (Meta's code, GGUF, Transformers) outputs noise, check this first.
The frequency spectrum: a clock with 64 hands¶
A 128-dim head has 64 pairs, so 64 rotation speeds. The fast hands resolve nearby tokens precisely; the slow hands distinguish tokens thousands of positions apart. A pair's wavelength, 2π / θᵢ, is how many tokens it takes to rotate a full circle:
base (rope_theta) | Used by | Fastest wavelength | Slowest wavelength | Pairs slower than 8K tokens |
|---|---|---|---|---|
| 10,000 | Original RoPE; Gemma 4 sliding-window layers | 6.3 tokens | 54,410 tokens | 14 of 64 |
| 500,000 | Llama 3 / 3.17 | 6.3 tokens | 2.56M tokens | 29 of 64 |
| 1,000,000 | Qwen38; Gemma 4 global layers9 | 6.3 tokens | 5.06M tokens | 30 of 64 |
| 10,000,000 | Qwen3.5 (64 rotated dims per head)10 | 6.3 tokens | 38.0M tokens | 17 of 32 |
A bigger base slows the slow hands, so more pairs stay unambiguous at long distances. With base 10,000 the slowest pair wraps around in about 54K tokens, and positions beyond that start to look alike. Meta raised Llama 3's base to 500,000 "to better support longer contexts"7; Qwen3 raised it from 10,000 to 1,000,000 during long-context pretraining8.
Stretching the context window¶
A model trained up to length L has only seen rotation angles up to L·θᵢ. Feed it more and the slow pairs hit angles it has never seen, and quality collapses. Context extension remaps positions so long inputs land back inside the familiar angle range.
| Method | Idea | Reported result |
|---|---|---|
| Position Interpolation (PI), 2023 | Divide every position by the extension factor | LLaMA to 32,768 tokens with under 1,000 fine-tuning steps12 |
| YaRN, 2023 | Interpolate only slow pairs, leave fast pairs alone, rescale attention temperature | 10x fewer tokens and 2.5x fewer steps than prior methods13 |
| Llama 3 scaling, 2024 | Three bands: fast untouched, slow divided by 8, smooth blend between | Llama 3.1: 8K → 128K |
How Llama 3.1 does it, concretely¶
Llama 3.1 8B's config.json ships this block14:
"rope_theta": 500000.0,
"rope_scaling": {
"rope_type": "llama3",
"factor": 8.0,
"low_freq_factor": 1.0,
"high_freq_factor": 4.0,
"original_max_position_embeddings": 8192
}
From the Transformers implementation:
- Wavelength under 2,048 tokens (8,192 ÷ 4): unchanged. These handle local word order. 29 of 64 pairs.
- Wavelength over 8,192 tokens (8,192 ÷ 1): frequency divided by 8, so 128K positions fit the trained angle range. Another 29 pairs.
- The 6 pairs in between: a smooth blend.
Scaling alone isn't enough; the model also has to practice. Meta pretrained at 8K, then grew the context in stages up to 128K at the end of pretraining; for 405B that took six stages and roughly 800B tokens7.
What 2026 models ship with¶
| Model | Native / original length | Scaling | Max context |
|---|---|---|---|
| Llama 3.1 8B | 8,192 | llama3, factor 8 (built in) | 131,07214 |
| Qwen3-8B | 32,768 | YaRN, factor 4 (opt-in) | 131,07215 |
| gpt-oss-20b | 4,096 | YaRN, factor 32 (built in) | 131,07217 |
| Qwen3.5-9B | 262,144 | YaRN, factor 4 (opt-in) | 1,010,00010 |
Turning on YaRN in vLLM¶
Qwen3-8B's YaRN is opt-in: it natively handles 32,768 tokens and you enable 4x only when you need it15. Current vLLM dropped the old --rope-scaling flag; use --hf-overrides with rope_parameters20:
vllm serve Qwen/Qwen3-8B \
--hf-overrides '{"rope_parameters": {"rope_type": "yarn", "factor": 4.0,
"original_max_position_embeddings": 32768, "rope_theta": 1000000}}' \
--max-model-len 131072
Static YaRN taxes short prompts
Engines apply YaRN with a fixed factor regardless of input length. Qwen warns this can hurt shorter texts and suggests factor: 2.0 if your typical context is around 65,536 tokens15. Don't enable 4x "just in case" on a chat workload of 2K-token prompts.
A model that accepts 128K tokens doesn't use 128K well; post 04 covers advertised vs effective context and what each token of context costs in GPU memory. Before you trust a long context:
- Read
max_position_embeddingsand therope_scaling/rope_parametersblock: trained length vs extended length - Know whether scaling is built in (Llama 3.1, gpt-oss) or opt-in (Qwen3) — opt-in means you enable it
- Set
--max-model-lento what you need, not the maximum - When porting weights, confirm the RoPE layout and
rope_thetamatch
2026 RoPE variants you'll see in config files¶
| Variant | What it does | Example |
|---|---|---|
| Partial RoPE | Rotate only some dims per head | Qwen3.5-9B: partial_rotary_factor: 0.25 = 64 of 256 dims10 |
| Per-layer-type RoPE | Different bases for local and global layers | Gemma 4: 10,000 local; 1,000,000 + partial rotation global9 |
| Decoupled RoPE | Position in a separate Q/K slice, since RoPE clashes with MLA's KV compression19 | DeepSeek-V3: qk_rope_head_dim: 64 + qk_nope_head_dim: 12818 |
| NoPE layers | Some layers have no position signal | Llama 4 "iRoPE"; Scout advertises 10M tokens21 |
| Multimodal RoPE | Rotary dims split across time, height, width | Qwen3.5: mrope_section: [11, 11, 10]11 |
Sliding-window layers and MLA themselves are explained in post 04.
The big picture: one forward pass through Llama 3.1 8B¶
The Transformer comes from "Attention Is All You Need"2. Its central idea is attention: every token can pull information directly from every earlier token. Here's the whole forward pass with real sizes from Llama 3.1 8B's config14:
"The cat sat"
│
▼
┌──────────────────────────┐
│ Tokenizer │ → [791, 8415, 7731] 3 token IDs
└────────────┬─────────────┘
▼
┌──────────────────────────┐
│ Embedding lookup │ → X: 3 × 4,096 128,256-row table
└────────────┬─────────────┘
▼
┌──────────────────────────┐ ┐
│ RMSNorm │ │
│ Attention (RoPE inside) │ │ each block reads from and adds to
│ + residual │ │ the same 3 × 4,096 "residual stream"
│ RMSNorm │ │ × 32 blocks
│ Feed-forward (SwiGLU) │ │
│ + residual │ │
└────────────┬─────────────┘ ┘
▼
┌──────────────────────────┐
│ Final RMSNorm │
│ LM head: 4,096 → 128,256 │ → logits: 3 × 128,256 one score per vocab token
└────────────┬─────────────┘
▼
softmax over the last row → P(next token | "The cat sat")
The shape never changes inside the stack: 3 × 4,096 in and out of every block. Only the embedding and the LM head change shape.
Generation uses only the last row of logits; training uses every row (row 1 predicts " cat", row 2 " sat"), as post 03 shows.
Shorthand from here on (Llama 3.1 8B values): d = 4,096 hidden size, L = 32 blocks, H = 32 heads of d_h = 128, d_ff = 14,336, V = 128,256; ⊙ is element-wise multiply.
Why decoder-only? The 2017 paper had an encoder and a decoder. Decoder-only won because predicting the next token scales on any unlabeled text, and the same model then does every task by prompting. Encoders like BERT survive in search, as many embedding and reranking models.
Inside one decoder block¶
A modern decoder block is two sublayers in the same wrapper:
a = x + Attention(RMSNorm(x)) ← sublayer 1: tokens exchange information
out = a + FFN(RMSNorm(a)) ← sublayer 2: each token is transformed on its own
Attention moves information between positions; the FFN processes each position independently. Everything else is plumbing that keeps the numbers stable.
The residual stream: a whiteboard every layer writes to¶
The x + … parts are residual connections (He et al., 201522): each sublayer computes a change and adds it on. Think of the token vectors as a shared whiteboard, the residual stream. Each sublayer reads the board and writes an update back; information from the embedding can survive all 32 blocks if nothing needs to change it. During backpropagation, gradients flow straight back along the + path. Without residuals, a 32-block model is very hard to train at all.
Normalization: keeping the numbers in range¶
Magnitudes drift over dozens of blocks, so each token's vector is rescaled before every sublayer. LayerNorm (2017) subtracts the mean and divides by the standard deviation; RMSNorm, used by Llama, Qwen, Gemma, DeepSeek, and gpt-oss, drops the mean and the shift:
Worked on the vector attention will produce for " sat" later in this post, x = [0.565, 0.540, 0.533, 0.464], with γ = 1, β = 0:
LayerNorm → [ 1.05, 0.39, 0.20, −1.64 ] re-centered to mean 0, variance 1
RMSNorm → [ 1.072, 1.025, 1.012, 0.881 ] mean(x²) = 0.27755, √ = 0.5269; rescaled only
RMSNorm rescales magnitude without re-centering, one fewer statistic per token per layer. Its authors reported LayerNorm-level quality with 7%–64% lower running time23. Llama 3.1 8B has 65 of them: two per block plus a final norm, each with 4,096 learned γ values.
Pre-norm, not post-norm¶
The 2017 paper normalized after adding the residual: x = Norm(x + Sublayer(x)). Every modern LLM normalizes before each sublayer, x = x + Sublayer(Norm(x)), leaving the residual path untouched from embedding to output. Pre-norm trains stably at depth and can skip the learning-rate warmup post-norm needs24.
Some models add extra norms: Qwen3 puts QK-Norm, an RMSNorm on each head's queries and keys, in every block "to ensure stable training"8. You'll see it as q_norm and k_norm in the module tree.
The causal mask: no peeking at the future¶
A decoder blocks each token from attending to anything after it, or next-token training would be trivial: the model would copy the answer from the next position. Before softmax, every score where the key comes after the query gets −∞, so its weight becomes exactly zero. You'll see it in step 4 of the worked example below.
The mask's payoff: one forward pass produces a next-token prediction at every position at once. A 4,096-token training sequence gives 4,096 examples per pass.
Attention with real numbers: Q, K, V on "The cat sat"¶
Attention is the only place in a transformer where tokens talk to each other. In "The animal didn't cross the street because it was too tired", the embedded "it" is the same vector as anywhere else; attention lets it ask which earlier tokens matter for me? and pull in a weighted blend. The weights always sum to 1: it's a soft lookup.
Every token gets projected into three vectors by learned matrices:
| Vector | Made by | Plain meaning |
|---|---|---|
Query q | x · W_Q | "What am I looking for?" |
Key k | x · W_K | "What do I advertise about myself?" |
Value v | x · W_V | "What do I hand over if you pick me?" |
Keys decide who gets attention; values decide what gets passed. Splitting them lets a token be easy to find for one reason and contribute something else entirely. The whole mechanism is one line2:
Step 1 — Project to Q, K, V¶
Use post 01's toy X. To follow by hand, set W_K and W_V to the identity (K = V = X) and let W_Q swap column pairs:
W_Q = Q = X · W_Q = K = V = X =
| 0 1 0 0 | | 0.0 1.0 0.2 0.5 | | 1.0 0.0 0.5 0.2 | ← "The"
| 1 0 0 0 | | 1.0 0.5 0.8 0.2 | | 0.5 1.0 0.2 0.8 | ← " cat"
| 0 0 0 1 | | 0.5 0.2 0.3 1.0 | | 0.2 0.5 1.0 0.3 | ← " sat"
| 0 0 1 0 |
In a trained model, gradient descent discovers what each query looks for.
Step 2 — Score every query against every key¶
For "sat":
q_sat · k_The = 0.5×1.0 + 0.2×0.0 + 0.3×0.5 + 1.0×0.2 = 0.85
q_sat · k_cat = 0.5×0.5 + 0.2×1.0 + 0.3×0.2 + 1.0×0.8 = 1.31
q_sat · k_sat = 0.5×0.2 + 0.2×0.5 + 0.3×1.0 + 1.0×0.3 = 0.80
Steps 3 and 4 — Scale by √d_k, then mask¶
Divide the full Q·Kᵀ by √4 = 2, then set future cells to −∞:
Q·Kᵀ scaled + masked
The cat sat The cat sat
"The" | 0.20 1.44 0.85 | "The" | 0.10 −∞ −∞ |
"cat" | 1.44 1.32 1.31 | "cat" | 0.72 0.66 −∞ |
"sat" | 0.85 1.31 0.80 | "sat" | 0.43 0.66 0.40 |
Why scale? If q and k components have mean 0 and variance 1, their dot product has variance d_k2. With d_k = 128, raw scores swing by roughly ±11, softmax collapses onto one token, and gradients vanish. Dividing by √d_k puts the variance back near 1.
Step 5 — Softmax: scores become percentages¶
softmax(xᵢ) = e^xᵢ / Σ e^xⱼ, and e^−∞ = 0. For the "sat" row:
e^0.43 = 1.537 e^0.66 = 1.935 e^0.40 = 1.492 sum = 4.964
weights = [0.31, 0.39, 0.30] ("The", "cat", "sat")
"sat" puts 39% of its attention on "cat". The "The" row is [1.0, 0, 0]: the first token can only see itself.
Step 6 — Weighted sum of values¶
out_sat = 0.31 × [1.0, 0.0, 0.5, 0.2] ← V_The
+ 0.39 × [0.5, 1.0, 0.2, 0.8] ← V_cat
+ 0.30 × [0.2, 0.5, 1.0, 0.3] ← V_sat
= [0.565, 0.540, 0.533, 0.464]
"sat" now carries information about the cat before it. This exact vector goes into the feed-forward network later in this post.
Check it yourself¶
# pip install "numpy>=2.0"
import numpy as np
X = np.array([[1.0, 0.0, 0.5, 0.2], # "The"
[0.5, 1.0, 0.2, 0.8], # " cat"
[0.2, 0.5, 1.0, 0.3]]) # " sat"
W_Q = np.array([[0,1,0,0],[1,0,0,0],[0,0,0,1],[0,0,1,0]], dtype=float)
Q, K, V = X @ W_Q, X, X # W_K = W_V = identity
scores = Q @ K.T / np.sqrt(K.shape[1]) # scale by sqrt(d_k)
mask = np.triu(np.full((3, 3), -np.inf), k=1) # hide the future
w = np.exp(scores + mask)
w /= w.sum(axis=1, keepdims=True) # softmax per row
print(w.round(2)) # row 3: [0.31 0.39 0.3 ]
print((w @ V)[2].round(3)) # [0.564 0.54 0.534 0.464]
(The third decimal differs because the hand version rounded first.) Try it: delete mask and "The" spreads [0.24, 0.44, 0.33] over tokens it should never see; double every number in X and the weights get peakier.
Multi-head attention: many relationships at once¶
One set of W_Q, W_K, W_V learns one notion of relevance; language needs many (subject–verb, pronoun–referent, previous token). Multi-head attention runs H smaller attentions in parallel, each with its own projections, then concatenates the results:
head_i = Attention(X·W_Qⁱ, X·W_Kⁱ, X·W_Vⁱ) each head has d_k = d / H dims
output = Concat(head_1, …, head_H) · W_O
The original Transformer used 8 heads of 64 dims on a 512-wide model2; Llama 3.1 8B uses 32 query heads of 128 dims on 4,09614.
Split our 4 dims into 2 heads of 2 dims (head 1 sees dims 1–2, head 2 sees dims 3–4; scale is √2):
| Head 1 (dims 1–2) | Head 2 (dims 3–4) | |
|---|---|---|
| "sat" vector in this head | [0.2, 0.5] | [1.0, 0.3] |
| Scaled scores vs The / cat / sat | 0.14 / 0.42 / 0.21 | 0.40 / 0.31 / 0.77 |
| Softmax weights | 0.29 / 0.39 / 0.32 | 0.30 / 0.27 / 0.43 |
| Head output for "sat" | [0.55, 0.55] | [0.63, 0.41] |
| What it "noticed" | the subject, "cat" | itself, the verb |
Concatenate to [0.55, 0.55, 0.63, 0.41] and multiply by W_O. The heads disagreed about what mattered, and the model keeps both views. Nobody assigns head roles; they specialize during training, and many stay hard to interpret.
H heads of d/H dims cost the same as one head of d dims, so the extra views are free.
Production models also let several query heads share one key/value head (Llama 3.1 8B: 32 query heads, 8 KV heads). That's Grouped-Query Attention, a KV-cache optimization explained in post 04.
Attention weights are not explanations: a high weight says where information came from in one layer, not why the model answered what it did.
The n² cost and FlashAttention¶
For n tokens, Q·Kᵀ is an n × n matrix per head, per layer. Double the context, quadruple the score matrix. At Llama 3.1 8B's full 131,072-token context14:
score matrix per head = 131,072 × 131,072 ≈ 1.7 × 10¹⁰ entries
in BF16 (2 bytes each) ≈ 32 GiB ← for ONE head in ONE layer
model has 32 heads × 32 layers
No GPU holds that. The fix that applies to every model is to never materialize the matrix.
A GPU has small, fast on-chip memory (SRAM) and large, slower main memory (HBM). Naive attention round-trips the n × n matrix through HBM several times. Attention is usually limited by memory traffic, not math.
FlashAttention (Dao et al., 2022) computes attention in tiles that fit in SRAM with a running ("online") softmax, so the full matrix never exists in HBM. It's exact, not an approximation: about 3× faster on GPT-2 at 1K tokens25; FlashAttention-3 hits up to 740 TFLOPs/s FP16 on H100 (75% utilization)26.
You rarely call it directly. PyTorch's scaled_dot_product_attention dispatches to a FlashAttention-2 or memory-efficient kernel automatically27, and serving engines ship their own fused kernels (post 10). FlashAttention removes the memory blowup, not the compute: the work still grows with n². The other levers (fewer K/V heads, windowed and hybrid layers, the KV cache) live in post 04.
The feed-forward network: expand, activate, contract¶
Attention is communication; the FFN is computation. After attention, "sat" carries a blend of "The" and "cat". The FFN rewrites that vector with no access to any other token. It runs the exact same weights on every position independently, which makes it trivially parallel.
The 2017 FFN is two linear layers with a ReLU between them2:
That 4× expansion was the default for years: a wider hidden layer gives more "detectors" to test the input against. The activation is the only thing stopping a deep network from being a shallow one — without it, x·W₁·W₂ collapses into a single matrix.
Worked example: the FFN on "sat"¶
Start from attention's output x = [0.565, 0.540, 0.533, 0.464]. Expand d = 4 to h = 8 with ReLU, biases zero. Each column of W₁ is one hidden neuron's detector:
W₁ (4 × 8) =
| 1.0 0.5 -0.5 1.0 -1.0 0.5 1.0 -0.5 |
| 0.5 1.0 0.5 0.5 -0.5 -0.5 0.0 0.5 |
| -0.5 0.5 1.0 0.5 0.5 0.5 -1.0 -0.5 |
| 0.0 -0.5 0.5 -0.5 0.5 1.0 0.5 1.0 |
h₁ = 0.565×1.0 + 0.540×0.5 + 0.533×(−0.5) + 0.464×0.0 = 0.568
h₅ = 0.565×(−1.0) + 0.540×(−0.5) + 0.533×0.5 + 0.464×0.5 = −0.336 ← negative
h = [0.568, 0.858, 0.752, 0.870, −0.336, 0.744, 0.264, 0.184]
ReLU(h) = [0.568, 0.858, 0.752, 0.870, 0.000, 0.744, 0.264, 0.184]
Neuron 5 was looking for a pattern that isn't in "sat", so ReLU silences it. Then contract with an 8 × 4 W₂, each row saying how one neuron pushes the outputs:
W₂ (8 × 4) =
| 0.5 0.2 0.1 0.1 | ← neuron 1
| 0.1 0.3 0.2 0.1 |
| 0.2 0.1 0.3 0.1 |
| 0.1 0.2 0.1 0.3 |
| 0.0 0.0 0.0 0.0 | ← neuron 5 (silenced anyway)
| 0.1 0.1 0.1 0.2 |
| 0.2 0.1 0.1 0.1 |
| 0.1 0.1 0.2 0.1 |
out₁ = 0.568×0.5 + 0.858×0.1 + 0.752×0.2 + 0.870×0.1 + 0 + 0.744×0.1 + 0.264×0.2 + 0.184×0.1 = 0.753
FFN("sat") = [0.753, 0.739, 0.679, 0.672]
That vector is added to x through the residual connection, so the FFN computes an update, not a replacement.
From ReLU to SwiGLU¶
The 2017 FFN isn't what you'll find in Llama, Qwen, or Gemma. The activation got smoother, and a gate was added.
ReLU has a hard corner and a flat dead zone: a neuron stuck negative gets zero gradient and can stop learning. GELU (z·Φ(z)) and SiLU (z·σ(z)) let a little negative signal through and curve smoothly, which trains more reliably: at z = −0.336, ReLU gives 0.000, GELU −0.124, SiLU −0.140.
Shazeer's 2020 "GLU Variants Improve Transformer" tested FFNs where one projection is multiplied element-wise by an activated second projection; some variants beat plain ReLU or GELU28. The SiLU-gated version, SwiGLU, won:
| Matrix | Hugging Face name | Shape (Llama 3.1 8B) | Job |
|---|---|---|---|
W_gate | gate_proj | 4,096 × 14,336 | decides how much of each hidden neuron passes |
W_up | up_proj | 4,096 × 14,336 | computes what each neuron carries |
W_down | down_proj | 14,336 × 4,096 | contracts back to model width |
Those names are exactly what you'll see in checkpoints and LoRA target_modules. The Transformers implementation is one line: down_proj(act_fn(gate_proj(x)) * up_proj(x))29.
Reuse W₁ as W_gate and add an illustrative W_up:
| Neuron | x·W_gate | ReLU (classic) | SiLU(gate) | x·W_up | SwiGLU = SiLU × up |
|---|---|---|---|---|---|
| 1 | 0.568 | 0.568 | 0.363 | 0.784 | 0.285 |
| 2 | 0.858 | 0.858 | 0.602 | 0.781 | 0.470 |
| 5 | −0.336 | 0.000 | −0.140 | 1.101 | −0.154 |
- Neuron 5 isn't dead. SiLU passes a small negative value, so gradient still flows.
- Each neuron's output is a product of two learned signals. The gate opens or closes a neuron per token.
Why 14,336 and not 16,384¶
A third matrix adds 50% more FFN parameters at the same width. To compare fairly, LLaMA used "a dimension of 2/3 4d instead of 4d"30: three matrices at (8/3)·d cost the same as two at 4d.
| Model | d_model | FFN hidden | Ratio | Params per FFN |
|---|---|---|---|---|
| Classic 4× GELU at 8B width | 4,096 | 16,384 | 4.0× | 134.2M (2 matrices) |
SwiGLU at 8/3·d | 4,096 | ~10,923 | 2.67× | 134.2M (3 matrices) |
| Qwen3-8B16 | 4,096 | 12,288 | 3.0× | 151.0M (3 matrices) |
| Llama 3.1 8B14 | 4,096 | 14,336 | 3.5× | 176.2M (3 matrices) |
Modern 8B models sit above the 8/3 baseline, spending extra parameters on FFN width.
What the FFN stores and what it costs¶
FFN layers act as key-value memories (Geva et al., 2021): W₁ columns are keys that fire on textual patterns, lower layers shallow and upper layers semantic; W₂ rows are values that nudge the output toward tokens that tend to follow31. Neuron 5 above was a key that didn't match "sat".
Factual recall concentrates in middle-layer FFNs (Meng et al., 2022): causal tracing located it, and a rank-one update to FFN weights (ROME) edited a single fact like "The Eiffel Tower is in…"32.
A useful model, not a filing cabinet
Knowledge is distributed across neurons and layers, and attention helps retrieve it. The takeaway: most capacity for what a model knows sits in FFN weights, which is why fine-tuning usually targets gate_proj, up_proj, down_proj alongside attention (post 08).
FFN vs attention compute: the 21K crossover¶
A matrix multiply costs about 2 FLOPs per weight per token (one multiply, one add)33. Per token, per layer in Llama 3.1 8B:
FFN: 2 × 176.2M weights ≈ 352 MFLOPs
Attention projections: 2 × 41.9M weights (Q,K,V,O) ≈ 84 MFLOPs
Attention over context: 4 × n × 4,096 (QKᵀ + weights·V, n = tokens so far)
4 × n × 4,096 = 352,000,000 → n ≈ 21,500 tokens
Below roughly 21K tokens of context, the FFN is the biggest compute cost per generated token; above it, attention takes over. Short-prompt chat is dominated by FFN matmuls; long-document workloads by attention.
There's also a memory cost: generating one token reads every FFN weight from GPU memory, 5.64B × 2 bytes ≈ 11.3 GB per decode step for Llama 3.1 8B in BF16, about 70% of the bytes that cap single-stream speed. Why that makes decode memory-bandwidth-bound is post 04's topic; quantization and Mixture of Experts (which splits the FFN into many experts and runs only a few per token) attack it in post 09.
Where 8 billion parameters live¶
You don't need 16 GB of weights to count parameters. Instantiate the architecture on PyTorch's meta device, which allocates shapes but no memory:
# pip install "transformers>=5.0" torch
import torch
from collections import defaultdict
from transformers import AutoConfig, AutoModelForCausalLM
cfg = AutoConfig.from_pretrained("Qwen/Qwen3-8B") # ungated; or a Llama 3.1 repo you can access
with torch.device("meta"):
model = AutoModelForCausalLM.from_config(cfg)
groups = defaultdict(int)
for name, p in model.named_parameters():
key = next((k for k in ["embed_tokens", "lm_head", "self_attn", "mlp", "norm"] if k in name), name)
groups[key] += p.numel()
print(dict(groups), sum(groups.values()))
Results (Transformers 5.22.1):
| Component | Llama 3.1 8B | Share | Qwen3-8B | Share |
|---|---|---|---|---|
| Embedding table | 525,336,576 | 6.5% | 622,329,856 | 7.6% |
| Attention (all blocks) | 1,342,177,280 | 16.7% | 1,509,958,656 | 18.4% |
| Feed-forward (all blocks) | 5,637,144,576 | 70.2% | 5,435,817,984 | 66.4% |
| Norms | 266,240 | 0.0% | 299,008 | 0.0% |
| LM head | 525,336,576 | 6.5% | 622,329,856 | 7.6% |
| Total | 8,030,261,248 | 8,190,735,360 |
Two-thirds or more of an 8B model is feed-forward weights; attention, the famous part, is under a fifth. Geva et al. said the same in 2021: "Feed-forward layers constitute two-thirds of a transformer model's parameters"31. Normalization is a rounding error.
One Llama 3.1 block from the module dump:
self_attn.q_proj (4096, 4096) 16.8M
self_attn.k_proj (1024, 4096) 4.2M ← 8 KV heads × 128 = 1,024
self_attn.v_proj (1024, 4096) 4.2M
self_attn.o_proj (4096, 4096) 16.8M
mlp.gate_proj (14336, 4096) 58.7M
mlp.up_proj (14336, 4096) 58.7M
mlp.down_proj (4096, 14336) 58.7M
input_layernorm (4096,)
post_attention_layernorm (4096,)
───────
218.1M per block × 32 = 6.98B
Two numbers fall out:
- Weight memory: 8.03B × 2 bytes (BF16) ≈ 16.1 GB before any KV cache.
- Compute per token: ~2 FLOPs per parameter33, so ~16 GFLOPs per generated token for an 8B dense model, plus attention's context-dependent share.
Trace the shapes for "The cat sat" and you'll find attention scores ([32, 3, 3]) are the only place tokens interact, and the only shape that grows with T². Everything else stays [3, 4096], except the SwiGLU's [3, 14336] interior and the final [3, 128256] logits.
Build one block in 40 lines¶
A complete, runnable Llama-style decoder block: RMSNorm, causal attention with shared KV heads, SwiGLU, pre-norm residuals. RoPE is left out for brevity; the build-from-scratch post adds it.
# pip install "torch>=2.5" (enable_gqa needs PyTorch 2.5+)
import torch
import torch.nn as nn
import torch.nn.functional as F
class RMSNorm(nn.Module):
def __init__(self, d, eps=1e-5):
super().__init__()
self.eps, self.weight = eps, nn.Parameter(torch.ones(d))
def forward(self, x):
return self.weight * x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
class Attention(nn.Module): # causal, shared KV heads; RoPE omitted
def __init__(self, d, n_heads, n_kv_heads):
super().__init__()
self.h, self.kv, self.hd = n_heads, n_kv_heads, d // n_heads
self.q_proj = nn.Linear(d, n_heads * self.hd, bias=False)
self.k_proj = nn.Linear(d, n_kv_heads * self.hd, bias=False)
self.v_proj = nn.Linear(d, n_kv_heads * self.hd, bias=False)
self.o_proj = nn.Linear(n_heads * self.hd, d, bias=False)
def forward(self, x):
B, T, _ = x.shape
q = self.q_proj(x).view(B, T, self.h, self.hd).transpose(1, 2)
k = self.k_proj(x).view(B, T, self.kv, self.hd).transpose(1, 2)
v = self.v_proj(x).view(B, T, self.kv, self.hd).transpose(1, 2)
out = F.scaled_dot_product_attention(q, k, v, is_causal=True, enable_gqa=True)
return self.o_proj(out.transpose(1, 2).reshape(B, T, -1))
class SwiGLU(nn.Module):
def __init__(self, d, d_ff):
super().__init__()
self.gate_proj = nn.Linear(d, d_ff, bias=False)
self.up_proj = nn.Linear(d, d_ff, bias=False)
self.down_proj = nn.Linear(d_ff, d, bias=False)
def forward(self, x):
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
class DecoderBlock(nn.Module):
def __init__(self, d, n_heads, n_kv_heads, d_ff):
super().__init__()
self.input_layernorm = RMSNorm(d)
self.self_attn = Attention(d, n_heads, n_kv_heads)
self.post_attention_layernorm = RMSNorm(d)
self.mlp = SwiGLU(d, d_ff)
def forward(self, x):
x = x + self.self_attn(self.input_layernorm(x)) # read, attend, write back
x = x + self.mlp(self.post_attention_layernorm(x)) # read, transform, write back
return x
block = DecoderBlock(d=4096, n_heads=32, n_kv_heads=8, d_ff=14336) # Llama 3.1 8B shapes
print(f"{sum(p.numel() for p in block.parameters()):,} parameters") # 218,112,000
x = torch.randn(1, 3, 4096) # "The cat sat"
print(block(x).shape) # torch.Size([1, 3, 4096])
218,112,000 parameters: exactly one Llama 3.1 8B block. The module names match Hugging Face's Llama implementation, so you can line them up against a real checkpoint.
What changed from 2017 to 2026¶
The skeleton is the 2017 design. Nearly every component inside it has been swapped.
| Component | 2017 Transformer | 2026 default | Why |
|---|---|---|---|
| Norm placement | Post-norm | Pre-norm | Stable training at depth24 |
| Norm type | LayerNorm | RMSNorm (+ QK-Norm in some) | Cheaper, same quality23 |
| Position | Sinusoidal, added to input | RoPE on Q and K | Relative positions, extendable context |
| Attention kernel | Materialized n × n | FlashAttention-style fused kernels | Memory traffic, not math, is the limit |
| Attention heads | Full multi-head | Shared KV heads (GQA) or latent KV (MLA) | Smaller KV cache (post 04) |
| FFN | ReLU, 4× expansion | SwiGLU, ~3–3.5× expansion | Better quality per parameter28 |
| Dense vs sparse | Dense | Dense for small models; MoE for large | More parameters at the same per-token compute (post 09) |
| Attention span | Every layer sees everything | Increasingly hybrid local/global/linear layers | Long context without quadratic cost everywhere (post 04) |
Hybrid models still use this post's block in every layer: norm, mixing sublayer, residual, norm, FFN, residual. Only the mixing sublayer changes.
Read any config.json in 60 seconds¶
The architecture maps one-to-one onto config fields:
-
hidden_size,num_hidden_layers→dandL -
num_attention_heads/num_key_value_heads→ query heads and shared KV heads (32/8 = 4 per group) -
head_dim→ per-head size; usuallyd / H, but not always (Qwen3.5 uses 256) -
intermediate_size→ FFN widthd_ff, and its ratio tohidden_size -
hidden_act→silumeans SwiGLU in Llama/Qwen-style models;mlp_biasusuallyfalse -
vocab_size,tie_word_embeddings→ embedding and LM head size (post 01) -
rope_theta,rope_scaling/rope_parameters,max_position_embeddings→ context behavior -
layer_types,sliding_window→ a hybrid attention stack (post 04) -
num_local_experts/n_routed_experts,num_experts_per_tok→ an MoE;dtype,quantization_config→ bytes per weight (post 09)
Quick estimate for a dense model with untied embeddings:
params ≈ L × (2·d² + 2·d·d_kv + 3·d·d_ff) + 2·V·d where d_kv = H_kv × d_h
Llama 3.1 8B: attention 2·4096² + 2·4096·1024 = 41.9M
SwiGLU 3·4096·14336 = 176.2M
per block 218.1M × 32 = 6.98B
+ embedding and LM head 2·128,256·4,096 = 1.05B → 8.03B
Summary¶
| Piece | Llama 3.1 8B | Rule to keep |
|---|---|---|
| RoPE on Q and K | rope_theta 500,000 | q·k depends only on m − n; values are never rotated |
| Context extension | llama3 scaling, 8K → 128K | Smallest YaRN factor that covers p99; static YaRN hurts short prompts |
| Residual stream + pre-norm RMSNorm | 3 × 4,096, 65 norms | Only the embedding and LM head change shape; this is what makes 30–100+ blocks trainable |
| Causal mask | Upper triangle → −∞ | One pass = a prediction at every position |
| Attention | 32 heads × 128 dims | softmax(QKᵀ/√d_k + mask)·V; the only token-to-token mixing |
| n² + FlashAttention | 32 GiB per head at 128K if materialized | Memory traffic, not math, is the limit; never materialize n × n |
| SwiGLU FFN | 14,336 wide, 176.2M per block | 66–70% of parameters; dominates compute below ~21.5K tokens |
| Whole model | 32 × 218.1M + 1.05B = 8.03B | ~2 bytes (BF16) and ~2 FLOPs per parameter per token |
Next: Post 03 — Training and Generation: you've seen every matrix in the forward pass. Now see where their numbers come from, and how a token gets picked from the logits.
Go deeper:
- Building an LLM from Scratch in PyTorch — the full model in working code: attention, RoPE on Q and K, SwiGLU, and an MoE layer
- Master Generative AI — Part 1: Foundation — neurons, activation functions, gradients, and training loops
-
Kazemnejad et al., The Impact of Positional Encoding on Length Generalization in Transformers (NeurIPS 2023) — decoder-only models without positional encoding (NoPE). ↩
-
Vaswani et al., Attention Is All You Need (2017) — sinusoidal encoding (§3.5), scaled dot-product attention and the
1/√d_kargument, 8 heads of 64 ond_model = 512, ReLU FFN withd_ff = 2048. ↩↩↩↩↩↩ -
OpenAI, GPT-2 config.json —
n_positions: 1024,n_embd: 768. ↩ -
Raffel et al., Exploring the Limits of Transfer Learning with a Unified Text-to-Text Transformer (2019) — relative position biases. ↩
-
Press, Smith, Lewis, Train Short, Test Long: Attention with Linear Biases Enables Input Length Extrapolation (ICLR 2022) — a 1.3B model trained at 1,024 tokens extrapolates to 2,048. ↩
-
Su et al., RoFormer: Enhanced Transformer with Rotary Position Embedding (2021). ↩
-
Llama Team, Meta, The Llama 3 Herd of Models (2024) — §3.2: vocabulary = 100K tiktoken + 28K extra tokens; RoPE base 500,000 "to better support longer contexts"; §3.4.2: 8K → 128K in six stages, ~800B tokens for 405B. ↩↩↩
-
Qwen Team, Qwen3 Technical Report (2025) — §2: pre-norm RMSNorm, SwiGLU, QK-Norm "to ensure stable training"; §3.2: RoPE base raised from 10,000 to 1,000,000. ↩↩↩
-
Google, Gemma 4 E4B config.json — sliding layers
rope_theta: 10000; full-attention layersrope_theta: 1000000,proportional,partial_rotary_factor: 0.25. ↩↩ -
Qwen, Qwen3.5-9B model card — head dim 256, rotary dim 64,
rope_theta: 10000000; native 262,144, up to 1,010,000 with YaRN factor 4. ↩↩↩ -
Qwen, Qwen3.5-9B config.json —
mrope_section: [11, 11, 10],mrope_interleaved: true. ↩ -
Chen et al., Extending Context Window of Large Language Models via Positional Interpolation (2023) — up to 32,768 tokens "with minimal fine-tuning (within 1000 steps)." ↩
-
Peng et al., YaRN: Efficient Context Window Extension of Large Language Models (2023) — "10x less tokens and 2.5x less training steps than previous methods." ↩
-
Llama 3.1 8B
config.json— hidden 4096, 32 layers, 32 Q / 8 KV heads, head_dim 128, intermediate 14336, SiLU, vocab 128,256, untied;rope_theta: 500000.0,llama3scaling factor 8 from 8,192,max_position_embeddings: 131072(mirror of meta-llama/Llama-3.1-8B; the official repo is gated). Parameter counts and RoPE band logic from Transformers 5.22.1. ↩↩↩↩↩↩ -
Qwen, Qwen3-8B model card, "Processing Long Texts" — native 32,768 tokens; YaRN factor 4.0 for 131,072; static YaRN may impact shorter texts; use factor 2.0 for ~65,536. ↩↩↩
-
Qwen, Qwen3-8B config.json — 36 layers, hidden 4096, intermediate 12288, 32 Q / 8 KV heads, head_dim 128, SiLU, vocab 151,936, untied embeddings. ↩
-
OpenAI, gpt-oss-20b config.json — YaRN factor 32 from 4,096 to 131,072. ↩
-
DeepSeek, DeepSeek-V3 config.json — YaRN factor 40 from 4,096 to 163,840;
qk_rope_head_dim: 64,qk_nope_head_dim: 128. ↩ -
DeepSeek-AI, DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model (2024), §2.1.3 — decoupled rotary position embedding for MLA. ↩
-
vLLM, Context extension — old
--rope-scaling"is no longer supported"; use--hf-overrides. ↩ -
Meta, The Llama 4 herd (2025) — "interleaved attention layers without positional embeddings" (iRoPE); Scout 10M context. ↩
-
He et al., Deep Residual Learning for Image Recognition (2015). ↩
-
Zhang, Sennrich, Root Mean Square Layer Normalization (NeurIPS 2019) — comparable performance to LayerNorm while reducing running time "by 7%~64% on different models." ↩↩
-
Xiong et al., On Layer Normalization in the Transformer Architecture (ICML 2020) — pre-LN Transformers can be trained without the learning-rate warmup stage. ↩↩
-
Dao et al., FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness (2022) — tiling between HBM and SRAM; 3× speedup on GPT-2 at 1K sequence length. ↩
-
Shah et al., FlashAttention-3 (2024) — up to 740 TFLOPs/s FP16 on H100 (75% utilization). ↩
-
PyTorch,
torch.nn.functional.scaled_dot_product_attention— FlashAttention-2 and memory-efficient backends;enable_gqa. ↩ -
Shazeer, GLU Variants Improve Transformer (2020) — gated linear unit variants in the FFN sublayer, including SwiGLU, outperform ReLU/GELU. ↩↩
-
Hugging Face Transformers,
modeling_llama.py—LlamaMLPwithgate_proj,up_proj,down_proj. ↩ -
Touvron et al., LLaMA: Open and Efficient Foundation Language Models (2023) — SwiGLU with a hidden dimension of 2/3 · 4d. ↩
-
Geva et al., Transformer Feed-Forward Layers Are Key-Value Memories (2021) — FFNs are two-thirds of parameters; keys match textual patterns; lower layers shallow, upper layers semantic. ↩↩
-
Meng et al., Locating and Editing Factual Associations in GPT (2022) — middle-layer FFN modules mediate factual predictions; Rank-One Model Editing (ROME). ↩
-
Kaplan et al., Scaling Laws for Neural Language Models (2020), §2.1 — forward pass ≈ 2N FLOPs per token for a model with N non-embedding parameters, plus a context-dependent attention term. ↩↩
Discussion
Have thoughts on this post? Share them below — questions, corrections, or your own experience are all welcome.





