Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Weighted attention

In the previous chapter, we closed the loophole of peeking at the answers with the causal mask. But the current causal attention still has a hidden problem: a token wears many hats, and its different roles interfere with each other in the weights.

Let us review the computation of self-attention:

Attention(X)=softmax(X⋅XTd)X\text{Attention}(X) = \text{softmax}\left(\frac{X \cdot X^T}{\sqrt{d}}\right) X

The same input XX plays three roles at the same time:

  • the asker: which token am I? What information do I need?

  • the answerer: which token am I? What information can I offer?

  • the information itself: which token am I? What content do I actually carry?

The same token has to ask, answer, and be the information itself. Playing several roles at once, it is hard to do all of them well.

Query, key, value

The solution is to separate the roles: use 3 different sets of weights to generate 3 different vectors for each token. Imagine giving the same token 3 different masks, each worn when playing a different role:

  • Query: plays the asker;

  • Key: plays the answerer;

  • Value: plays the information itself.

These three vectors are obtained by applying a linear transformation to the input XX separately:

Q=X⋅WQ,K=X⋅WK,V=X⋅WVQ = X \cdot W_Q, \quad K = X \cdot W_K, \quad V = X \cdot W_V

Here WQW_Q, WKW_K and WVW_V are three trainable weight matrices, which model training can adjust toward whatever suits each role best. With the roles separated, the formula of self-attention becomes:

Attention(Q,K,V)=softmax(Q⋅KTd)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{Q \cdot K^T}{\sqrt{d}}\right) V

Weighted attention

Attention with the linear projections of QQ, KK and VV is called weighted attention.

Dataset

Character-encoding dataset

Lower triangular matrix layer

Activation functions

Gaussian error linear unit (GELU)

Loss function

GPT cross-entropy loss function

Model

GPT embedding layer

GPT attention layer

We introduce the three linear projections QQ, KK and VV into the GPT attention layer. The forward pass steps are extended to:

  • generate QQ, KK and VV: obtain the query, key and value through three linear layers;

  • compute the attention score matrix: scores=Q⋅KT\text{scores} = Q \cdot K^T;

  • scale: multiply by 1/d1 / \sqrt{d} to prevent the values from getting too large, where dd is the embedding size embedding_size;

  • causal mask: block the future positions with the lower triangular matrix layer;

  • compute the attention weights: use the Softmax activation function to turn each row into a probability distribution;

  • weighted sum: multiply the attention weights by VV to get a new attention vector that fuses the context.

GPT feed-forward network layer

GPT Transformer block

GPT output layer

GPT model

GPT trainer

Hyperparameters

Learning rate

Batch size

Number of epochs

Context size

Embedding size

Number of Transformer blocks

Modeling

Training

Evaluation

prediction:	1742 steps, each (4, 32, 65)
loss:	1.9071517813219405

Inference

ROMEO:
Where as his and andrieus
That end with love will so so be dever onot, as is bideiffutend, go stay.

TRANIO:
That he the lady! elty I'll will thee hom.

ANGELO:
Her davent.

MO' him busio's tis! seest.

PETHA:
Deel he, do mastion; poitrtys love:
Ay, my ye

In this chapter, we added a role separation mechanism to the self-attention mechanism: with the three linear projections QQ, KK and VV, a token has a distinct role when asking, answering and passing on information.

The current self-attention still has a limitation: all tokens use the same single set of QQ, KK and VV. It is like a person who always looks at a problem from one perspective, which is bound to be one-sided. Take the word “apple”: it means something completely different in “eat an apple” and in “Apple phone”, yet the current self-attention can only understand it in one way.

In the next chapter, we will introduce the multi-head mechanism, so that the model learns to understand the context from different angles.

Exercises

  1. Try removing one of the three linear projections QQ, KK and VV and replacing it with XX directly. Observe how the training results change. Which projection has the biggest impact?