Attention mathematically: why Q, K, and V?
Build attention from linear projections and matrix products to softmax and weighted aggregation.
Mathematics for AIIntermediate
Learning goal
Understand Q, K, V, attention scores, softmax, and weighted aggregation well enough to explain the full computation chain.
Prerequisites
- Vectors and matrices
- Exponentials
- Basic probability
Q, K, and V
The input X is mapped through three parameter matrices. Q and K are used to construct scores; V carries the information that will be aggregated.
Scores
Entry (i,j) measures the compatibility between query i and key j.
Why scale?
Scaling controls the magnitude of dot products as vector dimension grows, helping keep softmax numerically usable.
Softmax and output
Each row of A sums to 1, so it can be interpreted as a distribution of weights over tokens. Z is the weighted combination of Value vectors.
Exercises
- Compute a dot-product score for two small vectors.
- Compute softmax for two simple scores.
- Explain why A is a weight matrix while V carries content.
Related projects
Related solutions
Go deeper into an AI model's mathematics
A concept can be followed from equation to implementation.