"They handed me a window long enough to remember the whole shift, then a compute budget that could barely afford the last five seconds. Efficiency is just me learning which seconds to forget."
A Budget-Conscious AI Agent
Prerequisites
This section assumes you have met scaled dot-product attention and the multi-head block in Section 15.1, and that you understand how a raw sensor stream is cut into tokens in Section 15.2, because patch length is the single biggest lever on the cost we are about to fight. Basic complexity notation (\(O(\cdot)\)) and the idea of a receptive field from Chapter 14 are all the extra background you need.
The Big Picture
A transformer's superpower is that every token can look at every other token in one hop. Its curse is the bill for that privilege: attention costs grow with the square of the sequence length. Text sequences top out at a few thousand tokens, but a sensor sampled at kilohertz rates produces sequences that are orders of magnitude longer, and the plain attention matrix simply will not fit in memory. This section is about buying back the long context that sensing genuinely needs (a vibration signature, a slow drift, an overnight sleep stage) without paying the quadratic price. The tools split into three families: make the attention pattern sparse, replace the softmax with a linear-cost approximation, or keep the exact math and just compute it more cleverly on the hardware. Knowing which lever to pull, and when to abandon attention entirely, is what separates a model that trains on a workstation from one that only ever exists in a paper.
Why quadratic attention breaks on long sensor windows
Self-attention builds an \(L \times L\) score matrix, where \(L\) is the number of tokens. For queries, keys, and values of width \(d\), computing \(QK^\top\), softmaxing it, and multiplying by \(V\) costs on the order of
\[ O(L^2 d) \text{ time and } O(L^2) \text{ memory}. \]What this means concretely: double the window and you quadruple the work. Why it bites sensing harder than language is a matter of raw arithmetic. A sentence is maybe 30 tokens; a page is 500. Now take an industrial accelerometer sampled at \(20\,\mathrm{kHz}\). A ten-second capture is \(200{,}000\) raw samples. Even after patchification collapses, say, 64 samples into one token, you are left with roughly \(3{,}000\) tokens, and the score matrix has \(3{,}000^2 \approx 9\) million entries per head, per layer. Push the window to a full minute of high-rate data and the matrix crosses a billion entries; the memory alone exceeds a commodity GPU before a single gradient flows. When does this matter? Precisely when the phenomenon you care about is slow or intermittent relative to the sample rate: a bearing fault that rings once per revolution, a cardiac arrhythmia that appears in one beat out of a thousand, a machine that drifts out of tolerance over an hour. Downsample to shorten the sequence and you blur the very event you are hunting.
Key Insight
The quadratic wall is not a hardware problem you outgrow with a bigger GPU; it is a scaling law. Each generation of accelerator roughly doubles memory, but doubling the window quadruples the demand, so hardware loses the race by construction. Long-context sensing is therefore an algorithmic problem: you must change what attention computes, not just where it runs.
Sparse and local attention: exploit the structure of signals
Full attention assumes any token might be decisively relevant to any other. Physical signals rarely honor that assumption. The value of a sample is dominated by its recent neighbors (local temporal correlation), plus a sparse set of far-away anchors (a periodic beat, a shift-start marker, a global summary). Sparse attention hard-codes this prior by letting each token attend to only a chosen subset of the others, dropping the cost from \(O(L^2)\) toward \(O(L)\).
The workhorse pattern is sliding-window (local) attention: token \(i\) attends only to the \(w\) tokens on either side, costing \(O(L w)\) with \(w \ll L\). This is attention's answer to the dilated receptive field you met in Chapter 14, and like a stack of dilated convolutions, stacking windowed-attention layers grows the effective receptive field linearly with depth, so distant tokens still communicate indirectly. To restore true global reach cheaply, designs such as Longformer and BigBird add two ingredients: dilated windows that skip tokens to cover more span at fixed cost, and a handful of global tokens that every position attends to and that attend to everyone, giving an \(O(L)\) information highway. A single \([\text{CLS}]\)-style global token is often enough to route a whole-window classification decision. The design question is always the same: what is the physical range of dependency in this signal, and how few links can honor it?
In Practice: 24-hour predictive maintenance on a pump
A water-utility maintenance team streams vibration from a pump's drive-end bearing at \(25.6\,\mathrm{kHz}\) and wants a transformer that flags an emerging outer-race fault a week before failure. The fault signature is a faint impact that repeats at the ball-pass frequency, buried in an hour of otherwise healthy running. Full attention over an hour is hopeless. The deployed model uses a \(512\)-token sliding window (covering a few seconds of local waveform shape, enough to see one impact cluster) plus four global tokens that each summarize a 15-minute quadrant of the capture. The local windows catch the shape of each impact; the global tokens accumulate how often impacts recur across the hour, which is the actual diagnostic. Memory drops from tens of gigabytes to under one, and the model runs on the edge gateway in the pump house rather than shipping raw waveforms to the cloud. This same span-versus-cost tradeoff drives the condition-monitoring pipelines in Chapter 37.
Linear attention: replace the softmax, not just the pattern
Sparse patterns still compute an exact softmax over the links they keep. A different family attacks the math itself. The bottleneck is that softmax forces you to form \(QK^\top\) explicitly before you can normalize. Linear attention replaces the softmax kernel with a feature map \(\phi(\cdot)\) so that the similarity between query \(i\) and key \(j\) factorizes as \(\phi(q_i)^\top \phi(k_j)\). Once it factorizes, the associativity of matrix multiplication lets you reorder the computation:
\[ \big(\phi(Q)\,\phi(K)^\top\big)V \;=\; \phi(Q)\,\big(\phi(K)^\top V\big). \]The left side builds the \(L \times L\) matrix; the right side first builds a \(d \times d\) matrix and never materializes anything of size \(L^2\). The cost falls to \(O(L d^2)\), linear in sequence length. Performer approximates the true softmax kernel with random features so the results stay close to exact attention, while simpler schemes (for example \(\phi(x) = \mathrm{elu}(x) + 1\)) trade a little fidelity for speed and, usefully, admit a recurrent form that streams one token at a time. That streaming form is why linear attention is attractive for the always-on, never-ending inputs of Chapter 60. The catch, which you should treat as a working rule rather than a footnote, is that linear attention often underperforms exact attention when the task hinges on sharp, precise matches between two specific distant tokens, because the low-rank feature map smears fine distinctions. Reach for it when context is long and the signal is smooth; be skeptical when a single needle in the haystack decides the label.
Research Frontier
The current default for long-context transformers is not an approximation at all but an exact, IO-aware kernel. FlashAttention (Dao et al., 2022) and its successors FlashAttention-2 (2023) and FlashAttention-3 (2024, tuned for NVIDIA Hopper GPUs) compute the standard softmax attention while never writing the full \(L \times L\) matrix to slow high-bandwidth memory; they tile the computation and fuse it in fast on-chip SRAM, cutting memory from \(O(L^2)\) to \(O(L)\) and running several times faster with bit-for-bit the same output. Because it changes only the memory-access pattern and not the math, FlashAttention has largely displaced approximate methods wherever exact attention still fits after the memory saving, and it is the kernel silently invoked by PyTorch's scaled_dot_product_attention. For sensor windows that are long but not astronomically so, the modern first move is FlashAttention plus modest patch merging, and only then sparse or linear attention if you are still over budget.
You do not implement any of this by hand. PyTorch exposes the fused, memory-efficient kernels behind one function, and it selects FlashAttention automatically when the inputs qualify. Listing 15.4 shows the whole thing.
import torch
import torch.nn.functional as F
# 8 heads, a long sensor window of L=4096 tokens, head width 64
B, H, L, d = 2, 8, 4096, 64
q = torch.randn(B, H, L, d, device="cuda", dtype=torch.float16)
k = torch.randn(B, H, L, d, device="cuda", dtype=torch.float16)
v = torch.randn(B, H, L, d, device="cuda", dtype=torch.float16)
# One call: fused, IO-aware, exact softmax attention.
# is_causal=True masks the future so a token never attends forward in time.
out = F.scaled_dot_product_attention(q, k, v, is_causal=True)
print(out.shape) # torch.Size([2, 8, 4096, 64]); no 4096x4096 matrix ever stored
scaled_dot_product_attention call over a 4096-token window. PyTorch dispatches to the FlashAttention kernel when the dtype and shapes allow, so the \(4096 \times 4096\) score matrix is never materialized in high-bandwidth memory. The is_causal flag enforces temporal ordering, which matters whenever a streaming sensor model must not peek at future samples.The Right Tool
A correct, numerically stable FlashAttention kernel is roughly 300 to 500 lines of CUDA with online-softmax bookkeeping, tiling, and careful reductions; a naive from-scratch attention that materializes the score matrix is a dozen lines but blows up at long \(L\). The single F.scaled_dot_product_attention(q, k, v, is_causal=True) call in Listing 15.4 replaces both, giving you the exact result of the naive version at the memory footprint of the hand-tuned kernel, a reduction from hundreds of lines (or an out-of-memory crash) to one. It also transparently upgrades when you install a newer FlashAttention build. What the library will not decide for you is your window length and patch size; those remain the modeling choices that set the bill in the first place.
Choosing an efficient-attention strategy
The three families answer different questions, and Table 15.4 lines them up. Full attention is your accuracy reference and the right choice whenever the post-patchification sequence fits in memory, which, thanks to FlashAttention, now covers many sensor tasks people assumed needed approximation. Reach for sparse or local attention when the signal has a clear locality structure and a few known long-range anchors, because you can encode that prior directly and cheaply. Reach for linear attention when the context is very long, the dynamics are smooth, and you want a streaming-friendly recurrent form. And when the sequence is truly enormous and the dependencies are long and diffuse, the honest answer is often to leave attention behind entirely for a state-space model, the linear-time architecture that Chapter 16 is devoted to.
| Family | Cost | Keeps exact softmax? | Best when |
|---|---|---|---|
| Full (FlashAttention) | \(O(L^2 d)\) time, \(O(L)\) memory | Yes | Sequence fits after patch merging; accuracy is paramount |
| Sparse / local + global | \(O(L w)\) | Yes, on kept links | Strong locality with a few long-range anchors |
| Linear / kernel | \(O(L d^2)\) | No (approximate) | Very long, smooth context; streaming inference |
| State-space (Ch 16) | \(O(L)\) | N/A (not attention) | Enormous windows, long diffuse dependencies |
Two disciplines cut across all four rows. First, the cheapest efficient attention is the token you never create: aggressive but sensible patchification (Section 15.2) shrinks \(L\) before any attention runs, and halving \(L\) quarters the full-attention bill for free. Second, whatever you choose, evaluate it under the leakage-safe protocol this book insists on, splitting by recording or subject rather than by window, so a long context does not quietly let the model memorize a device it will also be tested on; the machinery for that lives in Chapter 65.
Exercise
You are given a 5-minute ECG at \(500\,\mathrm{Hz}\) (150,000 samples) and must classify a rare arrhythmia that shows up in isolated single beats. (a) With a patch size of 50 samples, how many tokens \(L\) result, and roughly how many entries does a full attention matrix hold per head? (b) Argue whether sliding-window attention alone is safe here, given that the diagnostic event is local to one beat but its clinical significance depends on the surrounding rhythm. (c) Propose a concrete window size \(w\) plus a global-token scheme and justify each number physically. Contrast your design with reaching for a state-space model instead.
Self-Check
1. Why does doubling the sensor window quadruple full-attention cost, and why can a bigger GPU never win that race?
2. In the identity \((\phi(Q)\phi(K)^\top)V = \phi(Q)(\phi(K)^\top V)\), which grouping avoids ever forming an \(L \times L\) matrix, and what property of matrix multiplication makes the rewrite legal?
3. FlashAttention is called an "exact" method yet saves memory. If it does not approximate the softmax, where does the \(O(L^2) \to O(L)\) memory saving come from?
What's Next
In Section 15.5, we turn from the length axis to the channel axis and confront a design fork that quietly decides both accuracy and cost: should each sensor channel be modeled on its own (channel-independent), or should attention mix channels so the model can learn cross-sensor structure (channel-mixing)? The efficient-attention budget you just built is exactly what that choice spends.