Efficient Transformer Architectures
Derive blockwise softmax normalization and distinguish memory traffic, autoregressive KV storage, and sparse long-context attention.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 3
- Reading time
- 2 min
In this article3 chapters
Stable softmax can be merged across blocks
For a single query, accumulate a maximum \(m\), a denominator \(z\) and a value numerator \(u\), both sums scaled by the current maximum. For the next nonempty block of scores \(s_j\) and value vectors \(v_j\), update
\[ \begin{aligned} m'&=\max\!\bigl(m,\max_j s_j\bigr),\\ z'&=e^{m-m'}z+\sum_j e^{s_j-m'},\\ u'&=e^{m-m'}u+\sum_j e^{s_j-m'}v_j. \end{aligned} \]
The final output is \(u/z\). Every earlier contribution is rescaled by \(e^{m-m'}\), so the result equals dense softmax attention in exact arithmetic. Initialize with the first block containing unmasked scores. FlashAttention tiles the calculation to keep working data in fast memory and avoids writing a full matrix of scores and probabilities. Dense attention still computes a quadratic number of score pairs.
Dot-product attention defines the score matrix by query and key. Stable softmax explains the common shift behind exact blockwise normalization, and autoregressive decoding explains why earlier cache entries can be reused.
The KV cache changes autoregressive decoding work
During causal generation, a previous token’s key and value do not change when a new token is appended. Storing both avoids recomputing them. If \(L\) tokens are retained and the total key width per token is \(d_{\mathrm{kv}}\), equal-width keys and values occupy \(2Ld_{\mathrm{kv}}\) scalar slots per layer and sequence. A single new query can still read much of that state. Batching and shared key–value heads trade memory traffic against throughput and capacity.
Sparse connectivity changes reachable context
A sliding attention window of width \(w\) limits each token’s direct edges. Stacking layers widens the receptive field, and global tokens or other long-range edges can shorten paths. Changing edges changes the model and requires measuring which long-range relations it preserves. Multimodal models use cross-attention with separate source and target lengths. High-performance I/O examines similar tradeoffs between data movement, batching and latency.[1][2][3]