CNSLT ACADEMY / INSIDE MODERN AI MODELS

Inside the Transformer Block: Architecture, FFN, Residuals and Normalisation

FOUNDATIONSBEGINNERFREE TEXT LESSONVIDEO 🔒 PRO

By the end of this lesson, you should be able to explain why Transformers replaced RNNs, draw a complete Pre-Norm Transformer block from memory, contrast LayerNorm with RMSNorm, calculate the parameter split between Attention and a SwiGLU Feed-Forward Network (FFN), explain how Sparse Mixture-of-Experts (MoE) routes tokens, and link distributed representations to AI governance and model-card evaluation.

Inside the Transformer Block: Architecture, FFN, Residuals and Normalisation

##

  1. Why Transformers replaced RNNs

Before 2017, sequence models like RNNs and LSTMs read text strictly left-to-right, squeezing everything seen so far into one fixed-size hidden state hth_t:

  • Sequential bottleneck: You could not compute word 50 until word 49 finished—starving modern GPUs designed for massive parallel matrix multiplication.
  • Long-range forgetting: Information from word 3 had to survive 47 sequential transformations to reach word 50, suffering severe vanishing gradients.

A Transformer replaces recurrence with stacked Transformer Blocks that process all tokens in parallel and connect any two tokens in $O(1)$ hops via Self-Attention.

##

  1. Anatomy of one Pre-Norm Transformer Block

A modern decoder LLM (Llama, Gemma, Qwen, GPT-class) stacks 32 to 128 copies of the exact same structural block. Each block performs two sublayer updates on the shared Residual Stream xl\mathbf{x}_l:

x_mid = x_l   + Attention( RMSNorm(x_l) )     # Stage A: Cross-token communication
x_out = x_mid + FFN( RMSNorm(x_mid) )         # Stage B: Per-token deep computation

### Component 1: Residual Connections (The Residual Stream) Rather than overwriting xl\mathbf{x}_l at every layer, each sublayer adds a delta back onto xl\mathbf{x}_l. Think of the residual stream as a shared communication bus running vertically from Layer 1 to Layer 80:

  • Attention heads *read* from the bus, pull cross-token context, and *write* updates back.
  • FFN layers *read* from the bus, look up stored patterns, and *write* refinements back.
  • During backpropagation, the + operation creates an unimpeded identity highway (∂(x+f(x))∂x=1+f′(x)\frac{\partial(x + f(x))}{\partial x} = 1 + f'(x)), allowing gradients to reach Layer 1 cleanly without vanishing.

### Component 2: Pre-Norm & RMSNorm (Numerical Stability) The 2017 Transformer placed normalisation *after* the residual addition (Post-Norm), which made training very deep models fragile without heavy warmup hacks. Modern LLMs place normalisation *before* each sublayer (Pre-Norm), keeping the residual highway completely clean.

Most frontier open-weight models also replace full LayerNorm (which subtracts the mean and divides by standard deviation) with RMSNorm (Root Mean Square Normalisation):

RMSNorm(x)=x1d∑i=1dxi2+ϵ⊙γ\text{RMSNorm}(\mathbf{x}) = \frac{\mathbf{x}}{\sqrt{\frac{1}{d}\sum_{i=1}^d x_i^2 + \epsilon}} \odot \gamma

Dropping mean-centering saves ~10–15% normalisation overhead on GPUs while preserving virtually identical training stability.

### Component 3: Feed-Forward Network — FFN / SwiGLU (The Knowledge Store) Self-Attention only computes linear weighted averages of Values; it does not apply rich per-token non-linear reasoning. After Attention finishes mixing information *horizontally* across tokens, the FFN operates *vertically* on each token independently.

Classic Transformers used a two-matrix expand-and-contract MLP (d→4d→dd \rightarrow 4d \rightarrow d) with ReLU or GELU. Modern LLMs almost universally use SwiGLU (Swish Gated Linear Unit), which uses three matrices (Wgate,Wup,WdownW_{\text{gate}}, W_{\text{up}}, W_{\text{down}}) with hidden width dff≈83dd_{\text{ff}} \approx \frac{8}{3}d:

SwiGLU(x)=(SiLU(xWgate)⊙(xWup))Wdown\text{SwiGLU}(\mathbf{x}) = \big(\text{SiLU}(\mathbf{x} W_{\text{gate}}) \odot (\mathbf{x} W_{\text{up}})\big) W_{\text{down}}

Interpretability research shows FFNs function heavily like key-value pattern and factual memory banks—detecting complex combinations of concepts written into the residual stream and injecting associated facts or syntactic continuations.

##

  1. Worked example: proving where a 7B LLM's parameters actually live

Let us calculate the exact parameter count of one single layer in a representative 7B-class modern Transformer (L = 32 layers, d_model = 4,096, d_ff = 11,008 SwiGLU, GQA with 32 Query heads and 8 KV heads of d_head = 128):

### Attention sublayer parameters (per layer)

  • WQW_Q: $4,096 \times (32 \times
  1. = 16,777,216$
  • WKW_K: $4,096 \times (8 \times
  1. = 4,194,304$
  • WVW_V: $4,096 \times (8 \times
  1. = 4,194,304$
  • WOW_O: 4,096×4,096=16,777,2164,096 \times 4,096 = 16,777,216
  • Attention subtotal: `41,943,040` parameters (`23.7%` of the block)

### SwiGLU FFN sublayer parameters (per layer)

  • Wgate+Wup+Wdown=3×(4,096×11,008)=W_{\text{gate}} + W_{\text{up}} + W_{\text{down}} = 3 \times (4,096 \times 11,008) = `135,266,304` parameters (`76.3%` of the block)

Across 32 layers, those blocks total 5.67 billion parameters (plus ~1.05 billion in input/output embeddings for a 128k vocab ≈ 6.7B–7B total). Over three-quarters of each Transformer block's learned weights live inside the FFN, not Attention!

##

  1. Scaling beyond dense blocks: Sparse Mixture-of-Experts (MoE)

If FFNs dominate both parameter count and compute, what if you want the knowledge capacity of a 100B+ model at the speed of a 15B model?

Mixture-of-Experts (MoE) replaces the single giant FFN in each block with EE smaller specialist FFNs (for example, 8, 64, or 128 experts) plus a lightweight Router:

  1. For each token, the router computes compatibility scores across all EE experts and selects only the top-$k$ experts (commonly k=2k = 2).
  2. Only those 2 experts execute for that token, and their outputs are combined by router weights.
  3. During training, an auxiliary load-balancing loss prevents every token from collapsing onto the same two experts.

Practical trade-off: MoE dramatically lowers compute FLOPs per token (faster, cheaper inference), while still requiring VRAM to hold all total experts in GPU memory.

##

  1. How depth builds abstraction

When 32 to 96 blocks are stacked:

  • Early blocks: local syntax, bigrams, punctuation, disambiguating raw word senses.
  • Middle blocks: multi-step entity tracking, domain knowledge retrieval from FFNs, logical and code structures.
  • Final blocks: formatting, refusal/alignment steering, projecting concepts into next-token logit directions.

##

  1. AI GRC and security implications
  • Reading model cards critically: You can now decode architecture disclosures (32 layers, GQA 32/8, SwiGLU, RMSNorm, MoE 64x top-2) and immediately understand VRAM sizing (governed by *total* parameters + KV cache) versus throughput (governed by *active* parameters).
  • Superposition and why manual "fact patching" fails: Because a model encodes far more concepts than it has dimensions (superposition), individual FFN neurons are often polysemantic—firing for multiple unrelated concepts. That is why organisations cannot cleanly "delete one outdated compliance rule" from Layer 24 without risking regressions elsewhere. Governance must rely on external retrieval (RAG), guardrails, and versioned evaluation suites.
  • MoE batching non-determinism: In sparse MoE serving, dynamic token routing across shared batches can introduce subtle floating-point differences even at temperature = 0, reinforcing the need for schema validation and audit trails in regulated workflows.

##

  1. Common misconceptions
  • “Self-Attention holds most of the weights in a Transformer.” False. As we just proved, FFN layers typically hold ~66%–76% of a dense block's parameters.
  • “MoE models use less GPU memory than dense models of the same total size.” False. All expert weights must reside in GPU memory (unless painfully offloaded to CPU RAM); MoE saves *compute FLOPs*, not VRAM.
  • “Every layer in a Transformer uses a different custom architecture.” False. Every block uses the exact same blueprint; specialisation emerges purely from the learned weights inside each layer.

##

  1. Practical exercise
  2. Look up the public architecture table of any open-weight LLM (for example, Llama 3 8B, Mistral 7B, Gemma 2, or Qwen 2.5). Extract num_hidden_layers, hidden_size, intermediate_size, num_attention_heads, and num_key_value_heads.
  3. Plug those exact numbers into our parameter formula above to verify what percentage of each block lives in Attention vs. FFN.
  4. Explain to a finance or procurement stakeholder in 3 sentences why a "100B total / 12B active MoE" model can feel as fast as a small model while still requiring multi-GPU hardware to self-host.

##

  1. Knowledge check
  2. What two structural bottlenecks caused Transformers to overtake RNNs?
  3. Why does Pre-Norm train more reliably at 80+ layers than Post-Norm?
  4. What is the conceptual division of labour between Self-Attention and the FFN inside a block?
  5. In a Sparse MoE model, what is the practical difference between *total parameters* and *active parameters*?
  6. Why does superposition make surgical single-fact weight editing unreliable for enterprise compliance?

Answer key:

  1. Sequential step-by-step computation (poor GPU parallelism) and O(n)O(n) path length (long-range forgetting / vanishing gradients).
  2. Pre-Norm preserves an unobstructed additive residual highway so gradients flow straight back without scaling distortion at every layer.
  3. Attention routes and mixes information *across* tokens; the FFN processes each token *individually* and stores the bulk of pattern/factual weights.
  4. Total parameters determine VRAM capacity and stored knowledge; active parameters determine per-token compute FLOPs and speed.
  5. Concepts are distributed across overlapping polysemantic neurons, so editing weights for one fact risks corrupting unrelated behaviours.

##

  1. Checklist
  • [ ] Sketch a complete Pre-Norm Transformer block including both residual + paths.
  • [ ] Calculate Attention vs. FFN parameter shares from a model's config.json.
  • [ ] Distinguish Dense vs. MoE VRAM and latency trade-offs during infrastructure sizing.
  • [ ] Avoid relying on direct weight-editing promises for dynamic compliance updates.
  • [ ] Record exact architecture metadata (dense/MoE, layers, GQA ratio) in your organisation's model inventory.
  • [ ] Pair model internals understanding with end-to-end system evaluations (Lesson 20).

##

  1. Further reading
LEARNER FEEDBACK

Help improve this learning path.

Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.

COURSE PROGRESS0/29 complete
Not yet completed
CHECK YOUR UNDERSTANDING