liveBook · Manning

Key

As explained in Build a Large Language Model (From Scratch)

The attention-side vector associated with an input token and compared with a query to determine relevance.

A key is the attention-side vector associated with an input token. Self-attention compares a query with keys to produce relevance scores, then uses those scores to combine value vectors. section 3.4.1 section 3.7

The implementation follows this data flow:

  • Project each input embedding through the trainable matrix W_key: keys = inputs @ W_key. section 3.4.1
  • Compare one query with every key using dot products to obtain attention scores. section 3.4.1
  • Scale and normalize the scores with softmax; the resulting attention weights determine how strongly each value contributes. section 3.4.1

Six-token input

For the sentence “Your journey starts with one step,” a six-token input produces keys with shape [6, 2] when d_out = 2. A query for the second token compares against all six keys. section 3.4.1

Figure 3.14 In the first step of the self-attention mechanism with trainable weight matrices, we compute query (q), key (k), and value (v) vectors for input elements x. Similar to previous sections, we designate the second input, x(2), as the query input. The query vector q(2) is obtained via matrix multiplication between the input x(2) and the weight matrix Wq. Similarly, we obtain the key and value vectors via matrix multiplication involving the weight matrices Wk and Wv.
figure

Trace how an input element becomes a key through matrix multiplication alongside its query and value vectors. section 3.4.1

How Build a Large Language Model (From Scratch) covers it

How deep it goes
Traces key projection, tensor shapes, dot-product scoring, scaling, softmax, and value aggregation.
Examples
Uses a six-token sentence, a second-token query, W_key projection, and [6, 2] key tensors.
What it assumes
Starts from embedded input tokens and introduces the query, key, and value projections needed for self-attention.
What you can do after
Build key tensors in PyTorch and use them in scaled dot-product attention computations.
How it connects
Connects keys to queries, values, attention weights, scaled-dot product attention, causal attention masks, and multi-head attention.

Also explained in

Compare how 8 books explain key →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Large Language Model (From Scratch). The section links point to the parts of the book it draws on.