"Want to recreate ViT paper: \"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale\" - https://arxiv.org/abs/2010.11929 - TK will refer to this as \"ViT paper\" throughout.\n",
"* TK - The name Transformer comes from the architecture name in the paper where it was originally introduced, [*Attention is all you need*](https://arxiv.org/abs/1706.03762). An architecture is usually considered a Transformer variant if it uses attention layers in a specific pattern. Since the Transformer architecture originally focused on text data, the goal of the ViT paper was to bring it to the vision.\n",
"\n",
"* TK - The original transformer was made to work on sequences of text (1D), Vision Transformer turns images into sequences of \"patches\".\n",
"\n",
"* TK - original ViT also called \"vanilla vision transformer\""
"It's no secret machine learning is advancing fast.\n",
"\n",
"Many of these advances get published in machine learning research papers.\n",
"\n",
"And the goal of **paper replicating** is to take replicate these advances with code so you can use the techniques for your own problem.\n",
"\n",
"For example, let's say a new model architecture gets released that performs better than any other architecture before on various benchmarks, wouldn't it be nice to try that architecture on your own problems?\n",
"* TK image: paper replicating = research paper (language + diagrams + math) -> code (turn language, diagrams and math into usable code) / (translate a research paper into usable code)"
"## TK - What is a machine learning research paper?\n",
"\n",
"A machine learning research paper is a scientific paper that details findings of a research group on a specific area.\n",
"\n",
"The contents of a machine learning research paper can vary from paper to paper but they generally follow the structure:\n",
"\n",
"| **Section** | **Contents** |\n",
"| ----- | ----- | \n",
"| **Abstract** | An overview/summary of the paper's main findings/contributions. |\n",
"| **Introduction** | What's the paper's main problem and what are previous methods used to try and solve it? |\n",
"| **Method** | How did the researchers go about conducting their research? For example, what model(s) were used, data sources, training setups, etc. |\n",
"| **Results** | What are the outcomes of the paper? If a new type of model or training setup was used, how did the results of findings compare to previous works (this is where **experiment tracking** comes in handy)? |\n",
"| **Conclusion** | What are the limitations of the suggested methods? What are some next steps for the research community? |\n",
"| **References** | What resources/other papers did the researchers look at to build their own body of work? |\n",
"| **Appendix** | Are there any extra resources/findings to look at that weren't included in any of the above sections? |"
]
},
{
"cell_type": "markdown",
"id": "b8ce67f6-0b00-448b-885d-b7d22bce4ff6",
"metadata": {},
"source": [
"## TK - Why replicate a machine learning research paper?\n",
"\n",
"A machine learning research paper is often a presentation of months of work and experiments done by some of the best machine learning teams in the world condensed into a few pages of text.\n",
"\n",
"And if these experiments lead to better results in an area related to the problem you're working on, it'd be nice to them out.\n",
"\n",
"Also, replicating the work of others is a fantastic way to practice your skills.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-george-hotz-quote.png\" width=600 alt=\"george hotz quote saying to get better at being a machine learning engineer, download a paper, implement it and keep going until you have skills\"/>\n",
"\n",
"*George Hotz is founder of [comma.ai](https://comma.ai/), a self-driving car company and livestreams machine learning coding on [Twitch](https://www.twitch.tv/georgehotz) and those videos get posted in full to [YouTube](https://www.youtube.com/c/georgehotzarchive). I pulled this quote from one of his livestreams. The \"٭\" is to note that machine learning engineering often involves the extra step(s) of preprocessing data and making your models available for others to use (deployment).*\n",
" \n",
"When you first start trying to replicate research papers, you'll likely be overwhelmed.\n",
"\n",
"That's normal.\n",
"\n",
"Research teams spend weeks, months and sometimes years creating these works so it makes sense if it takes you sometime to even read let alone reproduce the works.\n",
"\n",
"Replicating research is such a tough problem, phenomenal machine learning libraries and tools such as, [HuggingFace](https://huggingface.co/), [PyTorch Image Models](https://github.com/rwightman/pytorch-image-models) (`timm` library) and [fast.ai](https://www.fast.ai/) have been born out of making machine learning research more accessible. "
]
},
{
"cell_type": "markdown",
"id": "b09a7ccf-41e8-4ee4-8d78-aff5f650ca7f",
"metadata": {},
"source": [
"## TK - Where can you find code examples for machine learning research papers?\n",
"\n",
"One of the first things you'll notice when it comes to machine learning research is: there's a lot of it.\n",
"\n",
"So beware, trying to stay on top of it is like trying to outrun a hamster wheel.\n",
"\n",
"Follow your interest, pick a few things that stand out to you.\n",
"\n",
"In saying this, there are several places to find and read machine learning research papers:\n",
"* [arXiv](https://arxiv.org/) - Pronounced \"archive\", arXiv is a free and open resource for reading technical articles on everything from physics to computer science (inlcuding machine learning).\n",
"* [Papers with Code](https://paperswithcode.com/) - A curated collection of trending, active and greatest machine learning papers, many of which include code resources attached. Also includes a collection of common machine learning datasets, benchmarks and current state-of-the-art models.\n",
"* [AK Twitter](https://twitter.com/ak92501) - The AK Twitter account publishes machine learning research highlights, often with live demos almost every day. I don't understand 9/10 posts but I find it fun to explore every so often.\n",
"* [lucidrains' `vit-pytorch` GitHub repository](https://github.com/lucidrains/vit-pytorch) - Less of a place to find research papers and more of an example of what paper replicating with code on a larger-scale looks like. The `vit-pytorch` repository is a collection of Vision Transformer model architectures from various research papers replicated with PyTorch code (much of the inspiration for this notebook was gathered from this repository). \n",
"\n",
"TK image: showcase the above"
]
},
{
"cell_type": "markdown",
"id": "7448de48-ec72-4d63-9948-869a4fc58c04",
"metadata": {},
"source": [
"## TK - What we're going to cover\n",
"\n",
"TODO\n",
"\n",
"* ViT -> FoodVision Mini\n",
"* Layers = collections of functions to manipulate data -> Architectures = collections of layers (blocks) -> All layers (and blocks) have inputs and outputs\n",
" * Replicating research papers starts by figuring out the inputs and outputs of your layers -> blocks -> model "
]
},
{
"cell_type": "markdown",
"id": "cf677bb7-719a-447e-a8e8-c4f287146b62",
"metadata": {},
"source": [
"## TK - Where can you get help?\n",
"\n",
"All of the materials for this course [are available on GitHub](https://github.com/mrdbourke/pytorch-deep-learning).\n",
"\n",
"If you run into trouble, you can ask a question on the course [GitHub Discussions page](https://github.com/mrdbourke/pytorch-deep-learning/discussions).\n",
"\n",
"And of course, there's the [PyTorch documentation](https://pytorch.org/docs/stable/index.html) and [PyTorch developer forums](https://discuss.pytorch.org/), a very helpful place for all things PyTorch. "
]
},
{
"cell_type": "markdown",
"id": "7a8913de-e49e-40c9-89c7-6b847fac9def",
"metadata": {},
"source": [
"## TK 0. Getting setup \n",
"\n",
"As we've done previously, let's make sure we've got all of the modules we'll need for this section.\n",
"\n",
"We'll import the Python scripts (such as `data_setup.py` and `engine.py`) we created in [05. PyTorch Going Modular](https://www.learnpytorch.io/05_pytorch_going_modular/).\n",
"\n",
"To do so, we'll download [`going_modular`](https://github.com/mrdbourke/pytorch-deep-learning/tree/main/going_modular) directory from the `pytorch-deep-learning` repository (if we don't already have it).\n",
"\n",
"We'll also get the [`torchinfo`](https://github.com/TylerYep/torchinfo) package if it's not available. \n",
"\n",
"`torchinfo` will help later on to give us a visual representation of our model.\n",
"\n",
"And since later on we'll be using a newer version of the `torchvision` package (as of June 2022), we'll make sure we've got the latest versions."
"> **Note:** If you're using Google Colab, you may have to restart your runtime after running the above cell. After restarting, you can run the cell again and verify you've got the right versions of `torch` and `torchvision`.\n",
"\n",
"Now we'll continue with the regular imports, setting up device agnostic code and this time we'll also get the [`helper_functions.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/helper_functions.py) script from GitHub.\n",
"\n",
"The `helper_functions.py` script contains several functions we created in previous sections:\n",
"* `set_seeds()` to set the random seeds (created in [07. PyTorch Experiment Tracking section 0](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#create-a-helper-function-to-set-seeds)).\n",
"* `download_data()` to download a data source given a link (created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data)).\n",
"* `plot_loss_curves()` to inspect our model's training results (created in [04. PyTorch Custom Datasets section 7.8](https://www.learnpytorch.io/04_pytorch_custom_datasets/#78-plot-the-loss-curves-of-model-0))\n",
"\n",
"> **Note:** It may be a better idea for many of the functions in the `helper_functions.py` script to be merged into `going_modular/going_modular/utils.py`, perhaps that's an extension you'd like to try.\n"
" !mv pytorch-deep-learning/helper_functions.py . # get the helper_functions.py script\n",
" !rm -rf pytorch-deep-learning\n",
" from going_modular.going_modular import data_setup, engine\n",
" from helper_functions import download_data, set_seeds, plot_loss_curves"
]
},
{
"cell_type": "markdown",
"id": "4f9bdd26-26ac-4756-bd8e-b7a50799f28b",
"metadata": {},
"source": [
"> **Note:** If you're using Google Colab, and you don't have a GPU turned on yet, it's now time to turn one on via `Runtime -> Change runtime type -> Hardware accelerator -> GPU`."
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"device"
]
},
{
"cell_type": "markdown",
"id": "5a695192-2644-4aa7-beab-7222a24b1a1a",
"metadata": {},
"source": [
"## TK 1. Get Data\n",
"\n",
"Since we're continuing on with FoodVision Mini, let's download the pizza, steak and sushi image dataset we've been using.\n",
"\n",
"To do so we can use the `download_data()` function from `helper_functions.py` that we created in [07. PyTorch Experiment Tracking section 1](https://www.learnpytorch.io/07_pytorch_experiment_tracking/#1-get-data).\n",
"\n",
"We'll `source` to the raw GitHub link of the [`pizza_steak_sushi.zip` data](https://github.com/mrdbourke/pytorch-deep-learning/raw/main/data/pizza_steak_sushi.zip) and the `destination` to `pizza_steak_sushi`."
"# Setup directory paths to train and test images\n",
"train_dir = image_path / \"train\"\n",
"test_dir = image_path / \"test\""
]
},
{
"cell_type": "markdown",
"id": "14e84624-6af8-4231-b606-3eabffd172db",
"metadata": {},
"source": [
"## TK 2. Create Datasets and DataLoaders\n",
"\n",
"Since we've got some data, let's now turn it into `DataLoader`'s.\n",
"\n",
"To do so we can use the `create_dataloaders()` function in [`data_setup.py`](https://github.com/mrdbourke/pytorch-deep-learning/blob/main/going_modular/going_modular/data_setup.py).\n",
"\n",
"First, we'll create a transform to prepare our images.\n",
"\n",
"This where one of the first references to the ViT paper will come in.\n",
"\n",
"In Table 3, the training resolution is mentioned as being 224 (height=224, width=224). \n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-image-size-and-batch-size.png\" width=900 alt=\"Table 3 from the Vision Transformer paper showing the image size and batch size\"/>\n",
"\n",
"*You can often find various hyperparameter settings listed in a table. In this case we're still preparing our data, so we're mainly concerned with things like image size and batch size. Source: Table 3 in [ViT paper](https://arxiv.org/abs/2010.11929).*\n",
"\n",
"So we'll make sure our transform resizes our images appropriately.\n",
"\n",
"And since we'll be training our model from scratch (no transfer learning to begin with), we won't provide a `normalize` transform like we did in [06. PyTorch Transfer Learning section 2.1](https://www.learnpytorch.io/06_pytorch_transfer_learning/#21-creating-a-transform-for-torchvisionmodels-manual-creation).\n",
"print(f\"Manually created transforms: {manual_transforms}\")"
]
},
{
"cell_type": "markdown",
"id": "437078c2-eb42-471f-8561-94845d0a878d",
"metadata": {},
"source": [
"### 2.2 Turn images into `DataLoader`'s\n",
"Transforms created!\n",
"\n",
"Let's now create our `DataLoader`'s.\n",
"\n",
"The ViT paper states the use of a batch size of 4096 which is 128x the size of the batch size we've been using (32).\n",
"\n",
"We're going to stick with a batch size of 32.\n",
"\n",
"Why?\n",
"\n",
"Because some hardware (including the free tier of Google Colab) may not be able to handle a batch size of 4096.\n",
"\n",
"Having a batch size of 4096 means that 4096 images need to fit into the GPU memory at a time.\n",
"\n",
"This works when you've got the hardware to handle it like a research team from Google often does but when you're running on a single GPU (such as using Google Colab), making sure things work with smaller batch size first is a good idea.\n",
"\n",
"An extension of this project could be to try a higher batch size value and see what happens.\n",
"\n",
"> **Note:** We're using the `pin_memory=True` parameter in the `create_dataloaders()` function to speed up computation. `pin_memory=True` avoids unnecessary copying of memory between the CPU and GPU memory by \"pinning\" examples that have been seen before. For more on this concept. Though the benefits of this will likely be seen with larger dataset sizes (our FoodVision Mini dataset is quite small). See the PyTorch [`torch.utils.data.DataLoader` documentation](https://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) or [Making Deep Learning Go Brrrr from First Principles](https://horace.io/brrr_intro.html) by Horace He for more."
"### 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",
"3. **Table 1** - This table shows the various hyperparameter settings (such as number of layers and number of hidden units) for different ViT model variants. We'll be focused on the smallest version, ViT-Base."
]
},
{
"cell_type": "markdown",
"id": "bac7c7d2-e58b-47b1-ae3e-7ae9f922326d",
"metadata": {},
"source": [
"#### TK 3.2.1 Exploring Figure 1\n",
"\n",
"Let's start by going through Figure 1 of the ViT Paper.\n",
"\n",
"The main things we'll be paying attention to are:\n",
"1. **Layers** - takes an **input**, performs an operation or function, produces an **output**.\n",
"2. **Blocks** - a collection of layers, which in turn also takes an **input** and produces an **output**.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-figure-1-inputs-and-outputs.png\" width=900 alt=\"figure 1 from the original vision transformer paper\"/>\n",
"\n",
"*Figure 1 from the ViT Paper showcasing the different inputs, outputs, layers and blocks that create the architecture. Our goal will be to replicate each of these using PyTorch code.* \n",
"\n",
"The ViT architecture is comprised of several stages:\n",
"* **Patch + Position Embedding (inputs)** - Turns the input image into a sequence of image patches and add a position number what order the patch comes in.\n",
"* **Linear projection of flattened patches (Embedded Patches)** - The image patches get turned into an **embedding**, the benefit of using an embedding rather than just the image values is that an embedding is a *learnable* representation (typically in the form of a vector) of the image that can improve with training.\n",
"* **Norm** - This is short for \"[Layer Normalization](https://paperswithcode.com/method/layer-normalization)\" or \"LayerNorm\", a technique for regularizing (reducing overfitting) a neural network, you can use LayerNorm via the PyTorch layer [`torch.nn.LayerNorm()`](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html).\n",
"* **Multi-Head Attention** - This is a [Multi-Headed Self-Attention layer](https://paperswithcode.com/method/multi-head-attention) or \"MSA\" for short. You can create an MSA layer via the PyTorch layer [`torch.nn.MultiheadAttention()`](https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html).\n",
"* **MLP (or [Multilayer perceptron](https://en.wikipedia.org/wiki/Multilayer_perceptron))** - A MLP can often refer to any collection of feedforward layers (or in PyTorch's case, a collection of layers with a `forward()` method). In the ViT Paper, the authors refer to the MLP as \"MLP block\" and it contains two [`torch.nn.Linear()`](https://pytorch.org/docs/stable/generated/torch.nn.Linear.html) layers with a [`torch.nn.GELU()`](https://pytorch.org/docs/stable/generated/torch.nn.GELU.html) non-linearity activation in between them (section 3.1) and a [`torch.nn.Dropout()`](https://pytorch.org/docs/stable/generated/torch.nn.Dropout.html) layer after each (Appendex B.1). \n",
"* **Transformer Encoder** - The Transformer Encoder, is a collection of the layers listed above. There are two skip connections inside the Transformer encoder (the \"+\" symbols) meaning the layer's inputs are fed directly to immediate layers as well as subsequent layers. The overall ViT architecture is comprised of a number of Transformer encoders stacked on top of eachother.\n",
"* **MLP Head** - This is the output layer of the architecture, it converts the learned features of an input to a class output. Since we're working on image classification, you could also call this the \"classifier head\". The structure of the MLP Head is similar to the MLP block.\n",
"\n",
"You might notice that many of the pieces of the ViT architecture can be created with existing PyTorch layers.\n",
"\n",
"This is because of how PyTorch is designed, it's one of the main purposes of PyTorch to create reusable neural network layers for both researchers and machine learning practitioners.\n",
"\n",
"> **Question:** Why not code everything from scratch?\n",
">\n",
"> You could definitely do that by reproducing all of the math equations from the paper with custom PyTorch layers and that would certainly be an educative exercise, however, using pre-existing PyTorch layers is usually favoured as pre-existing layers have often been extensively tested and performance checked to make sure they run correctly and fast. \n",
"\n",
"> **Note:** We're going to focused on write PyTorch code to create these layers, for the background on what each of these layers does, I'd suggest reading the ViT Paper in full or reading the linked resources for each layer.\n",
"\n",
"Let's take Figure 1 and adapt it to our FoodVision Mini problem of classifying images of food into pizza, steak or sushi.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-figure-1-inputs-and-outputs-food-mini.png\" width=900 alt=\"figure 1 from the original vision transformer paper adapted to work with food images, an image of pizza goes in and gets classified as 'pizza'\"/>\n",
"\n",
"*Figure 1 from the ViT Paper adapted for use with FoodVision Mini. An image of food goes in (pizza), the image gets turned into patches and then projected to an embedding. The embedding then travels through the various layers and blocks and (hopefully) the class \"pizza\" is returned.*"
]
},
{
"cell_type": "markdown",
"id": "add31aa8-2809-4f77-b94c-e34d865c12d0",
"metadata": {},
"source": [
"#### TK - 3.2.2 Exploring the Four Equations\n",
"\n",
"The next main part(s) of the ViT paper we're going to look at are the four equations in section 3.1.\n",
"| **Equation number** | **Description from ViT paper section 3.1** | \n",
"| ----- | ----- | \n",
"| 1 | ...The Transformer uses constant latent vector size $D$ through all of its layers, so we flatten the patches and map to $D$ dimensions with a **trainable linear projection** (Eq. 1). We refer to the output of this projection as the **patch embeddings**. |\n",
"| 2 | The Transformer encoder (Vaswani et al., 2017) consists of alternating layers of multiheaded selfattention (MSA, see Appendix A) and MLP blocks (Eq. 2, 3). **Layernorm (LN) is applied before every block**, and **residual connections after every block** (Wang et al., 2019; Baevski & Auli, 2019). |\n",
"| 3 | See above. |\n",
"| 4 | Similar to BERT's [ class ] token, we **prepend a learnable embedding to the sequence of embedded patches** $\\left(\\mathbf{z}_{0}^{0}=\\mathbf{x}_{\\text {class }}\\right)$, whose state at the output of the Transformer encoder $\\left(\\mathbf{z}_{L}^{0}\\right)$ serves as the image representation $\\mathbf{y}$ (Eq. 4)... |\n",
"\n",
"Let's map these descriptions to the ViT architecture in Figure 1.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-mapping-the-four-equations-to-figure-1.png\" width=1000 alt=\"mapping the vision transformer paper figure 1 to the four equations listed in the paper\"/>\n",
"\n",
"*Connecting Figure 1 from the ViT paper to the four equations from section 3.1 describing the math behind each of the layers/blocks. Some details such as \"residual connections after every block\" are referred to in Figure 1 and in the text but not in the equations.*\n",
"\n",
"There's a lot happening in the image above but following the coloured lines and arrows reveals the main concepts of the ViT architecture.\n",
"\n",
"How about we break down each equation further (it will be our goal to recreate these with code)?\n",
"\n",
"In all equations (except equation 4), \"$\\mathbf{z}$\" is the raw output of a particular layer:\n",
"\n",
"1. $\\mathbf{z}_{0}$ is \"z zero\" (this is the output of the initial patch embedding layer)\n",
"2. $\\mathbf{z}_{\\ell}^{\\prime}$ is \"z of a particular layer *prime*\" (or an intermediary value of z)\n",
"3. $\\mathbf{z}_{\\ell}$ is \"z of a particular layer\"\n",
"\n",
"And $\\mathbf{y}$ is the overall output of the architecture.\n",
"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",
"\\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",
"y = LN_layer(Linear_layer(x_output_MLP_block[0]))\n",
"```\n",
"\n",
"Of course there are some simplifications above but we'll take care of those when we start to write PyTorch code for each section.\n",
"\n",
"> **Note:** The above section covers alot of information. But don't forget if something doesn't make sense, you can always research it further. By asking questions like \"what is a residual connection?\"."
]
},
{
"cell_type": "markdown",
"id": "cd36899e-5bc7-411a-aab7-28e3a5a2c6cb",
"metadata": {},
"source": [
"#### TK - 3.2.3 Exploring Table 1\n",
"\n",
"The final piece of the ViT architecture puzzle we'll focus on (for now) is Table 1.\n",
"We're going to focus on replicating ViT-Base (start small and scale up when necessary) but we'll be writing code that could easily scale up to the larger variants.\n",
"\n",
"Breaking the hyperparameters down:\n",
"* **Layers** - How many Transformer encoder blocks are there? (each of these will contain a MSA block and MLP block)\n",
"* **Hidden size $D$** - This is the embedding dimension throughout the architecture, this will be the size of the vector that our image gets turned into when it gets patched and embedded. Generally, the larger the embedding dimension, the more information can be captured, the better results. However, a larger embedding comes at the cost of more compute.\n",
"* **MLP size** - What are the number of hidden units in the MLP layers?\n",
"* **Heads** - How many heads are there in the Multi-Head Attention layers?\n",
"* **Params** - What are the total number of parameters of the model? Generally, more parameters leads to better performance but at the cost of more compute. You'll notice even ViT-Base has far more parameters than any other model we've used so far.\n",
"\n",
"We'll use these values as the hyperparameter settings for our ViT architecture. "
"### TK - 3.3 My workflow for replicating papers\n",
"\n",
"When I start working on replicating a paper, I go through the following steps:\n",
"\n",
"1. Read the whole paper end-to-end once (to get an idea of the main concepts).\n",
"2. Go back through each section and see how they line up with each other and start thinking about how they might be turned into code (just like above).\n",
"3. Repeat step 2 until I've got a fairly good outline.\n",
"4. Use [mathpix.com](https://mathpix.com/) (a very handy tool) to turn any sections of the paper into markdown/LaTeX to put into notebooks.\n",
"5. Replicate the simplest version of the model possible.\n",
"6. If I get stuck, look up other examples.\n",
"\n",
"TK - gif of mathpix\n",
"\n",
"We've already gone through the first few steps above (and if you haven't read the full paper yet, I'd encourage you to give it a go) but what we'll be focusing on next is step 5: replicating the simplest version fo the model possible.\n",
"\n",
"This is why we're starting with ViT-Base.\n",
"\n",
"Replicating the smallest version of the architecture possible, get it working and then we can scale up if we wanted to.\n",
"\n",
"> **Note:** If you've never read a research paper before, many of the above steps can be intimidating. But don't worry, like anything, your skills at reading *and* replicating papers will improve with practice. Don't forget, a research paper is often *months* of work by many people compressed into a few pages. So trying to replicate it on your own is no small feat. "
]
},
{
"cell_type": "markdown",
"id": "9f1717f5-f6bc-4cce-b5eb-093822da988d",
"metadata": {
"tags": []
},
"source": [
"## TK 4. Equation 1: Split data into patches and creating the class, position and patch embedding \n",
"\n",
"I remember one of my machine learning engineer friends used to say \"it's all about the embedding.\"\n",
"\n",
"As in, if you can represent your data in a good, learnable way (as embeddings are learnable representations), chances are a learning algorithm will be able to perform well on them.\n",
"\n",
"So with that being said, let's start by creating the class, position and patch embeddings for the ViT architecture.\n",
"Recall that an **embedding** is a learnable representation of some form and is often a vector. The term learnable is important because this means the representation of an input image can be improved and learned over time.\n",
"> 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",
"* $D$ is the size of the **patch embeddings**, different values for $D$ can be found in Table 1.\n",
"* The image starts as 2D with size ${H \\times W \\times C}$.\n",
"* The image gets converted to a sequence of flattened 2D patches with size ${N \\times\\left(P^{2} \\cdot C\\right)}$.\n",
" * $(H, W)$ is the resolution of the original image.\n",
" * $C$ is the number of channels.\n",
" * $(P, P)$ is the resolution of each image patch (**patch size**).\n",
" * $N=H W / P^{2}$ is the resulting number of patches, which also serves as the effective input sequence length for the Transformer.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-annotated.png\" width=900 alt=\"mapping the vit architecture diagram positional and patch embeddings portion to the relative mathematical equation describing what's going on\"/>\n",
"\n",
"*Mapping the patch and position embedding portion of the ViT architecture from Figure 1 to Equation 1. The opening paragraph of section 3.1 describes the different input and output shapes of the patch embedding layer.*"
]
},
{
"cell_type": "markdown",
"id": "2010c168-88c7-4045-8c02-8e759ffacef8",
"metadata": {
"tags": []
},
"source": [
"### TK - 4.1 Calculating patch embedding input and output shapes by hand\n",
"\n",
"How about we start by calculating these input and output shape values by hand?\n",
"\n",
"To do so, let's create some variables to mimic each of the terms (such as $H$, $W$ etc) above.\n",
"\n",
"We'll use a patch size ($P$) of 16 since it's the best performing version of ViT-Base uses (see column \"ViT-B/16\" of Table 5 in the ViT paper for more)."
"Now how do we turn each of these patches into an embedding and convert them into a sequence?\n",
"\n",
"Hint: we can use PyTorch layers. Can you guess which?"
]
},
{
"cell_type": "markdown",
"id": "f774b58d-7095-4272-aba3-fd9a2db4f28f",
"metadata": {},
"source": [
"### TK - 4.3 Creating image patches with `torch.nn.Conv2d()`\n",
"\n",
"It's time to start moving towards replicating the patch embedding layers with PyTorch.\n",
"\n",
"To visualize our single image we wrote code to loop through the different height and width dimensions of a single image and plot individual patches.\n",
"\n",
"This operation is very similar to the convolutional operation we saw in [03. PyTorch Computer Vision section 7.1: Stepping through `nn.Conv2d()`](https://www.learnpytorch.io/03_pytorch_computer_vision/#71-stepping-through-nnconv2d).\n",
"\n",
"In fact, the authors of the ViT paper mention in section 3.1 that the patch embedding is achievable with a convolutional neural network (CNN): \n",
"\n",
"> **Hybrid Architecture.** As an alternative to raw image patches, the input sequence can be formed from feature maps of a CNN (LeCun et al., 1989). In this hybrid model, the patch embedding projection $\\mathbf{E}$ (Eq. 1) is applied to patches extracted from a **CNN feature map**. As a special case, the patches can have spatial size $1 \\times 1$, which means that the **input sequence is obtained by simply flattening the spatial dimensions of the feature map and projecting to the Transformer dimension**. The classification input embedding and position embeddings are added as described above.\n",
"\n",
"The \"**feature map**\" they're refering to are the weights/activations produced by a convolutional layer passing over a given image.\n",
"\n",
"<img src=\"https://github.com/mrdbourke/pytorch-deep-learning/raw/main/images/08-vit-paper-patch-embedding-animation.gif\" width=900 alt=\"example of creating a patch embedding by passing a convolutional layer over a single image\"/>\n",
"\n",
"*By setting the `kernel_size` and `stride` parameters of a [`torch.nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) layer equal to the `patch_size`, we can effectively get a layer that splits our image into patches and creates a learnable embedding (referred to as a \"Linear Projection\" in the ViT paper) of each patch.* \n",
"\n",
"Remember our ideal input and output shapes for the patch embedding layer?\n",
"\n",
"* **Input:** The image starts as 2D with size ${H \\times W \\times C}$.\n",
"* **Output:** The image gets converted to a sequence of flattened 2D patches with size ${N \\times\\left(P^{2} \\cdot C\\right)}$.\n",
"\n",
"Or for an image size of 224 and patch size of 16:\n",
"* [`torch.nn.Conv2d()`](https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html) for turning our image into patches of CNN feature maps.\n",
"* [`torch.nn.Flatten()`](https://pytorch.org/docs/stable/generated/torch.nn.Flatten.html) for flattening the spatial dimensions of the feature map.\n",
"\n",
"Let's start with the `torch.nn.Conv2d()` layer.\n",
"\n",
"We can replicate the creation of patches by setting the `kernel_size` and `stride` equal to `patch_size`.\n",
"\n",
"This means each convolutional kernel will be of size `(patch_size x patch_size)` or if `patch_size=16`, `(16 x 16)` (the equivalent of one whole patch) \n",
"\n",
"And each step or `stride` of the convolutional kernel will be `patch_size` pixels long or `16` pixels long (equivalent of stepping to the next patch).\n",
"\n",
"We'll set `in_channels=3` for the number of color channels in our image and we'll set `out_channels=768`, the same as the $D$ value in Table 1 for ViT-Base (this is the embedding dimension, each image will be embedded into a vector of size 768)."
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "3d4fd046-6b51-4ac0-8d39-e67fb333a18a",
"metadata": {},
"outputs": [],
"source": [
"from torch import nn\n",
"\n",
"# Set the patch size\n",
"patch_size=16\n",
"\n",
"# Create the Conv2d layer with hyperparameters from the ViT paper\n",
"conv2d = nn.Conv2d(in_channels=3, # number of color channels\n",
" out_channels=768, # from Table 1: Hidden size D, this is the embedding size\n",
" kernel_size=patch_size, # could also use (patch_size, patch_size)\n",
" stride=patch_size,\n",
" padding=0)"
]
},
{
"cell_type": "markdown",
"id": "03dec513-eea5-4d13-b7ab-41c9e997ef48",
"metadata": {},
"source": [
"Now we've got a convoluational layer, let's see what happens when we pass a single image through it."
"Notice how the feature maps all kind of represent the original image, visualizing a few you can see the different major outlines and some major features.\n",
"\n",
"The important thing to note is that these features may change over time as the neural network learns.\n",
"\n",
"And because of these, these feature maps can be considered a **learnable embedding** of our image.\n",
"The `grad_fn` output of the `single_feature_map` and the `required_grad=True` attribute means PyTorch is tracking the gradients of this feature map and it will be updated by gradient descent during training. "
]
},
{
"cell_type": "markdown",
"id": "572ae1c5-9488-4882-bdc1-409eef95424e",
"metadata": {},
"source": [
"### TK - 4.4 Flattening the patch embedding with `torch.nn.Flatten()`\n",
"\n",
"We've turned our image into patch embeddings but they're still in 2D format.\n",
"\n",
"How do we get them into the desired output shape of the patch embedding layer of the ViT model?\n",
"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",
"TK image - single image -> conv2d -> flatten -> get the output above (show the workflow and transformation, this could be the gif we've but using but extended to work with the flatten section)\n",
"\n",
"> **Note:** The [original Transformer architecture](https://arxiv.org/abs/1706.03762) was designed to work with text. The Vision Transformer architecture (ViT) had the goal of using the original Transformer for images. This is why the input to the ViT architecture is processed in the way it is. We're essentially taking a 2D image and formatting it so it appears as a 1D sequence of text. \n",
"\n",
"How about we view the flattened feature map in tensor form?"
"We've turned our single 2D image into a single 1D learnable embedding vector (or \"Linear Projection of Flattned Patches\" in Figure 1 of the ViT paper)."
]
},
{
"cell_type": "markdown",
"id": "b165987a-8370-471a-a663-711e0c6e60db",
"metadata": {},
"source": [
"### TK - 4.5 Turning the ViT patch embedding layer into a PyTorch module\n",
"\n",
"Time to put everything we've done for creating the patch embedding into a single PyTorch layer.\n",
"\n",
"We can do so by subclassing `nn.Module` and creating a small PyTorch \"model\" to do all of the steps above.\n",
"\n",
"Specifically we'll:\n",
"1. Create a class called `PatchEmbedding` which subclasses `nn.Module` (so it can be used a PyTorch layer).\n",
"2. Initialize the class with the parameters `in_channels=3`, `patch_size=16` (for ViT-Base) and `embedding_dim=768` (this is $D$ for ViT-Base from Table 1).\n",
"3. Create a layer to turn an image into patches using `nn.Conv2d()` (just like in 4.3 above).\n",
"4. Create a layer to flatten the patch feature maps into a single dimension (just like in 4.4 above). \n",
"5. Define a `forward()` method to take an input and pass it through the layers created in 3 and 4.\n",
"6. Make sure the output shape reflects the required output shape of the ViT architecture (${N \\times\\left(P^{2} \\cdot C\\right)}$).\n",
"*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."
"### TK 4.6 Creating the class token embedding\n",
"\n",
"Okay we've made the image patch embedding, time to get to work on the class token embedding.\n",
"\n",
"Or $\\mathbf{x}_\\text {class }$ from equation 1.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-the-class-token.png\" width=900 alt=\"class token embedding highlight from the vision transformer paper figure 1 and section 3.1\"/>\n",
"\n",
"*Left: Figure 1 from the ViT paper with the \"classification token\" or `[class]` embedding token we're going to recreate highlighted. Right: Equation 1 and section 3.1 of the ViT paper that relate to the learnable class embedding token.*\n",
"\n",
"Reading the second paragraph of section 3.1 from the ViT paper, we see the following description: \n",
"\n",
"> Similar to BERT's `[ class ]` token, we prepend a learnable embedding to the sequence of embedded patches $\\left(\\mathbf{z}_{0}^{0}=\\mathbf{x}_{\\text {class }}\\right)$, whose state at the output of the Transformer encoder $\\left(\\mathbf{z}_{L}^{0}\\right)$ serves as the image representation $\\mathbf{y}$ (Eq. 4). \n",
"\n",
"> **Note:** [BERT](https://arxiv.org/abs/1810.04805) (Bidirectional Encoder Representations from Transformers) is one of the original machine learning research papers to use the Transformer architecture to achieve outstanding results on natural language processing (NLP) tasks and is where the idea of having a `[ class ]` token at the start of a sequence originated, class being a description for the \"classification\" class the sequence belonged to.\n",
"\n",
"So we need to \"preprend a learnable embedding to the sequence of embedded patches\".\n",
"\n",
"Let's start by viewing our sequence of embedded patches tensor (created in 4.5) and its shape."
"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) (start with a random number). \n",
"\n",
"See how the `number_of_patches` dimension of `class_token` is `1` since we only want to prepend one class token value to the start of the patch embedding sequence.\n",
"\n",
"Now we've got the class token embedding, let's prepend it to our sequence of image patches, `patch_embedded_image`.\n",
"\n",
"We can so using [`torch.cat()`](https://pytorch.org/docs/stable/generated/torch.cat.html) and set `dim=1` (so `class_token`'s `number_of_patches` dimension is preprended to `patch_embedded_image`'s `number_of_patches` dimension)."
"print(f\"Sequence of patch embeddings with class token prepended shape: {patch_embedded_image_with_class_embedding.shape} -> [batch_size, number_of_patches, embedding_dimension]\")"
]
},
{
"cell_type": "markdown",
"id": "79fd9252-c15e-40a6-965a-a872e0e09cab",
"metadata": {},
"source": [
"Nice! Learnable class token prepended!\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-prepending-the-learnable-class-token.png\" width=900 alt=\"going from a sequence of patch embeddings, creating a learnable class token and then prepending it to the patch embeddings\"/>\n",
"\n",
"*Reviewing what we've done to create the learnable class token, we start with a sequence of image patch embeddings created by `PatchEmbedding()` on single image, we then created a learnable class token with one value for each of the embedding dimensions and then prepended it to the original sequence of patch embeddings. Note: Using `torch.ones()` to create the learnable class token is mostly for demonstration purposes only, in practice, you'd like create it with `torch.randn()`.* "
]
},
{
"cell_type": "markdown",
"id": "48502c61-16b0-4659-b95f-0e830ae93077",
"metadata": {},
"source": [
"### TK 4.7 Creating the position embedding \n",
"\n",
"Well, we've got the class token embedding and the patch embedding, now how might we create the position embedding?\n",
"\n",
"Or $\\mathbf{E}_{\\text {pos }}$ from equation 1 where $E$ stands for \"embedding\".\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-the-position-embeddings.png\" width=900 alt=\"extracting the position embeddings from the vision transformer architecture and comparing them to other sections of the vision transformer paper\"/>\n",
"\n",
"*Left: Figure 1 from the ViT paper with the position embedding we're going to recreate highlighted. Right: Equation 1 and section 3.1 of the ViT paper that relate to the position embedding.*\n",
"\n",
"Let's find out more by reading section 3.1 of the ViT paper (bold mine):\n",
"\n",
"> Position embeddings are added to the patch embeddings to retain positional information. We use **standard learnable 1D position embeddings**, since we have not observed significant performance gains from using more advanced 2D-aware position embeddings (Appendix D.4). The resulting sequence of embedding vectors serves as input to the encoder.\n",
"\n",
"To start creating the position embeddings, let's view our current embeddings. "
"> **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": {},
"source": [
"Notice how the values of each of the elements in the embedding tensor increases by 1 (this is because of the position embeddings being created with `torch.ones()`). \n",
"\n",
"> **Note:** We could put both the class token embedding and position embedding into their own layer if we wanted to. But we'll see later on how they can be incorporated into the overall ViT architecture's `forward()` method.\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-1-patch-embeddings-with-learnable-class-token-and-position-embeddings.png\" width=900 alt=\"patch embeddings with learnable class token and position embeddings\"/>\n",
"\n",
"*The workflow we've used for adding the position embeddings to the sequence of patch embeddings and class token. Note: `torch.ones()` only used to create embeddings for illustration purposes, in practice, you'd likely use `torch.randn()` to start with a random number.*"
"### TK 4.8 Putting it all together: from image to embedding\n",
"\n",
"Alright, we've come a long way in terms of turning our input images into an embedding and replicating equation 1 from section 3.1 of the ViT paper:\n",
"<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",
"*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",
"This indicates a Multi-Head Attention (MSA) layer wrapped in a LayerNorm (LN) layer with a residual connection (the input to the layer gets added to the output).\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-2-msa-block-mapped-to-equation.png\" alt=\"mapping equation 2 from the ViT paper to the ViT architecture diagram in figure 1\" width=900/> \n",
"\n",
"*Left: Figure 1 from the ViT paper with Multi-Head Attention and Norm layers as well as the residual connection (+) highlighted within the Transformer Encoder block. Right: Mapping the Multi-Head Self Attention (MSA) layer, Norm layer and residual connection to their respective parts of equation 2 in the ViT paper.*\n",
"\n",
"Many layers you find in research papers are already implemented in modern deep learning frameworks such as PyTorch.\n",
"\n",
"In saying this, to replicate these layers and residual connection with PyTorch code we can use:\n",
"[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",
"You can set `normalized_shape` to be equal to the dimension size you'd like to noramlize over (in our case it'll be $D$ or `768` for ViT-Base).\n",
"\n",
"You can find the formal definition of `torch.nn.LayerNorm()` in the [PyTorch documentation](https://pytorch.org/docs/stable/generated/torch.nn.LayerNorm.html).\n",
"\n",
"What does it do?\n",
"\n",
"Layer Normalization helps improve training time and model generalization (ability to adapt to unseen data).\n",
"\n",
"I like to think of any kind of normalization as \"getting the data into a similar format\" or \"getting data samples into a similar distribution\".\n",
"\n",
"Imagine trying to walk up (or down) a set of stairs all with differing heights and lengths.\n",
"\n",
"It'd take some adjustment each step right?\n",
"\n",
"And what you learn for each step wouldn't necessary help with the next one since they all differ.\n",
"\n",
"Normalization (including Layer Normalization) is the equivalent of making all the stairs the same height and length except the stairs are your data samples.\n",
"\n",
"So just like you can walk up (or down) stairs with similar heights and lengths much easier than those with unequal heights and widths, neural networks can optimize over data samples with similar distributions (similar mean and standard-deviations) easier than those with varying distributions. "
"### 5.2 The Multi-Head Self Attention (MSA) layer \n",
"\n",
"The power of the self-attention and multi-head attention (self-attention applied multiple times) were revealed in the form of the original Transformer architecture introduced in the [*Attention is all you need*](https://arxiv.org/abs/1706.03762) research paper.\n",
"\n",
"There are many resources online to learn more about the Transformer architeture and attention mechanism online such as Jay Alammar's wonderful [Illustrated Transformer post](https://jalammar.github.io/illustrated-transformer/) and [Illustrated Attention post](https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/).\n",
"\n",
"But we're going to focus more on coding an existing PyTorch MSA implementation than creating our own.\n",
"\n",
"However, you can find the formal defintion of the ViT paper's MSA implementation is defined in Appendix A:\n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-2-appendix-A.png\" alt=\"vision transformer paper figure 1 highlighted with equation 2 and appendix A\" width=900/>\n",
"\n",
"*Left: Vision Transformer architecture overview from Figure 1 of the ViT paper. Right: Definitions of equation 2, section 3.1 and Appendix A of the ViT paper highlighted to reflect their respective parts in Figure 1.*\n",
"\n",
"The image above highlights the triple input to the MSA layer.\n",
"\n",
"This is known as **query, key, value** input or **qkv** for short which is fundamental to the self-attention mechanism.\n",
"\n",
"In our case, the triple input will be three versions of the output of the Norm layer.\n",
"\n",
"Or three versions of our layer-normalized image patch and position embeddings created in section 4.8.\n",
"\n",
"We can implement the MSA layer in PyTorch with `torch.nn.MultiheadAttention()` with the parameters:\n",
"* `embed_dim` - the embedding dimension from Table 1 (Hidden size $D$).\n",
"* `num_heads` - how many attention heads to use (this is where the term \"multihead\" comes from), this value is also in Table 1 (Heads).\n",
"* `dropout` - whether or not to apply dropout to the attention layer (according to Appendix B.1, dropout isn't used after the qkv-projections). "
"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."
"> **Note:** Unlike Figure 1, our `MultiheadSelfAttentionBlock()` doesn't include a skip or residual connection (\"$+\\mathbf{z}_{\\ell-1}$\" in equation 2), we'll include this when we create the entire Transformer encoder later on. \n",
"\n",
"MSABlock created! \n",
"\n",
"Let's try it out by create an instance of our `MultiheadSelfAttentionBlock` and passing through the `patch_and_position_embedding` variable we created in section 4.8."
"Notice how the input and output shape of our data stays the same when it goes through the MSA block.\n",
"\n",
"This doesn't mean the data doesn't change as it goes through.\n",
"\n",
"You could try printing the input and output tensor to see how it changes (though this change will be across `1 * 197 * 768` values). \n",
"\n",
"<img src=\"https://raw.githubusercontent.com/mrdbourke/pytorch-deep-learning/main/images/08-vit-paper-equation-2-in-code.png\" width=900 alt=\"vision transformer paper with equation 2 of figure 1 highlighted and equation 2 turned into code\"/>\n",
"\n",
"*Left: Vision Transformer architecture from Figure 1 with Multi-Head Attention and LayerNorm layers highlighted, these layers make up equation 2 from section 3.1 of the paper. Right: Replicating equation 2 (without the skip connection on the end) using PyTorch layers.* \n",
"\n",
"We've now officially replicated equation 2 (except for the residual connection on the end but we'll get to this in section 7)!\n",
"* Replicate equation 3 like replicating equation 2\n",
"\n",
"* TK also called \"feedforward\" \n",
"\n",
"> Dropout, when used, is applied **after every dense layer except for the the qkv-projections and directly after adding positional- to patch embeddings.**\n",
"device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
"rand_image = torch.randn(1, 3, 224, 224)\n",
"# vit = ViT(num_classes=len(class_names)) \n",
"vit = ViT(num_classes=3)\n",
"vit(rand_image)"
]
},
{
"cell_type": "markdown",
"id": "2c0a0c9c-6d98-47fd-a152-8a06be99b5fa",
"metadata": {},
"source": [
"## TK 9. Inspect the model\n",
"\n",
"> **Note:** If you go too big, your hardware might not be able to handle it... (e.g. too high of a batch size...)\n",
"\n",
"TK - Number of parameters should be equivalent to: https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16 (`num_params=86,567,656`)"
"* TK - same number of parameters as: https://pytorch.org/vision/main/models/generated/torchvision.models.vit_b_16.html#torchvision.models.vit_b_16 -> 86567656"
"* See the illustrated transformer for an overview of the Transformer model: https://jalammar.github.io/illustrated-transformer/ + https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/\n",
"* Attention is all you need paper - Yannic video\n",