add notes

This commit is contained in:
rasbt
2024-03-17 09:29:06 -05:00
parent b58f66b684
commit 4fc6de7afa
2 changed files with 145 additions and 83 deletions

View File

@@ -37,6 +37,14 @@
"print(\"torch version:\", version(\"torch\"))"
]
},
{
"cell_type": "markdown",
"id": "a2a4474d-7c68-4846-8702-37906cf08197",
"metadata": {},
"source": [
"- This chapter covers attention mechanisms, the engine of LLMs:"
]
},
{
"cell_type": "markdown",
"id": "02a11208-d9d3-44b1-8e0d-0c8414110b93",
@@ -66,7 +74,8 @@
"id": "a55aa49c-36c2-48da-b1d9-70f416e46a6a",
"metadata": {},
"source": [
"- No code in this section"
"- No code in this section\n",
"- Translating a text word by word isn't feasible due to the differences in grammatical structures between the source and target languages:"
]
},
{
@@ -77,12 +86,21 @@
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/03.webp\" width=\"400px\">"
]
},
{
"cell_type": "markdown",
"id": "db03c48a-3429-48ea-9d4a-2e53b0e516b1",
"metadata": {},
"source": [
"- Prior to the introduction of transformer models, encoder-decoder RNNs were commonly used for machine translation tasks\n",
"- In this setup, the encoder processes a sequence of tokens from the source language, using a hidden state—a kind of intermediate layer within the neural network—to generate a condensed representation of the entire input sequence:"
]
},
{
"cell_type": "markdown",
"id": "03d8df2c-c1c2-4df0-9977-ade9713088b2",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/04.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/04.webp\" width=\"500px\">"
]
},
{
@@ -98,7 +116,8 @@
"id": "b6fde64c-6034-421d-81d9-8244932086ea",
"metadata": {},
"source": [
"- No code in this section"
"- No code in this section\n",
"- Through an attention mechanism, the text-generating decoder segment of the network is capable of selectively accessing all input tokens, implying that certain input tokens hold more significance than others in the generation of a specific output token:"
]
},
{
@@ -106,7 +125,15 @@
"id": "bc4f6293-8ab5-4aeb-a04c-50ee158485b1",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/05.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/05.webp\" width=\"500px\">"
]
},
{
"cell_type": "markdown",
"id": "8044be1f-e6a2-4a1f-a6dd-e325d3bad05e",
"metadata": {},
"source": [
"- Self-attention in transformers is a technique designed to enhance input representations by enabling each position in a sequence to engage with and determine the relevance of every other position within the same sequence"
]
},
{
@@ -114,7 +141,7 @@
"id": "6565dc9f-b1be-4c78-b503-42ccc743296c",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/06.webp\" width=\"200px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/06.webp\" width=\"300px\">"
]
},
{
@@ -138,17 +165,20 @@
"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.3.2, 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."
"- This section explains a very simplified variant of self-attention, which does not contain any trainable weights\n",
"- This is purely for illustration purposes and NOT the attention mechanism that is used in transformers\n",
"- The next section, section 3.3.2, 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)}$\n",
" - 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"
]
},
{
@@ -164,37 +194,29 @@
"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",
"- 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:"
]
},
{
"cell_type": "markdown",
"id": "28531e83-85bd-43a4-8928-57bb0372d9c7",
"metadata": {},
"source": [
"<img src=\"figures/attention.png\" width=\"600px\">"
]
},
{
"cell_type": "markdown",
"id": "01b10344-128d-462a-823f-2178dff5fd58",
"metadata": {},
"source": [
"- The code below walks through the figure above step by step.\n",
"- The code below walks through the figure above step by step\n",
"\n",
"<br>\n",
"\n",
"- **Step 1:** compute unnormalized attention scores $\\omega$.\n",
"- **Step 1:** compute unnormalized attention scores $\\omega$\n",
"- 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_{21} = 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."
"- 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"
]
},
{
@@ -224,6 +246,18 @@
")"
]
},
{
"cell_type": "markdown",
"id": "299baef3-b1a8-49ba-bad4-f62c8a416d83",
"metadata": {},
"source": [
"- The primary objective of this section is to demonstrate how the context vector $z^{(2)}$\n",
" is calculated using the second input sequence, $x^{(2)}$, as a query\n",
"\n",
"- The figure depicts the initial step in this process, which involves calculating the attention scores ω between $x^{(2)}$\n",
" and all other input elements through a dot product operation."
]
},
{
"cell_type": "markdown",
"id": "5cb3453a-58fa-42c4-b225-86850bc856f8",
@@ -300,19 +334,19 @@
},
{
"cell_type": "markdown",
"id": "dfd965d6-980c-476a-93d8-9efe603b1b3b",
"id": "7d444d76-e19e-4e9a-a268-f315d966609b",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/09.webp\" width=\"400px\">"
"- **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):"
]
},
{
"cell_type": "markdown",
"id": "7d444d76-e19e-4e9a-a268-f315d966609b",
"id": "dfd965d6-980c-476a-93d8-9efe603b1b3b",
"metadata": {},
"source": [
"- **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):"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/09.webp\" width=\"500px\">"
]
},
{
@@ -376,7 +410,7 @@
"id": "f0a1cbbb-4744-41cb-8910-f5c1355555fb",
"metadata": {},
"source": [
"- The naive implementation above can suffer from numerical instability issues for large or small input values due to overflow and underflow issues.\n",
"- 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:"
]
},
@@ -415,7 +449,7 @@
"id": "f1c9f5ac-8d3d-4847-94e3-fd783b7d4d3d",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/10.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/10.webp\" width=\"500px\">"
]
},
{
@@ -457,8 +491,8 @@
"source": [
"#### Generalize to all input sequence tokens:\n",
"\n",
"- Above, we computed the attention weights and context vector for input 2 (as illustrated in the highlighted row in the figure below).\n",
"- Next, we are generalizing this computation to compute all attention weights and context vectors."
"- Above, we computed the attention weights and context vector for input 2 (as illustrated in the highlighted row in the figure below)\n",
"- Next, we are generalizing this computation to compute all attention weights and context vectors"
]
},
{
@@ -469,6 +503,15 @@
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/11.webp\" width=\"400px\">"
]
},
{
"cell_type": "markdown",
"id": "b789b990-fb51-4beb-9212-bf58876b5983",
"metadata": {},
"source": [
"- In self-attention, the process starts with the calculation of attention scores, which are subsequently normalized to derive attention weights that total 1\n",
"- These attention weights are then utilized to generate the context vectors through a weighted summation of the inputs"
]
},
{
"cell_type": "markdown",
"id": "d9bffe4b-56fe-4c37-9762-24bd924b7d3c",
@@ -674,6 +717,14 @@
"## 3.4 Implementing self-attention with trainable weights"
]
},
{
"cell_type": "markdown",
"id": "88363117-93d8-41fb-8240-f7cfe08b14a3",
"metadata": {},
"source": [
"- A conceptual framework illustrating how the self-attention mechanism developed in this section integrates into the overall narrative and structure of this book and chapter"
]
},
{
"cell_type": "markdown",
"id": "ac9492ba-6f66-4f65-bd1d-87cf16d59928",
@@ -695,14 +746,14 @@
"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",
"- 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",
" - 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."
" - 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"
]
},
{
@@ -710,7 +761,7 @@
"id": "59db4093-93e8-4bee-be8f-c8fac8a08cdd",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/14.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/14.webp\" width=\"600px\">"
]
},
{
@@ -718,7 +769,7 @@
"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",
"- 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",
"\n",
" - Query vector: $q^{(i)} = W_q \\,x^{(i)}$\n",
@@ -731,7 +782,7 @@
"id": "9f334313-5fd0-477b-8728-04080a427049",
"metadata": {},
"source": [
"- 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",
"- 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 input and output dimensions are usually the same, but for illustration purposes, to better follow the computation, we choose different input and output dimensions here:"
]
},
@@ -752,7 +803,7 @@
"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."
"- 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"
]
},
{
@@ -843,7 +894,7 @@
"id": "8ed0a2b7-5c50-4ede-90cf-7ad74412b3aa",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/15.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/15.webp\" width=\"600px\">"
]
},
{
@@ -898,7 +949,7 @@
"id": "8622cf39-155f-4eb5-a0c0-82a03ce9b999",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/16.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/16.webp\" width=\"600px\">"
]
},
{
@@ -906,7 +957,7 @@
"id": "e1609edb-f089-461a-8de2-c20c1bb29836",
"metadata": {},
"source": [
"- 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",
"- 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_k}$ (i.e., `d_k**0.5`):"
]
},
@@ -935,7 +986,7 @@
"id": "b8f61a28-b103-434a-aee1-ae7cbd821126",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/17.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/17.webp\" width=\"600px\">"
]
},
{
@@ -1041,8 +1092,8 @@
"id": "048e0c16-d911-4ec8-b0bc-45ceec75c081",
"metadata": {},
"source": [
"- 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."
"- 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"
]
},
{
@@ -1095,7 +1146,7 @@
"id": "915cd8a5-a895-42c9-8b8e-06b5ae19ffce",
"metadata": {},
"source": [
"- Note that `SelfAttention_v1` and `SelfAttention_v2` give different outputs because they use different initial weights for the weight matrices."
"- Note that `SelfAttention_v1` and `SelfAttention_v2` give different outputs because they use different initial weights for the weight matrices"
]
},
{
@@ -1106,6 +1157,14 @@
"## 3.5 Hiding future words with causal attention"
]
},
{
"cell_type": "markdown",
"id": "aef0a6b8-205a-45bf-9d26-8fd77a8a03c3",
"metadata": {},
"source": [
"n causal attention, the attention weights above the diagonal are masked, ensuring that for any given input, the LLM is unable to utilize future tokens while calculating the context vectors with the attention weight"
]
},
{
"cell_type": "markdown",
"id": "71e91bb5-5aae-4f05-8a95-973b3f988a35",
@@ -1127,9 +1186,9 @@
"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",
"- 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):"
]
},
@@ -1138,7 +1197,7 @@
"id": "57f99af3-32bc-48f5-8eb4-63504670ca0a",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/20.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/20.webp\" width=\"600px\">"
]
},
{
@@ -1251,7 +1310,9 @@
"id": "3eb35787-cf12-4024-b66d-e7215e175500",
"metadata": {},
"source": [
"- 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."
"- However, if the mask were applied after softmax, like above, it would disrupt the probability distribution created by softmax\n",
"- Softmax ensures that all output values sum to 1\n",
"- Masking after softmax would require re-normalizing the outputs to sum to 1 again, which complicates the process and might lead to unintended effects"
]
},
{
@@ -1293,7 +1354,7 @@
"id": "512e7cf4-dc0e-4cec-948e-c7a3c4eb6877",
"metadata": {},
"source": [
"- 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",
"- 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:"
]
},
@@ -1302,7 +1363,7 @@
"id": "eb682900-8df2-4767-946c-a82bee260188",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/21.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/21.webp\" width=\"450px\">"
]
},
{
@@ -1377,13 +1438,13 @@
"id": "ec3dc7ee-6539-4fab-804a-8f31a890c85a",
"metadata": {},
"source": [
"- In addition, we also apply dropout to reduce overfitting during training.\n",
"- 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",
" - 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.)"
"- 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"
]
},
{
@@ -1391,7 +1452,7 @@
"id": "ee799cf6-6175-45f2-827e-c174afedb722",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/21.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/22.webp\" width=\"400px\">"
]
},
{
@@ -1475,8 +1536,8 @@
"id": "09c41d29-1933-43dc-ada6-2dbb56287204",
"metadata": {},
"source": [
"- 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 `CausalAttention` class supports the batch outputs produced by the data loader we implemented in chapter 2.\n",
"- 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 `CausalAttention` 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:"
]
},
@@ -1569,7 +1630,7 @@
"id": "c4333d12-17e4-4bb5-9d83-54b3a32618cd",
"metadata": {},
"source": [
"- Note that dropout is only applied during training, not during inference."
"- Note that dropout is only applied during training, not during inference"
]
},
{
@@ -1577,7 +1638,7 @@
"id": "a554cf47-558c-4f45-84cd-bf9b839a8d50",
"metadata": {},
"source": [
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/23.webp\" width=\"400px\">"
"<img src=\"https://sebastianraschka.com/images/LLMs-from-scratch-images/ch03_compressed/23.webp\" width=\"500px\">"
]
},
{
@@ -1601,7 +1662,7 @@
"id": "70766faf-cd53-41d9-8a17-f1b229756a5a",
"metadata": {},
"source": [
"- Below is a summary of the self-attention implemented previously (causal and dropout masks not shown for simplicity).\n",
"- Below is a summary of the self-attention implemented previously (causal and dropout masks not shown for simplicity)\n",
"\n",
"- This is also called single-head attention:\n",
"\n",
@@ -1672,7 +1733,7 @@
"id": "193d3d2b-2578-40ba-b791-ea2d49328e48",
"metadata": {},
"source": [
"- 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."
"- 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"
]
},
{
@@ -1688,9 +1749,10 @@
"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 `CausalAttention` implementation from earlier), we can write a stand-alone class called `MultiHeadAttention` to achieve the same.\n",
"- While the above is an intuitive and fully functional implementation of multi-head attention (wrapping the single-head attention `CausalAttention` 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:"
"- We don't concatenate single attention heads for this stand-alone `MultiHeadAttention` class\n",
"- Instead, we create single W_query, W_key, and W_value weight matrices and then split those into individual matrices for each attention head:"
]
},
{
@@ -1793,8 +1855,8 @@
"id": "d334dfb5-2b6c-4c33-82d5-b4e9db5867bb",
"metadata": {},
"source": [
"- 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 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"
]
},
@@ -1811,7 +1873,7 @@
"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."
"- 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"
]
},
{
@@ -1860,7 +1922,7 @@
"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",
"- 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 following becomes a more compact way to compute the matrix multiplication for each head separately:"
]
@@ -1910,7 +1972,7 @@
"id": "fa3e4113-ffca-432c-b3ec-7a50bd15da25",
"metadata": {},
"source": [
"- 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."
"- 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"
]
}
],