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!
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'!
Implementing a clean Pre-Norm Transformer Block and Sinusoidal Positional Encoding from scratch is a staple PyTorch engineering benchmark.
Knowing the difference between Encoder-Only (bidirectional embeddings), Decoder-Only (autoregressive generation), and Encoder-Decoder (seq2seq) guides every architecture choice!
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?'
If you feed 'Dog bites man' and 'Man bites dog' into raw Self-Attention with NO Positional Encoding, what happens?
- 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
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 )!
1. Sinusoidal Positional Encoding
Adding multi-frequency waves directly to token embeddings gives every position a unique vector with zero extra trainable parameters — and allows relative offsets to be expressed as a linear transformation of !
2. Pre-Norm vs. Post-Norm Residual Blocks
+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!
Pre-Norm vs. Post-Norm Residual Path
3. Encoder-Only vs. Decoder-Only vs. Encoder-Decoder
- 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!
Why does a Transformer block still need a Feed-Forward Network (FFN) after Multi-Head Attention?
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 !
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.
+1 residual highway.Universal Backbone Across Vision, Speech & Language
The exact same Pre-Norm Transformer block powers ViT, Whisper audio encoders, AlphaFold, and frontier LLMs.
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))
LayerNorm after the last Pre-Norm Transformer block before the output head.LayerNorm(x) right before the classification/LM head!x + SubLayer(Norm(x))) instead of Post-Norm (Norm(x + SubLayer(x)))?