The Transformer as a Compute Graph
Trace the complete forward pass of a decoder-only Transformer β tensor shapes, FLOP counts, and parameter counting at every step.
Every optimization in AI infrastructure β kernel design, parallelism strategy, memory management β acts on some component of the Transformer. This chapter traces the complete forward pass of a decoder-only Transformer, tracking tensor shapes, data dependencies, and compute costs at every step. The goal: see the Transformer not as an abstract diagram but as a concrete sequence of matrix operations with measurable costs.
1. The Decoder-Only Architecture
Modern LLMs (GPT, LLaMA, Qwen, Mistral, DeepSeek) all use the decoder-only architecture. The full pipeline:
Input tokens β Embedding β N Γ Decoder Block β Final Norm β LM Head β Logits
End-to-End Data Flow
Tracing a single forward pass with concrete shapes:
Input: "What is attention" β Tokenizer β [1234, 567, 89] (S=3 tokens)
Step 1: Token Embedding
token_ids (B, S) β W_embed (V, d) β X (B, S, d)
(1, 3) (32000, 4096) (1, 3, 4096)
Step 2: L Γ Decoder Block (shape preserved throughout)
ββ Block βββββββββββββββββββββββββββββββββββββββββββββββ
β x_norm = RMSNorm(X) (B, S, d) β
β attn_out = MaskedSelfAttention(x_norm) (B, S, d) β
β H = X + attn_out β residual β
β β
β h_norm = RMSNorm(H) (B, S, d) β
β ffn_out = SwiGLU_FFN(h_norm) (B, S, d) β
β X_out = H + ffn_out β residual β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Γ L layers (dimension stays (B, S, d) throughout)
Step 3: Final RMSNorm
X_final (B, S, d) β RMSNorm β X_norm (B, S, d)
Step 4: LM Head
X_norm (B, S, d) Γ W_lm (d, V) = logits (B, S, V)
(1, 3, 4096) (4096, 32000) (1, 3, 32000)
Step 5: Take last position, softmax β sample next token
logits[:, -1, :] β softmax β sample β next token
Key observation: the hidden dimension is preserved through all L blocks. The only shape changes happen at input (token IDs β embeddings) and output (embeddings β vocabulary logits).
2. Inside a Decoder Block
Each decoder block has two sub-layers: masked self-attention and feed-forward network, each wrapped with normalization and residual connections.
Masked Self-Attention
Where is the causal mask β an upper-triangular matrix of that prevents attending to future tokens.
Step by step with shapes (for a single head):
| Step | Operation | Shape |
|---|---|---|
| Input | ||
| Q projection | ||
| K projection | ||
| V projection | ||
| Split heads | Reshape + transpose | where |
| Attention scores | ||
| Causal mask | Add to upper triangle | |
| Softmax | Row-wise softmax | |
| Weighted sum | ||
| Merge heads | Reshape | |
| Output projection |
The attention matrix is why attention is in memory and compute β and why long-context serving is hard.
Feed-Forward Network (SwiGLU)
Modern LLMs use SwiGLU instead of the original ReLU FFN:
| Step | Operation | Shape |
|---|---|---|
| Gate projection | ||
| Up projection | ||
| Gate activation | ||
| Down projection |
SwiGLU has 3 weight matrices (gate, up, down) instead of 2 β this changes parameter counting.
RMSNorm
Only learnable parameters (the scale ). Compared to LayerNorm, RMSNorm skips mean centering β ~10-15% faster with comparable quality. Used by LLaMA, Qwen, Mistral, and most modern LLMs.
3. Model Configurations
Different model sizes use the same decoder block β just with different dimensions:
| Model | Attention | |||||||
|---|---|---|---|---|---|---|---|---|
| LLaMA-2-7B | 4096 | 32 | 32 | 128 | 32 | 11,008 | 32,000 | MHA |
| LLaMA-2-13B | 5120 | 40 | 40 | 128 | 40 | 13,824 | 32,000 | MHA |
| LLaMA-2-70B | 8192 | 64 | 8 | 128 | 80 | 28,672 | 32,000 | GQA |
| Mistral-7B | 4096 | 32 | 8 | 128 | 32 | 14,336 | 32,000 | GQA |
| DeepSeek-V3 | 7168 | 128 | β | β | 61 | 18,432 | 129,280 | MLA + MoE |
Patterns to notice:
- is universal: every model uses 128-dim attention heads. Scaling up means more heads, not bigger heads.
- SwiGLU changes : standard Transformer uses . SwiGLU has 3 matrices instead of 2, so to keep parameter count similar. LLaMA-2-7B: (rounded to 256 for GPU alignment).
- GQA reduces KV heads: LLaMA-2-70B uses 8 KV heads for 64 Q heads β each group of 8 Q heads shares 1 KV head. This cuts KV cache by 8Γ with minimal quality loss.
4. Parameter Counting
Estimating parameters is a fundamental AI infra skill β it directly tells you memory requirements.
Per-Block Parameters
For a single decoder block with MHA and SwiGLU:
| Component | Formula | Count (7B, ) |
|---|---|---|
| Q projection | 16.8M | |
| K projection | 16.8M | |
| V projection | 16.8M | |
| O projection | 16.8M | |
| Gate | 45.1M | |
| Up | 45.1M | |
| Down | 45.1M | |
| 2Γ RMSNorm | 8.2K | |
| Block total | 202M |
Total Model Parameters
| Component | Formula | Count (LLaMA-2-7B) |
|---|---|---|
| Embedding | 131M | |
| blocks | 32 Γ 202M = 6,464M | |
| Final RMSNorm | 4K | |
| LM Head | 131M (often tied with embedding) | |
| Total | ~6.7B |
With GQA (LLaMA-2-70B)
When , K and V projections shrink:
For 70B: :
- Q and O:
- K and V:
- Attention per block: 150.8M (vs 268M with full MHA β 44% reduction)
5. FLOP Counting
For a forward pass with batch size , sequence length , and model parameters:
Per-token compute (single decoder block):
| Operation | FLOPs |
|---|---|
| QKV + O projections | |
| Attention scores | |
| Attention Γ V | |
| FFN (SwiGLU, 3 matrices) | |
| Block total |
For the full model with layers:
Training FLOPs β 3Γ forward (1Γ forward + 2Γ backward).
For LLaMA-2-7B ():
- Per-token: ~14 GFLOPs
- Full sequence: ~28 TFLOPs
- The term (attention) is small at but dominates at +
6. Why Decoder-Only Won
The original Transformer (2017) had both an encoder and decoder. Three architecture families emerged:
| Architecture | Examples | Design | Status |
|---|---|---|---|
| Encoder-only | BERT, RoBERTa | Bidirectional attention, masked token prediction | Superseded for generation |
| Encoder-Decoder | T5, BART | Encoder processes input, decoder generates output | Used for translation, summarization |
| Decoder-only | GPT, LLaMA, Qwen | Causal attention, next-token prediction | Dominant for LLMs |
Why decoder-only won:
- Simpler: one architecture for both understanding and generation β no separate encoder
- Scalable: just stack more identical blocks. No encoder-decoder cross-attention complexity
- Unified pretraining: next-token prediction works for every task when prompted correctly
- Efficient inference: KV cache works naturally with causal attention; encoder-decoder requires managing two caches
Every major production LLM today (GPT-4, Claude, LLaMA, Qwen, Mistral, DeepSeek) is decoder-only.
7. Depth vs Width: Scaling Dimensions
When scaling a model from 7B to 70B to 400B+, which dimensions change?
| Dimension | 7B (LLaMA-2) | 70B (LLaMA-2) | 405B (LLaMA-3.1) | Scaling pattern |
|---|---|---|---|---|
| $ (hidden) | 4,096 | 8,192 | 16,384 | ~4Γ |
| $ (layers) | 32 | 80 | 126 | ~4Γ |
| $ (heads) | 32 | 64 | 128 | ~4Γ |
| $ (head dim) | 128 | 128 | 128 | Constant |
| {ff}$ | 11,008 | 28,672 | 53,248 | Scales with $ |
Key patterns:
- Head dimension stays fixed at 128 β universally. More capacity = more heads, not bigger heads.
- Depth and width scale together β roughly doubling both gives ~8Γ parameters.
- Width affects per-layer cost quadratically (^2$ in attention projections) while depth affects cost linearly (more layers, same cost each).
- Depth gives more representational layers (more processing steps), width gives more capacity per layer (higher-dimensional representations).
In practice, scaling both gives the best quality per FLOP β this is what scaling laws predict.
Self-Check
- Trace the shape of a tensor through a complete forward pass (embedding β L blocks β logits)
- Explain why the hidden dimension is preserved through all blocks
- Explain the causal mask and why it prevents attending to future tokens
- Explain SwiGLU vs standard FFN (3 matrices vs 2, activation function)
- Calculate parameter count for a given model config
- Explain why is universal and with SwiGLU
- Explain GQA and how it reduces KV cache
- Estimate forward FLOPs for a given model and sequence length