Problem 1Linear Attention Is All You Need
90 ptsGuided
SummaryDerive linear attention from standard softmax attention, analyze its complexity, add relative positional encoding, implement batched multi-head linear attention, and build a Transformer for time-series classification.
- TransformersLinear attentionPositional encoding
Submission Requirements
-
Each contestant must submit a Jupiter Notebook (.ipynb). You should put all your solutions on this file.
-
Your submitted file must follow the format
Attn_LastName_FirstName_SchoolName -
Each part's name/number must appear in a text cell in bold section format, such as
# **Part 1.3.4**
The attention mechanism is a central component of the transformer architecture introduced in Attention Is All You Need. In this problem, we study the computational properties of attention, explore linear attention, introduce relative positional encoding, and finally apply these techniques to build a transformer model for time-series classification.
Throughout this problem, we consider self-attention only and ignore masking for simplicity.
Part 1.1. Linear Attention
Assume the input sequence contains tokens. For any attention head, let
For each token position ,
are column vectors corresponding to the query, key, and value of the -th token, respectively.
The self-attention output matrix is
where
is a column vector corresponding to the output of the -th token.
Part 1.1.1
5 ptsAnalyze the time complexity of computing the self-attention output . Express the complexity in terms of and using Big-O notation. Reasoning is required.
Part 1.1.2
5 ptsSuppose
where is a feature map function. Write the attention output vector using the feature map representation. Reasoning is required.
Part 1.1.3
5 ptsDefine
Express the matrix using , and . Reasoning is required.
Part 1.1.4
5 ptsSuppose the feature map
Assume and have already been computed. Analyze the time complexity of computing in terms of , , and . Reasoning is required.
Part 1.1.5
5 ptsExplain why the representation
requires .
Hint:
Part 1.1.6
5 ptsConsider the truncated Taylor's expansion
Construct an explicit feature map for and compute the feature dimension . Reasoning is required.
Part 1.2. Relative Positional Encoding
In many time-series datasets, the relationship between two time steps depends on their relative distance rather than their absolute positions.
Part 1.2.1
5 ptsSuppose the attention score is modified as
where the learnable parameter represents the relative directional positional encoding from token to token .
Explain when this encoding is more appropriate than absolute positional encoding.
Part 1.2.2
5 ptsAssume the sequence contains tokens indexed as
Determine the possible range of . Reasoning is required.
Part 1.2.3
5 ptsFor each token , suppose each component satisfies
Suppose component in is initialized according to
Determine the appropriate value of . Reasoning is required.
Part 1.2.4
5 ptsExplain how relative positional encoding can be incorporated into the linear-attention framework developed earlier. Reasoning is required.
Part 1.3. Implementation of Linear Attention with Relative Positional Encoding
In this part, you are asked to build a PyTorch module called MyLinearAttentionRelativePos for multi-head self-attention with linear attention and relative positional encoding.
Starter Code Run the following starter code
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
You may use basic modules such as nn.Linear. You are not allowed to use high-level modules such as nn.MultiheadAttention or nn.TransformerEncoder. You are not allowed to import anything else beyond those provided in the starter code. You are not allowed to import any model from HuggingFace.
Hyperparameters Let denote the length of each input token, denote the number of tokens (a hyperparameter that needs to be instantiated), denote the number of attention heads and denote the length of each value vector for each token and each head. You should not assume that .
Hint: In this problem, we treat as a hyperparameter. This is because we will use this model to study a dataset that all samples are with equal length .
Feature Map Function In this task, please use a feature map function defined with the ELU function. Recall that the ELU function is defined as
Therefore, the feature map function is defined as
You can instantiate an ELU transformation by using nn.ELU().
Part 1.3.1
5 ptsWrite down the total number of learnable parameters of this module. Express your answer in terms of , , , and .
For simplicity, please ignore the bias term in any affine/linear transformation. Reasoning is required.
Part 1.3.2
5 ptsPlot and for . Put two plots in two separate figures.
Part 1.3.3
10 ptsBuild the PyTorch class MyLinearAttentionRelativePos from scratch as a subclass of nn.Module.
Part 1.4
20 ptsTransformer Model for Time-Series Classification
In this part you will build an encoder-only transformer by using the linear attention with relative positional encoding module that you build in the previous part. You then apply your transformer to the FordA dataset.
The FordA dataset is a time-series dataset derived from automotive sensor signals. Each sample consists of a time series of length 500. Each sample belongs to one of two classes.
Your task is to train a transformer model to perform binary classification.
Requirements
- The transformer must use linear attention with relative positional encoding that you build in the previous part.
- No additional positional encoding is allowed at the input.
- You should build an encoder-only transformer from scratch. Any attempt to load a well-built attention block or encoder module (except those that you build above) is prohibited.
Feel free to import any needed libraries/modules/functions, as long as they are not against the above requirements.
Starter Code Please use the following URL:
https://drive.google.com/file/d/1ZpO63c-LJAQL-n9po9HXdrQl57DDbI4K/view?usp=drive_link
Submission Beyond the Jupyter notebook, for this part, you should also submit a CSV file containing predictions for the test dataset.
All submitted files must follow the format
FordA_LastName_FirstName_SchoolName
GPU You must do training and testing with L4 GPU.
CSV Format The format of the CSV file must be the same as the sample submission file. It must contain two columns (in the sample submission file, the label column is empty):
| test_sample_id | label |
|---|
Each row corresponds to one test sample.
Evaluation Your model will be evaluated using the macro F1 score. A random guessing baseline achieves approximately 0.5. Your goal is to achieve a higher score.
Final Competition Score Let be the macro F1 score of your submission, be the baseline score, and be the best score among all submissions.
The final competition score is computed as
If , then the final score is 0. The best submission receives 100% of the total score in this part.
In addition,
- In your submitted CSV file, if your prediction in a sample has a missing value or a value that is not one of those two labels, your solution in this sample will be graded to be a wrong prediction.
- If we find that you manually label the test dataset, you will receive 0 point in this part.
- If your Jupiter Notebook does not run properly on L4 GPU, you will receive 0 point in this part.