FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Transformer Architecture

How attention feed-forward blocks residual paths and positions transform sequences.

Freshness: current•16 min read•Foundation Models and Multimodal AI

Key Learning Outcomes

  • ✓Trace a transformer block
  • ✓Explain attention roles
  • ✓Connect architecture to constraints
Isometric Diagram LabAI & LLM Systems · 6 steps · 10 min

Transformer Tokenization & RoPE Geometry

Interactive subword tokenization and Rotary Position Embedding phase-rotation stage.

Open Isometric Walkthrough
Full Technical Reference Document

Mental model

A decoder-only transformer refines token representations across stacked residual blocks: pre-norm RMSNorm stabilizes inputs, causal grouped-query self-attention with RoPE mixes context across past tokens without leaking future positions, and a gated SwiGLU feed-forward MLP transforms each position independently before handing residual tensors to the next layer.

Token embeddings
Pre-norm RMSNorm
QKV and RoPE rotation
Causal GQA scaled attention
Residual and SwiGLU MLP
Conceptual teaching model synthesized from:How Transformers Solve TasksAttention Is All You NeedFlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessRoFormer: Enhanced Transformer with Rotary Position Embedding

Learning outcomes

  • Derive scaled dot-product attention with causal masking and explain why the 1/dk1/\sqrt{d_k} factor prevents softmax gradient saturation.
  • Compare pre-norm RMSNorm and gated SwiGLU feed-forward blocks against original post-norm LayerNorm + ReLU transformers.
  • Explain how Rotary Position Embeddings (RoPE) encode relative token offsets inside query-key dot products and how FlashAttention avoids O(N2)O(N^2) HBM materialization.
  • Calculate KV-cache bytes per token across Multi-Head Attention (MHA), Grouped-Query Attention (GQA), and Multi-Query Attention (MQA).

Theory

Inside layer ll, hidden states X∈RN×dmodelX \in \mathbb{R}^{N \times d_{\text{model}}} first pass through pre-normalization along a clean residual highway: H=RMSNorm(X)H = \text{RMSNorm}(X), where Root Mean Square Normalization rescales vector magnitude using RMS(x)=1d∑i=1dxi2+ϵ\text{RMS}(x) = \sqrt{\frac{1}{d}\sum_{i=1}^{d} x_i^2 + \epsilon} and learned gain γ\gamma, dropping LayerNorm's mean-centering step to cut kernel memory traffic while preserving stable gradient flow across deep stacks.

Next, linear projections produce Queries (Q=HWQQ = H W_Q), Keys (K=HWKK = H W_K), and Values (V=HWVV = H W_V). Before scoring compatibility, modern LLMs apply Rotary Position Embeddings (RoPE) to pairs of dimensions inside QQ and KK. By rotating position mm by angle mθim\theta_i and position nn by nθin\theta_i, their inner product depends purely on relative offset (m−n)(m - n):

Rotary Position Embedding (RoPE) Visualizer

q_mk_n
Query q (pos m=2)Key k (pos n=6)
Query Position (m)2
Key Position (n)6
2D Channel Pair (i)Pair #0 (θ_i = 1.0000)
Inner Product Invariance: ⟨R_m q, R_n k⟩
Relative Offset (m - n):-4
Inner Product Value:-0.6536
RoPE Formula: θ_i = 10000^(-2(i-1)/d)⟨R_m q, R_n k⟩ depends ONLY on (m - n)

Each head computes scaled dot-product causal attention:

Attention(Q,K,V)=softmax ⁣(QKTdk+M)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{Q K^T}{\sqrt{d_k}} + M\right) V

Why divide by dk\sqrt{d_k}? If components of qq and kk are independent zero-mean unit-variance variables, their dot product q⋅k=∑i=1dkqikiq \cdot k = \sum_{i=1}^{d_k} q_i k_i has variance dkd_k. For dk=128d_k = 128, raw dot products swing by ±11.3\pm 11.3, pushing softmax weights toward hard saturation where Jacobian gradients vanish. Dividing by dk\sqrt{d_k} restores unit variance. Meanwhile, the additive causal mask Mij=0M_{ij} = 0 for j≤ij \le i and Mij=−∞M_{ij} = -\infty for j>ij \gt i enforces autoregressive causality so token ii never attends to future positions.

Naive materialization of the N×NN \times N attention matrix in GPU HBM incurs O(N2)O(N^2) memory traffic. IO-aware FlashAttention (dao-flashattention-2022) tiles QQ, KK, and VV blocks into fast on-chip SRAM and updates softmax normalization incrementally using online safe softmax statistics (mi,ℓi)(m_i, \ell_i), computing exact attention without writing N×NN \times N score tensors to HBM.

After residual addition (X′=X+Attn(H)X' = X + \text{Attn}(H)), a second pre-norm feeds the position-wise SwiGLU MLP:

SwiGLU(u)=(SiLU(uWgate)⊙(uWup))Wdown\text{SwiGLU}(u) = \Big(\text{SiLU}(u W_{\text{gate}}) \odot (u W_{\text{up}})\Big) W_{\text{down}}

Because SwiGLU introduces three projection matrices instead of two, architectures typically set inner width dff≈83dmodeld_{\text{ff}} \approx \frac{8}{3} d_{\text{model}} (rounded to tensor-core multiples such as 128) to match classic dff=4dmodeld_{\text{ff}} = 4 d_{\text{model}} parameter budgets while improving training perplexity.

For autoregressive serving, MHA vs MQA vs GQA governs KV-cache footprint and decode bandwidth. With nhn_h query heads, nkvn_{\text{kv}} key/value heads (group ratio g=nh/nkvg = n_h / n_{\text{kv}}), LL layers, head dimension dhd_h, and bb bytes per element:

KV bytes per token=2⋅L⋅nkv⋅dh⋅b\text{KV bytes per token} = 2 \cdot L \cdot n_{\text{kv}} \cdot d_h \cdot b

Standard MHA sets nkv=nhn_{\text{kv}} = n_h; Multi-Query Attention (MQA) collapses nkv=1n_{\text{kv}} = 1; Grouped-Query Attention (GQA) shares one KV pair across gg query heads (nh=32,nkv=8  ⟹  g=4n_h = 32, n_{\text{kv}} = 8 \implies g = 4), retaining near-MHA expressive capacity while cutting KV-cache reads and VRAM by factor gg.

Worked quantitative example

Consider a 32-layer model (L = 32, d_model = 4,096, n_h = 32, d_h = 128) running in BF16 (b = 2 bytes) at context length N = 8,192 tokens:

MMHA=8,192×(2⋅32⋅32⋅128⋅2)=4.0 GiB,MGQA-8=1.0 GiB,MMQA=128 MiBM_{\text{MHA}} = 8{,}192 \times (2 \cdot 32 \cdot 32 \cdot 128 \cdot 2) = 4.0\text{ GiB}, \quad M_{\text{GQA-8}} = 1.0\text{ GiB}, \quad M_{\text{MQA}} = 128\text{ MiB}

  • MHA (n_kv = 32): 512 KiB/token yields 4.0 GiB per 8k sequence.
  • GQA-8 (n_kv = 8, g = 4): 128 KiB/token drops per-sequence cache to 1.0 GiB (4x memory and decode bandwidth reduction).
  • MQA (n_kv = 1, g = 32): 16 KiB/token shrinks per-sequence cache to 128 MiB (32x reduction).
  • Materialized vs Tiled Scores: Without FlashAttention SRAM tiling, storing BF16 scores for 32 heads at N = 8,192 in just one layer requires Slayer=32×8,1922×2 B=4.29 GiBS_{\text{layer}} = 32 \times 8{,}192^2 \times 2\text{ B} = 4.29\text{ GiB} of transient HBM—more than the entire GQA KV cache across all 32 layers combined.

Attention KV-sharing architecture comparison

VariantQuery : KV RatioKV Bytes / Token (32L, d_h=128, BF16)Memory / HBM Bandwidth ReductionPrimary Architectural Trade-off
MHAn_h : n_h (1:1)512 KiB1x (baseline)Highest expressivity, severe KV VRAM & decode bottleneck
GQA (g=4)32 : 8 (4:1)128 KiB4x smaller KV & bandwidthNear-MHA quality with high concurrent batch headroom
MQA32 : 1 (32:1)16 KiB32x smaller KV & bandwidthMaximum batching, slight quality drop on complex tasks

Trade-offs

Adopting pre-norm RMSNorm, RoPE, SwiGLU, and GQA yields faster convergence, deeper training stability, and 4x–8x higher serving concurrency than post-norm absolute-positional MHA transformers. Yet every choice carries constraints: standard RoPE degrades beyond its pretraining context ceiling unless base frequency θ\theta is rescaled (YaRN or NTK scaling), and GQA relies on fused attention kernels so broadcasting KV heads never materializes duplicate KV copies in HBM.

Meanwhile, quadratic O(N2)O(N^2) prefill FLOPs remain unavoidable in dense causal attention even after FlashAttention shrinks HBM traffic to O(N)O(N). Long-context workloads (128k+ tokens) still pair dense attention with prefix KV caching, context compaction, or hybrid sliding-window layers to bound Time To First Token.

Failure modes and misconceptions

  • Assuming attention weights explain model reasoning faithfully. High attention scores show local routing inside one head and layer; residual bypasses and MLP key-value memories routinely route facts differently from attention heatmaps.
  • Forgetting that FlashAttention still requires O(N2)O(N^2) compute. FlashAttention removes O(N2)O(N^2) HBM memory allocations via SRAM tiling, not the quadratic pairwise compute scaling over long prompts.
  • Using repeat_interleave naively during GQA inference. Expanding K and V tensors in HBM to match n_h forfeits GQA's memory-bandwidth savings; production kernels index shared KV heads directly in SRAM.
  • Omitting 1/sqrt(d_k) scaling or FP32 softmax accumulation. Computing softmax in raw FP16/BF16 on unscaled logits triggers overflow, NaN activations, or collapsed attention weights.

Decision scenario

An engineering team hosts an 8B assistant handling 16,384-token RAG prompts on 80 GB GPUs for 20+ concurrent users. Their legacy MHA checkpoint allocates 512 KiB/token for KV cache, requiring 8.0 GiB per user and crashing with OOM past 7 concurrent sessions even though weights occupy only 16 GB.

Migrate onto a GQA (n_kv = 8) + RoPE + SwiGLU backbone served with fused FlashAttention tiling. Per-user 16k KV footprint drops from 8.0 GiB to 2.0 GiB, raising safe concurrency past 25 sessions while keeping 16k prefill activations in SRAM without O(N2)O(N^2) score-matrix OOMs. Verify long-range recall across 0%–100% prompt depth before rollout.

Implementation example

This PyTorch module implements pre-norm RMSNorm, grouped-query causal scaled dot-product attention with explicit 1/sqrt(d_k) scaling and upper-triangular -inf masking, and a SwiGLU residual MLP block.

python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
​
class CausalGQABlock(nn.Module):
def __init__(self, d_model: int, n_heads: int, n_kv_heads: int, d_ff: int, eps: float = 1e-6) -> None:
super().__init__()
self.nh, self.nkv, self.hd, self.eps = n_heads, n_kv_heads, d_model // n_heads, eps
self.g1, self.g2 = nn.Parameter(torch.ones(d_model)), nn.Parameter(torch.ones(d_model))
self.wq = nn.Linear(d_model, self.nh * self.hd, bias=False)
self.wk = nn.Linear(d_model, self.nkv * self.hd, bias=False)
self.wv = nn.Linear(d_model, self.nkv * self.hd, bias=False)
self.wo = nn.Linear(d_model, d_model, bias=False)
self.w_gate = nn.Linear(d_model, d_ff, bias=False)
self.w_up = nn.Linear(d_model, d_ff, bias=False)
self.w_down = nn.Linear(d_ff, d_model, bias=False)
​
def _rms(self, x: torch.Tensor, g: nn.Parameter) -> torch.Tensor:
return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) * g
​
def forward(self, x: torch.Tensor) -> torch.Tensor:
b, t, _ = x.shape
h = self._rms(x, self.g1)
q = self.wq(h).view(b, t, self.nh, self.hd).transpose(1, 2)
k = self.wk(h).view(b, t, self.nkv, self.hd).transpose(1, 2).repeat_interleave(self.nh // self.nkv, dim=1)
v = self.wv(h).view(b, t, self.nkv, self.hd).transpose(1, 2).repeat_interleave(self.nh // self.nkv, dim=1)
scores = (q @ k.transpose(-2, -1)) / math.sqrt(self.hd)
mask = torch.triu(torch.full((t, t), float("-inf"), device=x.device), diagonal=1)
attn = F.softmax((scores + mask).float(), dim=-1).to(q.dtype) @ v
x = x + self.wo(attn.transpose(1, 2).contiguous().view(b, t, -1))
h2 = self._rms(x, self.g2)
return x + self.w_down(F.silu(self.w_gate(h2)) * self.w_up(h2))
Reflect before revealing the guide

Why does scaling dot products by 1/sqrt(d_k) prevent gradient vanishing, and how does GQA reduce KV-cache memory bandwidth without collapsing multi-head representation?

Prerequisites & Related Concepts (2)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.

Next