Slides · LLM foundations
How LLMs work
1 / 31
How LLMs work
What happens between your prompt and the streamed answer, why attention replaced RNNs, and why long prompts cost memory.
Concept
Why this is worth 30 minutes
- Aarav, the support assistant, writes one token at a time, and each token depends on the ones before it.
- That one fact explains confident wrong answers, slow first tokens and surprise bills.
- Almost every later cost and latency question in the course goes back to this loop.
Four things you will be able to do:
- Trace a prompt through the generation loop.
- Explain why attention replaced RNNs.
- Describe Query, Key, Value scoring, the causal mask and the n x n score matrix.
- Explain prefill, decode and the KV-cache trade.
Concept
An LLM predicts the next token
- Input: a sequence of tokens. Output: a probability for every token in the vocabulary.
- You pick one token (sampling), append it, and ask again.
- This loop is autoregressive generation, and it is the whole of inference.
- Chat formatting, system prompts and tool calls are only structure fed into this same loop.
Mental model: autocomplete that runs again on its own output, until a stop token or the length limit.
Diagram
The generation loop
Worked example
One lap of the loop, with numbers
The probabilities below are illustrative; a real vocabulary has tens of thousands of entries.
| Text so far | Top candidates | Sampled | New text |
|---|---|---|---|
Your order arrives | Thursday 0.62, today 0.21, soon 0.09, other 0.08 | Thursday | Your order arrives Thursday |
Your order arrives Thursday | . 0.55, , 0.30, and 0.10, other 0.05 | , | Your order arrives Thursday, |
- Each row is one trip around the loop.
- The second pick was not the most likely token. Sampling chose it, which is why the same prompt can give different answers.
- Check: each row of probabilities adds to 1.00.
Worked example
From logits to probabilities
The model outputs raw scores (logits). Softmax turns them into probabilities.
softmax(zi)=∑jexp(zj)exp(zi)Illustrative logits for three candidates: 2.0, 1.0, 0.0.
| Candidate | Logit | exp(logit) | Probability |
|---|---|---|---|
| A | 2.0 | 7.389 | 7.389/11.107=0.665 |
| B | 1.0 | 2.718 | 2.718/11.107=0.245 |
| C | 0.0 | 1.000 | 1.000/11.107=0.090 |
| Sum | 11.107 | 1.000 |
- Higher logit means higher probability, and the probabilities always sum to 1.
- A logit that is minus infinity gives exp(−∞)=0, so that candidate gets probability 0. The causal mask uses this.
- How to choose from these probabilities is a later lesson, Sampling parameters and the model landscape.
Check yourself
Check: the loop
Aarav has produced “Your order arrives Thursday”. Name the steps that run before the next token is appended.
Answer
The sequence is embedded (with position information), passed through the transformer blocks, which produce logits. Softmax gives probabilities, one token is sampled, and only then is it appended. The loop repeats until a stop token or the maximum length.
Compare
Why not RNNs?
RNNs and LSTMs read a sequence one token at a time through a hidden state.
| Aspect | RNN / LSTM | Self-attention |
|---|---|---|
| Training across a sequence | Sequential: step 5 needs step 4 | All positions at once |
| Path between token 1 and token 50 | Through every hidden state in between | Direct, one step |
| Long-range information | Squeezed through a fixed-size state again and again | Read straight from the earlier token |
| Cost per layer (Vaswani et al., Table 1) | O(n×d2) | O(n2×d) |
- The paper says the sequential nature “precludes parallelization within training examples”.
- Self-attention pays for this with a larger cost in sequence length n. That is the price seen later in the score matrix.
Diagram
Chain versus direct reads
Diagram
Example: which noun does “big” describe?
“The trophy didn’t fit in the suitcase because it was too big.” The word that settles what “it” means, “big”, comes last. In a decoder-only model it may read the 11 words before it and itself.
Concept
Query, Key, Value: a room of experts
- Each token gets three vectors from its embedding: a Query (what am I looking for), a Key (what do I contain) and a Value (what do I offer).
- A token compares its Query with the Keys of the tokens it may see. The scores become weights.
- The weights blend the Values into the token’s updated representation.
- All tokens do this at once, as a few large matrix multiplications.
Mental model: your note (Query) is compared with each expert’s sign (Key). You take a weighted blend of what the relevant experts say (Value).
Diagram
One token through attention
Math
The formula
Attention(Q,K,V)=softmax(dkQK⊤+M)VThe paper describes masking as setting illegal entries to minus infinity before softmax. Adding a mask of 0 or minus infinity is the usual way to implement that.
| Symbol | Meaning |
|---|---|
| Q | Queries, one row per token (n×dk) |
| K | Keys, one row per token (n×dk) |
| V | Values, one row per token (n×dv) |
| K⊤ | K transposed, so QK⊤ has one score per (asking token, read token) pair |
| dk | Size of the Query and Key vectors |
| dk | Scaling: keeps the dot products from growing with vector size and pushing softmax into tiny gradients |
| M (mask) | 0 where a read is allowed, minus infinity where it is not |
The result has one row per token: its blended Values.
Worked example
Worked example: one token, three visible tokens
Illustrative tiny vectors with dk=4, so dk=2. Token 3 asks, Q=[1,0,1,0]. It sees tokens 1 to 3.
| Token read | Key | Q⋅K | Score = Q⋅K/2 | exp(score) | Weight |
|---|---|---|---|---|---|
| 1 | [1, 0, 0, 0] | 1 | 0.5 | 1.649 | 0.307 |
| 2 | [0, 1, 0, 0] | 0 | 0.0 | 1.000 | 0.186 |
| 3 | [1, 0, 1, 0] | 2 | 1.0 | 2.718 | 0.506 |
| Sum | 5.367 | 1.000 |
Values: V1=[1,0], V2=[0,1], V3=[2,2].
output=0.307×[1,0]+0.186×[0,1]+0.506×[2,2]=[0.307+0+1.012,0+0.186+1.012]=[1.32,1.20]Token 3 matches its own Key best, so its own Value dominates the blend.
Concept
The causal mask
A row is the token asking. A column is the token it may read.
| Asking / read | t1 | t2 | t3 | t4 | t5 |
|---|---|---|---|---|---|
| t1 | yes | no | no | no | no |
| t2 | yes | yes | no | no | no |
| t3 | yes | yes | yes | no | no |
| t4 | yes | yes | yes | yes | no |
| t5 | yes | yes | yes | yes | yes |
- Each token may also read itself (the diagonal). The allowed cells form a triangle. Blocked cells are set to minus infinity before softmax, so they get weight 0.
- In training, the mask lets the model learn next-token prediction at every position in parallel without seeing the answer.
- In generation, there is simply nothing later to read.
Sources[1] Attention Is All You Need[2] The Illustrated Transformer
Diagram
Try it: where does “it” look?
Select the row for it. Predict what will happen to the weight on cat when you raise the temperature. Try it, then turn off the causal mask and find the cell that allows it to look ahead to purred.
Text summary
This is a small, made-up example of how attention weights work, not output from a trained model. The sentence is “The cat sat and it purred”, and a person wrote the score table by hand so that the word “it” looks back at “cat”.
The heatmap is a table. Each row is one word asking which words to read, and each column is a word it could read. Every cell holds a weight between 0 and 1, and the weights in a row add up to 1 before rounding. They come from a softmax over the row’s scores.
Two controls change the table. The causal mask limits each word to itself and the words before it. When it is on, the cells above the diagonal are masked and get a weight of exactly 0, and each row’s weights are shared among fewer words. The temperature slider divides the scores before the softmax. The lesson divides by the square root of the key size, which is a fixed version of the same step; this slider is not the sampling temperature you set when you call a model. A low temperature makes the largest weight in a row bigger, and a high one spreads the weight more evenly.
Previous and Next pick which row the status line describes. Without JavaScript you see only this summary.
The interactive version needs JavaScript. The text summary above says what it shows.
Code
The same thing in code
Python
def attention(Q, K, V, causal_mask):
d_k = Q.shape[-1]
scores = (Q @ K.transpose(-2, -1)) / (d_k ** 0.5) # (n x n)
scores = scores.masked_fill(~causal_mask, float("-inf")) # no peeking ahead
weights = softmax(scores, axis=-1)
return weights @ V- Line 3: every Query against every Key gives an n×n matrix of scores.
- Line 4: future positions become minus infinity.
- Line 5: softmax per row gives weights that sum to 1; blocked cells get 0.
- Line 6: the weights blend the Values.
Worked example
Why the score matrix is n x n
scores has one entry per (asking token, read token) pair, so n tokens give n×n entries.
| Sequence length n | Scores (n×n) | Allowed by the causal mask, 2n(n+1) |
|---|---|---|
| 5 | 25 | 15 |
| 1,024 | 1,048,576 | 524,800 |
| 2,048 | 4,194,304 | 2,098,176 |
| 4,096 | 16,777,216 | 8,390,656 |
- Doubling the length quadruples the scores: 1,048,576 to 4,194,304.
- Masking does not remove the work in this simple version. It only zeroes about half of the entries.
- The feedforward layers scale linearly with length, so total cost grows less steeply than n2 at short lengths.
Check yourself
Check: attention versus RNNs
A teammate says “transformers beat RNNs because they remember more”. Give the two precise reasons, and one cost they accept.
Answer
Training runs over all positions at once, while an RNN must finish step 4 before step 5. And any token reads any earlier token directly, instead of through a fixed-size hidden state that is squeezed at every step. The cost: the score matrix is n x n, so attention work grows with the square of the sequence length.
Check yourself
Check: Query, Key, Value and the mask
In the worked example, token 3 had Q . K scores of 1, 0 and 2 against tokens 1 to 3. Why was the output closest to V3, and why can token 3 not read a token 4 (what would go wrong in training if it could)?
Answer
Token 3’s Query matched its own Key best, so its weight (0.506) was the largest and V3 dominates the blend. Token 4 is blocked by the causal mask: its score would be set to minus infinity, so softmax gives it weight 0. Without the mask, training could peek at the very token it must predict.
Process
Two phases of generation
- Prefill. The model processes the whole prompt in one pass. All tokens are known, so they run in parallel as large matrix multiplications that keep the GPU busy. Prefill sets the time to first token.
- Decode. The model produces one token per step. Each step has little new arithmetic but must read the weights and the stored history from memory, so it is typically limited by memory bandwidth, not compute.
Mental model: prefill is reading the whole question once. Decode is writing the answer one word at a time while glancing at your notes before each word.
Diagram
Prefill and decode over time
Concept
The KV-cache: do not recompute the past
- A past token’s Keys and Values never change once computed.
- The server stores them and, at each step, computes K and V only for the new token.
- Without the cache, every step would recompute Keys and Values, and everything that depends on them, for the whole history.
- It is not a response cache: it never returns a stored answer. It reuses Keys and Values, within one generation and, with prefix or prompt caching, across requests that share the same prompt start.
Sources[3] Mastering LLM Techniques: Inference Optimization[4] Cache strategies
Diagram
What the cache holds at each step
Math
What the cache costs
KV-cache bytes=2×layers×KV-heads×head-dim×sequence length×batch×bytes per value| Term | Meaning |
|---|---|
| 2 | One Key and one Value per entry |
| layers | Transformer blocks; each keeps its own cache |
| KV-heads | Number of Key/Value heads (fewer than Query heads in grouped-query attention) |
| head-dim | Size of each head’s vector |
| sequence length | Tokens stored so far: prompt plus generated |
| batch | Concurrent requests held on the GPU |
| bytes per value | 2 for 16-bit values |
The NVIDIA article states the same idea with hidden size in place of KV-heads times head-dim, and notes that the cache grows linearly with batch size and sequence length.
Worked example
Worked example: cache memory
Illustrative numbers, not a specific model: 32 layers, 8 KV-heads, head-dim 128, 16-bit values.
per token=2×32×8×128×2 bytes=131,072 bytes=128 KiB| Context length | One request | Ten concurrent requests |
|---|---|---|
| 1,024 tokens | 128 MiB | 1.25 GiB |
| 8,192 tokens | 1 GiB | 10 GiB |
| 32,768 tokens | 4 GiB | 40 GiB |
- Linear in context length and in concurrency, so it adds up faster than most people expect.
- This is before counting the model weights.
- If the same model used 32 KV-heads instead of 8, it would be 4 times larger: 512 KiB per token. This is why grouped-query attention exists.
Compare
The trade and its consequences
| Aspect | Without KV-cache | With KV-cache |
|---|---|---|
| Compute per new token | Recomputes K and V (and everything that depends on them) for the whole history | Projects K and V for the new token only |
| Memory | Small | Grows with context and concurrency |
| Helps the first token? | n/a | No. Prefill still processes the whole prompt |
| Helps later tokens? | n/a | Yes |
- Long contexts and many users compete for the same GPU memory, so the cache often caps how many requests a server can run at once.
- Memory-saving options exist: grouped-query attention, sliding-window layers, and quantized or offloaded caches, each trading speed or quality for memory.
Sources[4] Cache strategies[3] Mastering LLM Techniques: Inference Optimization
Concept
In production: a longer prompt has two bills
- “Just use a huge context window” is not free.
- Prefill: doubling the prompt roughly quadruples the attention-score arithmetic, which raises time to first token.
- Memory: the KV-cache grows with context and with every concurrent request.
- When cost or latency jumps after users send longer prompts, check prefill time and cache memory.
- Common mistakes: saying “it just predicts words” with no mechanism, and mixing up the KV-cache with a response cache.
Check yourself
Check: prefill, decode and the cache
Why does the KV-cache not make the first token faster, and what does it make cheaper?
Answer
Before the first token the cache is empty. Prefill must compute Keys and Values for the whole prompt anyway. The cache helps from the second token on, because each decode step computes K and V only for the new token and reuses the stored rest. The price is memory that grows with context length and concurrent requests.
Summary
Recap
- An LLM predicts one token at a time: tokenize, embed, transformer blocks, logits, softmax, sample, append, repeat.
- Self-attention replaced RNNs because it trains in parallel and links any two tokens directly.
- Each token scores its Query against visible Keys (causal mask), softmax gives weights, and the weights blend Values. The score matrix is n x n.
- Prefill is parallel and sets time to first token. Decode is one token per step and is usually memory-bound.
- The KV-cache saves recomputation and costs memory that grows with context and concurrency.
References
References & Sources
Attention Is All You Need (opens in a new tab)
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, et al.2017Advances in Neural Information Processing Systems 30 (NIPS 2017)Paper
arXiv 1706.03762 (opens in a new tab)https://arxiv.org/abs/1706.03762
Used for Self-attention removes recurrence, scaled dot-product attention, the -infinity mask in decoder self-attention, and the per-layer complexity comparison with recurrent layers.
The Illustrated Transformer (opens in a new tab)
Jay Alammar2018Article
https://jalammar.github.io/illustrated-transformer/
Used for Step-by-step walkthrough of Query, Key and Value vectors, softmax weights, and masking future positions with minus infinity.
Mastering LLM Techniques: Inference Optimization (opens in a new tab)
Shashank Verma, Neal Vaidya2023Article
https://developer.nvidia.com/blog/mastering-llm-techniques-inference-optimization/
Used for Prefill is a parallel matrix-matrix operation, decode is memory-bound, the KV-cache stores keys and values and grows linearly with batch size and sequence length, and multi-query and grouped-query attention reduce the number of KV heads.
Cache strategies (opens in a new tab)
Hugging Face2026Documentation
https://huggingface.co/docs/transformers/en/kv_cache
Used for A KV-cache stores key and value computations so they are not recomputed; sliding-window, quantized and offloaded caches trade speed for memory.
Keys: ← → move, Home End first and last, F full screen.