SysDesignAtlas

The Transformer as a System

What a forward pass actually does, where the parameters and the FLOPs live, and why prefill and decode are two completely different workloads running the same code.

CoreMedium11 min readaitransformerarchitectureinference
Confidence

#What we need from this

You do not need to be able to derive the training mathematics to design AI infrastructure. You need to know, precisely:

  • Where the parameters live — the model's learned numbers, billions of them, and every one occupies GPU memory you pay for
  • Where the arithmetic happens, because that's compute
  • Which parts have state that persists across tokens, because that's the KV cache
  • Which operations are compute-bound (limited by how fast the GPU can do arithmetic) versus memory-bandwidth-bound (limited by how fast data can be moved out of memory to the arithmetic units), because that determines everything about batching

That's the whole agenda. The mathematics is a means to those four answers.

#The shape of a forward pass

Token IDs → embeddings lookup table: vocab × d_model × N layers: attention tokens exchange information — the only place they interact × N layers: feed-forward per-token computation — most of the parameters Final norm → unembedding d_model → vocab logits Sample logits → one token
One forward pass. The middle block repeats 32-100+ times.

The essential structural fact: attention is the only operation where tokens see each other. Everything else — the feed-forward network, normalisation, the embedding lookup — operates on each token position independently.

That single asymmetry drives the entire system design. Per-token work needs nothing from other tokens, so you can run all positions side by side and keep nothing afterwards. Attention is different: each new token needs information from every previous token. That stored per-token information is why the KV cache exists, and why memory rather than compute ends up being the limit you hit first.

#The residual stream

A useful mental model: each token position carries a running list of numbers with it through the whole model — the residual stream. Its length is called d_model, typically 4,096 or 8,192, and it's fixed for a given model. Every block reads that list, computes something from it, and adds the result back in.

   Position i's residual stream, flowing down through layers:

     x  ──┬─────────────────────────────► + ──┬──────────────► + ──► ...
          │                               ▲   │                ▲
          └─► LayerNorm ─► Attention ─────┘   └─► LN ─► FFN ───┘
                          (reads OTHER            (reads only
                           positions)              position i)

   Nothing overwrites. Every block ADDS a contribution.

Two consequences worth holding onto:

  1. Gradients flow straight through the additions, which is what makes 100-layer networks trainable at all. A gradient is the learning signal that travels backwards through the network during training. Plain additions pass it through unchanged, so it doesn't fade away after crossing 100 layers. This is the ResNet insight (from image models) applied to sequences.
  2. The stream is the interface. Layers communicate only through it, which is why techniques like LoRA (adding a low-rank update to a weight matrix) and activation steering (adding a vector to the stream) work without retraining anything else.

#Attention, in the terms that matter for infrastructure

For each position, the model computes three projections from the residual stream:

   Query  Q = x·W_q     "what am I looking for?"
   Key    K = x·W_k     "what do I offer to others?"
   Value  V = x·W_v     "what do I contribute if selected?"

   attention(Q,K,V) = softmax( Q·Kᵀ / √d_head ) · V
                       ─────────────────────
                       score of every position
                       against every position

   Causal masking: position i may only attend to positions ≤ i.
   That is what makes generation possible — position i's output
   does not depend on anything after it.

The three infrastructure-relevant facts:

The score matrix is quadratic. For a sequence of length n, Q·Kᵀ is n × n per head per layer. Doubling the context quadruples this work. A 100K-token prompt produces a 10-billion-entry score matrix per head. That is why nobody ever builds the full matrix in memory. FlashAttention mattered so much because it computes the scores in small tiles that fit in on-chip SRAM (a small, very fast memory next to the arithmetic units) and throws each tile away once used.

K and V for past tokens never change. Because of causal masking, position 5's key and value are identical whether the sequence is 6 tokens long or 6,000. So you compute them once and cache them. That cache is the KV cache, and it is the dominant consumer of GPU memory in serving.

Q for the current token is all you need to move forward. During generation you have one new query attending over a cached set of keys and values. This is a tiny amount of arithmetic against a large amount of memory — the defining characteristic of the decode phase, where the model generates output one token at a time.

#Where the parameters live

   Per layer, for d_model = d, FFN hidden = 4d:

     Attention:  W_q, W_k, W_v, W_o   →  4 × d²      params
     FFN:        W_up (d→4d), W_down (4d→d)
                                      →  8 × d²      params
                                        ────────────
     Total per layer                  ≈ 12 × d²

   → The feed-forward network holds TWO THIRDS of the
     parameters. Attention gets all the attention; the FFN
     gets most of the memory and most of the FLOPs
     (floating-point operations — the actual arithmetic).

This is why quantization is a first-order infrastructure concern rather than a research curiosity.

#The two phases

The same weights, the same code, and two workloads with opposite performance characteristics.

PREFILL — process the prompt • All prompt positions in parallel • Big matrix × big matrix • High arithmetic intensity: lots of maths per byte read • COMPUTE-BOUND — GPU saturated • Produces the first output token DECODE — generate the rest • One position per forward pass • Big matrix × single vector • Reads every weight to emit one token • MEMORY-BANDWIDTH-BOUND — compute mostly idle • Repeats once per output token
Same model, same kernel, opposite bottlenecks. Everything in serving follows from this.

The arithmetic behind that claim is worked out in inference arithmetic, which is the next page and the one that makes all of this quantitative.

#Variations you'll encounter

VariationChangeWhy
Pre-normNormalise before each block rather than afterTrains stably at depth; universal in modern models
RMSNormDrop the mean-centring from LayerNormSame quality, cheaper
SwiGLUGated activation; FFN hidden ≈ 8/3·d across three matricesBetter quality per parameter
RoPERotate Q and K by position rather than adding a position embeddingThe model sees how far apart tokens are, not their absolute slots, and copes better with longer inputs than it trained on — see context windows
GQA / MQASeveral query heads share one K/V headShrinks the KV cache several-fold — the biggest serving win of the last few years
MoEMany FFN experts; route each token to a fewMany more parameters, same FLOPs per token — see mixture of experts

Grouped-query attention is the one to notice. Attention actually runs as many parallel heads (say 64), each with its own Q, K and V. GQA keeps 64 query heads but lets groups of them share one K/V head — say 8 K/V heads in total — so there is 8× less K and V to cache. It is a modest quality tradeoff for a large reduction in KV cache size. Because KV cache size is what limits how many requests fit on a GPU at once, it directly multiplies how many users one GPU can serve.

#Exercise

Check your reasoning on (4): you read essentially all the weights, so ~14 GB at BF16; at 3 TB/s that's ~4.7 ms per token, about 210 tokens/s. Batching does not change per-token latency — it multiplies total throughput, because the same weight read serves every request in the batch.

#Check yourself

What four things does infrastructure need from the transformer?Show answer
Where the parameters live (memory), where the arithmetic happens (compute), what state persists across tokens (the KV cache), and which operations are compute- versus bandwidth-bound (batching).
What is the one place tokens interact?Show answer
Attention. Feed-forward, normalisation and embedding lookups work on each position independently, which is why only attention needs past state.
What is the residual stream?Show answer
A running vector of d_model numbers carried by each position; every block reads it and adds its result back. It makes deep networks trainable and is why LoRA and activation steering work.
Why can past keys and values be cached?Show answer
Causal masking means a position's K and V never change as the sequence grows, so compute them once — the KV cache, the dominant consumer of serving memory.
Where do the parameters live in a layer?Show answer
About 12d² per layer: attention 4d² (Q, K, V, O) and the FFN 8d². The FFN holds two thirds of parameters and FLOPs.
How much memory does a 70B-class model need for weights?Show answer
About 266 GB in FP32, 133 GB in BF16, 67 GB in FP8 and 33 GB in INT4 — precision decides how many GPUs you need.
Why is batching the most important idea in serving?Show answer
Decode streams every weight to produce one token, leaving compute idle; the same weight read can serve a whole batch at almost no extra cost.
What does decode latency scale with?Show answer
Bytes of weights read, not FLOPs — so a model quantized from BF16 to FP8 decodes about 2× faster. Grouped-query attention shrinks the KV cache several-fold.

#What to carry forward

  • Attention is the only place tokens interact. Everything else works on each position independently, so it parallelises easily.
  • The residual stream is the interface; every block reads it and adds back.
  • The FFN holds two thirds of the parameters and FLOPs, despite attention getting the attention.
  • Past K and V never change → cache them → that cache dominates serving memory.
  • Prefill is compute-bound; decode is memory-bandwidth-bound. The same code, opposite bottlenecks.
  • Decode latency scales with bytes of weights, not FLOPs — which is why quantization is a speedup.
00:00
/ 11m