The problem in brief
This 90-point problem from the 2026 USA AI Olympiad Round 2 (Day 1, Problem 1) walks from theory to practice. First it asks why standard attention costs and how a feature map with makes attention linear in . Next it covers why an exact would need infinitely many features, and how to build one from a truncated Taylor series. Then it adds relative positional encodings to the attention scores and asks you to fit them into the linear-attention framework. Finally you must implement the module in PyTorch, with , build an encoder-only transformer from it, and classify the FordA engine-noise time series (500 samples each, 2 classes), with no other positional encoding allowed.
FordA is a public UCR archive dataset. The competition's test.csv matches the official UCR test file row for row, so we can score our final model on the real test set: the labels were used once, at the very end, and never for any choice.
How you are scored
Parts 1.1 to 1.3 are marked on correct reasoning and code. Part 1.4 (20 points) is marked on test macro F1, relative to the best submission: , since random guessing gives 0.5. The best contestant's score is not published.
Part 1.1: linear attention
1.1.1 Complexity. is a matrix whose entries each need a dot product of length : . The row-wise softmax costs , and multiplying the weights by costs again. Total: time, plus memory for the attention matrix. Doubling the sequence length quadruples the cost.
1.1.2 Output with a feature map. Softmax attention is a weighted average,
Since is a scalar, , and can be pulled out of both sums:
The two sums no longer depend on : they are computed once and shared by every query.
1.1.3 Matrix form. Stacking the rows, and . So
Each row of the numerator is divided by the corresponding entry of . The brackets matter: computing first is what avoids the matrix.
1.1.4 Complexity with features. : . times that matrix: . The denominator: for and for the product with . The normalisation: . Total: , linear in , with memory .
1.1.5 Why . With , the series contains every power of the dot product. Each power is itself an inner product of tensor powers: , with coordinates. So
and the natural feature map has coordinates. No finite can work either. If had features, then for any vectors the matrix would equal and have rank at most . But the exponential kernel is strictly positive definite: for distinct points this matrix is invertible, so its rank is . Taking points gives a contradiction, so the representation requires .
1.1.6 A finite map from the truncated series. With , approximate . Using , define
Then , exactly the truncated series. So . Since is symmetric, keeping only (with weight on off-diagonal terms) reduces this to . A bonus: for every , so the approximate attention weights stay positive and the normaliser never vanishes.
Part 1.2: relative positional encoding
1.2.1 When it is the better choice. It is better when what matters is how far apart two events are, not where they sit in the window: stationary signals, periodic patterns, and windows cut at arbitrary moments. FordA is exactly this case. A 500-sample snippet of engine noise starts at an arbitrary time, so "position 37" means nothing, while "an event 12 samples after another" may well be the fault signature. Relative encodings make the attention pattern (approximately) translation-equivariant, share parameters across all positions with the same lag, and generalise better to positions or lengths unseen in training. Absolute encodings are better when absolute position carries meaning (the first token of a sentence, a fixed time of day).
1.2.2 Range of . With , the lag ranges from to , so there are possible values, and therefore vectors to learn (per head).
1.2.3 Initial scale . The score is . With independent zero-mean components, and . To let neither the content term nor the positional term dominate at initialisation, make them equal: . A much smaller means position is ignored at first, and the gradient that would teach it is tiny. A much larger means the content is drowned out. (The total score variance then doubles. If you want to keep it unchanged, scale by .) In the code, is the variance of the key projections at initialisation, about with PyTorch's default nn.Linear initialisation and unit-variance inputs.
1.2.4 Relative positions inside linear attention. Plugging into a feature map does not factorise, because the "key" would then depend on . We instead use the sum of two positive kernels, one for content and one for position:
Both kernels are positive, so the weights stay positive and the normaliser never vanishes. The content part costs as before. is a cross-correlation along time between the sequence of lags and the values , so the FFT computes it for all in . And is a sum over a sliding window of lags, which prefix sums give in . Everything stays (almost) linear in , and no matrix is ever formed. This is the Toeplitz structure behind relative-position linear transformers. A simpler alternative is a learned scalar bias multiplying the weights, but the version above follows the statement's vector form .
Part 1.3: implementation
1.3.1 Number of parameters (no biases). The query, key and value projections each map to , and the output projection maps back to . Each head has relative vectors of length :
For , , , this gives , which matches PyTorch's count.
1.3.2 Plots. is the identity for and for , so is strictly positive, smooth at 0 (slope 1 on both sides) and grows linearly. Strict positivity is what we need: the similarities must be positive for the weights to form an average.


1.3.3 The module. The core of MyLinearAttentionRelativePos.forward (the full class is in solution.py):
q, k = phi(W_q(x)), phi(W_k(x)) # (B, H, T, d) after reshaping into heads
v, pr = W_v(x), phi(self.r) # pr: (H, 2T-1, d), one vector per lag
kv = einsum('bhtl,bhtc->bhlc', k, v) # phi(K)^T V
num = einsum('bhtl,bhlc->bhtc', q, kv)
den = einsum('bhtl,bhl->bht', q, k.sum(2))
S = irfft(rfft(pr.flip(1), n=4T)[..., None] * rfft(v, n=4T)[..., None, :])[:, :, T-1:2T-1]
num += einsum('bhtl,bhtlc->bhtc', q, S) # positional part via FFT correlation
den += einsum('bhtl,htl->bht', q, window_sums(pr))
out = W_o((num / den).merge_heads())
We checked it against a direct computation of the same similarity: the outputs agree to in double precision. The relative vectors are initialised with standard deviation equal to that of the keys, following 1.2.3.
Part 1.4: a transformer for FordA
The data. 3 601 training and 1 320 test series of 500 engine-noise samples, each already normalised to zero mean and unit variance, with two balanced classes (the symptom is present or absent). Two quick baselines tell us what kind of signal this is. Logistic regression on the raw samples is at chance (macro F1 0.51), because the series are not aligned in time. On the log magnitude of the Fourier spectrum it reaches 0.91. The class information is mostly in which frequencies and patterns appear, not where. That is exactly the setting in which relative positional encoding makes sense (Part 1.2.1).
The model (FordATransformer in solution.py):
- Cut the series into patches of 10 samples and map each patch to with one linear layer. Following the rules, no positional encoding is added at the input: position enters only through the relative terms inside attention.
- Three pre-norm encoder blocks: LayerNorm, then our linear attention ( heads, ), plus a residual connection; then LayerNorm, an MLP with GELU, plus a residual connection. Dropout is 0.1.
- Average the 50 tokens, apply LayerNorm, then a linear layer to 2 logits. About 120 k parameters.
- Training: AdamW (weight decay 0.05), one-cycle learning rate peaking at , batches of 64, label smoothing 0.05, gradient clipping at 1, 80 epochs. Augmentation: a random circular time shift and a random amplitude scale (0.8 to 1.2). The shift encodes the same translation invariance as the relative encoding: a fault pattern is the same fault wherever it appears in the window.
We tuned on a random 80/20 split of the training set, then retrained on all 3 601 series and predicted the test set once. FordA is a public UCR dataset, and the competition's test.csv is identical, row for row, to the UCR test file. That lets us report the true test score.
Results
| approach | data | macro F1 |
|---|---|---|
| random guessing | 0.50 | |
| logistic regression on raw samples | validation split | 0.508 |
| logistic regression on log-spectrum | validation split | 0.912 |
| transformer, 40 epochs, no augmentation | validation split | 0.919 |
| transformer, 40 epochs, shift + scale augmentation | validation split | 0.932 |
| transformer, 80 epochs, augmentation, patches of 5 () | validation split | 0.908 |
| transformer, 80 epochs, augmentation, patches of 10 () | validation split | 0.942 |
| final: same model trained on all training data | official test (1 320) | 0.944 (accuracy 94.4 %) |
The competition mark is relative to the best submission, which is not published, so there is no target to compare with. For context, the description file shipped with the UCR archive says the winning entry of the original 2008 competition reported 100 % test accuracy on FordA, so there is still room above our 94.4 %. We trained on Apple MPS (about 10 minutes per run), not on the L4 GPU the rules require for the notebook; nothing in the code depends on the device.
What to remember
- Softmax attention costs because of the matrix. A kernel feature map lets you compute first, which brings the cost down to .
- The exact exponential kernel needs infinitely many features (its Gram matrices have full rank). Truncated Taylor maps () or positive maps like are practical substitutes.
- Relative positions fit into linear attention as a second positive kernel. Their contribution is a correlation over lags, which the FFT computes in .
- Initialise new score terms at the same scale as the existing ones (), so neither dominates at the start.
- Match the inductive bias to the data. FordA is shift-invariant (the raw-sample model is at chance while the spectrum model works), so relative encoding plus shift augmentation is the right recipe.
- Test any fast implementation against a slow, obviously correct one. Ours matched the version to .