CSE5023: Recent Advances in Deep Learning
Assignment 2: Transformer and its Applications
This assignment is designed to deepen your understanding of the Transformer architecture and its applications across various fields of deep learning (including language modeling and computer vision). You are expected to train and finetune Transformer models using PyTorch, analyze their performance, and compare different configurations.
1 Part I: Translation (50 points)
In the first part of this assignment, you will train a Transformer-based model from scratch for a translation task using PyTorch, focusing on translating English to Chinese. This is a sequence-to-sequence task, which means it’s a problem that can be formulated as going from one sequence to another. We will provide a big enough corpus of texts in two languages, so you can train a new translation model from scratch.
1.1 Transformer Architecture
Implement the Transformer architecture and the training procedure by completing the python files tokenization.py and model/transformer.py. In these files, ”TODO” annotations would notify you where to complete and how to do it. Transformer comprises two main components: an encoder and a decoder. Each component is built using layers of Transformer blocks. After completing the code, please write down in the report your thoughts and understanding of the architecture of the transformer. Specifically, your report should at least answer the following questions.
1. What are the differences between the encoder and the decoder in terms of their structure and function?
2. How the attention masks are implemented within the encoder and decoder? And explain in detail the moti- vation why we need the attention mask.
3. What are the differences between the training and inference for the decoder?
1.2 Training and BLEU Evaluation
Train your Transformer model from scratch and plot the training loss curve. During training, remember to save intermediate models at appropriate intervals for the following BLEU score evaluation. BLEU (Bilingual Evaluation Understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another. Quality is considered to be the correspondence between a machine’s output and that of a human: “the closer a machine translation is to a professional human translation, the better it is” — this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and remains one of the most popular automated and inexpensive metrics.
Implement the BLEU score evaluation script in chinese bleu.ipynb. For Chinese, word segmentation should be done before BLEU evaluation. We have provide an optional segmentation tool in the file. You should not only report the BLEU scores during validation process but also evaluate your final model on the test dataset. Additionally, list some examples of translation outputs from the test data in your report as specific illustrations of the model’s performance.
1.3 Warm-up and Learning Rate Tuning
Fix your training procedure with a new learning rate scheduler: Cosine Annealing with Warm-up. The learning rate would increase linearly in warm-up epochs and then gradually drop in a half of cosine curve. Tuning the learning rate and evaluating the BLEU to get the better performance.
1.4 Ablation Study of Hyper-parameters
Ablation Study: Explore the effects of various hyper-parameters in terms of model’s architecture (the number of blocks, the number of attention heads, the dimension of embedding and so on). Document your findings in a tabulated format. Before comparison, you should set a baseline for the different ablation studies. Suggesting to use a set of hyper-parameters as a baseline before comparison. Subsequent adjustments should be based on this baseline to implement.
1.5 Positional Embedding
Implement a new type of positional embedding, for example, a learnable positional embedding. Report your findings and provide a detailed discussion on the role and effectiveness of different positional embedding strategies.
2 Part II: Sentiment Analysis (30 points)
In the second part of this assignment, you will finetune the encoder developed in the first part assignment on a sentiment analysis task (you may need to pre-process the data set and change the max length setup). Sentiment Analysis is the task of classifying the polarity of a given text. For instance, a text-based message can be categorized into either ”positive”, ”negative”, or ”neutral”. Given the text and accompanying labels, a model can be trained to predict the correct sentiment.
2.1 Task 1: Fine-tuning
Based on the Transformer model trained in the Part 1, implement a new model for sentiment analysis by removing the decoder and adding a linear layer for classification. You should use cross-entropy loss as the loss function and modify the training and validation code from Part 1 to suit this new task. Carefully monitor and document the training loss and validation accuracy curves in your report.
Since this is a fine-tuning task, it is essential to load the pre-trained parameters of the encoder from Part 1.
Besides, easy tuning of hyperparameters and debugging of your code are crucial to achieving reliable classification results.
2.2 Task 2: Positional Embedding
Investigate the effects of including or excluding positional embedding in your model. Report your findings and provide a detailed discussion on the role of positional embedding in different tasks.
2.3 Task 3 (Optional): Advanced Techniques
Employ advanced techniques not covered in class to enhance the performance of the translation or sentiment analysis tasks, providing detailed analyses, implementations, and results.
3 Part III: Vision Transformers (20 points)
Vision Transformer, or ViT, is a model for image classification that employs a Transformer-like architecture over patches of the image. An image is split into fixed-size patches, each of them are then linearly embedded, position embeddings are added, and the resulting sequence of vectors is fed to a standard Transformer encoder.
3.1 Task 1: ViT Implementation
Based on the code of Transformer architecture and training procedure in the Part 2, implement vision classification task on the CIFAR10 dataset. This involves constructing an appropriate DataLoader and replacing NLP-specific embeddings with a learnable linear layer. Carefully monitor and document the training loss and validation accuracy curves in your report.
3.2 Task 2: Comparison with CNNs
Implement CIFAR10 classification using a pre-trained CNN model, such as ResNet in PyTorch.
model = torch.hub.load(′pytorch/vision : v0.10.0′ ,′ resnet50′ , pretrained = True)
Compare and discuss the advantages and disadvantages of Vision Transformers (ViTs) relative to Convolutional Neural Networks (CNNs).
4 Submission instructions
The submission will include:
1. A written report with section-by-section descriptions of your procedures, results, and analysis.
2. Code for producing all results for all parts and tasks.
3. Instructions on how to run the code.
Create a ZIP archive with the results of Assignment (all parts and tasks). Give the ZIP file the name student- number assignment2.zip, where you insert your student number. Please submit the archive through Blackboard. Make sure all files needed to run your code are included or you may be given 0 points for it.
The deadline for assignment 2 (all parts and all tasks) is the 25 May 2025 at 23:55 (Beijing Time).