Attention (machine learning)
Lua error in package.lua at line 80: module 'strict' not found. In artificial neural networks, attention is a technique that is meant to mimic cognitive attention. This effect enhances some parts of the input data while diminishing other parts—the motivation being that the network should devote more focus to the important parts of the data, even though they may be a small portion of an image or sentence. Learning which part of the data is more important than another depends on the context, and this is trained by gradient descent.
Attention-like mechanisms were introduced in the 1990s under names like multiplicative modules, sigma pi units[1], and hyper-networks.[2] Its flexibility comes from its role as "soft weights" that can change during runtime, in contrast to standard weights that must remain fixed at runtime. Uses of attention include memory in fast weight controllers,[3] neural Turing machines, reasoning tasks in differentiable neural computers,[4] language processing in transformers, and LSTMs, and multi-sensory data processing (sound, images, video, and text) in perceivers. [5][6][7][8]
Contents
The Gist
Correlating the different parts within a sentence or a picture can help capture its structure. The attention scheme gives a neural network an opportunity to do that. For example, in the sentence "See that girl run.", when the network processes "that" we want it to know that this word refers to "girl". The next diagram shows how a well-trained network can make this happen.
- X is the input matrix of word embeddings, size 4 x 300. x is the word vector for "that".
- The attention head consists of 3 neural networks to be trained. Each has 100 neurons with a weight matrix sized 300 x 100.
- (*) this calculation is softmax( qKT / sqrt(100) ), without V. Rescaling by sqrt(100) prevents a high variance in qKT that would allow a single word to excessively dominate the softmax resulting in attention to only one word, as a discrete hard max would do.
Notation: the commonly written row-wise softmax formula here assumes that vectors are rows, which contradicts the standard math notation of column vectors. More correctly, we should take the transpose of the context vector and use the column-wise softmax, resulting in the more correct form
The structure of the input data is captured in the Qw and Kw weights, and the Vw weights express that structure in terms of more meaningful features for the task being trained for. For this reason, the attention head components are called Query (Q), Key (K), and Value (V)—a loose and possibly misleading analogy with relational database systems.
We can greatly speed up calculations by parallelizing the above. Note that the context vector for "that" does not rely on context vectors for the other words; therefore we can calculate all context vectors at once by simply using the matrix X of stacked word embeddings instead of x in the formula above. Now, the softmax should be interpreted as a matrix softmax acting on separate rows. This is a huge advantage over recurrent networks which must operate sequentially.
A language translation example
To build a machine that translates English to French, an attention unit is grafted to the basic Encoder-Decoder (diagram below). In the simplest case, the attention unit consists of dot products of the recurrent encoder states and does not need training. In practice, the attention unit consists of 3 trained, fully-connected neural network layers called query, key, and value.
[[File:attention-1-sn.png
|none|700px| Encoder-decoder with attention. The left part (black lines) is the encoder-decoder, the middle part (orange lines) is the attention unit, and the right part (in grey & colors) is the computed data. Grey regions in H matrix and w vector are zero values. Numerical subscripts indicate vector sizes while lettered subscripts i and i − 1 indicate time steps.]]
Label | Description |
---|---|
100 | Max. sentence length |
300 | Embedding size (word dimension) |
500 | Length of hidden vector |
9k, 10k | Dictionary size of input & output languages respectively. |
x, Y | 9k and 10k 1-hot dictionary vectors. x → x implemented as a lookup table rather than vector multiplication. Y is the 1-hot maximizer of the linear Decoder layer D; that is, it takes the argmax of D's linear layer output. |
x | 300-long word embedding vector. The vectors are usually pre-calculated from other projects such as GloVe or Word2Vec. |
h | 500-long encoder hidden vector. At each point in time, this vector summarizes all the preceding words before it. The final h can be viewed as a "sentence" vector, or a thought vector as Hinton calls it. |
s | 500-long decoder hidden state vector. |
E | 500 neuron RNN encoder. 500 outputs. Input count is 800–300 from source embedding + 500 from recurrent connections. The encoder feeds directly into the decoder only to initialize it, but not thereafter; hence, that direct connection is shown very faintly. |
D | 2-layer decoder. The recurrent layer has 500 neurons and the fully-connected linear layer has 10k neurons (the size of the target vocabulary).[9] The linear layer alone has 5 million (500 × 10k) weights – ~10 times more weights than the recurrent layer. |
score | 100-long alignment score |
w | 100-long vector attention weight. These are "soft" weights which changes during the forward pass, in contrast to "hard" neuronal weights that change during the learning phase. |
A | Attention module – this can be a dot product of recurrent states, or the query-key-value fully-connected layers. The output is a 100-long vector w. |
H | 500×100. 100 hidden vectors h concatenated into a matrix |
c | 500-long context vector = H * w. c is a linear combination of h vectors weighted by w. |
Viewed as a matrix, the attention weights show how the network adjusts its focus according to context.
I | love | you | |
je | 0.94 | 0.02 | 0.04 |
t' | 0.11 | 0.01 | 0.88 |
aime | 0.03 | 0.95 | 0.02 |
This view of the attention weights addresses the neural network "explainability" problem. Networks that perform verbatim translation without regard to word order would show the highest scores along the (dominant) diagonal of the matrix. The off-diagonal dominance shows that the attention mechanism is more nuanced. On the first pass through the decoder, 94% of the attention weight is on the first English word "I", so the network offers the word "je". On the second pass of the decoder, 88% of the attention weight is on the third English word "you", so it offers "t'". On the last pass, 95% of the attention weight is on the second English word "love", so it offers "aime".
Variants
Many variants of attention implement soft weights, such as
- "internal spotlights of attention"[10] generated by fast weight programmers or fast weight controllers (1992)[3] (also known as transformers with "linearized self-attention"[11][12]). A slow neural network learns by gradient descent to program the fast weights of another neural network through outer products of self-generated activation patterns called "FROM" and "TO" which in transformer terminology are called "key" and "value." This fast weight "attention mapping" is applied to queries.
- Bahdanau Attention,[13] also referred to as additive attention,
- Luong Attention [14] which is known as multiplicative attention, built on top of additive attention,
- highly parallelizable self-attention introduced in 2016 as decomposable attention [15] and successfully used in transformers a year later.
For convolutional neural networks, attention mechanisms can be distinguished by the dimension on which they operate, namely: spatial attention,[16] channel attention,[17] or combinations.[18][19]
These variants recombine the encoder-side inputs to redistribute those effects to each target output. Often, a correlation-style matrix of dot products provides the re-weighting coefficients.
1. encoder-decoder dot product | 2. encoder-decoder QKV | 3. encoder-only dot product | 4. encoder-only QKV | 5. Pytorch tutorial |
---|---|---|---|---|
File:Attn-xy-dot.png
Both encoder & decoder are needed to calculate attention.[14]
|
File:Attn-xy-qkv.png
Both encoder & decoder are needed to calculate attention.[20]
|
File:Attn-xx-dot.png
Decoder is not used to calculate attention. With only 1 input into corr, W is an auto-correlation of dot products. wij = xi xj[21]
|
File:Attn-xx-qkv.png
Decoder is not used to calculate attention.[22]
|
File:Attn-pytorch-tutorial.png
A fully-connected layer is used to calculate attention instead of dot product correlation.[23]
|
Label | Description |
---|---|
Variables X, H, S, T | Upper case variables represent the entire sentence, and not just the current word. For example, H is a matrix of the encoder hidden state—one word per column. |
S, T | S, decoder hidden state; T, target word embedding. In the Pytorch Tutorial variant training phase, T alternates between 2 sources depending on the level of teacher forcing used. T could be the embedding of the network's output word; i.e. embedding(argmax(FC output)). Alternatively with teacher forcing, T could be the embedding of the known correct word which can occur with a constant forcing probability, say 1/2. |
X, H | H, encoder hidden state; X, input word embeddings. |
W | Attention coefficients |
Qw, Kw, Vw, FC | Weight matrices for query, key, vector respectively. FC is a fully-connected weight matrix. |
⊕, ⊗ | ⊕, vector concatenation; ⊗, matrix multiplication. |
corr | Column-wise softmax(matrix of all combinations of dot products). The dot products are xi* xj in variant #3, hi* sj in variant 1, and columni ( Kw* H )* column j ( Qw* S ) in variant 2, and column i (Kw* X)* column j (Qw* X) in variant 4. Variant 5 uses a fully-connected layer to determine the coefficients. If the variant is QKV, then the dot products are normalized by the sqrt(d) where d is the height of the QKV matrices. |
See also
- Transformer (machine learning model) § Scaled dot-product attention
- Perceiver § Components for query-key-value (QKV) attention
References
<templatestyles src="Reflist/styles.css" />
Cite error: Invalid <references>
tag; parameter "group" is allowed only.
<references />
, or <references group="..." />
External links
- Dan Jurafsky and James H. Martin (2022) Speech and Language Processing (3rd ed. draft, January 2022), ch. 10.4 Attention and ch. 9.7 Self-Attention Networks: Transformers
- Alex Graves (4 May 2020), Attention and Memory in Deep Learning (video lecture), DeepMind / UCL, via YouTube
- Rasa Algorithm Whiteboard - Attention via YouTube
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ 3.0 3.1 Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ 14.0 14.1 Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.
- ↑ Lua error in package.lua at line 80: module 'strict' not found.