Skip to main content

Subsection 2.4 How Self-Attention Supplies Context

The academic paper that introduced the transformer architecture was called Attention Is All You Need. So what is โ€œattentionโ€ and why is it so important? This section explores what attention is and how it works in the context of a transformer based system like like GPT-2.

Subsubsection 2.4.1 Self-Attention at a High Level

Consider the phrase A robot must obey the orders given it. What does it refer to? A human reader sees that it refers to a robot, several tokens earlier. GPT-2 needs to be able to do the same trick. As it processes it, the tokens for a and robot should be given particular importance in its representation. Other parts of the context like orders are less relevant to understanding what it refers to. Self-attention is the mechanism that allows the model to focus on relevant parts of the context when processing a token.
In this illustration, the attention pattern puts most of its weight on a robot:
While processing โ€œitโ€ in โ€œa robot must obey the orders given it,โ€ masked self-attention gives the most weight to โ€œrobotโ€ and โ€œaโ€ before passing the result to a feed-forward network.

Subsubsection 2.4.2 Self-Attention Process

Self-attention is processed along the path of each token in the segment. The significant components are three vectors:
  • Query. What am I looking for? The query represents the current token. It is the thing that we are trying to understand. Given the token bank the query would be an embedding representing possible meanings of the word โ€œbankโ€ (financial institution, geographical feature of a waterway).
  • Key. What can I offer? Key vectors act as labels for all the tokens in the context. The key vectors are matched against the query to identify what is relevant to that particular query. The word river would have a key vector that represents the fact that it offers context about waterways.
  • Value. What information do I actually hold? Value vectors contain token representations. After relevance scores are calculated, a weighted sum of these vectors represents the current token in context. For our example, the value vector for river would contain information about the characteristics of a river.
A filing cabinet provides a good analogy. The query is a note describing a topic, keys are folder labels, and values are folder contents. Matching the query to the labels identifies relevant contents. Attention combines contents from multiple folders rather than selecting only one.
A note labeled โ€œitโ€ supplies a query that can be compared with keys on folders labeled โ€œa,โ€ โ€œrobot,โ€ โ€œmust,โ€ and โ€œobeyโ€; each folder also contains a value.

Subsubsection 2.4.3 The Mathematics of Attention

This matching of queries to keys is done mathematically by a series of matrix operations and mathematical transformations. We will not cover every detail of these operations, but it is worth understanding at a high level how information flows through the attention mechanism.
Part of what the language model learns as it is trained are weight values to use in these matrix operations. In the diagram below, \(W_Q\text{,}\) \(W_K\text{,}\) and \(W_V\) are learned weight matrices that transform an input vector into query, key, and value vectors. Given two tokens, \(x_1\) and \(x_2\text{,}\) their query, key, and value vectors, \(q_1\text{,}\) \(k_1\text{,}\) \(v_1\text{,}\) \(q_2\text{,}\) \(k_2\text{,}\) and \(v_2\text{,}\) are produced by applying the respective weight matrices to the input vectors.
Separate learned matrices transform the embeddings for โ€œThinkingโ€ and โ€œMachinesโ€ into a query, key, and value vector for each token.
Figure 2.6. Learned projections produce a query, key, and value for each token. The dimensions shown belong to the original Transformer and vary across models.
To calculate a representation for a given token, like machines in this example (\(x_2\)), the model takes that query, and for each token, combines the query with the relevant key to compute an attention score. A softmax function is applied to these scores to weight them so that when summed, they make 1, representing 100% attention. These scores are then used to weight the value vectors, which are summed to produce the final representation for the token. In the diagram below, the final output for machines is shown as \(z_2\) and was calculated by adding the weighted value vectors \(v_1\) and \(v_2\text{:}\)
The query for โ€œMachinesโ€ scores the keys for โ€œThinkingโ€ and โ€œMachinesโ€; softmax weights of 0.88 and 0.12 scale their values, which are summed into the output vector.
GPT-2 performs this calculation separately in each attention head, using only positions allowed by its mask. The decoder-block section below shows how it combines the heads.

Subsubsection 2.4.4 Masking Future Tokens

Masked self-attention refers to the idea that while processing a token, only previous tokens are allowed to influence the current token. Consider the sequence โ€œrobot must obey ordersโ€. When we form the representation for must, we only want the model to use the information from robot. When forming the representation for obey, it can use information from both robot and must.
The diagram below shows the attention mask for the four words. Grayed out squares represent tokens that should not be considered when processing the current token (ones that are masked). Notice how the mask is triangular, allowing each token to attend to itself and all previous tokens, but not to any future tokens.
In four rows for โ€œrobot must obey orders,โ€ each successive token can use itself and earlier tokens, while later tokens are grayed out.
The math for calculating the attention scores is done in matrix form, combining the application of all the query tokens to all the possible keys as one large matrix multiplication. This results in a matrix of scores where each row corresponds to a query token and each column corresponds to the calculated attention score for a key:
Queries for โ€œrobot,โ€ โ€œmust,โ€ โ€œobey,โ€ and โ€œordersโ€ are compared with keys for all four tokens, producing a four-by-four matrix of attention scores.
To apply the mask, we want to โ€œturn offโ€ the attention scores for the masked entries. We can do that by setting the values that should be ignored to negative infinity or a very large negative number (such as -1 billion in GPT-2):
Applying the attention mask changes scores for future token positions to negative infinity, leaving the scores for current and earlier positions intact.
Applying softmax to each row produces the attention weights. Anything that was given a negative infinity value will have a weight of 0:
Softmax converts each row of masked scores into attention weights that sum to one, with zero weight for every future token position.
What this scores table means is the following:
  • When the model processes the first example in the dataset (row #1), which contains only one word ("robot"), 100% of its attention will be on that word.
  • When the model processes the second example in the dataset (row #2), which contains the words ("robot must"), when it processes the word "must", 48% of its attention will be on "robot", and 52% of its attention will be on "must".
  • And so on.