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 lessonStep by step
Inside attention
Maya asks how attention actually decides what to look at.
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?).
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.
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.
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.
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?
- Query and key (correct)
- Key and value
- Value and output
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: