What conceptual roles do Queries, Keys, and Values play in scaled dot-product attention?

Last updated 22 November 2026

Attention works like a soft, differentiable lookup table. The query says what a token is looking for. Each key advertises what a token offers for matching. Each value is the content actually returned, weighted by how well the query matched the corresponding key.

  • Query (Q): the question: It is a projection of the current token that encodes what information it needs (for example, a verb looking for its subject).

  • Key (K): the address or label:

    • The relevance score is q·k / √d_k.

    • Keys exist only for matching and never appear in the output directly.

  • Value (V): the payload:

    • The output is Σ softmax(scores)_j · v_j, a weighted blend of values.

    • Separating V from K lets a token be found for one reason and contribute different information.

  • Soft vs hard lookup: A Python dict returns the one exact match. Attention returns a weighted mix over all entries, which makes it differentiable end to end.

  • Practical note: during autoregressive decoding, past K and V are reused by every new query. That is why we keep a KV cache but no query cache.

[lang:python] scores = Q @ K.transpose(-2, -1) / d_k**0.5 # match questions to labels weights = scores.softmax(dim=-1) # how much to read from each out = weights @ V # retrieve blended payloads

  • https://mbrenndoerfer.com/writing/scaled-dot-product-attention-transformer-mechanism
  • https://dev.to/nishanthan-k/how-query-key-and-value-qkv-work-in-transformers-199a
  • https://anushkadhiman.medium.com/attention-mechanisms-in-transformers-queries-keys-values-and-beyond-0589f1da8df5
All Transformers interview questions