Merge pull request #1064 from pritesh2000/gram-1/08

08_pytorch_paper_replicating.ipynb
This commit is contained in:
Daniel Bourke authored and GitHub committed 2024-09-05 14:50:34 +10:00
commit 344c834172
1 file changed
+63 -63
+63 -63
View File
@@ -16,8 +16,8 @@
"cell_type": "markdown",
"id": "873828f0-e50f-40b9-9879-f9a01adaa020",
"metadata": {
"tags": [],
"id": "873828f0-e50f-40b9-9879-f9a01adaa020"
"id": "873828f0-e50f-40b9-9879-f9a01adaa020",
"tags": []
},
"source": [
"# 08. PyTorch Paper Replicating\n",
@@ -126,7 +126,7 @@
"\n",
"| **Resource** | **What is it?** |\n",
"| ----- | ----- |\n",
"| [arXiv](https://arxiv.org/) | Pronounced \"archive\", arXiv is a free and open resource for reading technical articles on everything from physics to computer science (inlcuding machine learning). |\n",
"| [arXiv](https://arxiv.org/) | Pronounced \"archive\", arXiv is a free and open resource for reading technical articles on everything from physics to computer science (including machine learning). |\n",
"| [AK Twitter](https://twitter.com/_akhaliq) | The AK Twitter account publishes machine learning research highlights, often with live demos almost every day. I don't understand 9/10 posts but I find it fun to explore every so often. |\n",
"| [Papers with Code](https://paperswithcode.com/) | A curated collection of trending, active and greatest machine learning papers, many of which include code resources attached. Also includes a collection of common machine learning datasets, benchmarks and current state-of-the-art models. |\n",
"| [lucidrains' `vit-pytorch` GitHub repository](https://github.com/lucidrains/vit-pytorch) | Less of a place to find research papers and more of an example of what paper replicating with code on a larger-scale and with a specific focus looks like. The `vit-pytorch` repository is a collection of Vision Transformer model architectures from various research papers replicated with PyTorch code (much of the inspiration for this notebook was gathered from this repository). |\n",
@@ -153,7 +153,7 @@
"\n",
"And the original Transformer architecture was designed to work on one-dimensional (1D) sequences of text.\n",
"\n",
"A **Transformer architecture** is generally considered to be any neural network that uses the [**attention mechanism**](https://en.wikipedia.org/wiki/Attention_(machine_learning)) as its primary learning layer. Similar to a how a convolutional neural network (CNN) uses convolutions as its primary learning layer.\n",
"A **Transformer architecture** is generally considered to be any neural network that uses the [**attention mechanism**](https://en.wikipedia.org/wiki/Attention_(machine_learning)) as its primary learning layer. Similar to how a convolutional neural network (CNN) uses convolutions as its primary learning layer.\n",
"\n",
"Like the name suggests, **the Vision Transformer (ViT) architecture was designed to adapt the original Transformer architecture to vision problem(s)** (classification being the first and since many others have followed).\n",
"\n",
@@ -172,7 +172,7 @@
"| **[6. Equation 3: Multilayer Perceptron (MLP)](https://www.learnpytorch.io/08_pytorch_paper_replicating/#6-equation-3-multilayer-perceptron-mlp)** | The ViT architecture uses a multilayer perceptron as part of its Transformer Encoder and for its output layer. Let's start by creating an MLP for the Transformer Encoder. |\n",
"| **[7. Creating the Transformer Encoder](https://www.learnpytorch.io/08_pytorch_paper_replicating/#7-create-the-transformer-encoder)** | A Transformer Encoder is typically comprised of alternating layers of MSA (equation 2) and MLP (equation 3) joined together via residual connections. Let's create one by stacking the layers we created in sections 5 & 6 on top of each other. |\n",
"| **[8. Putting it all together to create ViT](https://www.learnpytorch.io/08_pytorch_paper_replicating/#8-putting-it-all-together-to-create-vit)** | We've got all the pieces of the puzzle to create the ViT architecture, let's put them all together into a single class we can call as our model. |\n",
"| **[9. Setting up training code for our ViT model](https://www.learnpytorch.io/08_pytorch_paper_replicating/#9-setting-up-training-code-for-our-vit-model)** | Training our custom ViT implementation is similar to all of the other model's we've trained previously. And thanks to our `train()` function in `engine.py` we can start training with a few lines of code. |\n",
"| **[9. Setting up training code for our ViT model](https://www.learnpytorch.io/08_pytorch_paper_replicating/#9-setting-up-training-code-for-our-vit-model)** | Training our custom ViT implementation is similar to all of the other models we've trained previously. And thanks to our `train()` function in `engine.py` we can start training with a few lines of code. |\n",
"| **[10. Using a pretrained ViT from `torchvision.models`](https://www.learnpytorch.io/08_pytorch_paper_replicating/#10-using-a-pretrained-vit-from-torchvisionmodels-on-the-same-dataset)** | Training a large model like ViT usually takes a fair amount of data. Since we're only working with a small amount of pizza, steak and sushi images, let's see if we can leverage the power of transfer learning to improve our performance. |\n",
"| **[11. Make predictions on a custom image](https://www.learnpytorch.io/08_pytorch_paper_replicating/#11-make-predictions-on-a-custom-image)** | The magic of machine learning is seeing it work on your own data, so let's take our best performing model and put FoodVision Mini to the test on the infamous *pizza-dad* image (a photo of my dad eating pizza). |\n",
"\n",
@@ -238,16 +238,16 @@
"execution_count": 1,
"id": "ebe46d77-6c4d-4102-9994-2cb89f633f18",
"metadata": {
"id": "ebe46d77-6c4d-4102-9994-2cb89f633f18",
"outputId": "e9549a27-62c5-41e3-ea94-4df42437c085",
"colab": {
"base_uri": "https://localhost:8080/"
}
},
"id": "ebe46d77-6c4d-4102-9994-2cb89f633f18",
"outputId": "e9549a27-62c5-41e3-ea94-4df42437c085"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"output_type": "stream",
"text": [
"torch version: 2.1.0+cu118\n",
"torchvision version: 0.16.0+cu118\n"
@@ -296,16 +296,16 @@
"execution_count": 2,
"id": "960eb156-c1b1-4e76-a812-01bf045835bd",
"metadata": {
"id": "960eb156-c1b1-4e76-a812-01bf045835bd",
"colab": {
"base_uri": "https://localhost:8080/"
},
"id": "960eb156-c1b1-4e76-a812-01bf045835bd",
"outputId": "ffe99818-a13e-4ade-b330-4f64d8123041"
},
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"output_type": "stream",
"text": [
"[INFO] Couldn't find torchinfo... installing it.\n",
"[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.\n",
@@ -797,7 +797,7 @@
"* **Linear projection of flattened patches (Embedded Patches)** - The image patches get turned into an **embedding**, the benefit of using an embedding rather than just the image values is that an embedding is a *learnable* representation (typically in the form of a vector) of the image that can improve with training.\n",
"* **Norm** - This is short for \"[Layer Normalization](https://paperswithcode.com/method/layer-normalization)\" or \"LayerNorm\", a technique for regularizing (reducing overfitting) a neural network, you can use LayerNorm via the PyTorch layer [`torch.nn.LayerNorm()`](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html).\n",
"* **Multi-Head Attention** - This is a [Multi-Headed Self-Attention layer](https://paperswithcode.com/method/multi-head-attention) or \"MSA\" for short. You can create an MSA layer via the PyTorch layer [`torch.nn.MultiheadAttention()`](https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html).\n",
"* **MLP (or [Multilayer perceptron](https://en.wikipedia.org/wiki/Multilayer_perceptron))** - A MLP can often refer to any collection of feedforward layers (or in PyTorch's case, a collection of layers with a `forward()` method). In the ViT Paper, the authors refer to the MLP as \"MLP block\" and it contains two [`torch.nn.Linear()`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers with a [`torch.nn.GELU()`](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html) non-linearity activation in between them (section 3.1) and a [`torch.nn.Dropout()`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html) layer after each (Appendex B.1).\n",
"* **MLP (or [Multilayer perceptron](https://en.wikipedia.org/wiki/Multilayer_perceptron))** - A MLP can often refer to any collection of feedforward layers (or in PyTorch's case, a collection of layers with a `forward()` method). In the ViT Paper, the authors refer to the MLP as \"MLP block\" and it contains two [`torch.nn.Linear()`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers with a [`torch.nn.GELU()`](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html) non-linearity activation in between them (section 3.1) and a [`torch.nn.Dropout()`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html) layer after each (Appendix B.1).\n",
"* **Transformer Encoder** - The Transformer Encoder, is a collection of the layers listed above. There are two skip connections inside the Transformer encoder (the \"+\" symbols) meaning the layer's inputs are fed directly to immediate layers as well as subsequent layers. The overall ViT architecture is comprised of a number of Transformer encoders stacked on top of eachother.\n",
"* **MLP Head** - This is the output layer of the architecture, it converts the learned features of an input to a class output. Since we're working on image classification, you could also call this the \"classifier head\". The structure of the MLP Head is similar to the MLP block.\n",
"\n",
@@ -807,7 +807,7 @@
"\n",
"> **Question:** Why not code everything from scratch?\n",
">\n",
"> You could definitely do that by reproducing all of the math equations from the paper with custom PyTorch layers and that would certainly be an educative exercise, however, using pre-existing PyTorch layers is usually favoured as pre-existing layers have often been extensively tested and performance checked to make sure they run correctly and fast.\n",
"> You could definitely do that by reproducing all of the math equations from the paper with custom PyTorch layers and that would certainly be an educative exercise, however, using pre-existing PyTorch layers is usually preferred as pre-existing layers have often been extensively tested and performance checked to make sure they run correctly and fast.\n",
"\n",
"> **Note:** We're going to be focused on writing PyTorch code to create these layers. For the background on what each of these layers does, I'd suggest reading the ViT Paper in full or reading the linked resources for each layer.\n",
"\n",
@@ -1005,10 +1005,10 @@
"\n",
"Breaking the hyperparameters down:\n",
"* **Layers** - How many Transformer Encoder blocks are there? (each of these will contain a MSA block and MLP block)\n",
"* **Hidden size $D$** - This is the embedding dimension throughout the architecture, this will be the size of the vector that our image gets turned into when it gets patched and embedded. Generally, the larger the embedding dimension, the more information can be captured, the better results. However, a larger embedding comes at the cost of more compute.\n",
"* **Hidden size $D$** - This is the embedding dimension throughout the architecture, this will be the size of the vector that our image gets turned into when it gets patched and embedded. Generally, the larger the embedding dimension, the more information can be captured, the better results. However, a larger embedding comes at the cost of more computation.\n",
"* **MLP size** - What are the number of hidden units in the MLP layers?\n",
"* **Heads** - How many heads are there in the Multi-Head Attention layers?\n",
"* **Params** - What are the total number of parameters of the model? Generally, more parameters leads to better performance but at the cost of more compute. You'll notice even ViT-Base has far more parameters than any other model we've used so far.\n",
"* **Params** - What are the total number of parameters of the model? Generally, more parameters leads to better performance but at the cost of more computation. You'll notice even ViT-Base has far more parameters than any other model we've used so far.\n",
"\n",
"We'll use these values as the hyperparameter settings for our ViT architecture."
]
@@ -1048,8 +1048,8 @@
"cell_type": "markdown",
"id": "9f1717f5-f6bc-4cce-b5eb-093822da988d",
"metadata": {
"tags": [],
"id": "9f1717f5-f6bc-4cce-b5eb-093822da988d"
"id": "9f1717f5-f6bc-4cce-b5eb-093822da988d",
"tags": []
},
"source": [
"## 4. Equation 1: Split data into patches and creating the class, position and patch embedding\n",
@@ -1095,8 +1095,8 @@
"cell_type": "markdown",
"id": "2010c168-88c7-4045-8c02-8e759ffacef8",
"metadata": {
"tags": [],
"id": "2010c168-88c7-4045-8c02-8e759ffacef8"
"id": "2010c168-88c7-4045-8c02-8e759ffacef8",
"tags": []
},
"source": [
"### 4.1 Calculating patch embedding input and output shapes by hand\n",
@@ -1362,7 +1362,7 @@
"\n",
"How about we do it for the whole image?\n",
"\n",
"This time we'll iterate through the indexs for height and width and plot each patch as it's own subplot."
"This time we'll iterate through the indexes for height and width and plot each patch as it's own subplot."
]
},
{
@@ -1370,9 +1370,9 @@
"execution_count": null,
"id": "7d45e15a-eb50-4c46-8055-2acaaacb881c",
"metadata": {
"tags": [],
"id": "7d45e15a-eb50-4c46-8055-2acaaacb881c",
"outputId": "8e28f9ff-547b-4581-939b-35d708e2d4c0"
"outputId": "8e28f9ff-547b-4581-939b-35d708e2d4c0",
"tags": []
},
"outputs": [
{
@@ -1473,7 +1473,7 @@
"\n",
"> **Hybrid Architecture.** As an alternative to raw image patches, the input sequence can be formed from feature maps of a CNN (LeCun et al., 1989). In this hybrid model, the patch embedding projection $\\mathbf{E}$ (Eq. 1) is applied to patches extracted from a **CNN feature map**. As a special case, the patches can have spatial size $1 \\times 1$, which means that the **input sequence is obtained by simply flattening the spatial dimensions of the feature map and projecting to the Transformer dimension**. The classification input embedding and position embeddings are added as described above.\n",
"\n",
"The \"**feature map**\" they're refering to are the weights/activations produced by a convolutional layer passing over a given image.\n",
"The \"**feature map**\" they're referring to are the weights/activations produced by a convolutional layer passing over a given image.\n",
"\n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-patch-embedding-animation.gif\" width=900 alt=\"example of creating a patch embedding by passing a convolutional layer over a single image\"/>\n",
"\n",
@@ -1533,7 +1533,7 @@
"id": "03dec513-eea5-4d13-b7ab-41c9e997ef48"
},
"source": [
"Now we've got a convoluational layer, let's see what happens when we pass a single image through it."
"Now we've got a convolutional layer, let's see what happens when we pass a single image through it."
]
},
{
@@ -2039,7 +2039,7 @@
"source": [
"Beautiful!\n",
"\n",
"We've turned our single 2D image into a 1D learnable embedding vector (or \"Linear Projection of Flattned Patches\" in Figure 1 of the ViT paper)."
"We've turned our single 2D image into a 1D learnable embedding vector (or \"Linear Projection of Flattened Patches\" in Figure 1 of the ViT paper)."
]
},
{
@@ -2106,7 +2106,7 @@
" def forward(self, x):\n",
" # Create assertion to check that inputs are the correct shape\n",
" image_resolution = x.shape[-1]\n",
" assert image_resolution % patch_size == 0, f\"Input image size must be divisble by patch size, image shape: {image_resolution}, patch size: {patch_size}\"\n",
" assert image_resolution % patch_size == 0, f\"Input image size must be divisible by patch size, image shape: {image_resolution}, patch size: {patch_size}\"\n",
"\n",
" # Perform the forward pass\n",
" x_patched = self.patcher(x)\n",
@@ -2353,7 +2353,7 @@
"\n",
"Now we've got the class token embedding, let's prepend it to our sequence of image patches, `patch_embedded_image`.\n",
"\n",
"We can do so using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) and set `dim=1` (so `class_token`'s `number_of_tokens` dimension is preprended to `patch_embedded_image`'s `number_of_patches` dimension)."
"We can do so using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) and set `dim=1` (so `class_token`'s `number_of_tokens` dimension is prepended to `patch_embedded_image`'s `number_of_patches` dimension)."
]
},
{
@@ -2528,7 +2528,7 @@
"\n",
"# Show the first 10 sequences and 10 position embedding values and check the shape of the position embedding\n",
"print(position_embedding[:, :10, :10])\n",
"print(f\"Position embeddding shape: {position_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]\")"
"print(f\"Position embedding shape: {position_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]\")"
]
},
{
@@ -2772,7 +2772,7 @@
"\n",
"You can find the formal definition of `torch.nn.LayerNorm()` in the [PyTorch documentation](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html).\n",
"\n",
"PyTorch's `torch.nn.LayerNorm()`'s main parameter is `normalized_shape` which we can set to be equal to the dimension size we'd like to noramlize over (in our case it'll be $D$ or `768` for ViT-Base).\n",
"PyTorch's `torch.nn.LayerNorm()`'s main parameter is `normalized_shape` which we can set to be equal to the dimension size we'd like to normalize over (in our case it'll be $D$ or `768` for ViT-Base).\n",
"\n",
"What does it do?\n",
"\n",
@@ -2784,7 +2784,7 @@
"\n",
"It'd take some adjustment on each step right?\n",
"\n",
"And what you learn for each step wouldn't necessary help with the next one since they all differ, increasing the time it takes you to navigate the stairs.\n",
"And what you learn for each step wouldn't necessarily help with the next one since they all differ, increasing the time it takes you to navigate the stairs.\n",
"\n",
"Normalization (including Layer Normalization) is the equivalent of making all the stairs the same height and length except the stairs are your data samples.\n",
"\n",
@@ -2810,15 +2810,15 @@
"\n",
"Since our input is a sequence of image patches rather than words, self-attention and in turn multi-head attention will calculate which patch of an image is most related to another patch, eventually forming a learned representation of an image.\n",
"\n",
"But what's most important is that the layer does this on it's own given the data (we don't tell it what patterns to learn).\n",
"But what's most important is that the layer does this on its own given the data (we don't tell it what patterns to learn).\n",
"\n",
"And if the learned representation the layers form using MSA are good, we'll see the results in our model's performance.\n",
"\n",
"There are many resources online to learn more about the Transformer architeture and attention mechanism online such as Jay Alammar's wonderful [Illustrated Transformer post](https://jalammar.github.io/illustrated-transformer/) and [Illustrated Attention post](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/).\n",
"There are many resources online to learn more about the Transformer architecture and attention mechanism online such as Jay Alammar's wonderful [Illustrated Transformer post](https://jalammar.github.io/illustrated-transformer/) and [Illustrated Attention post](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/).\n",
"\n",
"We're going to focus more on coding an existing PyTorch MSA implementation than creating our own.\n",
"\n",
"However, you can find the formal defintion of the ViT paper's MSA implementation is defined in Appendix A:\n",
"However, you can find the formal definition of the ViT paper's MSA implementation is defined in Appendix A:\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-2-appendix-A.png\" alt=\"vision transformer paper figure 1 highlighted with equation 2 and appendix A\" width=900/>\n",
"\n",
@@ -2888,7 +2888,7 @@
" dropout=attn_dropout,\n",
" batch_first=True) # does our batch dimension come first?\n",
"\n",
" # 5. Create a forward() method to pass the data throguh the layers\n",
" # 5. Create a forward() method to pass the data through the layers\n",
" def forward(self, x):\n",
" x = self.layer_norm(x)\n",
" attn_output, _ = self.multihead_attn(query=x, # query embeddings\n",
@@ -2967,8 +2967,8 @@
"cell_type": "markdown",
"id": "236848a7-a1e0-403d-8c78-d1c61d1e45fd",
"metadata": {
"tags": [],
"id": "236848a7-a1e0-403d-8c78-d1c61d1e45fd"
"id": "236848a7-a1e0-403d-8c78-d1c61d1e45fd",
"tags": []
},
"source": [
"## 6. Equation 3: Multilayer Perceptron (MLP)\n",
@@ -2998,8 +2998,8 @@
"cell_type": "markdown",
"id": "589be777-e2af-48d2-9ba7-4cd922aa1528",
"metadata": {
"tags": [],
"id": "589be777-e2af-48d2-9ba7-4cd922aa1528"
"id": "589be777-e2af-48d2-9ba7-4cd922aa1528",
"tags": []
},
"source": [
"### 6.1 The MLP layer(s)\n",
@@ -3037,8 +3037,8 @@
"cell_type": "markdown",
"id": "baebde6a-d03b-4fd1-bb43-dc78454e41e1",
"metadata": {
"tags": [],
"id": "baebde6a-d03b-4fd1-bb43-dc78454e41e1"
"id": "baebde6a-d03b-4fd1-bb43-dc78454e41e1",
"tags": []
},
"source": [
"### 6.2 Replicating Equation 3 with PyTorch layers\n",
@@ -3087,7 +3087,7 @@
" nn.Dropout(p=dropout) # \"Dropout, when used, is applied after every dense layer..\"\n",
" )\n",
"\n",
" # 5. Create a forward() method to pass the data throguh the layers\n",
" # 5. Create a forward() method to pass the data through the layers\n",
" def forward(self, x):\n",
" x = self.layer_norm(x)\n",
" x = self.mlp(x)\n",
@@ -3284,7 +3284,7 @@
"\n",
"*Mapping the ViT Transformer Encoder to code.*\n",
"\n",
"You might've noticed that Table 1 from the ViT paper has a Layers column. This refers to the number of Transformer Encoder blocks in the specific ViT architecure.\n",
"You might've noticed that Table 1 from the ViT paper has a Layers column. This refers to the number of Transformer Encoder blocks in the specific ViT architecture.\n",
"\n",
"In our case, for ViT-Base, we'll be stacking together 12 of these Transformer Encoder blocks to form the backbone of our architecture (we'll get to this in section 8).\n",
"\n",
@@ -3331,8 +3331,8 @@
"cell_type": "markdown",
"id": "8219d44e-0e17-4404-ac0e-45886bfda71e",
"metadata": {
"tags": [],
"id": "8219d44e-0e17-4404-ac0e-45886bfda71e"
"id": "8219d44e-0e17-4404-ac0e-45886bfda71e",
"tags": []
},
"source": [
"### 7.2 Creating a Transformer Encoder with PyTorch's Transformer layers\n",
@@ -3435,7 +3435,7 @@
"Now we've replicated a series of equations and layers from a paper, if you need to change the layers and try something different you can.\n",
"\n",
"But there are benefits of using the PyTorch pre-built layers, such as:\n",
"* **Less prone to errors** - Generally, if a layer makes it into the PyTorch standard library, its been tested and tried to work.\n",
"* **Less prone to errors** - Generally, if a layer makes it into the PyTorch standard library, it's been tested and tried to work.\n",
"* **Potentially better performance** - As of July 2022 and PyTorch 1.12, the PyTorch implemented version of `torch.nn.TransformerEncoderLayer()` can see [a speedup of more than 2x on many common workloads](https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/).\n",
"\n",
"Finally, since the ViT architecture uses several Transformer Layers stacked on top of each for the full architecture (Table 1 shows 12 Layers in the case of ViT-Base), you can do this with [`torch.nn.TransformerEncoder(encoder_layer, num_layers)`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder) where:\n",
@@ -3533,7 +3533,7 @@
" num_classes:int=1000): # Default for ImageNet but can customize this\n",
" super().__init__() # don't forget the super().__init__()!\n",
"\n",
" # 3. Make the image size is divisble by the patch size\n",
" # 3. Make the image size is divisible by the patch size\n",
" assert img_size % patch_size == 0, f\"Image size must be divisible by patch size, image size: {img_size}, patch size: {patch_size}.\"\n",
"\n",
" # 4. Calculate number of patches (height * width/patch^2)\n",
@@ -3839,13 +3839,13 @@
"execution_count": null,
"id": "9107b068-f253-4026-ad21-83be41404043",
"metadata": {
"id": "9107b068-f253-4026-ad21-83be41404043",
"outputId": "a73ca64b-fc9f-47e6-8675-d59faf679aae",
"colab": {
"referenced_widgets": [
"97484323a38248e98ded3df3e074655c"
]
}
},
"id": "9107b068-f253-4026-ad21-83be41404043",
"outputId": "a73ca64b-fc9f-47e6-8675-d59faf679aae"
},
"outputs": [
{
@@ -4015,7 +4015,7 @@
"\n",
"These results are likely because of the difference in data resources and training regime of our ViT model versus the ViT paper.\n",
"\n",
"It seems our model is [severly underfitting](learnpytorch.io/04_pytorch_custom_datasets/#82-how-to-deal-with-underfitting) (not achieving the results we'd like it to).\n",
"It seems our model is [severely underfitting](learnpytorch.io/04_pytorch_custom_datasets/#82-how-to-deal-with-underfitting) (not achieving the results we'd like it to).\n",
"\n",
"How about we see if we can fix that by bringing in a pretrained ViT model?"
]
@@ -4103,7 +4103,7 @@
"id": "45a65cda-db08-441c-9f60-cf79138e029d"
},
"source": [
"Then we'll setup device-agonistc code."
"Then we'll setup device-agnostic code."
]
},
{
@@ -4240,7 +4240,7 @@
"\n",
"But in the name of practice, let's download some image data (pizza, steak and sushi images for Food Vision Mini), setup train and test directories and then transform the images into tensors and DataLoaders.\n",
"\n",
"We can download pizza, steak and sushi images from the course GitHub and the `download_data()` function we creating in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data).\n",
"We can download pizza, steak and sushi images from the course GitHub and the `download_data()` function we created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data).\n",
" "
]
},
@@ -4327,7 +4327,7 @@
"source": [
"Finally, we'll transform our images into tensors and turn the tensors into DataLoaders.\n",
"\n",
"Since we're using a pretrained model form `torchvision.models` we can call the `transforms()` method on it to get its required transforms.\n",
"Since we're using a pretrained model from `torchvision.models` we can call the `transforms()` method on it to get its required transforms.\n",
"\n",
"Remember, if you're going to use a pretrained model, it's generally important to **ensure your own custom data is transformed/formatted in the same way the data the original model was trained on**.\n",
"\n",
@@ -4372,7 +4372,7 @@
"source": [
"And now we've got transforms ready, we can turn our images into DataLoaders using the `data_setup.create_dataloaders()` method we created in [05. PyTorch Going Modular section 2](https://www.learnpytorch.io/05_pytorch_going_modular/#2-create-datasets-and-dataloaders-data_setuppy).\n",
"\n",
"Since we're using a feature extractor model (less trainable parameters), we could increase the batch size to a higher value (if we set it to 1024, we'd be mimicing an improvement found in [*Better plain ViT baselines for ImageNet-1k*](https://arxiv.org/abs/2205.01580), a paper which improves upon the original ViT paper and suggested extra reading). But since we only have ~200 training samples total, we'll stick with 32."
"Since we're using a feature extractor model (less trainable parameters), we could increase the batch size to a higher value (if we set it to 1024, we'd be mimicking an improvement found in [*Better plain ViT baselines for ImageNet-1k*](https://arxiv.org/abs/2205.01580), a paper which improves upon the original ViT paper and suggested extra reading). But since we only have ~200 training samples total, we'll stick with 32."
]
},
{
@@ -4412,13 +4412,13 @@
"execution_count": null,
"id": "a49408b4-24d9-4bb1-90a2-dd61c08f78a4",
"metadata": {
"id": "a49408b4-24d9-4bb1-90a2-dd61c08f78a4",
"outputId": "cccd177f-7815-487e-a165-2d9e95b91184",
"colab": {
"referenced_widgets": [
"e47702187773418aafc32e0078ff1895"
]
}
},
"id": "a49408b4-24d9-4bb1-90a2-dd61c08f78a4",
"outputId": "cccd177f-7815-487e-a165-2d9e95b91184"
},
"outputs": [
{
@@ -4559,7 +4559,7 @@
"\n",
"It looks like our ViT feature extractor model is performing quite well for our Food Vision Mini problem.\n",
"\n",
"Perhaps we might want to try deploying it and see how it goes in production (in this case, deploying means putting our trained model in an application someone could use, say taking photos on their smartphone of food and seeing if our model thinks its pizza, steak or sushi).\n",
"Perhaps we might want to try deploying it and see how it goes in production (in this case, deploying means putting our trained model in an application someone could use, say taking photos on their smartphone of food and seeing if our model thinks it's pizza, steak or sushi).\n",
"\n",
"To do so we can first save our model with the `utils.save_model()` function we created in [05. PyTorch Going Modular section 5](https://www.learnpytorch.io/05_pytorch_going_modular/#5-creating-a-function-to-save-the-model-utilspy)."
]
@@ -4649,7 +4649,7 @@
"\n",
"> **Note:** ^ the EffNetB2 model in reference was trained with 20% of pizza, steak and sushi data (double the amount of images) rather than the ViT feature extractor which was trained with 10% of pizza, steak and sushi data. An exercise would be to train the ViT feature extractor model on the same amount of data and see how much the results improve.\n",
"\n",
"The EffNetB2 model is ~11x smaller than the ViT model with similiar results for test loss and accuracy.\n",
"The EffNetB2 model is ~11x smaller than the ViT model with similar results for test loss and accuracy.\n",
"\n",
"However, the ViT model's results may improve more when trained with the same data (20% pizza, steak and sushi data).\n",
"\n",
@@ -4671,7 +4671,7 @@
"\n",
"Let's download the pizza dad image (a photo of my dad eating pizza) and use our ViT feature extractor to predict on it.\n",
"\n",
"To do we, let's can use the `pred_and_plot()` function we created in [06. PyTorch Transfer Learning section 6](https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set), for convenience, I saved this function to [`going_modular.going_modular.predictions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/predictions.py) on the course GitHub."
"To do so, let's use the `pred_and_plot()` function we created in [06. PyTorch Transfer Learning section 6](https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set), for convenience, I saved this function to [`going_modular.going_modular.predictions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/predictions.py) on the course GitHub."
]
},
{
@@ -4822,6 +4822,9 @@
}
],
"metadata": {
"colab": {
"provenance": []
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
@@ -4843,9 +4846,6 @@
"interpreter": {
"hash": "110a4ad9b3b23ac6a757cfb6c77f1e39e8d0496598f07ec14a944919c025e818"
}
},
"colab": {
"provenance": []
}
},
"nbformat": 4,