Part XIII: Trust, Safety, Evaluation, and Operations
Chapter 66: Distribution Shift, OOD, and Test-Time Adaptation

Benchmarks (HAROOD, BenchHAR, WILDS)

"Every method I met claimed to beat distribution shift. Then I checked whether the same subject was in both the train and the test split, and most of the miracles evaporated."

A Skeptical AI Agent

Prerequisites

This section assumes the leakage-safe splitting discipline of Chapter 65 and the leakage-aware dataset construction of Chapter 5: if you cannot yet say why a random 80/20 split of a human-activity dataset overstates accuracy, read those first. It uses the shift taxonomy of Section 66.1, the OOD scores of Section 66.2, and the calibration language of Chapter 18. The adaptation methods being measured (DIVERSIFY, TENT, CoTTA) come from Sections 66.3 through 66.5.

The Big Picture

Every prior section in this chapter proposed a way to survive shift. This one asks the harder question: how do you measure whether any of it worked, without fooling yourself? A benchmark for distribution shift is not just a dataset plus an accuracy number. It is a contract about which axis of variation is held out (subject, device, site, session), which metrics are reported (worst-group accuracy, OOD detection AUROC, adaptation recovery), and which forms of leakage are forbidden. Get the contract wrong and a method that merely memorized subjects will post a beautiful number. This section covers three reference points that get the contract right: WILDS, the general in-the-wild shift benchmark that made "domain" a first-class metadata axis; BenchHAR, the cross-subject, cross-device, cross-dataset evaluation protocol for human-activity recognition; and HAROOD, which turns HAR into a proper open-world out-of-distribution detection task.

What a shift benchmark must specify before it reports a number

An ordinary benchmark answers "how accurate is the model on held-out data drawn from the same distribution as training." A shift benchmark must answer something stricter: "how accurate is it on data drawn from a distribution the model has never seen, and does it know when it is guessing." That requires four commitments the benchmark author has to make explicit. First, the shift axis: the metadata field along which train and test are separated. In sensing this is almost always subject, device, body position, or recording site, never a random row shuffle. Second, the split protocol: leave-one-subject-out (LOSO), leave-one-device-out, or a fixed OOD test split with a disjoint validation domain used for model selection. Third, the metric set: not just mean accuracy but the worst-performing group, because a fleet is only as trustworthy as its unluckiest deployment. Fourth, the adaptation budget: whether test-time adaptation is allowed, how many unlabeled target samples it may see, and whether it adapts online or offline. A benchmark that leaves any of these implicit is a benchmark you can beat by accident.

Key Insight

The single most common way sensor "robustness" results are inflated is subject leakage: windows from the same person, sliding-window-overlapped, land in both train and test. The model recognizes the person, not the activity, and reports 95% where an honest leave-one-subject-out split would report 78%. The entire value of WILDS, BenchHAR, and HAROOD is that they remove your ability to make this mistake: the split is defined by domain metadata, so same-subject or same-device leakage is structurally impossible. When you read a distribution-shift paper, the first thing to check is not the method, it is whether the split held out the axis the method claims to conquer.

WILDS: making the domain a first-class citizen

WILDS (Koh et al., 2021) is the framework that reframed distribution-shift evaluation for the whole field. Its contribution is less any single dataset than a discipline: every example carries a domain label (which hospital, which camera trap, which region, which time period), and the benchmark ships an official split in which the test domains are disjoint from the training domains. It distinguishes two shift structures that sensing engineers meet constantly: domain generalization, where you must perform on domains never seen in training, and subpopulation shift, where all groups appear in training but their proportions change at test time. Crucially WILDS reports worst-group or worst-domain performance alongside the average, which is the number that matters when a model will be deployed across a fleet of heterogeneous sensors. Although WILDS's headline datasets are vision and text, its protocol is exactly what a sensor benchmark needs, and the modern HAR benchmarks below are best understood as WILDS's discipline applied to inertial and physiological streams.

BenchHAR: cross-subject, cross-device, cross-dataset HAR

BenchHAR names the unified evaluation protocol for sensor-based human-activity recognition: a common set of public datasets (the lineage runs through UCI-HAR, PAMAP2, Opportunity, DSADS, USC-HAD, and the heterogeneity-focused HHAR), a common windowing and preprocessing pipeline, and, above all, a common set of leakage-safe splits. It evaluates along three shift axes that a wearable actually experiences. Cross-subject (leave-one-subject-out) probes covariate shift from gait and body morphology. Cross-device probes the sampling-rate, sensitivity, and mounting differences that HHAR was built to expose, where a model trained on one phone model quietly fails on another. Cross-dataset is the harshest: train on one study's protocol and sensors, test on another's, which folds in label-definition drift as well as covariate shift. The value of a named protocol is comparability: when two adaptation methods both report BenchHAR cross-device F1, the numbers mean the same thing, which is precisely what ad-hoc per-paper splits destroyed. This is the protocol Lab 66 builds on, and it is the natural evaluation home for the DIVERSIFY, TENT, and optimization-free methods of Sections 66.3 through 66.5.

HAROOD: turning HAR into an open-world detection task

Closed-set HAR assumes every test window belongs to one of the training classes. Deployed wearables violate this hourly: the wearer does something the taxonomy never covered (climbing a ladder, swimming, simply fidgeting), and a closed-set model must, by construction, assign it a known label with often high confidence. HAROOD reframes HAR as an out-of-distribution detection problem: the benchmark holds out entire activity classes as "unknown," and the model is scored not only on classifying the known activities but on abstaining on the unknown ones. Its metrics are the OOD-detection standard from Section 66.2: AUROC for separating in-distribution from out-of-distribution windows, and FPR@95TPR, the false-positive rate when the detector is tuned to catch 95% of true novelties. This matters for safety: a fall detector that confidently classifies an unseen motion as "walking" is worse than one that says "I do not know." HAROOD is where the OOD scores of this chapter get their honest report card.

Step-Through: a clinical gait study that looked solved and was not

A rehabilitation group trains a wearable classifier to score six post-stroke gait patterns from ankle IMUs, and reports 93% macro-F1. On the BenchHAR cross-subject protocol the number falls to 74%, because the original split had multiple sessions from the same patient on both sides of the line. Worse, on HAROOD it emerges that when a patient performs a compensatory movement outside the six trained patterns, the model labels it "normal gait" with 0.9 confidence and an AUROC of 0.58, barely above chance. The team keeps the honest 74% as their headline, adds an OOD score with a threshold set at FPR@95TPR from the HAROOD calibration split, and routes flagged windows to a clinician. The reported number went down; the deployed system got safer. That trade, a smaller true number over a larger false one, is the entire reason these benchmarks exist, and it is the operational handoff that Chapter 69 turns into fleet monitoring.

Computing the numbers that actually matter

Three metrics carry most of the weight in these benchmarks, and none of them is mean accuracy. Code 66.7.1 computes all three from a scored evaluation set: worst-group accuracy (the WILDS/BenchHAR discipline), and the AUROC plus FPR@95TPR pair that HAROOD uses to score abstention. Reading it makes the contract concrete: the OOD score is just a per-window confidence, and the benchmark is a ranking problem over those scores.

import numpy as np
from sklearn.metrics import roc_auc_score

def worst_group_accuracy(y_true, y_pred, group):
    """Min over domains (subject/device) of per-group accuracy: the fleet's unluckiest sensor."""
    accs = []
    for g in np.unique(group):
        m = group == g
        accs.append((y_pred[m] == y_true[m]).mean())
    return min(accs), np.mean(accs)          # worst-group, and average for contrast

def fpr_at_95_tpr(id_score, ood_score):
    """OOD detection: higher score = more in-distribution. FPR when 95% of true OOD is caught."""
    y = np.r_[np.ones_like(id_score), np.zeros_like(ood_score)]   # 1 = in-dist
    s = np.r_[id_score, ood_score]
    auroc = roc_auc_score(y, s)
    thr = np.quantile(ood_score, 0.95)       # threshold catching 95% of OOD (TPR_ood)
    fpr = (id_score < thr).mean()            # in-dist windows wrongly flagged as OOD
    return auroc, fpr

wg, avg = worst_group_accuracy(y_true, y_pred, subject_id)
auroc, fpr95 = fpr_at_95_tpr(id_conf, ood_conf)
print(f"worst-group {wg:.3f}  avg {avg:.3f}  |  OOD AUROC {auroc:.3f}  FPR@95 {fpr95:.3f}")
Code 66.7.1: the three metrics a shift benchmark reports. worst_group_accuracy returns the unluckiest domain's score next to the average, and the gap between them is the story; fpr_at_95_tpr scores open-world abstention. A model can win on average accuracy and lose badly on both of these, which is exactly what the benchmarks are designed to reveal.

The gap that Code 66.7.1 exposes between worst-group and average accuracy is the number a fleet owner cares about, because customers experience the worst group, not the mean. A method that lifts the average by two points while dropping the worst group by five has made your product less trustworthy, and only a benchmark that reports both will tell you.

Right Tool: do not hand-roll the split or the leaderboard

Code 66.7.1 shows the metrics, but the load-bearing work is the leakage-safe split and the standardized loader, and libraries own that. The wilds package exposes every official domain split, grouper, and worst-group evaluator behind a few lines, so you cannot accidentally leak a domain. For OOD detection, OpenOOD ships the detectors, the ID/OOD dataset pairings, and AUROC/FPR@95 evaluation as a single harness; for test-time adaptation, TTAB provides the reference method implementations and protocols the leaderboards were measured against. Together they replace roughly 200 to 400 lines of split logic, metric plumbing, and baseline re-implementation with a handful of configured calls, and, more importantly, they make your numbers directly comparable to published ones instead of "comparable if we trust your preprocessing."

Research Frontier

The open question is what a shift benchmark should measure in the foundation-model era. Sensor and wearable foundation models (Google's LSM, and the time-series models MOMENT and TimesFM from Chapter 20) are pretrained on such heterogeneous data that a "held-out device" may well have leaked into pretraining, which quietly breaks the disjoint-domain guarantee these benchmarks rely on. The frontier is therefore twofold: contamination-aware splits that certify a target domain was truly unseen, and few-shot or zero-shot shift protocols that ask how much labeled target data a large pretrained encoder needs to close the gap, rather than assuming none. Expect the next generation of BenchHAR-style suites to report a data-efficiency curve, not a single OOD accuracy.

How these benchmarks lie, and how to read them honestly

A benchmark is only as trustworthy as the leakage it prevents and the metric it foregrounds, so a few failure modes are worth naming. Validation-domain leakage: selecting hyperparameters on the test domains, which quietly turns domain generalization into transduction; WILDS forbids it by giving you a disjoint OOD-validation split, and you should use it. Overlapping windows across the split boundary: sliding windows from one recording bleeding across a subject cut, re-introducing the leakage the split was meant to remove. Cherry-picked shift axis: reporting cross-subject where the deployment shift is actually cross-device, so the easy axis flatters the method. Average-only reporting: hiding a collapsed worst group inside a healthy mean. And for test-time adaptation specifically, online evaluation order matters: adapting on class-sorted or tiny non-i.i.d. batches, the pitfall the TTAB benchmark was built to expose, can make an adaptation method look either magical or catastrophic depending on stream order alone. The defense is the same discipline throughout this part of the book: fix the shift axis to match the deployment, hold out the domain, report the worst group next to the average, and treat any result whose split you cannot reconstruct as unproven.

Exercise

Take a public HAR dataset with subject and device metadata (HHAR is ideal). (a) Train a classifier under a random 80/20 window split and record accuracy; this is your inflated number. (b) Re-evaluate under leave-one-subject-out and leave-one-device-out and report the worst-group accuracy of each with Code 66.7.1. (c) Hold out two activity classes as "unknown," compute a max-softmax OOD score, and report AUROC and FPR@95TPR in the HAROOD style. (d) Explain, in three sentences, which of your four numbers you would put in a product datasheet and why the largest one is the least defensible.

Self-Check

  1. A paper claims state-of-the-art cross-person HAR but selected its learning rate on the held-out subjects. Name the specific leakage and state which WILDS mechanism prevents it.
  2. Two methods report identical average accuracy on BenchHAR cross-device, but one has a worst-group accuracy 12 points lower. Which would you ship to a heterogeneous fleet, and what single metric decided it?
  3. Why is FPR@95TPR, rather than classification accuracy, the right headline number for a fall detector evaluated on HAROOD, and what real-world cost does a high FPR@95 impose?

Lab 66

evaluate a HAR model under subject/device shift; add test-time adaptation and measure the recovery.

What's Next

In Chapter 67, we stop asking whether a model is wrong and start asking why. Once a benchmark tells you the worst group collapsed under device shift, interpretability and root-cause analysis for time series let you trace that collapse back to a specific channel, frequency band, or window, so the next fix is aimed rather than guessed.

Bibliography

Distribution-shift benchmarks

Koh, Sagawa, Marklund, et al. (2021). WILDS: A Benchmark of in-the-Wild Distribution Shifts. ICML.

The framework that made the domain label a first-class metadata axis and popularized worst-group reporting for domain generalization and subpopulation shift. The protocol that the sensor benchmarks in this section inherit.

Zhao, Chen, Chen, et al. (2023). On Pitfalls of Test-Time Adaptation (TTAB). ICML.

A benchmark and cautionary study showing that TTA results swing wildly with batch composition, stream order, and hyperparameter selection. Required reading before you trust any adaptation-recovery number.

Out-of-distribution detection

Yang, Wang, Zou, et al. (2022). OpenOOD: Benchmarking Generalized Out-of-Distribution Detection. NeurIPS.

A unified harness for OOD detectors with standardized ID/OOD pairings and AUROC/FPR@95 evaluation. The reference implementation behind HAROOD-style abstention metrics.

Hendrycks, Gimpel (2017). A Baseline for Detecting Misclassified and Out-of-Distribution Examples. ICLR.

Introduced maximum-softmax-probability as the OOD baseline that every HAR-OOD benchmark still reports as its floor. Simple, hard to beat, and the right first thing to try.

Sensor and HAR benchmarks

Stisen, Blunck, Bhattacharya, et al. (2015). Smart Devices are Different: Assessing and Mitigating Mobile Sensing Heterogeneities (HHAR). SenSys.

Built the Heterogeneity Human Activity Recognition dataset that exposes cross-device sampling-rate and sensitivity shift. The canonical cross-device axis in BenchHAR-style evaluation.

Anguita, Ghio, Oneto, et al. (2013). A Public Domain Dataset for Human Activity Recognition Using Smartphones (UCI-HAR). ESANN.

The most-used public HAR dataset and a standard component of cross-subject and cross-dataset HAR protocols. Its subject metadata is what makes leave-one-subject-out possible.

Domain generalization and adaptation for time series

Lu, Wang, Sun, et al. (2023). Out-of-distribution Representation Learning for Time Series Classification (DIVERSIFY). ICLR.

Established rigorous cross-person and cross-dataset OOD evaluation for time-series classification and the DIVERSIFY method measured against it. The train-time counterpart to the adaptation methods this chapter benchmarks.

Wang, Shelhamer, Liu, et al. (2021). Tent: Fully Test-Time Adaptation by Entropy Minimization. ICLR.

The entropy-minimization method whose adaptation-recovery numbers these benchmarks were largely designed to report fairly. The baseline every TTA leaderboard entry is compared against.