My account

Transformers and attention

A language model turns text into tokens, tokens into vectors, sends the vectors through a stack of transformer blocks, and gets a score for every possible next token. Attention lets each token look back at earlier tokens using queries, keys and values. The model writes one token at a time, and the keys and values of earlier tokens never change, which is why the KV cache exists.

Not reviewedWritten with AI helpReading time: 13 minShop assistant examplePython

Author: bezzad

Contents

The problem: words you will hear every day

In inference work, people say “prefill”, “KV cache”, “8 KV heads”, “context length” and “temperature”. These words all come from how a transformer works inside. If the inside is a black box, the serving tricks look like magic. This lesson opens the box, one part at a time, with our shop assistant on an 8B model.

You should know vectors, matrix multiply and softmax (“Math for ML”), and layers and the forward pass (“Neural network basics”).

The whole path, from text to the next token

text: “Where is my order?”tokenizer → token idsembedding: one vector per token (4,096 numbers)32 transformer blockseach block: attention + MLPscores for about 128,000 tokenspick one token (sampling)add the new tokento the text,run againOne step of the modelOne token comes out of each step.
One step of a language model. Text becomes tokens and vectors, goes through 32 blocks, and comes out as one score per possible token. One token is picked and added to the text, and the loop runs again.
  1. Tokenizer. The text “Where is my order?” becomes token ids, small integers like [11649, 374, 856, 2015, 30] (example ids).
  2. Embedding. Each id picks one row from a big table. Our model’s vocabulary has about 128,000 tokens, and each row has 4,096 numbers.
  3. Transformer blocks. The vectors go through 32 blocks. Each block has an attention part and an MLP part (two or three matrix multiplies with an activation).
  4. Output scores. The last vector is multiplied by a matrix that gives one score (logit) for every token in the vocabulary: about 128,000 scores.
  5. Pick one token. Softmax turns the scores into chances, and one token is picked.
  6. Repeat. The new token is added to the text, and the model runs again for the next one.

So the model only ever predicts the next token. A long answer is just this loop, run many times.

Attention: each token looks back

Inside every block, attention lets each token gather information from earlier tokens. For example, in “My order 1042 is late. Where is it?”, the token “it” needs to look back at “order 1042”.

Each token makes three vectors from its own vector, with three weight matrices:

  1. Query (Q): “What am I looking for?”
  2. Key (K): “What do I contain?”
  3. Value (V): “What do I give if you pick me?”

Then:

  1. The score between the current token and each earlier token is the dot product of the current query with that token’s key, divided by √d (d = 128 in our model) to keep the numbers small.
  2. Softmax turns these scores into weights that add up to 1.
  3. The output is the weighted sum of the values.
import numpy as np

def attention(q, K, V):
    # q: (d,) for the current token; K, V: (t, d) for tokens 0..t-1
    scores = K @ q / np.sqrt(q.shape[0])   # (t,)
    w = np.exp(scores - scores.max())
    w = w / w.sum()                        # softmax
    return w @ V                           # (d,)

The causal mask: no looking ahead

A language model is trained to predict the next token, so a token may only look at itself and earlier tokens, never later ones. This rule is called the causal mask.

looks at (keys of earlier tokens)Whereismyorder?Whereismyorder?current tokenallowedmasked (future)
Each row is a token. It can attend only to itself and to tokens before it (filled squares). The empty squares are masked.

This rule has a big effect on serving:

  1. Old tokens never change their keys and values. Token 3’s K and V depend only on tokens 0 to 3.
  2. So we keep them. That is the KV cache: store K and V of every earlier token, for every layer, and compute only the new token’s Q, K and V in each step.
  3. We do not keep old queries. A query is used only by its own token, once.

That is why it is called a KV cache, not a QKV cache.

Heads and grouped-query attention

Attention runs many times in parallel in each layer, as heads. Each head can learn to look for something different (for example names, numbers or grammar).

  1. Our model has 32 query heads of size 128 per layer: 32 × 128 = 4,096, the hidden size.
  2. It has only 8 key/value heads. Each KV head is shared by 4 query heads. This is called grouped-query attention (GQA).
  3. GQA makes the KV cache 4 times smaller than with 32 KV heads, with little loss in quality. That is why “8 KV heads” matters to an inference engineer.

Context length and cost

The context length (or context window) is the most tokens the model can handle in one chat, for example 8,000 or 128,000.

  1. Prefill must compute attention between every prompt token and the tokens before it, so its attention work grows roughly with the square of the prompt length.
  2. Decode compares one new token with all earlier tokens, so each step grows with the chat length.
  3. The KV cache grows by one entry per token, per layer.

Long context is a feature, but you pay for it in time and memory.

Picking the next token: sampling

The model gives chances; a sampler picks one token.

  1. Greedy (temperature 0): always pick the most likely token. Stable, but can repeat itself.
  2. Temperature: divide the scores by a number before softmax. Below 1 makes the top choice stronger; above 1 makes the answer more random.
  3. Top-p (nucleus): keep only the most likely tokens whose chances add up to p (for example 0.9), then pick from them.
def sample(logits, temperature=0.7, rng=np.random.default_rng()):
    if temperature == 0:
        return int(np.argmax(logits))
    p = np.exp((logits - logits.max()) / temperature)
    p = p / p.sum()
    return int(rng.choice(len(p), p=p))

For a support assistant, low temperature is a common choice: answers should be correct and stable, not creative.

Common mistakes

Mistake Result Right way
Thinking the model writes the whole answer at once Wrong speed and cost estimates. It is a loop: one forward pass per new token.
Thinking every word is one token Wrong memory and cost estimates. Count with the model’s tokenizer.
Caching queries too Wasted memory. Only keys and values of earlier tokens are reused.
Ignoring KV heads when sizing memory KV cache off by 4 times or more. Read num_key_value_heads in the config.
Expecting the same answer with temperature above 0 “The model is broken” bug reports. Sampling is random by design.

Summary in six lines

  1. Text → tokens → vectors → 32 blocks → one score per possible token → pick one → repeat.
  2. Attention: the current query is compared with earlier keys; softmax weights sum the values.
  3. The causal mask lets a token see only itself and earlier tokens.
  4. So earlier keys and values never change, and the KV cache keeps them.
  5. Grouped-query attention shares KV heads and makes the cache smaller.
  6. Temperature and top-p decide how the next token is picked.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.