Zero Labs
Industry News / AI

Paper Replicating: Vision Transformer with PyTorch — Part 2-Create Self Attention and Perceptron

Source · Towards AI By tanta base

From the publisher’s feed, collected in the ZeroLabs newsroom.

Paper Replicating: Vision Transformer with PyTorch — Part 2: Create Self-Attention and PerceptronImage by authorPreviously, the Transformer architecture has been the standard for Natural Language Processing tasks, Vision Transformer (ViT) aims to apply the same architecture to Computer Vision. Let’s have some fun and replicate the ViT architecture using PyTorch. We will be using the original publication, AN IMAGE IS WORTH 16X16 WORDS: TRANSFORMERS FOR IMAGE RECOGNITION AT SCALE as our guide. I highly recommend you read the paper first, just to give more information and context as we move forward.👉Due to compute restraints this will not be a 1:1 recreation of ViT. However, this will still be a great series on how to utilize PyTorch!👉Full code can be found here on github, you will need a GPU it!IntroductionA Computer Vision tasks rely on Convolutional Neural Networks (CNN) and these techniques remain dominant in the field. According to the paper, other researchers have tried to combine CNN-like architecture with self-attention, however these applications have not scaled effectively due to specialized attention patterns. The researchers experiment with applying the Transformer to images, using this methodology:Split an image into patches and create linear sequence of embeddings.Position embeddings and Class Tokens are added to the sequence.Sequence is the input to a Transformer Encoder.Transformer Encoder has a Multi-Head Attention block and a Multi-Layer Perceptron block.Use Supervised Learning to train ViTViT architecture explained. sourceMulti-Head Self Attention (MSA)Okay, before we dive further into the paper, we gotta take a step back and first briefly touch on the Attention Mechanism outlined in the original paper for Attention is All You Need.The self-attention mechanism enables the model to capture relationships among tokens in a sequence, so that each token’s representation is influenced by the others. Multiple attention heads allow the model to consider these relationships from different perspectives.The attention mechanism determines the importance of each component in a sequence relative to the other components in that sequence.For a set of input vectors, self-attention computers scores to understand how much attention or focus each element in the sequence should have on others. The matrices used in this computation are:Query (Q): Represents the current item’s relationship with others.Key (K): Represents the items that are being compared against.Value (V): Contains the actual item representations.👉I just wanted to add this here, in the paper MSA undergoes it’s own training. Since we are importing PyTorch’s MSA class we won’t need to do this, but just be aware that this is how MSA is trained.We employ the masked patch prediction objective for preliminary self-supervision experiments. To do so we corrupt 50% of patch embeddings by either replacing their embeddings with a learnable [mask] embedding (80%), a random other patch embedding (10%) or just keeping them as is (10%). This setup is very similar to the one used for language by Devlin et al. (2019). Finally, we predict the 3-bit, mean color (i.e., 512 colors in total) of every corrupted patch using their respective patch representations.Okay, now that we have sorted out, let’s return to our project!From the paper:Standard qkv self-attention (SA, Vaswani et al. (2017)) is a popular building block for neural architectures. For each element in an input sequence z ∈ R N×D, we compute a weighted sum over all values v in the sequence. The attention weights Aij are based on the pairwise similarity between two elements of the sequence and their respective query q i and key k j representations. [q, k, v] = zUqkv Uqkv ∈ R D×3Dh , (5) A = softmax qk>/ p Dh A ∈ R N×N , (6) SA(z) = Av . (7) Multihead self-attention (MSA) is an extension of SA in which we run k self-attention operations, called “heads”, in parallel, and project their concatenated outputs. To keep compute and number of parameters constant when changing k, Dh (Eq. 5) is typically set to D/k. MSA(z) = [SA1(z); SA2(z); · · · ; SAk(z)] Umsa Umsa ∈ R k·Dh×D (8)Our multi-head attention will calculate which patch of an image is most related to the other patches. This will form a learned representation of the image. Then a residual connection is the last step.Detailed below of Equation 2:If you’re feeling overwhelmed, don’t worry — PyTorch makes this so easy to implement. We got this!Converted into PyTorch# 1. Create a class that inherits from nn.Moduleclass MultiheadSelfAttentionBlock(nn.Module): """Creates a multi-head self-attention block ("MSA block" for short). """ # 2. Initialize the class with hyperparameters from Table 1 def __init__(self, embedding_dim:int=768, # Hidden size D from Table 1 for ViT-Base num_heads:int=12, # Heads from Table 1 for ViT-Base attn_dropout:float=0): # doesn't look like the paper uses any dropout in MSABlocks super().__init__() # 3. Create the Norm layer (LN) self.layer_norm = nn.LayerNorm(normalized_shape=embedding_dim) # 4. Create the Multi-Head Attention (MSA) layer self.multihead_attn = nn.MultiheadAttention(embed_dim=embedding_dim, num_heads=num_heads, dropout=attn_dropout, batch_first=True) # does our batch dimension come first? # 5. Create a forward() method to pass the data through the layers def forward(self, x): x = self.layer_norm(x) attn_output, _ = self.multihead_attn(query=x, # query embeddings key=x, # key embeddings value=x, # value embeddings need_weights=False) # do we need the weights or just the layer outputs? return attn_outputtorch.nn.LayerNormLayer Normalization helps improve training time and model generalization (ability to adapt to unseen data). It stabilizes and accelerates the training process in deep learning. In typical neural networks, activations of each layer can vary drastically which leads to issues like exploding or vanishing gradients which slow down training. Layer Normalization addresses this by normalizing the output of each layer which helps in ensuring that the activations stay within a stable range.nn.MultiheadAttentionThis MultiheadAttention layer implements the original architectureMultilayer Perceptron (MLP)Okay, let’s do a brief run down of MLP. It is another component of a Transformer block. It operates after the self-attention mechanism to transform and enrich the token representations. It plays a crucial role in helping the model transform and refine the representation of each token. It aids in non-linear representation learning, ability to detect complex patterns and expansion of dimensionality for richer features.Breaking down the architecture and the equation:image by authorThe paper mentions two facts about the MLP layer:The MLP contains two layers with a GELU non-linearity…We found strong regularization to be key when training models from scratch on ImageNet. Dropout, when used, is applied after every dense layer except for the the qkv-projections and directly after adding positional- to patch embeddings👉A linear layer is also known as a dense layer or feedforward layerSo what this means, is MLP has two linear layers, two dropout layers and an non-linear layer.Our architecture will look like this:image by authorBreaking down the equation:Converted into PyTorch# 1. Create a class that inherits from nn.Moduleclass MLPBlock(nn.Module): """Creates a layer normalized multilayer perceptron block ("MLP block" for short).""" # 2. Initialize the class with hyperparameters from Table 1 and Table 3 def __init__(self, embedding_dim:int=768, # Hidden Size D from Table 1 for ViT-Base mlp_size:int=3072, # MLP size from Table 1 for ViT-Base dropout:float=0.1): # Dropout from Table 3 for ViT-Base super().__init__() # 3. Create the Norm layer (LN) self.layer_norm = nn.LayerNorm(normalized_shape=embedding_dim) # 4. Create the Multilayer perceptron (MLP) layer(s) self.mlp = nn.Sequential( nn.Linear(in_features=embedding_dim, out_features=mlp_size), nn.GELU(), # "The MLP contains two layers with a GELU non-linearity (section 3.1)." nn.Dropout(p=dropout), nn.Linear(in_features=mlp_size, # needs to take same in_features as out_features of layer above out_features=embedding_dim), # take back to embedding_dim nn.Dropout(p=dropout) # "Dropout, when used, is applied after every dense layer.." ) # 5. Create a forward() method to pass the data through the layers def forward(self, x): x = self.layer_norm(x) x = self.mlp(x) return xnn.LinearApplies an affine linear transformation to the incoming data: y=xAT+by=xAT+b.nn.GELUApplies the Gaussian Error Linear Units function.nn.DropoutDuring training, randomly zeroes some of the elements of the input tensor. The zeroed elements are chosen independently for each forward call. This has proven to be an effective technique for regularization and preventing the co-adaptation of neurons.Putting it all together: Creating the EncoderTime to bring together the dynamic duo, MLP and MSA!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.From the paper: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).In addition, we will also add in the residual connections (mentioned earlier) into our block.Converted into PyTorch# 1. Create a class that inherits from nn.Moduleclass TransformerEncoderBlock(nn.Module): """Creates a Transformer Encoder block.""" # 2. Initialize the class with hyperparameters from Table 1 and Table 3 def __init__(self, embedding_dim:int=768, # Hidden size D from Table 1 for ViT-Base num_heads:int=12, # Heads from Table 1 for ViT-Base mlp_size:int=3072, # MLP size from Table 1 for ViT-Base mlp_dropout:float=0.1, # Amount of dropout for dense layers from Table 3 for ViT-Base attn_dropout:float=0): # Amount of dropout for attention layers super().__init__() # 3. Create MSA block (equation 2) self.msa_block = MultiheadSelfAttentionBlock(embedding_dim=embedding_dim, num_heads=num_heads, attn_dropout=attn_dropout) # 4. Create MLP block (equation 3) self.mlp_block = MLPBlock(embedding_dim=embedding_dim, mlp_size=mlp_size, dropout=mlp_dropout) # 5. Create a forward() method def forward(self, x): # 6. Create residual connection for MSA block (add the input to the output) x = self.msa_block(x) + x # 7. Create residual connection for MLP block (add the input to the output) x = self.mlp_block(x) + x return xHold up! It’s important to mention that PyTorch has it’s own Transformer class nn.TransformerEncoderLayer. So to expedite coding time, you can call the class with the same hyperparameters:# Create the same as above with torch.nn.TransformerEncoderLayer()torch_transformer_encoder_layer = nn.TransformerEncoderLayer(d_model=768, # Hidden size D from Table 1 for ViT-Base nhead=12, # Heads from Table 1 for ViT-Base dim_feedforward=3072, # MLP size from Table 1 for ViT-Base dropout=0.1, # Amount of dropout for dense layers from Table 3 for ViT-Base activation="gelu", # GELU non-linear activation batch_first=True, # Do our batches come first? norm_first=True) # Normalize first or after MSA/MLP layers?torch_transformer_encoder_layerWe are almost done!! This was a huge hurdle that was successfully completed. Up next is putting it all together and seeing how it stacks up to PyTorch’s torchvision.models version of ViT!Sources:https://docs.pytorch.org/docs/stable/generated/torch.nn.Dropout.htmlhttps://docs.pytorch.org/docs/stable/generated/torch.nn.Linear.htmlhttps://www.geeksforgeeks.org/deep-learning/what-is-layer-normalization/https://www.learnpytorch.io/08_pytorch_paper_replicating/#45-turning-the-vit-patch-embedding-layer-into-a-pytorch-modulehttps://poloclub.github.io/transformer-explainer/Paper Replicating: Vision Transformer with PyTorch — Part 2-Create Self Attention and Perceptron was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.