← govind p lal
AI and ML Bootcamp · Lecture 5 · lecture notes

TRANSFORMERS - PART 2: SELF-ATTENTION, KV CACHE, MULTI-HEAD

In short — How do tokens in a sentence talk to each other? Self-attention answers this with queries, keys and values and one formula. This lecture breaks the formula down, writes it in NumPy, then shows the KV cache (why the first token is slow and long context is hard) and multi-head attention.

Self-attention: the intuition

adds to earlier · Importance-score mechanism, dynamic weighting and the 'it refers to bank' example; heart of the transformer block. · builds on Lecture 2: Week 1 - AI and ML | Fast-tracking the course of AI | 18/01/2026, Lecture 4: Week 3 - AI and ML | Transformers- Part 1 | 31/01/2026

Embeddings give each word meaning. Positional embeddings give order. But how does the sentence talk to itself? -> Self-attention.

Example

"The bank was closed because it was a holiday." The token "it" gives high attention to "bank" and almost none to "closed" or "holiday".

Transformer block = self-attention -> feed forward, repeated in N blocks. Feed forward is the simple neural network already learned.

!

Positional embeddings (sinusoidal) are not learned. Sine and cosine are fixed functions, so nothing to train.

Query, Key, Value

builds on Lecture 4: Week 3 - AI and ML | Transformers- Part 1 | 31/01/2026

Input embedding = token embedding + positional embedding. Before attention, each token gets three vectors made from it.

VectorMeaningRole
Query (Q)What am I looking for?The question it asks others
Key (K)What do I contain?What others match against
Value (V)What information do I offer?What is handed over if matched

Database lookup is a hard lookup: exact match only. Attention is a soft lookup: partial or fuzzy matches, each with a score.

!

Layer normalization before the projections keeps values from getting too big or too small. It only stabilises the maths.

The attention formula, step by step

builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026
  1. Q K^T - similarity of every query with every key
  1. Divide by sqrt(d_k) - d_k is the key dimension. Scaling keeps numbers and gradients stable in backprop. Otherwise values blow up or die off. Found by experiment. Relative order of scores stays the same.
  1. Softmax - turns raw scores into a probability distribution between 0 and 1 that sums to 1.
Example

Input 2, 1, 0.1 -> 0.66, 0.24, 0.10. Sum = 1. Now it reads as 66%, 24%, 10%.

  1. Multiply by V (weighted sum) - each token collects the values of others in proportion to its attention weights. Result: a context-rich representation.
Q x K transposesimilarity scoresDivide by sqrt(d_k)stabilitySoftmax0 to 1, sums to 1Multiply by Vweighted sum
Four steps of attention.

Attention weights can be drawn as a heat map (n x n). Bright = high attention, dark = low.

Example

"The animal didn't cross the street because it was too tired." The query of "it" matches the key of "animal", so "it" absorbs animal's meaning.

Self-attention in NumPy

builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026
import numpy as np

def softmax(x):
    e = np.exp(x - x.max(axis=-1, keepdims=True))
    return e / e.sum(axis=-1, keepdims=True)

X = np.random.randn(3, 8)       # 3 tokens, 8 dims
Wq = np.random.randn(8, 4)
Wk = np.random.randn(8, 4)
Wv = np.random.randn(8, 4)
Q, K, V = X @ Wq, X @ Wk, X @ Wv  # each 3x4

def self_attention(Q, K, V):
    dk = K.shape[-1]
    scores = Q @ K.T / np.sqrt(dk)  # 3x3
    w = softmax(scores)
    return w @ V, w

Generation flow and KV cache

adds to earlier · What attention computes per step, the KV cache optimization, time to first token vs tokens per second, and why long context is hard. · builds on Lecture 2: Week 1 - AI and ML | Fast-tracking the course of AI | 18/01/2026

Generation is autoregressive: one token out, appended to input, run again. Each step runs attention over the whole sequence.

Problem

Is everything recomputed at every step? For "the cat sat", when generating the next token, the keys and values of "the", "cat", "sat" are identical to the previous step.

Solution

Only the new token needs a new query (its own new question). Previous keys and values are stored and reused -> KV cache.

store K, Vold K, Vnew QNew tokenCompute new Q, K, VKV cacheold keys and valuesAttentionNext token
Only the new query is fresh; keys and values come from the cache.

Why the first token is slow -> the cache is empty, so K and V for the whole prompt must be built. Later tokens reuse it.

MetricMeaning
Time to first tokenHow fast the prompt is processed and the cache filled
Tokens per secondAverage speed of each later token
!

Time to first token and tokens per second are different metrics. Mixing them up is a red flag in interviews.

Why long context is hard

Multi-head attention

One head explores only one kind of relationship. Several heads look at different things at once, giving richer context.

8 heads x 96 = 768 after concatenating the outputs, back to the model dimension. A model has N stacked transformer blocks, each with multi-head self-attention.

Glossary

Self-attention
Each token scores every other token and gathers information from the relevant ones.
Query
Vector saying what a token is looking for.
Key
Vector saying what a token contains, matched against queries.
Value
Vector holding the information a token offers when matched.
Dot product
Operation that measures how aligned two vectors are.
Softmax
Function turning scores into probabilities between 0 and 1 that sum to 1.
KV cache
Stored keys and values of earlier tokens reused during generation.
Time to first token
Delay before the first output token, dominated by building the cache.
Multi-head attention
Several attention heads run in parallel, each on a smaller dimension.
Transpose
Matrix with rows and columns swapped.