Quant Memo
Advanced

The Transformer Architecture

A sequence model that throws away recurrence entirely and lets every position look at every other position in one hop, using attention weights it computes on the fly. The dot-product-scale-softmax-average recipe is the whole engine.

Prerequisites: The Self-Attention Mechanism, The Multilayer Perceptron

Recurrent models pass information along a chain: step 1 tells step 2, which tells step 3. Two problems follow. Information from far back has to survive every intermediate hop, and every step must wait for the one before it, so a thousand-step sequence takes a thousand sequential operations no matter how many GPUs you own. The transformer removes the chain. Every position reads every other position directly, in parallel, and the model decides for itself which ones are worth reading.

The analogy: everyone asks the room

Imagine a trading floor where each day of price history is a person holding a note. To form its view, each person stands up and announces what it is looking for — "I need days where volume spiked" — and everyone else holds up a tag saying what they have — "big volume day", "quiet drift day". Each listener compares its request to every tag, decides how much attention to give each person, and takes a weighted blend of their notes.

Those three roles are the whole mechanism, and they have names:

  • the query qq: what this position is looking for,
  • the key kk: what that position advertises about itself,
  • the value vv: the content it hands over if you attend to it.

All three are just small learned linear projections of the same input. Nothing mystical happens; the model learns three different ways of looking at each token.

Attention is a soft lookup. Compare a query against every key to get a relevance score, turn the scores into weights that sum to one, then average the values with those weights. Everything else in a transformer is scaffolding around that one operation.

The formula

For a whole sequence, stack the queries into a matrix QQ, keys into KK, values into VV:

Attention(Q,K,V)=softmax ⁣(QKdk)V.\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^{\top}}{\sqrt{d_k}}\right) V .

Read it right to left in four moves. QKQK^{\top} takes the dot product of every query with every key, giving a score for each pair. Dividing by dk\sqrt{d_k} — the square root of the key dimension — keeps those scores from growing simply because the vectors are long. The softmax turns each row of scores into positive weights that add to one. Multiplying by VV averages the values using those weights.

Worked example: attention by hand

Three days of history, keys of dimension dk=2d_k = 2. Today (day 3) issues the query q=(1.0, 0.5)q = (1.0,\ 0.5). The three keys and their scalar values are

k1=(0.2, 1.0), v1=2.0;k2=(1.2, 0.4), v2=1.0;k3=(0.9, 0.6), v3=0.5.k_1 = (0.2,\ 1.0),\ v_1 = 2.0; \qquad k_2 = (1.2,\ 0.4),\ v_2 = -1.0; \qquad k_3 = (0.9,\ 0.6),\ v_3 = 0.5 .

Step 1, score every pair. Dot products:

qk1=0.2+0.5=0.7,qk2=1.2+0.2=1.4,qk3=0.9+0.3=1.2.q \cdot k_1 = 0.2 + 0.5 = 0.7, \qquad q \cdot k_2 = 1.2 + 0.2 = 1.4, \qquad q \cdot k_3 = 0.9 + 0.3 = 1.2 .

Step 2, scale. Divide each by 2=1.414\sqrt{2} = 1.414: the scores become 0.4950.495, 0.9900.990, 0.8490.849.

Step 3, softmax. Exponentiate: e0.495=1.641e^{0.495} = 1.641, e0.990=2.691e^{0.990} = 2.691, e0.849=2.337e^{0.849} = 2.337. They sum to 6.6696.669, so the weights are

0.246,0.404,0.350.0.246, \qquad 0.404, \qquad 0.350 .

Step 4, average the values.

0.246(2.0)+0.404(1.0)+0.350(0.5)=0.4920.404+0.175=0.263.0.246 (2.0) + 0.404 (-1.0) + 0.350 (0.5) = 0.492 - 0.404 + 0.175 = 0.263 .

Today's output is 0.2630.263. It leaned most on day 2 because day 2's key matched today's query best — and it worked that out from the data, not from a fixed rule about how far back to look.

keys: which day is being read d1 d2 d3 d4 d1 d2 d3 d4 queries darker = more attention dashed = the future, masked out every row sums to 1
One attention head as a matrix. Each row is a day deciding how to split its attention across earlier days. The dashed upper triangle is the causal mask: on live data you may never attend forward in time.

Worked example: why divide by the square root

Scores are dot products of dkd_k terms, so they grow roughly like dk\sqrt{d_k} as the dimension rises. Take the same three days but with dk=64d_k = 64 instead of 2. The raw dot products come out about 32=5.66\sqrt{32} = 5.66 times larger: 3.963.96, 7.927.92, 6.796.79.

Softmax those unscaled and the weights become

0.014,0.745,0.241.0.014, \qquad 0.745, \qquad 0.241 .

Day 2 now soaks up three quarters of the attention and day 1 has effectively vanished — not because the relationships changed, but because the vectors got longer. Worse, a saturated softmax has almost no gradient, so training stalls.

Now divide by 64=8\sqrt{64} = 8: the scores return to 0.4950.495, 0.9900.990, 0.8490.849 and the weights to 0.2460.246, 0.4040.404, 0.3500.350 — exactly the two-dimensional answer. The scaling makes attention behave the same at any width.

The softmax is exponential, which is what makes it so easy to saturate. Steepen the exponential curve below and watch how a modest gap in the input turns into a huge gap in the output — that is the effect the dk\sqrt{d_k} divisor is holding in check.

Function explorer
-2260.1
x = 1.00f(x) = 2.718

The rest of the block

Attention alone is a weighted average, which is a fairly weak operation. Four pieces surround it:

  • Multi-head. Run several attentions in parallel with separate projections, then concatenate. One head can track momentum, another liquidity, another the earnings date. Splitting a 512-wide model into 8 heads of 64 costs nothing extra in compute.
  • Positional encoding. Attention is order-blind — shuffle the days and the maths is identical. A position signal is added to each input so the model can tell "yesterday" from "a year ago".
  • Residual connections and normalisation. Each sublayer computes x+sublayer(x)x + \text{sublayer}(x) followed by a normalisation, which is what lets dozens of blocks stack without the signal degrading.
  • A position-wise feed-forward layer. A small two-layer network applied to each position separately, giving the model the nonlinearity that averaging cannot provide.

Stack that block NN times and you have a transformer.

input embedding + position multi-head self-attention add and normalise position-wise feed-forward on to block 2, 3, ... N residual
One block. The dashed line is the residual path that carries the input around the attention layer, so a deep stack degrades gracefully rather than losing the original signal.

What this means in practice

Transformers arrived in finance on the promise of modelling long-range structure in returns, order flow and text. What actually holds up:

  • Cost is quadratic in sequence length. A thousand ticks means a million scores per head per layer. Doubling the window quadruples the bill. This is the reason people bucket ticks into bars before feeding a transformer.
  • They are data-hungry. With no recurrence prior, a transformer must learn the very notion of "adjacent in time" from scratch. Twenty years of daily bars is roughly 5,000 rows — far too little. They earn their keep on tick data, cross-sectional panels of thousands of names, and text.
  • Causal masking is not optional. In language modelling the mask is a nicety; in trading it is the difference between a result and a fantasy. Any position attending to a later timestamp has leaked the future.

Attention weights are not an explanation. A large weight means one position was blended heavily into another after some arbitrary projection, not that the feature caused the prediction. Heatmaps of attention look wonderfully interpretable and routinely disagree with proper attribution methods. Do not put them in a research note as evidence of what the model learned.

Before reaching for a transformer, run the same features through gradient boosting. On tabular financial panels the boosted trees win far more often than not, and when they lose it is usually by a margin that does not survive transaction costs.

The transformer's real gift is that path length between any two positions is one, not nn. That is why it learns long-range structure where gated recurrent cells struggle — and why the bill arrives as memory rather than as forgetting.

Related concepts

Practice in interviews

Further reading

  • Vaswani et al., Attention Is All You Need (2017)
  • Goodfellow, Bengio & Courville, Deep Learning (ch. 10)
  • Phuong & Hutter, Formal Algorithms for Transformers (2022)
ShareTwitterLinkedIn