"Welcome to Milestone Project 2: PyTorch Paper Replicating!\n",
"\n",
"In this project, we're going to be **replicating a machine learning research paper** and creating a Vision Transformer (ViT) from scratch using PyTorch.\n",
"\n",
"We'll then see how ViT, a state-of-the-art computer vision architecture, performs on our FoodVision Mini problem.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-applying-vit-to-food-vision-mini.png\" alt=\"appyling the vision transformer architecture to FoodVision mini\" width=900/>\n",
"\n",
"*For Milestone Project 2 we're going to focus on recreating the Vision Transformer (ViT) computer vision architecture and applying it to our FoodVision Mini problem to classify different images of pizza, steak and sushi.*"
]
},
{
"cell_type": "markdown",
"id": "ccb53b99-277c-4ac0-a1fb-283c47576be1",
"metadata": {
"id": "ccb53b99-277c-4ac0-a1fb-283c47576be1"
},
"source": [
"## 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 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",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-what-is-paper-replicating-images-math-text-to-code.png\" alt=\"paper replicating involves turning a machine learning reserch paper comprised of images/diagrams, text and math into usable code\" width=1000/>\n",
"\n",
"*Machine learning paper replicating involves turning a machine learning paper comprised of images/diagrams, math and text into usable code and in our case, usable PyTorch code. Diagram, math equations and text from the [ViT paper](https://arxiv.org/abs/2010.11929).*\n"
]
},
{
"cell_type": "markdown",
"id": "966b353c-c9d8-4568-ad64-c0df45a39442",
"metadata": {
"id": "966b353c-c9d8-4568-ad64-c0df45a39442"
},
"source": [
"## 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 details of previous methods used to try and solve it. |\n",
"| **Method** | How did the researchers go about conducting their research? For example, what model(s), data sources, training setups were used? |\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": {
"id": "b8ce67f6-0b00-448b-885d-b7d22bce4ff6"
},
"source": [
"## 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 check 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": {
"id": "b09a7ccf-41e8-4ee4-8d78-aff5f650ca7f"
},
"source": [
"## 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 (and code):\n",
"| [arXiv](https://arxiv.org/) | Pronounced \"archive\", arXiv is a free and open resource for reading technical articles on everything from physics to computer science (including machine learning). |\n",
"| [AK Twitter](https://twitter.com/_akhaliq) | The AK Twitter account publishes machine learning research highlights, often with live demos almost every day. I don't understand 9/10 posts but I find it fun to explore every so often. |\n",
"| [Papers with Code](https://paperswithcode.com/) | A curated collection of trending, active and greatest machine learning papers, many of which include code resources attached. Also includes a collection of common machine learning datasets, benchmarks and current state-of-the-art models. |\n",
"| [lucidrains' `vit-pytorch` GitHub repository](https://github.com/lucidrains/vit-pytorch) | Less of a place to find research papers and more of an example of what paper replicating with code on a larger-scale and with a specific focus looks like. The `vit-pytorch` repository is a collection of Vision Transformer model architectures from various research papers replicated with PyTorch code (much of the inspiration for this notebook was gathered from this repository). |\n",
"> **Note:** This list is far from exhaustive. I only list a few places, the ones I use most frequently personally. So beware the bias. However, I've noticed that even this short list often fully satisfies my needs for knowing what's going on in the field. Any more and I might go crazy."
"Rather than talk about replicating a paper, we're going to get hands-on and *actually* replicate a paper.\n",
"\n",
"The process for replicating all papers will be slightly different but by seeing what it's like to do one, we'll get the momentum to do more.\n",
"\n",
"More specifically, we're going to be replicating the machine learning research paper [*An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale*](https://arxiv.org/abs/2010.11929) (ViT paper) with PyTorch.\n",
"\n",
"The Transformer neural network architecture was originally introduced in the machine learning research paper [*Attention is all you need*](https://arxiv.org/abs/1706.03762).\n",
"\n",
"And the original Transformer architecture was designed to work on one-dimensional (1D) sequences of text.\n",
"A **Transformer architecture** is generally considered to be any neural network that uses the [**attention mechanism**](https://en.wikipedia.org/wiki/Attention_(machine_learning)) as its primary learning layer. Similar to how a convolutional neural network (CNN) uses convolutions as its primary learning layer.\n",
"Like the name suggests, **the Vision Transformer (ViT) architecture was designed to adapt the original Transformer architecture to vision problem(s)** (classification being the first and since many others have followed).\n",
"\n",
"The original Vision Transformer has been through several iterations over the past couple of years, however, we're going to focus on replicating the original, otherwise known as the \"vanilla Vision Transformer\". Because if you can recreate the original, you can adapt to the others.\n",
"\n",
"We're going to be focusing on building the ViT architecture as per the original ViT paper and applying it to FoodVision Mini.\n",
"\n",
"| **Topic** | **Contents** |\n",
"| ----- | ----- |\n",
"| **[0. Getting setup](https://www.learnpytorch.io/08_pytorch_paper_replicating/#0-getting-setup)** | We've written a fair bit of useful code over the past few sections, let's download it and make sure we can use it again. |\n",
"| **[1. Get data](https://www.learnpytorch.io/08_pytorch_paper_replicating/#1-get-data)** | Let's get the pizza, steak and sushi image classification dataset we've been using and build a Vision Transformer to try and improve FoodVision Mini model's results. |\n",
"| **[2. Create Datasets and DataLoaders](https://www.learnpytorch.io/08_pytorch_paper_replicating/#2-create-datasets-and-dataloaders)** | We'll use the `data_setup.py` script we wrote in chapter 05. PyTorch Going Modular to setup our DataLoaders. |\n",
"| **[3. Replicating the ViT paper: an overview](https://www.learnpytorch.io/08_pytorch_paper_replicating/#3-replicating-the-vit-paper-an-overview)** | Replicating a machine learning research paper can be bit a fair challenge, so before we jump in, let's break the ViT paper down into smaller chunks, so we can replicate the paper chunk by chunk. |\n",
"| **[4. Equation 1: The Patch Embedding](https://www.learnpytorch.io/08_pytorch_paper_replicating/#4-equation-1-split-data-into-patches-and-creating-the-class-position-and-patch-embedding)** | The ViT architecture is comprised of four main equations, the first being the patch and position embedding. Or turning an image into a sequence of learnable patches. |\n",
"| **[5. Equation 2: Multi-Head Attention (MSA)](https://www.learnpytorch.io/08_pytorch_paper_replicating/#5-equation-2-multi-head-attention-msa)** | The self-attention/multi-head self-attention (MSA) mechanism is at the heart of every Transformer architecture, including the ViT architecture, let's create an MSA block using PyTorch's in-built layers. |\n",
"| **[6. Equation 3: Multilayer Perceptron (MLP)](https://www.learnpytorch.io/08_pytorch_paper_replicating/#6-equation-3-multilayer-perceptron-mlp)** | The ViT architecture uses a multilayer perceptron as part of its Transformer Encoder and for its output layer. Let's start by creating an MLP for the Transformer Encoder. |\n",
"| **[7. Creating the Transformer Encoder](https://www.learnpytorch.io/08_pytorch_paper_replicating/#7-create-the-transformer-encoder)** | A Transformer Encoder is typically comprised of alternating layers of MSA (equation 2) and MLP (equation 3) joined together via residual connections. Let's create one by stacking the layers we created in sections 5 & 6 on top of each other. |\n",
"| **[8. Putting it all together to create ViT](https://www.learnpytorch.io/08_pytorch_paper_replicating/#8-putting-it-all-together-to-create-vit)** | We've got all the pieces of the puzzle to create the ViT architecture, let's put them all together into a single class we can call as our model. |\n",
"| **[9. Setting up training code for our ViT model](https://www.learnpytorch.io/08_pytorch_paper_replicating/#9-setting-up-training-code-for-our-vit-model)** | Training our custom ViT implementation is similar to all of the other models we've trained previously. And thanks to our `train()` function in `engine.py` we can start training with a few lines of code. |\n",
"| **[10. Using a pretrained ViT from `torchvision.models`](https://www.learnpytorch.io/08_pytorch_paper_replicating/#10-using-a-pretrained-vit-from-torchvisionmodels-on-the-same-dataset)** | Training a large model like ViT usually takes a fair amount of data. Since we're only working with a small amount of pizza, steak and sushi images, let's see if we can leverage the power of transfer learning to improve our performance. |\n",
"| **[11. Make predictions on a custom image](https://www.learnpytorch.io/08_pytorch_paper_replicating/#11-make-predictions-on-a-custom-image)** | The magic of machine learning is seeing it work on your own data, so let's take our best performing model and put FoodVision Mini to the test on the infamous *pizza-dad* image (a photo of my dad eating pizza). |\n",
"\n",
"> **Note:** Despite the fact we're going to be focused on replicating the ViT paper, avoid getting too bogged down on a particular paper as newer better methods will often come along, quickly, so the skill should be to remain curious whilst building the fundamental skills of turning math and words on a page into working code."
]
},
{
"cell_type": "markdown",
"id": "c348ba8b-579f-4707-be16-79557a9d92e1",
"metadata": {
"id": "c348ba8b-579f-4707-be16-79557a9d92e1"
},
"source": [
"## Terminology\n",
"\n",
"There are going to be a fair few acronyms throughout this notebook.\n",
"\n",
"In light of this, here are some definitions:\n",
"* **ViT** - Stands for Vision Transformer (the main neural network architecture we're going to be focused on replicating).\n",
"* **ViT paper** - Short hand for the original machine learning research paper that introduced the ViT architecture, [*An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale*](https://arxiv.org/abs/2010.11929), anytime *ViT paper* is mentioned, you can be assured it is referencing this paper."
]
},
{
"cell_type": "markdown",
"id": "cf677bb7-719a-447e-a8e8-c4f287146b62",
"metadata": {
"id": "cf677bb7-719a-447e-a8e8-c4f287146b62"
},
"source": [
"## 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": {
"id": "7a8913de-e49e-40c9-89c7-6b847fac9def"
},
"source": [
"## 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 `torchvision` v0.13 package (available as of July 2022), we'll make sure we've got the latest versions."
"> **Note:** If you're using Google Colab and the cell above starts to install various software packages, 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"
" !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": {
"id": "4f9bdd26-26ac-4756-bd8e-b7a50799f28b"
},
"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`."
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"id": "5a695192-2644-4aa7-beab-7222a24b1a1a",
"metadata": {
"id": "5a695192-2644-4aa7-beab-7222a24b1a1a"
},
"source": [
"## 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`."
"Beautiful! Data downloaded, let's setup the training and test directories."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "92a426b6-df22-4a58-9d5e-b382c73c6048",
"metadata": {
"id": "92a426b6-df22-4a58-9d5e-b382c73c6048"
},
"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": "d6fce58f-0f0b-48ef-a9b6-1ef3ca09380d",
"metadata": {
"id": "d6fce58f-0f0b-48ef-a9b6-1ef3ca09380d"
},
"source": [
"## 2. Create Datasets and DataLoaders\n",
"\n",
"Now 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",
"# Create image size (from Table 3 in the ViT paper)\n",
"IMG_SIZE = 224\n",
"\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": {
"id": "437078c2-eb42-471f-8561-94845d0a878d"
},
"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",
"However, 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. Though the benefits of this will likely be seen with larger dataset sizes (our FoodVision Mini dataset is quite small). However, setting `pin_memory=True` doesn't *always* improve performance (this is another one of those we're scenarios in machine learning where some things work sometimes and don't other times), so best to *experiment, experiment, experiment*. 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."
"An important step in the ViT paper is preparing the images into patches.\n",
"\n",
"We'll get to what this means in [section 4](https://www.learnpytorch.io/08_pytorch_paper_replicating/#4-equation-1-split-data-into-patches-and-creating-the-class-position-and-patch-embedding) 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."
"Looks like our images are importing correctly, let's continue with the paper replication."
]
},
{
"cell_type": "markdown",
"id": "13bfb028-1afa-44ec-89e9-8890975311ea",
"metadata": {
"id": "13bfb028-1afa-44ec-89e9-8890975311ea"
},
"source": [
"## 3. Replicating the ViT paper: an overview\n",
"\n",
"Before we write any more 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 **model 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",
"The question is: how do we go from our inputs to the desired outputs?"
]
},
{
"cell_type": "markdown",
"id": "6e7f0a12-cce9-45d0-a572-4ad612a98735",
"metadata": {
"id": "6e7f0a12-cce9-45d0-a572-4ad612a98735"
},
"source": [
"### 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",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-intputs-outputs-layers-and-blocks.png\" alt=\"inputs and outputs, layers and blocks of a model\" width=900/>\n",
"\n",
"*A modern deep learning architecture is usually collection of layers and blocks. Where layers take an input (data as a numerical representation) and manipulate it using some kind of function (for example, the self-attention formula pictured above, however, this function could be almost anything) and then output it. Blocks are generally stacks of layers on top of each other doing a similar thing to a single layer but multiple times.*"
]
},
{
"cell_type": "markdown",
"id": "c2852f3f-61f0-4dad-ae8c-49db54e28470",
"metadata": {
"id": "c2852f3f-61f0-4dad-ae8c-49db54e28470"
},
"source": [
"### 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",
"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",
"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",
"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": "4c90c4c0-0039-4790-a25b-f14754e6b468",
"metadata": {
"id": "4c90c4c0-0039-4790-a25b-f14754e6b468"
},
"source": [
"#### 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 on the input, 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 adds a position number to specify in 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 (Appendix B.1).\n",
"* **Transformer Encoder** - The Transformer Encoder, is a collection of the layers listed above. There are two skip connections inside the Transformer encoder (the \"+\" symbols) meaning the layer's inputs are fed directly to immediate layers as well as subsequent layers. The overall ViT architecture is comprised of a number of Transformer encoders stacked on top of eachother.\n",
"* **MLP Head** - This is the output layer of the architecture, it converts the learned features of an input to a class output. Since we're working on image classification, you could also call this the \"classifier head\". The structure of the MLP Head is similar to the MLP block.\n",
"\n",
"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",
"> You could definitely do that by reproducing all of the math equations from the paper with custom PyTorch layers and that would certainly be an educative exercise, however, using pre-existing PyTorch layers is usually preferred as pre-existing layers have often been extensively tested and performance checked to make sure they run correctly and fast.\n",
"> **Note:** We're going to be focused on writing PyTorch code to create these layers. For the background on what each of these layers does, I'd suggest reading the ViT Paper in full or reading the linked resources for each layer.\n",
"\n",
"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": "d95ff18c-9df1-45fa-a22d-9eca72160b6e",
"metadata": {
"id": "d95ff18c-9df1-45fa-a22d-9eca72160b6e"
},
"source": [
"#### 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",
"\n",
"<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",
"\n",
"*These four equations represent the math behind the four major parts of the ViT architecture.*\n",
"\n",
"Section 3.1 describes each of these (some of the text has been omitted for brevity, bolded text is mine):\n",
"\n",
"| **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**... **Position embeddings** are added to the patch embeddings to retain positional information. We use standard **learnable 1D position 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 | Same as equation 2. |\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.*\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."
"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",
"Notice the skip connection on the end (adding the input of the layers to the output of the layers)."
]
},
{
"cell_type": "markdown",
"id": "c2ea68c1-4172-43c3-9a8a-d7632b0ab8c3",
"metadata": {
"id": "c2ea68c1-4172-43c3-9a8a-d7632b0ab8c3"
},
"source": [
"#### 3.2.5 Equation 3 overview\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",
"$$\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",
"This says for the last layer $L$, the output $y$ is the 0 index token of $z$ wrapped in a LayerNorm layer (LN).\n",
"\n",
"Or in our case, the 0 index of `x_output_MLP_block`:\n",
"\n",
"```python\n",
"y = Linear_layer(LN_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": {
"id": "cd36899e-5bc7-411a-aab7-28e3a5a2c6cb"
},
"source": [
"#### 3.2.7 Exploring Table 1\n",
"\n",
"The final piece of the ViT architecture puzzle we'll focus on (for now) is Table 1.\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",
"\n",
"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 computation.\n",
"* **Params** - What are the total number of parameters of the model? Generally, more parameters leads to better performance but at the cost of more computation. You'll notice even ViT-Base has far more parameters than any other model we've used so far.\n",
"We'll use these values as the hyperparameter settings for our ViT architecture."
]
},
{
"cell_type": "markdown",
"id": "d9aedd15-5a98-431e-bd9e-9d18616e4bff",
"metadata": {
"id": "d9aedd15-5a98-431e-bd9e-9d18616e4bff"
},
"source": [
"### 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",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-mathpix-demo.gif\" width=900 alt=\"using mathpix.com to turn text from a machine learning research paper (PDF) into editable LaTeX\"/>\n",
"\n",
"*Turning the four equations from the ViT paper into editable LaTeX/markdown using [mathpix.com](https://mathpix.com/).*\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 of 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."
"## 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",
"With that being said, let's start by creating the class, position and patch embeddings for the ViT architecture.\n",
"\n",
"We'll start with the **patch embedding**.\n",
"\n",
"This means we'll be turning our input images in a sequence of patches and then embedding those patches.\n",
"\n",
"Recall that an **embedding** is a learnable representation of some form and is often a vector.\n",
"\n",
"The term learnable is important because this means the numerical representation of an input image (that the model sees) can be improved over time.\n",
"\n",
"We'll begin by following the opening paragraph of section 3.1 of the ViT paper (bold mine):\n",
"\n",
"> 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",
"\n",
"And size we're dealing with image shapes, let's keep in mind the line from Table 3 of the ViT paper:\n",
"\n",
"> 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$ for various sized ViT models can be found in Table 1.\n",
"* The image starts as 2D with size ${H \\times W \\times C}$.\n",
" * $(H, W)$ is the resolution of the original image (height, width).\n",
" * $C$ is the number of channels.\n",
"* The image gets converted to a sequence of flattened 2D patches with size ${N \\times\\left(P^{2} \\cdot C\\right)}$.\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 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.*"
"### 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)."
"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": {
"id": "f774b58d-7095-4272-aba3-fd9a2db4f28f"
},
"source": [
"### 4.3 Creating image patches with `torch.nn.Conv2d()`\n",
"\n",
"We've seen what an image looks like when it gets turned into patches, now let's 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",
"<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 1D 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",
"* [`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 learnable vector of size 768)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3d4fd046-6b51-4ac0-8d39-e67fb333a18a",
"metadata": {
"id": "3d4fd046-6b51-4ac0-8d39-e67fb333a18a"
},
"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",
"Notice how the feature maps all kind of represent the original image, after visualizing a few more you can start to 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",
"The `grad_fn` output of the `single_feature_map` and the `requires_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": {
"id": "572ae1c5-9488-4882-bdc1-409eef95424e"
},
"source": [
"### 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",
"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?"
"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",
"> **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?"
"### 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!"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3ef75c7e",
"metadata": {
"id": "3ef75c7e"
},
"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",
"*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": null,
"id": "e440be53-d72c-42b8-87c8-1c31c4262c16",
"metadata": {
"id": "e440be53-d72c-42b8-87c8-1c31c4262c16"
},
"outputs": [],
"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 (uncomment for full output)\n",
"# summary(PatchEmbedding(),\n",
"# input_size=random_input_image, # try swapping this for \"random_input_image_error\"\n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-summary-output-patchembedding.png\" alt=\"summary output of patchembedding layer for vision transformer with input and output shapes\" width=900/>"
]
},
{
"cell_type": "markdown",
"id": "8576f2f1-a2ad-4874-8f76-08156371f444",
"metadata": {
"id": "8576f2f1-a2ad-4874-8f76-08156371f444"
},
"source": [
"### 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 section 4.5) and its shape."
"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",
"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`."
"> **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) (since machine learning is all about harnessing the power of controlled randomness, you generally start with a random number and improve it over time).\n",
"\n",
"See how the `number_of_tokens` 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",
"We can do so using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) and set `dim=1` (so `class_token`'s `number_of_tokens` dimension is prepended to `patch_embedded_image`'s `number_of_patches` dimension)."
"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": {
"id": "79fd9252-c15e-40a6-965a-a872e0e09cab"
},
"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 likely create it with `torch.randn()`.*"
]
},
{
"cell_type": "markdown",
"id": "48502c61-16b0-4659-b95f-0e830ae93077",
"metadata": {
"id": "48502c61-16b0-4659-b95f-0e830ae93077"
},
"source": [
"### 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",
"By \"retain positional information\" the authors mean they want the architecture to know what \"order\" the patches come in. As in, patch two comes after patch one and patch three comes after patch two and on and on.\n",
"This positional information can be important when considering what's in an image (without positional information and a flattened sequence could be seen as having no order and thus no patch relates to any other patch).\n",
"* $N=H W / P^{2}$ is the resulting number of patches, which also serves as the effective input sequence length for the Transformer (number of patches).\n",
"* $D$ is the size of the **patch embeddings**, different values for $D$ can be found in Table 1 (embedding dimension).\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 }}$."
"> **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."
"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": {
"id": "80a39e97-4504-4931-9cec-2569389f3faf"
},
"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 in section 8 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.*"
]
},
{
"cell_type": "markdown",
"id": "6654c7ed-eb94-408b-b435-9b352c84328b",
"metadata": {
"id": "6654c7ed-eb94-408b-b435-9b352c84328b"
},
"source": [
"### 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",
"print(f\"Patch and position embedding shape: {patch_and_position_embedding.shape}\")"
]
},
{
"cell_type": "markdown",
"id": "129b4a2b-0a24-461f-a437-ad49925576c4",
"metadata": {
"id": "129b4a2b-0a24-461f-a437-ad49925576c4"
},
"source": [
"Woohoo!\n",
"\n",
"From a single image to patch and position embeddings in a single cell of code.\n",
"\n",
"<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",
"\n",
"*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!"
]
},
{
"cell_type": "markdown",
"id": "02f725de-64d1-41d2-a9d6-374cf6d4f589",
"metadata": {
"id": "02f725de-64d1-41d2-a9d6-374cf6d4f589"
},
"source": [
"## 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",
"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 of the layer).\n",
"\n",
"We'll refer to equation 2 as the \"MSA block\".\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",
"* **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 in section 7.1)."
]
},
{
"cell_type": "markdown",
"id": "97430d7a-a69b-423c-be2b-ac16e7f9f83f",
"metadata": {
"id": "97430d7a-a69b-423c-be2b-ac16e7f9f83f"
},
"source": [
"### 5.1 The LayerNorm (LN) layer\n",
"\n",
"[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",
"\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",
"PyTorch's `torch.nn.LayerNorm()`'s main parameter is `normalized_shape` which we can set to be equal to the dimension size we'd like to normalize over (in our case it'll be $D$ or `768` for ViT-Base).\n",
"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 on each step right?\n",
"And what you learn for each step wouldn't necessarily help with the next one since they all differ, increasing the time it takes you to navigate the stairs.\n",
"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."
]
},
{
"cell_type": "markdown",
"id": "cf09f6d0-2480-4577-a694-1171898e1777",
"metadata": {
"id": "cf09f6d0-2480-4577-a694-1171898e1777"
},
"source": [
"### 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",
"Originally designed for text inputs, the original self-attention mechanism takes a sequence of words and then calculates which word should pay more \"attention\" to another word.\n",
"\n",
"In other words, in the sentence \"the dog jumped over the fence\", perhaps the word \"dog\" relates strongly to \"jumped\" and \"fence\".\n",
"\n",
"This is simplified but the premise remains for images.\n",
"\n",
"Since our input is a sequence of image patches rather than words, self-attention and in turn multi-head attention will calculate which patch of an image is most related to another patch, eventually forming a learned representation of an image.\n",
"There are many resources online to learn more about the Transformer architecture and attention mechanism online such as Jay Alammar's wonderful [Illustrated Transformer post](https://jalammar.github.io/illustrated-transformer/) and [Illustrated Attention post](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/).\n",
"<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 embedding 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 embedding input will be three versions of the output of the Norm layer, one for query, key and value.\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).\n",
"* `batch_first` - does our batch dimension come first? (yes it does)"
]
},
{
"cell_type": "markdown",
"id": "b1a012fa-9bf6-4cf2-bbd0-30ed692f9d74",
"metadata": {
"id": "b1a012fa-9bf6-4cf2-bbd0-30ed692f9d74"
},
"source": [
"### 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",
"\n",
"To do so, we'll: \n",
"\n",
"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."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b76ae98c",
"metadata": {
"id": "b76ae98c"
},
"outputs": [],
"source": [
"# 1. Create a class that inherits from nn.Module\n",
" need_weights=False) # do we need the weights or just the layer outputs?\n",
" return attn_output"
]
},
{
"cell_type": "markdown",
"id": "fc1f0c30-a4ea-41e8-98b2-1a6d8de802d1",
"metadata": {
"id": "fc1f0c30-a4ea-41e8-98b2-1a6d8de802d1"
},
"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 in section 7.1.\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."
"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 and could be hard to visualize).\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.1)!\n",
"Here MLP stands for \"multilayer perceptron\" and LN stands for \"layer normalization\" (as discussed above).\n",
"\n",
"And the addition on the end is the skip/residual connection.\n",
"\n",
"We'll refer to equation 3 as the \"MLP block\" of the Transformer encoder (notice how we're continuing the trend of breaking down the architecture into smaller chunks).\n",
"\n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-equation-3-annotated.png\" alt=\"mapping equation 3 from the ViT paper to the ViT architecture diagram in figure 1\" width=900/>\n",
"\n",
"***Left:** Figure 1 from the ViT paper with MLP and Norm layers as well as the residual connection (+) highlighted within the Transformer Encoder block. **Right:** Mapping the multilayer perceptron (MLP) layer, Norm layer (LN) and residual connection to their respective parts of equation 3 in the ViT paper.*"
"The term [MLP](https://en.wikipedia.org/wiki/Multilayer_perceptron) is quite broad as it can refer to almost any combination of *multiple* layers (hence the \"multi\" in multilayer perceptron).\n",
"In the the case of the ViT paper, the MLP structure is defined in section 3.1:\n",
"\n",
"> The MLP contains two layers with a GELU non-linearity.\n",
"\n",
"Where \"two layers\" refers to linear layers ([`torch.nn.Linear()`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) in PyTorch) and \"GELU non-linearity\" is the GELU (Gaussian Error Linear Units) non-linear activation function ([`torch.nn.GELU()`](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html) in PyTorch).\n",
"\n",
"> **Note:** A linear layer (`torch.nn.Linear()`) can sometimes also be referred to as a \"dense layer\" or \"feedforward layer\". Some papers even use all three terms to describe the same thing (as in the ViT paper).\n",
"\n",
"Another sneaky detail about the MLP block doesn't appear until Appendix B.1 (Training):\n",
"\n",
"> Table 3 summarizes our training setups for our different models. ...Dropout, when used, is applied **after every dense layer except for the the qkv-projections and directly after adding positional- to patch embeddings.**\n",
"\n",
"This means that every linear layer (or dense layer) in the MLP block has a dropout layer ([`torch.nn.Dropout()`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html) in PyTorch).\n",
"\n",
"The value of which can be found in Table 3 of the ViT paper (for ViT-Base, `dropout=0.1`).\n",
"\n",
"Knowing this, the structure of our MLP block will be:\n",
"\n",
"`layer norm -> linear layer -> non-linear layer -> dropout -> linear layer -> dropout`\n",
"\n",
"With hyperparameter values for the linear layers available from Table 1 (MLP size is the number of hidden units between the linear layers and hidden size $D$ is the output size of the MLP block)."
"### 6.2 Replicating Equation 3 with PyTorch layers\n",
"\n",
"Let's put everything we've discussed about the LayerNorm (LN) and MLP (MSA) layers in equation 3 into practice.\n",
"\n",
"To do so, we'll: \n",
"\n",
"1. Create a class called `MLPBlock` that inherits from `torch.nn.Module`.\n",
"2. Initialize the class with hyperparameters from Table 1 and Table 3 of the ViT paper for the ViT-Base model.\n",
"3. 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 sequential series of MLP layers(s) using `torch.nn.Linear()`, `torch.nn.Dropout()` and `torch.nn.GELU()` with appropriate hyperparameter values from Table 1 and Table 3.\n",
"5. Create a `forward()` method for our class passing the in the inputs through the LN layer and MLP layer(s)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "68d9dbfe",
"metadata": {
"id": "68d9dbfe"
},
"outputs": [],
"source": [
"# 1. Create a class that inherits from nn.Module\n",
"class MLPBlock(nn.Module):\n",
" \"\"\"Creates a layer normalized multilayer perceptron block (\"MLP block\" for short).\"\"\"\n",
" # 2. Initialize the class with hyperparameters from Table 1 and Table 3\n",
" def __init__(self,\n",
" embedding_dim:int=768, # Hidden Size D from Table 1 for ViT-Base\n",
" mlp_size:int=3072, # MLP size from Table 1 for ViT-Base\n",
" dropout:float=0.1): # Dropout from Table 3 for ViT-Base\n",
"> **Note:** Unlike Figure 1, our `MLPBlock()` doesn't include a skip or residual connection (\"$+\\mathbf{z}_{\\ell}^{\\prime}$\" in equation 3), we'll include this when we create the entire Transformer encoder later on.\n",
"\n",
"MLPBlock class created!\n",
"\n",
"Let's try it out by create an instance of our `MLPBlock` and passing through the `patched_image_through_msa_block` variable we created in section 5.3."
"Notice how the input and output shape of our data again stays the same when it goes in and out of the MLP block.\n",
"\n",
"However, the shape does change when the data gets passed through the `nn.Linear()` layers within the MLP block (expanded to MLP size from Table 1 and then compressed back to Hidden size $D$ from Table 1).\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-3-mapped-to-code.png\" width=900 alt=\"vision transformer paper with equation 3 of figure 1 highlighted and equation 3 turned into code\"/>\n",
"\n",
"*Left: Vision Transformer architecture from Figure 1 with MLP and Norm layers highlighted, these layers make up equation 3 from section 3.1 of the paper. Right: Replicating equation 3 (without the skip connection on the end) using PyTorch layers.*\n",
"\n",
"Ho ho!\n",
"\n",
"Equation 3 replicated (except for the residual connection on the end but we'll get to this in section 7.1)!\n",
"\n",
"Now we've got equation's 2 and 3 in PyTorch code, let's now put them together to create the Transformer Encoder."
]
},
{
"cell_type": "markdown",
"id": "6259bdc6-525a-4bd6-89e8-c2dcdab09d0d",
"metadata": {
"id": "6259bdc6-525a-4bd6-89e8-c2dcdab09d0d"
},
"source": [
"## 7. Create the Transformer Encoder\n",
"\n",
"Time to stack together our `MultiheadSelfAttentionBlock` (equation 2) and `MLPBlock` (equation 3) and create the Transformer Encoder of the ViT architecture.\n",
"\n",
"In deep learning, an [\"encoder\" or \"auto encoder\"](https://paperswithcode.com/method/autoencoder) generally refers to a stack of layers that \"encodes\" an input (turns it into some form of numerical representation).\n",
"\n",
"In our case, the Transformer Encoder will encode our patched image embedding into a learned representation using a series of alternating layers of MSA blocks and MLP blocks, as per section 3.1 of the ViT Paper:\n",
"\n",
"> 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",
"\n",
"We've created MSA and MLP blocks but what about the residual connections?\n",
"\n",
"[Residual connections](https://paperswithcode.com/method/residual-connection) (also called skip connections), were first introduced in the paper [*Deep Residual Learning for Image Recognition*](https://arxiv.org/abs/1512.03385v1) and are achieved by adding a layer(s) input to its subsequent output.\n",
"\n",
"Where the subsequence output might be one or more layers later.\n",
"\n",
"In the case of the ViT architecture, the residual connection means the input of the MSA block is added back to the output of the MSA block before it passes to the MLP block.\n",
"\n",
"And the same thing happens with the MLP block before it goes onto the next Transformer Encoder block.\n",
"One of the main ideas behind residual connections is that they prevent weight values and gradient updates from getting too small and thus allow deeper networks and in turn allow deeper representations to be learned.\n",
"\n",
"> **Note:** The iconic computer vision architecture \"ResNet\" is named so because of the introduction of *res*idual connections. You can find many pretrained versions of ResNet architectures in [`torchvision.models`](https://pytorch.org/vision/stable/models.html)."
]
},
{
"cell_type": "markdown",
"id": "0d8c4f01-e6b5-4b70-b991-a2ec03a6e6b5",
"metadata": {
"id": "0d8c4f01-e6b5-4b70-b991-a2ec03a6e6b5"
},
"source": [
"### 7.1 Creating a Transformer Encoder by combining our custom made layers\n",
"\n",
"Enough talk, let's see this in action and make a ViT Transformer Encoder with PyTorch by combining our previously created layers.\n",
"\n",
"To do so, we'll: \n",
"\n",
"1. Create a class called `TransformerEncoderBlock` that inherits from `torch.nn.Module`.\n",
"2. Initialize the class with hyperparameters from Table 1 and Table 3 of the ViT paper for the ViT-Base model.\n",
"3. Instantiate a MSA block for equation 2 using our `MultiheadSelfAttentionBlock` from section 5.2 with the appropriate parameters.\n",
"4. Instantiate a MLP block for equation 3 using our `MLPBlock` from section 6.2 with the appropriate parameters.\n",
"5. Create a `forward()` method for our `TransformerEncoderBlock` class.\n",
"6. Create a residual connection for the MSA block (for equation 2).\n",
"7. Create a residual connection for the MLP block (for equation 3)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2c43855c",
"metadata": {
"id": "2c43855c"
},
"outputs": [],
"source": [
"# 1. Create a class that inherits from nn.Module\n",
"class TransformerEncoderBlock(nn.Module):\n",
" \"\"\"Creates a Transformer Encoder block.\"\"\"\n",
" # 2. Initialize the class with hyperparameters from Table 1 and Table 3\n",
" def __init__(self,\n",
" embedding_dim:int=768, # Hidden size D from Table 1 for ViT-Base\n",
" num_heads:int=12, # Heads from Table 1 for ViT-Base\n",
" mlp_size:int=3072, # MLP size from Table 1 for ViT-Base\n",
" mlp_dropout:float=0.1, # Amount of dropout for dense layers from Table 3 for ViT-Base\n",
" attn_dropout:float=0): # Amount of dropout for attention layers\n",
"***Left:** Figure 1 from the ViT paper with the Transformer Encoder of the ViT architecture highlighted. **Right:** Transformer Encoder mapped to equation 2 and 3 of the ViT paper, the Transformer Encoder is comprised of alternating blocks of equation 2 (Multi-Head Attention) and equation 3 (Multilayer perceptron).*\n",
"\n",
"See how we're starting to piece together the overall architecture like legos, coding one brick (or equation) at a time.\n",
"You might've noticed that Table 1 from the ViT paper has a Layers column. This refers to the number of Transformer Encoder blocks in the specific ViT architecture.\n",
"In our case, for ViT-Base, we'll be stacking together 12 of these Transformer Encoder blocks to form the backbone of our architecture (we'll get to this in section 8).\n",
"\n",
"Let's get a `torchinfo.summary()` of passing an input of shape `(1, 197, 768) -> (batch_size, num_patches, embedding_dimension)` to our Transformer Encoder block."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "a63be4de-ffff-4fa1-97b8-103012797d36",
"metadata": {
"id": "a63be4de-ffff-4fa1-97b8-103012797d36"
},
"outputs": [],
"source": [
"# Create an instance of TransformerEncoderBlock\n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-summary-output-transformer-encoder.png\" alt=\"summary output of a Transformer Encoder layer in PyTorch\" width=900/>\n",
"\n",
"Woah! Check out all those parameters!\n",
"\n",
"You can see our input changing shape as it moves through all of the various layers in the MSA block and MLP block of the Transformer Encoder block before finally returning to its original shape at the very end.\n",
"\n",
"> **Note:** Just because our input to the Transformer Encoder block has the same shape at the output of the block doesn't mean the values weren't manipulated, the whole goal of the Transformer Encoder block (and stacking them together) is to learn a deep representation of the input using the various layers in between."
"### 7.2 Creating a Transformer Encoder with PyTorch's Transformer layers\n",
"\n",
"So far we've built the components of and the Transformer Encoder layer itself ourselves.\n",
"\n",
"But because of their rise in popularity and effectiveness, PyTorch now has in-built [Transformer layers as part of `torch.nn`](https://pytorch.org/docs/stable/nn.html#transformer-layers).\n",
"\n",
"For example, we can recreate the `TransformerEncoderBlock` we just created using [`torch.nn.TransformerEncoderLayer()`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html#torch.nn.TransformerEncoderLayer) and setting the same hyperparameters as above."
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-summary-output-pytorch-transformer-encoder.png\" alt=\"output summary of PyTorch's implementation of the Transformer Encoder layer\" width=900/>\n",
"\n",
"The output of the summary is slightly different to ours due to how `torch.nn.TransformerEncoderLayer()` constructs its layer.\n",
"\n",
"But the layers it uses, number of parameters and input and output shapes are the same.\n",
"\n",
"You might be thinking, \"if we could create the Transformer Encoder so quickly with PyTorch layers, why did we bother reproducing equation 2 and 3?\"\n",
"\n",
"The answer is: practice.\n",
"\n",
"Now we've replicated a series of equations and layers from a paper, if you need to change the layers and try something different you can.\n",
"\n",
"But there are benefits of using the PyTorch pre-built layers, such as:\n",
"* **Potentially better performance** - As of July 2022 and PyTorch 1.12, the PyTorch implemented version of `torch.nn.TransformerEncoderLayer()` can see [a speedup of more than 2x on many common workloads](https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/).\n",
"\n",
"Finally, since the ViT architecture uses several Transformer Layers stacked on top of each for the full architecture (Table 1 shows 12 Layers in the case of ViT-Base), you can do this with [`torch.nn.TransformerEncoder(encoder_layer, num_layers)`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder) where:\n",
"* `encoder_layer` - The target Transformer Encoder layer created with `torch.nn.TransformerEncoderLayer()`.\n",
"* `num_layers` - The number of Transformer Encoder layers to stack together."
]
},
{
"cell_type": "markdown",
"id": "94f9041c-a0af-4fbe-8969-a2bde8637821",
"metadata": {
"id": "94f9041c-a0af-4fbe-8969-a2bde8637821"
},
"source": [
"## 8. Putting it all together to create ViT\n",
"\n",
"Alright, alright, alright, we've come a long way!\n",
"\n",
"But now it's time to do the exciting thing of putting together all of the pieces of the puzzle.\n",
"\n",
"We're going to combine all of the blocks we've created to replicate the full ViT architecture.\n",
"\n",
"From the patch and positional embedding to the Transformer Encoder(s) to the MLP Head.\n",
"\n",
"But wait, we haven't created equation 4 yet...\n",
"Don't worry, we can put equation 4 into our overall ViT architecture class.\n",
"\n",
"All we need is a `torch.nn.LayerNorm()` layer and a `torch.nn.Linear()` layer to convert the 0th index ($\\mathbf{z}_{L}^{0}$) of the Transformer Encoder logit outputs to the target number of classes we have.\n",
"\n",
"To create the full architecture, we'll also need to stack a number of our `TransformerEncoderBlock`s on top of each other, we can do this by passing a list of them to `torch.nn.Sequential()` (this will make a sequential range of `TransformerEncoderBlock`s).\n",
"\n",
"We'll focus on the ViT-Base hyperparameters from Table 1 but our code should be adaptable to other ViT variants.\n",
"\n",
"Creating ViT will be our biggest code block yet but we can do it!\n",
"\n",
"Finally, to bring our own implementation of ViT to life, let's:\n",
"\n",
"1. Create a class called `ViT` that inherits from `torch.nn.Module`.\n",
"2. Initialize the class with hyperparameters from Table 1 and Table 3 of the ViT paper for the ViT-Base model.\n",
"3. Make sure the image size is divisible by the patch size (the image should be split into even patches).\n",
"4. Calculate the number of patches using the formula $N=H W / P^{2}$, where $H$ is the image height, $W$ is the image width and $P$ is the patch size.\n",
"5. Create a learnable class embedding token (equation 1) as done above in section 4.6.\n",
"6. Create a learnable position embedding vector (equation 1) as done above in section 4.7.\n",
"7. Setup the embedding dropout layer as discussed in Appendix B.1 of the ViT paper.\n",
"8. Create the patch embedding layer using the `PatchEmbedding` class as above in section 4.5.\n",
"9. Create a series of Transformer Encoder blocks by passing a list of `TransformerEncoderBlock`s created in section 7.1 to `torch.nn.Sequential()` (equations 2 & 3).\n",
"10. Create the MLP head (also called classifier head or equation 4) by passing a `torch.nn.LayerNorm()` (LN) layer and a `torch.nn.Linear(out_features=num_classes)` layer (where `num_classes` is the target number of classes) linear layer to `torch.nn.Sequential()`.\n",
"11. Create a `forward()` method that accepts an input.\n",
"12. Get the batch size of the input (the first dimension of the shape).\n",
"13. Create the patching embedding using the layer created in step 8 (equation 1).\n",
"14. Create the class token embedding using the layer created in step 5 and expand it across the number of batches found in step 11 using [`torch.Tensor.expand()`](https://pytorch.org/docs/stable/generated/torch.Tensor.expand.html) (equation 1).\n",
"15. Concatenate the class token embedding created in step 13 to the first dimension of the patch embedding created in step 12 using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) (equation 1).\n",
"16. Add the position embedding created in step 6 to the patch and class token embedding created in step 14 (equation 1).\n",
"17. Pass the patch and position embedding through the dropout layer created in step 7.\n",
"18. Pass the patch and position embedding from step 16 through the stack of Transformer Encoder layers created in step 9 (equations 2 & 3).\n",
"19. Pass index 0 of the output of the stack of Transformer Encoder layers from step 17 through the classifier head created in step 10 (equation 4).\n",
"20. Dance and shout woohoo!!! We just built a Vision Transformer!\n",
"\n",
"You ready?\n",
"\n",
"Let's go."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "2df890d5",
"metadata": {
"id": "2df890d5"
},
"outputs": [],
"source": [
"# 1. Create a ViT class that inherits from nn.Module\n",
"class ViT(nn.Module):\n",
" \"\"\"Creates a Vision Transformer architecture with ViT-Base hyperparameters by default.\"\"\"\n",
" # 2. Initialize the class with hyperparameters from Table 1 and Table 3\n",
" def __init__(self,\n",
" img_size:int=224, # Training resolution from Table 3 in ViT paper\n",
" in_channels:int=3, # Number of channels in input image\n",
" patch_size:int=16, # Patch size\n",
" num_transformer_layers:int=12, # Layers from Table 1 for ViT-Base\n",
" embedding_dim:int=768, # Hidden size D from Table 1 for ViT-Base\n",
" mlp_size:int=3072, # MLP size from Table 1 for ViT-Base\n",
" num_heads:int=12, # Heads from Table 1 for ViT-Base\n",
" attn_dropout:float=0, # Dropout for attention projection\n",
" mlp_dropout:float=0.1, # Dropout for dense/MLP layers\n",
" embedding_dropout:float=0.1, # Dropout for patch and position embeddings\n",
" num_classes:int=1000): # Default for ImageNet but can customize this\n",
" super().__init__() # don't forget the super().__init__()!\n",
"Shape of class token embedding single: torch.Size([1, 1, 768])\n",
"Shape of class token embedding expanded: torch.Size([32, 1, 768])\n"
]
}
],
"source": [
"# Example of creating the class embedding and expanding over a batch dimension\n",
"batch_size = 32\n",
"class_token_embedding_single = nn.Parameter(data=torch.randn(1, 1, 768)) # create a single learnable class token\n",
"class_token_embedding_expanded = class_token_embedding_single.expand(batch_size, -1, -1) # expand the single learnable class token across the batch dimension, \"-1\" means to \"infer the dimension\"\n",
"\n",
"# Print out the change in shapes\n",
"print(f\"Shape of class token embedding single: {class_token_embedding_single.shape}\")\n",
"print(f\"Shape of class token embedding expanded: {class_token_embedding_expanded.shape}\")"
]
},
{
"cell_type": "markdown",
"id": "3f07ff70-e09c-4d7c-a119-b2185f46e35a",
"metadata": {
"id": "3f07ff70-e09c-4d7c-a119-b2185f46e35a"
},
"source": [
"Notice how the first dimension gets expanded to the batch size and the other dimensions stay the same (because they're inferred by the \"`-1`\" dimensions in `.expand(batch_size, -1, -1)`).\n",
"\n",
"Alright time to test out `ViT()` class.\n",
"\n",
"Let's create a random tensor in the same shape as a single image, pass to an instance of `ViT` and see what happens."
"# Create an instance of ViT with the number of classes we're working with (pizza, steak, sushi)\n",
"vit = ViT(num_classes=len(class_names))\n",
"\n",
"# Pass the random image tensor to our ViT instance\n",
"vit(random_image_tensor)"
]
},
{
"cell_type": "markdown",
"id": "e210b803-f6a4-47e9-af63-dfa92f0eadbe",
"metadata": {
"id": "e210b803-f6a4-47e9-af63-dfa92f0eadbe"
},
"source": [
"Outstanding!\n",
"\n",
"It looks like our random image tensor made it all the way through our ViT architecture and it's outputting three logit values (one for each class).\n",
"\n",
"And because our `ViT` class has plenty of parameters we could customize the `img_size`, `patch_size` or `num_classes` if we wanted to."
]
},
{
"cell_type": "markdown",
"id": "2c0a0c9c-6d98-47fd-a152-8a06be99b5fa",
"metadata": {
"id": "2c0a0c9c-6d98-47fd-a152-8a06be99b5fa"
},
"source": [
"### 8.1 Getting a visual summary of our ViT model\n",
"\n",
"We handcrafted our own version of the ViT architecture and seen that a random image tensor can flow all the way through it.\n",
"\n",
"How about we use `torchinfo.summary()` to get a visual overview of the input and output shapes of all the layers in our model?\n",
"\n",
"> **Note:** The ViT paper states the use of a batch size of 4096 for training, however, this requires a far bit of CPU/GPU compute memory to handle (the larger the batch size the more memory required). So to make sure we don't get memory errors, we'll stick with a batch size of 32. You could always increase this later if you have access to hardware with more memory."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "494bde26-ed1e-45dc-b615-78ac268ca20e",
"metadata": {
"id": "494bde26-ed1e-45dc-b615-78ac268ca20e"
},
"outputs": [],
"source": [
"from torchinfo import summary\n",
"\n",
"# # Print a summary of our custom ViT model using torchinfo (uncomment for actual output)\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-summary-output-custom-vit-model.png\" alt=\"input and output summary of our custom made ViT model\" width=900/>\n",
"\n",
"Now those are some nice looking layers!\n",
"\n",
"Checkout the total number of parameters too, 85,800,963, our biggest model yet!\n",
"\n",
"The number is very close to PyTorch's pretrained ViT-Base with patch size 16 at [`torch.vision.models.vit_b_16()`](https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16) with 86,567,656 total parameters (though this number of parameters is for the 1000 classes in ImageNet).\n",
"\n",
"> **Exercise:** Try changing the `num_classes` parameter of our `ViT()` model to 1000 and then creating another summary with `torchinfo.summary()` and see if the number of parameters lines up between our code and `torchvision.models.vit_b_16()`."
]
},
{
"cell_type": "markdown",
"id": "e8088ca7-48b4-4a96-8f58-f84980073e0b",
"metadata": {
"id": "e8088ca7-48b4-4a96-8f58-f84980073e0b"
},
"source": [
"## 9. Setting up training code for our ViT model\n",
"\n",
"Ok time for the easy part.\n",
"\n",
"Training!\n",
"\n",
"Why easy?\n",
"\n",
"Because we've got most of what we need ready to go, from our model (`vit`) to our DataLoaders (`train_dataloader`, `test_dataloader`) to the training functions we created in [05. PyTorch Going Modular section 4](https://www.learnpytorch.io/05_pytorch_going_modular/#4-creating-train_step-and-test_step-functions-and-train-to-combine-them).\n",
"\n",
"To train our model we can import the `train()` function from [`going_modular.going_modular.engine`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/train.py).\n",
"\n",
"All we need is a loss function and an optimizer."
]
},
{
"cell_type": "markdown",
"id": "2554a736-ca45-4f83-abc3-41750c20ec58",
"metadata": {
"id": "2554a736-ca45-4f83-abc3-41750c20ec58"
},
"source": [
"### 9.1 Creating an optimizer\n",
"\n",
"Searching the ViT paper for \"optimizer\", section 4.1 on Training & Fine-tuning states:\n",
"\n",
"> **Training & Fine-tuning.** We train all models, including ResNets, using Adam (Kingma & Ba, 2015 ) with $\\beta_{1}=0.9, \\beta_{2}=0.999$, a batch size of 4096 and apply a high weight decay of $0.1$, which we found to be useful for transfer of all models (Appendix D.1 shows that, in contrast to common practices, Adam works slightly better than SGD for ResNets in our setting).\n",
"\n",
"So we can see they chose to use the \"Adam\" optimizer ([`torch.optim.Adam()`](https://pytorch.org/docs/stable/generated/torch.optim.Adam.html#torch.optim.Adam)) rather than SGD (stochastic gradient descent, [`torch.optim.SGD()`](https://pytorch.org/docs/stable/generated/torch.optim.SGD.html#torch.optim.SGD)).\n",
"\n",
"The authors set Adam's $\\beta$ (beta) values to $\\beta_{1}=0.9, \\beta_{2}=0.999$, these are the default values for the `betas` parameter in `torch.optim.Adam(betas=(0.9, 0.999))`.\n",
"\n",
"They also state the use of [weight decay](https://paperswithcode.com/method/weight-decay) (slowly reducing the values of the weights during optimization to prevent overfitting), we can set this with the `weight_decay` parameter in `torch.optim.Adam(weight_decay=0.3)` (according to the setting of ViT-* trained on ImageNet-1k).\n",
"\n",
"We'll set the learning rate of the optimizer to 0.003 as per Table 3 (according to the setting of ViT-* trained on ImageNet-1k).\n",
"\n",
"And as discussed previously, we're going to use a lower batch size than 4096 due to hardware limitations (if you have a large GPU, feel free to increase this)."
]
},
{
"cell_type": "markdown",
"id": "1d434f2f-2723-4ce4-8eac-32a8b9228305",
"metadata": {
"id": "1d434f2f-2723-4ce4-8eac-32a8b9228305"
},
"source": [
"### 9.2 Creating a loss function\n",
"\n",
"Strangely, searching the ViT paper for \"loss\" or \"loss function\" or \"criterion\" returns no results.\n",
"\n",
"However, since the target problem we're working with is multi-class classification (the same for the ViT paper), we'll use [`torch.nn.CrossEntropyLoss()`](https://pytorch.org/docs/stable/generated/torch.nn.CrossEntropyLoss.html)."
]
},
{
"cell_type": "markdown",
"id": "73d4f1e2-2922-4b01-9288-e8d206e20dad",
"metadata": {
"id": "73d4f1e2-2922-4b01-9288-e8d206e20dad"
},
"source": [
"### 9.3 Training our ViT model\n",
"\n",
"Okay, now we know what optimizer and loss function we're going to use, let's setup the training code for training our ViT.\n",
"\n",
"We'll start by importing the `engine.py` script from `going_modular.going_modular` then we'll setup the optimizer and loss function and finally we'll use the `train()` function from `engine.py` to train our ViT model for 10 epochs (we're using a smaller number of epochs than the ViT paper to make sure everything works)."
" lr=3e-3, # Base LR from Table 3 for ViT-* ImageNet-1k\n",
" betas=(0.9, 0.999), # default values but also mentioned in ViT paper section 4.1 (Training & Fine-tuning)\n",
" weight_decay=0.3) # from the ViT paper section 4.1 (Training & Fine-tuning) and Table 3 for ViT-* ImageNet-1k\n",
"\n",
"# Setup the loss function for multi-class classification\n",
"loss_fn = torch.nn.CrossEntropyLoss()\n",
"\n",
"# Set the seeds\n",
"set_seeds()\n",
"\n",
"# Train the model and save the training results to a dictionary\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": "1d99ae68-6825-42b7-a567-de5701e62014",
"metadata": {
"id": "1d99ae68-6825-42b7-a567-de5701e62014"
},
"source": [
"Wonderful!\n",
"\n",
"Our ViT model has come to life!\n",
"\n",
"Though the results on our pizza, steak and sushi dataset don't look too good.\n",
"\n",
"Perhaps it's because we're missing a few things?"
]
},
{
"cell_type": "markdown",
"id": "4ba435de-1521-4d70-a48e-7039062c6a6f",
"metadata": {
"id": "4ba435de-1521-4d70-a48e-7039062c6a6f"
},
"source": [
"### 9.4 What our training setup is missing\n",
"\n",
"The original ViT architecture achieves good results on several image classification benchmarks (on par or better than many state-of-the-art results when it was released).\n",
"\n",
"However, our results (so far) aren't as good.\n",
"\n",
"There's a few reasons this could be but the main one is scale.\n",
"\n",
"The original ViT paper uses a far larger amount of data than ours (in deep learning, more data is generally always a good thing) and a longer training schedule (see Table 3).\n",
"Even though our ViT architecture is the same as the paper, the results from the ViT paper were achieved using far more data and a more elaborate training scheme than ours.\n",
"\n",
"Because of the size of the ViT architecture and its high number of parameters (increased learning capabilities), and amount of data it uses (increased learning opportunities), many of the techniques used in the ViT paper training scheme such as learning rate warmup, learning rate decay and gradient clipping are specifically designed to [prevent overfitting](https://www.learnpytorch.io/04_pytorch_custom_datasets/#81-how-to-deal-with-overfitting) (regularization).\n",
"\n",
"> **Note:** For any technique you're unsure of, you can often quickly find an example by searching \"pytorch TECHNIQUE NAME\", for exmaple, say you wanted to learn about learning rate warmup and what it does, you could search \"pytorch learning rate warmup\".\n",
"\n",
"Good news is, there are many pretrained ViT models (using vast amounts of data) available online, we'll see one in action in section 10."
]
},
{
"cell_type": "markdown",
"id": "32cb3ad2-6eea-4b69-9ce8-322270643919",
"metadata": {
"id": "32cb3ad2-6eea-4b69-9ce8-322270643919"
},
"source": [
"### 9.5 Plot the loss curves of our ViT model\n",
"\n",
"We've trained our ViT model and seen the results as numbers on a page.\n",
"\n",
"But let's now follow the data explorer's motto of *visualize, visualize, visualize!*\n",
"\n",
"And one of the best things to visualize for a model is its loss curves.\n",
"\n",
"To check out our ViT model's loss curves, we can use the `plot_loss_curves` function from `helper_functions.py` we 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)."
"It seems our model is [severely underfitting](learnpytorch.io/04_pytorch_custom_datasets/#82-how-to-deal-with-underfitting) (not achieving the results we'd like it to).\n",
"How about we see if we can fix that by bringing in a pretrained ViT model?"
]
},
{
"cell_type": "markdown",
"id": "de0f9531-64f3-4e13-8482-ce545d608900",
"metadata": {
"id": "de0f9531-64f3-4e13-8482-ce545d608900"
},
"source": [
"## 10. Using a pretrained ViT from `torchvision.models` on the same dataset\n",
"\n",
"We've discussed the benefits of using pretrained models in [06. PyTorch Transfer Learning](https://www.learnpytorch.io/06_pytorch_transfer_learning/).\n",
"\n",
"But since we've now trained our own ViT from scratch and achieved less than optimal results, the benefits of transfer learning (using a pretrained model) really shine.\n",
"\n",
"### 10.1 Why use a pretrained model?\n",
"\n",
"An important note on many modern machine learning research papers is that much of the results are obtained with large datasets and vast compute resources.\n",
"\n",
"And in modern day machine learning, the original fully trained ViT would likely not be considered a \"super large\" training setup (models are continually getting bigger and bigger).\n",
"\n",
"Reading the ViT paper section 4.2:\n",
"\n",
"> Finally, the ViT-L/16 model pre-trained on the public ImageNet-21k dataset performs well on most datasets too, while taking fewer resources to pre-train: it could be trained using a standard cloud TPUv3 with 8 cores in approximately **30 days**.\n",
"\n",
"As of July 2022, the [price for renting a TPUv3](https://cloud.google.com/tpu/pricing) (Tensor Processing Unit version 3) with 8 cores on Google Cloud is $8 USD per hour.\n",
"\n",
"To rent one for 30 straight days would cost **$5,760 USD**.\n",
"\n",
"This cost (monetary and time) may be viable for some larger research teams or enterprises but for many people it's not.\n",
"\n",
"So having a pretrained model available through resources like [`torchvision.models`](https://pytorch.org/vision/stable/models.html), the [`timm` (Torch Image Models) library](https://github.com/rwightman/pytorch-image-models), the [HuggingFace Hub](https://huggingface.co/models) or even from the authors of the papers themselves (there's a growing trend for machine learning researchers to release the code and pretrained models from their research papers, I'm a big fan of this trend, many of these resources can be found on [Paperswithcode.com](https://paperswithcode.com/)).\n",
"\n",
"If you're focused on leveraging the benefits of a specific model architecture rather than creating your custom architecture, I'd highly recommend using a pretrained model."
]
},
{
"cell_type": "markdown",
"id": "93027389-1309-47c0-85d3-50e241b617b0",
"metadata": {
"id": "93027389-1309-47c0-85d3-50e241b617b0"
},
"source": [
"### 10.2 Getting a pretrained ViT model and creating a feature extractor\n",
"\n",
"We can get a pretrained ViT model from `torchvision.models`.\n",
"\n",
"We'll go from the top by first making sure we've got the right versions of `torch` and `torchvision`.\n",
"\n",
"> **Note:** The following code requires `torch` v0.12+ and `torchvision` v0.13+ to use the latest `torchvision` model weights API."
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"id": "f3d05630-aa4c-41cc-b7c0-ac9de0a4390c",
"metadata": {
"id": "f3d05630-aa4c-41cc-b7c0-ac9de0a4390c"
},
"source": [
"Finally, we'll get the pretrained ViT-Base with patch size 16 from `torchvision.models` and prepare it for our FoodVision Mini use case by turning it into a feature extractor transfer learning model.\n",
"\n",
"Specifically, we'll:\n",
"1. Get the pretrained weights for ViT-Base trained on ImageNet-1k from [`torchvision.models.ViT_B_16_Weights.DEFAULT`](https://pytorch.org/vision/stable/models/generated/torchvision.models.vit_b_16.html#torchvision.models.ViT_B_16_Weights) (`DEFAULT` stands for best available).\n",
"2. Setup a ViT model instance via `torchvision.models.vit_b_16`, pass it the pretrained weights step 1 and send it to the target device.\n",
"3. Freeze all of the parameters in the base ViT model created in step 2 by setting their `requires_grad` attribute to `False`.\n",
"4. Update the classifier head of the ViT model created in step 2 to suit our own problem by changing the number of `out_features` to our number of classes (pizza, steak, sushi).\n",
"\n",
"We covered steps like this in 06. PyTorch Transfer Learning [section 3.2: Setting up a pretrained model](https://www.learnpytorch.io/06_pytorch_transfer_learning/#32-setting-up-a-pretrained-model) and [section 3.4: Freezing the base model and changing the output layer to suit our needs](https://www.learnpytorch.io/06_pytorch_transfer_learning/#34-freezing-the-base-model-and-changing-the-output-layer-to-suit-our-needs)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b8e2dda6-8af0-4255-815f-4d885fa4b477",
"metadata": {
"id": "b8e2dda6-8af0-4255-815f-4d885fa4b477"
},
"outputs": [],
"source": [
"# 1. Get pretrained weights for ViT-Base\n",
"pretrained_vit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT # requires torchvision >= 0.13, \"DEFAULT\" means best available\n",
"\n",
"# 2. Setup a ViT model instance with pretrained weights\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-summary-output-pytorch-vit.png\" alt=\"output of pytorch pretrained ViT model summary\" width=900 />\n",
"\n",
"Woohoo!\n",
"\n",
"Notice how only the output layer is trainable, where as, all of the rest of the layers are untrainable (frozen).\n",
"\n",
"And the total number of parameters, 85,800,963, is the same as our custom made ViT model above.\n",
"\n",
"But the number of trainable parameters for `pretrained_vit` is much, much lower than our custom `vit` at only 2,307 compared to 85,800,963 (in our custom `vit`, since we're training from scratch, all parameters are trainable).\n",
"\n",
"This means the pretrained model should train a lot faster, we could potentially even use a larger batch size since less parameter updates are going to be taking up memory."
]
},
{
"cell_type": "markdown",
"id": "a50dfe1f-a475-473d-bc23-ef3c58ba4854",
"metadata": {
"id": "a50dfe1f-a475-473d-bc23-ef3c58ba4854"
},
"source": [
"### 10.3 Preparing data for the pretrained ViT model\n",
"\n",
"We downloaded and created DataLoaders for our own ViT model back in section 2.\n",
"\n",
"So we don't necessarily need to do it again.\n",
"\n",
"But in the name of practice, let's download some image data (pizza, steak and sushi images for Food Vision Mini), setup train and test directories and then transform the images into tensors and DataLoaders.\n",
"We can download pizza, steak and sushi images from the course GitHub and the `download_data()` function we created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data).\n",
"Remember, if you're going to use a pretrained model, it's generally important to **ensure your own custom data is transformed/formatted in the same way the data the original model was trained on**.\n",
"\n",
"We covered this method of \"automatic\" transform creation in [06. PyTorch Transfer Learning section 2.2](https://www.learnpytorch.io/06_pytorch_transfer_learning/#22-creating-a-transform-for-torchvisionmodels-auto-creation)."
"And now we've got transforms ready, we can turn our images into DataLoaders using the `data_setup.create_dataloaders()` method we created in [05. PyTorch Going Modular section 2](https://www.learnpytorch.io/05_pytorch_going_modular/#2-create-datasets-and-dataloaders-data_setuppy).\n",
"Since we're using a feature extractor model (less trainable parameters), we could increase the batch size to a higher value (if we set it to 1024, we'd be mimicking an improvement found in [*Better plain ViT baselines for ImageNet-1k*](https://arxiv.org/abs/2205.01580), a paper which improves upon the original ViT paper and suggested extra reading). But since we only have ~200 training samples total, we'll stick with 32."
" batch_size=32) # Could increase if we had more samples, such as here: https://arxiv.org/abs/2205.01580 (there are other improvements there too...)\n"
]
},
{
"cell_type": "markdown",
"id": "4e9da731-3c11-4d79-9e68-f006fcedd288",
"metadata": {
"id": "4e9da731-3c11-4d79-9e68-f006fcedd288"
},
"source": [
"### 10.4 Train feature extractor ViT model\n",
"\n",
"Feature extractor model ready, DataLoaders ready, time to train!\n",
"\n",
"As before we'll use the Adam optimizer (`torch.optim.Adam()`) with a learning rate of `1e-3` and `torch.nn.CrossEntropyLoss()` as the loss function.\n",
"\n",
"Our `engine.train()` function we created in [05. PyTorch Going Modular section 4](https://www.learnpytorch.io/05_pytorch_going_modular/#4-creating-train_step-and-test_step-functions-and-train-to-combine-them) will take care of the rest."
"Those are some close to textbook looking (really good) loss curves (check out [04. PyTorch Custom Datasets section 8](https://www.learnpytorch.io/04_pytorch_custom_datasets/#8-what-should-an-ideal-loss-curve-look-like) for what an ideal loss curve should look like).\n",
"\n",
"That's the power of transfer learning!\n",
"\n",
"We managed to get outstanding results with the *same* model architecture, except our custom implementation was trained from scratch (worse performance) and this feature extractor model has the power of pretrained weights from ImageNet behind it.\n",
"\n",
"What do you think?\n",
"\n",
"Would our feature extractor model improve more if you kept training it?"
]
},
{
"cell_type": "markdown",
"id": "eab07548-3b1c-43a3-9f8d-02672ef1f47c",
"metadata": {
"id": "eab07548-3b1c-43a3-9f8d-02672ef1f47c"
},
"source": [
"### 10.6 Save feature extractor ViT model and check file size\n",
"\n",
"It looks like our ViT feature extractor model is performing quite well for our Food Vision Mini problem.\n",
"Perhaps we might want to try deploying it and see how it goes in production (in this case, deploying means putting our trained model in an application someone could use, say taking photos on their smartphone of food and seeing if our model thinks it's pizza, steak or sushi).\n",
"To do so we can first save our model with the `utils.save_model()` function we created in [05. PyTorch Going Modular section 5](https://www.learnpytorch.io/05_pytorch_going_modular/#5-creating-a-function-to-save-the-model-utilspy)."
"And since we're thinking about deploying this model, it'd be good to know the size of it (in megabytes or MB).\n",
"\n",
"Since we want our Food Vision Mini application to run fast, generally a smaller model with good performance will be better than a larger model with great performance.\n",
"\n",
"We can check the size of our model in bytes using the `st_size` attribute of Python's [`pathlib.Path().stat()`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.stat) method whilst passing it our model's filepath name.\n",
"\n",
"We can then scale the size in bytes to megabytes."
"print(f\"Pretrained ViT feature extractor model size: {pretrained_vit_model_size} MB\")"
]
},
{
"cell_type": "markdown",
"id": "6b63b857-04e1-460c-a510-fc61231b5bc4",
"metadata": {
"id": "6b63b857-04e1-460c-a510-fc61231b5bc4"
},
"source": [
"Hmm, looks like our ViT feature extractor model for Food Vision Mini turned out to be about 327 MB in size.\n",
"\n",
"How does this compare to the EffNetB2 feature extractor model in [07. PyTorch Experiment Tracking section 9](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#9-load-in-the-best-model-and-make-predictions-with-it)?\n",
"> **Note:** ^ the EffNetB2 model in reference was trained with 20% of pizza, steak and sushi data (double the amount of images) rather than the ViT feature extractor which was trained with 10% of pizza, steak and sushi data. An exercise would be to train the ViT feature extractor model on the same amount of data and see how much the results improve.\n",
"However, the ViT model's results may improve more when trained with the same data (20% pizza, steak and sushi data).\n",
"\n",
"But in terms of deployment, if we were comparing these two models, something we'd need to consider is whether the extra accuracy from the ViT model is worth the ~11x increase in model size?\n",
"\n",
"Perhaps such a large model would take longer to load/run and wouldn't provide as good an experience as EffNetB2 which performs similarly but at a much reduced size."
]
},
{
"cell_type": "markdown",
"id": "2adf6c78-95c9-4c0c-b143-6d66d3b7aa25",
"metadata": {
"id": "2adf6c78-95c9-4c0c-b143-6d66d3b7aa25"
},
"source": [
"## 11. Make predictions on a custom image\n",
"\n",
"And finally, we'll finish with the ultimate test, predicting on our own custom data.\n",
"\n",
"Let's download the pizza dad image (a photo of my dad eating pizza) and use our ViT feature extractor to predict on it.\n",
"To do so, let's use the `pred_and_plot()` function we created in [06. PyTorch Transfer Learning section 6](https://www.learnpytorch.io/06_pytorch_transfer_learning/#6-make-predictions-on-images-from-the-test-set), for convenience, I saved this function to [`going_modular.going_modular.predictions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/predictions.py) on the course GitHub."
"We've gone all the way from research paper to usable model code on our own custom images!"
]
},
{
"cell_type": "markdown",
"id": "b2d4e7fc-4b0c-4466-8530-2a81f41eab76",
"metadata": {
"id": "b2d4e7fc-4b0c-4466-8530-2a81f41eab76"
},
"source": [
"## Main takeaways\n",
"\n",
"* With the explosion of machine learning, new research papers detailing advancements come out every day. And it's impossible to keep up with it *all* but you can narrow things down to your own use case, such as what we did here, replicating a computer vision paper for FoodVision Mini.\n",
"* Machine learning research papers often contain months of research by teams of smart people compressed into a few pages (so teasing out all the details and replicating the paper in full can be a bit of challenge).\n",
"* The goal of paper replicating is to turn machine learning research papers (text and math) into usable code.\n",
" * With this being said, many machine learning research teams are starting to publish code with their papers and one of the best places to see this is at [Paperswithcode.com](https://paperswithcode.com/)\n",
"* Breaking a machine learning research paper into inputs and outputs (what goes in and out of each layer/block/model?) and layers (how does each layer manipulate the input?) and blocks (a collection of layers) and replicating each part step by step (like we've done in this notebook) can be very helpful for understanding.\n",
"* Pretrained models are available for many state of the art model architectures and with the power of transfer learning, these often perform *very* well with little data.\n",
"* Larger models generally perform better but have a larger footprint too (they take up more storage space and can take longer to perform inference).\n",
" * A big question is: deployment wise, is the extra performance of a larger model worth it/aligned with the use case?"
]
},
{
"cell_type": "markdown",
"id": "04b1569b-117e-43fd-9e0b-324157cb82a4",
"metadata": {
"id": "04b1569b-117e-43fd-9e0b-324157cb82a4"
},
"source": [
"## Exercises\n",
"\n",
"> **Note:** These exercises expect the use of `torchvision` v0.13+ (released July 2022), previous versions may work but will likely have errors.\n",
"\n",
"All of the exercises are focused on practicing the code above.\n",
"\n",
"You should be able to complete them by referencing each section or by following the resource(s) linked.\n",
"\n",
"All exercises should be completed using [device-agnostic code](https://pytorch.org/docs/stable/notes/cuda.html#device-agnostic-code).\n",
"\n",
"**Resources:**\n",
"\n",
"* [Exercise template notebook for 08](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/exercises/08_pytorch_paper_replicating_exercises.ipynb).\n",
"* [Example solutions notebook for 08](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/extras/solutions/08_pytorch_paper_replicating_exercise_solutions.ipynb) (try the exercises *before* looking at this).\n",
" * See a live [video walkthrough of the solutions on YouTube](https://youtu.be/tjpW_BY8y3g) (errors and all).\n",
"\n",
"1. Replicate the ViT architecture we created with in-built [PyTorch transformer layers](https://pytorch.org/docs/stable/nn.html#transformer-layers).\n",
" * You'll want to look into replacing our `TransformerEncoderBlock()` class with [`torch.nn.TransformerEncoderLayer()`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoderLayer.html#torch.nn.TransformerEncoderLayer) (these contain the same layers as our custom blocks).\n",
" * You can stack `torch.nn.TransformerEncoderLayer()`'s on top of each other with [`torch.nn.TransformerEncoder()`](https://pytorch.org/docs/stable/generated/torch.nn.TransformerEncoder.html#torch.nn.TransformerEncoder).\n",
"2. Turn the custom ViT architecture we created into a Python script, for example, `vit.py`.\n",
" * You should be able to import an entire ViT model using something like`from vit import ViT`.\n",
"3. Train a pretrained ViT feature extractor model (like the one we made in [08. PyTorch Paper Replicating section 10](https://www.learnpytorch.io/08_pytorch_paper_replicating/#10-bring-in-pretrained-vit-from-torchvisionmodels-on-same-dataset)) on 20% of the pizza, steak and sushi data like the dataset we used in [07. PyTorch Experiment Tracking section 7.3](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#73-download-different-datasets).\n",
" * See how it performs compared to the EffNetB2 model we compared it to in [08. PyTorch Paper Replicating section 10.6](https://www.learnpytorch.io/08_pytorch_paper_replicating/#106-save-feature-extractor-vit-model-and-check-file-size).\n",
"4. Try repeating the steps from excercise 3 but this time use the \"`ViT_B_16_Weights.IMAGENET1K_SWAG_E2E_V1`\" pretrained weights from [`torchvision.models.vit_b_16()`](https://pytorch.org/vision/stable/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16).\n",
" * **Note:** ViT pretrained with SWAG weights has a minimum input image size of `(384, 384)` (the pretrained ViT in exercise 3 has a minimum input size of `(224, 224)`), though this is accessible in the weights `.transforms()` method.\n",
"5. Our custom ViT model architecture closely mimics that of the ViT paper, however, our training recipe misses a few things. Research some of the following topics from Table 3 in the ViT paper that we miss and write a sentence about each and how it might help with training:\n",
" * ImageNet-21k pretraining (more data).\n",
" * Learning rate warmup.\n",
" * Learning rate decay.\n",
" * Gradient clipping."
]
},
{
"cell_type": "markdown",
"id": "dd69be46-cb68-4391-9834-8f87d8814722",
"metadata": {
"id": "dd69be46-cb68-4391-9834-8f87d8814722"
},
"source": [
"## Extra-curriculum\n",
"\n",
"* There have been several iterations and tweaks to the Vision Transformer since its original release and the most concise and best performing (as of July 2022) can be viewed in [*Better plain ViT baselines for ImageNet-1k*](https://arxiv.org/abs/2205.01580). Despite of the upgrades, we stuck with replicating a \"vanilla Vision Transformer\" in this notebook because if you understand the structure of the original, you can bridge to different iterations.\n",
"* The [`vit-pytorch` repository on GitHub by lucidrains](https://github.com/lucidrains/vit-pytorch) is one of the most extensive resources of different ViT architectures implemented in PyTorch. It's a phenomenal reference and one I used often to create the materials we've been through in this chapter.\n",
"* PyTorch have their [own implementation of the ViT architecture on GitHub](https://github.com/pytorch/vision/blob/main/torchvision/models/vision_transformer.py), it's used as the basis of the pretrained ViT models in `torchvision.models`.\n",
"* Jay Alammar has fantastic illustrations and explanations on his blog of the [attention mechanism](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/) (the foundation of Transformer models) and [Transformer models](https://jalammar.github.io/illustrated-transformer/).\n",
"* Adrish Dey has a fantastic [write up of Layer Normalization](https://wandb.ai/wandb_fc/LayerNorm/reports/Layer-Normalization-in-Pytorch-With-Examples---VmlldzoxMjk5MTk1) (a main component of the ViT architecture) can help neural network training.\n",
"* The self-attention (and multi-head self-attention) mechanism is at the heart of the ViT architecture as well as many other Transformer architectures, it was originally introduced in the [*Attention is all you need*](https://arxiv.org/abs/1706.03762) paper.\n",
"* Yannic Kilcher's YouTube channel is a sensational resource for visual paper walkthroughs, you can see his videos for the following papers:\n",
" * [Attention is all you need](https://www.youtube.com/watch?v=iDulhoQ2pro) (the paper that introduced the Transformer architecture).\n",
" * [An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale](https://youtu.be/TrdevFK_am4) (the paper that introduced the ViT architecture)."