"The transformer read the entire recording again for every new sample. I kept a small vector and answered before it finished re-reading the first second."
A Frugal AI Agent
Prerequisites
This section compares two families you have already met: the attention mechanism and its quadratic cost from Chapter 15, and the linear-time recurrences of Section 16.2 (S4/S5) and Section 16.3 (Mamba). It assumes you understand asymptotic cost in sequence length \(L\) from Section 16.1, and it leans on the streaming and quantization ideas developed in Chapter 59. No new mathematics is introduced here; the goal is to turn the mechanisms into a defensible engineering decision.
The Big Picture
By now you can build both an attention layer and a selective SSM. The practical question is which one to ship, and the honest answer is that the tradeoff is not "SSMs win." Transformers still hold an edge on tasks that demand sharp, content-addressable recall over a modest window, and their tooling is more mature. SSMs win decisively on the axis that sensing actually stresses: cost that grows with sequence length. Attention is \(O(L^2)\) time and \(O(L)\) memory for the key-value cache; a selective SSM is \(O(L)\) time and \(O(1)\) state at inference. For a wearable sampling an IMU at 100 Hz all day, or a vibration probe at 25.6 kHz, that asymptotic gap is the difference between a model that fits in a microcontroller's SRAM and one that cannot run at all. This section makes the comparison concrete on four axes (accuracy, latency, memory, on-device fit), tells you where each family genuinely wins, and gives you a measurement harness so you never have to argue the tradeoff from a table you half-trust.
The four axes, side by side
Start with the asymptotics, because they drive everything else. For a length-\(L\) sequence, model width \(d\), and SSM state size \(N\), the dominant costs are as follows. The table entries are per-layer; multiply by depth for the full model.
| Axis | Transformer (full attention) | Selective SSM (Mamba-style) |
|---|---|---|
| Training time | \(O(L^2 d)\) | \(O(L\,d\,N)\), parallel scan |
| Autoregressive step (inference) | \(O(L d)\) with a growing KV cache | \(O(d\,N)\), constant in \(L\) |
| Inference memory | \(O(L d)\) KV cache, grows with context | \(O(d\,N)\) state, fixed |
| Long-range dependency | Direct, any-to-any lookup | Compressed into state, decays gracefully |
| Content-based recall | Strong (this is what attention is) | Weaker; the selection gate helps but does not match it |
Read the table as a decision tool, not a scoreboard. The \(O(L^2)\) training cost is often tolerable because you train once, offline, on windowed data. The rows that bite in production are the inference step and the memory footprint, because those are paid on the device, forever, once per incoming sample. A transformer serving a continuous stream must either cap its context (throwing away old information) or carry a key-value cache that grows linearly with how long it has been running; neither is acceptable on a coin-cell wearable. The SSM simply keeps its fixed-size state and steps forward.
Key Insight
Accuracy comparisons at a fixed, short context length flatter the transformer, because that is the regime attention was designed for and the regime most benchmarks use. The moment you extend the context to the lengths raw sensor feeds actually produce (tens of thousands of samples), the transformer's quadratic cost forces you to subsample, chunk, or truncate, and its effective accuracy on the real task collapses even though its accuracy-per-token looks fine. The SSM's advantage is often less "better math on the same window" and more "it can afford to look at the whole window at all." Always compare at the context length your deployment demands, not the one the leaderboard chose.
Accuracy: who actually wins, and on what
On long-sequence classification and forecasting for sensor data, well-tuned SSMs and transformers land within a point or two of each other, and which one leads depends on the task structure rather than on raw capacity. Selective SSMs (Mamba, and the time-series variants of Section 16.4) tend to lead when the signal is long and its informative structure is smooth or periodic: gait cycles, respiration envelopes, slow machine degradation. Transformers tend to lead when the task hinges on retrieving a specific earlier event by its content (find the one prior beat that looked like this one), because any-to-any attention is a literal content-addressable lookup and a compressed state is not. The selection gate in Mamba narrows this gap by letting the recurrence copy or ignore inputs on demand, but it does not fully close it. The pragmatic reading is that for most streaming sensor classification you lose little or no accuracy moving to an SSM, and for the recall-heavy minority you either keep attention or use the hybrids of Section 16.6. Whichever you pick, evaluate on a leakage-safe split (Chapter 5); with long contexts it is easy to let a window straddle the train/test boundary and inflate both models equally.
Latency and memory: the axis sensing actually cares about
Latency splits into two very different questions. Throughput (samples per second during a parallel forward pass) favors whichever kernel is better tuned for your hardware; on a modern GPU with FlashAttention a transformer at short \(L\) can be extremely fast, and an SSM's advantage only appears once \(L\) is large enough for \(O(L^2)\) to dominate. Streaming step latency (time to emit one output for one new sample, with the model already caught up) is where the families diverge structurally. The SSM step is a fixed-size state update, constant in \(L\); the transformer step must attend over a cache that grows with elapsed time. For an always-on device the second number is the one that sets your battery life, and it is the one an SSM wins by construction. Memory follows the same logic: the SSM carries \(O(dN)\) numbers regardless of stream length, while the transformer's KV cache is \(O(Ld)\) and grows without bound until you evict.
The listing below measures this directly. It times a single autoregressive step for a growing context and reports how each family scales.
import time, numpy as np
d, N = 256, 16 # model width, SSM state size
def ssm_step(state, u, Abar, Bbar, C):
# O(d*N): fixed-size state update, independent of how long we have streamed
state = Abar * state + Bbar * u[:, None] # (d, N)
return state, (state * C).sum(axis=1) # (d,)
def attn_step(kv_cache, q):
# O(L*d): must attend over every cached key/value seen so far
scores = kv_cache["k"] @ q / np.sqrt(d) # (L,)
w = np.exp(scores - scores.max()); w /= w.sum()
return w @ kv_cache["v"] # (d,)
rng = np.random.default_rng(0)
Abar, Bbar, C = rng.normal(size=(d, N)), rng.normal(size=(d, N)), rng.normal(size=(d, N))
for L in [256, 4096, 65536]:
# SSM: state size never changes with L
state = np.zeros((d, N)); u = rng.normal(size=(1, d))
t0 = time.perf_counter()
for _ in range(200): state, _ = ssm_step(state, u, Abar, Bbar, C)
t_ssm = (time.perf_counter() - t0) / 200
# Transformer: cache holds L past tokens
kv = {"k": rng.normal(size=(L, d)), "v": rng.normal(size=(L, d))}
q = rng.normal(size=d)
t0 = time.perf_counter()
for _ in range(200): _ = attn_step(kv, q)
t_attn = (time.perf_counter() - t0) / 200
print(f"L={L:6d} SSM step={t_ssm*1e6:7.1f} us "
f"attn step={t_attn*1e6:8.1f} us "
f"cache={kv['k'].nbytes/1e6:6.1f} MB")
Run this and you see the SSM step time hold flat while the attention step time and cache size climb with \(L\). That flat line is why the same Mamba weights that trained on a workstation can step on a microcontroller: nothing about the runtime cost depends on how long the sensor has been streaming.
Practical Example: an always-on hearable doing continuous activity context
A wearables team ships earbuds that infer coarse activity and head motion from an onboard IMU to steer noise cancellation, the kind of always-on inference of Chapter 26. Their first prototype used a small transformer with a 512-sample window; to keep context they either slid the window (losing the slow drift that distinguished walking from a moving vehicle) or grew a KV cache that blew the 512 KB SRAM budget within seconds. Switching the encoder to a Mamba-style block fixed the state at a few kilobytes regardless of how long the earbud had been worn, cut the per-sample energy enough to matter on a coin cell, and let the model retain minutes of context for free. Accuracy on their internal activity set moved by under a point. The win was not accuracy; it was that the constant-memory model was the only one that fit the device at all.
Right Tool: benchmark both families without writing two runtimes
You do not need to hand-build the kernels to compare them fairly. With the mamba-ssm package and Hugging Face transformers, an apples-to-apples latency and memory sweep is about 8 lines: instantiate MambaForCausalLM and a size-matched AutoModel, wrap each in torch.utils.benchmark.Timer, and sweep the sequence length. That replaces roughly 150 lines of custom timing, cache management, and CUDA-sync bookkeeping, and it gives you the tuned fused kernels (FlashAttention on one side, the hardware-aware selective scan on the other) so neither family is unfairly hobbled by a naive implementation.
On-device fit: quantization, tooling, and the honest caveats
Constant memory is necessary but not sufficient for edge deployment; the model also has to quantize cleanly and run on the runtime you actually have. Here the picture is mixed and worth stating plainly. In the model's favor: the SSM's fixed state and elementwise recurrence map naturally onto streaming, fixed-point hardware, and the absence of a growing cache removes the memory-management headache that dominates transformer edge serving. Against it: the selective SSM's internal dynamics span a wide dynamic range (the state can hold information across thousands of steps), so aggressive 8-bit quantization of the recurrence needs care, and the tooling is younger. Transformer quantization and edge runtimes (the toolchain of Chapter 59 and TinyML of Chapter 61) are far more mature, with off-the-shelf converters and vendor kernels. The practical verdict: for a long-context, streaming, tightly memory-bound target, an SSM is usually the right architecture and the extra quantization effort pays for itself; for a short-context task on a platform with a polished transformer runtime, the transformer's tooling maturity can win on time-to-ship even where the SSM would be theoretically leaner.
Research Frontier
The comparison is still moving. On the SSM side, Mamba-2 (Dao and Gu, 2024) reframes the selective scan as a structured matrix multiply to reuse the same fused, hardware-efficient kernels that made attention fast, narrowing the throughput gap on GPUs. On the evaluation side, work on associative-recall benchmarks has sharpened exactly where pure SSMs trail attention, motivating the hybrids of Section 16.6 that interleave a few attention layers into an SSM backbone to buy content recall at near-linear cost. For sensing specifically, the open questions are quantization-robust selective scans for microcontrollers and honest long-context benchmarks that report accuracy at the deployment context length rather than at a short leaderboard window. Treat any single-number claim of superiority skeptically until you see the axis and the context length it was measured at.
A decision recipe
Fold the four axes into one procedure. First, fix the context length your task truly needs, not the one a benchmark used. Second, if that length is short (hundreds of samples) and the task is recall-heavy, default to a transformer and lean on its mature tooling. Third, if the length is long (thousands and up) or the target is memory-bound and always-on, default to a selective SSM and budget a little extra time for quantization. Fourth, if you need both long cheap context and sharp recall, reach for a hybrid. In every case, measure latency and memory at the real context length with the harness above, and validate accuracy on a leakage-safe split so a long window does not smuggle test information into training. The tradeoff is a measurement, not an opinion; make it one.
Exercise
Extend the latency listing to also record peak memory (state size for the SSM, cache bytes for the transformer) and plot both step time and memory against \(L\) on log-log axes for \(L\) from \(256\) to \(262144\). Fit slopes to each curve and confirm the SSM lines are flat (slope near 0) while the attention lines have slope near 1. Then pick a memory budget (say 256 KB of SRAM) and read off the maximum context each family can serve within it. Report the crossover context length where the transformer can no longer fit but the SSM still can.
Self-Check
- Why can an accuracy comparison at a short, fixed context length mislead you about which family to deploy on a long streaming feed?
- Distinguish throughput latency from streaming step latency. Which one does an SSM win by construction, and why does that one set battery life for an always-on device?
- Name one axis on which a transformer genuinely still wins, and one deployment-side reason (not accuracy) you might pick a transformer even when an SSM is theoretically leaner.
What's Next
In Section 16.6, we stop choosing sides. Hybrid SSM-attention architectures interleave a majority of cheap linear-time SSM layers with a few attention layers, buying the SSM's constant-memory streaming and long context together with the transformer's sharp content-based recall, and we look at how to place those attention layers so the hybrid keeps almost all of the SSM's on-device thrift.