Paper Replicating: Vision Transformer with PyTorch — Part 3-Putting it all Together
From the publisher’s feed, collected in the ZeroLabs newsroom.
Paper Replicating: Vision Transformer with PyTorch — Part 3-Putting it all TogetherImage 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 githubIntroductionA 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. sourcePutting it all TogetherOkay! We are almost at the end. In this section We will combine the pieces from section 1 and 2 to create our very own transformer!Step 1: Create patches, embeddings, class and position tokens:# 1. Create a class called PatchEmbeddingclass PatchEmbedding(nn.Module): # 2. Initilaize the layer with appropriate hyperparameters def __init__(self, in_channels:int=3, patch_size:int=16, embedding_dim:int=768): # from Table 1 for ViT-Base super().__init__() self.patch_size = patch_size # 3. Create a layer to turn an image into embedded patches self.patcher = nn.Conv2d(in_channels=in_channels, out_channels=embedding_dim, kernel_size=patch_size, stride=patch_size, padding=0) # 4. Create a layer to flatten feature map outputs of Conv2d self.flatten = nn.Flatten(start_dim=2, end_dim=3) # 5. Define a forward method to define the forward computation steps def forward(self, x): # Create assertion to check that inputs are the correct shape image_resolution = x.shape[-1] assert image_resolution % self.patch_size == 0, f"Input image size must be divisible by patch size, image shape: {image_resolution}, patch size: {self.patch_size}" # Perform the forward pass x_patched = self.patcher(x) x_flattened = self.flatten(x_patched) # 6. Make the returned sequence embedding dimensions are in the right order (batch_size, number_of_patches, embedding_dimension) return x_flattened.permute(0, 2, 1)Step 2: Create Multi-Head Self Attention and Multi-Layer Perceptron block:class TransformerEncoderBlock(nn.Module): def __init__(self, embedding_dim:int=768, # Hidden size D from table 1, 768 for ViT-Base num_heads:int=12, # from table 1 mlp_size:int=3072, # from table 1 mlp_dropout:int=0.1, # from table 3 attn_dropout:int=0): super().__init__() # Create MSA block (equation 2) self.msa_block = MultiHeadSelfAttentionBlock(embedding_dim=embedding_dim, num_heads=num_heads, attn_dropout=attn_dropout) # Create MLP block (equation 3) self.mlp_block = MLPBlock(embedding_dim=embedding_dim, mlp_size=mlp_size, dropout=mlp_dropout) def forward(self, x): x = self.msa_block(x) + x # residual/skip connection for equation 2 x = self.mlp_block(x) + x # residual/skip connection for equation 3 return xStep 3: Create the ViT Transformer:# 1. Create a ViT class that inherits from nn.Moduleclass ViT(nn.Module): """Creates a Vision Transformer architecture with ViT-Base hyperparameters by default.""" # 2. Initialize the class with hyperparameters from Table 1 and Table 3 def __init__(self, img_size:int=224, # Training resolution from Table 3 in ViT paper in_channels:int=3, # Number of channels in input image patch_size:int=16, # Patch size num_transformer_layers:int=12, # Layers from Table 1 for ViT-Base 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 num_heads:int=12, # Heads from Table 1 for ViT-Base attn_dropout:float=0, # Dropout for attention projection mlp_dropout:float=0.1, # Dropout for dense/MLP layers embedding_dropout:float=0.1, # Dropout for patch and position embeddings num_classes:int=1000): # Default for ImageNet but can customize this super().__init__() # don't forget the super().__init__()! # 3. Make the image size is divisible by the patch size assert img_size % patch_size == 0, f"Image size must be divisible by patch size, image size: {img_size}, patch size: {patch_size}." # 4. Calculate number of patches (height * width/patch^2) self.num_patches = (img_size * img_size) // patch_size**2 # 5. Create learnable class embedding (needs to go at front of sequence of patch embeddings) self.class_embedding = nn.Parameter(data=torch.randn(1, 1, embedding_dim), requires_grad=True) # 6. Create learnable position embedding self.position_embedding = nn.Parameter(data=torch.randn(1, self.num_patches+1, embedding_dim), requires_grad=True) # 7. Create embedding dropout value self.embedding_dropout = nn.Dropout(p=embedding_dropout) # 8. Create patch embedding layer self.patch_embedding = PatchEmbedding(in_channels=in_channels, patch_size=patch_size, embedding_dim=embedding_dim) # 9. Create Transformer Encoder blocks (we can stack Transformer Encoder blocks using nn.Sequential()) # Note: The "*" means "all" self.transformer_encoder = nn.Sequential(*[TransformerEncoderBlock(embedding_dim=embedding_dim, num_heads=num_heads, mlp_size=mlp_size, mlp_dropout=mlp_dropout) for _ in range(num_transformer_layers)]) # 10. Create classifier head self.classifier = nn.Sequential( nn.LayerNorm(normalized_shape=embedding_dim), nn.Linear(in_features=embedding_dim, out_features=num_classes) ) # 11. Create a forward() method def forward(self, x): # 12. Get batch size batch_size = x.shape[0] # 13. Create class token embedding and expand it to match the batch size (equation 1) class_token = self.class_embedding.expand(batch_size, -1, -1) # "-1" means to infer the dimension (try this line on its own) # 14. Create patch embedding (equation 1) x = self.patch_embedding(x) # 15. Concat class embedding and patch embedding (equation 1) x = torch.cat((class_token, x), dim=1) # 16. Add position embedding to patch embedding (equation 1) x = self.position_embedding + x # 17. Run embedding dropout (Appendix B.1) x = self.embedding_dropout(x) # 18. Pass patch, position and class embedding through transformer encoder layers (equations 2 & 3) x = self.transformer_encoder(x) # 19. Put 0 index logit through classifier (equation 4) x = self.classifier(x[:, 0]) # run on each sample in a batch at 0 index return xStep 4: Train and test:👉The original Vision Transformer (ViT) was pre-trained on very large image datasets to achieve competitive performance with CNNs. The key pre-training datasets used were:ImageNet-21k: A dataset containing 14 million images across 21,843 classes.JFT-300M: A proprietary Google dataset containing approximately 300 million images.After pre-training on one of these large datasets, the models were then fine-tuned on smaller, downstream datasets, such as the standard ImageNet (ILSVRC2012) dataset, which has about 1 million images. The success of ViT is highly dependent on this large-scale pre-training👉The paper used a batch size of 4096, which I am not be able to do. For this I used a batch size of 32, see below from the paper for more details on training hyperparameters.Training & Fine-tuning. We train all models, including ResNets, using Adam (Kingma & Ba, 2015) with β1 = 0.9, β2 = 0.999, a batch size of 4096 and apply a high weight decay of 0.1, which we found to be useful for transfer of all modelsfrom going_modular.going_modular import engine# Set the seed for general torch operationstorch.manual_seed(42)# Set the seed for CUDA torch operations (ones that happen on the GPU)torch.cuda.manual_seed(42)optimizer = torch.optim.Adam(vit.parameters(), lr=1e-3, betas=(0.9, 0.999), weight_decay=0.1)loss_fn = torch.nn.CrossEntropyLoss()results = engine.train(model=vit, train_dataloader=train_dataloader, test_dataloader=test_dataloader, epochs=10, optimizer=optimizer, loss_fn=loss_fn, device=device)Let’s plot the graphsSo what does mean?The model converged almost immediately and stopped improving. The accuracy is the same as a coin flip.Let’s see what the paper says:Finally, the ViT-L/16 model pre-trained on the public ImageNet-21k dataset performs well on most datasets too, while taking fewer resources to pre-train: it could be trained using a standard cloud TPUv3 with 8 cores in approximately 30 days.Meaning that, I do not have the resources to create a doppelganger of ViT. This is completely okay! For this, it’s not about the destination — it’s about the journey!Transfer Learning With PyTorchLet’s see how PyTorch’s ViT model performs.# Get pretrained weights for ViT-Basepretrained_vit_weights = torchvision.models.ViT_B_16_Weights.DEFAULT # requires torchvision >= 0.13, "DEFAULT" means best available# Setup a ViT model instance with pretrained weightspretrained_vit = torchvision.models.vit_b_16(weights=pretrained_vit_weights).to(device)# Freeze the base parametersfor parameter in pretrained_vit.parameters(): parameter.requires_grad = False# Change the classifier head (set the seeds to ensure same initialization with linear head)pretrained_vit.heads = nn.Linear(in_features=768, out_features=len(class_names)).to(device)# Get automatic transforms from pretrained ViT weightspretrained_vit_transforms = pretrained_vit_weights.transforms()from going_modular.going_modular import engine# Create optimizer and loss functionoptimizer = torch.optim.Adam(params=pretrained_vit.parameters(), lr=1e-3)loss_fn = torch.nn.CrossEntropyLoss()# Train the classifier head of the pretrained ViT feature extractor modelpretrained_vit_results = engine.train(model=pretrained_vit, train_dataloader=train_dataloader, test_dataloader=test_dataloader, optimizer=optimizer, loss_fn=loss_fn, epochs=10, device=device)Plot the testing and training graph:Loss curvesTraining loss drops steadily from 0.05 to 0.013. The model is fitting the training data better each epoch. Test loss drops at first, then flattens and slightly rises after epoch 4–5. Generalization stops improving. Meaning that the model continues memorizing training data, but gains on unseen data have peaked.Accuracy curvesTraining accuracy rises to 99.6%. Test accuracy peaks around 99.3–99.4%, then slowly declines.This looks like classic early overfitting! This won’t be something we address in this article. However, it’s really important that you can diagnose issues with your model so they can be addressed.And if we recall from the article:👉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.Meaning that, if we did want to address the overfitting we would have to use way more data than our current dataset.Wow! What a journey! So much was covered in this series and I hope you enjoyed it! Leave a comment below and let me know what you think!Sources:https://www.learnpytorch.io/08_pytorch_paper_replicating/#45-turning-the-vit-patch-embedding-layer-into-a-pytorch-modulePaper Replicating: Vision Transformer with PyTorch — Part 3-Putting it all Together was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.