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.
| Variant | Keys and values | What it gives |
|---|---|---|
| Multi-head (MHA) | a separate pair for each query head | the highest quality, the largest KV cache |
| Multi-query (MQA) | one pair for all heads | the smallest cache, possible loss of quality |
| Grouped-query (GQA) | one pair per group of query heads | a 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- Vaswani et al. Attention Is All You Need (2017)arxiv.org/abs/1706.03762(opens in a new tab)
- Ainslie et al. GQA: Training Generalized Multi-Query Transformer Models (2023)arxiv.org/abs/2305.13245(opens in a new tab)
- Bahdanau, Cho, Bengio. Neural Machine Translation by Jointly Learning to Align and Translate (2014)arxiv.org/abs/1409.0473(opens in a new tab)
Verified 18 Nov