Files
pytorch-deep-learning/docs/08_pytorch_paper_replicating.ipynb
T

3576 lines
1.5 MiB
Plaintext
Raw Normal View History

2022-07-04 16:38:17 +10:00
{
"cells": [
{
"cell_type": "markdown",
"id": "e7e81227-aa0c-4e15-9ac4-20cc7128c915",
"metadata": {},
"source": [
"<a href=\"https://colab.research.google.com/github/mrdbourke/pytorch-deep-learning/blob/main/08_pytorch_paper_replicating.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
]
},
{
"cell_type": "markdown",
"id": "873828f0-e50f-40b9-9879-f9a01adaa020",
2022-07-22 14:06:23 +10:00
"metadata": {
"tags": []
},
2022-07-04 16:38:17 +10:00
"source": [
"# (WIP) 08. PyTorch Paper Replicating\n",
"\n",
"TK intro\n",
"\n",
"Want to recreate ViT paper: \"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale\" - https://arxiv.org/abs/2010.11929 - TK will refer to this as \"ViT paper\" throughout.\n",
"\n",
2022-07-22 14:06:23 +10:00
"* TK what is ViT?\n",
"\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",
"\n",
"* TK - The original transformer was made to work on sequences of text (1D), Vision Transformer turns images into sequences of \"patches\".\n",
"\n",
"* TK - original ViT also called \"vanilla vision transformer\""
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "markdown",
"id": "ccb53b99-277c-4ac0-a1fb-283c47576be1",
"metadata": {},
"source": [
"## TK - What is paper replicating?\n",
"\n",
"It's no secret machine learning is advancing fast.\n",
"\n",
"Many of these advances get published in machine learning research papers.\n",
"\n",
"And the goal of **paper replicating** is to take replicate these advances with code so you can use the techniques for your own problem.\n",
"\n",
"For example, let's say a new model architecture gets released that performs better than any other architecture before on various benchmarks, wouldn't it be nice to try that architecture on your own problems?\n",
"\n",
2022-07-22 14:06:23 +10:00
"* TK image: paper replicating = research paper (language + diagrams + math) -> code (turn language, diagrams and math into usable code) / (translate a research paper into usable code)"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "markdown",
"id": "966b353c-c9d8-4568-ad64-c0df45a39442",
"metadata": {},
"source": [
"## TK - What is a machine learning research paper?\n",
"\n",
"A machine learning research paper is a scientific paper that details findings of a research group on a specific area.\n",
"\n",
"The contents of a machine learning research paper can vary from paper to paper but they generally follow the structure:\n",
"\n",
"| **Section** | **Contents** |\n",
"| ----- | ----- | \n",
"| **Abstract** | An overview/summary of the paper's main findings/contributions. |\n",
"| **Introduction** | What's the paper's main problem and what are previous methods used to try and solve it? |\n",
"| **Method** | How did the researchers go about conducting their research? For example, what model(s) were used, data sources, training setups, etc. |\n",
"| **Results** | What are the outcomes of the paper? If a new type of model or training setup was used, how did the results of findings compare to previous works (this is where **experiment tracking** comes in handy)? |\n",
"| **Conclusion** | What are the limitations of the suggested methods? What are some next steps for the research community? |\n",
"| **References** | What resources/other papers did the researchers look at to build their own body of work? |\n",
"| **Appendix** | Are there any extra resources/findings to look at that weren't included in any of the above sections? |"
]
},
{
"cell_type": "markdown",
"id": "b8ce67f6-0b00-448b-885d-b7d22bce4ff6",
"metadata": {},
"source": [
"## TK - Why replicate a machine learning research paper?\n",
"\n",
"A machine learning research paper is often a presentation of months of work and experiments done by some of the best machine learning teams in the world condensed into a few pages of text.\n",
"\n",
"And if these experiments lead to better results in an area related to the problem you're working on, it'd be nice to them out.\n",
"\n",
"Also, replicating the work of others is a fantastic way to practice your skills.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-george-hotz-quote.png\" width=600 alt=\"george hotz quote saying to get better at being a machine learning engineer, download a paper, implement it and keep going until you have skills\"/>\n",
"\n",
"*George Hotz is founder of [comma.ai](https://comma.ai/), a self-driving car company and livestreams machine learning coding on [Twitch](https://www.twitch.tv/georgehotz) and those videos get posted in full to [YouTube](https://www.youtube.com/c/georgehotzarchive). I pulled this quote from one of his livestreams. The \"٭\" is to note that machine learning engineering often involves the extra step(s) of preprocessing data and making your models available for others to use (deployment).*\n",
" \n",
"When you first start trying to replicate research papers, you'll likely be overwhelmed.\n",
"\n",
"That's normal.\n",
"\n",
"Research teams spend weeks, months and sometimes years creating these works so it makes sense if it takes you sometime to even read let alone reproduce the works.\n",
"\n",
"Replicating research is such a tough problem, phenomenal machine learning libraries and tools such as, [HuggingFace](https://huggingface.co/), [PyTorch Image Models](https://github.com/rwightman/pytorch-image-models) (`timm` library) and [fast.ai](https://www.fast.ai/) have been born out of making machine learning research more accessible. "
]
},
{
"cell_type": "markdown",
"id": "b09a7ccf-41e8-4ee4-8d78-aff5f650ca7f",
"metadata": {},
"source": [
"## TK - Where can you find code examples for machine learning research papers?\n",
"\n",
"One of the first things you'll notice when it comes to machine learning research is: there's a lot of it.\n",
"\n",
"So beware, trying to stay on top of it is like trying to outrun a hamster wheel.\n",
"\n",
"Follow your interest, pick a few things that stand out to you.\n",
"\n",
"In saying this, there are several places to find and read machine learning research papers:\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",
"* [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",
"* [AK Twitter](https://twitter.com/ak92501) - 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",
"* [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 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",
"\n",
"TK image: showcase the above"
]
},
{
"cell_type": "markdown",
"id": "7448de48-ec72-4d63-9948-869a4fc58c04",
"metadata": {},
"source": [
"## TK - What we're going to cover\n",
"\n",
"TODO\n",
"\n",
"* ViT -> FoodVision Mini\n",
"* Layers = collections of functions to manipulate data -> Architectures = collections of layers (blocks) -> All layers (and blocks) have inputs and outputs\n",
" * Replicating research papers starts by figuring out the inputs and outputs of your layers -> blocks -> model "
]
},
{
"cell_type": "markdown",
"id": "cf677bb7-719a-447e-a8e8-c4f287146b62",
"metadata": {},
"source": [
"## TK - Where can you get help?\n",
"\n",
"All of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n",
"\n",
"If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).\n",
"\n",
"And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. "
]
},
{
"cell_type": "markdown",
"id": "7a8913de-e49e-40c9-89c7-6b847fac9def",
"metadata": {},
"source": [
"## TK 0. Getting setup \n",
"\n",
"As we've done previously, let's make sure we've got all of the modules we'll need for this section.\n",
"\n",
"We'll import the Python scripts (such as `data_setup.py` and `engine.py`) we created in [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n",
"\n",
"To do so, we'll download [`going_modular`](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/going_modular) directory from the `pytorch-deep-learning` repository (if we don't already have it).\n",
"\n",
"We'll also get the [`torchinfo`](https://github.com/TylerYep/torchinfo) package if it's not available. \n",
"\n",
"`torchinfo` will help later on to give us a visual representation of our model.\n",
"\n",
"And since later on we'll be using a newer version of the `torchvision` package (as of June 2022), we'll make sure we've got the latest versions."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 2,
2022-07-04 16:38:17 +10:00
"id": "ebe46d77-6c4d-4102-9994-2cb89f633f18",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-07-22 14:06:23 +10:00
"torch version: 1.12.0+cu102\n",
"torchvision version: 0.13.0+cu102\n"
2022-07-04 16:38:17 +10:00
]
}
],
"source": [
"# For this notebook to run with updated APIs, we need torch 1.12+ and torchvision 0.13+\n",
"try:\n",
" import torch\n",
" import torchvision\n",
" assert int(torch.__version__.split(\".\")[1]) >= 12, \"torch version should be 1.12+\"\n",
" assert int(torchvision.__version__.split(\".\")[1]) >= 13, \"torchvision version should be 0.13+\"\n",
" print(f\"torch version: {torch.__version__}\")\n",
" print(f\"torchvision version: {torchvision.__version__}\")\n",
"except:\n",
" print(f\"[INFO] torch/torchvision versions not as required, installing nightly versions.\")\n",
" !pip3 install -U --pre torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/nightly/cu113\n",
" import torch\n",
" import torchvision\n",
" print(f\"torch version: {torch.__version__}\")\n",
" print(f\"torchvision version: {torchvision.__version__}\")"
]
},
{
"cell_type": "markdown",
"id": "30caf875-557e-410f-8dff-bd4a9f6c7ae4",
"metadata": {},
"source": [
"> **Note:** If you're using Google Colab, you may have to restart your runtime after running the above cell. After restarting, you can run the cell again and verify you've got the right versions of `torch` and `torchvision`.\n",
"\n",
"Now we'll continue with the regular imports, setting up device agnostic code and this time we'll also get the [`helper_functions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) script from GitHub.\n",
"\n",
"The `helper_functions.py` script contains several functions we created in previous sections:\n",
"* `set_seeds()` to set the random seeds (created in [07. PyTorch Experiment Tracking section 0](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#create-a-helper-function-to-set-seeds)).\n",
"* `download_data()` to download a data source given a link (created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data)).\n",
"* `plot_loss_curves()` to inspect our model's training results (created in [04. PyTorch Custom Datasets section 7.8](https://www.learnpytorch.io/04_pytorch_custom_datasets/#78-plot-the-loss-curves-of-model-0))\n",
"\n",
"> **Note:** It may be a better idea for many of the functions in the `helper_functions.py` script to be merged into `going_modular/going_modular/utils.py`, perhaps that's an extension you'd like to try.\n"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 3,
2022-07-04 16:38:17 +10:00
"id": "960eb156-c1b1-4e76-a812-01bf045835bd",
"metadata": {},
"outputs": [],
"source": [
"# Continue with regular imports\n",
"import matplotlib.pyplot as plt\n",
"import torch\n",
"import torchvision\n",
"\n",
"from torch import nn\n",
"from torchvision import transforms\n",
"\n",
"# Try to get torchinfo, install it if it doesn't work\n",
"try:\n",
" from torchinfo import summary\n",
"except:\n",
" print(\"[INFO] Couldn't find torchinfo... installing it.\")\n",
" !pip install -q torchinfo\n",
" from torchinfo import summary\n",
"\n",
"# Try to import the going_modular directory, download it from GitHub if it doesn't work\n",
"try:\n",
" from going_modular.going_modular import data_setup, engine\n",
" from helper_functions import download_data, set_seeds, plot_loss_curves\n",
"except:\n",
" # Get the going_modular scripts\n",
" print(\"[INFO] Couldn't find going_modular or helper_functions scripts... downloading them from GitHub.\")\n",
" !git clone https://github.com/mrdbourke/pytorch-deep-learning\n",
" !mv pytorch-deep-learning/going_modular .\n",
" !mv pytorch-deep-learning/helper_functions.py . # get the helper_functions.py script\n",
" !rm -rf pytorch-deep-learning\n",
" from going_modular.going_modular import data_setup, engine\n",
" from helper_functions import download_data, set_seeds, plot_loss_curves"
]
},
{
"cell_type": "markdown",
"id": "4f9bdd26-26ac-4756-bd8e-b7a50799f28b",
"metadata": {},
"source": [
"> **Note:** If you're using Google Colab, and you don't have a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 4,
2022-07-04 16:38:17 +10:00
"id": "5e246f92-e509-474e-b6c7-c82cf11cb8ca",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'cuda'"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 4,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"id": "5a695192-2644-4aa7-beab-7222a24b1a1a",
"metadata": {},
"source": [
"## TK 1. Get Data\n",
"\n",
"Since we're continuing on with FoodVision Mini, let's download the pizza, steak and sushi image dataset we've been using.\n",
"\n",
"To do so we can use the `download_data()` function from `helper_functions.py` that we created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data).\n",
"\n",
"We'll `source` to the raw GitHub link of the [`pizza_steak_sushi.zip` data](https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip) and the `destination` to `pizza_steak_sushi`."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 5,
2022-07-04 16:38:17 +10:00
"id": "37b5ffc0-7093-481e-8081-dbdfac4c24f0",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[INFO] data/pizza_steak_sushi directory exists, skipping download.\n"
]
},
{
"data": {
"text/plain": [
"PosixPath('data/pizza_steak_sushi')"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 5,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Download pizza, steak, sushi images from GitHub\n",
"image_path = download_data(source=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip\",\n",
" destination=\"pizza_steak_sushi\")\n",
"image_path"
]
},
{
"cell_type": "markdown",
"id": "55a047b1-9f12-4dcf-8d97-83b7cbb37392",
"metadata": {},
"source": [
"Beautiful! Data downloaded, let's setup the training and test directories."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 6,
2022-07-04 16:38:17 +10:00
"id": "92a426b6-df22-4a58-9d5e-b382c73c6048",
"metadata": {},
"outputs": [],
"source": [
"# Setup directory paths to train and test images\n",
"train_dir = image_path / \"train\"\n",
"test_dir = image_path / \"test\""
]
},
{
"cell_type": "markdown",
"id": "14e84624-6af8-4231-b606-3eabffd172db",
"metadata": {},
"source": [
"## TK 2. Create Datasets and DataLoaders\n",
"\n",
"Since we've got some data, let's now turn it into `DataLoader`'s.\n",
"\n",
"To do so we can use the `create_dataloaders()` function in [`data_setup.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/data_setup.py).\n",
"\n",
"First, we'll create a transform to prepare our images.\n",
"\n",
"This where one of the first references to the ViT paper will come in.\n",
"\n",
"In Table 3, the training resolution is mentioned as being 224 (height=224, width=224). \n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-image-size-and-batch-size.png\" width=900 alt=\"Table 3 from the Vision Transformer paper showing the image size and batch size\"/>\n",
"\n",
"*You can often find various hyperparameter settings listed in a table. In this case we're still preparing our data, so we're mainly concerned with things like image size and batch size. Source: Table 3 in [ViT paper](https://arxiv.org/abs/2010.11929).*\n",
"\n",
"So we'll make sure our transform resizes our images appropriately.\n",
"\n",
"And since we'll be training our model from scratch (no transfer learning to begin with), we won't provide a `normalize` transform like we did in [06. PyTorch Transfer Learning section 2.1](https://www.learnpytorch.io/06_pytorch_transfer_learning/#21-creating-a-transform-for-torchvisionmodels-manual-creation).\n",
"\n",
"### 2.1 Prepare transforms for images"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 7,
2022-07-04 16:38:17 +10:00
"id": "a45ea650-c3fa-479c-8767-48bc3a1f1267",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Manually created transforms: Compose(\n",
2022-07-22 14:06:23 +10:00
" Resize(size=(224, 224), interpolation=bilinear, max_size=None, antialias=None)\n",
2022-07-04 16:38:17 +10:00
" ToTensor()\n",
")\n"
]
}
],
"source": [
"# Create image size (from Table 3 in the ViT paper) \n",
2022-07-22 14:06:23 +10:00
"IMG_SIZE = 224\n",
2022-07-04 16:38:17 +10:00
"\n",
"# Create transform pipeline manually\n",
"manual_transforms = transforms.Compose([\n",
" transforms.Resize((IMG_SIZE, IMG_SIZE)),\n",
" transforms.ToTensor(),\n",
"]) \n",
"print(f\"Manually created transforms: {manual_transforms}\")"
]
},
{
"cell_type": "markdown",
"id": "437078c2-eb42-471f-8561-94845d0a878d",
"metadata": {},
"source": [
"### 2.2 Turn images into `DataLoader`'s\n",
"Transforms created!\n",
"\n",
"Let's now create our `DataLoader`'s.\n",
"\n",
"The ViT paper states the use of a batch size of 4096 which is 128x the size of the batch size we've been using (32).\n",
"\n",
"We're going to stick with a batch size of 32.\n",
"\n",
"Why?\n",
"\n",
"Because some hardware (including the free tier of Google Colab) may not be able to handle a batch size of 4096.\n",
"\n",
"Having a batch size of 4096 means that 4096 images need to fit into the GPU memory at a time.\n",
"\n",
"This works when you've got the hardware to handle it like a research team from Google often does but when you're running on a single GPU (such as using Google Colab), making sure things work with smaller batch size first is a good idea.\n",
"\n",
"An extension of this project could be to try a higher batch size value and see what happens.\n",
"\n",
"> **Note:** We're using the `pin_memory=True` parameter in the `create_dataloaders()` function to speed up computation. `pin_memory=True` avoids unnecessary copying of memory between the CPU and GPU memory by \"pinning\" examples that have been seen before. For more on this concept. Though the benefits of this will likely be seen with larger dataset sizes (our FoodVision Mini dataset is quite small). See the PyTorch [`torch.utils.data.DataLoader` documentation](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) or [Making Deep Learning Go Brrrr from First Principles](https://horace.io/brrr_intro.html) by Horace He for more."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 8,
2022-07-04 16:38:17 +10:00
"id": "d0ac8145-f89a-490f-82e3-d4b22225d163",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2022-07-22 14:06:23 +10:00
"(<torch.utils.data.dataloader.DataLoader at 0x7fa8cc731550>,\n",
" <torch.utils.data.dataloader.DataLoader at 0x7fa8cc731520>,\n",
2022-07-04 16:38:17 +10:00
" ['pizza', 'steak', 'sushi'])"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 8,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Set the batch size\n",
"BATCH_SIZE = 32 # this is lower than the ViT paper but it's because we're starting small\n",
"\n",
"# Create data loaders\n",
"train_dataloader, test_dataloader, class_names = data_setup.create_dataloaders(\n",
" train_dir=train_dir,\n",
" test_dir=test_dir,\n",
" transform=manual_transforms, # use manually created transforms\n",
" batch_size=BATCH_SIZE\n",
")\n",
"\n",
"train_dataloader, test_dataloader, class_names"
]
},
{
"cell_type": "markdown",
"id": "4a980a5b-0c3b-440d-87f5-c54f1ab143ab",
"metadata": {},
"source": [
"### TK 2.3 Visualize a single image\n",
"\n",
"Now we've loaded our data, let's *visualize, visualize, visualize!*\n",
"\n",
"An important step in the ViT paper is preparing the images into patches.\n",
"\n",
"We'll get to what this means in a second but for now, let's view a single image and its label.\n",
"\n",
"To do so, let's get a single image and label from a batch of data and inspect their shapes."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 9,
2022-07-04 16:38:17 +10:00
"id": "b5734a22-ded5-403e-84f5-d7a90ed3f085",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2022-07-22 14:06:23 +10:00
"(torch.Size([3, 224, 224]), tensor(0))"
2022-07-04 16:38:17 +10:00
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 9,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get a batch of images\n",
"image_batch, label_batch = next(iter(train_dataloader))\n",
"\n",
"# Get a single image from the batch\n",
"image, label = image_batch[0], label_batch[0]\n",
"\n",
"# View the batch shapes\n",
"image.shape, label"
]
},
{
"cell_type": "markdown",
"id": "898cbb6d-b433-41be-9280-41de129077df",
"metadata": {},
"source": [
"Wonderful!\n",
"\n",
"Now let's plot the image and its label with `matplotlib`. "
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 10,
2022-07-04 16:38:17 +10:00
"id": "afe85fae-38fd-4f34-a52c-29d02cce09c1",
"metadata": {},
"outputs": [
{
"data": {
2022-07-22 14:06:23 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAOcAAAD3CAYAAADmIkO7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOz9Waxta3bfh/2+fs65mr33Offe6lgki5TIIuk4VkMppMnIiiRKJCVZUhTJcQwFCPIWIHlJECTwQwLE8JuBNC95CpIgTvwQJwGiKLZliYoEkmJfrGKxGlax6tat251zdrPWmt3X5uGbc+11bhUr0rVlVoDzAfuefVe315rrG98Y4z/+4z9EKYVX69V6tb77lvzDfgOv1qv1an379co4X61X67t0vTLOV+vV+i5dr4zz1Xq1vkvXK+N8tV6t79L1yjhfrVfru3S9Ms7/P1tCiJ8WQnzxD/t9vFr/4pd4Ved8tV6t7871ynO+Wq/Wd+l6ZZzfpUsI8TUhxP9ECPF5IcSdEOJ/J4RohBD/mhDireUxf1sIcbr4mYUQvyCE+PgHbh+EEGV5zg8KIf6BEOKFEOK5EOL/JIS4/kP9sK/Wt12vjPO7e/23gL8I/CDwQ8C/fXlnKeU/KKVsSylb4OPAV4H/cynl7fX25b7/G/B/WZ4mgH93efyPAJ8E/mf/RXyYV+ufb70yzu/u9b8ppXyjlHIL/DvAf/PbPUgIIYF/H/iFUsr/9gP3/Y+BTwP/HYBSyu+VUv6TUspcSnkG/HvAn/kX+SFerQ+39B/2G3i1vuP6xsXvX6d6u2+3/h1gB/z3L28UQvws8D8A/nQpZVxuewP4XwE/vTxHAnf/+b7tV+s/j/XKc353r09e/P69wNsffIAQ4t+getS/WUoJF7f/MPC/B/5WKeXSyP9doAD/cillD/xb1FD31fouW6+M87t7/feEEN8jhHgC/E+B/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Zng8FqdT5EFNaI4REqJoKrCFvYX2/nEN4hEAs1nk+KJd/ynINubydJYwVVCNZPt9L3+n62+I1L77myy+HQj5fI3l+5UIhPBqrgFISJWdi8MzTicP9A++98zbvvf0mt+99g7l/ztw/kOYRWcAoSUkRqxVKSaSo17Zxmlzg4XjkdPs+zrXsjETniJ9GWmtIIeBDQEmJ2RjuDz2Hh8Dt+wd8FIzTiesne1wrmA4911dbFKBK4Xq/Q4tCnibmKTKKyPXVhrAVeJ9IPpJCps+Bw8Mto4+E00QDsIHrm5b9pgWjGX3geDpxHCY0Cm0tSjnGeWb0iaebLfvXr/5A+/uOxhnRvPv8OW98/CPsnz7lH/9H/4j7oydhgAxiyRd4PElZTtE1jCoFjNH88A//Ef7Wf+Nv8BM/8ae4vt6h9RJqnU9hUQ15PeHXzVYKKSWGU8/D/QOHuwce7u+Z+qmexFIsPxJrHZvtluvra7rtFm0MpRRi8Ph55nQ6cTqd8ONECnHdfee9JqsbP+eDq+fMKaOkRiuF1urxMYsnrGGmesnwVk8opfoW43zpd1mNWmm1eEeWVFDCOWcvFLGG+kCp134N+ZcbedkLLt9AWQ+/JbwtnFMPkRdPuVyDnPNjKrFcm3pMLeHsOTBavrOS6v3L61dcAVKMpBIZhhMlJXKKHB/uef+9d3nvnbe5e+89+n7geDjihwPbRrJzGSsLqrXIUhCphpNSSbQ1CGVJWeKD5/b2OQ8PR7Kfsa7ByUIJAQvIDAhFLgmrHX0fGI4zcRZcdVcM/YgygZbEx59e8eTmuuIPx577acJqjZYFp0Bqh9tY5pMHAc4IVJchJRhm/DExzx5bJK1xSOVBFbKMpJJAC1zXMY0BqAf4OEf6yaNsg3Itrt1+OON8//kDx3HmJ3/8T/GFL32Z3//6N4lIUinLF3I2y/N2WMOYeoRXD/ID3/99/I2/9q/
2022-07-04 16:38:17 +10:00
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Plot image with matplotlib\n",
"plt.imshow(image.permute(1, 2, 0)) # rearrange image dimensions to suit matplotlib [color_channels, height, width] -> [height, width, color_channels]\n",
"plt.title(class_names[label])\n",
"plt.axis(False);"
]
},
{
"cell_type": "markdown",
"id": "4b8416fa-fb0c-4276-8405-12531ba78b71",
"metadata": {},
"source": [
"Nice!\n",
"\n",
"Looks like our images are importing correctly, let's continue with the paper replication."
]
},
{
"cell_type": "markdown",
2022-07-22 14:06:23 +10:00
"id": "13bfb028-1afa-44ec-89e9-8890975311ea",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
"## TK 3. Replicating the ViT paper: an overview\n",
"\n",
"Before we write anymore code, let's discuss what we're doing.\n",
"\n",
"We'd like to replicate the ViT paper for our own problem, FoodVision Mini.\n",
"\n",
"So our inputs are: images of pizza, steak and sushi.\n",
"\n",
"And our ideal model outputs are: predicted labels of pizza, steak or sushi.\n",
"\n",
"No different to what we've been doing throughout the previous sections.\n",
"\n",
2022-07-22 14:06:23 +10:00
"The question is: how do we go from our inputs to the desired outputs?"
]
},
{
"cell_type": "markdown",
"id": "6e7f0a12-cce9-45d0-a572-4ad612a98735",
"metadata": {},
"source": [
2022-07-04 16:38:17 +10:00
"### 3.1 Inputs and outputs, layers and blocks\n",
"\n",
"ViT is a deep learning neural network architecture.\n",
"\n",
"And any neural network architecture is generally comprised of **layers**.\n",
"\n",
"And a collection of layers is often referred to as a **block**.\n",
"\n",
"And stacking many blocks together is what gives us the whole architecture.\n",
"\n",
"A **layer** takes an input (say an image tensor), performs some kind of function on it (for example what's in the layer's `forward()` method) and then returns an output.\n",
"\n",
"So if a **single layer** takes an input and gives an output, then a collection of layers or a **block** also takes an input and gives an output.\n",
"\n",
"Let's make this concrete:\n",
"* **Layer** - takes an input, performs a function on it, returns an output.\n",
"* **Block** - a collection of layers, takes an input, performs a series of functions on it, returns an output.\n",
"* **Architecture (or model)** - a collection of blocks, takes an input, performs a series of functions on it, returns an output.\n",
"\n",
"This ideology is what we're going to be using to replicate the ViT paper.\n",
"\n",
"We're going to take it layer by layer, block by block, function by function putting the pieces of the puzzle together like Lego to get our desired overall architecture.\n",
"\n",
"The reason we do this is because looking at a whole research paper can be intimidating.\n",
"\n",
"So for a better understanding, we'll break it down, starting with the inputs and outputs of single layer and working up to the inputs and outputs of the whole model.\n",
"\n",
2022-07-22 14:06:23 +10:00
"TK image: stacking the network together like lego (functions + layers + blocks = model)."
]
},
{
"cell_type": "markdown",
"id": "c2852f3f-61f0-4dad-ae8c-49db54e28470",
"metadata": {},
"source": [
2022-07-04 16:38:17 +10:00
"### 3.2 Getting specific: What's ViT made of?\n",
"\n",
"There are many little details about the ViT model sprinkled throughout the paper.\n",
"\n",
2022-07-22 14:06:23 +10:00
"Finding them all is like one big treasure hunt!\n",
"\n",
"Remember, a research paper is often months of work compressed into a few pages so it's understandable for it to take of practice to replicate.\n",
"\n",
2022-07-04 16:38:17 +10:00
"However, the main three resources we'll be looking at for the architecture design are:\n",
"1. **Figure 1** - This gives an overview of the model in a graphical sense, you could *almost* recreate the architecture with this figure alone.\n",
"2. **Four equations in section 3.1** - These equations give a little bit more of a mathematical grounding to the coloured blocks in Figure 1.\n",
2022-07-22 14:06:23 +10:00
"3. **Table 1** - This table shows the various hyperparameter settings (such as number of layers and number of hidden units) for different ViT model variants. We'll be focused on the smallest version, ViT-Base."
]
},
{
"cell_type": "markdown",
"id": "bac7c7d2-e58b-47b1-ae3e-7ae9f922326d",
"metadata": {},
"source": [
"#### TK 3.2.1 Exploring Figure 1\n",
"\n",
"Let's start by going through Figure 1 of the ViT Paper.\n",
"\n",
"The main things we'll be paying attention to are:\n",
"1. **Layers** - takes an **input**, performs an operation or function, produces an **output**.\n",
"2. **Blocks** - a collection of layers, which in turn also takes an **input** and produces an **output**.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-figure-1-inputs-and-outputs.png\" width=900 alt=\"figure 1 from the original vision transformer paper\"/>\n",
"\n",
"*Figure 1 from the ViT Paper showcasing the different inputs, outputs, layers and blocks that create the architecture. Our goal will be to replicate each of these using PyTorch code.* \n",
"\n",
"The ViT architecture is comprised of several stages:\n",
"* **Patch + Position Embedding (inputs)** - Turns the input image into a sequence of image patches and add a position number what order the patch comes in.\n",
"* **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",
"* **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",
"You might notice that many of the pieces of the ViT architecture can be created with existing PyTorch layers.\n",
"\n",
"This is because of how PyTorch is designed, it's one of the main purposes of PyTorch to create reusable neural network layers for both researchers and machine learning practitioners.\n",
"\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",
"\n",
"> **Note:** We're going to focused on write 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",
"Let's take Figure 1 and adapt it to our FoodVision Mini problem of classifying images of food into pizza, steak or sushi.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-figure-1-inputs-and-outputs-food-mini.png\" width=900 alt=\"figure 1 from the original vision transformer paper adapted to work with food images, an image of pizza goes in and gets classified as 'pizza'\"/>\n",
"\n",
"*Figure 1 from the ViT Paper adapted for use with FoodVision Mini. An image of food goes in (pizza), the image gets turned into patches and then projected to an embedding. The embedding then travels through the various layers and blocks and (hopefully) the class \"pizza\" is returned.*"
]
},
{
"cell_type": "markdown",
"id": "add31aa8-2809-4f77-b94c-e34d865c12d0",
"metadata": {},
"source": [
"#### TK - 3.2.2 Exploring the Four Equations\n",
"\n",
"The next main part(s) of the ViT paper we're going to look at are the four equations in section 3.1.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-four-equations.png\" width=650 alt=\"four mathematical equations from the vision transformer machine learning paper\"/>\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"*These four equations represent the math behind the four major parts of the ViT architecture.*\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"Section 3.1 describes each of these (some of the text has been omitted for brevity, bolded text is mine):\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"| **Equation number** | **Description from ViT paper section 3.1** | \n",
"| ----- | ----- | \n",
"| 1 | ...The Transformer uses constant latent vector size $D$ through all of its layers, so we flatten the patches and map to $D$ dimensions with a **trainable linear projection** (Eq. 1). We refer to the output of this projection as the **patch embeddings**. |\n",
"| 2 | The Transformer encoder (Vaswani et al., 2017) consists of alternating layers of multiheaded selfattention (MSA, see Appendix A) and MLP blocks (Eq. 2, 3). **Layernorm (LN) is applied before every block**, and **residual connections after every block** (Wang et al., 2019; Baevski & Auli, 2019). |\n",
"| 3 | See above. |\n",
"| 4 | 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)... |\n",
"\n",
"Let's map these descriptions to the ViT architecture in Figure 1.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-mapping-the-four-equations-to-figure-1.png\" width=1000 alt=\"mapping the vision transformer paper figure 1 to the four equations listed in the paper\"/>\n",
"\n",
"*Connecting Figure 1 from the ViT paper to the four equations from section 3.1 describing the math behind each of the layers/blocks. Some details such as \"residual connections after every block\" are referred to in Figure 1 and in the text but not in the equations.*\n",
"\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",
"\\begin{aligned}\n",
"\\mathbf{z}_{0} &=\\left[\\mathbf{x}_{\\text {class }} ; \\mathbf{x}_{p}^{1} \\mathbf{E} ; \\mathbf{x}_{p}^{2} \\mathbf{E} ; \\cdots ; \\mathbf{x}_{p}^{N} \\mathbf{E}\\right]+\\mathbf{E}_{\\text {pos }}, & & \\mathbf{E} \\in \\mathbb{R}^{\\left(P^{2} \\cdot C\\right) \\times D}, \\mathbf{E}_{\\text {pos }} \\in \\mathbb{R}^{(N+1) \\times D}\n",
"\\end{aligned}\n",
"$$\n",
"\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",
"TK - update the vector form to reflect a real exmaple\n",
"\n",
"```python\n",
"x_input = [class_token, image_patch_1, image_patch_2, image_patch_3...] + [class_token_position, image_patch_1_position, image_patch_2_position, image_patch_3_position...]\n",
"```\n",
"\n",
"Where each of the elements in the vector is learnable (their `requires_grad=True`).\n",
"\n",
"**Equation 2**\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{z}_{\\ell}^{\\prime} &=\\operatorname{MSA}\\left(\\operatorname{LN}\\left(\\mathbf{z}_{\\ell-1}\\right)\\right)+\\mathbf{z}_{\\ell-1}, & & \\ell=1 \\ldots L\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"This says that for every layer from $1$ through to $L$ (the total number of layers), there's a Multi-Head Attention layer (MSA) wrapping a LayerNorm layer (LN).\n",
"\n",
"The addition on the end is the equivalent of adding the input to the output and forming a [skip/residual connection](https://paperswithcode.com/method/residual-connection).\n",
"\n",
"We'll call this layer the \"MSA block\".\n",
"\n",
"In pseudocode, this might look like: \n",
"\n",
"```python\n",
"x_output_MSA_block = MSA_layer(LN_layer(x_input)) + x_input\n",
"```\n",
"\n",
"Notice the skip connection on the end (adding the input of the layers to the output of the layers).\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"**Equation 3**\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{z}_{\\ell} &=\\operatorname{MLP}\\left(\\operatorname{LN}\\left(\\mathbf{z}_{\\ell}^{\\prime}\\right)\\right)+\\mathbf{z}_{\\ell}^{\\prime}, & & \\ell=1 \\ldots L \\\\\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"This says that for every layer from $1$ through to $L$ (the total number of layers), there's also a Multilayer Perceptron layer (MLP) wrapping a LayerNorm layer (LN).\n",
"\n",
"The addition on the end is showing the presence of a skip/residual connection.\n",
"\n",
"We'll call this layer the \"MLP block\".\n",
"\n",
"In pseudocode, this might look like: \n",
"\n",
"```python\n",
"x_output_MLP_block = MLP_layer(LN_layer(x_output_MSA_block)) + x_output_MSA_block\n",
"```\n",
"\n",
"Notice the skip connection on the end (adding the input of the layers to the output of the layers).\n",
"\n",
"**Equation 4**\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{y} &=\\operatorname{LN}\\left(\\mathbf{z}_{L}^{0}\\right) & &\n",
"\\end{aligned}\n",
"$$\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"This says for the last layer $L$, the output $y$ is the 0 index token of $z$ wrapped in a LayerNorm layer (LN).\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"Or in our case, the 0 index of `x_output_MLP_block`:\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"```python\n",
"y = LN_layer(Linear_layer(x_output_MLP_block[0]))\n",
"```\n",
"\n",
"Of course there are some simplifications above but we'll take care of those when we start to write PyTorch code for each section.\n",
"\n",
"> **Note:** The above section covers alot of information. But don't forget if something doesn't make sense, you can always research it further. By asking questions like \"what is a residual connection?\"."
]
},
{
"cell_type": "markdown",
"id": "cd36899e-5bc7-411a-aab7-28e3a5a2c6cb",
"metadata": {},
"source": [
"#### TK - 3.2.3 Exploring Table 1\n",
"\n",
"The final piece of the ViT architecture puzzle we'll focus on (for now) is Table 1.\n",
2022-07-04 16:38:17 +10:00
"\n",
"| Model | Layers | Hidden size $D$ | MLP size | Heads | Params |\n",
"| :--- | :---: | :---: | :---: | :---: | :---: |\n",
2022-07-22 14:06:23 +10:00
"| ViT-Base | 12 | 768 | 3072 | 12 | $86M$ |\n",
"| ViT-Large | 24 | 1024 | 4096 | 16 | $307M$ |\n",
"| ViT-Huge | 32 | 1280 | 5120 | 16 | $632M$ |\n",
"\n",
"<div align=center>\n",
" <i>Table 1: Details of Vision Transformer model variants. Source: <a href=\"https://arxiv.org/abs/2010.11929\">ViT paper</a>.</i>\n",
"</div>\n",
"<br>\n",
"\n",
"This table showcasing the various hyperparameters of each of the ViT architectures.\n",
"\n",
"You can see the numbers gradually increase from ViT-Base to ViT-Huge.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"We're going to focus on replicating ViT-Base (start small and scale up when necessary) but we'll be writing code that could easily scale up to the larger variants.\n",
"\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",
"* **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",
"\n",
"We'll use these values as the hyperparameter settings for our ViT architecture. "
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "markdown",
2022-07-22 14:06:23 +10:00
"id": "d9aedd15-5a98-431e-bd9e-9d18616e4bff",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"### TK - 3.3 My workflow for replicating papers\n",
"\n",
"When I start working on replicating a paper, I go through the following steps:\n",
"\n",
"1. Read the whole paper end-to-end once (to get an idea of the main concepts).\n",
"2. Go back through each section and see how they line up with each other and start thinking about how they might be turned into code (just like above).\n",
"3. Repeat step 2 until I've got a fairly good outline.\n",
"4. Use [mathpix.com](https://mathpix.com/) (a very handy tool) to turn any sections of the paper into markdown/LaTeX to put into notebooks.\n",
"5. Replicate the simplest version of the model possible.\n",
"6. If I get stuck, look up other examples.\n",
"\n",
"TK - gif of mathpix\n",
"\n",
"We've already gone through the first few steps above (and if you haven't read the full paper yet, I'd encourage you to give it a go) but what we'll be focusing on next is step 5: replicating the simplest version fo the model possible.\n",
"\n",
"This is why we're starting with ViT-Base.\n",
"\n",
"Replicating the smallest version of the architecture possible, get it working and then we can scale up if we wanted to.\n",
"\n",
"> **Note:** If you've never read a research paper before, many of the above steps can be intimidating. But don't worry, like anything, your skills at reading *and* replicating papers will improve with practice. Don't forget, a research paper is often *months* of work by many people compressed into a few pages. So trying to replicate it on your own is no small feat. "
]
},
{
"cell_type": "markdown",
"id": "9f1717f5-f6bc-4cce-b5eb-093822da988d",
"metadata": {
"tags": []
},
"source": [
"## TK 4. Equation 1: Split data into patches and creating the class, position and patch embedding \n",
"\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",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"We'll start with the **patch embedding**.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"This means we'll be turning our input images in a sequence of patches and then embedding those patches.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"Recall that an **embedding** is a learnable representation of some form and is often a vector. The term learnable is important because this means the representation of an input image can be improved and learned over time.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"We'll begin by following the opening paragraph of section 3.1 of the ViT paper (bold mine):\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"> The standard Transformer receives as input a 1D sequence of token embeddings. To handle 2D images, we reshape the image $\\mathbf{x} \\in \\mathbb{R}^{H \\times W \\times C}$ into a sequence of flattened 2D patches $\\mathbf{x}_{p} \\in \\mathbb{R}^{N \\times\\left(P^{2} \\cdot C\\right)}$, where $(H, W)$ is the resolution of the original image, $C$ is the number of channels, $(P, P)$ is the resolution of each image patch, and $N=H W / P^{2}$ is the resulting number of patches, which also serves as the effective input sequence length for the Transformer. The Transformer uses constant latent vector size $D$ through all of its layers, so we flatten the patches and map to $D$ dimensions with a trainable linear projection (Eq. 1). We refer to the output of this projection as the **patch embeddings**.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"And size we're dealing with image shapes, let's keep in mind the line from Table 3 of the ViT paper: \n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"> Training resolution is **224**.\n",
"\n",
"Let's break down the text above.\n",
"\n",
"* $D$ is the size of the **patch embeddings**, different values for $D$ can be found in Table 1.\n",
"* The image starts as 2D with size ${H \\times W \\times C}$.\n",
"* The image gets converted to a sequence of flattened 2D patches with size ${N \\times\\left(P^{2} \\cdot C\\right)}$.\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",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-annotated.png\" width=900 alt=\"mapping the vit architecture diagram positional and patch embeddings portion to the relative mathematical equation describing what's going on\"/>\n",
"\n",
"*Mapping the patch and position embedding portion of the ViT architecture from Figure 1 to Equation 1. The opening paragraph of section 3.1 describes the different input and output shapes of the patch embedding layer.*"
]
},
{
"cell_type": "markdown",
"id": "2010c168-88c7-4045-8c02-8e759ffacef8",
"metadata": {
"tags": []
},
"source": [
"### TK - 4.1 Calculating patch embedding input and output shapes by hand\n",
"\n",
"How about we start by calculating these input and output shape values by hand?\n",
"\n",
"To do so, let's create some variables to mimic each of the terms (such as $H$, $W$ etc) above.\n",
"\n",
"We'll use a patch size ($P$) of 16 since it's the best performing version of ViT-Base uses (see column \"ViT-B/16\" of Table 5 in the ViT paper for more)."
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 11,
"id": "bb10d7f1-1aca-416f-b5a4-3abe722ff207",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
2022-07-22 14:06:23 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
"Number of patches (N) with image height (H=224), width (W=224) and patch size (P=16): 196\n"
]
2022-07-04 16:38:17 +10:00
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# Create example values\n",
"height = 224 # H (\"The training resolution is 224.\")\n",
"width = 224 # W\n",
"color_channels = 3 # C\n",
"patch_size = 16 # P\n",
"\n",
"# Calculate N (number of patches)\n",
"number_of_patches = int((height * width) / patch_size**2)\n",
"print(f\"Number of patches (N) with image height (H={height}), width (W={width}) and patch size (P={patch_size}): {number_of_patches}\")"
]
},
{
"cell_type": "markdown",
"id": "0e5f118e-e828-498a-abe1-0de8a5d90cd5",
"metadata": {},
"source": [
"We've got the number of patches, how about we create the image output size as well?\n",
"\n",
"Better yet, let's replicate the input and output shapes of the patch embedding layer.\n",
"\n",
"Recall:\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)}$."
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 12,
"id": "1f684bab-1e4e-4251-99b7-839b0b69dbd3",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
2022-07-22 14:06:23 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
"Input shape (2D image): (224, 224, 3)\n",
"Output shape (flattened 2D patches): (196, 768)\n"
]
2022-07-04 16:38:17 +10:00
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# Input shape\n",
"input_shape = (height, width, color_channels)\n",
"\n",
"# Output shape\n",
"output_shape = (number_of_patches, patch_size**2 * color_channels)\n",
"\n",
"print(f\"Input shape (2D image): {input_shape}\")\n",
"print(f\"Output shape (flattened 2D patches): {output_shape}\")"
2022-07-04 16:38:17 +10:00
]
},
{
2022-07-22 14:06:23 +10:00
"cell_type": "markdown",
"id": "addb44a8-dd44-4ad4-8641-5e8c6f49753b",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"Input and output shapes acquired!"
]
},
{
"cell_type": "markdown",
"id": "7ee6c9bf-e40f-4511-9325-498251f5b998",
"metadata": {},
"source": [
"### TK - 4.2 Turning a single image into patches\n",
"\n",
"Now we know the ideal input and output shapes for our **patch embedding** layer.\n",
"\n",
"What we're doing here is breaking the overall architecture down into smaller pieces, focusing on the inputs and outputs of individual layers.\n",
"\n",
"So how do we create the patch embedding layer?\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"We'll get to that shortly, first, let's *visualize, visualize, visualize!* what it looks like to turn an image into patches.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"Let's start with our single image."
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 13,
"id": "336e1b36-9849-4104-8cb9-bb64a20ffc48",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
"data": {
2022-07-22 14:06:23 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAOcAAAD3CAYAAADmIkO7AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOz9Waxta3bfh/2+fs65mr33Offe6lgki5TIIuk4VkMppMnIiiRKJCVZUhTJcQwFCPIWIHlJECTwQwLE8JuBNC95CpIgTvwQJwGiKLZliYoEkmJfrGKxGlax6tat251zdrPWmt3X5uGbc+11bhUr0rVlVoDzAfuefVe315rrG98Y4z/+4z9EKYVX69V6tb77lvzDfgOv1qv1an379co4X61X67t0vTLOV+vV+i5dr4zz1Xq1vkvXK+N8tV6t79L1yjhfrVfru3S9Ms7/P1tCiJ8WQnzxD/t9vFr/4pd4Ved8tV6t7871ynO+Wq/Wd+l6ZZzfpUsI8TUhxP9ECPF5IcSdEOJ/J4RohBD/mhDireUxf1sIcbr4mYUQvyCE+PgHbh+EEGV5zg8KIf6BEOKFEOK5EOL/JIS4/kP9sK/Wt12vjPO7e/23gL8I/CDwQ8C/fXlnKeU/KKVsSylb4OPAV4H/cynl7fX25b7/G/B/WZ4mgH93efyPAJ8E/mf/RXyYV+ufb70yzu/u9b8ppXyjlHIL/DvAf/PbPUgIIYF/H/iFUsr/9gP3/Y+BTwP/HYBSyu+VUv6TUspcSnkG/HvAn/kX+SFerQ+39B/2G3i1vuP6xsXvX6d6u2+3/h1gB/z3L28UQvws8D8A/nQpZVxuewP4XwE/vTxHAnf/+b7tV+s/j/XKc353r09e/P69wNsffIAQ4t+getS/WUoJF7f/MPC/B/5WKeXSyP9doAD/cillD/xb1FD31fouW6+M87t7/feEEN8jhHgC/E+B/+DyTiHEHwP+18BfW0LU9fY98P8A/u1Syj/5wG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s1nk+KJd/ynINubydJYwVVCNZPt9L3+n62+I1L77myy+HQj5fI3l+5UIhPBqrgFISJWdi8MzTicP9A++98zbvvf0mt+99g7l/ztw/kOYRWcAoSUkRqxVKSaSo17Zxmlzg4XjkdPs+zrXsjETniJ9GWmtIIeBDQEmJ2RjuDz2Hh8Dt+wd8FIzTiesne1wrmA4911dbFKBK4Xq/Q4tCnibmKTKKyPXVhrAVeJ9IPpJCps+Bw8Mto4+E00QDsIHrm5b9pgWjGX3geDpxHCY0Cm0tSjnGeWb0iaebLfvXr/5A+/uOxhnRvPv8OW98/CPsnz7lH/9H/4j7oydhgAxiyRd4PElZTtE1jCoFjNH88A//Ef7Wf+Nv8BM/8ae4vt6h9RJqnU9hUQ15PeHXzVYKKSWGU8/D/QOHuwce7u+Z+qmexFIsPxJrHZvtluvra7rtFm0MpRRi8Ph55nQ6cTqd8ONECnHdfee9JqsbP+eDq+fMKaOkRiuF1urxMYsnrGGmesnwVk8opfoW43zpd1mNWmm1eEeWVFDCOWcvFLGG+kCp134N+ZcbedkLLt9AWQ+/JbwtnFMPkRdPuVyDnPNjKrFcm3pMLeHsOTBavrOS6v3L61dcAVKMpBIZhhMlJXKKHB/uef+9d3nvnbe5e+89+n7geDjihwPbRrJzGSsLqrXIUhCphpNSSbQ1CGVJWeKD5/b2OQ8PR7Kfsa7ByUIJAQvIDAhFLgmrHX0fGI4zcRZcdVcM/YgygZbEx59e8eTmuuIPx577acJqjZYFp0Bqh9tY5pMHAc4IVJchJRhm/DExzx5bJK1xSOVBFbKMpJJAC1zXMY0BqAf4OEf6yaNsg3Itrt1+OON8//kDx3HmJ3/8T/GFL32Z3//6N4lIUinLF3I2y/N2WMOYeoRXD/ID3/99/I2/9q/
2022-07-04 16:38:17 +10:00
"text/plain": [
2022-07-22 14:06:23 +10:00
"<Figure size 432x288 with 1 Axes>"
2022-07-04 16:38:17 +10:00
]
},
2022-07-22 14:06:23 +10:00
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
2022-07-04 16:38:17 +10:00
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# View single image\n",
"plt.imshow(image.permute(1, 2, 0)) # adjust for matplotlib\n",
"plt.title(class_names[label])\n",
"plt.axis(False);"
]
},
{
"cell_type": "markdown",
"id": "c7ebc6e5-c601-49fa-a185-05a50fdc81cc",
"metadata": {},
"source": [
"We want to turn this image into patches of itself inline with Figure 1 of the ViT paper.\n",
"\n",
"How about we start by just visualizing the top row of patched pixels?\n",
"\n",
"We can do this by indexing on the different image dimensions."
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 14,
"id": "bcd2e784-7989-40e5-b8f5-64de18f1fe3d",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
"data": {
2022-07-22 14:06:23 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA54AAABhCAYAAAC+o362AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAyFklEQVR4nO2dWZBtV33e/+vsM/c5PdxBF01IAktAgDBEARcYQsXBATPISQWXcEIJjBEikIorL+DkIS4/ESdOVZ6SwmUqpMoG2+UQE5cTIMTEVakAAqEESaB5urpD33t7OH3ms/deebiNur9vde91j/qe7vbt71eluvr3nta81u5e3/6c996EEEIIIYQQQohZUTroBAghhBBCCCGEuLbRi6cQQgghhBBCiJmiF08hhBBCCCGEEDNFL55CCCGEEEIIIWaKXjyFEEIIIYQQQswUvXgKIYQQQgghhJgpe3rxdM69xzn3qHPuCefc565WooQQQgghhBBCXDu4l+rj6ZxLzOwxM3u3mZ02s/vN7MPe+0euXvKEEEIIIYQQQvxVp7yHa99iZk94758yM3POfcXM7jKzXV88G7WyX2hUXozz3MHxLMeX4DRPIfYOjy8uLkA8GE4g7mz08Xp6x36J79xXDN/euR1P2wPFNyyV8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EM+RxrNK/lesu2FN53iM2gX2Le1RPCR/KO57Mf3t9N54rHljX8jYHYt1T6FvImsAizWTrKncq8YzptEMNZ/FmsaYxjF2fqxvRjWLrvh5obCsuHy5PbDnMGs8A19cyn/ok1ssTGSvx4hMMUxAxFszHCq3joeSy+KHx8o6Jhn0sb4
2022-07-04 16:38:17 +10:00
"text/plain": [
2022-07-22 14:06:23 +10:00
"<Figure size 1152x1152 with 1 Axes>"
2022-07-04 16:38:17 +10:00
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# Change image shape to be compatible with matplotlib (color_channels, height, width) -> (height, width, color_channels) \n",
"image_permuted = image.permute(1, 2, 0)\n",
"\n",
"# Index to plot the top row of patched pixels\n",
"patch_size = 16\n",
"plt.figure(figsize=(patch_size, patch_size))\n",
"plt.imshow(image_permuted[:patch_size, :, :]);"
]
},
{
"cell_type": "markdown",
"id": "ad0f2977-7c7b-45e5-91a9-a8626e8e73c7",
"metadata": {},
"source": [
"Now we've got the top row, let's turn it into patches.\n",
"\n",
"We can do this by iterating through the number of patches there'd be in the top row. "
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 15,
"id": "93210158-3dcb-4d1f-b728-c7c9c3df99dd",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-07-22 14:06:23 +10:00
"Number of patches per row: 14.0\n"
2022-07-04 16:38:17 +10:00
]
},
{
"data": {
2022-07-22 14:06:23 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAx8AAABLCAYAAAARUzrZAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAABQZklEQVR4nO29eawlzXUf9jvV3Xd/+zYz3zf6KFE0F5HUEkdRIkCIJTuRbIFKbNhwoARCnMQJ4DhyFkhRFCgIYgGxncWG/wgQWDIFSGZASyTsKLZC2Upk5w9KlijKpEhRsrh9+3yzvHnLXXqpyh9VXedU3+737p15M4/fTP0Gb27dvtXVtXX3OXV+dQ4ZYxAREREREREREREREfGkoa67AhERERERERERERERzwei8hERERERERERERER8VQQlY+IiIiIiIiIiIiIiKeCqHxERERERERERERERDwVROUjIiIiIiIiIiIiIuKpICofERERERERERERERFPBek6mYf91GwNMxgAxgAwBAMDbQAY2LTWMNCA/dleJE0wGAyQpCm0NijLClobVGWFeV6iqiqb37hyrwiyKK01tNZ0UX6llEmSR9XHlosmckeJfB+kaYosSzEajpBlKYgIShGIyJ1DF5bZhZdffhX37j+49IS93R1z+/YLlzRFFCMGpOMwZE/XrpuNMTDawMBw2hgYY8fCGG3njDFY1d3zW/fu4+T07MI2bm5MzOHe7tJxpXhcVZKI45wOxl40Vl7QyLZqTmutxXFOa2Naj7d135279/Dw9PTSMdza2DBHB3tLxw26+7G7UGr/0fDP3eU0T/QTvjPvG3fu4Pjk5MI2bm9tmpuHh8vXaE+udJtQMJ5dBWGtPG35X3ntddw/Pr70jN3tbfPirRutJXVc4NHRMZe7s3c8g1zy5Vcuf9bs7e6Y2y/ecqet15erQc71lVq1cplfXeFZure7a77usudoZ1WegHt7UeQqLf2tf/47d40xBxfl2dvdMS+5NnbVuOvZ2FULmaernt3X6jjDLCdXn6MvXFIXE3xrzySe68E4kDgu35Gcvwvhe0M20J772ptv4cHDy98V25sTc9O9K6qqlJVurb88XpWcX+tKpDl/ZwVk/YNribTqkDNcqfdOFzidFRe2cTJIzd5GHwBQFFxf2We9XtZ6+aB9FbcpEfIBEcsEuqNNssxgqCopH3C6bvZpUWJWXiyTAsAoS8z2wLahlpUBoBK2g6BdIo8cz1TIN71+0ppHyfaKMa9KMS8q2Q/i3SLeG0lqyzmZF5gVVWsb11I+tkYZfui734mqUigKBV0plFpjnmuUlUZe5ZjOz5BXOZKUk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3/JDUMSqMs9FaKVtkKxjnQ+eSpVlGcaTMba2trC9s429vT0cHByg3+9hMBggy1IoIiRK8eogtYuNVxmJvku4CNriNQ7jn/rBK1OskEsloiorVJW1cJRlibIoUJUVyrJAWdjfdGU/ZRnyAla5cVYWAGRMKKE99xAa9VK3yNmzmhDlSuxU1L2SgVDhkFYN+yygtlsCtfJMaymREREREREREc8i1lI+gHqFgqCMAilCZRyvHwaGAJUmSEyKXq+PwXCE4XAMUgkWiwJ5oXE+nWOxKFAUFcpSBxy5dlzAZL9M8bhKSDZY8MWma6ErS1MMR0NkaYrdnR0cHR1hb3cHBwcHmEwm6Pf76GUpkkQ5gazlWisuWq+2yrYOgkZ25xJ7OHTlFA7NSkdVVSiLEmVeeMtHWdjjVaXdno+G4gE30rVFq7GqHAXXNnSZ9VabQNyjgjZo6jVDIxQMN0+bVCsS1jJPPayVaFpSVuIARkRERERERKxt+UizFFoToBIYQyid8lHqygrfvR5UmmA0mWBrew9b25uYzhe4d/8Es/kCx8dneHg6xfk0R6X
2022-07-04 16:38:17 +10:00
"text/plain": [
2022-07-22 14:06:23 +10:00
"<Figure size 1008x1008 with 14 Axes>"
2022-07-04 16:38:17 +10:00
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# Setup hyperparameters and make sure img_size and patch_size are compatible\n",
"img_size = 224\n",
"patch_size = 16\n",
"num_patches = img_size/patch_size \n",
"assert img_size % patch_size == 0, \"Image size must be divisible by patch size\" \n",
"print(f\"Number of patches per row: {num_patches}\")\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"# Create a series of subplots\n",
"fig, axs = plt.subplots(nrows=1, \n",
" ncols=img_size // patch_size, # one column for each patch\n",
" figsize=(num_patches, num_patches),\n",
" sharex=True,\n",
" sharey=True)\n",
"\n",
"# Iterate through number of patches in the top row\n",
"for i, patch in enumerate(range(0, img_size, patch_size)):\n",
" axs[i].imshow(image_permuted[:patch_size, patch:patch+patch_size, :]); # keep height index constant, alter the width index\n",
" axs[i].set_xlabel(i+1) # set the label\n",
" axs[i].set_xticks([])\n",
" axs[i].set_yticks([])"
]
},
{
"cell_type": "markdown",
"id": "dc30f0a2-7344-4a90-b5b7-7a98127c59fd",
"metadata": {},
"source": [
"Those are some nice looking patches!\n",
"\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."
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "7d45e15a-eb50-4c46-8055-2acaaacb881c",
"metadata": {
"tags": []
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Number of patches per row: 14.0\n",
"Number of patches per column: 14.0\n",
"Total patches: 196.0\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAysAAAN6CAYAAACOhdYOAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAEAAElEQVR4nOz9a7Bsy5YWhn0jc86q9dp7n7P3edx7XvfcV9/bdBMgW5YBg9R2BBICKRojCSSBHsgQWLZkoxByY2QJEFYI2QEBkgKBeATmYay2ETIGAQ2NQebRCBtoBE3T0C/69u37OPec/VhrVc1H5vCPMUZmzllVa1XV3uf04pLfjrVrVtWsnJk5c2aOb4yRYxAzo6KioqKioqKioqKi4q7B/XhXoKKioqKioqKioqKiYhsqWamoqKioqKioqKiouJOoZKWioqKioqKioqKi4k6ikpWKioqKioqKioqKijuJSlYqKioqKioqKioqKu4kKlmpqKioqKioqKioqLiTqGSloqKi4jlBRN9CRExE3/LjXZePCkT0a7TN9veYiP47IvoXjyzrf3ZkPX6IiH7fHuf9biL6odlnnyeiP01ET7UNP9fadUxddlz3X9Wy331RZVZUVFT8g4RKVioqKiqeH38FwE/V13/Q8NMhbf8XAfwogN9PRP/agWX8agBHkZUD8OsA/M9n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9KvBPBfqcXsK5BACPc/inpWVFRUfL2ikpWKioqK2/GtkPC7/x6AJxCLyE3hbj+vr795y3e/GGIxOIMQn39i9v2fBfAtzPw3iegXAvgPIO5k3w8Rhn8WgG85phGKt5j5S8/x+73AzD0R/VwA/xkkNPL7kPDPfw+yT6fEvwHgPwHw/4LkJfm1EDL4/ySinwnp99+p534/ZBP/R4lfBNk39K9B9tt0kHv4J6B7UrS9PxPS3t8C4AoSieyPAvitm0VWVFRUVOwD+vGzrFdUVFTcbWhywl8NoN2xL6OioqKioqLiQ0QNXVxRUVFRUVFRUVFRcSdRyUpFRUVFRUVFRUVFxZ1EdQOrqKioqKioqKioqLiTqJaVioqKioqKioqKioo7iUpWKioqKioqKioqKiruJCpZqaioqKioqKioqKi4k6hkpaKioqKioqKioqLiTqKSlYqKioqKioqKioqKO4lKVioqKioqKioqKioq7iQqWamoqKioqKioqKiouJOoZKWioqKioqKioqKi4k6ikpWKioqKioqKioqKijuJSlYqKioqKioqKioqKu4kKlmpqKioqKioqKioqLiTqGSloqKioqKioqKiouJOopKVioqKioqKioqKioo7iUpWKioqKioqKioqKiruJCpZqaioqKioqKioqKi4k6hkpaKioqKioqKioqLiTqKSlYqKioqKioqKioqKO4lKVioqKioqKioqKioq7iQqWamoqKioqKioqKiouJOoZKWioqKioqKioqKi4k6ikpWKioqKioqKioqKijuJSlYqKioqKioqKioqKu4kKlmpqKioqKioqKioqLiTqGSloqKioqKioqKiouJOopKVioqKioqKioqKioo7iUpWKioqKioqKioqKiruJCpZqaioqKioqKioqKi4k6hkpaKioqKioqKioqLiTqKSlYqKioqKioqKioqKO4lKVioqKioqKioqKioq7iQqWamoqKioqKioqKiouJOoZKWioqKioqKioqKi4k6ikpWKioqKioqKioqKijuJSlYqKioqKioqKioqKu4kKlmpqKioqKioqKioqLiTqGSloqKioqKioqKiouJOopKVioqKioqKioqKioo7iUpWKioqKioqKioqKiruJCpZqaioqKioqKioqKi4k6hkpaKioqKioqKioqLiTqKSlYqKioqKioqKioqKO4lKVioqKioqKioqKioq7iQqWamoqKioqKioqKiouJOoZKWioqKioqKioqKi4k6ikpWKioq
"text/plain": [
"<Figure size 1008x1008 with 196 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Setup hyperparameters and make sure img_size and patch_size are compatible\n",
"img_size = 224\n",
"patch_size = 16\n",
"num_patches = img_size/patch_size \n",
"assert img_size % patch_size == 0, \"Image size must be divisible by patch size\" \n",
"print(f\"Number of patches per row: {num_patches}\\nNumber of patches per column: {num_patches}\\nTotal patches: {num_patches*num_patches}\")\n",
"\n",
"# Create a series of subplots\n",
"fig, axs = plt.subplots(nrows=img_size // patch_size, # need int not float\n",
" ncols=img_size // patch_size, \n",
" figsize=(num_patches, num_patches),\n",
" sharex=True,\n",
" sharey=True)\n",
"\n",
"# Loop through height and width of image\n",
"for i, patch_height in enumerate(range(0, img_size, patch_size)): # iterate through height\n",
" for j, patch_width in enumerate(range(0, img_size, patch_size)): # iterate through width\n",
" \n",
" # Plot the permuted image patch (image_permuted -> (Height, Width, Color Channels))\n",
" axs[i, j].imshow(image_permuted[patch_height:patch_height+patch_size, # iterate through height \n",
" patch_width:patch_width+patch_size, # iterate through width\n",
" :]) # get all color channels\n",
" \n",
" # Set up label information, remove the ticks for clarity and set labels to outside\n",
" axs[i, j].set_ylabel(i+1, \n",
" rotation=\"horizontal\", \n",
" horizontalalignment=\"right\", \n",
" verticalalignment=\"center\") \n",
" axs[i, j].set_xlabel(j+1) \n",
" axs[i, j].set_xticks([])\n",
" axs[i, j].set_yticks([])\n",
" axs[i, j].label_outer()\n",
"\n",
"# Set a super title\n",
"fig.suptitle(f\"{class_names[label]} -> Patchified\", fontsize=16)\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"id": "32a983e8-6d76-4ef0-b0f2-c97a42bdbb08",
"metadata": {},
"source": [
"Image patchified!\n",
"\n",
"Woah, that looks cool.\n",
"\n",
"Now how do we turn each of these patches into an embedding and convert them into a sequence?\n",
"\n",
"Hint: we can use PyTorch layers. Can you guess which?"
]
},
{
"cell_type": "markdown",
"id": "f774b58d-7095-4272-aba3-fd9a2db4f28f",
"metadata": {},
"source": [
"### TK - 4.3 Creating image patches with `torch.nn.Conv2d()`\n",
"\n",
"It's time to start moving towards replicating the patch embedding layers with PyTorch.\n",
"\n",
"To visualize our single image we wrote code to loop through the different height and width dimensions of a single image and plot individual patches.\n",
"\n",
"This operation is very similar to the convolutional operation we saw in [03. PyTorch Computer Vision section 7.1: Stepping through `nn.Conv2d()`](https://www.learnpytorch.io/03_pytorch_computer_vision/#71-stepping-through-nnconv2d).\n",
"\n",
"In fact, the authors of the ViT paper mention in section 3.1 that the patch embedding is achievable with a convolutional neural network (CNN): \n",
"\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",
"\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",
"*By setting the `kernel_size` and `stride` parameters of a [`torch.nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) layer equal to the `patch_size`, we can effectively get a layer that splits our image into patches and creates a learnable embedding (referred to as a \"Linear Projection\" in the ViT paper) of each patch.* \n",
"\n",
"Remember our ideal input and output shapes for 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",
"Or for an image size of 224 and patch size of 16:\n",
"\n",
"* **Input (2D image):** (224, 224, 3) \n",
"* **Output (flattened 2D patches):** (196, 768)\n",
"\n",
"We can recreate these with:\n",
"* [`torch.nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) for turning our image into patches of CNN feature maps.\n",
"* [`torch.nn.Flatten()`](https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html) for flattening the spatial dimensions of the feature map.\n",
"\n",
"Let's start with the `torch.nn.Conv2d()` layer.\n",
"\n",
"We can replicate the creation of patches by setting the `kernel_size` and `stride` equal to `patch_size`.\n",
"\n",
"This means each convolutional kernel will be of size `(patch_size x patch_size)` or if `patch_size=16`, `(16 x 16)` (the equivalent of one whole patch) \n",
"\n",
"And each step or `stride` of the convolutional kernel will be `patch_size` pixels long or `16` pixels long (equivalent of stepping to the next patch).\n",
"\n",
"We'll set `in_channels=3` for the number of color channels in our image and we'll set `out_channels=768`, the same as the $D$ value in Table 1 for ViT-Base (this is the embedding dimension, each image will be embedded into a vector of size 768)."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "3d4fd046-6b51-4ac0-8d39-e67fb333a18a",
"metadata": {},
"outputs": [],
"source": [
"from torch import nn\n",
"\n",
"# Set the patch size\n",
"patch_size=16\n",
"\n",
"# Create the Conv2d layer with hyperparameters from the ViT paper\n",
"conv2d = nn.Conv2d(in_channels=3, # number of color channels\n",
" out_channels=768, # from Table 1: Hidden size D, this is the embedding size\n",
" kernel_size=patch_size, # could also use (patch_size, patch_size)\n",
" stride=patch_size,\n",
" padding=0)"
]
},
{
"cell_type": "markdown",
"id": "03dec513-eea5-4d13-b7ab-41c9e997ef48",
"metadata": {},
"source": [
"Now we've got a convoluational layer, let's see what happens when we pass a single image through it."
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "1d3424d2-2cfa-431c-9fd0-e2afdf15fc9c",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUg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xVKSaSo17Zxmlzg4XjkdPs+zrXsjETniJ9GWmtIIeBDQEmJ2RjuDz2Hh8Dt+wd8FIzTiesne1wrmA4911dbFKBK4Xq/Q4tCnibmKTKKyPXVhrAVeJ9IPpJCps+Bw8Mto4+E00QDsIHrm5b9pgWjGX3geDpxHCY0Cm0tSjnGeWb0iaebLfvXr/5A+/uOxhnRvPv8OW98/CPsnz7lH/9H/4j7oydhgAxiyRd4PElZTtE1jCoFjNH88A//Ef7Wf+Nv8BM/8ae4vt6h9RJqnU9hUQ15PeHXzVYKKSWGU8/D/QOHuwce7u+Z+qmexFIsPxJrHZvtluvra7rtFm0MpRRi8Ph55nQ6cTqd8ONECnHdfee9JqsbP+eDq+fMKaOkRiuF1urxMYsnrGGmesnwVk8opfoW43zpd1mNWmm1eEeWVFDCOWcvFLGG+kCp134N+ZcbedkLLt9AWQ+/JbwtnFMPkRdPuVyDnPNjKrFcm3pMLeHsOTBavrOS6v3L61dcAVKMpBIZhhMlJXKKHB/uef+9d3nvnbe5e+89+n7geDjihwPbRrJzGSsLqrXIUhCphpNSSbQ1CGVJWeKD5/b2OQ8PR7Kfsa7ByUIJAQvIDAhFLgmrHX0fGI4zcRZcdVcM/YgygZbEx59e8eTmuuIPx577acJqjZYFp0Bqh9tY5pMHAc4IVJchJRhm/DExzx5bJK1xSOVBFbKMpJJAC1zXMY0BqAf4OEf6yaNsg3Itrt1+OON8//kDx3HmJ3/8T/GFL32Z3//6N4lIUinLF3I2y/N2WMOYeoRXD/ID3/99/I2/9q/
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# View single image\n",
"plt.imshow(image.permute(1, 2, 0)) # adjust for matplotlib\n",
"plt.title(class_names[label])\n",
"plt.axis(False);"
]
},
{
"cell_type": "code",
"execution_count": 19,
"id": "a72a5614-f1cb-4c01-9696-24f07bf2a219",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"torch.Size([1, 768, 14, 14])\n"
]
}
],
"source": [
"# Pass the image through the convolutional layer \n",
"image_out_of_conv = conv2d(image.unsqueeze(0)) # add a single batch dimension (height, width, color_channels) -> (batch, height, width, color_channels)\n",
"print(image_out_of_conv.shape)"
]
},
{
"cell_type": "markdown",
"id": "87afeb8f-86cf-4cad-bf88-84dfaccdbe2b",
"metadata": {},
"source": [
"Passing our image through the convolutional layer turns it into a series of 768 (this is the embedding size or $D$) feature/activation maps.\n",
"\n",
"So its output shape can be read as:\n",
" \n",
"```python\n",
"torch.Size([1, 768, 14, 14]) -> [batch_size, embedding_dim, feature_map_height, feature_map_width]\n",
"```\n",
"\n",
"Let's visualize five random feature maps and see what they look like."
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "af5b58ca-0d73-4c62-b4af-4e8867b764e2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Showing random convolutional feature maps from indexes: [180, 39, 286, 72, 105]\n"
]
},
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAAq8AAACFCAYAAAB1yRHkAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAAAZqklEQVR4nO3daXRc533f8f8MMIPBYBkABAiCIMBVIsVd+2aZtFWpsiVHcWLJle04teskx7HixHGWkzpNTnwaO00iJzqx6zW1Y7e2oqZypbiRZOlYC8XIWk2JG2guICCSIPYBBpgZzHbzInZe5f7+AFlU5/Z8P29/w3sf3HnuMw/mEL8bC4LAAAAAgCiIv9kDAAAAABaLzSsAAAAig80rAAAAIoPNKwAAACKDzSsAAAAig80rAAAAIqN+KS9ONDQFDen20Hx936h7jFNnV8m82qD/fcxp9qol3CGY1emDdKTnZd5ep3Mzs3JQJ/PhuRUyT8zE9Amc2MysKt7d8uyUVQrzizjK0iVjDUHKmkLz9Tvn3GN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/PP66rJS3/33SP60Kr7tqr5fPuGNpeGgnN6uZ1n+DFqARxmyiH9799b8jvk8yN6/649KDup+u7Rffgnhpb4Y5hV7fuWN0/qsf42eff6Z7j+s0nZf7s8/paNa2fkXk+7XcyBovobVwusZpZ/Xx4/jMffM49xoOPvUXm6699Q+bjRf0+ZtIFdwyW1vGxbLfMt67Tc83M7Mfnu2ReKOl7YsuKMZk/P6x7YM3M4mmxNi5jB2ysGlhyNrwbc2ad/1HW91uDMi9W9TGazug1ebbmrykpZ9mNz+sO7FFdf21mZrV
"text/plain": [
"<Figure size 864x864 with 5 Axes>"
]
},
"metadata": {},
"output_type": "display_data"
}
],
"source": [
"# Plot random 5 convolutional feature maps\n",
"import random\n",
"random_indexes = random.sample(range(0, 758), k=5) # pick 5 numbers between 0 and the embedding size\n",
"print(f\"Showing random convolutional feature maps from indexes: {random_indexes}\")\n",
"\n",
"# Create plot\n",
"fig, axs = plt.subplots(nrows=1, ncols=5, figsize=(12, 12))\n",
"\n",
"# Plot random image feature maps\n",
"for i, idx in enumerate(random_indexes):\n",
" image_conv_feature_map = image_out_of_conv[:, idx, :, :] # index on the output tensor of the convolutional layer\n",
" axs[i].imshow(image_conv_feature_map.squeeze().detach().numpy())\n",
" axs[i].set(xticklabels=[], yticklabels=[], xticks=[], yticks=[]);"
]
},
{
"cell_type": "markdown",
"id": "b847f2e1-1700-4040-a9aa-df9ab1139cce",
"metadata": {},
"source": [
"Notice how the feature maps all kind of represent the original image, visualizing a few you can see the different major outlines and some major features.\n",
"\n",
"The important thing to note is that these features may change over time as the neural network learns.\n",
"\n",
"And because of these, these feature maps can be considered a **learnable embedding** of our image.\n",
"\n",
"Let's check one out in numerical form."
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "94f6f5b9-a1c7-4aa1-9780-7cd06457b2b3",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[[0.2642, 1.1367, 1.0221, 0.9712, 1.0950, 1.2478, 1.2884, 1.1481,\n",
" 0.9640, 0.6204, 0.5996, 0.5855, 0.5560, 0.4992],\n",
" [1.1578, 1.0633, 0.9593, 1.1931, 1.3194, 1.1306, 0.7317, 0.4322,\n",
" 0.6025, 0.7246, 0.7891, 0.5383, 0.4786, 0.7098],\n",
" [1.0163, 0.9368, 1.1675, 1.3373, 1.0429, 0.7497, 0.7445, 0.4270,\n",
" 0.7430, 0.8750, 0.6105, 0.5147, 1.0207, 0.7852],\n",
" [1.0669, 1.0157, 1.3291, 1.0117, 0.4848, 0.6802, 0.8365, 0.7736,\n",
" 0.8618, 0.9144, 0.8926, 0.9795, 0.7475, 0.7585],\n",
" [0.9371, 1.1937, 1.0068, 0.6377, 0.7283, 0.9625, 1.0372, 0.8920,\n",
" 0.9372, 0.9034, 0.9683, 0.9405, 0.5958, 0.8740],\n",
" [0.9419, 0.8599, 0.5429, 0.6954, 1.0202, 0.9093, 1.0003, 0.7619,\n",
" 0.8472, 0.8062, 0.6418, 0.7741, 0.5791, 0.9816],\n",
" [0.7965, 0.7202, 0.6424, 0.9137, 0.8264, 1.0243, 1.0920, 0.9548,\n",
" 0.9166, 0.7937, 0.4675, 0.5346, 0.7774, 1.1001],\n",
" [0.3298, 0.4832, 0.5324, 0.7486, 0.8303, 0.8101, 0.9969, 0.9931,\n",
" 1.0058, 0.6002, 0.6643, 0.7254, 0.8453, 1.1323],\n",
" [0.5384, 0.4798, 0.6725, 0.8014, 0.7044, 0.7988, 0.8185, 0.8911,\n",
" 0.9720, 0.8939, 0.6234, 0.5674, 0.5775, 1.0011],\n",
" [0.6199, 0.6465, 0.6503, 0.6215, 0.8154, 0.7950, 0.8647, 0.9872,\n",
" 0.8513, 0.8833, 0.5799, 0.5914, 0.6936, 1.0554],\n",
" [0.5140, 0.6462, 0.6982, 0.7445, 0.7394, 0.8124, 0.7462, 0.9183,\n",
" 0.7471, 0.9436, 0.7147, 0.6396, 0.5795, 1.0201],\n",
" [0.5467, 0.7408, 0.6854, 0.6624, 0.7465, 0.5077, 0.7633, 0.8709,\n",
" 1.0026, 0.7276, 0.7847, 0.5811, 0.5521, 1.0318],\n",
" [0.8041, 0.8868, 0.5559, 0.5889, 0.7236, 0.6976, 0.7940, 0.9365,\n",
" 0.9110, 0.8182, 0.7013, 0.4890, 0.8364, 1.0031],\n",
" [0.1976, 1.0262, 1.1979, 0.9982, 0.9644, 0.8868, 0.9556, 1.0204,\n",
" 1.0060, 0.9586, 0.9351, 0.8819, 0.9290, 0.9289]]],\n",
" grad_fn=<SliceBackward0>),\n",
" True)"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Get a single feature map in tensor form\n",
"single_feature_map = image_out_of_conv[:, 0, :, :]\n",
"single_feature_map, single_feature_map.requires_grad"
]
},
{
"cell_type": "markdown",
"id": "fc7c08ca-a4ef-4350-b471-088b2f12b80e",
"metadata": {},
"source": [
"The `grad_fn` output of the `single_feature_map` and the `required_grad=True` attribute means PyTorch is tracking the gradients of this feature map and it will be updated by gradient descent during training. "
]
},
{
"cell_type": "markdown",
"id": "572ae1c5-9488-4882-bdc1-409eef95424e",
"metadata": {},
"source": [
"### TK - 4.4 Flattening the patch embedding with `torch.nn.Flatten()`\n",
"\n",
"We've turned our image into patch embeddings but they're still in 2D format.\n",
"\n",
"How do we get them into the desired output shape of the patch embedding layer of the ViT model?\n",
"\n",
"* **Desried output (flattened 2D patches):** (196, 768) -> ${N \\times\\left(P^{2} \\cdot C\\right)}$\n",
"\n",
"Let's check the current shape."
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "c8219029-6162-4046-8702-0c2cb42f2378",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Current tensor shape: torch.Size([1, 768, 14, 14]) -> [batch, embedding_dim, feature_map_height, feature_map_width]\n"
]
}
],
"source": [
"# Current tensor shape\n",
"print(f\"Current tensor shape: {image_out_of_conv.shape} -> [batch, embedding_dim, feature_map_height, feature_map_width]\")"
]
},
{
"cell_type": "markdown",
"id": "0160c70b-0fe8-42f9-b6e9-5cac23e06836",
"metadata": {},
"source": [
"Well we've got the 768 part ( $(P^{2} \\cdot C)$ ) but we still need the number of patches ($N$).\n",
"\n",
"Reading back through section 3.1 of the ViT paper it says (bold mine):\n",
"\n",
"> 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**.\n",
"\n",
"Flattening the spatial dimensions of the feature map hey?\n",
"\n",
"What layer do we have in PyTorch that can flatten?\n",
"\n",
"How about [`torch.nn.Flatten()`](https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html )?\n",
"\n",
"But we don't want to flatten the whole tensor, we only want to flatten the \"spatial dimensions of the feature map\".\n",
"\n",
"Which in our case is the `feature_map_height` and `feature_map_width` dimensions of `image_out_of_conv`.\n",
"\n",
"So how about we create a `torch.nn.Flatten()` layer to only flatten those dimensions, we can use the `start_dim` and `end_dim` parameters to set that up?"
]
},
{
"cell_type": "code",
"execution_count": 23,
"id": "ed82899d-7bbc-49f9-a423-8fa6344b8e99",
"metadata": {},
"outputs": [],
"source": [
"# Create flatten layer\n",
"flatten = nn.Flatten(start_dim=2, # flatten feature_map_height (dimension 2)\n",
" end_dim=3) # flatten feature_map_width (dimension 3)"
]
},
{
"cell_type": "markdown",
"id": "adcf7cfc-2635-4081-9ade-3542f77c47e2",
"metadata": {},
"source": [
"Nice! Now let's put it all together!\n",
"\n",
"We'll:\n",
"1. Take a single image.\n",
"2. Put in through the convolutional layer (`conv2d`) to turn the image into 2D feature maps (patch embeddings).\n",
"3. Flatten the 2D feature map into a single sequence."
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "e3fa363b-1923-4e27-a0b5-980d885fcda2",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Original image shape: torch.Size([3, 224, 224])\n",
"Image feature map shape: torch.Size([1, 768, 14, 14])\n",
"Flattened image feature map shape: torch.Size([1, 768, 196])\n"
]
},
{
"data": {
"image/png": "iV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/ztw/kOYRWcAoSUkRqxVKSaSo17Zxmlzg4XjkdPs+zrXsjETniJ9GWmtIIeBDQEmJ2RjuDz2Hh8Dt+wd8FIzTiesne1wrmA4911dbFKBK4Xq/Q4tCnibmKTKKyPXVhrAVeJ9IPpJCps+Bw8Mto4+E00QDsIHrm5b9pgWjGX3geDpxHCY0Cm0tSjnGeWb0iaebLfvXr/5A+/uOxhnRvPv8OW98/CPsnz7lH/9H/4j7oydhgAxiyRd4PElZTtE1jCoFjNH88A//Ef7Wf+Nv8BM/8ae4vt6h9RJqnU9hUQ15PeHXzVYKKSWGU8/D/QOHuwce7u+Z+qmexFIsPxJrHZvtluvra7rtFm0MpRRi8Ph55nQ6cTqd8ONECnHdfee9JqsbP+eDq+fMKaOkRiuF1urxMYsnrGGmesnwVk8opfoW43zpd1mNWmm1eEeWVFDCOWcvFLGG+kCp134N+ZcbedkLLt9AWQ+/JbwtnFMPkRdPuVyDnPNjKrFcm3pMLeHsOTBavrOS6v3L61dcAVKMpBIZhhMlJXKKHB/uef+9d3nvnbe5e+89+n7geDjihwPbRrJzGSsLqrXIUhCphpNSSbQ1CGVJWeKD5/b2OQ8PR7Kfsa7ByUIJAQvIDAhFLgmrHX0fGI4zcRZcdVcM/YgygZbEx59e8eTmuuIPx577acJqjZYFp0Bqh9tY5pMHAc4IVJchJRhm/DExzx5bJK1xSOVBFbKMpJJAC1zXMY0BqAf4OEf6yaNsg3Itrt1+OON8//kDx3HmJ3/8T/GFL32Z3//6N4lIUinLF3I2y/N2WMOYeoRXD/ID3/99/I2/9q/
"text/plain": [
"<Figure size 432x288 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# 1. View single image\n",
"plt.imshow(image.permute(1, 2, 0)) # adjust for matplotlib\n",
"plt.title(class_names[label])\n",
"plt.axis(False);\n",
"print(f\"Original image shape: {image.shape}\")\n",
"\n",
"# 2. Turn image into feature maps\n",
"image_out_of_conv = conv2d(image.unsqueeze(0)) # add batch dimension to avoid shape errors\n",
"print(f\"Image feature map shape: {image_out_of_conv.shape}\")\n",
"\n",
"# 3. Flatten the feature maps\n",
"image_out_of_conv_flattened = flatten(image_out_of_conv)\n",
"print(f\"Flattened image feature map shape: {image_out_of_conv_flattened.shape}\")"
]
},
{
"cell_type": "markdown",
"id": "fe802095-e944-4607-b3a7-891ba452372b",
"metadata": {},
"source": [
"Woohoo! It looks like our `image_out_of_conv_flattened` shape is very close to our desired output shape: \n",
" \n",
"* **Desried output (flattened 2D patches):** (196, 768) -> ${N \\times\\left(P^{2} \\cdot C\\right)}$\n",
"* **Current shape:** (1, 768, 196)\n",
"\n",
"The only difference is our current shape has a batch size and the dimensions are in a different order to the desired output.\n",
"\n",
"How could we fix this?\n",
"\n",
"Well, how about we rearrange the dimensions?\n",
"\n",
"We can do so with `torch.Tensor.permute()` just like we do when rearranging image tensors to plot them with matplotlib.\n",
"\n",
"Let's try."
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "47f571a1-2303-4981-85f5-33936b39cf14",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Patch embedding sequence shape: torch.Size([1, 196, 768]) -> [batch_size, num_patches, embedding_size]\n"
]
}
],
"source": [
"# Get flattened image patch embeddings in right shape \n",
"image_out_of_conv_flattened_reshaped = image_out_of_conv_flattened.permute(0, 2, 1) # [batch_size, P^2•C, N] -> [batch_size, N, P^2•C]\n",
"print(f\"Patch embedding sequence shape: {image_out_of_conv_flattened_reshaped.shape} -> [batch_size, num_patches, embedding_size]\")"
]
},
{
"cell_type": "markdown",
"id": "224d751a-11a0-4645-a225-cd36e507ebf8",
"metadata": {},
"source": [
"Yes!!!\n",
"\n",
"We've now matched the desired input and output shapes for the patch embedding layer of the ViT architecture using a couple of PyTorch layers.\n",
"\n",
"How about we visualize one of the flattened feature maps?"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "e4204163-8689-4b9e-8828-4e1e20d9316e",
"metadata": {},
"outputs": [
{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V1224CrhE0pTcjrGSju9lvaVx+T3gS7mcMaS18K5tUsZ/AF+RtK+SgyWN7mX9fyDpq5IOyg88aAM+BTzVcBsq+UEL1wOnRVo/sF5lX+TX5A56uK05j8nBpLtF+kkaLGlA3fYFkj5acazysQPz74NzEr62/eAcG6L0oIzxwHfy5nuAhcDf5z54M2nG3k+btHUQ8DrgZ83OyczMzF4aJ9rMzMx2kbxu2NmkhFYHKVHy47rtvyUlMObldd4m8MKtgSsl1dbyOo30Jf3xXM6NpC/jvdHs2KtJX9hnA48AP9jBU/wC8BTwgKS1pITF9LztcmB30syzB4CfNBx7BWmdrA5J38ixTwKfB1YCM4D7dqL+nfVXwEWSOklJpdIstLtz/f8LfD2v81ZyKrAgt/Es0oMX+roNV5DG2u35+AdIC+sDIOkxSSeXKq0YlxeTbmucQ7r1+ZEcq/Ivub23k5KLM0njoSlJb5W0ri40BPgh6TbIeaRZdccVDn0HaQbkjXrhyaO1p3w27Qvg39h+vbmSU0mJ42+T1ljsIl0/tSeXjs7llkzJ+9fa00V6eEl92UtJa7W9A3hnXkuulgg8nvRQiTW5ztPya1TlOGBWpIdYmJmZWYspojT738zMzMxeCklTgfnAgIb11V5VbXglkfQL4K8j4lFJV5MeKrEsInq8/VXSW4BPR0TVwzD6jKTzSU94HQQMjYitkh4ETo+I37zc7TEzM3s1cKLNzMzMrIX+GJJcfwxtMDMzM3s18q2jZmZmZmZmZmZmLeAZbWZmZmZmZmZmZi3gGW1mZmZmZmZmZmYt4ESbmZmZmZmZmZlZC+zWbON7xp1VvK/0yFkLKo+5f9VrivHlG9qK8Te
"text/plain": [
"<Figure size 1584x1584 with 1 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Get a single flattened feature map\n",
"single_flattened_feature_map = image_out_of_conv_flattened_reshaped[:, :, 0]\n",
"\n",
"# Plot the flattened feature map visually\n",
"plt.figure(figsize=(22, 22))\n",
"plt.imshow(single_flattened_feature_map.detach().numpy())\n",
"plt.title(f\"Flattened feature map shape: {single_flattened_feature_map.shape}\")\n",
"plt.axis(False);"
]
},
{
"cell_type": "markdown",
"id": "2fe6c0a6-687c-473c-a30f-6b01b1df533f",
"metadata": {},
"source": [
"Hmm, the flattened feature map doesn't look like much visually, but that's not what we're concerned about, this is what will be the output of the patching embedding layer and the input to the rest of the ViT architecture.\n",
"\n",
"TK image - single image -> conv2d -> flatten -> get the output above (show the workflow and transformation, this could be the gif we've but using but extended to work with the flatten section)\n",
"\n",
"> **Note:** The [original Transformer architecture](https://arxiv.org/abs/1706.03762) was designed to work with text. The Vision Transformer architecture (ViT) had the goal of using the original Transformer for images. This is why the input to the ViT architecture is processed in the way it is. We're essentially taking a 2D image and formatting it so it appears as a 1D sequence of text. \n",
"\n",
"How about we view the flattened feature map in tensor form?"
]
},
{
"cell_type": "code",
"execution_count": 27,
"id": "0cdeb08e-948d-4810-ae8d-c607b3b9feec",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[0.2642, 1.1367, 1.0221, 0.9712, 1.0950, 1.2478, 1.2884, 1.1481, 0.9640,\n",
" 0.6204, 0.5996, 0.5855, 0.5560, 0.4992, 1.1578, 1.0633, 0.9593, 1.1931,\n",
" 1.3194, 1.1306, 0.7317, 0.4322, 0.6025, 0.7246, 0.7891, 0.5383, 0.4786,\n",
" 0.7098, 1.0163, 0.9368, 1.1675, 1.3373, 1.0429, 0.7497, 0.7445, 0.4270,\n",
" 0.7430, 0.8750, 0.6105, 0.5147, 1.0207, 0.7852, 1.0669, 1.0157, 1.3291,\n",
" 1.0117, 0.4848, 0.6802, 0.8365, 0.7736, 0.8618, 0.9144, 0.8926, 0.9795,\n",
" 0.7475, 0.7585, 0.9371, 1.1937, 1.0068, 0.6377, 0.7283, 0.9625, 1.0372,\n",
" 0.8920, 0.9372, 0.9034, 0.9683, 0.9405, 0.5958, 0.8740, 0.9419, 0.8599,\n",
" 0.5429, 0.6954, 1.0202, 0.9093, 1.0003, 0.7619, 0.8472, 0.8062, 0.6418,\n",
" 0.7741, 0.5791, 0.9816, 0.7965, 0.7202, 0.6424, 0.9137, 0.8264, 1.0243,\n",
" 1.0920, 0.9548, 0.9166, 0.7937, 0.4675, 0.5346, 0.7774, 1.1001, 0.3298,\n",
" 0.4832, 0.5324, 0.7486, 0.8303, 0.8101, 0.9969, 0.9931, 1.0058, 0.6002,\n",
" 0.6643, 0.7254, 0.8453, 1.1323, 0.5384, 0.4798, 0.6725, 0.8014, 0.7044,\n",
" 0.7988, 0.8185, 0.8911, 0.9720, 0.8939, 0.6234, 0.5674, 0.5775, 1.0011,\n",
" 0.6199, 0.6465, 0.6503, 0.6215, 0.8154, 0.7950, 0.8647, 0.9872, 0.8513,\n",
" 0.8833, 0.5799, 0.5914, 0.6936, 1.0554, 0.5140, 0.6462, 0.6982, 0.7445,\n",
" 0.7394, 0.8124, 0.7462, 0.9183, 0.7471, 0.9436, 0.7147, 0.6396, 0.5795,\n",
" 1.0201, 0.5467, 0.7408, 0.6854, 0.6624, 0.7465, 0.5077, 0.7633, 0.8709,\n",
" 1.0026, 0.7276, 0.7847, 0.5811, 0.5521, 1.0318, 0.8041, 0.8868, 0.5559,\n",
" 0.5889, 0.7236, 0.6976, 0.7940, 0.9365, 0.9110, 0.8182, 0.7013, 0.4890,\n",
" 0.8364, 1.0031, 0.1976, 1.0262, 1.1979, 0.9982, 0.9644, 0.8868, 0.9556,\n",
" 1.0204, 1.0060, 0.9586, 0.9351, 0.8819, 0.9290, 0.9289]],\n",
" grad_fn=<SelectBackward0>),\n",
" True,\n",
" torch.Size([1, 196]))"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# See the flattened feature map as a tensor\n",
"single_flattened_feature_map, single_flattened_feature_map.requires_grad, single_flattened_feature_map.shape"
]
},
{
"cell_type": "markdown",
"id": "6cc9dae5-5bf2-45b4-8266-cf733868441d",
"metadata": {},
"source": [
"Beautiful!\n",
"\n",
"We've turned our single 2D image into a single 1D learnable embedding vector (or \"Linear Projection of Flattned Patches\" in Figure 1 of the ViT paper)."
]
},
{
"cell_type": "markdown",
"id": "b165987a-8370-471a-a663-711e0c6e60db",
"metadata": {},
"source": [
"### TK - 4.5 Turning the ViT patch embedding layer into a PyTorch module\n",
"\n",
"Time to put everything we've done for creating the patch embedding into a single PyTorch layer.\n",
"\n",
"We can do so by subclassing `nn.Module` and creating a small PyTorch \"model\" to do all of the steps above.\n",
"\n",
"Specifically we'll:\n",
"1. Create a class called `PatchEmbedding` which subclasses `nn.Module` (so it can be used a PyTorch layer).\n",
"2. Initialize the class with the parameters `in_channels=3`, `patch_size=16` (for ViT-Base) and `embedding_dim=768` (this is $D$ for ViT-Base from Table 1).\n",
"3. Create a layer to turn an image into patches using `nn.Conv2d()` (just like in 4.3 above).\n",
"4. Create a layer to flatten the patch feature maps into a single dimension (just like in 4.4 above). \n",
"5. Define a `forward()` method to take an input and pass it through the layers created in 3 and 4.\n",
"6. Make sure the output shape reflects the required output shape of the ViT architecture (${N \\times\\left(P^{2} \\cdot C\\right)}$).\n",
"\n",
"Let's do it!"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 28,
"id": "3ef75c7e",
"metadata": {},
"outputs": [],
"source": [
"# 1. Create a class which subclasses nn.Module\n",
"class PatchEmbedding(nn.Module):\n",
" \"\"\"Turns a 2D input image into a 1D sequence learnable embedding vector.\n",
" \n",
" Args:\n",
" in_channels (int): Number of color channels for the input images. Defaults to 3.\n",
" patch_size (int): Size of patches to convert input image into. Defaults to 16.\n",
" embedding_dim (int): Size of embedding to turn image into. Defaults to 768.\n",
" \"\"\" \n",
" # 2. Initialize the class with appropriate variables\n",
" def __init__(self, \n",
" in_channels:int=3,\n",
" patch_size:int=16,\n",
" embedding_dim:int=768):\n",
" super().__init__()\n",
" \n",
" # 3. Create a layer to turn an image into patches\n",
" self.patcher = nn.Conv2d(in_channels=in_channels,\n",
" out_channels=embedding_dim,\n",
" kernel_size=patch_size,\n",
" stride=patch_size,\n",
" padding=0)\n",
"\n",
" # 4. Create a layer to flatten the patch feature maps into a single dimension\n",
" self.flatten = nn.Flatten(start_dim=2, # only flatten the feature map dimensions into a single vector\n",
" end_dim=3)\n",
"\n",
" # 5. Define the forward method \n",
" 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",
" \n",
" # Perform the forward pass\n",
" x_patched = self.patcher(x)\n",
" x_flattened = self.flatten(x_patched) \n",
" # 6. Make sure the output shape has the right order \n",
" return x_flattened.permute(0, 2, 1) # adjust so the embedding is on the final dimension [batch_size, P^2•C, N] -> [batch_size, N, P^2•C]"
]
},
{
"cell_type": "markdown",
"id": "5270aa24-85b7-4b5a-a799-8e5eeca47f8f",
"metadata": {},
"source": [
"`PatchEmbedding` layer created!\n",
"\n",
"Let's try it out on a single image."
]
},
{
"cell_type": "code",
"execution_count": 29,
"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": [
"set_seeds()\n",
"\n",
"# 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",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-replicating-the-patch-embedding-layer.png\" width=900 alt=\"replicating the vision transformer architecture patch embedding layer\"/>\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": 30,
"id": "e440be53-d72c-42b8-87c8-1c31c4262c16",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2022-07-22 14:06:23 +10:00
"========================================================================================================================\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",
"========================================================================================================================"
2022-07-04 16:38:17 +10:00
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# 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",
"Okay we've made the image patch embedding, time to get to work on the class token embedding.\n",
"\n",
"Or $\\mathbf{x}_\\text {class }$ from equation 1.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-the-class-token.png\" width=900 alt=\"class token embedding highlight from the vision transformer paper figure 1 and section 3.1\"/>\n",
"\n",
"*Left: Figure 1 from the ViT paper with the \"classification token\" or `[class]` embedding token we're going to recreate highlighted. Right: Equation 1 and section 3.1 of the ViT paper that relate to the learnable class embedding token.*\n",
"\n",
"Reading the second paragraph of section 3.1 from the ViT paper, we see the following description: \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). \n",
"\n",
"> **Note:** [BERT](https://arxiv.org/abs/1810.04805) (Bidirectional Encoder Representations from Transformers) is one of the original machine learning research papers to use the Transformer architecture to achieve outstanding results on natural language processing (NLP) tasks and is where the idea of having a `[ class ]` token at the start of a sequence originated, class being a description for the \"classification\" class the sequence belonged to.\n",
"\n",
"So we need to \"preprend a learnable embedding to the sequence of embedded patches\".\n",
"\n",
"Let's start by viewing our sequence of embedded patches tensor (created in 4.5) and its shape."
]
},
{
"cell_type": "code",
"execution_count": 31,
"id": "50381789-d73d-4648-9144-4d48da87318f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[[-0.4923, 0.0265, -0.0909, ..., 0.1478, -0.0986, 0.2243],\n",
" [-0.9849, 0.3805, -0.3638, ..., 0.6115, -0.0805, 0.2097],\n",
" [-0.6015, 0.1235, -0.2506, ..., 0.6307, -0.4673, 0.2756],\n",
" ...,\n",
" [-0.6668, 0.1713, -0.1711, ..., 0.4699, -0.2881, 0.2599],\n",
" [-0.6983, 0.1949, -0.1884, ..., 0.5152, -0.3126, 0.2151],\n",
" [-0.6889, 0.1862, -0.1444, ..., 0.5019, -0.3564, 0.2378]]],\n",
" grad_fn=<PermuteBackward0>)\n",
"Patch embedding shape: torch.Size([1, 196, 768]) -> [batch_size, number_of_patches, embedding_dimension]\n"
]
}
],
"source": [
"# View the patch embedding and patch embedding shape\n",
"print(patch_embedded_image) \n",
"print(f\"Patch embedding shape: {patch_embedded_image.shape} -> [batch_size, number_of_patches, embedding_dimension]\")"
]
},
{
"cell_type": "markdown",
"id": "d5e417fc-70c9-43d4-a294-e7728a24bf42",
"metadata": {},
"source": [
"To \"prepend a learnable embedding to the sequence of embedded patches\" we need to create a learnable embedding in the shape of the `embedding_dimension` ($D$) and then add it to the `number_of_patches` dimension. \n",
"\n",
"Or in pseudocode:\n",
"\n",
"```python\n",
"patch_embedding = [image_patch_1, image_patch_2, image_patch_3...]\n",
"class_token = learnable_embedding\n",
"patch_embedding_with_class_token = torch.cat((class_token, patch_embedding), dim=1)\n",
"```\n",
"\n",
"Notice the concatenation (`torch.cat()`) happens on `dim=1` (the `number_of_patches` dimension).\n",
"\n",
"Let's create a learnable embedding for the class token.\n",
"\n",
"To do so, we'll get the batch size and embedding dimension shape and then we'll create a `torch.ones()` tensor in the shape `[batch_size, 1, embedding_dimension]`.\n",
"\n",
"And we'll make the tensor learnable by passing it to `nn.Parameter()` with `requires_grad=True`."
]
},
{
"cell_type": "code",
"execution_count": 32,
"id": "cc0bb859-e62e-41a8-9a47-339e4272a152",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]], grad_fn=<SliceBackward0>)\n",
"Class token shape: torch.Size([1, 1, 768]) -> [batch_size, number_of_tokens, embedding_dimension]\n"
]
}
],
"source": [
"# Get the batch size and embedding dimension\n",
"batch_size = patch_embedded_image.shape[0]\n",
"embedding_dimension = patch_embedded_image.shape[-1]\n",
"\n",
"# Create the class token embedding as a learnable parameter that shares the same size as the embedding dimension (D)\n",
"class_token = nn.Parameter(torch.ones(batch_size, 1, embedding_dimension), # [batch_size, number_of_patches, embedding_dimension]\n",
" requires_grad=True) # make sure the embedding is learnable\n",
"\n",
"# Show the first 10 examples of the class_token\n",
"print(class_token[:, :, :10])\n",
"\n",
"# Print the class_token shape\n",
"print(f\"Class token shape: {class_token.shape} -> [batch_size, number_of_tokens, embedding_dimension]\")"
]
},
{
"cell_type": "markdown",
"id": "f1ce6046-f018-4099-96d1-31dad6fc423b",
"metadata": {},
"source": [
"> **Note:** Here we're only creating the class token embedding as [`torch.ones()`](https://pytorch.org/docs/stable/generated/torch.ones.html) for demonstration purposes, in reality, you'd likely create the class token embedding with [`torch.randn()`](https://pytorch.org/docs/stable/generated/torch.randn.html) (start with a random number). \n",
"\n",
"See how the `number_of_patches` dimension of `class_token` is `1` since we only want to prepend one class token value to the start of the patch embedding sequence.\n",
"\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 so using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) and set `dim=1` (so `class_token`'s `number_of_patches` dimension is preprended to `patch_embedded_image`'s `number_of_patches` dimension)."
]
},
{
"cell_type": "code",
"execution_count": 33,
"id": "a7287b01-76cb-4371-ab07-981f7bbf2be5",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[[ 1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n",
" [-0.4923, 0.0265, -0.0909, ..., 0.1478, -0.0986, 0.2243],\n",
" [-0.9849, 0.3805, -0.3638, ..., 0.6115, -0.0805, 0.2097],\n",
" ...,\n",
" [-0.6668, 0.1713, -0.1711, ..., 0.4699, -0.2881, 0.2599],\n",
" [-0.6983, 0.1949, -0.1884, ..., 0.5152, -0.3126, 0.2151],\n",
" [-0.6889, 0.1862, -0.1444, ..., 0.5019, -0.3564, 0.2378]]],\n",
" grad_fn=<CatBackward0>)\n",
"Sequence of patch embeddings with class token prepended shape: torch.Size([1, 197, 768]) -> [batch_size, number_of_patches, embedding_dimension]\n"
]
}
],
"source": [
"# Add the class token embedding to the front of the patch embedding\n",
"patch_embedded_image_with_class_embedding = torch.cat((class_token, patch_embedded_image), \n",
" dim=1) # concat on first dimension\n",
"\n",
"# Print the sequence of patch embeddings with the prepended class token embedding\n",
"print(patch_embedded_image_with_class_embedding)\n",
"print(f\"Sequence of patch embeddings with class token prepended shape: {patch_embedded_image_with_class_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]\")"
]
},
{
"cell_type": "markdown",
"id": "79fd9252-c15e-40a6-965a-a872e0e09cab",
"metadata": {},
"source": [
"Nice! Learnable class token prepended!\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-prepending-the-learnable-class-token.png\" width=900 alt=\"going from a sequence of patch embeddings, creating a learnable class token and then prepending it to the patch embeddings\"/>\n",
"\n",
"*Reviewing what we've done to create the learnable class token, we start with a sequence of image patch embeddings created by `PatchEmbedding()` on single image, we then created a learnable class token with one value for each of the embedding dimensions and then prepended it to the original sequence of patch embeddings. Note: Using `torch.ones()` to create the learnable class token is mostly for demonstration purposes only, in practice, you'd like create it with `torch.randn()`.* "
]
},
{
"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",
"Or $\\mathbf{E}_{\\text {pos }}$ from equation 1 where $E$ stands for \"embedding\".\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-the-position-embeddings.png\" width=900 alt=\"extracting the position embeddings from the vision transformer architecture and comparing them to other sections of the vision transformer paper\"/>\n",
"\n",
"*Left: Figure 1 from the ViT paper with the position embedding we're going to recreate highlighted. Right: Equation 1 and section 3.1 of the ViT paper that relate to the position embedding.*\n",
"\n",
"Let's find out more by reading section 3.1 of the ViT paper (bold mine):\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",
"\n",
"To start creating the position embeddings, let's view our current embeddings. "
]
},
{
"cell_type": "code",
"execution_count": 34,
"id": "33e5e5bf-e744-4249-ac9b-08986be5ef81",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(tensor([[[ 1.0000, 1.0000, 1.0000, ..., 1.0000, 1.0000, 1.0000],\n",
" [-0.4923, 0.0265, -0.0909, ..., 0.1478, -0.0986, 0.2243],\n",
" [-0.9849, 0.3805, -0.3638, ..., 0.6115, -0.0805, 0.2097],\n",
" ...,\n",
" [-0.6668, 0.1713, -0.1711, ..., 0.4699, -0.2881, 0.2599],\n",
" [-0.6983, 0.1949, -0.1884, ..., 0.5152, -0.3126, 0.2151],\n",
" [-0.6889, 0.1862, -0.1444, ..., 0.5019, -0.3564, 0.2378]]],\n",
" grad_fn=<CatBackward0>),\n",
" torch.Size([1, 197, 768]))"
]
},
"execution_count": 34,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# View the sequence of patch embeddings with the prepended class embedding\n",
"patch_embedded_image_with_class_embedding, patch_embedded_image_with_class_embedding.shape"
]
},
{
"cell_type": "markdown",
"id": "ecd1d068-7cac-46b7-aa43-ea8f01ffed4a",
"metadata": {},
"source": [
"Equation 1 states that the position embeddings should have the shape $(N + 1) \\times D$ where: \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",
"* $D$ is the size of the **patch embeddings**, different values for $D$ can be found in Table 1.\n",
"\n",
"Luckily we've got both of these values already.\n",
"\n",
"So let's make a learnable 1D embedding with `torch.ones()` to create $\\mathbf{E}_{\\text {pos }}$. "
]
},
{
"cell_type": "code",
"execution_count": 35,
"id": "5bb7f6d1-0824-47eb-a059-6854da5c7433",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[[1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],\n",
" [1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]]], grad_fn=<SliceBackward0>)\n",
"Position embeddding shape: torch.Size([1, 197, 768]) -> [batch_size, number_of_patches, embedding_dimension]\n"
]
}
],
"source": [
"# Calculate N (number of patches)\n",
"number_of_patches = int((height * width) / patch_size**2)\n",
"\n",
"# Get embedding dimension\n",
"embedding_dimension = patch_embedded_image_with_class_embedding.shape[2]\n",
"\n",
"# Create the learnable 1D position embedding\n",
"position_embedding = nn.Parameter(torch.ones(1,\n",
" number_of_patches+1, \n",
" embedding_dimension),\n",
" requires_grad=True) # make sure it's learnable\n",
"\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]\")"
]
},
{
"cell_type": "markdown",
"id": "332facb6-b478-4910-b620-c06d1462d8b8",
"metadata": {},
"source": [
"> **Note:** Only creating the position embedding as `torch.ones()` for demonstration purposes, in reality, you'd likely create the position embedding with `torch.randn()` (start with a random number and improve via gradient descent). \n",
"\n",
"Position embeddings created!\n",
"\n",
"Let's add them to our sequence of patch embeddings with a prepended class token."
]
},
{
"cell_type": "code",
"execution_count": 36,
"id": "03370370-e2c2-4e46-bc20-302b97fba9d7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"tensor([[[2.0000, 2.0000, 2.0000, ..., 2.0000, 2.0000, 2.0000],\n",
" [0.5077, 1.0265, 0.9091, ..., 1.1478, 0.9014, 1.2243],\n",
" [0.0151, 1.3805, 0.6362, ..., 1.6115, 0.9195, 1.2097],\n",
" ...,\n",
" [0.3332, 1.1713, 0.8289, ..., 1.4699, 0.7119, 1.2599],\n",
" [0.3017, 1.1949, 0.8116, ..., 1.5152, 0.6874, 1.2151],\n",
" [0.3111, 1.1862, 0.8556, ..., 1.5019, 0.6436, 1.2378]]],\n",
" grad_fn=<AddBackward0>)\n",
"Patch embeddings, class token prepended and positional embeddings added shape: torch.Size([1, 197, 768]) -> [batch_size, number_of_patches, embedding_dimension]\n"
]
}
],
"source": [
"# Add the position embedding to the patch and class token embedding\n",
"patch_and_position_embedding = patch_embedded_image_with_class_embedding + position_embedding\n",
"print(patch_and_position_embedding)\n",
"print(f\"Patch embeddings, class token prepended and positional embeddings added shape: {patch_and_position_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]\")"
]
},
{
"cell_type": "markdown",
"id": "80a39e97-4504-4931-9cec-2569389f3faf",
"metadata": {},
"source": [
"Notice how the values of each of the elements in the embedding tensor increases by 1 (this is because of the position embeddings being created with `torch.ones()`). \n",
"\n",
"> **Note:** We could put both the class token embedding and position embedding into their own layer if we wanted to. But we'll see later on how they can be incorporated into the overall ViT architecture's `forward()` method.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-patch-embeddings-with-learnable-class-token-and-position-embeddings.png\" width=900 alt=\"patch embeddings with learnable class token and position embeddings\"/>\n",
"\n",
"*The workflow we've used for adding the position embeddings to the sequence of patch embeddings and class token. Note: `torch.ones()` only used to create embeddings for illustration purposes, in practice, you'd likely use `torch.randn()` to start with a random number.*"
2022-07-04 16:38:17 +10:00
]
},
{
2022-07-22 14:06:23 +10:00
"cell_type": "markdown",
"id": "6654c7ed-eb94-408b-b435-9b352c84328b",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"### TK 4.8 Putting it all together: from image to embedding\n",
"\n",
"Alright, we've come a long way in terms of turning our input images into an embedding and replicating equation 1 from section 3.1 of the ViT paper:\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{z}_{0} &=\\left[\\mathbf{x}_{\\text {class }} ; \\mathbf{x}_{p}^{1} \\mathbf{E} ; \\mathbf{x}_{p}^{2} \\mathbf{E} ; \\cdots ; \\mathbf{x}_{p}^{N} \\mathbf{E}\\right]+\\mathbf{E}_{\\text {pos }}, & & \\mathbf{E} \\in \\mathbb{R}^{\\left(P^{2} \\cdot C\\right) \\times D}, \\mathbf{E}_{\\text {pos }} \\in \\mathbb{R}^{(N+1) \\times D}\n",
"\\end{aligned}\n",
"$$\n",
"\n",
"Let's now put everything together in a single code cell and go from input image ($x$) to output embedding ${z}_0$.\n",
"\n",
"We can do so by:\n",
"1. Setting the patch size (we'll use `16` as it's widely used throughout the paper and for ViT-Base).\n",
"2. Getting a single image, printing it's shape and storing its height and width.\n",
"3. Adding a batch dimension to the single image so it's compatible with our `PatchEmbedding` layer.\n",
"4. Creating a `PatchEmbedding` layer with a `patch_size=16` and `embedding_dim=768` (from Table 1 for ViT-Base).\n",
"5. Passing the single image through the `PatchEmbedding` layer in 4 to create a sequence of patch embeddings.\n",
"6. Creating a class token embedding like in section 4.6. \n",
"7. Prepending the class token emebdding to the patch embeddings created in step 5.\n",
"8. Creating a position embedding like in section 4.7.\n",
"9. Adding the position embedding to the class token and patch embeddings created in step 7.\n",
"\n",
"We'll also make sure to set the random seeds with `set_seeds()` and print out the shapes of different tensors along the way."
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 37,
"id": "8de90548-e6b0-4123-90ca-a23b0fab52a9",
2022-07-04 16:38:17 +10:00
"metadata": {},
"outputs": [
{
2022-07-22 14:06:23 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
"Image tensor shape: torch.Size([3, 224, 224])\n",
"Input image with batch dimension shape: torch.Size([1, 3, 224, 224])\n",
"Patching embedding shape: torch.Size([1, 196, 768])\n",
"Class token embedding shape: torch.Size([1, 1, 768])\n",
"Patch embedding with class token shape: torch.Size([1, 197, 768])\n",
"Patch and position embedding shape: torch.Size([1, 197, 768])\n"
]
2022-07-04 16:38:17 +10:00
}
],
"source": [
2022-07-22 14:06:23 +10:00
"set_seeds()\n",
"\n",
"# 1. Set patch size\n",
"patch_size = 16\n",
"\n",
"# 2. Print shape of original image tensor and get the image dimensions\n",
"print(f\"Image tensor shape: {image.shape}\")\n",
"height, width = image.shape[1], image.shape[2]\n",
"\n",
"# 3. Get image tensor and add batch dimension\n",
"x = image.unsqueeze(0)\n",
"print(f\"Input image with batch dimension shape: {x.shape}\")\n",
"\n",
"# 4. Create patch embedding layer\n",
"patch_embedding_layer = PatchEmbedding(in_channels=3,\n",
" patch_size=patch_size,\n",
" embedding_dim=768)\n",
"\n",
"# 5. Pass image through patch embedding layer\n",
"patch_embedding = patch_embedding_layer(x)\n",
"print(f\"Patching embedding shape: {patch_embedding.shape}\")\n",
"\n",
"# 6. Create class token embedding\n",
"batch_size = patch_embedding.shape[0]\n",
"embedding_dimension = patch_embedding.shape[-1]\n",
"class_token = nn.Parameter(torch.ones(batch_size, 1, embedding_dimension),\n",
" requires_grad=True) # make sure it's learnable\n",
"print(f\"Class token embedding shape: {class_token.shape}\")\n",
"\n",
"# 7. Prepend class token embedding to patch embedding\n",
"patch_embedding_class_token = torch.cat((class_token, patch_embedding), dim=1)\n",
"print(f\"Patch embedding with class token shape: {patch_embedding_class_token.shape}\")\n",
"\n",
"# 8. Create position embedding\n",
"number_of_patches = int((height * width) / patch_size**2)\n",
"position_embedding = nn.Parameter(torch.ones(1, number_of_patches+1, embedding_dimension),\n",
" requires_grad=True) # make sure it's learnable\n",
"\n",
"# 9. Add position embedding to patch embedding with class token\n",
"patch_and_position_embedding = patch_embedding_class_token + position_embedding\n",
"print(f\"Patch and position embedding shape: {patch_and_position_embedding.shape}\")"
2022-07-04 16:38:17 +10:00
]
},
{
2022-07-22 14:06:23 +10:00
"cell_type": "markdown",
"id": "129b4a2b-0a24-461f-a437-ad49925576c4",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"Woohoo!\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"From a single image to patch and position embeddings in a single cell of code.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-putting-it-all-together.png\" width=900 alt=\"mapping equation 1 from the vision transformer paper to pytorch code\"/> \n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"*Mapping equation 1 from the ViT paper to our PyTorch code. This is the essence of paper replicating, taking a research paper and turning it into usable code.* \n",
"\n",
"Now we've got a way to encode our images and pass them to the Transformer Encoder in Figure 1 of the ViT paper.\n",
"\n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-architecture-animation-full-architecture.gif\" alt=\"Vision transformer architecture animation, going from a single image and passing it through a patch embedidng layer and then passing it through the transformer encoder.\" width=900/>\n",
"\n",
"*Animating the entire ViT workflow: from patch embeddings to transformer encoder to MLP head.* \n",
"\n",
"From a code perspective, creating the patch embedding is probably the largest section of replicating the ViT paper.\n",
"\n",
"Many of the other parts of the ViT paper such as the Multi-Head Attention and Norm layers can be created using existing PyTorch layers.\n",
"\n",
"Onwards!"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "markdown",
2022-07-22 14:06:23 +10:00
"id": "02f725de-64d1-41d2-a9d6-374cf6d4f589",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"## TK. 5. Equation 2: Multi-Head Attention (MSA)\n",
"\n",
"We've got our input data patchified and embedded, now let's move onto the next part of the ViT architecture.\n",
"\n",
"To start, we'll break down the Transformer Encoder section into two parts (start small and increase when necessary).\n",
"\n",
"The first being equation 2 and the second being equation 3.\n",
"\n",
"Recall equation 2 states:\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{z}_{\\ell}^{\\prime} &=\\operatorname{MSA}\\left(\\operatorname{LN}\\left(\\mathbf{z}_{\\ell-1}\\right)\\right)+\\mathbf{z}_{\\ell-1}, & & \\ell=1 \\ldots L\n",
"\\end{aligned}\n",
"$$\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"This indicates a Multi-Head Attention (MSA) layer wrapped in a LayerNorm (LN) layer with a residual connection (the input to the layer gets added to the output).\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-2-msa-block-mapped-to-equation.png\" alt=\"mapping equation 2 from the ViT paper to the ViT architecture diagram in figure 1\" width=900/> \n",
"\n",
"*Left: Figure 1 from the ViT paper with Multi-Head Attention and Norm layers as well as the residual connection (+) highlighted within the Transformer Encoder block. Right: Mapping the Multi-Head Self Attention (MSA) layer, Norm layer and residual connection to their respective parts of equation 2 in the ViT paper.*\n",
"\n",
"Many layers you find in research papers are already implemented in modern deep learning frameworks such as PyTorch.\n",
"\n",
"In saying this, to replicate these layers and residual connection with PyTorch code we can use:\n",
"* Multi-Head Self Attention (MSA) - [`torch.nn.MultiheadAttention()`](https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html). \n",
"* Norm (LN or LayerNorm) - [`torch.nn.LayerNorm()`](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html).\n",
"* Residual connection - add the input to output (we'll see this later on when we create the full Transformer Encoder block). "
2022-07-04 16:38:17 +10:00
]
},
{
2022-07-22 14:06:23 +10:00
"cell_type": "markdown",
"id": "97430d7a-a69b-423c-be2b-ac16e7f9f83f",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"### 5.1 The LayerNorm (LN) layer\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"[Layer Normalization](https://paperswithcode.com/method/layer-normalization) (`torch.nn.LayerNorm()` or Norm or LayerNorm or LN) normalizes an input over the last dimension.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"You can set `normalized_shape` to be equal to the dimension size you'd like to noramlize over (in our case it'll be $D$ or `768` for ViT-Base).\n",
"\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",
"What does it do?\n",
"\n",
"Layer Normalization helps improve training time and model generalization (ability to adapt to unseen data).\n",
"\n",
"I like to think of any kind of normalization as \"getting the data into a similar format\" or \"getting data samples into a similar distribution\".\n",
"\n",
"Imagine trying to walk up (or down) a set of stairs all with differing heights and lengths.\n",
"\n",
"It'd take some adjustment each step right?\n",
"\n",
"And what you learn for each step wouldn't necessary help with the next one since they all differ.\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",
"So just like you can walk up (or down) stairs with similar heights and lengths much easier than those with unequal heights and widths, neural networks can optimize over data samples with similar distributions (similar mean and standard-deviations) easier than those with varying distributions. "
2022-07-04 16:38:17 +10:00
]
},
{
2022-07-22 14:06:23 +10:00
"cell_type": "markdown",
"id": "cf09f6d0-2480-4577-a694-1171898e1777",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"### 5.2 The Multi-Head Self Attention (MSA) layer \n",
"\n",
"The power of the self-attention and multi-head attention (self-attention applied multiple times) were revealed in the form of the original Transformer architecture introduced in the [*Attention is all you need*](https://arxiv.org/abs/1706.03762) research paper.\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",
"\n",
"But 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",
"\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",
"*Left: Vision Transformer architecture overview from Figure 1 of the ViT paper. Right: Definitions of equation 2, section 3.1 and Appendix A of the ViT paper highlighted to reflect their respective parts in Figure 1.*\n",
"\n",
"The image above highlights the triple input to the MSA layer.\n",
"\n",
"This is known as **query, key, value** input or **qkv** for short which is fundamental to the self-attention mechanism.\n",
"\n",
"In our case, the triple input will be three versions of the output of the Norm layer.\n",
"\n",
"Or three versions of our layer-normalized image patch and position embeddings created in section 4.8.\n",
"\n",
"We can implement the MSA layer in PyTorch with `torch.nn.MultiheadAttention()` with the parameters:\n",
"* `embed_dim` - the embedding dimension from Table 1 (Hidden size $D$).\n",
"* `num_heads` - how many attention heads to use (this is where the term \"multihead\" comes from), this value is also in Table 1 (Heads).\n",
"* `dropout` - whether or not to apply dropout to the attention layer (according to Appendix B.1, dropout isn't used after the qkv-projections). "
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "markdown",
2022-07-22 14:06:23 +10:00
"id": "b1a012fa-9bf6-4cf2-bbd0-30ed692f9d74",
2022-07-04 16:38:17 +10:00
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"### 5.3 Replicating Equation 2 with PyTorch layers\n",
"\n",
"Let's put everything we've discussed about the LayerNorm (LN) and Multi-Head Attention (MSA) layers in equation 2 into practice.\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"To do so, we'll: \n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"1. Create a class called `MultiheadSelfAttentionBlock()` that inherits from `torch.nn.Module`.\n",
"2. Initialize the class with hyperparameters from Table 1 of the ViT paper for the ViT-Base model.\n",
"3. Create a layer normalization (LN) layer with `torch.nn.LayerNorm()` with the `normalized_shape` parameter the same as our embedding dimension ($D$ from Table 1).\n",
"4. Create a multi-head attention (MSA) layer with the appropriate `embed_dim`, `num_heads`, `dropout` and `batch_first` parameters.\n",
"5. Create a `forward()` method for our class passing the in the inputs through the LN layer and MSA layer."
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 38,
2022-07-04 16:38:17 +10:00
"id": "b76ae98c",
"metadata": {},
"outputs": [],
"source": [
2022-07-22 14:06:23 +10:00
"# 1. Create a class that inherits from nn.Module\n",
2022-07-04 16:38:17 +10:00
"class MultiheadSelfAttentionBlock(nn.Module):\n",
2022-07-22 14:06:23 +10:00
" \"\"\"Creates a multi-head self-attention block (\"MSA block\" for short).\n",
2022-07-04 16:38:17 +10:00
" \"\"\"\n",
2022-07-22 14:06:23 +10:00
" # 2. Initialize the class with hyperparameters from Table 1\n",
2022-07-04 16:38:17 +10:00
" def __init__(self,\n",
2022-07-22 14:06:23 +10:00
" embedding_dim:int=768, # from Table 1 for ViT-Base\n",
" num_heads:int=12, # from Table 1 for ViT-Base\n",
" attn_dropout:int=0): # doesn't look like the paper uses any dropout in MSABlocks\n",
2022-07-04 16:38:17 +10:00
" super().__init__()\n",
2022-07-22 14:06:23 +10:00
" \n",
" # 3. Create the Norm layer (LN)\n",
" self.layer_norm = nn.LayerNorm(normalized_shape=embedding_dim)\n",
" \n",
" # 4. Create the Multi-Head Attention (MSA) layer\n",
2022-07-04 16:38:17 +10:00
" self.multihead_attn = nn.MultiheadAttention(embed_dim=embedding_dim,\n",
" num_heads=num_heads,\n",
" dropout=attn_dropout,\n",
2022-07-22 14:06:23 +10:00
" batch_first=True) # does our batch dimension come first?\n",
" \n",
" # 5. Create a forward() method to pass the data throguh the layers\n",
2022-07-04 16:38:17 +10:00
" def forward(self, x):\n",
2022-07-22 14:06:23 +10:00
" x = self.layer_norm(x)\n",
" attn_output, _ = self.multihead_attn(query=x, # query embeddings \n",
" key=x, # key embeddings\n",
" value=x, # value embeddings\n",
" need_weights=False) # do we need the weights or just the layer outputs?\n",
2022-07-04 16:38:17 +10:00
" return attn_output"
]
},
2022-07-22 14:06:23 +10:00
{
"cell_type": "markdown",
"id": "fc1f0c30-a4ea-41e8-98b2-1a6d8de802d1",
"metadata": {},
"source": [
"> **Note:** Unlike Figure 1, our `MultiheadSelfAttentionBlock()` doesn't include a skip or residual connection (\"$+\\mathbf{z}_{\\ell-1}$\" in equation 2), we'll include this when we create the entire Transformer encoder later on. \n",
"\n",
"MSABlock created! \n",
"\n",
"Let's try it out by create an instance of our `MultiheadSelfAttentionBlock` and passing through the `patch_and_position_embedding` variable we created in section 4.8."
]
},
2022-07-04 16:38:17 +10:00
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 40,
2022-07-04 16:38:17 +10:00
"id": "ceb1dfc0-40ad-4cee-bc54-e9a5cec56895",
"metadata": {},
"outputs": [
{
2022-07-22 14:06:23 +10:00
"name": "stdout",
"output_type": "stream",
"text": [
"Input shape of MSA block: torch.Size([1, 197, 768])\n",
"Output shape MSA block: torch.Size([1, 197, 768])\n"
]
2022-07-04 16:38:17 +10:00
}
],
"source": [
2022-07-22 14:06:23 +10:00
"# Create an instance of MSABlock\n",
"multihead_self_attention_block = MultiheadSelfAttentionBlock(embedding_dim=768, # from Table 1 \n",
" num_heads=12) # from Table 1\n",
"\n",
"# Pass patch and position image embedding through MSABlock\n",
"patched_image_through_msa_block = multihead_self_attention_block(patch_and_position_embedding)\n",
"print(f\"Input shape of MSA block: {patch_and_position_embedding.shape}\")\n",
"print(f\"Output shape MSA block: {patched_image_through_msa_block.shape}\")"
]
},
{
"cell_type": "markdown",
"id": "5c9f8384-6120-495a-b253-baff5de58097",
"metadata": {},
"source": [
"Notice how the input and output shape of our data stays the same when it goes through the MSA block.\n",
"\n",
"This doesn't mean the data doesn't change as it goes through.\n",
"\n",
"You could try printing the input and output tensor to see how it changes (though this change will be across `1 * 197 * 768` values). \n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-2-in-code.png\" width=900 alt=\"vision transformer paper with equation 2 of figure 1 highlighted and equation 2 turned into code\"/>\n",
"\n",
"*Left: Vision Transformer architecture from Figure 1 with Multi-Head Attention and LayerNorm layers highlighted, these layers make up equation 2 from section 3.1 of the paper. Right: Replicating equation 2 (without the skip connection on the end) using PyTorch layers.* \n",
"\n",
"We've now officially replicated equation 2 (except for the residual connection on the end but we'll get to this in section 7)!\n",
"\n",
"Onto the next!"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "markdown",
"id": "0168ef51-ab1f-4ee7-8e9d-2ee7ecca3c7b",
"metadata": {
"tags": []
},
"source": [
2022-07-22 14:06:23 +10:00
"## TK 6. Equation 3: Multilayer Perceptron (MLP)\n",
2022-07-04 16:38:17 +10:00
"\n",
2022-07-22 14:06:23 +10:00
"UPTOHERE:\n",
"* Replicate equation 3 like replicating equation 2\n",
"\n",
"* TK also called \"feedforward\" \n",
"\n",
"> Dropout, when used, is applied **after every dense layer except for the the qkv-projections and directly after adding positional- to patch embeddings.**\n",
2022-07-04 16:38:17 +10:00
"\n",
"> The MLP contains two layers with a GELU non-linearity\n",
"\n",
"$$\n",
"\\begin{aligned}\n",
"\\mathbf{z}_{\\ell} &=\\operatorname{MLP}\\left(\\operatorname{LN}\\left(\\mathbf{z}_{\\ell}^{\\prime}\\right)\\right)+\\mathbf{z}_{\\ell}^{\\prime}, & & \\ell=1 \\ldots L\n",
"\\end{aligned}\n",
2022-07-22 14:06:23 +10:00
"$$ \n",
"\n",
"* TK - GELU in PyTorch -- https://pytorch.org/docs/stable/generated/torch.nn.GELU.html"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 39,
2022-07-04 16:38:17 +10:00
"id": "68d9dbfe",
"metadata": {},
"outputs": [],
"source": [
"# Could also call this \"FeedForward\"\n",
"class MLPBlock(nn.Module):\n",
" \"\"\"Creates an MLPBlock of the Vision Transformer architecture.\"\"\"\n",
" def __init__(self,\n",
" embedding_dim, # embedding dimension (Hidden Size D in Table 1)\n",
" mlp_size, # MLP size in Table 1\n",
" dropout=0): # \"Dropout... is applied to every dense layer... (Appendix B.1)\"\n",
" super().__init__()\n",
" \n",
2022-07-22 14:06:23 +10:00
" self.layer_norm = nn.LayerNorm(normalized_shape=embedding_dim)\n",
" \n",
2022-07-04 16:38:17 +10:00
" self.mlp = nn.Sequential(\n",
" nn.Linear(in_features=embedding_dim,\n",
" out_features=mlp_size),\n",
" nn.GELU(), # \"The MLP contains two layers with a GELU non-linearity (section 3.1).\"\n",
" nn.Dropout(p=dropout),\n",
" nn.Linear(in_features=mlp_size, # needs to take same in_features as out_features of layer above\n",
2022-07-22 14:06:23 +10:00
" out_features=embedding_dim), # take back to embedding_dim\n",
" nn.Dropout(p=dropout)\n",
2022-07-04 16:38:17 +10:00
" )\n",
"\n",
" def forward(self, x):\n",
2022-07-22 14:06:23 +10:00
" x = self.layer_norm(x)\n",
" x = self.mlp(x)\n",
" return x"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 40,
2022-07-04 16:38:17 +10:00
"id": "442fb987",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2022-07-22 14:06:23 +10:00
"torch.Size([1, 197, 768])"
2022-07-04 16:38:17 +10:00
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 40,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"mlp_block = MLPBlock(embedding_dim=768, # Table 1 \n",
" mlp_size=3072) # Table 1\n",
"patched_image_through_mlp_block = mlp_block(patched_image_through_msa_block)\n",
"patched_image_through_mlp_block.shape"
]
},
{
"cell_type": "markdown",
"id": "812ccd0a-554f-4722-9987-f03c079a269f",
"metadata": {},
"source": [
2022-07-22 14:06:23 +10:00
"## TK 7. Create the Transformer Encoder \n",
"\n",
"* Tk - what is an \"encoder\"?\n",
"* Tk - \"transformer block\" or \"transformer encoder\"? - line this up with the paper\n",
"\n",
"See here for pre-built transformer blocks/layers: https://pytorch.org/docs/stable/nn.html#transformer-layers \n"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 41,
2022-07-04 16:38:17 +10:00
"id": "2c43855c",
"metadata": {},
"outputs": [],
"source": [
"class TransformerEncoderBlock(nn.Module):\n",
" \"\"\"Creates a Transformer Encoder block.\"\"\"\n",
" def __init__(self,\n",
" embedding_dim=768, # From Table 1\n",
" num_heads=12, # From Table 1\n",
" mlp_size=3072, # From Table 1\n",
" mlp_dropout=0.1,\n",
" attn_dropout=0):\n",
" super().__init__()\n",
"\n",
" # Create MSA Block (for equation 2)\n",
2022-07-22 14:06:23 +10:00
" self.msa_block = MultiheadSelfAttentionBlock(embedding_dim=embedding_dim,\n",
" num_heads=num_heads,\n",
" attn_dropout=attn_dropout)\n",
2022-07-04 16:38:17 +10:00
" # Create MLP Block (for equation 3)\n",
2022-07-22 14:06:23 +10:00
" self.mlp_block = MLPBlock(embedding_dim=embedding_dim,\n",
" mlp_size=mlp_size,\n",
" dropout=mlp_dropout)\n",
" \n",
2022-07-04 16:38:17 +10:00
" def forward(self, x):\n",
" x = self.msa_block(x) + x # Create skip connection\n",
" x = self.mlp_block(x) + x # Create skip connection\n",
" return x"
]
},
{
"cell_type": "markdown",
"id": "94f9041c-a0af-4fbe-8969-a2bde8637821",
"metadata": {},
"source": [
"## TK 8. Putting it all together to create ViT\n",
2022-07-22 14:06:23 +10:00
" \n",
"TK - replicate this with the TransformerEncoderLayer - https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/\n",
2022-07-04 16:38:17 +10:00
"\n",
"Combine the transformer blocks and patched embedding into a ViT architecture."
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 42,
2022-07-04 16:38:17 +10:00
"id": "2df890d5",
"metadata": {},
"outputs": [],
"source": [
"class ViT(nn.Module):\n",
" \"\"\"Creates a Vision Transformer architecture.\"\"\"\n",
" def __init__(self,\n",
" img_size=224, # From Table 3 in ViT paper\n",
" in_channels=3,\n",
" patch_size=16,\n",
" num_transformer_layers=12, # From Table 1 in ViT paper\n",
" embedding_dim=768,\n",
" mlp_size=3072,\n",
" num_heads=12,\n",
" attn_dropout=0,\n",
" mlp_dropout=0.1,\n",
" embedding_dropout=0.1,\n",
" num_classes=1000): # default for ImageNet\n",
2022-07-22 14:06:23 +10:00
" super().__init__() # don't forget the super().__init__()!\n",
2022-07-04 16:38:17 +10:00
" \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",
" \n",
" # Create class embedding (needs to go at front of sequence embedding)\n",
" self.class_embedding = nn.Parameter(data=torch.randn(1, 1, embedding_dim),\n",
" requires_grad=True)\n",
2022-07-22 14:06:23 +10:00
" \n",
" # Create position embedding\n",
" self.position_embedding = nn.Parameter(data=torch.randn(1, self.num_patches+1, embedding_dim),\n",
" requires_grad=True)\n",
2022-07-04 16:38:17 +10:00
" \n",
" # Create embedding dropout\n",
" self.embedding_dropout = nn.Dropout(p=embedding_dropout)\n",
" \n",
" # 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\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",
" 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",
" def forward(self, x):\n",
" # Get batch size\n",
" batch_size = x.shape[0]\n",
" # Create class token embedding\n",
" class_token = self.class_embedding.expand(batch_size, -1, -1)\n",
"\n",
" # Create patch embedding\n",
" x = self.patch_embedding(x)\n",
"\n",
" # Concat class embedding and patch embedding (equation 1)\n",
" x = torch.cat((class_token, x), dim=1)\n",
"\n",
2022-07-22 14:06:23 +10:00
" # Add position embedding to patch embedding (equation 1) for every batch\n",
2022-07-04 16:38:17 +10:00
" x = self.position_embedding + x\n",
"\n",
" # Run embedding dropout\n",
" x = self.embedding_dropout(x)\n",
"\n",
" # 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",
" x = self.classifier(x[:, 0]) # run on each sample in a batch at 0 index\n",
"\n",
" return x\n",
" "
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 43,
2022-07-04 16:38:17 +10:00
"id": "7dc9f8ec",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"torch.Size([32, 1, 768])"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 43,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"batch_size = 32\n",
"class_tokens = nn.Parameter(data=torch.randn(1, 1, 768))\n",
"class_tokens.expand(batch_size, -1, -1).shape"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 44,
2022-07-04 16:38:17 +10:00
"id": "f86190a3-ed1f-4ab3-881c-4eecea996912",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2022-07-22 14:06:23 +10:00
"tensor([[-0.2377, 0.7360, 1.2137]], grad_fn=<AddmmBackward0>)"
2022-07-04 16:38:17 +10:00
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 44,
2022-07-04 16:38:17 +10:00
"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)"
]
},
{
"cell_type": "markdown",
"id": "2c0a0c9c-6d98-47fd-a152-8a06be99b5fa",
"metadata": {},
"source": [
"## TK 9. Inspect the 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",
"\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`)"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 45,
2022-07-04 16:38:17 +10:00
"id": "494bde26-ed1e-45dc-b615-78ac268ca20e",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
2022-07-22 14:06:23 +10:00
"======================================================================================================================================================\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",
"======================================================================================================================================================\n",
2022-07-04 16:38:17 +10:00
"Total params: 85,800,963\n",
"Trainable params: 85,800,963\n",
"Non-trainable params: 0\n",
"Total mult-adds (G): 22.08\n",
2022-07-22 14:06:23 +10:00
"======================================================================================================================================================\n",
2022-07-04 16:38:17 +10:00
"Input size (MB): 77.07\n",
"Forward/backward pass size (MB): 13168.81\n",
"Params size (MB): 257.55\n",
"Estimated Total Size (MB): 13503.43\n",
2022-07-22 14:06:23 +10:00
"======================================================================================================================================================"
2022-07-04 16:38:17 +10:00
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 45,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"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",
" # col_names=[\"input_size\"], # uncomment for smaller output\n",
" col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n",
" col_width=20,\n",
" row_settings=[\"var_names\"]\n",
")"
]
},
{
"cell_type": "markdown",
"id": "d0279251-5cc1-42a5-bebc-8391ef911343",
"metadata": {},
"source": [
"* 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",
2022-07-22 14:06:23 +10:00
"execution_count": 46,
2022-07-04 16:38:17 +10:00
"id": "3791f963-7d51-418b-b8bd-4c77341560e5",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(torch.Size([1, 1, 768]), torch.Size([32, 1, 768]))"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 46,
2022-07-04 16:38:17 +10:00
"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"
]
},
{
"cell_type": "markdown",
"id": "dd92b752-22f0-4a13-95ac-e085d20013ac",
"metadata": {},
"source": [
"## TK 10. Train model\n",
"\n"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 47,
2022-07-04 16:38:17 +10:00
"id": "9107b068-f253-4026-ad21-83be41404043",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
2022-07-22 14:06:23 +10:00
"model_id": "0632771598bb43e7a49ed5ffa70c4490",
2022-07-04 16:38:17 +10:00
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/10 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-07-22 14:06:23 +10:00
"Epoch: 1 | train_loss: 4.8759 | train_acc: 0.2891 | test_loss: 1.0465 | test_acc: 0.5417\n",
"Epoch: 2 | train_loss: 1.5900 | train_acc: 0.2617 | test_loss: 1.5876 | test_acc: 0.1979\n",
"Epoch: 3 | train_loss: 1.4644 | train_acc: 0.2617 | test_loss: 1.2738 | test_acc: 0.1979\n",
"Epoch: 4 | train_loss: 1.3159 | train_acc: 0.2773 | test_loss: 1.7498 | test_acc: 0.1979\n",
"Epoch: 5 | train_loss: 1.3114 | train_acc: 0.3008 | test_loss: 1.7444 | test_acc: 0.2604\n",
"Epoch: 6 | train_loss: 1.2445 | train_acc: 0.3008 | test_loss: 1.9704 | test_acc: 0.1979\n",
"Epoch: 7 | train_loss: 1.2050 | train_acc: 0.3984 | test_loss: 3.5480 | test_acc: 0.1979\n",
"Epoch: 8 | train_loss: 1.4368 | train_acc: 0.4258 | test_loss: 1.8324 | test_acc: 0.2604\n",
"Epoch: 9 | train_loss: 1.5757 | train_acc: 0.2344 | test_loss: 1.2848 | test_acc: 0.5417\n",
"Epoch: 10 | train_loss: 1.4658 | train_acc: 0.4023 | test_loss: 1.2389 | test_acc: 0.2604\n"
2022-07-04 16:38:17 +10:00
]
}
],
"source": [
"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",
"loss_fn = torch.nn.CrossEntropyLoss()\n",
"\n",
"set_seeds()\n",
"results = engine.train(model=vit,\n",
" train_dataloader=train_dataloader,\n",
" test_dataloader=test_dataloader,\n",
" optimizer=optimizer,\n",
" loss_fn=loss_fn,\n",
" epochs=10,\n",
" device=device)"
]
},
{
"cell_type": "markdown",
"id": "32cb3ad2-6eea-4b69-9ce8-322270643919",
"metadata": {},
"source": [
"## TK 11. Evaluate model\n",
"\n",
"TK - plot the loss curves"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 48,
2022-07-04 16:38:17 +10:00
"id": "fcca1148-6475-4012-bfc9-cbad2706c22d",
"metadata": {},
"outputs": [
{
"data": {
2022-07-22 14:06:23 +10:00
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA2oAAAG5CAYAAAD/HsejAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAACluUl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ymvm3My7e67q7+n1+G3DbAI/bCMwIeYEiIhJz1KiJiPRzoJWvcJk3b94eA6NvvfVWHn/8cQBqamr45JNP9mnUysrKmDlzJgBz5syhqqrqoK+zbt06ysrKOPTQQwH4whe+wO233851111HWloaV111FWeffTbnnOOMBps/fz5XXnkll1xyCZ/5zGeC8CcVERGR/YnaM2od3b18uKWZtq4et0sREQmqzMzMvs9fffVVXnrpJd555x1WrlzJrFmz6Ojo2OcxqampfZ8nJibS03Pw743WDhwsmJSUxJIlS7jwwgt54oknOPPMMwG46667+OUvf0lNTQ0zZ86kvr5+qH80CZfmLVD3sdtViIiMXFuD2xW4JmobtfcqGzjr1jdYvTm4Z0lERMItKyuLlpaWAW9ramrC4/GQkZHB2rVreffdd4P2uocddhhVVVWsX78egH/84x+ceOKJtLa20tTUxFlnncUtt9zCihUrANiwYQPHHHMMv/jFL8jPz6empuYAzy6ueuI/4Ylr3K5CRGRkaivg/ybBjo/crsQVUbv1sdjjHJKvaWhjXlmey9WIiAzf6NGjmT9/PtOmTSM9PZ2xY8f23XbmmWd
2022-07-04 16:38:17 +10:00
"text/plain": [
"<Figure size 1080x504 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"from helper_functions import plot_loss_curves\n",
"\n",
"plot_loss_curves(results)"
]
},
{
"cell_type": "markdown",
"id": "0c370cae-9854-474c-be05-51dabe62c204",
"metadata": {},
"source": [
"TK - why do the loss curves look the way they do? (too big of a model, not enough data)"
]
},
{
"cell_type": "markdown",
"id": "c9bc3d75-028d-4d48-bcfb-d0dd4f53d2ca",
"metadata": {},
"source": [
"## TK 12. Bring in pretrained ViT from `torchvision.models` on same dataset \n",
"\n",
"* Get a similar model from here - https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16 "
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 49,
2022-07-04 16:38:17 +10:00
"id": "30de8333-74b0-49ae-a81e-0266e6325f26",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
2022-07-22 14:06:23 +10:00
"1.12.0+cu102\n",
"0.13.0+cu102\n"
2022-07-04 16:38:17 +10:00
]
}
],
"source": [
"# The following requires torch v0.12+ and torchvision v0.13+\n",
"import torch\n",
"import torchvision\n",
"print(torch.__version__) \n",
"print(torchvision.__version__)"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 50,
2022-07-04 16:38:17 +10:00
"id": "b0b87f68-98cc-49f8-89bd-ff220a757f76",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'cuda'"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 50,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 51,
2022-07-04 16:38:17 +10:00
"id": "29887400-2f92-4c75-961e-0541bea6b73a",
"metadata": {},
"outputs": [],
"source": [
"# Set seeds\n",
"def set_seeds(seed=42):\n",
" torch.manual_seed(seed)\n",
" torch.cuda.manual_seed(seed)"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 52,
2022-07-04 16:38:17 +10:00
"id": "b8e2dda6-8af0-4255-815f-4d885fa4b477",
"metadata": {},
"outputs": [],
"source": [
"# Requires torchvision >= 0.13\n",
"pretrained_vit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT\n",
"pretrained_vit = torchvision.models.vit_b_16(weights=pretrained_vit_weights).to(device)\n",
"\n",
"# Freeze the base parameters\n",
"for parameter in pretrained_vit.parameters():\n",
" parameter.requires_grad = False\n",
" \n",
"# Change the classifier head\n",
"set_seeds()\n",
"pretrained_vit.heads = nn.Linear(in_features=768, out_features=len(class_names)).to(device)"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 53,
2022-07-04 16:38:17 +10:00
"id": "8fbd83a1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"======================================================================================================================================================\n",
"Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n",
"======================================================================================================================================================\n",
"VisionTransformer (VisionTransformer) [128, 3, 224, 224] [128, 3] 768 Partial\n",
"├─Conv2d (conv_proj) [128, 3, 224, 224] [128, 768, 14, 14] (590,592) False\n",
"├─Encoder (encoder) [128, 197, 768] [128, 197, 768] 151,296 False\n",
"│ └─Dropout (dropout) [128, 197, 768] [128, 197, 768] -- --\n",
"│ └─Sequential (layers) [128, 197, 768] [128, 197, 768] -- False\n",
"│ │ └─EncoderBlock (encoder_layer_0) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_1) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_2) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_3) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_4) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_5) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_6) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_7) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_8) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_9) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_10) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ │ └─EncoderBlock (encoder_layer_11) [128, 197, 768] [128, 197, 768] (7,087,872) False\n",
"│ └─LayerNorm (ln) [128, 197, 768] [128, 197, 768] (1,536) False\n",
"├─Linear (heads) [128, 768] [128, 3] 2,307 True\n",
"======================================================================================================================================================\n",
"Total params: 85,800,963\n",
"Trainable params: 2,307\n",
"Non-trainable params: 85,798,656\n",
"Total mult-adds (G): 22.08\n",
"======================================================================================================================================================\n",
"Input size (MB): 77.07\n",
"Forward/backward pass size (MB): 13322.95\n",
"Params size (MB): 257.55\n",
"Estimated Total Size (MB): 13657.57\n",
"======================================================================================================================================================"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 53,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Print a summary using torchinfo (uncomment for actual output)\n",
"summary(model=pretrained_vit, \n",
" input_size=(128, 3, 224, 224), # make sure this is \"input_size\", not \"input_shape\"\n",
" # col_names=[\"input_size\"], # uncomment for smaller output\n",
" col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n",
" col_width=20,\n",
" row_settings=[\"var_names\"]\n",
")"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 54,
2022-07-04 16:38:17 +10:00
"id": "2e4ed730-de72-415f-99d1-5dffd57e9dec",
"metadata": {},
"outputs": [],
"source": [
"# TK - the above output has the same number of parameters as our own created model"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 55,
2022-07-04 16:38:17 +10:00
"id": "94cb3900",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[INFO] data/pizza_steak_sushi directory exists, skipping download.\n"
]
},
{
"data": {
"text/plain": [
"PosixPath('data/pizza_steak_sushi')"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 55,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Download pizza, steak, sushi images from GitHub\n",
"image_path = download_data(source=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip\",\n",
" destination=\"pizza_steak_sushi\")\n",
"image_path"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 56,
2022-07-04 16:38:17 +10:00
"id": "2e6ae0fe-73c0-4930-988a-e4df903084b6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"(PosixPath('data/pizza_steak_sushi/train'),\n",
" PosixPath('data/pizza_steak_sushi/test'))"
]
},
2022-07-22 14:06:23 +10:00
"execution_count": 56,
2022-07-04 16:38:17 +10:00
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"train_dir = image_path / \"train\"\n",
"test_dir = image_path / \"test\" \n",
"train_dir, test_dir"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 57,
2022-07-04 16:38:17 +10:00
"id": "dd2f58ff-6182-453a-a802-70ff98c09557",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ImageClassification(\n",
" crop_size=[224]\n",
" resize_size=[256]\n",
" mean=[0.485, 0.456, 0.406]\n",
" std=[0.229, 0.224, 0.225]\n",
" interpolation=InterpolationMode.BILINEAR\n",
")\n"
]
}
],
"source": [
"# Create dataset for pretrained ViT\n",
"pretrained_vit_transforms = pretrained_vit_weights.transforms()\n",
"print(pretrained_vit_transforms)\n",
"\n",
"train_dataloader_pretrained, test_dataloader_pretrained, class_names = data_setup.create_dataloaders(train_dir=train_dir,\n",
" test_dir=test_dir,\n",
" transform=pretrained_vit_transforms,\n",
" batch_size=1024) # From here: https://arxiv.org/abs/2205.01580 (there are other improvements there too...)\n"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 58,
2022-07-04 16:38:17 +10:00
"id": "a49408b4-24d9-4bb1-90a2-dd61c08f78a4",
"metadata": {},
"outputs": [
{
"data": {
"application/vnd.jupyter.widget-view+json": {
2022-07-22 14:06:23 +10:00
"model_id": "7904829b8c1646d38bb6033a5b4367c4",
2022-07-04 16:38:17 +10:00
"version_major": 2,
"version_minor": 0
},
"text/plain": [
" 0%| | 0/10 [00:00<?, ?it/s]"
]
},
"metadata": {},
"output_type": "display_data"
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"Epoch: 1 | train_loss: 1.1490 | train_acc: 0.2356 | test_loss: 1.0584 | test_acc: 0.4667\n",
"Epoch: 2 | train_loss: 1.0017 | train_acc: 0.5289 | test_loss: 0.9194 | test_acc: 0.6400\n",
"Epoch: 3 | train_loss: 0.8716 | train_acc: 0.7244 | test_loss: 0.7983 | test_acc: 0.6667\n",
"Epoch: 4 | train_loss: 0.7583 | train_acc: 0.8089 | test_loss: 0.6942 | test_acc: 0.7733\n",
"Epoch: 5 | train_loss: 0.6608 | train_acc: 0.8622 | test_loss: 0.6060 | test_acc: 0.8800\n",
"Epoch: 6 | train_loss: 0.5777 | train_acc: 0.8889 | test_loss: 0.5318 | test_acc: 0.8933\n",
"Epoch: 7 | train_loss: 0.5076 | train_acc: 0.9156 | test_loss: 0.4700 | test_acc: 0.9067\n",
"Epoch: 8 | train_loss: 0.4487 | train_acc: 0.9244 | test_loss: 0.4188 | test_acc: 0.9333\n",
"Epoch: 9 | train_loss: 0.3993 | train_acc: 0.9378 | test_loss: 0.3765 | test_acc: 0.9333\n",
"Epoch: 10 | train_loss: 0.3580 | train_acc: 0.9378 | test_loss: 0.3417 | test_acc: 0.9467\n"
]
}
],
"source": [
"# Train pretrained feature extractor ViT for 5 epochs on Pizza, Steak, Sushi\n",
"# TK - can probably increase the batch_size here because we're using feature extraction and not \n",
"# training the whole model\n",
"from going_modular.going_modular import engine\n",
"\n",
"optimizer = torch.optim.Adam(params=pretrained_vit.parameters(), \n",
" lr=1e-3)\n",
"loss_fn = torch.nn.CrossEntropyLoss()\n",
"\n",
"set_seeds()\n",
"pretrained_vit_results = engine.train(model=pretrained_vit,\n",
" train_dataloader=train_dataloader_pretrained,\n",
" test_dataloader=test_dataloader_pretrained,\n",
" optimizer=optimizer,\n",
" loss_fn=loss_fn,\n",
" epochs=10,\n",
" device=device)"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 59,
2022-07-04 16:38:17 +10:00
"id": "3c0af18e-6419-4dd6-b8ea-f5830bbd63d5",
"metadata": {},
"outputs": [
{
"data": {
"image/png": "iVBORw0KGgoAAAANSUhEUgAAA2oAAAG5CAYAAAD/HsejAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMSwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/YYfK9AAAACXBIWXMAAAsTAAALEwEAmpwYAACOc0lEQVR4nOzdd3RUVdfH8e9JT0gIEBJ67733Lor0DtJUlCIq1lcfsffyqI8FRRALKjaKIFIUBVGalCC9JrQQQkkIBAKkn/ePiYoIEshN/33Wykpm5s4+e8KQmT33nH2MtRYRERERERHJPdxyOgERERERERH5OxVqIiIiIiIiuYwKNRERERERkVxGhZqIiIiIiEguo0JNREREREQkl1GhJiIiIiIiksuoUBMREREREcllVKiJZIIx5oAx5vqczkNERCSrGWN+McacNMZ453QuIgWBCjURERER+VfGmIpAO8ACvbNxXI/sGkskt1GhJuIwY4y3MeYtY0xU+tdbf3z6aIwpboxZYIw5ZYyJNcasMMa4pd/2iDHmsDHmjDFmtzGmc84+EhERkT/dAqwBPgFu/eNKY0w5Y8wcY0y0MeaEMebdC24bY4zZmf66tsMY0zj9emuMqXrBcZ8YY15I/7mjMSYy/TXxKDDNGFM0/bUzOv2M3gJjTNkL7l/MGDMt/TX3pDHm2/Trtxljel1wnKcxJsYY0zCLfkcijlKhJuK8x4GWQEOgAdAceCL9tv8DIoFgoATwGGCNMTWA8UAza20AcCNwIFuzFhERubxbgC/Sv240xpQwxrgDC4CDQEWgDPA1gDFmEPBM+v0K4zoLdyKDY5UEigEVgLG43q9OS79cHjgPvHvB8dMBP6AOEAK8mX79Z8CIC47rDhyx1m7KYB4iOUqnk0WcNxy4x1p7HMAY8yzwPvAkkAyUAipYa8OBFenHpALeQG1jTLS19kBOJC4iInIxY0xbXEXSTGttjDFmLzAM1xm20sDD1tqU9MNXpn8fDbxqrV2ffjn8KoZMA5621iamX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QBNmjThwIEDVxxn9+7dVKpUierVqwNw6623MmnSJMaPH4+Pjw+jR4+mR48e9OzZE4A2bdowcuRIBg8eTP/+/R14pHKtCsLzdNu2bTzxxBOcOnWK+Ph4brzxRgB+/vlnPvvsM4A/z+5+9tlnDBw48M9iqVixYo7kHx0dTfv27f887o+4t99+O3369OH+++/n448/5rbbbrvieCIiVyvPrlGz1rL+QCzW2pxORUTEUYUKFfrz519++YUlS5bw22+/sXnzZho1anTJTXS9vb3//Nnd3Z2UlJQrjnO5v58eHh6sW7eOAQMG8O2339K1a1cApkyZwgsvvMChQ4do2LAhJ06cuNqHJvlIVj9PR44cybvvvsvWrVt5+umn/3XzaGvtJfct8/DwIC0t7c9jkpKSrir/y8UtV64cJUqU4Oeff2bt2rV069btsrmJSD5kLZyKgNh9WTpMni3UFm8/xqApv7F4+9GcTkVEJFMCAgI4c+bMJW+Li4ujaNGi+Pn5sWvXLtasWePYuDVr1uTAgQOEh4cDMH36dDp06EB8fDxxcXF0796dt956i02bNgGwd+9eWrRowXPPPUfx4sU5dOiQY7lI7pfdz9MzZ85QqlQpkpOT+eKLL/68vnPnzkyePBlwNQI5ffo0nTt3ZubMmX9+ePDH1MeKFSuyYcMGAObNm0dycvJV5d+qVSt+/fVX9u/f/7e4AKNHj2bEiBEMHjwYd3f3TD9eEcmFrIW4wxC+BFa/C/Puhg86w8tl4a168PMLWTp8np36eH2tEGqVKsyz83fQrlowhbzz7EMRkQIuKCiINm3aULduXXx9fSlRosSft3Xt2pUpU6ZQv359atSoQcuWLR0b18f
"text/plain": [
"<Figure size 1080x504 with 2 Axes>"
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"# Plot the loss curves\n",
"from helper_functions import plot_loss_curves\n",
"\n",
"plot_loss_curves(pretrained_vit_results) "
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 60,
2022-07-04 16:38:17 +10:00
"id": "0fd00943-01aa-4ef4-b366-3cb859a25b6f",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[INFO] Saving model to: models/08_pretrained_vit_feature_extractor_pizza_steak_sushi.pth\n"
]
}
],
"source": [
"# Save the model\n",
"from going_modular.going_modular import utils\n",
"\n",
"utils.save_model(model=pretrained_vit,\n",
" target_dir=\"models\",\n",
" model_name=\"08_pretrained_vit_feature_extractor_pizza_steak_sushi.pth\")"
]
},
{
"cell_type": "code",
2022-07-22 14:06:23 +10:00
"execution_count": 61,
2022-07-04 16:38:17 +10:00
"id": "f52ef12c-b88e-4796-84eb-981491a84334",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Pretrained ViT feature extractor model size: 327 MB\n"
]
}
],
"source": [
"from pathlib import Path\n",
"\n",
"# Get the model size in bytes then convert to megabytes\n",
"pretrained_vit_model_size = Path(\"models/08_pretrained_vit_feature_extractor_pizza_steak_sushi.pth\").stat().st_size // (1024*1024)\n",
"print(f\"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB\")"
]
},
{
"cell_type": "markdown",
"id": "277a08e0-bc0e-453d-bf0f-b56164ae71ab",
"metadata": {},
"source": [
"## TK - Things this replication misses out on\n",
"\n",
"TK Put down the difference in the paper vs this replication\n",
"* Many of these things are in Table 3:\n",
" * training data (ImageNet from scratch vs FoodVision Mini data) \n",
" * LR warmup\n",
" * LR decay\n",
" * Weight decay\n",
" * Number of epochs"
]
},
{
"cell_type": "markdown",
"id": "04b1569b-117e-43fd-9e0b-324157cb82a4",
"metadata": {},
"source": [
"## TK - Exercises"
]
},
{
"cell_type": "markdown",
"id": "dd69be46-cb68-4391-9834-8f87d8814722",
"metadata": {},
"source": [
"## TK - Extra-curriculum\n",
"\n",
2022-07-22 14:06:23 +10:00
"* layernorm\n",
"* See the illustrated transformer for an overview of the Transformer model: https://jalammar.github.io/illustrated-transformer/ + https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/\n",
"* Attention is all you need paper - Yannic video\n",
"* Vision transformer - yannic video"
2022-07-04 16:38:17 +10:00
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3ecc8ddc-fd70-4e4b-b888-430f01de73c9",
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
2022-07-22 14:06:23 +10:00
"version": "3.8.13"
2022-07-04 16:38:17 +10:00
},
"vscode": {
"interpreter": {
"hash": "03bc13acfc4e8139fb32f411c6712485d4605f3bdd6569f6973c62d6adcc8291"
}
}
},
"nbformat": 4,
"nbformat_minor": 5
}