"## 3.2 Capturing data dependencies with attention mechanisms"
]
},
{
"cell_type": "markdown",
"id": "b6fde64c-6034-421d-81d9-8244932086ea",
"metadata": {},
"source": [
"- No code in this section"
]
},
{
"cell_type": "markdown",
"id": "5efe05ff-b441-408e-8d66-cde4eb3397e3",
"metadata": {},
"source": [
"## 3.3 Attending to different parts of the input with self-attention"
]
},
{
"cell_type": "markdown",
"id": "6d9af516-7c37-4400-ab53-34936d5495a9",
"metadata": {},
"source": [
"### 3.3.1 A simple self-attention mechanism without trainable weights"
]
},
{
"cell_type": "markdown",
"id": "d269e9f1-df11-4644-b575-df338cf46cdf",
"metadata": {},
"source": [
"- This section explains a very simplified variant of self-attention, which does not contain any trainable weights. This is purely for illustration purposes and NOT the attention mechanism that is used in transformers. The next section, section 3.4, will extend this simple attention mechanism to implement the real self-attention mechanism.\n",
"- Suppose we are given an input sequence $x^{(1)}$ to $x^{(T)}$.\n",
" - The input is a text (for example, a sentence like \"Your journey starts with one step\") that has already been converted into token embeddings as described in chapter 2.\n",
" - For instance, $x^{(1)}$ is a d-dimensional vector representing the word \"Your\", and so forth.\n",
"- **Goal:** compute context vectors $z^{(i)}$ for each input sequence element $x^{(i)}$ in $x^{(1)}$ to $x^{(T)}$ (where $z$ and $x$ have the same dimension).\n",
" - A context vector $z^{(i)}$ is a weighted sum over the inputs $x^{(1)}$ to $x^{(T)}$.\n",
" - The context vector is \"context\"-specific to a certain input.\n",
" - Instead of $x^{(i)}$ as a placeholder for an arbitrary input token, let's consider the second input, $x^{(2)}$.\n",
" - And to continue with a concrete example, instead of the placeholder $z^{(i)}$, we consider the second output context vector, $z^{(2)}$.\n",
" - The second context vector, $z^{(2)}$, is a weighted sum over all inputs $x^{(1)}$ to $x^{(T)}$ weighted with respect to the second input element, $x^{(2)}$. The attention weights are the weights that determine how much each of the input elements contributes to the weighted sum when computing $z^{(2)}$.\n",
" - In short, think of $z^{(2)}$ as a modified version of $x^{(2)}$ that also incorporates information about all other input elements that are relevant to a given task at hand."
]
},
{
"cell_type": "markdown",
"id": "ff856c58-8382-44c7-827f-798040e6e697",
"metadata": {},
"source": [
"- By convention, the unnormalized attention weights are referred to as **\"attention scores\"** whereas the normalized attention scores, which sum to 1, are referred to as **\"attention weights\"**.\n",
"\n",
"- The attention weights and context vector calculation are summarized in the figure below:"
"- Suppose we use the second input token as the query, that is, $q^{(2)} = x^{(2)}$, we compute the unnormalized attention scores via dot products:\n",
" - $\\omega_{12} = x^{(1)} q^{(2)\\top}$\n",
" - $\\omega_{22} = x^{(2)} q^{(2)\\top}$\n",
" - $\\omega_{23} = x^{(3)} q^{(2)\\top}$\n",
" - ...\n",
" - $\\omega_{2T} = x^{(T)} q^{(2)\\top}$\n",
"- Above, $\\omega$ is the Greek letter \"omega\" used to symbolize the unnormalized attention scores.\n",
" - The subscript \"21\" in $\\omega_{21}$ means that input sequence element 2 was used as a query against input sequence element 1."
"- Suppose we have the following input sentence that is already embedded in 3-dimensional vectors as described in chapter 3 (we use a very small embedding dimension here for illustration purposes, so that it fits onto the page without line breaks):"
"- We use input sequence element 2, $x^{(2)}$, as an example to compute context vector $z^{(2)}$; later in this section, we will generalize this to compute all context vectors.\n",
"- The first step is to compute the unnormalized attention scores by computing the dot product between the query $x^{(2)}$ and all other input tokens:"
"- **Step 2:** normalize the unnormalized attention scores (\"omegas\", $\\omega$) so that they sum up to 1.\n",
"- Here is a simple way to normalize the unnormalized attention scores to sum up to 1 (a convention, useful for interpretation, and important for training stability):"
"- However, in practice, using the softmax function for normalization, which is better at handling extreme values and has more desirable gradient properties during training, is common and recommended.\n",
"- Here's a naive implementation of a softmax function for scaling, which also normalizes the vector elements such that they sum up to 1:"
"- The naive implementation above can suffer from numerical instability issues for large or small input values due to overflow and underflow issues.\n",
"- Hence, in practice, it's recommended to use the PyTorch implementation of softmax instead, which has been highly optimized for performance:"
"- **Step 3**: compute the context vector $z^{(2)}$ by multiplying the embedded input tokens, $x^{(i)}$ with the attention weights and sum the resulting vectors:"
"## 3.4 Implementing self-attention with trainable weights"
]
},
{
"cell_type": "markdown",
"id": "2b90a77e-d746-4704-9354-1ddad86e6298",
"metadata": {},
"source": [
"### 3.4.1 Computing the attention weights step by step"
]
},
{
"cell_type": "markdown",
"id": "46e95a46-1f67-4b71-9e84-8e2db84ab036",
"metadata": {},
"source": [
"- In this section, we are implementing the self-attention mechanism that is used in the original transformer architecture, the GPT models, and most other popular LLMs.\n",
"- This self-attention mechanism is also called \"scaled dot-product attention\".\n",
"- The overall idea is similar to before:\n",
" - We want to compute context vectors as weighted sums over the input vectors specific to a certain input element.\n",
" - For the above, we need attention weights.\n",
"- As you will see, there are only slight differences compared to the basic attention mechanism introduced earlier:\n",
" - The most notable difference is the introduction of weight matrices that are updated during model training.\n",
" - These trainable weight matrices are crucial so that the model (specifically, the attention module inside the model) can learn to produce \"good\" context vectors."
]
},
{
"cell_type": "markdown",
"id": "4d996671-87aa-45c9-b2e0-07a7bcc9060a",
"metadata": {},
"source": [
"- Implementing the self-attention mechanism step by step, we will start by introducing the three training weight matrices $W_q$, $W_k$, and $W_v$.\n",
"- These three matrices are used to project the embedded input tokens, $x^{(i)}$ into query, key, and value vectors via matrix multiplication:\n",
"- The embedding dimensions of the input $x$ and the query vector $q$ can be the same or different, depending on the model's design and specific implementation.\n",
"- In GPT models, the dimensions are usually the same, but for illustration purposes, to better follow the computation, we choose different input and output dimensions here:"
"d_in = inputs.shape[1] # the input embedding size, d=3\n",
"d_out = 2 # the output embedding size, d=2"
]
},
{
"cell_type": "markdown",
"id": "f528cfb3-e226-47dd-b363-cc2caaeba4bf",
"metadata": {},
"source": [
"- Below, we initialize the three weight matrices; note that we are setting `requires_grad=False` to reduce clutter in the outputs for illustration purposes, but if we were to use the weight matrices for model training, we would set `requires_grad=True` to update these matrices during model training."
"- Next, in **step 3**, we compute the attention weights (normalized attention scores that sum up to 1) using the softmax function we used earlier.\n",
"- The difference to earlier is that we now scale the attention scores by dividing them by the square root of the embedding dimension, $\\sqrt{d}$ (i.e., `d_out**0.5`):"
"- We can streamline the implementation above using PyTorch's Linear layers, which are equivalent to a matrix multiplication if we disable the bias units.\n",
"- Another big advantage of using `nn.Linear` over our manual `nn.Parameter(torch.rand(...)` approach is that `nn.Linear` has a preferred weight initialization scheme, which leads to more stable model training."
"- Note that `SelfAttention_v1` and `SelfAttention_v2` give different outputs because they use different initial weighs for the weight matrices."
]
},
{
"cell_type": "markdown",
"id": "c5025b37-0f2c-4a67-a7cb-1286af7026ab",
"metadata": {},
"source": [
"## 3.5 Hiding future words with causal self-attention"
]
},
{
"cell_type": "markdown",
"id": "82f405de-cd86-4e72-8f3c-9ea0354946ba",
"metadata": {},
"source": [
"### 3.5.1 Applying a causal attention mask"
]
},
{
"cell_type": "markdown",
"id": "014f28d0-8218-48e4-8b9c-bdc5ce489218",
"metadata": {},
"source": [
"- In this section, we are converting the previous self-attention mechanism into a causal self-attention mechanism.\n",
"- Causal self-attention ensures that the model's prediction for a certain position in a sequence is only dependent on the known outputs at previous positions, not on future positions.\n",
"- In simpler words, this ensures that each next word prediction should only depend on the preceding words.\n",
"- To achieve this, for each given token, we mask out the future tokens (the ones that come after the current token in the input text):"
"- The simplest way to mask out future attention weights is by creating a mask via PyTorch's tril function with elements below the main diagonal (including the diagonal itself) set to 1 and above the main diagonal set to 0:"
"- However, if the mask were applied after softmax, like above, it would disrupt the probability distribution created by softmax. Softmax ensures that all output values sum to 1. Masking after softmax would require re-normalizing the outputs to sum to 1 again, which complicates the process and might lead to unintended effects."
"- While we are technically done with coding the causal attention mechanism now, let's briefly look at a more efficient approach to achieve the same as above.\n",
"- So, instead of zeroing out attention weights above the diagonal and renormalizing the results, we can mask the unnormalized attention scores above the diagonal with negative infinity before they enter the softmax function:"
"### 3.5.2 Masking additional attention weights with dropout"
]
},
{
"cell_type": "markdown",
"id": "ec3dc7ee-6539-4fab-804a-8f31a890c85a",
"metadata": {},
"source": [
"- In addition, we also apply dropout to reduce overfitting during training.\n",
"- Dropout can be applied in several places:\n",
" - for example, after computing the attention weights;\n",
" - or after multiplying the attention weights with the value vectors.\n",
"- Here, we will apply the dropout mask after computing the attention weights because it's more common.\n",
"\n",
"- Furthermore, in this specific example, we use a dropout rate of 50%, which means randomly masking out half of the attention weights. (When we train the GPT model later, we will use a lower dropout rate, such as 0.1 or 0.2.)"
"- Now, we are ready to implement a working implementation of self-attention, including the causal and dropout masks. \n",
"- One more thing is to implement the code to handle batches consisting of more than one input so that our `CausalSelfAttention` class supports the batch outputs produced by the data loader we implemented in chapter 2.\n",
"- For simplicity, to simulate such batch input, we duplicate the input text example:"
"- The main idea behind multi-head attention is to run the attention mechanism multiple times (in parallel) with different, learned linear projections. This allows the model to jointly attend to information from different representation subspaces at different positions."
"- In the implementation above, the embedding dimension is 4, because we `d_out=2` as the embedding dimension for the key, query, and value vectors as well as the context vector. And since we have 2 attention heads, we have the output embedding dimension 2*2=4.\n",
"\n",
"- If we want to have an output dimension of 2, as earlier in single-head attention, we can have to change the projection dimension `d_out` to 1:"
"### 3.6.2 Implementing multi-head attention with weight splits"
]
},
{
"cell_type": "markdown",
"id": "f4b48d0d-71ba-4fa0-b714-ca80cabcb6f7",
"metadata": {},
"source": [
"- While the above is an intuitive and fully functional implementation of multi-head attention (wrapping the single-head attention `CausalSelfAttention` implementation from earlier), we can write a stand-alone class called `MultiHeadAttention` to achieve the same.\n",
"\n",
"- We don't concatenate single attention heads for this stand-alone `MultiHeadAttention` class. Instead, we create single W_query, W_key, and W_value weight matrices and then split those into individual matrices for each attention head:"
"- Note that the above is essentially a rewritten version of `MultiHeadAttentionWrapper` that is more efficient.\n",
"- The resulting output looks a bit different since the random weight initializations differ, but both are fully functional implementations that can be used in the GPT class we will implement in the upcoming chapters.\n",
"- Note that in addition, we added a linear projection layer (`self.out_proj `) to the `MultiHeadAttention` class above. This is simply a linear transformation that doesn't change the dimensions. It's a standard convention to use such a projection layer in LLM implementation, but it's not strictly necessary (recent research has shown that it can be removed without affecting the modeling performance; see the further reading section at the end of this chapter)\n"
]
},
{
"cell_type": "markdown",
"id": "8b0ed78c-e8ac-4f8f-a479-a98242ae8f65",
"metadata": {},
"source": [
"- Note that if you are interested in a compact and efficient implementation of the above, you can also consider the [`torch.nn.MultiheadAttention`](https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html) class in PyTorch."
]
},
{
"cell_type": "markdown",
"id": "363701ad-2022-46c8-9972-390d2a2b9911",
"metadata": {},
"source": [
"- Since the above implementation may look a bit complex at first glance, let's look at what happens when executing `attn_scores = queries @ keys.transpose(2, 3)`:"
"a = torch.tensor([[[[0.2745, 0.6584, 0.2775, 0.8573],\n",
" [0.8993, 0.0390, 0.9268, 0.7388],\n",
" [0.7179, 0.7058, 0.9156, 0.4340]],\n",
"\n",
" [[0.0772, 0.3565, 0.1479, 0.5331],\n",
" [0.4066, 0.2318, 0.4545, 0.9737],\n",
" [0.4606, 0.5159, 0.4220, 0.5786]]]])\n",
"\n",
"print(a @ a.transpose(2, 3))"
]
},
{
"cell_type": "markdown",
"id": "0587b946-c8f2-4888-adbf-5a5032fbfd7b",
"metadata": {},
"source": [
"- In this case, the matrix multiplication implementation in PyTorch will handle the 4-dimensional input tensor so that the matrix multiplication is carried out between the 2 last dimensions (num_tokens, head_dim) and then repeated for the individual heads. \n",
"\n",
"- For instance, the above becomes a more compact way to compute the matrix multiplication for each head separately:"
"- See the [./multihead-attention.ipynb](./multihead-attention.ipynb) code notebook, which is a concise version of the data loader (chapter 2) plus the multi-head attention class that we implemented in this chapter and will need for training the GPT model in upcoming chapters."