From 0197a027cb27bc000cd3a99f584f604984425ffe Mon Sep 17 00:00:00 2001 From: Daniel Bourke Date: Tue, 12 Jul 2022 16:13:36 +1000 Subject: [PATCH] add annotations to 08 --- 08_pytorch_paper_replicating.ipynb | 205 ++++++++++++++++++++++------- README.md | 1 + 2 files changed, 156 insertions(+), 50 deletions(-) diff --git a/08_pytorch_paper_replicating.ipynb b/08_pytorch_paper_replicating.ipynb index 3826839..29682b7 100644 --- a/08_pytorch_paper_replicating.ipynb +++ b/08_pytorch_paper_replicating.ipynb @@ -164,7 +164,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 137, "id": "ebe46d77-6c4d-4102-9994-2cb89f633f18", "metadata": {}, "outputs": [ @@ -214,7 +214,7 @@ }, { "cell_type": "code", - "execution_count": 2, + "execution_count": 138, "id": "960eb156-c1b1-4e76-a812-01bf045835bd", "metadata": {}, "outputs": [], @@ -260,7 +260,7 @@ }, { "cell_type": "code", - "execution_count": 3, + "execution_count": 139, "id": "5e246f92-e509-474e-b6c7-c82cf11cb8ca", "metadata": {}, "outputs": [ @@ -270,7 +270,7 @@ "'cuda'" ] }, - "execution_count": 3, + "execution_count": 139, "metadata": {}, "output_type": "execute_result" } @@ -296,7 +296,7 @@ }, { "cell_type": "code", - "execution_count": 4, + "execution_count": 140, "id": "37b5ffc0-7093-481e-8081-dbdfac4c24f0", "metadata": {}, "outputs": [ @@ -313,7 +313,7 @@ "PosixPath('data/pizza_steak_sushi')" ] }, - "execution_count": 4, + "execution_count": 140, "metadata": {}, "output_type": "execute_result" } @@ -335,7 +335,7 @@ }, { "cell_type": "code", - "execution_count": 5, + "execution_count": 141, "id": "92a426b6-df22-4a58-9d5e-b382c73c6048", "metadata": {}, "outputs": [], @@ -698,6 +698,16 @@ "\n", "There's a lot happening in the image above but following the coloured lines and arrows reveals the main concepts of the ViT architecture.\n", "\n", + "How about we break down each equation further (it will be our goal to recreate these with code)?\n", + "\n", + "In all equations (except equation 4), \"$\\mathbf{z}$\" is the raw output of a particular layer:\n", + "\n", + "1. $\\mathbf{z}_{0}$ is \"z zero\" (this is the output of the initial patch embedding layer)\n", + "2. $\\mathbf{z}_{\\ell}^{\\prime}$ is \"z of a particular layer *prime*\" (or an intermediary value of z)\n", + "3. $\\mathbf{z}_{\\ell}$ is \"z of a particular layer\"\n", + "\n", + "And $\\mathbf{y}$ is the overall output of the architecture.\n", + "\n", "**Equation 1**\n", "\n", "$$\n", @@ -706,7 +716,7 @@ "\\end{aligned}\n", "$$\n", "\n", - "This equation deals with the patch embedding and position embedding of the input image.\n", + "This equation deals with the class token, patch embedding and position embedding ($\\mathbf{E}$ is for embedding) of the input image.\n", "\n", "In vector form, the embedding might look something like:\n", "\n", @@ -853,9 +863,15 @@ "tags": [] }, "source": [ - "## TK 4. Equation 1: Split data into patches and creating the patch embedding \n", + "## TK 4. Equation 1: Split data into patches and creating the class, position and patch embedding \n", "\n", - "Let's start by creating the patch embedding.\n", + "I remember one of my machine learning engineer friends used to say \"it's all about the embedding.\"\n", + "\n", + "As in, if you can represent your data in a good, learnable way (as embeddings are learnable representations), chances are a learning algorithm will be able to perform well on them.\n", + "\n", + "So with that being said, let's start by creating the class, position and patch embeddings for the ViT architecture.\n", + "\n", + "We'll start with the **patch embedding**.\n", "\n", "This means we'll be turning our input images in a sequence of patches and then embedding those patches.\n", "\n", @@ -1769,7 +1785,7 @@ }, { "cell_type": "code", - "execution_count": 134, + "execution_count": null, "id": "3ef75c7e", "metadata": {}, "outputs": [], @@ -1821,68 +1837,157 @@ "source": [ "`PatchEmbedding` layer created!\n", "\n", - "Let's try it out on a single image.\n", - "\n", - "UPTOHERE: single forward pass on an image, \n", - "* print the input and output shapes of the image and the layer\n", - "* get a summary of the layer\n", - "* show the layer erroring with the wrong shapes" + "Let's try it out on a single image." ] }, { "cell_type": "code", - "execution_count": 135, + "execution_count": 146, "id": "a5599575-44cc-46c9-95a4-e65eb1379a59", "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input image shape: torch.Size([1, 3, 224, 224])\n", + "Output patch embedding shape: torch.Size([1, 196, 768])\n" + ] + } + ], + "source": [ + "# Create an instance of patch embedding layer\n", + "patchify = PatchEmbedding(in_channels=3,\n", + " patch_size=16,\n", + " embedding_dim=768)\n", + "\n", + "# Pass a single image through\n", + "print(f\"Input image shape: {image.unsqueeze(0).shape}\")\n", + "patch_embedded_image = patchify(image.unsqueeze(0)) # add an extra batch dimension on the 0th index, otherwise will error\n", + "print(f\"Output patch embedding shape: {patch_embedded_image.shape}\")" + ] + }, + { + "cell_type": "markdown", + "id": "a4d59a81-0cef-4251-832b-5f69da199996", + "metadata": {}, + "source": [ + "Beautiful!\n", + "\n", + "The output shape matches the ideal input and output shapes we'd like to see from the patch embedding layer:\n", + "\n", + "* **Input:** The image starts as 2D with size ${H \\times W \\times C}$.\n", + "* **Output:** The image gets converted to a sequence of flattened 2D patches with size ${N \\times\\left(P^{2} \\cdot C\\right)}$.\n", + "\n", + "Where:\n", + "* $(H, W)$ is the resolution of the original image.\n", + "* $C$ is the number of channels.\n", + "* $(P, P)$ is the resolution of each image patch (**patch size**).\n", + "* $N=H W / P^{2}$ is the resulting number of patches, which also serves as the effective input sequence length for the Transformer.\n", + " \n", + "We've now replicated the patch embedding for equation 1 but not the class token/position embedding.\n", + "\n", + "We'll get to these later on.\n", + "\n", + "\"replicating\n", + "\n", + "*Our `PatchEmbedding` class (right) replicates the patch embedding of the ViT architecture from Figure 1 and Equation 1 from the ViT paper (left). However, the learnable class embedding and position embeddings haven't been created yet. These will come soon.*\n", + "\n", + "Let's now get a summary of our `PatchEmbedding` layer." + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "id": "e440be53-d72c-42b8-87c8-1c31c4262c16", + "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "torch.Size([1, 196, 768])" + "========================================================================================================================\n", + "Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n", + "========================================================================================================================\n", + "PatchEmbedding (PatchEmbedding) [1, 3, 224, 224] [1, 196, 768] -- True\n", + "├─Conv2d (patcher) [1, 3, 224, 224] [1, 768, 14, 14] 590,592 True\n", + "├─Flatten (flatten) [1, 768, 14, 14] [1, 768, 196] -- --\n", + "========================================================================================================================\n", + "Total params: 590,592\n", + "Trainable params: 590,592\n", + "Non-trainable params: 0\n", + "Total mult-adds (M): 115.76\n", + "========================================================================================================================\n", + "Input size (MB): 0.60\n", + "Forward/backward pass size (MB): 1.20\n", + "Params size (MB): 2.36\n", + "Estimated Total Size (MB): 4.17\n", + "========================================================================================================================" ] }, - "execution_count": 135, + "execution_count": 147, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "patchify = PatchEmbedding()\n", - "patched_image = patchify(image.unsqueeze(0)) # add an extra batch dimension on the 0th index, otherwise will error\n", - "patched_image.shape" + "# Create random input sizes\n", + "random_input_image = (1, 3, 224, 224)\n", + "random_input_image_error = (1, 3, 250, 250) # will error because image size is incompatible with patch_size\n", + "\n", + "# Get a summary of the input and outputs of PatchEmbedding\n", + "summary(PatchEmbedding(), \n", + " input_size=random_input_image, # try swapping this for \"random_input_image_error\" \n", + " col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n", + " col_width=20,\n", + " row_settings=[\"var_names\"])" + ] + }, + { + "cell_type": "markdown", + "id": "8576f2f1-a2ad-4874-8f76-08156371f444", + "metadata": {}, + "source": [ + "### TK 4.6 Creating the class token embedding\n", + "\n", + "UPTOHERE: creating the class embedding, then create the position embedding and add them together... and finish the embedding section!!!\n", + "\n", + "TK image - class embedding image\n", + "\n", + "> Similar to BERT's `[ class ]` token, we prepend a learnable embedding to the sequence of embedded patches $\\left(\\mathbf{z}_{0}^{0}=\\mathbf{x}_{\\text {class }}\\right)$, whose state at the output of the Transformer encoder $\\left(\\mathbf{z}_{L}^{0}\\right)$ serves as the image representation $\\mathbf{y}$ (Eq. 4). " ] }, { "cell_type": "code", - "execution_count": 136, - "id": "e440be53-d72c-42b8-87c8-1c31c4262c16", + "execution_count": null, + "id": "50381789-d73d-4648-9144-4d48da87318f", "metadata": {}, - "outputs": [ - { - "ename": "RuntimeError", - "evalue": "Failed to run torchinfo. See above stack traces for more details. Executed layers up to: []", - "output_type": "error", - "traceback": [ - "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[0;31mAssertionError\u001b[0m Traceback (most recent call last)", - "File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torchinfo/torchinfo.py:290\u001b[0m, in \u001b[0;36mforward_pass\u001b[0;34m(model, x, batch_dim, cache_forward_pass, device, mode, **kwargs)\u001b[0m\n\u001b[1;32m 289\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(x, (\u001b[38;5;28mlist\u001b[39m, \u001b[38;5;28mtuple\u001b[39m)):\n\u001b[0;32m--> 290\u001b[0m _ \u001b[38;5;241m=\u001b[39m \u001b[43mmodel\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mto\u001b[49m\u001b[43m(\u001b[49m\u001b[43mdevice\u001b[49m\u001b[43m)\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mx\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 291\u001b[0m \u001b[38;5;28;01melif\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(x, \u001b[38;5;28mdict\u001b[39m):\n", - "File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torch/nn/modules/module.py:1148\u001b[0m, in \u001b[0;36mModule._call_impl\u001b[0;34m(self, *input, **kwargs)\u001b[0m\n\u001b[1;32m 1146\u001b[0m \u001b[38;5;28minput\u001b[39m \u001b[38;5;241m=\u001b[39m bw_hook\u001b[38;5;241m.\u001b[39msetup_input_hook(\u001b[38;5;28minput\u001b[39m)\n\u001b[0;32m-> 1148\u001b[0m result \u001b[38;5;241m=\u001b[39m \u001b[43mforward_call\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 1149\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m _global_forward_hooks \u001b[38;5;129;01mor\u001b[39;00m \u001b[38;5;28mself\u001b[39m\u001b[38;5;241m.\u001b[39m_forward_hooks:\n", - "Input \u001b[0;32mIn [134]\u001b[0m, in \u001b[0;36mPatchEmbedding.forward\u001b[0;34m(self, x)\u001b[0m\n\u001b[1;32m 31\u001b[0m image_resolution \u001b[38;5;241m=\u001b[39m x\u001b[38;5;241m.\u001b[39mshape[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m]\n\u001b[0;32m---> 32\u001b[0m \u001b[38;5;28;01massert\u001b[39;00m image_resolution \u001b[38;5;241m%\u001b[39m patch_size \u001b[38;5;241m==\u001b[39m \u001b[38;5;241m0\u001b[39m, \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mInput image size must be divisble by patch size, image shape: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mimage_resolution\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m, patch size: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mpatch_size\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 34\u001b[0m \u001b[38;5;66;03m# Check the shapes if necessary\u001b[39;00m\n\u001b[1;32m 35\u001b[0m \u001b[38;5;66;03m# print(x.shape)\u001b[39;00m\n", - "\u001b[0;31mAssertionError\u001b[0m: Input image size must be divisble by patch size, image shape: 250, patch size: 16", - "\nThe above exception was the direct cause of the following exception:\n", - "\u001b[0;31mRuntimeError\u001b[0m Traceback (most recent call last)", - "Input \u001b[0;32mIn [136]\u001b[0m, in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43msummary\u001b[49m\u001b[43m(\u001b[49m\u001b[43mpatchify\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43minput_size\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m(\u001b[49m\u001b[38;5;241;43m1\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m3\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m250\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m250\u001b[39;49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 2\u001b[0m \u001b[43m \u001b[49m\u001b[43mcol_names\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43minput_size\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43moutput_size\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mnum_params\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mtrainable\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[1;32m 3\u001b[0m \u001b[43m \u001b[49m\u001b[43mcol_width\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[38;5;241;43m20\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[1;32m 4\u001b[0m \u001b[43m \u001b[49m\u001b[43mrow_settings\u001b[49m\u001b[38;5;241;43m=\u001b[39;49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mvar_names\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m)\u001b[49m\n", - "File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torchinfo/torchinfo.py:218\u001b[0m, in \u001b[0;36msummary\u001b[0;34m(model, input_size, input_data, batch_dim, cache_forward_pass, col_names, col_width, depth, device, dtypes, mode, row_settings, verbose, **kwargs)\u001b[0m\n\u001b[1;32m 211\u001b[0m validate_user_params(\n\u001b[1;32m 212\u001b[0m input_data, input_size, columns, col_width, device, dtypes, verbose\n\u001b[1;32m 213\u001b[0m )\n\u001b[1;32m 215\u001b[0m x, correct_input_size \u001b[38;5;241m=\u001b[39m process_input(\n\u001b[1;32m 216\u001b[0m input_data, input_size, batch_dim, device, dtypes\n\u001b[1;32m 217\u001b[0m )\n\u001b[0;32m--> 218\u001b[0m summary_list \u001b[38;5;241m=\u001b[39m \u001b[43mforward_pass\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m 219\u001b[0m \u001b[43m \u001b[49m\u001b[43mmodel\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mx\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mbatch_dim\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcache_forward_pass\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mdevice\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mmodel_mode\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[38;5;241;43m*\u001b[39;49m\u001b[43mkwargs\u001b[49m\n\u001b[1;32m 220\u001b[0m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m 221\u001b[0m formatting \u001b[38;5;241m=\u001b[39m FormattingOptions(depth, verbose, columns, col_width, rows)\n\u001b[1;32m 222\u001b[0m results \u001b[38;5;241m=\u001b[39m ModelStatistics(\n\u001b[1;32m 223\u001b[0m summary_list, correct_input_size, get_total_memory_used(x), formatting\n\u001b[1;32m 224\u001b[0m )\n", - "File \u001b[0;32m~/code/pytorch/env/lib/python3.8/site-packages/torchinfo/torchinfo.py:299\u001b[0m, in \u001b[0;36mforward_pass\u001b[0;34m(model, x, batch_dim, cache_forward_pass, device, mode, **kwargs)\u001b[0m\n\u001b[1;32m 297\u001b[0m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m e:\n\u001b[1;32m 298\u001b[0m executed_layers \u001b[38;5;241m=\u001b[39m [layer \u001b[38;5;28;01mfor\u001b[39;00m layer \u001b[38;5;129;01min\u001b[39;00m summary_list \u001b[38;5;28;01mif\u001b[39;00m layer\u001b[38;5;241m.\u001b[39mexecuted]\n\u001b[0;32m--> 299\u001b[0m \u001b[38;5;28;01mraise\u001b[39;00m \u001b[38;5;167;01mRuntimeError\u001b[39;00m(\n\u001b[1;32m 300\u001b[0m \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mFailed to run torchinfo. See above stack traces for more details. \u001b[39m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 301\u001b[0m \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mExecuted layers up to: \u001b[39m\u001b[38;5;132;01m{\u001b[39;00mexecuted_layers\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m\n\u001b[1;32m 302\u001b[0m ) \u001b[38;5;28;01mfrom\u001b[39;00m \u001b[38;5;21;01me\u001b[39;00m\n\u001b[1;32m 303\u001b[0m \u001b[38;5;28;01mfinally\u001b[39;00m:\n\u001b[1;32m 304\u001b[0m \u001b[38;5;28;01mif\u001b[39;00m hooks:\n", - "\u001b[0;31mRuntimeError\u001b[0m: Failed to run torchinfo. See above stack traces for more details. Executed layers up to: []" - ] - } - ], + "outputs": [], "source": [ - "summary(patchify, input_size=(1, 3, 250, 250),\n", - " col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n", - " col_width=20,\n", - " row_settings=[\"var_names\"])" + "# TODO add code for class embedding" + ] + }, + { + "cell_type": "markdown", + "id": "48502c61-16b0-4659-b95f-0e830ae93077", + "metadata": {}, + "source": [ + "### TK 4.7 Creating the position embedding \n", + "\n", + "Well, we've got the class token embedding and the patch embedding, now how might we create the position embedding?\n", + "\n", + "Let's read section 3.1 of the ViT paper:\n", + "\n", + "> Position embeddings are added to the patch embeddings to retain positional information. We use standard learnable 1D position embeddings, since we have not observed significant performance gains from using more advanced 2D-aware position embeddings (Appendix D.4). The resulting sequence of embedding vectors serves as input to the encoder.\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "33e5e5bf-e744-4249-ac9b-08986be5ef81", + "metadata": {}, + "outputs": [], + "source": [ + "# TODO: add code for position embedding." ] }, { diff --git a/README.md b/README.md index db80a66..691b218 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. +* 12 July 2022 - add annotations for 08, woo woo this is bigggg section! * 11 July 2022 - add annotations for 08 * 9 July 2022 - add annotations for 08 * 8 July 2022 - add a bunch of annotations to 08