Chapter 34 of 42 · ~20 min read & lab+80 XP
Chapter 34 · Deep Learning

The Transformer Block: Sinusoidal Positional Encoding, Pre-Norm Residuals & Encoder vs. Decoder

Assembling the complete Transformer architecture: why Self-Attention is blind to word order without Sinusoidal Positional Encoding, Pre-Norm vs. Post-Norm stability, Token-Mixing + Channel-Mixing FFN, and Encoder vs. Decoder families!

Why ML Engineers & Data Scientists Actually Need This

Attention alone is only half the story — without Positional Encoding, Pre-Norm Residuals, and the Feed-Forward Network (FFN), a Transformer can't tell 'Dog bites man' from 'Man bites dog'!

ML / AI Engineer

Implementing a clean Pre-Norm Transformer Block and Sinusoidal Positional Encoding from scratch is a staple PyTorch engineering benchmark.

Data Scientist

Knowing the difference between Encoder-Only (bidirectional embeddings), Decoder-Only (autoregressive generation), and Encoder-Decoder (seq2seq) guides every architecture choice!

Interview & Debug Edge

Classic Transformer deep-dive question: 'Why did modern Transformers switch from Post-Norm (2017 paper) to Pre-Norm, and why do we still need an FFN after Multi-Head Attention?'

Step 0 · Test Your Gut Before Any Math!

If you feed 'Dog bites man' and 'Man bites dog' into raw Self-Attention with NO Positional Encoding, what happens?

What You Will Master in This Chapter
  • Explain why raw Self-Attention is permutation-equivariant and implement Sinusoidal Positional Encoding from scratch
  • Contrast Post-Norm (Norm(x + Sub(x))) with modern Pre-Norm (x + Sub(Norm(x))) for deep Transformer stability
  • Understand the two halves of every Transformer block: Token-Mixing (Attention) and Channel-Mixing (2-layer FFN)
  • Choose between Encoder-Only (BERT/ViT), Decoder-Only (GPT/Llama), and Encoder-Decoder (T5/Whisper) architectures
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
PE(pos,2i)=sin⁡ ⁣(pos100002i/d),  PE(pos,2i+1)=cos⁡ ⁣(pos100002i/d)\text{PE}_{(pos, 2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \; \text{PE}_{(pos, 2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)Say aloud:“Sinusoidal positional encoding uses alternating sine and cosine waves across geometric wavelengths”
Plain-English Meaning
Gives every token position a unique multi-frequency fingerprint (like binary clock hands) where relative shift +k+k is a linear rotation matrix!
Everyday Example
Low ii oscillates fast (adjacent words); high ii oscillates slowly (paragraphs apart).
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Every Transformer Block alternates two complementary jobs: Attention ('Token Mixing') lets tokens talk across the sequence to gather context, while the FFN ('Channel Mixing') lets each token think deeply within its own feature vector (expanding D→4D→DD \to 4D \to D)!

1. Sinusoidal Positional Encoding

Sinusoidal Positional Encoding: Multi-Frequency Clocks for Every Token PositionHigh-frequency dims track adjacent positions; low-frequency dims track long-range distance!
Self-Attention is permutation-equivariant (bag of tokens!) — Sinusoidal Positional Encoding injects multi-frequency sin/cos waves so relative offsets map to linear rotations!

Adding multi-frequency sin⁡/cos⁡\sin / \cos waves directly to token embeddings gives every position a unique vector with zero extra trainable parameters — and allows relative offsets PEpos+k\text{PE}_{pos+k} to be expressed as a linear transformation of PEpos\text{PE}_{pos}!

2. Pre-Norm vs. Post-Norm Residual Blocks

Post-Norm (2017 Original) vs. Pre-Norm (Modern Stable Transformer Block)Post-Normy = Norm(x + SubLayer(x))Norm interrupts the residual highway!Pre-Norm (Modern Standard ✓)y = x + SubLayer(Norm(x))Clean identity highway across 100+ layers ✓
Post-Norm puts LayerNorm on the residual highway (fragile without heavy warmup); modern Pre-Norm puts LayerNorm inside each sub-layer, preserving a clean +1 residual path!

The original 2017 Transformer used Post-Norm (Norm(x + SubLayer(x))), placing LayerNorm directly on the residual path (requiring delicate warmup tuning). Pre-Norm (x + SubLayer(Norm(x))) leaves the +1 residual highway completely unobstructed — enabling effortless training of 100-layer networks!

Animated Mini-Lab • Transformer Block

Pre-Norm vs. Post-Norm Residual Path

x = x + Attn(Norm(x)) → Clean +1 residual highway; trains 96+ layers stably with minimal warmup ✓

3. Encoder-Only vs. Decoder-Only vs. Encoder-Decoder

The Three Transformer Families: Encoder, Decoder & Encoder-DecoderEncoder-OnlyBERT / ViT / DINOBidirectional embeddingsDecoder-OnlyGPT / Llama / ClaudeCausal next-token LLMsEncoder-DecoderT5 / Whisper / DETRCross-attention seq2seq
Three Transformer families: Encoder-Only (BERT/ViT, bidirectional), Decoder-Only (GPT/Llama, causal autoregressive), and Encoder-Decoder (T5/Whisper, cross-attention)!
  • Encoder-Only (BERT, ViT, DINOv2): Bidirectional attention — best for embeddings, classification, and retrieval.
  • Decoder-Only (GPT, Llama, Claude): Causal attention — unified architecture for autoregressive generation and reasoning.
  • Encoder-Decoder (T5, Whisper, DETR): Bidirectional Encoder + Causal Decoder linked by Cross-Attention!
Pause & Check · Quick Intuition Pulse

Why does a Transformer block still need a Feed-Forward Network (FFN) after Multi-Head Attention?

“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Sinusoidal PE adds sin/cos waves once at the input embeddings, whereas RoPE (covered in our Generative AI book!) rotates Q and K inside every attention layer so dot products depend strictly on relative distance m−nm - n!

Interactive Visual Lab
Lab Challenge: Watch the 60 FPS Pre-Norm Transformer Block alternate Token Mixing and Channel Mixing.
Interactive Animation • Transformer Block Deep Lab

Pre-Norm Transformer Block: Token Mixing + Channel Mixing

Watch a token vector travel through Pre-Norm Attention and Pre-Norm FFN on the residual highway.

Step 1 / 4
1. Add Positional Encoding to token embeddings → x₀
2. Sub-Layer 1 (Token Mixing): x₁ = x₀ + MultiHeadAttn(Norm(x₀))
3. Sub-Layer 2 (Channel Mixing): x₂ = x₁ + FFN(Norm(x₁))
4. Clean +1 residual stream passes straight to Block L+1 ✓
0%
Block Step 1
Intuition Takeaway: A complete Pre-Norm Transformer Block combines Positional Encoding, Token-Mixing Attention, Channel-Mixing FFN, and an unobstructed +1 residual highway.
Where This Powers Real ML, Deep Learning & Generative AI

Universal Backbone Across Vision, Speech & Language

The exact same Pre-Norm Transformer block powers ViT, Whisper audio encoders, AlphaFold, and frontier LLMs.

Production NumPy & PyTorch Code Patterns
import math
import torch
import torch.nn as nn

# Sinusoidal Positional Encoding + Pre-Norm Transformer Block
def sinusoidal_pe(seq_len: int, d_model: int) -> torch.Tensor:
    pos = torch.arange(seq_len).unsqueeze(1)
    div = torch.exp(torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model))
    pe = torch.zeros(seq_len, d_model)
    pe[:, 0::2] = torch.sin(pos * div)
    pe[:, 1::2] = torch.cos(pos * div)
    return pe.unsqueeze(0)  # [1, T, D]

class PreNormTransformerBlock(nn.Module):
    def __init__(self, d_model: int = 64, n_heads: int = 4):
        super().__init__()
        self.ln1, self.ln2 = nn.LayerNorm(d_model), nn.LayerNorm(d_model)
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
        self.ffn = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        h = self.ln1(x)
        x = x + self.attn(h, h, h, need_weights=False)[0]  # Pre-Norm residual
        return x + self.ffn(self.ln2(x))

x = torch.randn(2, 16, 64) + sinusoidal_pe(16, 64)
out = PreNormTransformerBlock(64, 4)(x)
print("Transformer block output shape:", tuple(out.shape))
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Forgetting a final LayerNorm after the last Pre-Norm Transformer block before the output head.
Best Practice: Because Pre-Norm never normalizes the final residual sum, always apply one final LayerNorm(x) right before the classification/LM head!
Chapter Mastery Check (+80 XP)
Score: 0 / 1
1Why do modern deep Transformers use Pre-Norm (x + SubLayer(Norm(x))) instead of Post-Norm (Norm(x + SubLayer(x)))?

Apply What You Learned — Solve Matching Coding Problems