Zero Labs
Industry News / AI

Paper Replicating: Vision Transformer with PyTorch — Part 1-Create Embeddings

Source · Towards AI By tanta base

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

Paper Replicating: Vision Transformer with PyTorch — Part 1: Create EmbeddingsImage 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 and you will need a GPU to run 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. source👉When the ViT is training on mid-sized datasets, the model is more prone to overfitting. However, ViT did very well when trained on a large amount of images. This large amount of data reduces inductive bias. ViT has great results when pre-trained at sufficient scale and transferred to tasks with fewer datapoints.Create Patches, Class Token and Position EmbeddingIn this section, I will break down equation 1 from the paper:image created by author: graph and equation from ViTCreate PatchesTime for the first step, we will have to turn the images in a sequence of patches and then do the embeddings. From the paper:To handle 2D images, we reshape the image x ∈ R H×W×C into a sequence of flattened 2D patches xp ∈ R N×(P 2 ·C) , 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 = HW/P2 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.Breaking it down:image by authorConverted into PyTorch# 1. Create a class which subclasses nn.Moduleclass GetPatchEmbeddings(nn.Module): """Turns a 2D input image into a 1D sequence learnable embedding vector.Args: in_channels (int): Number of color channels for the input images. Defaults to 3. patch_size (int): Size of patches to convert input image into. Defaults to 16. embedding_dim (int): Size of embedding to turn image into. Defaults to 768.""" def __init__(self, # Three color channels in_channels:int=3, # 16 was the best performing amount of patches for vit-base in table 5 patch_size:int=16, # The hidden layers in table 1 for Vit-base embedding_dim:int=768): super().__init__() # Create a layer to turn an image into patches self.patcher = nn.Conv2d(in_channels=in_channels, out_channels=embedding_dim, kernel_size=patch_size, stride=patch_size, padding=0) # Flattening the spatial dimensions of the feature map. self.flatten = nn.Flatten(start_dim=2, end_dim=3) # Define the forward method def forward(self, x): # Perform the forward pass x_patched = self.patcher(x) x_flattened = self.flatten(x_patched) # 6. Make sure the output shape has the right order return x_flattened.permute(0, 2, 1) # adjust so the embedding is on the final dimension [batch_size, P^2•C, N] -> [batch_size, N, P^2•C]nn.ModuleEvery module in PyTorch subclasses the nn.Module. A neural network is a module itself that consists of other modules (layers). This nested structure allows for building and managing complex architectures easily.torch.nn.Conv2dThe operation uses a small matrix of learnable weights, called a kernel (or filter), which “slides” over the 2D input data. At each position, it performs an element-wise multiplication with the part of the input it is currently on and then sums up the results into a single output value (pixel).nn.FlattenThe primary role of nn.Flatten is to reshape the multi-dimensional output of convolutional/pooling layers into a one-dimensional vector, which is the required input format for nn.Linear (fully connected) layers.ForwardDefines the forward pass of a neural network. This method takes the input data x and processes it through the layers of the network to produce an output tensorPermutepermute() method is used to reorder the dimensions (axes) of a tensorAppend Class TokenIn order to make the network function as a transformer a class token needs to be added. Because Transformers operate on sequences, but classification needs one final vector (a summary), ViT needs a way to turn all patches of an image into one prediction. It acts like a placeholder that will learn to summarize the entire image. In ViT the class token is not computed from the image — it is a learnable parameter that is initialized randomly and trained jointly with the model, just like positional embeddings or weights in a neural layer.From the paper:Similar to BERT’s [class] token, we prepend a learnable embedding to the sequence of embedded patches (z 0 0 = xclass), whose state at the output of the Transformer encoder (z 0 L ) serves as the image representation y (Eq. 4). Both during pre-training and fine-tuning, a classification head is attached to z 0 L . The classification head is implemented by a MLP with one hidden layer at pre-training time and by a single linear layer at fine-tuning time.👉Learnable Embedding means the numerical representation of an input image can be improved over time. It is a low-dimensional, continuous vector representation of discrete data whose numerical values are automatically adjusted, or “learned,” during the training process of a machine learning modelConverted into PyTorch# Get a batch of imagesimage_batch, label_batch = next(iter(train_dataloader))# Get a single image from the batchimage, label = image_batch[0], label_batch[0]# Create an instance of patch embedding layercreate_patches = GetPatchEmbeddings(in_channels=3, patch_size=16, embedding_dim=768)# Pass a single image throughpatch_embedded_image = create_patches(image.unsqueeze(0)) # Get the batch size and embedding dimensionbatch_size,embedding_dimension = patch_embedded_image.shape[0], patch_embedded_image.shape[-1] # Create learnable class embedding (needs to go at front of sequence of patch embeddings)class_embedding = nn.Parameter(data=torch.randn(1, 1, embedding_dimension), requires_grad=True)patch_embedded_image_with_class_embedding = torch.cat((class_embedding, patch_embedded_image), dim=1) # concat on first dimensionnn.Parameter()Creates a learnable parameter tensor within a PyTorch neural network module. The torch.randn() part initializes this tensor with the random numbers, with the specified shape. We only want to prepend one class token value to the start of the patch embedding sequence.Add Position EmbeddingThe makers of ViT want to know what order the patches are coming in. This is important when the system tries to understand what is in the image. Without this information, the flattened sequence could be seen as having no order and no way to understand the patches as whole.From the paper: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.# Calculate N (number of patches)number_of_patches = int((height * width) / patch_size**2)# Get embedding dimensionembedding_dimension = patch_embedded_image_with_class_embedding.shape[2]# Create the learnable 1D position embeddingposition_embedding = nn.Parameter(torch.randn(1, number_of_patches+1, embedding_dimension), requires_grad=True) # make sure it's learnablepatch_and_position_embedding = patch_embedded_image_with_class_embedding + position_embeddingWell there you have it! We are about half way done with creating our own transformer! Stay tuned for the next part when we create the transformer encoder and for part three when we put it all together!Sources:08. PyTorch Paper Replicating - Zero to Mastery Learn PyTorch for Deep Learninghttps://medium.com/data-science/intuitively-understanding-convolutions-for-deep-learning-1f6f42faee1#:~:text=The%202D%20convolution%20is%20a,into%20a%20single%20output%20pixel.https://aws.amazon.com/what-is/embeddings-in-machine-learning/#:~:text=Embeddings%20are%20numerical%20representations%20of,needed%20to%20complete%20new%20tasks.https://medium.com/media/eb55fec9ce02bbebfe6abaed1c29df04/hrefhttps://www.learnpytorch.io/08_pytorch_paper_replicating/#45-turning-the-vit-patch-embedding-layer-into-a-pytorch-modulehttps://www.geeksforgeeks.org/deep-learning/understanding-the-forward-function-output-in-pytorch/Paper Replicating: Vision Transformer with PyTorch — Part 1-Create Embeddings was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.