How GPT Works: Complete Forward Pass, Decoding and KV Caching
By the end of this lesson, you should be able to trace tensor shapes end-to-end from raw prompt text to the next generated token, compute temperature-scaled Softmax probabilities by hand, contrast Top-k, Top-p, and Min-p decoding, explain why Prefill is compute-bound while Decode is memory-bandwidth-bound, calculate exact KV-cache VRAM requirements, and understand why PagedAttention and Prompt Caching power modern serving engines.
##
- The complete 7-step tensor trace
Let us snap Modules 02, 03, and 04 together on one concrete prompt (batch B = 1, prompt length T = 4, model width d = 4,096, vocabulary V = 128,000, layers L = 32):
"The bank approved the "- Tokenisation (`string → [1, 4]`): BPE maps text to integer IDs
[791, 4820, 9142, 279]. - Embedding Lookup (`[1, 4] → [1, 4, 4096]`): Each ID pulls its 4,096-dimensional starting vector from matrix .
- Stacked Transformer Blocks (`32×`, shape stays `[1, 4, 4096]`): Inside every block, RMSNorm → RoPE + Causal GQA Attention (storing each layer's and into the KV Cache) → Residual
+→ RMSNorm → SwiGLU FFN → Residual+. - Final Norm & LM Head (`[1, 4096] → [1, 128000]`): We take the final token's top-layer hidden vector (position 4, which now synthesises the entire prompt) and multiply it by the unembedding matrix . The result is a vector of
128,000raw unnormalised scores called Logits (). - Temperature Scaling & Softmax: Divide logits by Temperature and convert to probabilities:
- Sampling Strategy: Filter implausible tail tokens (Top-k, Top-p, or Min-p) and draw one token ID—say,
8954(" loan"). - Append & Autoregressive Loop: Feed only the newly generated token
8954(position - back into Layer 1, attend against positions
1..4already sitting in the KV Cache, emit" because", and repeat until<|eos|>ormax_tokens.
##
- Worked example A: how Temperature reshapes logits
Suppose the top 4 candidate logits after "The bank approved the " are loan = 14.2, request = 13.0, mortgage = 12.5, merger = 11.8 (ignoring negligible tail tokens). Watch exact Softmax probabilities shift across three temperatures:
| Candidate token | Raw Logit () | (Sharp / Focused) | (Natural) | (Flat / Exploratory) |
|---|---|---|---|---|
" loan" | 14.2 | `99.7%` | `63.5%` | `50.7%` |
" request" | 13.0 | 0.2% | 19.1% | 22.8% |
" mortgage" | 12.5 | 0.0% | 11.6% | 16.3% |
" merger" | 11.8 | 0.0% | 5.8% | 10.2% |
Now layer on decoding filters (building directly on Lesson 11):
- Greedy Decoding ($T = 0$): Always picks
argmax(" loan"). Best for deterministic classification and structured JSON extraction. - Top-k: Keeps only the fixed top tokens (say,
k = 40). Weakness: too wide when the model is 99% certain, too narrow when 100 valid creative words tie. - Top-p (Nucleus Sampling): Dynamically keeps the smallest top set whose cumulative probability reaches (e.g.,
p = 0.90). At above,loan (63.5%) + request (19.1%) + mortgage (11.6%) = 94.2%, cleanly pruning" merger"and all 127,996 absurd tail tokens. - Min-p: Keeps tokens whose probability is at least —often preserving coherence better than Top-p at higher temperatures.
##
- Prefill vs. Decode: why reading is fast and writing is slow
This single mechanical distinction unlocks real LLM performance engineering (extending Lesson 15):
- Prefill Phase (processing your input prompt): All prompt tokens pass through every weight matrix together as dense matrix-matrix multiplications (GEMM). Arithmetic intensity is high, tensor cores stay saturated, and time spent here drives TTFT (Time To First Token).
- Decode Phase (generating output tokens one by one): Because token depends on token , each step runs a skinny matrix-vector multiplication (GEMV). To emit *just one single word*, the GPU must stream all model weights + the entire KV Cache from HBM VRAM into compute cores. Tensor cores sit mostly idle waiting on memory pipes—making Decode memory-bandwidth-bound and driving TPOT (Time Per Output Token) / tokens-per-second.
*(That is also why most LLM APIs price output tokens 3×–5× higher than input tokens!)*
##
- Worked example B: exact KV-cache VRAM math and PagedAttention
Remember Lesson 15's note that raw model-weight VRAM estimates exclude KV-cache overhead? Here is the exact formula:
*(The factor 2 accounts for storing both K and V tensors at every layer.)*
Let us calculate this for our 7B-class GQA model (L = 32, n_kv = 8, d_head = 128, seq_len = 8,192, FP16 = 2 bytes):
- Single user (`batch = 1`):
- 32 concurrent users (`batch = 32`): `32.00 GiB`—more than 2× the VRAM of the 7B model weights themselves (~14 GiB in FP16)!
- Compare without GQA (classic MHA, `n_kv = 32`): `4.00 GiB` per user, or `128.00 GiB` at 32 users!
### How production engines tame KV memory
- PagedAttention (vLLM): Older servers pre-allocated a contiguous chunk of VRAM for each request's maximum possible length, wasting 60%–80% of memory to internal fragmentation. PagedAttention partitions the KV cache into small non-contiguous fixed-size pages/blocks (just like operating-system virtual memory), allocating blocks dynamically as tokens generate.
- Prefix / Prompt Caching: When 1,000 requests share the same 4,000-token system prompt and policy preamble, the serving engine computes those KV pages once and shares them across requests—slashing TTFT and input token costs by 50%–90%.
- KV-Cache Quantisation (FP8 / INT8): Cuts KV memory footprint in half with negligible quality loss for long-context serving.
##
- AI GRC and security implications
- Why `temperature = 0` is still not 100% bitwise deterministic: Dynamic continuous batching changes GPU floating-point reduction order (and MoE routing), occasionally flipping near-tied logits. Regulated applications must enforce schema validation, log exact model/snapshot IDs, and design idempotent business logic rather than assuming mathematical determinism.
- Logprobs for risk triage: Checking token
logprobson classification or extraction outputs reveals low-confidence guesses (51% Yes / 49% No) that should automatically escalate to human review. - Unbounded generation / Sponge attacks (OWASP LLM10): Because Decode scales linearly with output length and holds KV-cache VRAM for the full duration of the request, adversarial prompts engineered to trigger endless rambling can exhaust GPU memory and inflate bills. Always enforce strict
max_tokens, timeouts, and per-user concurrency caps. - Cross-tenant Prompt-Caching isolation: When using prefix caching in multi-tenant deployments, ensure cache keys are strictly scoped per tenant/ACL so cached KV states from Tenant A can never influence or leak timing information to Tenant B.
##
- Common misconceptions
- “The LLM writes the entire answer internally, then streams it slowly for UX effect.” False. Standard LLMs genuinely generate one token per full forward pass; streaming displays each token as it is decoded.
- “Temperature alters the model's factual knowledge.” False. Weights never change; temperature only reshapes Step 5's probability distribution.
- “A 14 GB model fits comfortably on a 16 GB GPU for production traffic.” False. Once you add KV caches for concurrent users, activation scratchpads, and CUDA overhead, a 16 GB GPU will OOM under even modest concurrency.
##
- Practical exercise
- Calculate the KV-cache VRAM required for a 70B-class GQA model (
L = 80,n_kv = 8,d_head = 128,FP16 = 2 bytes) atseq_len = 32,768tokens forbatch = 1andbatch = 8. - Close your notes and draw the 7-step GPT forward-pass pipeline from raw text to next token, labelling where Prefill, Decode, KV Cache, Temperature, and Top-p sit.
- For a customer-facing API, explain two ways Prompt Caching and concise structured outputs cut both monthly spend and p95 latency.
##
- Knowledge check
- What tensor does the final LM Head produce, and what is its length?
- Why does lowering temperature from
1.0to0.2sharpen probability mass onto the top token? - Why is Decode memory-bandwidth-bound rather than compute-bound?
- How does PagedAttention increase concurrent user throughput on the same GPU?
- Why can two identical
temperature = 0API calls occasionally produce slightly different tokens?
Answer key:
- A vector of raw unnormalised scores called logits, of length (vocabulary size).
- Dividing logits by
0.2multiplies differences by5×before exponentiation in Softmax, heavily concentrating probability on the highest logit. - Generating one token at a time forces the GPU to read billions of weights + KV cache from HBM VRAM per single matrix-vector step, leaving compute cores waiting on memory bandwidth.
- By allocating non-contiguous KV-cache blocks on demand, eliminating contiguous pre-allocation fragmentation and allowing prefix sharing.
- GPU floating-point non-associativity across dynamic batching (and MoE routing) can flip near-tied logits.
##
- Checklist
- [ ] Trace raw text through Tokenisation, Embeddings, Transformer Blocks, LM Head, Softmax, Sampling, and Autoregressive Loop.
- [ ] Size self-hosted GPU VRAM using model weights + exact KV-cache concurrency formula + runtime overhead.
- [ ] Structure prompts with stable static prefixes first to maximise Prompt Caching hit rates.
- [ ] Set explicit
max_tokens, timeouts, and per-tenant concurrency limits to mitigate LLM10 resource exhaustion. - [ ] Use low temperature + strict schema validation (not temperature alone) for structured workflows.
- [ ] Verify tenant isolation policies for shared prefix caches in hosted or self-hosted deployments.
##
- Further reading
- Brendan Bycroft: Interactive 3D LLM Visualization
- Kwon et al. (2023): Efficient Memory Management for Large Language Model Serving with PagedAttention (vLLM)
- Holtzman et al. (2019): The Curious Case of Neural Text Degeneration (Top-p / Nucleus Sampling)
- Hugging Face: Generation Strategies & KV Caching
- OWASP LLM10: Unbounded Consumption
Help improve this learning path.
Suggest a concept we should teach, or tell us what is unclear. No account is required. Email is optional and only for a reply. Do not include confidential or sensitive information.