Part IV: Deep Learning for Sensor Time Series
Chapter 15: Transformers for Sensor Data

Compute-efficient deployment

"I scored one point higher on the benchmark and drew four times the current. The battery, unimpressed, filed a complaint."

A Power-Budgeted AI Agent

Why this section matters

Every earlier section in this chapter bought accuracy: attention over time and channels, patchification, positional grounding, long-context tricks, masked pretraining. This section spends the bill. A transformer that classifies gait beautifully in a notebook is worthless on a wristband if a single inference drains 40 mJ and arrives 300 ms late. Deployment is where the model meets a fixed silicon budget, a real battery, a hard latency deadline, and a thermal envelope that will throttle you if you ignore it. The good news is that transformers are unusually forgiving targets for compression: their compute is dominated by a few large dense matrix multiplies and a couple of attention kernels, so a small number of well-chosen optimizations (quantization, kernel fusion, cache reuse, distillation) move the numbers a lot. The discipline is measuring the right numbers. This section is about turning a trained sensor transformer into an artifact that hits a stated latency, energy, and memory target on a named piece of hardware, and knowing which knob to turn when it does not.

This section assumes the transformer architecture built across Sections 15.1 through 15.6, and the general edge-optimization toolkit is developed at depth in Chapter 59; here we focus on what is specific to attention-based sensor models. We keep the chapter's notation: a window is \(N\) tokens of width \(D\), stacked into \(L\) layers with \(H\) heads.

Know your cost model before you optimize

You cannot shrink what you have not measured. A transformer layer has two cost centers. The position-wise projections and the feed-forward block are dense matrix multiplies whose cost scales as \(O(N D^2)\); attention itself scales as \(O(N^2 D)\). For short sensor windows (a few hundred tokens) the \(D^2\) term dominates and you are compute-bound on the linear layers; for the long windows of Section 15.4 the \(N^2\) term takes over and you become memory-bandwidth-bound on attention. Which regime you are in decides everything: quantizing weights helps the linear-bound case, while fusing the attention kernel helps the bandwidth-bound case. The three quantities a deployment target actually specifies are latency (milliseconds per window), energy (millijoules per inference, the real currency on a battery), and peak memory (activation plus weight footprint that must fit in on-chip SRAM or tight DRAM). Report all three, because optimizing one silently trades against the others: a larger batch cuts per-window energy but raises latency and peak memory.

Energy per inference is the metric that ships, not FLOPs

FLOP counts are seductive because they are architecture-only and easy to compute, but they mispredict deployed cost badly. Two models with equal FLOPs can differ 5x in energy because one is bandwidth-bound (moving activations in and out of DRAM, which costs roughly two orders of magnitude more energy per byte than an on-chip multiply) and the other keeps its working set in SRAM. On a sensor node the dominant energy term is often data movement, not arithmetic. So the winning optimizations are frequently the ones that reduce bytes moved: lower-precision activations, kernel fusion that avoids writing intermediates to DRAM, and keeping the KV cache small. Measure joules on the actual device; treat FLOPs as a rough sanity check only.

Quantization: the highest-leverage single move

Quantization maps 32-bit floats to low-bit integers, typically 8-bit (INT8), sometimes 4-bit. The what is a per-tensor or per-channel affine map \(x \approx s\,(q - z)\) with scale \(s\) and zero-point \(z\); the why is that INT8 matmuls run 2x to 4x faster and use roughly a quarter of the memory bandwidth of FP32, and many microcontroller and DSP targets have no fast float unit at all; the how comes in two flavors. Post-training quantization (PTQ) calibrates \(s\) and \(z\) from a few hundred representative windows and needs no retraining, which is the right first attempt. Quantization-aware training (QAT) simulates the rounding during fine-tuning so the network learns weights robust to it, recovering the last point or two of accuracy when PTQ falls short. Transformers have one notorious wrinkle: activation outliers in the attention and layer-norm paths blow up the quantization range, so keep layer-norm and the softmax in higher precision and quantize the big linear layers aggressively. Do the accuracy check on a leakage-safe split (Chapter 5), because a quantized model that memorized a subject will look fine on a leaky test and fail in the field.

The snippet below applies dynamic INT8 quantization to the linear layers of a trained sensor transformer and measures the size reduction, the cheapest experiment in the whole optimization budget.

import torch, torch.nn as nn, io

def size_kb(m):
    buf = io.BytesIO(); torch.save(m.state_dict(), buf)
    return buf.getbuffer().nbytes / 1024

model = torch.load("sensor_transformer.pt").eval()   # your trained patch transformer

# Dynamic PTQ: weights -> INT8, activations quantized on the fly at runtime.
qmodel = torch.quantization.quantize_dynamic(
    model, {nn.Linear}, dtype=torch.qint8)

x = torch.randn(1, 128, 64)                            # one window: 128 tokens, D=64
print(f"fp32 {size_kb(model):7.1f} KB -> int8 {size_kb(qmodel):7.1f} KB")
torch.testing.assert_close(model(x), qmodel(x), atol=5e-2, rtol=5e-2)  # sanity
Dynamic post-training INT8 quantization of the linear layers, with a size readout and a tolerance check. Typical result is a 3.5x to 4x shrink of the linear-layer weights with sub-point accuracy loss; the assert guards against a botched conversion.

One call instead of a hand-rolled quantizer

Writing the calibration loop, per-channel scale estimation, fake-quant nodes, and INT8 kernels by hand is 200-plus lines and easy to get subtly wrong. torch.quantization.quantize_dynamic (above) is one call for the PTQ baseline; torch.ao.quantization or onnxruntime's quantization tools handle static PTQ and QAT with calibration in a dozen lines, and export to a runtime (ONNX Runtime, TensorRT, TFLite) that ships fused INT8 kernels for your target. The library owns the numerics and the hardware-specific kernel selection; you own choosing which layers stay in higher precision.

Distillation, pruning, and cache reuse

When quantization alone misses the budget, three further moves apply. Knowledge distillation trains a small student transformer (fewer layers, narrower \(D\), fewer heads) to match the soft outputs and, often, the attention maps of a large teacher; the student reaches accuracy its size alone would not, because the teacher's smoothed targets carry more information than hard labels. This pairs naturally with the masked pretraining of Section 15.6: distill from a heavy pretrained model into a deployable one. Structured pruning removes whole heads or feed-forward channels (unstructured sparsity rarely helps real hardware because it needs sparse-matmul support the target lacks); many attention heads turn out redundant on sensor tasks, so head pruning is a reliable 20-to-40 percent win. Finally, for streaming inference where a new sample arrives every few milliseconds, the KV cache stores the keys and values of past tokens so each step recomputes attention only for the newest token, turning per-step cost from \(O(N^2)\) into \(O(N)\); this is the single most important trick for real-time causal deployment, and its memory footprint (\(2 L H\) times cache length times head dimension) is often the binding constraint, which is why efficient-attention variants and the state-space models of Chapter 16 exist.

A hearing aid running a transformer denoiser at 10 mW

A hearing-aid team ports an attention-based speech-and-environment classifier onto a low-power DSP with a 10 mW active budget and a 10 ms end-to-end latency deadline, because audio delay past that becomes perceptible. The FP32 research model needs 55 mW and 22 ms: dead on arrival. They apply the stack in order. INT8 PTQ (keeping layer-norm in FP16) cuts energy 3.2x and, more importantly, lets the working set live in on-chip SRAM so activations never hit DRAM, which is where most of the power was going. Pruning six of twelve attention heads, chosen by their low average attention entropy, removes 30 percent of the attention cost with a 0.4-point accuracy drop. A KV cache makes the model causal-streaming so each 8 ms audio frame costs a single-token update rather than a full-window recompute. The shipped model runs at 8.9 mW and 7 ms, inside both budgets, and the team validates on a held-out set of unseen acoustic scenes to be sure the pruning did not overfit the calibration environments.

Kernels, runtimes, and the deployment target

Optimizations chosen on paper only pay off if the runtime emits kernels that exploit them. Three practical levers: operator fusion collapses the attention softmax, scaling, and matmuls into one kernel (FlashAttention is the canonical example) so intermediate scores are never written to DRAM, which is a large bandwidth and energy win on long windows; graph-level compilation (ONNX Runtime, TensorRT, TVM, TFLite, ExecuTorch) fuses adjacent linear-plus-activation ops, picks INT8 kernels, and lays out memory for the specific chip; and batching or windowing policy trades latency for throughput, which matters on a gateway aggregating many sensors but hurts a single-stream wearable. The target dictates the toolchain: a Cortex-M microcontroller wants TFLite Micro or CMSIS-NN and lives inside a few hundred kilobytes (the province of Chapter 61), a phone-class NPU wants NNAPI or Core ML, and a Jetson-class edge GPU wants TensorRT. Always benchmark on the actual device under the real thermal load, because a bench measurement taken cold will not survive sustained duty cycling.

Where the field is moving

The current frontier pushes below INT8. SmoothQuant and GPTQ-style 4-bit weight quantization, first proven on large language models, are migrating to time-series and sensor transformers, and hardware-aware kernels such as FlashAttention-2 and FlashAttention-3 keep cutting the bandwidth cost of attention. On the sensor-foundation-model side, models like MOMENT and Google's Large Sensor Model raise the question of how to deploy a pretrained giant on a wristband at all; the answer is increasingly distillation into a small task-specific student plus INT8 or INT4 export. Meanwhile the linear-time state-space models of Chapter 16 compete by removing the quadratic term entirely, and hybrid attention-SSM designs try to keep the transformer's accuracy at the SSM's deployment cost. Watch also the uncertainty question: an aggressively quantized model can become overconfident, so pair compression with the calibration checks of Chapter 18.

Exercise

Take your trained patch transformer from the chapter lab. (1) Profile it on a target device (or a CPU with a thread cap as a proxy) and report latency, peak memory, and, if you can, energy per window; identify whether you are linear-bound or attention-bound by varying \(N\) and \(D\). (2) Apply INT8 PTQ and re-measure all three, plus accuracy on a leakage-safe split. (3) Prune the two lowest-entropy attention heads and re-measure. (4) Plot accuracy against energy for the three variants and state which one you would ship for a wearable with a 20 mJ per-window budget, and why.

Self-check

1. Why can two models with identical FLOP counts differ several-fold in deployed energy, and what physical cost does FLOPs ignore?

2. Which transformer sub-layers should you keep in higher precision when quantizing, and what failure mode motivates this?

3. What does a KV cache change about the per-step cost of causal streaming inference, and which resource does it trade away to get that?

Lab 15

train a patch transformer for sensor classification; compare with CNN/TCN baselines.

Bibliography

Quantization and compression

Xiao, Lin, Seznec, Wu, Demouth, Han (2023). SmoothQuant: Accurate and Efficient Post-Training Quantization for Large Language Models. ICML.

Introduces the outlier-smoothing trick that makes INT8 quantization of attention models work despite activation outliers, the exact failure mode called out for sensor transformers here.

Frantar, Ashkboos, Hoefler, Alistarh (2023). GPTQ: Accurate Post-Training Quantization for Generative Pre-trained Transformers. ICLR.

The reference method for pushing transformer weights to 3 to 4 bits with minimal accuracy loss, now migrating from language models to time-series and sensor transformers.

Hinton, Vinyals, Dean (2015). Distilling the Knowledge in a Neural Network. NeurIPS Deep Learning Workshop.

The original knowledge-distillation paper; the foundation for compressing a heavy pretrained sensor transformer into a deployable student.

Efficient attention kernels

Dao, Fu, Ermon, Rudra, Re (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. NeurIPS.

The IO-aware fused attention kernel that removes the DRAM round-trip for attention scores, the canonical operator-fusion win cited in the runtime discussion.

Dao (2023). FlashAttention-2: Faster Attention with Better Parallelism and Work Partitioning. arXiv.

The follow-up that further improves attention throughput; part of the ongoing frontier of cutting attention bandwidth cost.

Pruning and edge deployment

Michel, Levy, Neubig (2019). Are Sixteen Heads Really Better than One? NeurIPS.

Empirical evidence that many attention heads are redundant and can be pruned, the basis for the head-pruning move used in the hearing-aid example.

Jacob, Kligys, Chen, Zhu, Tang, Howard, Adam, Kalenichenko (2018). Quantization and Training of Neural Networks for Efficient Integer-Arithmetic-Only Inference. CVPR.

The affine integer-quantization scheme and quantization-aware training recipe underlying INT8 deployment on float-free sensor hardware.

Sensor and time-series foundation models

Goswami, Szafer, Choudhry, Cai, Li, Dubrawski (2024). MOMENT: A Family of Open Time-Series Foundation Models. ICML.

A large pretrained time-series transformer that concretely raises the deploy-a-giant-on-a-small-device problem this section answers with distillation and quantization.

What's Next

In Chapter 16, we take the deployment pressure of this section to its logical conclusion and ask what happens if we remove the quadratic attention cost altogether. State-space models (S4, S5, and the selective Mamba family) process sequences in linear time with a bounded recurrent state, promising transformer-class accuracy at a fraction of the memory and energy on long sensor streams, and we will benchmark that promise head to head.