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

Masked sensor modeling

"You hid a third of the accelerometer window and asked me to guess it back. After a million windows, I stopped guessing and started understanding walking."

A Self-Supervised AI Agent

Prerequisites

This section builds directly on the patch tokens of Section 15.2 and the encoder mechanics of Section 15.1, because a masked model masks and reconstructs patches with an attention encoder. It assumes the channel-layout choices of Section 15.5, since where you mask (in time or across sensors) interacts with whether the model mixes channels. You should be comfortable with the idea of a pretext task and with the leakage-safe splitting discipline of Chapter 5, which decides whether your unlabeled pretraining data secretly contains your test subjects. No familiarity with contrastive learning is needed; that alternative is the subject of Chapter 17.

The Big Picture

Labeled sensor data is expensive and rare. A wearable fleet streams billions of accelerometer windows a day, but almost none carry a clinician-verified activity label. Masked sensor modeling turns that flood of unlabeled signal into supervision for free. You hide part of each window, ask a transformer to reconstruct the hidden part from what remains, and in doing so force the network to learn how a sensor stream is put together: how a gait cycle continues, how three accelerometer axes co-move, how a vibration harmonic repeats. The reconstruction target is the data itself, so no human ever labels anything. Once pretrained, the encoder is a reusable feature extractor: freeze it and fit a small head with the few hundred labels you actually have. This is the sensor-domain descendant of masked language modeling and the masked autoencoder for images, and it is the engine behind most sensor and time-series foundation models in Chapter 20.

Why reconstruct what you already have?

The pretext looks circular: hide data you possess, predict it back. The value is not the prediction but the representation the network must build to make that prediction possible. To fill a masked gap in an ECG trace, a model has to encode the QRS morphology and the rhythm well enough to extrapolate the missing beat. To recover a masked axis of an inertial window, it must have learned the geometric coupling between axes that a real motion imposes. These are exactly the features a downstream classifier wants, and they were learned without a single label. Formally, masked modeling minimizes a reconstruction loss over only the masked positions,

$$\mathcal{L}_{\text{mask}} = \frac{1}{|\mathcal{M}|}\sum_{i \in \mathcal{M}} \big\lVert \hat{x}_i - x_i \big\rVert_2^2,$$

where \(\mathcal{M}\) is the set of masked patch indices and \(\hat{x}_i\) is the model's estimate of masked patch \(x_i\). Computing the loss only on \(\mathcal{M}\), not on the visible patches, is deliberate: it stops the network from taking the lazy shortcut of copying visible input through and forces every gradient to reward genuine inference about hidden content.

Key Insight

Masking is a solvable-difficulty knob. Mask too little and the task is trivial: neighboring samples in an oversampled signal are so correlated that linear interpolation wins, and the network learns nothing. Mask too much and the task is impossible: there is not enough context to reconstruct anything, and the model regresses to the mean. The sweet spot is high because sensor signals are smooth and redundant. Images tolerate around 75 percent masking; sensor patch models commonly sit in the 40 to 75 percent range, far above the 15 percent that masked language modeling uses on discrete, information-dense text. The right ratio is the one that makes the pretext just barely solvable from long-range structure rather than local smoothness.

The geometry of the mask: time, channels, and blocks

What you hide decides what the model learns. Three masking geometries dominate, and they are not interchangeable. Random patch masking in time hides scattered temporal patches within each channel; the model learns temporal continuation and is the default for univariate or channel-independent designs. Block (span) masking hides one long contiguous stretch, which is harder than the same fraction scattered, because the model cannot lean on immediate neighbors and must reason over the full window; this better matches the real failure mode of a dropout or a sensor going dark for a second. Channel masking hides entire sensors for the window and asks the model to impute them from the surviving channels, which is only meaningful in a channel-mixing architecture (Section 15.5) and directly rehearses the missing-modality robustness that Chapter 50 depends on. Many strong recipes combine them: mask random time patches most of the time and occasionally black out a whole channel, so the encoder becomes fluent in both temporal continuation and cross-sensor imputation.

There is also an efficiency prize specific to the autoencoder design. In the masked autoencoder (MAE) recipe, the heavy encoder sees only the visible patches; the mask tokens are inserted just before a lightweight decoder. With 75 percent of patches dropped, the encoder processes a quarter of the sequence, and because attention cost grows with the square of sequence length (Section 15.4), pretraining runs several times faster and cheaper than a model that must attend over the full window.

import torch

def mask_patches(x, mask_ratio=0.5):
    # x: (batch, num_patches, patch_dim), a patchified sensor window
    B, N, D = x.shape
    keep = int(N * (1 - mask_ratio))
    # per-sample random order; smallest-noise patches are kept
    order = torch.argsort(torch.rand(B, N, device=x.device), dim=1)
    keep_idx, mask_idx = order[:, :keep], order[:, keep:]
    visible = torch.gather(x, 1, keep_idx.unsqueeze(-1).expand(-1, -1, D))
    # boolean mask marks which of the N patches were hidden (loss computed here only)
    is_masked = torch.ones(B, N, dtype=torch.bool, device=x.device)
    is_masked.scatter_(1, keep_idx, False)
    return visible, keep_idx, mask_idx, is_masked

x = torch.randn(4, 16, 32)          # 4 windows, 16 patches, 32-dim each
visible, keep_idx, mask_idx, is_masked = mask_patches(x, mask_ratio=0.5)
print(visible.shape, int(is_masked[0].sum()))   # (4, 8, 32)  8
Random patch masking for a patchified sensor window. Only the visible patches enter the MAE encoder; keep_idx lets the decoder scatter reconstructions back into place, and is_masked selects the positions the reconstruction loss is averaged over. Swapping the per-sample random order for a contiguous span turns this into block masking.

The listing above shows why the bookkeeping matters: you must remember the original position of every kept patch so the decoder can re-slot it and add positional encoding, and you must carry is_masked so the loss is scored only where it should be.

Practical Example: pretraining a wrist IMU encoder

A wearables team has 50,000 hours of raw 50 Hz wrist accelerometer and gyroscope from a consumer band, and only 900 hours labeled with activity types by a lab study. Training a supervised transformer on 900 hours overfits the study's twelve participants and collapses on new wrists. Instead they patchify each 10-second window, mask half the patches, and pretrain a channel-mixing encoder to reconstruct them across all 50,000 hours, occasionally masking the entire gyroscope so the model learns to infer rotation from linear acceleration. This is essentially the LIMU-BERT recipe for inertial data. They then freeze the encoder and fit a linear activity head on the 900 labeled hours. Macro-F1 on held-out wrists rises sharply versus the from-scratch supervised baseline, and the biggest gains appear on the rare classes (stair climbing, cycling) where labels were thinnest, because the encoder already understood the motion before it ever saw a label. Crucially, subjects in the labeled test set were excluded from pretraining too, or the leakage rules of Chapter 5 would inflate the whole result.

Reconstruction targets and the smooth-signal trap

Predicting raw amplitude with a mean-squared loss is the simplest target and often enough, but it has a known weakness: because sensor signals are dominated by low frequencies, an \(L_2\) loss lets the model win by matching the slow envelope while smearing the transients that carry the diagnostic information (a foot strike, a valve knock, an arrhythmic beat). Three fixes recur. Normalize each patch to zero mean and unit variance before scoring, so the loss cannot be dominated by DC offset and gain, a trick that also stabilizes across sensors with different sensitivities (Chapter 2). Reconstruct in a time-frequency representation rather than raw amplitude, so the loss weights spectral content the way Chapter 7 does; this is the approach that works well for vibration and audio-like signals. Or add a masked frequency objective alongside the time one, which is the idea behind SimMTM and related series-modeling methods. The lesson: choose the target so that reconstructing it well is impossible without capturing the structure your downstream task cares about.

Right Tool: skip the plumbing

Writing masked pretraining from scratch means the masking sampler, the visible-only encoder, positional re-slotting, mask tokens, the masked-only loss, and a train loop, roughly 150 to 200 lines before you can pretrain anything. Libraries collapse this. tsai exposes a MVP (masked value prediction) callback that wraps any of its time-series transformers, so masked self-supervised pretraining on a multivariate array is about 5 lines: build the learner, attach the callback with a mask ratio, and call fit. The library handles the masking geometry, the loss restriction to masked positions, and the checkpoint you later fine-tune. Reach for the from-scratch version only when you need a custom masking geometry (say, physically correlated channel dropouts) the callback does not expose.

When masked modeling is the right choice

Prefer masked modeling when unlabeled sensor data vastly outnumbers labeled, when the downstream tasks are diverse enough that one reusable encoder amortizes the pretraining cost, and when your signals are continuous and locally redundant so reconstruction is a meaningful pretext. It is the natural pretraining route for the foundation models of Chapter 19. It is a weaker choice when labels are plentiful (train supervised and skip the detour), when the signal is so noisy that reconstructing it rewards memorizing noise, or when you care about invariances that reconstruction does not capture: if you want an encoder that ignores sensor placement or device, a contrastive objective that explicitly pulls augmented views together (Chapter 17) may transfer better. In practice the two are complementary, and several strong systems combine a masked reconstruction loss with a contrastive one.

Research Frontier

Masked reconstruction is now the dominant pretraining objective for open time-series foundation models. MOMENT (2024) pretrains a family of transformers by masked patch reconstruction across a large multi-domain corpus and releases a general-purpose encoder for forecasting, classification, and anomaly detection. Ti-MAE and PatchTST established that patch-level masked pretraining beats point-level masking and improves both forecasting and transfer. SimMTM reframes the pretext as reconstructing a masked series from its neighbors in a learned series manifold, adding a frequency-aware objective. On the sensor side, LIMU-BERT brought masked reconstruction to inertial data on constrained wearables. The open questions are the masking geometry that best matches physical sensor dropout, how to mask across heterogeneous multi-rate channels (Chapter 14 discusses irregular sampling), and how much masked pretraining still helps once state-space backbones (Chapter 16) replace attention.

Exercise

Take a 50 Hz triaxial accelerometer dataset with an activity label. Patchify 10-second windows and pretrain a small transformer encoder with random patch masking at ratios of 15, 50, and 75 percent, then freeze each encoder and fit a linear probe on 5 percent of the labels. Plot linear-probe accuracy against masking ratio. Then repeat the 50 percent run with contiguous block masking instead of scattered masking and compare. Which geometry gives the better frozen features, and does the best masking ratio match the redundancy of your signal?

Self-Check

  1. Why is the reconstruction loss computed only over the masked patches and not over the visible ones?
  2. Sensor patch models mask 40 to 75 percent, but masked language modeling masks about 15 percent. What property of sensor signals explains the difference?
  3. You want an encoder that can impute a failed gyroscope from the surviving accelerometer. Which masking geometry rehearses that ability, and why does it require a channel-mixing architecture?

What's Next

In Section 15.7, we turn from how to pretrain these transformers to how to run them cheaply once trained: quantization, patch and token reduction, distillation, and the deployment tradeoffs that decide whether a masked-pretrained encoder can actually live on a wearable or an edge gateway rather than a server.