diff --git a/08_pytorch_paper_replicating.ipynb b/08_pytorch_paper_replicating.ipynb index ebd9e3f..338c762 100644 --- a/08_pytorch_paper_replicating.ipynb +++ b/08_pytorch_paper_replicating.ipynb @@ -25,7 +25,7 @@ "* TK what is ViT?\n", "* TK - The name Transformer comes from the architecture name in the paper where it was originally introduced, [*Attention is all you need*](https://arxiv.org/abs/1706.03762). An architecture is usually considered a Transformer variant if it uses attention layers in a specific pattern. Since the Transformer architecture originally focused on text data, the goal of the ViT paper was to bring it to the vision.\n", "* TK - The original transformer was made to work on sequences of text (1D), Vision Transformer turns images into sequences of \"patches\".\n", - "* TK - original ViT also called \"vanilla vision transformer\"\n", + "* TK - original ViT also called \"vanilla vision transformer\", understand Vanilla vision transformer, you can start to understand the many variants of the vision transformer \n", "* TK - Transformer can be generally defined any architecture that uses a form of the attention mechanism as part of its architecture. " ] }, @@ -3182,30 +3182,43 @@ "\n", "Finally, to bring ViT to life we'll:\n", "\n", - "1. ...\n", - "\n", - "UPTOHERE: \n", - "\n", - "* Add steps for ViT\n", - "\n", - "1. Create a class called `TransformerEncoderBlock()` that inherits from `torch.nn.Module`.\n", + "1. Create a class called `ViT()` that inherits from `torch.nn.Module`.\n", "2. Initialize the class with hyperparameters from Table 1 and Table 3 of the ViT paper for the ViT-Base model.\n", - "3. Instantiate a MSA block for equation 2 using our `MultiheadSelfAttentionBlock()` with the appropriate parameters.\n", - "4. Instantiate a MLP block for equation 3 using our `MLPBlock()` with the appropriate parameters.\n", - "5. Create a `forward()` method for our `TransformerEncoderBlock()` class.\n", - "6. Create a residual connection for the MSA block (for equation 2).\n", - "7. Create a residual connection for the MLP block (for equation 3)." + "3. Make sure the image size is divisible by the patch size (the image should be split into even patches).\n", + "4. Calculate the number of patches using the formula $N=H W / P^{2}$, where $H$ is the image height, $W$ is the image width and $P$ is the patch size.\n", + "5. Create a learnable class embedding token (equation 1) as done above in section 4.6.\n", + "6. Create a learnable position embedding vector (equation 1) as done above in section 4.7.\n", + "7. Setup the embedding dropout layer as discussed in Appendix B.1 of the ViT paper.\n", + "8. Create the patch embedding layer using the `PatchEmbedding()` class as done above in section 4.5.\n", + "9. Create a series of Transformer Encoder blocks by passing a list of `TransformerEncoderBlock()`s created above in section 7.1 to `torch.nn.Sequential()` (equations 2 & 3).\n", + "10. Create the MLP head (also called classifier head or equation 4) by passing a `torch.nn.LayerNorm()` (LN) layer and a `torch.nn.Linear(out_features=num_classes)` layer (where `num_classes` is the target number of classes) linear layer to `torch.nn.Sequential()`.\n", + "11. Create a `forward()` method that accepts an input.\n", + "12. Get the batch size of the input (the first dimension of the shape).\n", + "13. Create the patching embedding using the layer created in step 8 (equation 1).\n", + "14. Create the class token embedding using the layer created in step 5 and expand it across the number of batches found in step 11 using [`torch.Tensor.expand()`](https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html) (equation 1).\n", + "15. Concatenate the class token embedding created in step 13 to the first dimension of the patch embedding created in step 12 using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) (equation 1).\n", + "16. Add the position embedding created in step 6 to the patch and class token embedding created in step 14 (equation 1). \n", + "17. Pass the patch and position embedding through the dropout layer created in step 7.\n", + "18. Pass the patch and position embedding from step 16 through the stack of Transformer Encoder layers created in step 9 (equations 2 & 3).\n", + "19. Pass index 0 of the output of the stack of Transformer Encoder layers from step 17 through the classifier head created in step 10 (equation 4).\n", + "20. Dance and shout woohoo!!! We just built a Vision Transformer!\n", + "\n", + "You ready?\n", + "\n", + "Let's go." ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 64, "id": "2df890d5", "metadata": {}, "outputs": [], "source": [ + "# 1. Create a ViT class that inherits from nn.Module\n", "class ViT(nn.Module):\n", " \"\"\"Creates a Vision Transformer architecture with ViT-Base hyperparameters by default.\"\"\"\n", + " # 2. Initialize the class with hyperparameters from Table 1 and Table 3\n", " def __init__(self,\n", " img_size:int=224, # Training resolution from Table 3 in ViT paper\n", " in_channels:int=3, # Number of channels in input image\n", @@ -3219,101 +3232,130 @@ " embedding_dropout:int=0.1, # Dropout for patch and position embeddings\n", " num_classes:int=1000): # Default for ImageNet but can customize this\n", " super().__init__() # don't forget the super().__init__()!\n", - " \n", + " \n", + " # 3. Make the image size is divisble 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", - " # Get image size\n", - " self.img_height, self.img_width = img_size, img_size\n", - " \n", - " # Calculate number of patches (height * width/patch^2)\n", - " self.num_patches = (self.img_height * self.img_width) // patch_size**2\n", " \n", + " # 4. Calculate number of patches (height * width/patch^2)\n", + " self.num_patches = (img_size * img_size) // patch_size**2\n", " \n", - " # Create learnable class embedding (needs to go at front of sequence of patch embeddings)\n", + " # 5. Create learnable class embedding (needs to go at front of sequence of patch embeddings)\n", " self.class_embedding = nn.Parameter(data=torch.randn(1, 1, embedding_dim),\n", " requires_grad=True)\n", " \n", - " # Create learnable position embedding\n", + " # 6. Create learnable position embedding\n", " self.position_embedding = nn.Parameter(data=torch.randn(1, self.num_patches+1, embedding_dim),\n", " requires_grad=True)\n", " \n", - " # Create embedding dropout value\n", + " # 7. Create embedding dropout value\n", " self.embedding_dropout = nn.Dropout(p=embedding_dropout)\n", " \n", - " # Create patch embedding layer\n", + " # 8. Create patch embedding layer\n", " self.patch_embedding = PatchEmbedding(in_channels=in_channels,\n", " patch_size=patch_size,\n", " embedding_dim=embedding_dim)\n", " \n", - " # Create Transformer Encoder blocks (we can stack Transformer Encoder blocks using nn.Sequential())\n", + " # 9. Create Transformer Encoder blocks (we can stack Transformer Encoder blocks using nn.Sequential()) \n", + " # Note: The \"*\" means \"all\"\n", " self.transformer_enedoder = nn.Sequential(*[TransformerEncoderBlock(embedding_dim=embedding_dim,\n", " num_heads=num_heads,\n", " mlp_size=mlp_size,\n", " mlp_dropout=mlp_dropout) for _ in range(num_transformer_layers)])\n", " \n", - " # Create classifier head (equation 4)\n", + " # 10. Create classifier head\n", " self.classifier = nn.Sequential(\n", " nn.LayerNorm(normalized_shape=embedding_dim),\n", " nn.Linear(in_features=embedding_dim, \n", " out_features=num_classes)\n", " )\n", " \n", + " # 11. Create a forward() method\n", " def forward(self, x):\n", " \n", - " # Get batch size\n", + " # 12. Get batch size\n", " batch_size = x.shape[0]\n", " \n", - " # Create class token embedding and expand it to match the batch size (equation 1)\n", - " class_token = self.class_embedding.expand(batch_size, -1, -1)\n", + " # 13. Create class token embedding and expand it to match the batch size (equation 1)\n", + " class_token = self.class_embedding.expand(batch_size, -1, -1) # \"-1\" means to infer the dimension (try this line on its own)\n", "\n", - " # Create patch embedding (equation 1)\n", + " # 14. Create patch embedding (equation 1)\n", " x = self.patch_embedding(x)\n", "\n", - " # Concat class embedding and patch embedding (equation 1)\n", + " # 15. Concat class embedding and patch embedding (equation 1)\n", " x = torch.cat((class_token, x), dim=1)\n", "\n", - " # Add position embedding to patch embedding (equation 1) \n", + " # 16. Add position embedding to patch embedding (equation 1) \n", " x = self.position_embedding + x\n", "\n", - " # Run embedding dropout (Appendix B.1)\n", + " # 17. Run embedding dropout (Appendix B.1)\n", " x = self.embedding_dropout(x)\n", "\n", - " # Pass patch, position and class embedding through transformer encoder layers (equations 2 & 3)\n", + " # 18. Pass patch, position and class embedding through transformer encoder layers (equations 2 & 3)\n", " x = self.transformer_enedoder(x)\n", "\n", - " # Put 0 index logit through classifier (equation 4)\n", + " # 19. Put 0 index logit through classifier (equation 4)\n", " x = self.classifier(x[:, 0]) # run on each sample in a batch at 0 index\n", "\n", - " return x\n", - " " + " return x " + ] + }, + { + "cell_type": "markdown", + "id": "b26bd2d5-a7cd-4d14-a2fc-ff8edd8b29b7", + "metadata": {}, + "source": [ + "20. 🕺💃🥳 Woohoo!!! We just built a vision transformer!\n", + "\n", + "Woah!\n", + "\n", + "What an effort!\n", + "\n", + "Slowly but surely we created layers and blocks, inputs and outputs and put them all together to build our own ViT!\n", + "\n", + "Let's create a quick demo to showcase what's happening with the class token embedding being expanded over the batch dimensions." ] }, { "cell_type": "code", - "execution_count": 43, + "execution_count": 71, "id": "7dc9f8ec", "metadata": {}, "outputs": [ { - "data": { - "text/plain": [ - "torch.Size([32, 1, 768])" - ] - }, - "execution_count": 43, - "metadata": {}, - "output_type": "execute_result" + "name": "stdout", + "output_type": "stream", + "text": [ + "Shape of class token embedding single: torch.Size([1, 1, 768])\n", + "Shape of class token embedding expanded: torch.Size([32, 1, 768])\n" + ] } ], "source": [ + "# Example of creating the class embedding and expanding over a batch dimension\n", "batch_size = 32\n", - "class_tokens = nn.Parameter(data=torch.randn(1, 1, 768))\n", - "class_tokens.expand(batch_size, -1, -1).shape # \"-1\" means to \"infer the dimension\"" + "class_token_embedding_single = nn.Parameter(data=torch.randn(1, 1, 768)) # create a single learnable class token\n", + "class_token_embedding_expanded = class_token_embedding_single.expand(batch_size, -1, -1) # expand the single learnable class token across the batch dimension, \"-1\" means to \"infer the dimension\"\n", + "\n", + "# Print out the change in shapes\n", + "print(f\"Shape of class token embedding single: {class_token_embedding_single.shape}\") \n", + "print(f\"Shape of class token embedding expanded: {class_token_embedding_expanded.shape}\")" + ] + }, + { + "cell_type": "markdown", + "id": "3f07ff70-e09c-4d7c-a119-b2185f46e35a", + "metadata": {}, + "source": [ + "Notice how the first dimension gets expanded to the batch size and the other dimensions stay the same (because they're inferred by the \"`-1`\" dimensions in `.expand(batch_size, -1, -1)`).\n", + "\n", + "Alright time to test out `ViT()` class.\n", + "\n", + "Let's create a random tensor in the same shape as a single image, pass to an instance of `ViT()` and see what happens." ] }, { "cell_type": "code", - "execution_count": 44, + "execution_count": 69, "id": "f86190a3-ed1f-4ab3-881c-4eecea996912", "metadata": {}, "outputs": [ @@ -3323,18 +3365,34 @@ "tensor([[-0.2377, 0.7360, 1.2137]], grad_fn=)" ] }, - "execution_count": 44, + "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "set_seeds()\n", - "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", - "rand_image = torch.randn(1, 3, 224, 224)\n", - "# vit = ViT(num_classes=len(class_names)) \n", - "vit = ViT(num_classes=3)\n", - "vit(rand_image)" + "\n", + "# Create a random tensor with same shape as a single image\n", + "random_image_tensor = torch.randn(1, 3, 224, 224) # (batch_size, color_channels, height, width)\n", + "\n", + "# Create an instance of ViT with the number of classes we're working with (pizza, steak, sushi)\n", + "vit = ViT(num_classes=len(class_names))\n", + "\n", + "# Pass the random image tensor to our ViT instance\n", + "vit(random_image_tensor)" + ] + }, + { + "cell_type": "markdown", + "id": "e210b803-f6a4-47e9-af63-dfa92f0eadbe", + "metadata": {}, + "source": [ + "Outstanding!\n", + "\n", + "It looks like our random image tensor made it all the way through our ViT architecture and it's outputting three logit values (one for each class).\n", + "\n", + "And because our `ViT()` class has plenty of parameters we could customize the `img_size`, `patch_size` or `num_classes` if we wanted to." ] }, { @@ -3342,16 +3400,18 @@ "id": "2c0a0c9c-6d98-47fd-a152-8a06be99b5fa", "metadata": {}, "source": [ - "### TK 8.1 Inspect the ViT model\n", + "### TK 8.1 Getting a visual summary of our ViT model\n", "\n", - "> **Note:** If you go too big, your hardware might not be able to handle it... (e.g. too high of a batch size...)\n", + "We handcrafted our own version of the ViT architecture and seen that a random image tensor can flow all the way through it.\n", "\n", - "TK - Number of parameters should be equivalent to: https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16 (`num_params=86,567,656`)" + "How about we use `torchinfo.summary()` to get a visual overview of the input and output shapes of all the layers in our model?\n", + "\n", + "> **Note:** The ViT paper states the use of a batch size of 4096 for training, however, this requires a far bit of CPU/GPU compute memory to handle (the larger the batch size the more memory required). So to make sure we don't get memory errors, we'll stick with a batch size of 32. You could always increase this later if you have access to hardware with more memory. " ] }, { "cell_type": "code", - "execution_count": 45, + "execution_count": 70, "id": "494bde26-ed1e-45dc-b615-78ac268ca20e", "metadata": {}, "outputs": [ @@ -3361,66 +3421,66 @@ "======================================================================================================================================================\n", "Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n", "======================================================================================================================================================\n", - "ViT (ViT) [128, 3, 224, 224] [128, 3] 152,064 True\n", - "├─Dropout (embedding_dropout) [128, 197, 768] [128, 197, 768] -- --\n", - "├─PatchEmbedding (patch_embedding) [128, 3, 224, 224] [128, 196, 768] -- True\n", - "│ └─Conv2d (patcher) [128, 3, 224, 224] [128, 768, 14, 14] 590,592 True\n", - "│ └─Flatten (flatten) [128, 768, 14, 14] [128, 768, 196] -- --\n", - "├─Dropout (embedding_dropout) [128, 197, 768] [128, 197, 768] -- --\n", - "├─Sequential (transformer_enedoder) [128, 197, 768] [128, 197, 768] -- True\n", - "│ └─TransformerEncoderBlock (0) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (1) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (2) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (3) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (4) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (5) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (6) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (7) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (8) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (9) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (10) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "│ └─TransformerEncoderBlock (11) [128, 197, 768] [128, 197, 768] -- True\n", - "│ │ └─MultiheadSelfAttentionBlock (msa_block) [128, 197, 768] [128, 197, 768] 2,363,904 True\n", - "│ │ └─MLPBlock (mlp_block) [128, 197, 768] [128, 197, 768] 4,723,968 True\n", - "├─Sequential (classifier) [128, 768] [128, 3] -- True\n", - "│ └─LayerNorm (0) [128, 768] [128, 768] 1,536 True\n", - "│ └─Linear (1) [128, 768] [128, 3] 2,307 True\n", + "ViT (ViT) [32, 3, 224, 224] [32, 3] 152,064 True\n", + "├─Dropout (embedding_dropout) [32, 197, 768] [32, 197, 768] -- --\n", + "├─PatchEmbedding (patch_embedding) [32, 3, 224, 224] [32, 196, 768] -- True\n", + "│ └─Conv2d (patcher) [32, 3, 224, 224] [32, 768, 14, 14] 590,592 True\n", + "│ └─Flatten (flatten) [32, 768, 14, 14] [32, 768, 196] -- --\n", + "├─Dropout (embedding_dropout) [32, 197, 768] [32, 197, 768] -- --\n", + "├─Sequential (transformer_enedoder) [32, 197, 768] [32, 197, 768] -- True\n", + "│ └─TransformerEncoderBlock (0) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (1) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (2) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (3) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (4) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (5) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (6) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (7) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (8) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (9) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (10) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "│ └─TransformerEncoderBlock (11) [32, 197, 768] [32, 197, 768] -- True\n", + "│ │ └─MultiheadSelfAttentionBlock (msa_block) [32, 197, 768] [32, 197, 768] 2,363,904 True\n", + "│ │ └─MLPBlock (mlp_block) [32, 197, 768] [32, 197, 768] 4,723,968 True\n", + "├─Sequential (classifier) [32, 768] [32, 3] -- True\n", + "│ └─LayerNorm (0) [32, 768] [32, 768] 1,536 True\n", + "│ └─Linear (1) [32, 768] [32, 3] 2,307 True\n", "======================================================================================================================================================\n", "Total params: 85,800,963\n", "Trainable params: 85,800,963\n", "Non-trainable params: 0\n", - "Total mult-adds (G): 22.08\n", + "Total mult-adds (G): 5.52\n", "======================================================================================================================================================\n", - "Input size (MB): 77.07\n", - "Forward/backward pass size (MB): 13168.81\n", + "Input size (MB): 19.27\n", + "Forward/backward pass size (MB): 3292.20\n", "Params size (MB): 257.55\n", - "Estimated Total Size (MB): 13503.43\n", + "Estimated Total Size (MB): 3569.02\n", "======================================================================================================================================================" ] }, - "execution_count": 45, + "execution_count": 70, "metadata": {}, "output_type": "execute_result" } @@ -3428,10 +3488,9 @@ "source": [ "from torchinfo import summary\n", "\n", - "# TK - clean up the summary so it looks nice when it prints out \n", "# Print a summary using torchinfo (uncomment for actual output)\n", "summary(model=vit, \n", - " input_size=(128, 3, 224, 224), # make sure this is \"input_size\", not \"input_shape\"\n", + " input_size=(32, 3, 224, 224), # (batch_size, color_channels, height, width)\n", " # col_names=[\"input_size\"], # uncomment for smaller output\n", " col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n", " col_width=20,\n", @@ -3444,33 +3503,15 @@ "id": "d0279251-5cc1-42a5-bebc-8391ef911343", "metadata": {}, "source": [ - "TK - turn summary into image\n", + "TK image - turn summary into image\n", "\n", - "* TK - same number of parameters as: https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16 -> 86567656" - ] - }, - { - "cell_type": "code", - "execution_count": 46, - "id": "3791f963-7d51-418b-b8bd-4c77341560e5", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(torch.Size([1, 1, 768]), torch.Size([32, 1, 768]))" - ] - }, - "execution_count": 46, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "batch_size = 32\n", - "cls_embedding = nn.Parameter(torch.randn(1, 1, 768))\n", - "# See here: https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html\n", - "cls_embedding.shape, cls_embedding.expand(batch_size, -1, -1).shape" + "Now those are some nice looking layers!\n", + "\n", + "Checkout the total number of parameters too, 85,800,963, our biggest model yet!\n", + "\n", + "The number is very close to PyTorch's pretrained ViT-Base with patch size 16 at [`torch.vision.models.vit_b_16()`](https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16) with 86,567,656 total parameters (though this number of parameters is for the 1000 classes in ImageNet).\n", + "\n", + "> **Exercise:** Try changing the `num_classes` parameter of our `ViT()` model to 1000 and then creating another summary with `torchinfo.summary()` and see if the number of parameters lines up between our code and `torchvision.models.vit_b_16()`." ] }, { @@ -3478,8 +3519,26 @@ "id": "dd92b752-22f0-4a13-95ac-e085d20013ac", "metadata": {}, "source": [ - "## TK 9. Train model\n", - "\n" + "## TK 9. Train ViT model\n", + "\n", + "Ok time for the easy part.\n", + "\n", + "Training!\n", + "\n", + "Why easy?\n", + "\n", + "Because we've got most of what we need ready to go, from our model (`vit`) to our DataLoaders (`train_dataloader`, `test_dataloader`) to the training functions we created in [05. PyTorch Going Modular section 4](https://www.learnpytorch.io/05_pytorch_going_modular/#4-creating-train_step-and-test_step-functions-and-train-to-combine-them). \n", + "\n", + "To train our model we can import the `train()` function from [`going_modular.going_modular.engine`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/train.py). \n", + "\n", + "All we need is a loss function and an optimizer.\n", + "\n", + "UPTOHERE: ...\n", + "* TK search the paper for \"loss\" function and \"optimizer\"... what comes up?\n", + "* TK Optimizer -> see ViT paper section 4.1, training and fine-tuning\n", + "* TK - note on training regime being different from the paper (see Appendix B.1 and Table 3 for more)\n", + "* TK - What we're missing: ...parts from the paper we're missing... (mostly due to scale/lack of resources/only using a single GPU on Google Colab, see Table 2/section 4.2 for the resources they used)\n", + " * TK - \"Finally, the ViT-L/16 model pre-trained on the public ImageNet-21k dataset performs well on most datasets too, while taking fewer resources to pre-train: it could be trained using a standard cloud TPUv3 with 8 cores in approximately 30 days\"... how much is a standard TPUv3 with 8 cores for 30 days on GCP 🤔?" ] }, { @@ -3523,9 +3582,10 @@ "from going_modular.going_modular import engine\n", "\n", "optimizer = torch.optim.Adam(params=vit.parameters(), \n", - " lr=1e-3,\n", - " betas=(0.9, 0.999), # default\n", - " weight_decay=0.1) # from the ViT paper section 4.1\n", + " lr=1e-3, # Base LR from Table 3 \n", + " betas=(0.9, 0.999), # default values but also mentioned in ViT paper section 4.1 (Training & Fine-tuning)\n", + " weight_decay=0.1) # from the ViT paper section 4.1 (Training & Fine-tuning)\n", + "\n", "loss_fn = torch.nn.CrossEntropyLoss()\n", "\n", "set_seeds()\n", @@ -3543,7 +3603,7 @@ "id": "32cb3ad2-6eea-4b69-9ce8-322270643919", "metadata": {}, "source": [ - "## TK 10. Evaluate model\n", + "## TK 10. Evaluate ViT model\n", "\n", "TK - plot the loss curves" ] @@ -3583,7 +3643,7 @@ }, { "cell_type": "markdown", - "id": "c9bc3d75-028d-4d48-bcfb-d0dd4f53d2ca", + "id": "8910673d-e0ba-4d88-85c5-1889bea0a341", "metadata": {}, "source": [ "## TK 11. Bring in pretrained ViT from `torchvision.models` on same dataset \n", @@ -3953,6 +4013,14 @@ "print(f\"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB\")" ] }, + { + "cell_type": "markdown", + "id": "2adf6c78-95c9-4c0c-b143-6d66d3b7aa25", + "metadata": {}, + "source": [ + "## TK - Try ViT on a custom image" + ] + }, { "cell_type": "markdown", "id": "277a08e0-bc0e-453d-bf0f-b56164ae71ab", @@ -3976,8 +4044,12 @@ "source": [ "## TK - Exercises\n", "\n", + "* Turn the ViT architecture into a Python script (e.g. `vit.py`) so you can call it and instantiate it.\n", "* Replicate the architecture with PyTorch transformer layers - https://pytorch.org/docs/stable/nn.html#transformer-layers\n", " * Use TransformerEncoderLayer + TransformerEncoder\n", + "* Train a pretrained ViT feature extractor for 50 epochs - what's the highest test accuracy/lowest loss you can achieve?\n", + "* Table 3 research: \n", + " * Look up what Learning Rate decay is, how does it help with training? How do you do it in PyTorch?\n", " " ] }, diff --git a/README.md b/README.md index 2d41e1e..e2f4031 100644 --- a/README.md +++ b/README.md @@ -119,6 +119,7 @@ Please leave a [discussion](https://github.com/mrdbourke/pytorch-deep-learning/d Almost daily updates of what's happening. +* 21 July 2022 - add annotations and images for 08 * 20 July 2022 - add annotations and images for 08, getting so close! this is an epic section * 19 July 2022 - add annotations and images for 08 * 15 July 2022 - add annotations and images for 08