Bookmarks

Attention mechanism

An operation in a neural network that decides, for each token, which other tokens in the sequence to look at and how strongly, and builds a new representation from them.

Also: attention, self-attention, self-attention, multi-head attention, multi-head attention

checked 18 Nov

All terms

The attention mechanism lets a model link distant parts of a text: a word at the end of a paragraph can “refer” to a word at the beginning. It is the main building block of the transformer, and in language models it is the main reason a long context is expensive.

Queries, keys and values

For each token, the model computes three vectors: a query, a key and a value. A token’s query is compared with the keys of all tokens, and the comparison yields weights that sum to one. The result is the sum of the values, weighted by those weights. In self-attention, the queries, keys and values all come from the same sequence. In generative language models, a token looks only at itself and the preceding tokens; future tokens are hidden by a mask.

Heads and saving memory

The model runs a single attention operation as several parallel “heads”, each of which learns to look for its own type of relationship. The original transformer had 8 heads of 64 dimensions each. During generation, the keys and values of past tokens are stored in the KV cache, and the more key and value groups a model has, the larger that cache is.

VariantKeys and valuesWhat it gives
Multi-head (MHA)a separate pair for each query headthe highest quality, the largest KV cache
Multi-query (MQA)one pair for all headsthe smallest cache, possible loss of quality
Grouped-query (GQA)one pair per group of query headsa compromise: a cache several times smaller at similar quality

Attention was proposed in 2014 for neural machine translation, and the transformer was built entirely on it in the paper “Attention Is All You Need” (2017). GQA was described in 2023.

Sources

the term is written from these pages

Verified 18 Nov

Not to be confused with

what it is mixed up with and how it differs

  • transformer

    The transformer is the whole architecture, while attention is one of its operations, repeated in every layer.

  • KV cache

    The KV cache stores keys and values that have already been computed, while attention is the operation that uses them.

In depth in the references

where the topic is covered in detail