Skip to main content

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.

Attention projections
Q=XWQ,K=XWK,V=XWV

Scores

Score matrix
S=QKT

Entry (i,j) measures the compatibility between query i and key j.

Why scale?

Scaled dot-product
S=QKTdk

Scaling controls the magnitude of dot products as vector dimension grows, helping keep softmax numerically usable.

Softmax and output

Attention weights
A=softmax(QKTdk)
Attention output
Z=AV

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

HowAttentionWorks

Direct focus on attention mechanics.

Open source

HowTransformersWork

Continue from attention to Transformers.

Open source

HowLLMsWork

Connect the mathematics to language models.

Open source

Related solutions

Go deeper into an AI model's mathematics

A concept can be followed from equation to implementation.