Part IV: Deep Learning for Sensor Time Series
Chapter 17: Self-Supervised and Contrastive Sensor Learning

Relative and relational objectives (RelCon)

"Two joggers are not identical and not strangers. Most of the world lives in that gap, and a binary label refuses to see it."

A Graded AI Agent

The Big Picture

Standard contrastive learning (Section 17.2) is built on a hard binary: the augmented copy of a window is a positive, every other window in the batch is a negative. For sensor streams that lie is expensive. Two accelerometer windows from two people walking are not the same sample, yet they are far more alike than a walking window and a keyboard-typing window. Treating both as equally "negative" pushes genuinely similar motion apart and wastes the structure that makes sensor data learnable. Relative and relational objectives replace the binary with a graded target: embeddings should encode not just same or different, but how much. This section develops that idea and its cleanest instance, RelCon, a relative-contrastive recipe that trained one of the largest motion foundation models to date. It assumes you are comfortable with the InfoNCE loss and cosine-similarity embeddings from Section 17.2 and the temporal representation ideas of Section 17.4; time alignment concepts trace back to Chapter 3.

Why binary positives break on sensor data

The augmentation-based positive works when a single semantic class dominates a window and augmentations are label-preserving, an assumption vision inherited from crops of one object. Sensor streams violate both halves of it. A ten-second inertial window can contain a gait cycle plus a stumble, and jitter or scaling augmentations sometimes cross a semantic boundary (a small time-warp can turn a slow walk into something the downstream head reads as a shuffle). Worse, the negative set is polluted: in any reasonably sized batch of wearable data, several "negatives" are other subjects doing the same activity, and InfoNCE dutifully repels them, injecting label noise no amount of data cleans up.

The fix is to stop pretending similarity is binary. If we had, for each anchor, a trustworthy ordering of candidates from most to least similar, we could ask the embedding to reproduce that ordering rather than a 0/1 verdict. This turns pretraining into a ranking problem over relationships between distinct real samples, hence "relative" and "relational." The two engineering questions become: (1) where does a reliable similarity ranking come from without labels, and (2) what loss turns a ranking into gradients.

Key Insight

Binary contrastive learning encodes one bit per pair ("same or not"). A relative objective encodes an ordering over many pairs, which is far more information per anchor and, critically, information that survives class-collision noise. You are no longer betting that a random batch has no false negatives; you are only betting that your similarity measure ranks candidates approximately correctly.

A learnable, label-free similarity measure

RelCon answers question (1) with a learnable distance measure trained before the main encoder. The measure judges how well one motion segment can explain another: given a candidate segment, can it reconstruct the masked portions of the anchor after an alignment that tolerates speed differences? Dynamic time warping supplies the alignment, so two walks at different cadences are recognized as close, and a reconstruction objective supplies the graded score. The result is a function \(d(x, c)\), small when \(c\) is a good motif-level match for anchor \(x\) and large otherwise, learned entirely from unlabeled signals. This is the sensor-native analogue of the intuition in Chapter 7 that similar signals share time-frequency structure, but here "similar" is fit to the data rather than fixed by hand.

For each anchor we sample \(K\) candidates from the corpus and score them with \(d\), yielding an ordering \(d_{(1)} \le d_{(2)} \le \dots \le d_{(K)}\). Nearest candidates are soft positives; farthest are clear negatives; the middle is exactly the graded region binary methods throw away.

The relative contrastive loss

Question (2) is answered by a nested InfoNCE. Order the candidates by learned distance. Then, for every rank \(j\), treat candidate \(j\) as the positive and all candidates at least as far as \(j\) as its negatives. Summing these nested terms gives

$$ \mathcal{L}_{\text{rel}}(x) = -\frac{1}{K-1}\sum_{j=1}^{K-1} \log \frac{\exp\!\big(s(z, z_{(j)})/\tau\big)}{\sum_{k \ge j} \exp\!\big(s(z, z_{(k)})/\tau\big)}, $$

where \(z\) is the anchor embedding, \(z_{(k)}\) is the embedding of the \(k\)-th nearest candidate, \(s\) is cosine similarity, and \(\tau\) is the temperature. Each term is an ordinary contrastive loss; stacking them forces \(s(z, z_{(1)}) > s(z, z_{(2)}) > \dots\), so the embedding geometry mirrors the similarity ranking. A single candidate is simultaneously a positive (against those farther) and a negative (against those nearer), which is precisely the relational bookkeeping a binary loss cannot express.

import torch
import torch.nn.functional as F

def relative_contrastive_loss(z_anchor, z_cands, dist, tau=0.1):
    # z_anchor: (D,)  z_cands: (K, D)  dist: (K,) learned distances to anchor
    z_anchor = F.normalize(z_anchor, dim=-1)
    z_cands  = F.normalize(z_cands, dim=-1)
    sim = (z_cands @ z_anchor) / tau            # (K,) cosine sim, scaled
    order = torch.argsort(dist)                 # nearest (smallest dist) first
    sim = sim[order]
    losses = []
    for j in range(sim.shape[0] - 1):
        # candidate j is positive; all farther candidates (k >= j) are negatives
        denom = torch.logsumexp(sim[j:], dim=0)
        losses.append(denom - sim[j])
    return torch.stack(losses).mean()

# toy check: distances that agree with embedding sims give a lower loss
z  = torch.randn(64)
zc = torch.randn(8, 64)
d  = torch.arange(8.0)                          # candidate 0 is "closest"
print(float(relative_contrastive_loss(z, zc, d)))
A minimal relative contrastive loss: candidates are sorted by the learned distance dist, then a nested InfoNCE enforces that embedding similarity decreases monotonically with distance. In practice dist comes from the pretrained similarity measure, not the raw signal, and the loop is vectorized over a batch of anchors.

The loop above is written for clarity; a production implementation vectorizes it across a batch of anchors, as the callout below explains. The temperature and the candidate count \(K\) are the two knobs that matter: too small a \(K\) and the ranking is noisy, too large and most candidates are trivially far and contribute nothing.

Common Misconception

It is tempting to assume the nested sum in \(\mathcal{L}_{\text{rel}}\) reruns the encoder \(K\) times, once per rank. It does not: all \(K\) candidate embeddings are computed once, and the nested denominators simply reuse different suffixes of the same similarity vector, so the reference implementation collapses the loop into one cumulative logsumexp pass. A second, easier trap is conflating the two distances in play: \(d(x, c)\), which decides the ranking, and \(s(z, z_c)\), which the loss optimizes, come from two different networks. \(d\) is the DTW-reconstruction model, trained to convergence and frozen; \(s\) is the encoder RelCon is currently training. Let one network produce both and the ranking chases a moving target, which is why the distance measure is fit first and frozen before the contrastive stage begins.

Library Shortcut

You do not have to hand-roll the ranking machinery. pytorch-metric-learning ships ranked-list and multi-similarity losses plus distance-weighted miners that select and order candidates for you; feeding it your learned distances as the pairing signal replaces roughly 40 lines of nested-loop loss and miner code with about 5, while the library handles numerically stable log-sum-exp, hard-pair mining, and cross-batch memory banks. The one piece it cannot supply is the sensor-specific distance measure itself, which stays bespoke because it encodes what "similar motion" means for your modality.

Practical Example: a wearable motion foundation model

An Apple team applied exactly this recipe in RelCon, pretraining on roughly one billion accelerometer segments from about 87,000 participants in the Apple Heart and Movement Study, with no activity labels at all. The learnable DTW-based measure ranked candidate motions per anchor, and the relative contrastive loss shaped a single encoder that, frozen, transferred across independent human-activity benchmarks (gait, activity classification, energy expenditure), beating prior self-supervised wearable encoders on most downstream tasks. The lesson for a product team: the graded objective let one model absorb messy, multi-subject, unlabeled motion that binary contrastive learning would have poisoned with false negatives, and the payoff showed up as label efficiency on every activity head built on top of it (see Chapter 26). Cross-user transfer like this is the whole promise of sensor foundation models in Chapter 20.

When relational objectives are the right tool

Reach for a relative or relational loss when three conditions hold: labels are absent, the corpus has heavy class overlap (many subjects or devices repeating the same motions, so false negatives are rife), and you can define a cheap, trustworthy similarity between distinct samples. Inertial and physiological streams (Chapter 23) fit perfectly. When the corpus is genuinely single-class per window and augmentations are safe, the extra machinery buys little and plain SimCLR-style contrastive learning is simpler and just as good.

Nearest-neighbor variants such as NNCLR (Dwibedi et al., 2021) are a lighter-weight cousin, useful when a bespoke similarity measure is not worth engineering. Instead of ranking a whole candidate set against a learned distance, NNCLR keeps a support queue of recent embeddings and, at each step, swaps the augmented view for the anchor's single nearest neighbor in that queue, then runs ordinary binary InfoNCE against it: a real, different sample stands in for the synthetic positive, at the cost of a queue lookup rather than a trained distance model and a nested loss. What it gives up is the graded ordering that makes RelCon's geometry finer-grained, so reach for the full ranking when the downstream task rewards that, such as regressing energy expenditure rather than only classifying activity. As always in this book, evaluate on a leakage-safe split: because relational objectives explicitly pull same-activity samples together, a subject leaking across the train/test boundary can inflate scores dramatically, so hold out whole subjects and devices per Chapter 5.

Research Frontier

RelCon (Xu et al., 2024, arXiv:2411.18822, ICLR 2025) is the current reference point for relative contrastive pretraining on wearable motion, notable for pairing a learnable DTW-reconstruction distance with the nested relative loss at billion-segment scale. Active directions include making the similarity measure multimodal (ranking motion by co-recorded PPG or audio rather than motion alone), replacing per-anchor candidate sampling with a maintained ranked memory to cut compute, and extending the graded target beyond one modality toward the cross-device, cross-user objectives of the next section. The open question is whether a learned similarity can be trusted enough to define ranks without occasionally encoding its own biases into the foundation model.

Exercise

Take a small labeled HAR dataset (PAMAP2 or UCI-HAR). Build a per-anchor candidate set of size \(K = 16\) and define the "distance" \(d\) two ways: (a) Euclidean distance in raw signal space, and (b) DTW distance. Train two encoders with the relative contrastive loss above, then freeze each and fit a linear probe. Report the label-efficiency curve (accuracy vs number of labeled examples). Does the alignment-aware distance in (b) transfer better, and by how much at 1% of labels?

Self-Check

  1. Explain in one sentence why a batch of walking windows from many subjects is a failure mode for binary InfoNCE but an advantage for a relative objective.
  2. In the nested loss \(\mathcal{L}_{\text{rel}}\), what role does a single candidate at rank \(j\) play with respect to candidates at ranks \(< j\) versus \(> j\)?
  3. Why must the learned distance measure be trained before the encoder rather than jointly, and what would go wrong if the two were optimized against each other from scratch?

What's Next

In Section 17.6, we scale the relational idea across boundaries: pretraining that spans different devices, different users, and different modalities at once, where the notion of "similar" must survive a change of sensor, sampling rate, and body location.