Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 3/ 160
01. LLM Fundamentals

Self-Attention

Query/key/value projections, multi-head attention, and how models relate tokens across a sequence.

IntermediateQKV · Multi-head · Softmax3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidHands-onQuiz (3)Practice

In plain words

Each word asks "which other words matter to me?", scores them, and takes more information from the ones that score high.

Think of it like…

A reader holding a question while scanning a page: each word is both a query ("what in this page helps me?") and a card with a label (key) and contents (value). The reader gives each card a relevance score, then reads a blend of the cards, weighted by those scores.

Where you’ve seen it

In "The trophy didn't fit in the suitcase because it was too big", the query vector for "it" has a high dot product with the key for "trophy", so that token's value dominates the update to "it". Swap "big" for "small" and a well-trained model shifts the weight toward "suitcase".

Words you’ll hear

Query / key / value
Three learned projections of each token: what it seeks, what it advertises, what it contributes.
Scaled dot-product
softmax(QKᵀ / √d) V, the core attention formula.
Multi-head attention
Several attention operations in parallel, each with its own projections, concatenated afterwards.
Causal mask
Sets scores for future positions to −∞ so decoders can't peek ahead.

Visual diagram

Loading interactive diagram

Theory & deep dive

The computation, step by step

For a sequence of n tokens with vectors X, three weight matrices produce Q = XW_Q, K = XW_K and V = XW_V. The n × n matrix QKᵀ holds a score for every pair of tokens. Dividing by √d (the key dimension) stops large dot products from saturating the softmax, then softmax turns each row into weights that sum to 1. Multiplying by V gives each token a mixture of the values it should attend to.

In a decoder, a causal mask sets scores for later positions to −∞ before the softmax, so each token only mixes information from itself and earlier tokens. This is what makes next-token training possible in parallel: one pass produces a prediction at every position without leakage.

A tiny numeric sketch

If "it" has scores [trophy 4, suitcase 1, because 0] over its visible tokens, softmax gives weights of about 0.94, 0.05 and 0.02, so the new vector for "it" is almost entirely the value of "trophy".

Key takeaway: Attention = softmax(QKᵀ/√d)·V; a causal mask enforces left-to-right.

Multi-head attention and the cost of long sequences

A single head can capture one kind of relation at a time. Multi-head attention splits the model dimension into h heads (for example 32), each with its own Q, K and V projections, so different heads can specialise: one tracks syntax, another coreference, another position-based patterns. Their outputs are concatenated and mixed by an output projection. Grouped-query and multi-query attention share K and V across heads to shrink the KV cache with little quality loss.

The n × n score matrix is the cost driver: doubling the context quadruples attention compute, and naive implementations also materialise that matrix in GPU memory. FlashAttention computes the same result in tiles without storing the full matrix, making long contexts practical; sliding-window and sparse variants limit which tokens each token may see. These are optimisations of how attention is computed, not changes to what it means.

Scaling with length

Going from 8K to 128K tokens is 16× longer, so the attention score computation per layer grows by about 256×. That's why providers price long-context requests higher and why prefill latency rises sharply with prompt length.

Key takeaway: Heads specialise in parallel; attention cost grows quadratically unless optimised.

How it works, step by step

Step 1 of 4
Linear layers

1. Project into Q, K, V

Multiply each token vector by three learned matrices to get its query, key and value.

Q = XW_Q · K = XW_K · V = XW_V
Key numbers at this step
Per head
d_k = d / h

When to use it & trade-offs

What it is

Self-attention lets each token build its next representation as a weighted average of other tokens' information. Every token is projected into a query (what I'm looking for), a key (what I offer) and a value (what I'll contribute). The score between two tokens is the dot product of one's query and the other's key, scaled by √d and passed through softmax to give weights; the output is the weighted sum of the values. Multi-head attention runs several of these in parallel with different projections.

Why it matters: Attention is why transformers resolve "it" to the right noun, follow instructions given thousands of tokens earlier and pull the one relevant line out of a long document. It's also the source of the main costs: compute and memory grow with the square of sequence length unless optimised, which is why long context is expensive and why techniques such as FlashAttention, grouped-query attention and sliding windows exist.

When to reach for it

  • Explaining how a model resolves references across long text
  • Reasoning about why long prompts are slow and costly
  • Choosing serving optimisations such as GQA or FlashAttention

When to avoid or be careful

  • Describing attention weights as a full explanation of model decisions
  • Assuming context length is free to increase
  • Confusing self-attention with cross-attention between two sequences

Attention variants

Multi-head attention (MHA)
Best for: Quality-first training and smaller models

Strengths: Every head has its own K and V; highest flexibility.

Watch out: Largest KV cache.

Grouped-query / multi-query attention
Best for: Serving large models at long context

Strengths: Shares K and V across heads, so a much smaller KV cache and faster decode.

Watch out: Slight quality trade-off at the extreme.

Sliding-window / sparse attention
Best for: Very long sequences

Strengths: Linear-ish cost in length.

Watch out: Tokens can't directly see everything.

Interview signals & numbers to know

When this topic comes up

  • “Explain query, key and value”
  • “Why divide by √d?”
  • “Why is attention quadratic?”
  • Multi-head vs grouped-query attention
  • FlashAttention

Benchmarks & rules of thumb

n² -
attention score entries for n tokens
√d_k -
the scaling factor
16× length -
≈ 256× attention compute

Common mistakes & follow-ups

Common interview mistakes

  • Saying softmax is applied across the whole matrix instead of each row (per query).
  • Forgetting to mask future tokens, which leaks the answer during training.
  • Treating attention weights as a reliable explanation of why the model said something.

Likely interviewer follow-ups

  • Why does attention scale quadratically with sequence length?
  • What's the benefit of multiple heads?
  • How does grouped-query attention reduce memory?
Interview tip: Walk through one concrete token like "it" scoring "trophy" highly. A tiny worked example beats reciting the formula.
Loading hands-on exercise

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Self-Attention with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Transformer Architecture
Next topic
Context Windows