CNSLT ACADEMY / INSIDE MODERN AI MODELS

How GPT Works: Complete Forward Pass, Decoding and KV Caching

FOUNDATIONSBEGINNERFREE TEXT LESSONVIDEO 🔒 PRO

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.

How GPT Works: Complete Forward Pass, Decoding and KV Caching

##

  1. 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 "
  1. Tokenisation (`string → [1, 4]`): BPE maps text to integer IDs [791, 4820, 9142, 279].
  2. Embedding Lookup (`[1, 4] → [1, 4, 4096]`): Each ID pulls its 4,096-dimensional starting vector from matrix EE.
  3. Stacked Transformer Blocks (`32×`, shape stays `[1, 4, 4096]`): Inside every block, RMSNorm → RoPE + Causal GQA Attention (storing each layer's KK and VV into the KV Cache) → Residual + → RMSNorm → SwiGLU FFN → Residual +.
  4. 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 WLM∈R4096×128000W_{\text{LM}} \in \mathbb{R}^{4096 \times 128000}. The result is a vector of 128,000 raw unnormalised scores called Logits (z1,…,zVz_1, \dots, z_V).
  5. Temperature Scaling & Softmax: Divide logits by Temperature TT and convert to probabilities:
P(i)=ezi/T∑jezj/TP(i) = \frac{e^{z_i / T}}{\sum_j e^{z_j / T}}
  1. Sampling Strategy: Filter implausible tail tokens (Top-k, Top-p, or Min-p) and draw one token ID—say, 8954 (" loan").
  2. Append & Autoregressive Loop: Feed only the newly generated token 8954 (position
  3. back into Layer 1, attend against positions 1..4 already sitting in the KV Cache, emit " because", and repeat until <|eos|> or max_tokens.

##

  1. 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 tokenRaw Logit (zz)T=0.2T = 0.2 (Sharp / Focused)T=1.0T = 1.0 (Natural)T=1.5T = 1.5 (Flat / Exploratory)
" loan"14.2`99.7%``63.5%``50.7%`
" request"13.00.2%19.1%22.8%
" mortgage"12.50.0%11.6%16.3%
" merger"11.80.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 kk 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 pp (e.g., p = 0.90). At T=1.0T = 1.0 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 pmin×Ptopp_{\text{min}} \times P_{\text{top}}—often preserving coherence better than Top-p at higher temperatures.

##

  1. 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 TT 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 t+1t+1 depends on token tt, 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!)*

##

  1. 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:

KV Cache Bytes=2×L×nkv_heads×dhead×seq_len×bytes_per_param×batch\text{KV Cache Bytes} = 2 \times L \times n_{\text{kv\_heads}} \times d_{\text{head}} \times \text{seq\_len} \times \text{bytes\_per\_param} \times \text{batch}

*(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`):
2×32×8×128×8,192×2=1,073,741,824 bytes=1.00 GiB2 \times 32 \times 8 \times 128 \times 8,192 \times 2 = 1,073,741,824\text{ bytes} = \mathbf{1.00\text{ GiB}}
  • 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

  1. 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.
  2. 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%.
  3. KV-Cache Quantisation (FP8 / INT8): Cuts KV memory footprint in half with negligible quality loss for long-context serving.

##

  1. 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 logprobs on 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.

##

  1. 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.

##

  1. Practical exercise
  2. Calculate the KV-cache VRAM required for a 70B-class GQA model (L = 80, n_kv = 8, d_head = 128, FP16 = 2 bytes) at seq_len = 32,768 tokens for batch = 1 and batch = 8.
  3. 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.
  4. For a customer-facing API, explain two ways Prompt Caching and concise structured outputs cut both monthly spend and p95 latency.

##

  1. Knowledge check
  2. What tensor does the final LM Head produce, and what is its length?
  3. Why does lowering temperature from 1.0 to 0.2 sharpen probability mass onto the top token?
  4. Why is Decode memory-bandwidth-bound rather than compute-bound?
  5. How does PagedAttention increase concurrent user throughput on the same GPU?
  6. Why can two identical temperature = 0 API calls occasionally produce slightly different tokens?

Answer key:

  1. A vector of raw unnormalised scores called logits, of length VV (vocabulary size).
  2. Dividing logits by 0.2 multiplies differences by 5× before exponentiation in Softmax, heavily concentrating probability on the highest logit.
  3. 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.
  4. By allocating non-contiguous KV-cache blocks on demand, eliminating contiguous pre-allocation fragmentation and allowing prefix sharing.
  5. GPU floating-point non-associativity across dynamic batching (and MoE routing) can flip near-tied logits.

##

  1. 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.

##

  1. Further reading
LEARNER FEEDBACK

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.

COURSE PROGRESS0/29 complete
Not yet completed
CHECK YOUR UNDERSTANDING