Basic Prerequisites: 02 · RNNs & LSTMs and linear algebra (dot products, softmax).


1. Intuition & Practical Objective

Recurrence compresses the past into one vector that is overwritten at each step. Attention does something different and powerful: it keeps all past states and lets the model look back and choose which ones to use. The mechanism is a soft dictionary lookup. Every past position offers a key and a value ; the current position issues a query ; the output is the similarity-weighted average of the values:

Three “aha”s:

  1. No fixed memory horizon. Attention’s path length between any two positions is (they interact directly), versus for recurrence. This is why Transformers learn long-range dependencies that RNNs cannot.
  2. It is fully parallel over time. All queries and keys are computed at once - the reason Transformers train fast on GPUs, unlike the sequential BPTT of page 02.
  3. Causality must be enforced, not assumed. In a forecasting task the query at must not see keys at . A raw (bidirectional) attention will happily attend to the future - look-ahead leakage inside the architecture. The fix is an explicit causal mask (§3 verifies it produces an exact zero upper triangle).

The practical objective: read and write the attention formula correctly, and never build a forecasting model without a causal mask.


2. Mathematical Ground Truth & Derivations

2.1 Scaled dot-product attention (Vaswani et al. 2017)

Given a matrix of queries , keys , values :

where is applied row-wise and is the mask.

Why divide by ? If the components of and are i.i.d. with mean and variance , then has mean and variance . Unscaled, the logits grow like , pushing the softmax into a saturated region where one weight and the gradients . Dividing by restores unit variance and keeps the softmax in its informative range (§3 measures this: score stdev as grows, and the softmax entropy collapses without the scaling).

2.2 The causal mask

For an autoregressive / forecasting model,

so the pre-softmax logit for any future position is and . Position can attend only to . This is the exact attention analogue of the no-look-ahead requirement; without it, the model is trained on the answer.

2.3 Multi-head attention and the Transformer block

One attention head computes one similarity notion. Multi-head attention runs heads in parallel subspaces and concatenates:

A Transformer block adds residual connections and a position-wise feed-forward net: , . Positional encodings (sinusoidal or learned) are added to the inputs, because attention - unlike a recurrence - is permutation-invariant and otherwise cannot tell position from position .


3. Computational Implementation - causal attention and the scaling argument

numpy + stdlib. Part A computes masked attention and proves the causality property; Part B measures why the scaling exists.

Read it as two facts. First, the weight matrix is lower-triangular by construction - the upper triangle is exactly zero, every row sums to , and position can only attend to itself. This is what makes an attention forecasting model honest; drop the mask and you have built a leak. Second, the scaling matters: at the unscaled score standard deviation is and the softmax entropy collapses to (attention has pinned almost all weight on one key - gradient-starved), whereas the -scaled version stays at , near the maximum-entropy value for positions.


4. Failure Modes & First-Principles Breakdowns

  1. Missing causal mask = look-ahead leakage. The most common and most damaging bug. A bidirectional/encoder-only attention over a forecasting target sees the future by construction. Always verify on a test batch. (The validation-side twin of this is the Purged CV folder.)
  2. cost in time and memory. Attention scales quadratically with sequence length; a full LOB day at tick resolution is millions of tokens. This is the practical reason microstructure models use local attention or convolution (DeepLOB) rather than a full Transformer.
  3. Attention weights are not explanations. High attention on a timestep does not prove it caused the prediction; “attention is not explanation” (Jain & Wallace 2019). Use it as a diagnostic, not a story.
  4. Positional encoding is not neutral in finance. Time is not a uniform grid (trading hours, overnight gaps, information-driven bars). Naive positional encoding imposes a regularity the market does not have.
  5. Over-parameterisation on small data. A single Transformer block has millions of weights; on financial samples it will memorise. Attention is a tool for the large- microstructure regime, not for monthly bars.

5. References

  • Vaswani, Ashish et al. (2017), Attention Is All You Need, NeurIPS
  • Lim, Bryan et al. (2021), Temporal Fusion Transformers for Interpretable Multi-horizon Time Series Forecasting, IJF 37(4)
  • Goodfellow, Bengio & Courville, Deep Learning, Ch. 10 (§10.4 “Encoder–Decoder Sequence-to-Sequence Architectures” and the attention mechanism)
  • Zhang, Zohren & Roberts (2019), DeepLOB: Deep Convolutional Neural Networks for Limit Order Books, IEEE TSP 67(11), arXiv:1808.03668
  • Jain, S. & Wallace, B. (2019), Attention is not Explanation

6. Connected Graph Bridges