Scaled dot-product self-attention
In the simple attention mechanism, the attention weights are computed deterministically from the input context. We call the combination of context-free embedding (eg word2vec) and positional embedding, the input embedding. What we would like to do is to Given the input embedding, the output embedding has no information about the data distribution that the input token is part of outside the context. Lets look at the grammatical structure of the following sentences:-
“I love bears”
- Subject: I
- Verb: love
- Object: bears
-
“She bears the pain”
- Subject: She
- Verb: bears
- Object: the pain
-
“Bears won the game”
- Subject: Bears
- Verb: won
- Object: the game
bears plays a different function in each sentence: as an object, as a verb, and as a subject. In addition, we have other and more complicated language patterns, such as this:
-
“The hiking trail led us through bear country.”
- Subject: “The hiking trail”
- Verb: “led”
- Object: “us”
- Prepositional Phrase: “through bear country”
- Preposition: “through”
- Object of the Preposition: “bear country”
- Noun: “country”
- Adjective: “bear” (modifying “country”)
Linear transformation of the input embeddings
This is done by projecting the input embeddings using a projection matrix obtaining a new coordinate system whoseaxes can be associated with object, verb, subject, adjective etc. The semantic meaning of such new coordinate system is not necessary to be explicitly defined but it helps understand what this projection may achieve.
We define three such trainable matrices and ask each token (or equivalently the matrix ) to project itself to the three different spaces.
where is the input embedding matrix of size where is the input sequence length and is the embedding dimension. are the query, keys and values respectively and the dimensions of the matrices are respectively. Queries and keys occupy typically the same dimensional space ().
Each token is undertaking three roles, lets focus here on the first two:
In a query role the current token effectively seeks to find other functions eg ‘adjective’
In a key role the current token effectively expresses its own function eg ‘noun’.
For example: ‘I am key=noun’ and I am seeking for a earlier query=adjective’.
The premise that that after training, the attention mechanism will be able to reveal the keys of the input context that can best respond to the query.
Let us now recall what we saw already during the word2vec construction: we trained a network that will take one-hot vectors of semantically similar tokens that were orthonormal and projected them to vectors that are close to each other in the embedding space. So we have seen evidence that a projection with proper weights can cause all sorts of interesting mappings to happen from a large dimensional space to a lower space. By analogy, the multiplication of the matrix with the input token embedding will create a vector (a point) in the d_k dimensional space that will represent the query. Similarly the multiplication of the matrix with each and every input token embedding will create vectors (a point) in the d_k dimensional space that will represent the keys. After training the keys that can best respond to the query will end up close to it.
Computation of the attention scores
Lets see an example of the projection of the input embeddings to the query and key spaces for the input context.Given matrices and (the key parameter matrix is analogous) where: The resulting matrix , where , will have dimensions . Each element of is computed as: Notice something not obvious earlier: the matrix allows to weigh differently some features of the input embedding (across the dimensions) than others when it calculates the query and key vectors. Lets now proceed with the evolved dot product that now is done at the query-key space. “The hiking trail led us through bear country.” where Now that we have projected the tokens in their new space we can form the generalized dot product Geometrically you can visualize this as shown below:

Scaling
We divide the scores by the square root of the dimension of the key vector (). This is done in to prevent the softmax from saturating on the higher attention score elements and severely attenuating the attention weights that correspond to the lower attention scores. We can do an experiment to see the behavior of softmax.

Masking and Causal Attention
When we decode we do not want to use the attention scores of the future tokens since we dont want to train the tranformer using ground truth that will simply wont be available during inference. To prevent this from happening we mask the attention scores of the future tokens by setting them to before passing them through the softmax. This will cause the softmax to output a vector of values that are very close to 0 for the future tokens - for query , only keys through are accessible. All keys with are masked (i.e., set to ).Softmax
The dot-product terms will be positive or negative numbers and as also in the case of the simpler version of the attention mechanism, we will pass them through a softmax function column-wise to obtain the attention weights for each of the tokens.Weighting the values
We then use the attention weights to create a weighted sum of each of the values to obtain the output embedding. where is the attention weight of the token of the input sequence for the value of the input sequence of length T. What purpose the values play though and why the matrix ? The values are the actual information that the input token will use to update its embedding. The matrix is used to project the input tokens to values (points) in a dimensional space. There is no reason to make the dimensionality of the value space the same as the dimensionality of the key space but typically they are the same. We use the value projection () as a way to decouple the determination of the attention weights from the actual adjustment of their specific embeddings.
bear) that adjusts the specific noun (country) and makes it a bear country vector.

Example
An example of the output of the scaled dot-product self-attention is shown below using thebertviz library.


PyTorch reference
Key references: (Kottur et al., 2015; Rong, 2014; Collobert et al., 2011; Dong et al., 2017; Dauphin et al., 2016)
References
- Collobert, R., Weston, J., Bottou, L., Karlen, M., Kavukcuoglu, K., et al. (2011). Natural Language Processing (almost) from Scratch.
- Dauphin, Y., Fan, A., Auli, M., Grangier, D. (2016). Language Modeling with Gated Convolutional Networks.
- Dong, J., Li, X., Snoek, C. (2017). Predicting Visual Features from Text for Image and Video Caption Retrieval.
- Kottur, S., Vedantam, R., Moura, J., Parikh, D. (2015). Visual Word2Vec (vis-w2v): Learning Visually Grounded Word Embeddings Using Abstract Scenes.
- Rong, X. (2014). word2vec Parameter Learning Explained.

