update 08 and log

This commit is contained in:
Daniel Bourke committed 2022-07-20 15:03:37 +10:00
1 parent 04bd68f1d9
commit 7f5976fb66
2 files changed
+269 -35

No files matched your search

+268 -35
View File
@@ -17,17 +17,16 @@
"source": [
"# (WIP) 08. PyTorch Paper Replicating\n",
"\n",
"TK intro\n",
"TK intro... welcome to Milestone Project 2!\n",
"\n",
"Want to recreate ViT paper: \"An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale\" - https://arxiv.org/abs/2010.11929 - TK will refer to this as \"ViT paper\" throughout.\n",
"\n",
"TODO: \n",
"* TK what is ViT?\n",
"\n",
"* TK - The name Transformer comes from the architecture name in the paper where it was originally introduced, [*Attention is all you need*](https://arxiv.org/abs/1706.03762). An architecture is usually considered a Transformer variant if it uses attention layers in a specific pattern. Since the Transformer architecture originally focused on text data, the goal of the ViT paper was to bring it to the vision.\n",
"\n",
"* TK - The original transformer was made to work on sequences of text (1D), Vision Transformer turns images into sequences of \"patches\".\n",
"\n",
"* TK - original ViT also called \"vanilla vision transformer\""
"* TK - original ViT also called \"vanilla vision transformer\"\n",
"* TK - Transformer can be generally defined any architecture that uses a form of the attention mechanism as part of its architecture. "
]
},
{
@@ -45,7 +44,7 @@
"\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",
"* 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 image: paper replicating = research paper (language + diagrams + math) -> code (turn language, diagrams and math into usable code) / (translate a research paper into usable code)\n"
]
},
{
@@ -127,6 +126,8 @@
"\n",
"TODO\n",
"\n",
"* TK - rather than talk about replicating a paper, we're going to hands-on and *actually* replicate a paper (Vision Transformer)\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",
"* 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 "
@@ -693,7 +694,7 @@
"| ----- | ----- | \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",
"| 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",
@@ -1906,7 +1907,7 @@
},
{
"cell_type": "code",
"execution_count": 29,
"execution_count": 49,
"id": "e440be53-d72c-42b8-87c8-1c31c4262c16",
"metadata": {},
"outputs": [
@@ -1932,7 +1933,7 @@
"========================================================================================================================"
]
},
"execution_count": 29,
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
@@ -1950,6 +1951,14 @@
" row_settings=[\"var_names\"])"
]
},
{
"cell_type": "markdown",
"id": "fa26d9f9-1cc4-4e20-b7e4-e214deef36db",
"metadata": {},
"source": [
"TK - turn summary into image"
]
},
{
"cell_type": "markdown",
"id": "8576f2f1-a2ad-4874-8f76-08156371f444",
@@ -2476,9 +2485,21 @@
"\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",
"\n",
"But what's most important is that the layer does this on it's own given the data (we don't tell it what patterns to learn).\n",
"\n",
"And if the learned representation the layers form using MSA are good, we'll see the results in our model's performance.\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",
"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",
@@ -2795,68 +2816,275 @@
"\n",
"Equation 3 replicated (except for the residual connection on the end but we'll get to this in section 7)!\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."
"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": "812ccd0a-554f-4722-9987-f03c079a269f",
"id": "6259bdc6-525a-4bd6-89e8-c2dcdab09d0d",
"metadata": {},
"source": [
"## TK 7. Create the Transformer Encoder \n",
"\n",
"UPTOHERE: combine equation's 2 and 3 to make the Transformer Encoder\n",
"Time to stack together our `MultiheadSelfAttentionBlock()` (equation 2) and `MLPBlock()` (equation 3) and create the Transformer Encoder of the ViT architecture.\n",
"\n",
"* Tk - what is an \"encoder\"?\n",
"* Tk - \"transformer block\" or \"transformer encoder\"? - line this up with the paper\n",
"* TK - replicate this with the TransformerEncoderLayer - https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/\n",
"* TK - See here for pre-built transformer blocks/layers: https://pytorch.org/docs/stable/nn.html#transformer-layers \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.\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, reading section 3.1 of the ViT Paper:\n",
"\n",
"TK - make a step by step playbook for the Transformer Encoder\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",
"\n",
"Or in pseudocode:\n",
"\n",
"`x_input -> MSA_block -> [MSA_block_output + x_input] -> MLP_block -> [MLP_block_output + MSA_block_output + x_input] -> ...`\n",
"\n",
"What does this do?\n",
"\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": {},
"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 `MLPBlock()` that inherits from `torch.nn.Module`.\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. 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)."
"3. Instantiate a MSA block for equation 2 using our `MultiheadSelfAttentionBlock()` with the appropriate parameters.\n",
"4. Instantiate a MLP block for equation 3 using our `MLPBlock()` with the appropriate parameters.\n",
"5. Create a `forward()` method for our `TransformerEncoderBlock()` class.\n",
"6. Create a residual connection for the MSA block (for equation 2).\n",
"7. Create a residual connection for the MLP block (for equation 3)."
]
},
{
"cell_type": "code",
"execution_count": 41,
"execution_count": 44,
"id": "2c43855c",
"metadata": {},
"outputs": [],
"source": [
"# 1. Create a class that inherits from nn.Module\n",
"class TransformerEncoderBlock(nn.Module):\n",
" \"\"\"Creates a Transformer Encoder block.\"\"\"\n",
" # TK add type annoations\n",
" # 2. Initialize the class with hyperparameters from Table 1 and Table 3\n",
" def __init__(self,\n",
" embedding_dim=768, # Hidden size D from Table 1 for ViT-Base\n",
" num_heads=12, # Heads from Table 1 for ViT-Base\n",
" mlp_size=3072, # MLP size from Table 1 for ViT-Base\n",
" mlp_dropout=0.1,\n",
" attn_dropout=0):\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:int=0.1, # Amount of dropout for dense layers from Table 3 for ViT-Base\n",
" attn_dropout:int=0): # Amount of dropout for attention layers\n",
" super().__init__()\n",
"\n",
" # Create MSA Block (for equation 2)\n",
" # 3. Create MSA block (equation 2)\n",
" self.msa_block = MultiheadSelfAttentionBlock(embedding_dim=embedding_dim,\n",
" num_heads=num_heads,\n",
" attn_dropout=attn_dropout)\n",
" # Create MLP Block (for equation 3)\n",
" \n",
" # 4. Create MLP block (equation 3)\n",
" self.mlp_block = MLPBlock(embedding_dim=embedding_dim,\n",
" mlp_size=mlp_size,\n",
" dropout=mlp_dropout)\n",
" \n",
" # 5. Create a forward() method \n",
" def forward(self, x):\n",
" x = self.msa_block(x) + x # Create skip connection\n",
" x = self.mlp_block(x) + x # Create skip connection\n",
" \n",
" # 6. Create residual connection MSA block (add the input to the output)\n",
" x = self.msa_block(x) + x \n",
" \n",
" # 7. Create residual connection for MLP block (add the input to the output)\n",
" x = self.mlp_block(x) + x \n",
" \n",
" return x"
]
},
{
"cell_type": "markdown",
"id": "b9199182-d14e-4c54-a391-7a53b6c78a44",
"metadata": {},
"source": [
"Beautiful!\n",
"\n",
"Transformer Encoder block created!\n",
"\n",
"UPTOHERE:\n",
"* TK image - transformer encoder block\n",
"\n",
"See how we're starting to piece together the overall architecture like legos, coding one brick (or equation) at a time.\n",
"\n",
"You might've noticed that Table 1 has a Layers column. This refers to the number of Transformer Encoder blocks in the specific ViT architecure.\n",
"\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": 55,
"id": "a63be4de-ffff-4fa1-97b8-103012797d36",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"============================================================================================================================================\n",
"Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n",
"============================================================================================================================================\n",
"TransformerEncoderBlock (TransformerEncoderBlock) [1, 197, 768] [1, 197, 768] -- True\n",
"├─MultiheadSelfAttentionBlock (msa_block) [1, 197, 768] [1, 197, 768] -- True\n",
"│ └─LayerNorm (layer_norm) [1, 197, 768] [1, 197, 768] 1,536 True\n",
"│ └─MultiheadAttention (multihead_attn) -- [1, 197, 768] 1,771,776 True\n",
"│ │ └─NonDynamicallyQuantizableLinear (out_proj) -- -- 590,592 True\n",
"├─MLPBlock (mlp_block) [1, 197, 768] [1, 197, 768] -- True\n",
"│ └─LayerNorm (layer_norm) [1, 197, 768] [1, 197, 768] 1,536 True\n",
"│ └─Sequential (mlp) [1, 197, 768] [1, 197, 768] -- True\n",
"│ │ └─Linear (0) [1, 197, 768] [1, 197, 3072] 2,362,368 True\n",
"│ │ └─GELU (1) [1, 197, 3072] [1, 197, 3072] -- --\n",
"│ │ └─Dropout (2) [1, 197, 3072] [1, 197, 3072] -- --\n",
"│ │ └─Linear (3) [1, 197, 3072] [1, 197, 768] 2,360,064 True\n",
"│ │ └─Dropout (4) [1, 197, 768] [1, 197, 768] -- --\n",
"============================================================================================================================================\n",
"Total params: 7,087,872\n",
"Trainable params: 7,087,872\n",
"Non-trainable params: 0\n",
"Total mult-adds (M): 4.73\n",
"============================================================================================================================================\n",
"Input size (MB): 0.61\n",
"Forward/backward pass size (MB): 8.47\n",
"Params size (MB): 21.26\n",
"Estimated Total Size (MB): 30.34\n",
"============================================================================================================================================"
]
},
"execution_count": 55,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create an instance of TransformerEncoderBlock\n",
"transformer_encoder_block = TransformerEncoderBlock()\n",
"\n",
"summary(model=transformer_encoder,\n",
" input_size=(1, 197, 768), # (batch_size, num_patches, embedding_dimension)\n",
" col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n",
" col_width=20,\n",
" row_settings=[\"var_names\"])"
]
},
{
"cell_type": "markdown",
"id": "fdf8796b-e3f5-4a23-912b-d1d7264287c3",
"metadata": {},
"source": [
"TK - turn summary into image\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."
]
},
{
"cell_type": "markdown",
"id": "8219d44e-0e17-4404-ac0e-45886bfda71e",
"metadata": {},
"source": [
"### TK 7.2 Creating a Transformer Encoder with PyTorch's Transformer layers \n",
"\n",
"UPTOHERE: \n",
"* TK - Can replicate the same with PyTorch's Transformer layers, recently been updated for inference:\n",
"* TK - replicate this with the TransformerEncoderLayer - https://pytorch.org/blog/a-better-transformer-for-fast-transformer-encoder-inference/\n",
"* TK - See here for pre-built transformer blocks/layers: https://pytorch.org/docs/stable/nn.html#transformer-layers "
]
},
{
"cell_type": "code",
"execution_count": 54,
"id": "eb2d60f2-1dd6-45ac-a6a6-1577af9160f8",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"==================================================================================================================================\n",
"Layer (type (var_name)) Input Shape Output Shape Param # Trainable\n",
"==================================================================================================================================\n",
"TransformerEncoderLayer (TransformerEncoderLayer) [1, 197, 768] [1, 197, 768] 3,072 True\n",
"├─LayerNorm (norm1) [1, 197, 768] [1, 197, 768] (recursive) True\n",
"├─MultiheadAttention (self_attn) [1, 197, 768] [1, 197, 768] 2,362,368 True\n",
"├─Dropout (dropout1) [1, 197, 768] [1, 197, 768] -- --\n",
"├─LayerNorm (norm2) [1, 197, 768] [1, 197, 768] (recursive) True\n",
"├─Linear (linear1) [1, 197, 768] [1, 197, 3072] 2,362,368 True\n",
"├─LayerNorm (norm1) [1, 197, 768] [1, 197, 768] (recursive) True\n",
"├─LayerNorm (norm2) [1, 197, 768] [1, 197, 768] (recursive) True\n",
"├─Dropout (dropout) [1, 197, 3072] [1, 197, 3072] -- --\n",
"├─Dropout (dropout2) [1, 197, 768] [1, 197, 768] -- --\n",
"├─Linear (linear2) [1, 197, 3072] [1, 197, 768] 2,360,064 True\n",
"├─Dropout (dropout2) [1, 197, 768] [1, 197, 768] -- --\n",
"==================================================================================================================================\n",
"Total params: 7,087,872\n",
"Trainable params: 7,087,872\n",
"Non-trainable params: 0\n",
"Total mult-adds (M): 4.73\n",
"==================================================================================================================================\n",
"Input size (MB): 0.61\n",
"Forward/backward pass size (MB): 6.05\n",
"Params size (MB): 18.89\n",
"Estimated Total Size (MB): 25.55\n",
"=================================================================================================================================="
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Create the same as above with torch.nn.TransformerEncoderLayer()\n",
"torch_transformer_encoder_layer = nn.TransformerEncoderLayer(d_model=768, # Hidden size D from Table 1 for ViT-Base\n",
" nhead=12, # Heads from Table 1 for ViT-Base\n",
" dim_feedforward=3072, # MLP size from Table 1 for ViT-Base\n",
" dropout=0.1, # Amount of dropout for dense layers from Table 3 for ViT-Base\n",
" activation=\"gelu\", # GELU non-linear activation\n",
" batch_first=True, # Do our batches come first?\n",
" norm_first=True) # Normalize first or after MSA/MLP layers?\n",
"\n",
"summary(model=torch_transformer_encoder_layer,\n",
" input_size=(1, 197, 768), # (batch_size, num_patches, embedding_dimension)\n",
" col_names=[\"input_size\", \"output_size\", \"num_params\", \"trainable\"],\n",
" col_width=20,\n",
" row_settings=[\"var_names\"])s"
]
},
{
"cell_type": "markdown",
"id": "aab22163-243b-44e5-a84e-01216b63d9d6",
"metadata": {},
"source": [
"TK - turn summary into image"
]
},
{
"cell_type": "markdown",
"id": "94f9041c-a0af-4fbe-8969-a2bde8637821",
@@ -3638,7 +3866,10 @@
"id": "04b1569b-117e-43fd-9e0b-324157cb82a4",
"metadata": {},
"source": [
"## TK - Exercises"
"## TK - Exercises\n",
"\n",
"* Replicate the architecture with PyTorch transformer layers - https://pytorch.org/docs/stable/nn.html#transformer-layers\n",
" * Use TransformerEncoderLayer + TransformerEncoder"
]
},
{
@@ -3648,7 +3879,9 @@
"source": [
"## TK - Extra-curriculum\n",
"\n",
"* layernorm\n",
"* Compact vision transformers explanation of attention + implementation on PyTorch blog\n",
"* ViT-PyTorch by LucidRains (many different implementations of Vision Transformers in PyTorch)\n",
"* layernorm resources\n",
"* See the illustrated transformer for an overview of the Transformer model: https://jalammar.github.io/illustrated-transformer/ + https://jalammar.github.io/visualizing-neural-machine-translation-mechanics-of-seq2seq-models-with-attention/\n",
"* Attention is all you need paper - Yannic video\n",
"* Vision transformer - yannic video\n",
+1
View File
@@ -119,6 +119,7 @@ Please leave a [discussion](https://github.com/mrdbourke/pytorch-deep-learning/d
Almost daily updates of what's happening.
* 20 July 2022 - add annotations and images for 08, getting so close! this is an epic section
* 19 July 2022 - add annotations and images for 08
* 15 July 2022 - add annotations and images for 08
* 14 July 2022 - add annotations for 08