Gradient LabStart the lesson

Lessons › Chapter 11: Transformers and LLMs

Queries, keys and values

Each token makes three vectors: a query (red: what am I looking for?), a key (blue: what do I contain?) and a value (purple: what will I hand over?).

Watch it move. This lesson is interactive on Gradient Lab: every step is an animated scene you can replay.

Start the interactive lesson

Step by step

Story

Inside attention

Maya asks how attention actually decides what to look at.

Concept

Three vectors per token

Each token makes three vectors: a query (red: what am I looking for?), a key (blue: what do I contain?) and a value (purple: what will I hand over?).

Key idea

Match the query against every key

Take “it”’s query and compute its dot product with every token’s key. A big dot product means a good match: “animal” matches best.

Build

Turn scores into weights

Softmax turns the scores into weights that add up to 1: animal 57%, tired 18%, and small amounts for the rest.

Build

Blend the values

Finally, mix everyone’s values using those weights. The result becomes “it”’s new vector, mostly made of “animal”. Every token does this simultaneously, which is why transformers are fast on graphics chips.

Real life

In real life: searching a library

Your question is the query. The labels on the book spines are the keys. What’s inside the books is the value you take home. Attention is that lookup, done softly: you borrow a little from many books, mostly from the best matches.

Quick check: Which two vectors are compared to get the attention scores?

Scores are dot products of one token’s query with every token’s key; values are then mixed.

Pseudocode

for each token:
    query = what am I looking for?
    key   = what do I contain?
    value = what will I hand over?

score(i, j) = query_i · key_j          # a dot product
weights = softmax(scores)
output_i = sum of weights × values

Key terms

query
In attention, a vector saying what this token is looking for.
key
In attention, a vector saying what this token contains, to be matched against queries.
value
In attention, the information a token hands over when it is attended to.

In the news

Recent models and papers that build on this idea: