Topic 09 of 62 · Inside the Transformer block
FFNs and residual connections
EasyWhy does a Transformer need feed-forward layers and residual connections in addition to attention?
1 · Start with the intuition
Attention and the feed-forward network (FFN) divide the work of a Transformer block along two orthogonal axes: attention moves information across token positions, while the FFN applies a nonlinear feature transformation within each token position independently. Residual connections wrap both sublayers (y = x + F(x)) so gradients have a direct identity highway back to early layers and each sublayer only needs to learn a refinement Δx to the running representation.
2 · How the mechanism works
Mechanism step 1 of 3 · no question to answer
Mix across tokens (Attention)
Each token gathers context from eligible earlier tokens via attention and adds the result to the residual stream.
Next, we will look at: Transform within each token (FFN). Move on when this operation makes sense.
Visualizing the behavior
Pre-norm Transformer block: two residual corrections
Where block parameters live (d = 4096, full MHA, no biases)
Derived- Attention projections (4d²)
- FFN (8d²)
3 · The governing equation
Standard FFN(x) = W₂ φ(W₁x + b₁) + b₂
SwiGLU FFN(x) = W_down ( Swish(W_gate x) ⊙ W_up x )
Pre-norm block: x_{ℓ+1} = x_ℓ + F_ℓ(N_ℓ(x_ℓ)), J_ℓ = I + J_{F_ℓ} J_{N_ℓ}
Across layers: ∂x_L/∂x₀ = J_{L−1} ⋯ J₀ (still a product; expanding it gives a sum of paths, one of them I)Notation: x ∈ ℝ^d is a single token’s hidden state, φ is an elementwise nonlinearity, and ⊙ is elementwise multiplication. The same FFN weights are shared across all token positions.
What does the FFN’s nonlinearity add? Not the network’s only nonlinearity: attention is already nonlinear in its input, because its softmax weights depend on queries and keys computed from that input. So removing φ would not turn the whole Transformer into a linear map. It would remove nonlinear processing within each token: for a fixed attention pattern, a layer could only mix value vectors and re-project them linearly, and the FFN itself would reduce to one linear map per token. Residual connections are a separate story. Through a pre-norm block the Jacobian is J_ℓ = I + J_F J_N, and the gradient to early layers is still the ordered product J_{L−1} ⋯ J₀. Expanding that product gives a sum over paths, including the pure identity path, so the signal does not have to pass through every sublayer’s Jacobian. That makes deep stacks far easier to train than plain stacks, but it is not a guarantee: if the J_F J_N terms are large or aligned, the product can still grow or shrink. Initialization, normalization, warmup and clipping do the rest.
4 · Put concrete numbers on it
Worked numbers (from stated assumptions)5 · Common misconception to avoid
Thinking “attention does all the heavy lifting and the FFN is a minor projection.” In a dense Transformer, the FFN holds roughly two-thirds of the parameters and FLOPs per token at moderate context lengths.
In practice · implementation & engineering rule of thumb
When switching a classic 2-matrix FFN (hidden width 4d) to a 3-matrix SwiGLU FFN, shrink the intermediate width to (8/3)d rounded to a multiple of 256 so parameter count and tensor-core alignment stay matched.
class SwiGLUFFN(nn.Module):
def __init__(self, d, hidden_d=None):
super().__init__()
# Match 2 * d * (4d) = 8d^2 params using 3 matrices -> hidden_d ≈ (8/3)d
h = hidden_d or ((int(8 * d / 3) + 255) // 256) * 256
self.w_gate = nn.Linear(d, h, bias=False)
self.w_up = nn.Linear(d, h, bias=False)
self.w_down = nn.Linear(h, d, bias=False)
def forward(self, x):
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))Go one level deeper
Follow-ups that often come after a correct first answer.
- Gated FFNs (SwiGLU)
- FFN(x) = W₂(SiLU(W₁x) ⊙ W₃x). One branch acts as a learned, input-dependent gate on the other. Shazeer (2020) reported quality gains over ReLU/GELU FFNs at matched parameter count.
- Pre-norm vs post-norm
- The original Transformer used post-norm, LN(x + F(x)), which normalizes the residual stream itself. Pre-norm, x + F(LN(x)), leaves a clean identity path and is usually easier to train deep, with less sensitivity to warmup. Post-norm can still work well but typically needs more careful tuning.
6 · Self-check & interview synthesis
Explain it in your own words first
Before revealing the reference answer, try answering the opening question aloud in four beats: what it is → how the math works → what trade-off it makes → a concrete number or failure mode.
Follow-up question interviewers often ask next
MediumWhat is the difference between Pre-Norm and Post-Norm residual blocks?
Show follow-up reasoning
Post-Norm (used in the original 2017 Transformer) computes y = Norm(x + F(x)), placing normalization on the main residual highway so gradients must pass through every norm’s Jacobian. Pre-Norm (used in GPT, Llama, and Qwen) computes y = x + F(Norm(x)), keeping the residual stream completely unobstructed from the first layer to the final output norm, which markedly improves training stability at scale.