Learn the MachineDansk

Explained with an interactive visualization

How self-attention works

Attention is the mechanism that lets each token in a transformer pull in information from other tokens. When the model reads “it” in a sentence, it can look back and work out what “it” refers to. Pick a word below and see where it looks.

The demo needs JavaScript. The text below explains what it shows.

Embed this demo on your site

Copy the code into your page. The demo loads from learnthemachine.com, so it stays up to date, and the link under it shows where it comes from.

Query, key and value

Each token makes three vectors from its own representation: a query (“what am I looking for?”), a key (“what do I offer?”) and a value (“what do I pass on if someone looks at me?”). All three are linear maps of the same input, and the model learns the weights behind them during training.

From scores to weights

To work out where a token should look, you take the dot product of its query with every other token’s key. A large dot product means the key matches what the query is looking for. The scores are divided by √d, where d is how many numbers each vector has, so they do not grow too large when d is large. Softmax then turns the scores into weights that are positive and add up to 1.

The token’s output is a weighted mix of all the values. If “it” puts 63% of its weight on “cat”, its output is mostly the value of “cat”. That is how information moves between positions.

Sharpness

The slider multiplies every score by the same number before softmax. It works like temperature in reverse: high sharpness concentrates the weight on the best match, and at 0 the weight is spread evenly. A real model has no slider; the size of the query and key vectors, which training learns, decides how sharp the pattern is.

The causal mask

A language model that predicts the next token must not look at the future. So the scores for later positions are set to minus infinity, which gives them a weight of 0 after softmax. Turn the mask off and every word can also see the words after it. That is how an encoder model such as BERT reads text.

Multiple heads

A transformer has many attention heads in each layer, each with its own query, key and value weights. One head might follow pronouns back to nouns; another might look at the previous token. Their outputs are combined and passed on to the next layer.

An attention pattern shows where the model looks, but not whether it uses what it finds. To test that, you have to intervene in the calculation and measure the effect, for example with activation patching.

Train your own transformer and read its attention

In the Transformer lab you change query, key and value yourself, train a small attention model in the browser and a one-layer transformer in PyTorch, and examine its actual attention pattern with activation patching. The lab requires full access.

See the Transformer labStart free with Tokenization

More explainers