4.1.8Transformer Architecture

Feed-forward network sublayers

2,615 words12 min readdifficulty · medium

What is the Feed-Forward Network (FFN)?

Architecture Deep Dive

Why the Expansion-Contraction Pattern?

Let's derive why we expand then contract, starting from what we need:

Goal: Learn a non-linear function f:RdmodelRdmodelf: \mathbb{R}^{d_{\text{model}}} \to \mathbb{R}^{d_{\text{model}}} that can represent complex patterns.

Step 1 — Universal Approximation

By the universal approximation theorem, a two-layer network with enough hidden units can approximate any continuous function. But how many units?

Step 2 — Information Bottleneck

If dff=dmodeld_{ff} = d_{\text{model}}, we have a bottleneck—limited capacity. The hidden layer needs to represent more features than the input to capture complex combinations.

Step 3 — The4x Rule

Empirically, dff=4×dmodeld_{ff} = 4 \times d_{\text{model}} works well. Why?

  • Expansion: 4x more neurons means we can compute 4×dmodel\sim 4 \times d_{\text{model}} different feature combinations
  • Sparsity: ReLU activations are sparse (~50% neurons active), so effective capacity is 2×dmodel\sim 2 \times d_{\text{model}}
  • Compression: Second layer projects back, forcing the network to learn useful high-dimensional features

Activation Functions: ReLU → GELU → SiLU

Why not just ReLU?

Starting with ReLU (Rectified Linear Unit): ReLU(x)=max(0,x)\text{ReLU}(x) = \max(0, x)

Problem: Hard cutoff at zero creates dead neurons (gradient = 0 for x<0x < 0).

Figure — Feed-forward network sublayers

Evolution to GELU: GELU(x)=xΦ(x)=xP(Xx),XN(0,1)\text{GELU}(x) = x \cdot \Phi(x) = x \cdot P(X \leq x), \quad X \sim \mathcal{N}(0, 1)

Intuition: Multiply input by probability it's greater than a random Gaussian. Small negative values get small but non-zero gradients (smooth!).

Approximation: GELU(x)0.5x(1+tanh[2π(x+0.044715x3)])\text{GELU}(x) \approx 0.5x\left(1 + \tanh\left[\sqrt{\frac{2}{\pi}}\left(x + 0.044715x^3\right)\right]\right)

Modern SiLU/Swish: SiLU(x)=xσ(x)=x1+ex\text{SiLU}(x) = x \cdot \sigma(x) = \frac{x}{1 + e^{-x}}

Why better? Smooth everywhere, self-gated (output depends on input magnitude), empirically stronger for large models.

Position-Wise = No Cross-Position Mixing

Mathematical statement: For sequence X=[x1,x2,,xn]X = [x_1, x_2, \ldots, x_n] where xiRdmodelx_i \in \mathbb{R}^{d_{\text{model}}}: FFN(X)=[FFN(x1),FFN(x2),,FFN(xn)]\text{FFN}(X) = [\text{FFN}(x_1), \text{FFN}(x_2), \ldots, \text{FFN}(x_n)]

Each FFN(xi)\text{FFN}(x_i) uses the same weights W1,W2,b1,b2W_1, W_2, b_1, b_2 but different input data.

Role in the Transformer Block

The complete encoder block:

x=LayerNorm(x+MultiHeadAttention(x))x=LayerNorm(x+FFN(x))\begin{align} x' &= \text{LayerNorm}(x + \text{MultiHeadAttention}(x)) \\ x'' &= \text{LayerNorm}(x' + \text{FFN}(x')) \end{align}

Why this order?

  1. Attention first: Aggregate context (linear mixing)
  2. FFN second: Extract non-linear patterns from aggregated context
  3. Repeat 12-24 times: Each layer refines representations further

Common Mistakes

Modern Variations

GLU Variants (Gated Linear Units)

Recent models (PaLM, LaMA) replace standard FFN with gated variants:

FFNGLU(x)=(σ(xW1)xW3)W2\text{FFN}_{\text{GLU}}(x) = (\sigma(xW_1) \odot xW_3)W_2

Where \odot is element-wise multiplication.

Why gating?

  • σ(xW1)\sigma(xW_1) acts as a learned gate (which features to pass)
  • xW3xW_3 computes the features
  • Gate × Features = selective amplification
  • Benefit: 15-20% fewer parameters for same performance (gates provide implicit regularization)

Mixture of Experts (MoE)

Replace single FFN with multiple expert FFNs + router:

FFNMoE(x)=i=1NRouter(x)iExperti(x)\text{FFN}_{\text{MoE}}(x) = \sum_{i=1}^N \text{Router}(x)_i \cdot \text{Expert}_i(x)

Why?

  • Each expert specializes (e.g., Expert 1 = syntax, Expert 2 = semantics)
  • Sparse activation: only top-k experts compute per token
  • Benefit: 10x parameters, 1.5x compute (most experts dormant per token)

Connections


Flashcards

#flashcards/ai-ml

What is the feed-forward network sublayer in Transformers? :: A position-wise fully connected network applied independently to each token, consisting of two linear layers with a non-linear activation between them, typically expanding dimension by 4x then projecting back.

Why does the FFN expand to 4x the model dimension?
To create a richer feature space for learning complex non-linear patterns. The expansion provides enough capacity for universal approximation, while ReLU sparsity (~50% active) makes the effective capacity ~2x model dimension.
What is the formula for the standard Transformer FFN?
FFN(x) = max(0, xW₁ + b₁)W₂ + b₂, where W₁ expands dimensions (d_model → d_ff), activation is applied, and W₂ projects back (d_ff → d_model).
Why is the FFN applied position-wise?
Attention already mixes information across positions. FFN specializes in position-independent feature extraction on the already-mixed representations, which paralelizes perfectly and prevents redundant cross-position modeling.
What percentage of Transformer parameters are in the FFN?
Approximately 2/3 of each layer's parameters. With d_ff = 4×d_model, the FFN has ~8d²_model parameters vs ~4d²_model for attention.
Why did models move from ReLU to GELU to SiLU?
ReLU has hard cutoff (dead neurons for x<0). GELU smooths the activation with Gaussian probability weighting. SiLU (x·σ(x)) is self-gated, smooth everywhere, and empirically performs best for large models.
What is the difference between FFN and a regular MLP?
FFN applies the same network independently to each sequence position (like 1x1 convolution), while MLP processes the entire input as a single vector. FFN has position-wise weight sharing.
What is a GLU variant and why use it?
Gated Linear Unit: FFN_GLU(x) = (σ(xW₁) ⊙ xW₃)W₂, where one path gates the other. Provides 15-20% parameter savings for same performance through learned selective amplification.
Recall Explain to a 12-year-old

Imagine you're in a class and the teacher asks everyone to share one interesting fact. That's like attention—everyone hears what others said and combines those ideas in their head.

Now, each student goes home and thinks deeply about all the facts they heard, connecting them to what they already know. Maybe you heard "dogs are loyal" and "wolves hunt in packs," and at home you realize "oh, dogs evolved from wolves, that's why they're social!" That deep thinking alone at home is the feed-forward network.

You don't call your classmates while thinking (no mixing with others). You just process what you learned. Then tomorrow, you come back to class with better understanding, and the cycle repeats.

The "4x expansion" is like having 4x more brain space when you think at home—you can consider way more connections and ideas before summarizing your final thought to bring back to class.

Concept Map

mixes info across positions

only linear weighted averages

provided by

applied per token

structure

W1 expansion

activation sigma

W2 projection

typical ratio

justified by

ReLU sparsity ~50%

dominates params ~8 d_model squared

Attention sublayer

Feed-forward network

Need for non-linearity

Position-wise processing

Expand then contract

Hidden layer d_ff

ReLU / GELU / SiLU

Output d_model

d_ff = 4x d_model

Universal approximation

Effective capacity ~2x

Parameter count

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Feed-forward network (FFN) transformer ka wo component hai jo har token ko independently process karta hai. Socho jaise attention ne sab tokens se information mix kar di, ab FFN ka kaam hai us mixed information se patterns nikalna.

Architecture simple hai: pehle input ko4x zyada dimensions mein expand karo (agar model dimension 768 hai to 3072 ban jata hai), phir ek non-linear activation (ReLU ya GELU) apply karo, aur phir wapas original dimension mein compress karo. Ye expansion zaruri hai kyunki zyada neurons ka matlabzyada complex patterns seekh sakte ho. ReLU se GELU tak evolutionhua kyunki GELU smooth hai—negative values ke liye bhi thoda gradient milta hai, matlab training better hoti hai.

Ek important baat: FFN har position ko alag-alag process karta hai, kisi position ke data ko dusre position ke sath mix nahi karta. Ye deliberate design choice hai kyunki attention layer already mixing kar chuka hota hai. FFN ka kaam sirf feature extraction hai, not information routing. Aur parameters ki baat karein to FFN mein transformer ki2/3 parameters hoti hain (attention sezyada!), isliye ye model ki real learning capacity hai. Modern variants jaise GLU ya Mixture-of-Experts (MoE) FFN ko aur efficient banate hain by using gating mechanisms ya specialized expert networks.

Go deeper — visual, from zero

Test yourself — Transformer Architecture

Connections