Foundation Models for Health · Ultra

Ultra deep dive · Health · Foundation Models · Wearables · EHR · Sleep

Foundation Models for Health · Ultra

How foundation models for health data are built, evaluated and deployed: what makes a good health representation, the lineage of the field, the data (EHR events, clinical text, waveforms, polysomnography, wearable time series), self-supervised objectives and how to choose positives, tokenization of signals and clinical events, time-series foundation models, wearable, biosignal and sleep models, EHR foundation models, multimodal models and LLM integration, adaptation, evaluation and leakage, and practice in production, with three reference workloads (a wearable PPG encoder, a generative EHR model and a sleep PSG model) traced at every level from intuition to production.

Health AIFoundation ModelsWearablesEHRSleepTime SeriesSelf-Supervised Learning

Summary

  • A health foundation model is a single model pretrained without labels on a large body of health data and adapted cheaply to many tasks. Its value is measured by what a small head on frozen embeddings can do with few labels. In reference workload W1, a 50M-parameter wearable PPG encoder, a linear probe with 257 parameters trained on 5,000 labelled participants reaches AFib AUROC 0.93, against 0.88 for a model trained from scratch on the same labels (Definition and scope, Adaptation methods).
  • In contrastive learning, the positive pair decides what the representation keeps. W1's positives are two windows of the same participant within 24 hours, so stable traits survive and momentary state is discarded, but so does the device, which identifies a person as reliably as physiology. A checkpoint whose 10 nearest neighbours share the device 63% of the time, against a chance level of 0.30, has learned a shortcut even at AFib AUROC 0.93 (Choosing positives, What makes a good representation).
  • Health data are missing in blocks and not at random. 38% of W1's 30-million-hour grid has no PPG, so only about 6.7 of 10.8 billion window slots carry signal. Natural gaps must be masked, not imputed with zeros: on W1-like data an ETS forecaster fed zero-filled contexts scores masked MASE 9.3, against 0.90 with same-hour filling (Scaling and missingness, What the evidence says for health data).
  • Clinical events are tokenized with time and value made explicit. W2, a 120M-parameter decoder over 2 million patients, uses 42,000 codes, 64 time-gap tokens and 10 value-decile tokens. The median patient becomes about 142 tokens and the 95th percentile about 2,078, inside a 4,096-token context; the whole corpus is only about 0.46 billion tokens, roughly 3.8 per parameter, against a compute-optimal ratio near 1,000 reported for EHR models (Clinical events, Generative EHR models).
  • A generative EHR model predicts by simulation: the risk of an outcome is the fraction of sampled futures in which it occurs. One W2 patient with 7 of 64 simulated futures ending in death within a year has an estimated 1-year mortality of 0.11. The same mechanism silently underestimates risk when sampled timelines end at an end-of-record token, a bias no number of rollouts removes (Generative EHR models, Time-to-event pretraining).
  • The unit of independence is the person, and time. A W2 readmission model scores 0.78 on an admission-level split and 0.71 on a patient-disjoint one, where a count-based gradient-boosting baseline reaches 0.69. W2's headline numbers (1-year mortality 0.89, readmission 0.71, ECE 0.03) are defined only with their protocol: patient-level splits and a temporal holdout that trains on data up to 2022 and tests in 2024 (Leakage, EHR benchmarks).
  • Agreement with one scorer is bounded by how well scorers agree. W3, a sleep model over 30,000 polysomnograms, stages sleep with Cohen's κ 0.78 against single-scorer labels, near the inter-scorer κ of about 0.76; without EEG, EOG and EMG, a wearable-only student reaches 0.62. Its heart-failure C-index of 0.86 falls to 0.78 once events within 90 days of the study are excluded: prognosis and detection must be separated (From manual scoring to learned staging, SleepFM).
  • Deployment is a distribution-shift problem, and calibration breaks before ranking. At a second hospital W2's mortality AUROC holds at 0.88 while ECE rises from 0.03 to 0.09; temperature and intercept refitted on 2,000 local patients restore it. Firmware updates, unit changes and tokenizer versions cause most production incidents, so the tokenizer, the split keys and the monitors are versioned with the weights (Shift, fairness and calibration, Production challenges).

Reference workloads used in this book

The book traces three reference workloads. All their numbers are illustrative and internally consistent, identical at every level, and are not published results. Chapters refer to them as W1 to W3 and keep workload-specific material in "Worked example" and "Worked incident" callouts; this box is the specification those callouts assume. Where a callout needs a quantity the specification does not fix (a prevalence, a stage distribution, an architecture width), it states the assumption.

W1 · Wearable PPG foundation model (illustrative). The primary workload: a contrastive encoder for wrist photoplethysmography and accelerometry.

ParameterW1 value
Cohort and data150,000 participants; 30 million participant-hours of PPG + accelerometry at 64 Hz
Windows10-s windows (640 samples); ~10.8 billion windows, 1% sampled per epoch
Input channels4 (PPG + 3-axis accelerometry)
Missingness38% of the 30M-hour grid has no PPG (device off-wrist / charging), so ≈6.7B of the 10.8B window slots carry PPG
Encoder1D-CNN/Transformer, 50M parameters, 256-d embedding
ObjectiveContrastive (InfoNCE, temperature 0.1, batch 4,096, positives = same participant within 24 h)
Downstream (linear probe, 5,000 labelled participants)AFib AUROC 0.93 (supervised-from-scratch 0.88); age regression MAE 6.1 years; resting HR MAE 2.4 bpm

W2 · EHR generative model (illustrative). A decoder-only model over coded patient timelines, used for representation, zero-shot simulation and calibration.

ParameterW2 value
Cohort and events2 million patients; 310 million events; median 96 events/patient, p95 1,450
Vocabulary42,000 codes + 64 time-gap tokens + 10 value-decile tokens per lab
Value tokens10 decile tokens shared across labs with per-lab edges → vocabulary ≈ 42,074 incl. special tokens; ~35% of events carry a numeric value
ModelDecoder-only, 120M parameters, context 4,096 tokens
Tasks1-year mortality AUROC 0.89; 30-day readmission AUROC 0.71; calibration ECE 0.03
SplitsPatient-level, plus temporal holdout (train ≤ 2022, test 2024)

W3 · Sleep PSG foundation model (illustrative). A multimodal encoder for overnight polysomnography, used for staging, apnea detection and transfer to wearables.

ParameterW3 value
Data30,000 overnight PSGs (~240,000 hours); 30-s epochs (~28.8 million epochs)
Channel groupsEEG, EOG, EMG, ECG, respiratory (5)
Sleep staging (5 classes)Cohen's κ 0.78 vs single-scorer labels (inter-scorer κ ≈ 0.76)
ApneaAHI ≥ 15 detection AUROC 0.91
TransferWearable-only setting: κ 0.62

One-Pager: Building a Health Foundation Model End to End

A health foundation model is one pipeline. Harmonize records and signals into a versioned snapshot with person-level split keys, tokenize them with time, values and gaps made explicit, pretrain with an objective chosen for the intended use, register the weights together with their tokenizer, adapt with the cheapest head that meets the target, evaluate on splits that separate people, sites and years, and monitor in production for the shifts that every device update and coding change introduces. This page is that pipeline on one screen. Its numbers come from reference workloads W1 (wearable PPG), W2 (generative EHR) and W3 (sleep PSG) (Reference workloads); they are illustrative and the same at every level of the book.

What Is Being Built

Every term below is defined in Chapter 1 and recurs, with workload values, in the modality chapters. The model is an encoder or a generator over one data type, its product is an embedding or a simulated future, and its quality is judged by what a small head can do with it (Definition and scope, What makes a good representation).

TermWhat it isWorkload value (illustrative)Read
Unit of inputThe piece of data the model reads at onceW1: 10-s window, 4 channels × 640 samples. W2: a patient timeline of up to 4,096 tokens. W3: a night of 960 30-s epochs in 5 channel groups3.3, 3.1, 3.4
TokenWhat one position of the sequence model seesW1: a 1-s patch of 64 samples, 10 per window. W2: a code, a gap token or a value-decile token; median patient ≈ 142 tokens5.1, 5.2
Self-supervised objectiveThe label-free task that trains the modelW1: InfoNCE, τ = 0.1, 4,096 candidates, step-0 loss ≈ ln 4,096 = 8.32 nats. W2: next token, uniform loss ln 42,074 = 10.65 nats4.1, 9.1
Positive pairTwo views the contrastive loss pulls together; what differs between them is discardedW1: same participant within 24 h. W3: one modality group against the average of the other four4.5, 8.2
EmbeddingThe vector a frozen encoder returns for one inputW1: 256 numbers per window; about 5.5 TB in fp16 for all 10.8B window slots, 15.4 GB pooled per participant-hour1.1, 12.1
ProbeA linear, logistic or Cox head fitted on frozen embeddingsW1 AFib probe: 257 parameters on 5,000 participants, AUROC 0.93 against 0.88 from scratch11.1
Honest splitTrain and test separated by person, and by time where the use is prospectiveW2: patient-level plus temporal holdout (≤ 2022 / 2024). W1: participant-level, with one device model held out11.4

Table. The vocabulary of health foundation models, with workload values. The same seven words describe a wearable encoder, a generative EHR model and a sleep model; what changes between them is which shortcut each objective invites (Lineage threads).

The Reference Architecture

Eight stages in a loop. The top row builds a pretrained model once inside a governed environment; the middle row ships it per task and per site; monitored data returns to the next snapshot. The dashed line is the governance boundary: raw records and signals stay inside it, and only versioned artifacts (weights, tokenizer, cards, embeddings) leave it (Reference architecture, A practical playbook).

A health foundation model end to end: data sources with consent tags are harmonized into a versioned snapshot with person-level split keys, tokenized and used for self-supervised pretraining inside a governed environment; weights are registered with their tokenizer and cards, adapted per task with probes or adapters, evaluated on person, time, site and device hold-outs, and deployed with monitors whose data flows back into the next snapshot. governed environment: build once (raw data never leaves) ① Sources + consentW1: 30M part.-hoursW2: 310M eventsW3: 30,000 PSGs ② HarmonizeMEDS / OMOP · 64 Hzone split key a personversioned snapshot ③ TokenizeW1: 10 × 1-s patchesW2: ≈ 42,074 tokensgap masks · fit on train ④ PretrainW1: InfoNCE, τ 0.1W2: next token, 4,096W3: cross-modal weights, tokenizer and split keys travel together monitored data → next snapshot ⑧ Deploybatch or on-devicelocal recalibrationPCCP change control ⑦ Evaluateperson + time splitssite, device hold-outsleakage audit · CIs ⑥ Adaptlinear / Cox probeLP-FT · LoRAcalibration layer ⑤ Registryweights + tokenizermodel and data cardsembedding store Monitorsoff-wrist share · unknown-token share · PSIper-device and per-site AUROC and ECE Governance (spans every stage)consent and data use · access and audit logsprivacy review · regulatory documentation · incidents Top row: build a pretrained model once. Middle row: ship it per task and per site, and feed what is observed back.
Fig. The health foundation-model system on one screen, with W1 to W3 numbers (illustrative). Sources enter with consent tags; harmonization assigns one split key per person and freezes a snapshot; the tokenizer is fitted on training patients only; pretraining runs inside the governed environment. The registry stores weights with their tokenizer, cards and an embedding store. Each task and site gets the cheapest adaptation that meets its target, an evaluation on person, time, site and device hold-outs, and a deployment with monitors whose data (new missingness patterns, device versions, outcomes) returns to the next snapshot.

Which Objective for Which Data

The objective follows from two facts: what the data look like (dense signal, gappy aggregates, several simultaneous channels, coded events) and what the representation is for (person-level traits, imputation, prognosis, forecasting, conversation). The table gives the default each chapter argues for and the condition that changes it.

SettingDefaultWhyChange whenRead
Raw wearable or ECG windows, person-level targetsContrastive (InfoNCE) with same-participant positives, large batches, collisions maskedW1: keeps stable traits; AFib 0.93 vs 0.88 from scratchDevice identity is decodable from embeddings: device-stratified batches, cross-device positives4.1, 4.5, 7.1
Minute-level wearable aggregates with natural gapsMasked reconstruction with natural-gap masking (AIM, LSM-2)Learns from incomplete days without imputing; loss only on artificially masked tokensTargets depend on rare morphology rather than daily structure: waveform encoders4.2, 7.2
Multichannel polysomnographyLeave-one-out cross-modal contrastive (SleepFM recipe), channel-invariant trainingMost objectives tie on staging, apnea and age; contrastive led on disease prediction in a head-to-head benchmarkChannels are often missing at inference: train for channel dropout; staging only: a supervised multi-input model may suffice8.2, 8.3
Coded EHR timelinesDecoder-only next-token model with gap and value tokensCausal by construction; learns from every position (141 predictions for a 142-token patient, against about 21 when masking 15%); zero-shot by simulationCensoring dominates the outcome: time-to-event pretraining (MOTOR-style piecewise hazards)9.1, 9.2, 9.3
Forecasting smooth physiological aggregatesZero-shot time-series foundation model, scored against seasonal naive and ETS on post-cutoff dataW1 hourly heart rate: TSFM MASE 0.84 against ETS 0.93Raw, fast waveforms or condition prediction: modality-specific encoders or summary statistics6.2, 6.4
Noisy waveforms where reconstruction wastes capacityJoint-embedding prediction (JEPA, LeJEPA) as a candidate, compared against contrastive and masked baselinesPredicts embeddings, not samples, so artefacts are not modelledEvidence remains early (mostly preprints): keep a contrastive or masked baseline in every comparison4.4
Notes, questions, coachingAn LLM as interface; signal encoders through adapters; exact numbers through code toolsSerializing W2 as text costs about 3.7B tokens instead of 0.46B; tool-based agents compute rather than recallShort summaries only: serialize into the prompt10.3, 10.2, 10.1

Table. Objectives by data shape and intended use. The lineage behind each row is mapped in Chapter 2 (Lineage map).

The Decisions

#DecisionDefaultDeviate whenRead
1Is a new foundation model needed?Build baselines first (gradient boosting on counts, summary statistics, seasonal naive and ETS), then probe the closest public model with k-shot curves.No public model fits the modality, or in-domain unlabelled data dwarfs public corpora and the probe falls short of the target: pretrain.12.3, 11.2
2Unit of splitOne split key per person, assigned once in the canonical store and read by every pipeline; a later time period and at least one site or device held out before anyone looks at results.Never relaxed. A window-, night- or admission-level split is a leakage bug, not a design choice.11.4, 12.1
3Feature timeFilter every input by its recording time, not its clinical date, relative to the prediction time; document "present on admission" exceptions.The source system has no recording timestamps: audit a sample by hand and drop late-arriving code classes.3.1, 11.4
4TokenizationW1: 1-s patches of 64 samples (10 tokens a window). W2: codes, 64 log-spaced gap tokens and per-lab decile tokens with edges fitted on training patients; the tokenizer versioned with the checkpoint.Sequence length binds: fused code-value tokens cut the W2 p95 patient from 2,078 to 1,570 tokens at the cost of about 10,790 extra vocabulary entries.5.1, 5.2
5MissingnessMask natural gaps; never feed zeros as values; score only observed hours; report every metric stratified by observed fraction.Gaps carry clinical information (a patient too ill to wear a device): add explicit missingness indicators as inputs, not imputed values.7.2, 3.5, 6.4
6Objective and checkpoint selectionPer the table above; select checkpoints by probe performance on held-out tasks and by label-free gates (RankMe, neighbour purity), not by pretraining loss.Probe and loss disagree: trust the probe and investigate the loss.4.5, 1.2
7ScaleSmall sweeps over parameters and data; count people and hours per person separately. W2's 3.8 tokens per parameter says more patients will help more than more parameters.Paired probe intervals stop excluding zero: spend on new people, devices or modalities, not on longer training.7.4, 9.2
8AdaptationLinear or Cox probe; LP-FT or LoRA when the representation must move; full fine-tuning only with ample labels.The target device or site differs from training: prefer LP-FT, since plain fine-tuning raised W1 AFib to 0.94 in distribution but fell to 0.84 on a new device where the probe held 0.90.11.1
9EvaluationA task suite with patient-bootstrap intervals, paired comparisons, subgroup and per-site results, reliability diagrams, and results with channels or hours removed.A single headline metric is requested: report it with its interval and the worst subgroup beside it.11.2, 11.3
10DeploymentRegistry with tokenizer and data cards; monitors for off-wrist share, unknown-token share, value-token shares and embedding PSI; local recalibration; a predetermined change control plan where the model is a device.A monitor fires: stratify by device, firmware and site before touching the model; most incidents are input changes.12.2

Table. The ten design decisions in build order, each with the default the book argues for and the condition that justifies deviating.

The Numbers on One Card

QuantityW1 · wearable PPGW2 · generative EHRW3 · sleep PSG
Data30M participant-hours → 10.8B windows, ≈6.7B with PPG; about 200 hours per participant310M events from 2M patients → about 0.46B tokens30,000 nights, 240,000 hours, 28.8M epochs (960 a night)
Input per unit4 × 640 samples → 10 patch tokensMedian patient ≈ 142 tokens; p95 ≈ 2,078 of a 4,096 context5 channel groups per 30-s epoch
Training signalInfoNCE from ≈ 8.3–8.5 nats at step 0; about 56 same-participant collisions masked per batchNext token from ln 42,074 = 10.65 nats; about 3.3 × 1017 FLOPs an epochLeave-one-out contrast over 5 groups (5 terms rather than 10 pairwise)
Headline resultAFib 0.93 (scratch 0.88); age MAE 6.1 years; resting HR MAE 2.4 bpmMortality 0.89; readmission 0.71; ECE 0.03κ 0.78 (inter-scorer ≈ 0.76); AHI ≥ 15 AUROC 0.91; wearable κ 0.62
UncertaintyAbout ±0.025 on AFib AUROC with 200 positive participantsAbout ±0.016 on mortality AUROC (750 deaths in 10,000)Patient-bootstrap intervals; nights of one patient are not independent
Cost26,368 steps an epoch; 553 GB of random reads an epoch; 55.3 TB raw at 2 bytes a sample64 rollouts a patient for simulated risk; about 7.7 × 108 generated tokens a night for 40,000 patientsAbout 3.5 TB raw at 128 Hz, 16 channels, fp16; data loading sets throughput
First warning signDevice generation decodable from embeddings; off-wrist share above its alert levelRandom-split AUROC above the release figure; unknown-token or value-token shares movingPer-site presence mask or per-stage κ (N1, N3) dropping while W and REM hold

Table. The three workloads side by side (illustrative). Each warning sign has a worked incident in the chapter that owns it (7.1, 9.4, 3.4, 8.1).

Build It Step by Step

Each step ends in an exit check a script can evaluate, so nothing downstream is built on a part that has not been checked (A practical playbook).

  1. Fix the decision and the deployment target. Task, prediction time, horizon, who acts on the output, and the device or site where it runs. Exit: the split design and the metrics follow from the written specification without further choices (Playbook).
  2. Harmonize and freeze a snapshot. EHR into MEDS or OMOP, signals resampled to 64 Hz with device and firmware recorded, local times stored with their UTC offset. Exit: one split key per person, a versioned snapshot, a held-out year and a held-out device or site, and a join of every pipeline's split table on person showing zero overlap (Reference architecture, Wearable time series).
  3. Build the baselines. Count features with gradient boosting, wearable summary statistics, seasonal naive and ETS. Exit: every later table has a baseline column on the same split (EHR benchmarks, Zero-shot evaluation).
  4. Probe a public model. Frozen embeddings from the closest open checkpoint, linear or Cox probes, k-shot curves. Exit: the curve against the baseline says whether a foundation model helps at the label budget available (Open PPG, ECG and EEG models, Task suites).
  5. Audit leakage and identity. Compare random, person-level and temporal splits; probe for participant, device and site identity. Exit: random-split and person-split results agree within their intervals, and device purity is near its chance level (0.30 for W1's assumed device mix) (Leakage, Good representations).
  6. Tokenize and pretrain, if the gates say so. Fit tokenizer state on training people only; check the step-0 loss against its chance value (8.32 nats for W1, 10.65 for W2); run small sweeps. Exit: probe performance, not pretraining loss, improves across checkpoints (Clinical events, Contrastive learning, Scaling).
  7. Adapt and calibrate. Probe, then LP-FT or LoRA if needed; fit a calibration layer per site. Exit: ECE at or below the release figure (0.03 for W2) on the target site's held-out patients (Adaptation methods, Calibration).
  8. Evaluate as a regulator would. Task suite with paired intervals, subgroups, sites, devices, calibration, and channels or hours removed. Exit: the gain over the baseline survives every stratification, with intervals stated (Task suites, Benchmarks).

After that, maintenance is triggered by events. A firmware update, a new device generation or a unit change at a site means returning to step 2 and re-running the identity and calibration checks. A new tokenizer version means re-checking that serving and training load the same one. A monitor that fires means stratifying by device, site and observed fraction before changing the model (Production challenges).

If only one thing is built

One split key per person assigned in the canonical store, a baseline that every result is compared against on that split, and a dashboard that plots the headline metric by device, site and observed fraction on the same axes.

Key Concepts

The core ideas of this book, one card each: a definition, an explanation from basics, why it matters, a common misconception and a diagram. Click a card, or any dotted-underlined term with a badge in the text, to open it in the side panel. To add your own, highlight any phrase and choose Key Concept.

Expert Primer: Mental Models, Debates and Self-Test

This primer condenses the book into what an expert carries around: five ideas that sit under almost every health foundation model from wearable encoders to generative EHR models, three questions on which informed practitioners still disagree, and ten problems that test whether the ideas can be applied rather than recited. Every item links to the section that develops it, so the primer doubles as a map of the book. Numbers attributed to W1 to W3 are illustrative (Reference workloads).

Five core mental models of health foundation models, each with a reference-workload number. 1Invariancesdevice purity 0.63vs chance 0.30 2Gaps are data38% of hours empty;zero-fill MASE 9.3 3Split by personreadmission 0.78→ 0.71 per patient 4Probe first257 parameters:AFib 0.93 vs 0.88 5Calibration driftsAUROC 0.88 holds;ECE 0.03 → 0.09
Fig. The five mental models in one row, with a reference-workload number for each (illustrative). Each is developed, with sources and links, below.

Five Core Mental Models

1. A self-supervised objective learns whatever lets it succeed most cheaply, so choosing positives, masks or targets is choosing invariances. In contrastive learning, whatever differs between the two views of a positive pair is discarded and whatever they share is kept. Same-participant positives over long intervals make the embedding about the person, as in Apple's PPG and ECG models (Abbaspourazad et al. 2023); simultaneous recordings from different sensors make it about physiological state, as in SleepFM; morphology-based or relative positives build an explicit notion of similarity, as in Pulse-PPG (Saha et al. 2025). Anything else the two views share is kept too, including the device, the site and the firmware. Masked objectives have the same property in another form: reconstruction losses spend capacity on high-variance artefacts, which is the argument for predicting embeddings instead (Panchavati et al. 2026) (Choosing positives, Joint-embedding predictive architectures, What makes a good representation).

Worked example · W1

With device generations in shares 0.4, 0.3, 0.2 and 0.1 (an assumption), the chance that two random participants share a device is \(0.16 + 0.09 + 0.04 + 0.01 = 0.30\). A checkpoint whose 10 nearest neighbours share the device 63% of the time has a purity ratio of 2.1, and purity stays at 0.61 when same-participant neighbours are excluded: the objective rewarded encoding the device, because in a mixed batch the device separates a positive from most negatives. Device-stratified batches remove the reward; cross-device positives for participants who wore two generations remove the invariance gap.

2. Missingness in health data is structured, frequent and often informative, so it is part of the input, not a cleaning step. Wearables come off to charge, overnight and in the shower; sensors saturate; patients leave the ward or the health system. LSM-2's authors found no day-long window without missing data among 1.6 million windows and trained on incomplete data with natural-gap masking instead of imputation (Xu et al. 2025), and SensorFM scaled that recipe to about 2 billion hours (Narayanswamy, Xu et al. 2026). Missingness also changes what is evaluated: an error computed on filled values measures the filling, and a population whose wear pattern shifts moves into strata where the model is weaker without the model itself changing. In the EHR, the equivalent is censoring: patients who leave before the horizon are neither survivors nor events (Scaling and missingness, Wearable time series, Time-to-event pretraining).

Worked example · W1

38% of W1's grid has no PPG, so about \(0.62 \times 10.8 \approx 6.7\) billion window slots carry signal. On a synthetic week with a nightly charging slot, night hours are observed 69% of the time and day hours 59%, so the observed mean heart rate is 0.7 bpm below the true 70.0 bpm; the hour-stratified mean removes most of the bias but cannot recover hours that are never observed. A forecaster fed zero-filled contexts scores masked MASE 9.3; with same-hour filling, 0.90.

3. The unit of statistical independence is the person, and for prospective use also time; every split, normalization statistic and tokenizer edge must respect both. Physiological signals carry a fingerprint, so a window-wise split lets a classifier recognise people instead of conditions: in a simulation with labels unrelated to signal, nearest-neighbour accuracy is 1.000 on a window split and 0.520 on a subject split. EHR data add copy-forward: chronic codes are re-recorded at every visit, so metrics that do not separate new onsets from repeats are inflated (Rajamohan et al. 2025). Time-series foundation models add a third route: test series, or series correlated with them over the same period, can sit in the pretraining corpus (Meyer et al. 2025) (Leakage, Waveforms, Zero-shot evaluation).

Worked example · W1 and W2

A W1 participant with 200 hours has 72,000 ten-second windows; under a random 80/20 window split, essentially every participant has windows in both sets. A W2 readmission report split by admission put 41% of test admissions with patients who had other admissions in training; it showed 0.78 for W2 and 0.77 for gradient boosting, against 0.71 and 0.69 on a patient-disjoint split. The leak inflated both models and hid the size of the real gap.

4. A representation is worth what a small head on frozen embeddings achieves, against honest baselines, at the label budget the task actually has. A linear probe is cheap, hard to overfit and isolates what the encoder already contains; most results in this book, from SleepFM to the Apple models to EHRSHOT, are probes. The comparison that matters is with strong simple baselines on the same split: EHRSHOT's count-based gradient-boosting model caught up with the pretrained model as labels grew and won on new-diagnosis tasks above 64 examples per class (Wornow et al. 2023), and FoMoH found that foundation models beat traditional baselines especially with few labels but could underperform on low-prevalence outcomes (Jeanselme et al. 2025). When the representation must move, linear-probe-then-fine-tune distorts pretrained features less than fine-tuning from a random head (Kumar et al. 2022) (Adaptation methods, Task suites and label scarcity, Playbook).

Worked example · W1

The AFib probe has \(256 + 1 = 257\) parameters fitted on 5,000 participants, about 19 participants a parameter; a from-scratch model must learn features and decision rule from the same 5,000. Assuming 10% prevalence, the 0.88 model mis-orders 270,000 of 2.25 million positive–negative pairs and the 0.93 probe 157,500. Full fine-tuning on one watch generation raised AUROC to 0.94 in distribution and fell to 0.84 on a new generation, where the probe held 0.90.

5. Deployment is a sequence of distribution shifts, and calibration fails before ranking does. A model moved to a new site, device, year or coding practice usually keeps much of its discrimination while its probabilities drift, because prevalence and input scales change. Foundation models evaluated across institutions were less well calibrated with few labels and transported poorly (Jeanselme et al. 2025), and Delphi-2M's average AUC of about 0.76 fell to about 0.67 under unchanged validation on Danish registries (Shmatko et al. 2025). Most production incidents in this book are input changes: firmware that alters PPG amplitude or off-wrist detection, a site that switches creatinine units, a serving job that loads an old tokenizer. The defences are monitors stratified by device and site, local recalibration, and change control that versions the tokenizer with the weights (Shift, fairness and calibration, Production challenges).

Worked example · W2

At a second hospital W2's 1-year mortality AUROC is 0.88 but ECE is 0.09: mean predicted risk is 0.075, the development prevalence, against a local one-year mortality of 0.05, and the alert rate at a threshold of 0.30 is 6.1% instead of 3.8%. A calibration intercept of −0.4 and slope of 0.8 turns a raw prediction of 0.30 into 0.254 without changing any ranking; temperature and intercept fitted on 2,000 local patients restore ECE to about 0.03.

Three Fundamental Disagreements

Three disagreements remain open because both sides have strong evidence and the right answer depends on the modality, the task and the data available. The table gives the shape of each. The sections below set out the strongest case for each side and where practice is converging.

DebateSide ASide BEmerging synthesis
General or health-specific time-series models?General TSFMs transfer zero-shot to physiological seriesHealth signals need modality-specific models; general results are inflated by leakageGeneral TSFMs as baselines and forecasters of smooth aggregates; modality-specific encoders for representation and raw waveforms
Dedicated EHR models or LLMs over records?Dedicated code-token models: efficient, zero-shot by simulationLLMs over serialized records match or beat them, and generalizeDedicated models for structured risk; LLMs as feature extractors, interfaces and tool users
Does scale buy clinical value?Loss and downstream performance follow scaling laws with no saturation in sightDownstream gains plateau; data, people and evaluation limit before parameters doScale is two-dimensional (people and hours); measure with paired probes, not loss

Table. The three debates at a glance.

1. Do general time-series foundation models serve health data, or does health need its own models?

The case for general time-series foundation models.

  • They forecast physiological aggregates well zero-shot. TimesFM and Chronos forecast heart-rate variability from consumer wearables with average MASE of about 0.81–0.87, beating mean, moving-average and ETS baselines without any training on the data (Peräkylä et al. 2026, What the evidence says for health data).
  • They now handle the structure health series have. Covariate-aware models such as Chronos-2 accept related series and covariates in context (Ansari et al. 2025), which lets accelerometry inform a heart-rate forecast; on the illustrative W1 task the TSFM scores MASE 0.84 against 0.93 for ETS on 5,000 post-cutoff participants, a difference whose interval is about ±0.004 (Time-series foundation models, Zero-shot evaluation).
  • Where signals are smooth, general models win even against health-specific ones: on MMASH, the low-complexity exception in SOTER's comparison, the general models came out ahead (Chen et al. 2026).

The case for health-specific models.

  • As representations of health, general embeddings lose. Combining All of Us records with Fitbit data for ten conditions, hand-engineered wearable statistics beat MOMENT embeddings (Wang et al. 2025). SOTER, a 50M-parameter generative model pretrained on about 226 billion physiological time points, reported lower zero-shot error than Chronos-2, TimesFM 2.5 and Moirai 2.0 on most of six physiological datasets (Chen et al. 2026, Health evidence).
  • Reported zero-shot gains are fragile. Sample overlap and temporal overlap of correlated series inflate zero-shot scores (Meyer et al. 2025); in the book's W1 example, a mixed evaluation set in which 20% is a leaked public dataset turns a clean 0.84 into an apparent 0.812. The GIFT-Eval leaderboard resolves about 6.2 rank places while neighbouring entries are a median of 0.91 places apart (Sikder and Pillutla 2026, Zero-shot evaluation).
  • Health series are personal, gappy and instrumental, and general benchmarks contain little physiological data; a model fed charging gaps as zeros forecasts a heart rate of zero (Health evidence, Missingness).
Where it is heading

A split by question. General TSFMs are strong zero-shot forecasters and imputers for smooth daily or nightly aggregates and belong in every table as baselines; modality-specific encoders and well-chosen summary statistics serve representation and raw-waveform tasks. Open benchmarks with classical baselines, such as OpenMHC's prediction, imputation and forecasting tracks (Schuetz et al. 2026), and leakage audits against model cards are becoming the minimum for a claim (Health evidence, Scaling behavior and cohorts).

2. Should structured EHR data be modelled by dedicated code-token models or by LLMs over serialized records?

The case for dedicated EHR models.

  • They predict well zero-shot and scale predictably. CoMET, trained on 118 million patients and about 115 billion events, matched or beat task-specific supervised models across 78 tasks by Monte Carlo simulation, reaching readmission AUROC 0.770 against 0.717 for the best supervised model, with power-law scaling and a compute-optimal ratio near 1,000 tokens per parameter (Waxler et al. 2025, Generative EHR models).
  • They can be very small. Delphi-2M, about 2.2 million parameters with continuous age encoding and a time-to-next-event head, predicted rates of 1,256 diseases with accuracy comparable to single-disease models (Shmatko et al. 2025).
  • Text is expensive and blurs time. Serializing W2 at about 12 tokens an event turns 0.46 billion tokens into about 3.7 billion; EHR sequences have copy-forward repetition, irregular intervals and perplexity that rises later in a timeline, properties general models were not built for (Wornow et al. 2025, Clinical text and medical LLMs, Clinical events).

The case for LLMs over records.

  • General LLM embeddings of code descriptions matched the dedicated CLMBR-T-base across EHRSHOT's 15 tasks and generalized somewhat better to UK Biobank (Hegselmann et al. 2025). Having an LLM restructure records before embedding beat both naive serialization and CLMBR-T on average (Demirel et al. 2026) (Clinical text and medical LLMs).
  • Language carries what codes miss (reasoning, uncertainty, social context), and one model can read notes, explain predictions and converse; PH-LLM scored above sampled experts on sleep and fitness examinations (Cosentino et al. 2025, LLMs over wearable data).
Where it is heading

A division of labour. Dedicated models remain efficient and competitive for risk prediction from structured histories, and CLMBR-T stayed stronger on operational outcomes such as ICU transfer and length of stay even where LLM pipelines won on average. The better LLM pipelines increasingly act as feature extractors feeding ordinary predictors, and as interfaces that call tools for exact computation. Benchmark knowledge is not the bottleneck in use: LLMs alone identified relevant conditions in 94.9% of scenarios, but members of the public using them did so in under 34.5% (Bean et al. 2025, Clinical text, Open problems).

3. Does more pretraining scale buy clinical value?

The case for scale.

  • Loss falls predictably. SensorFM's loss fell over data from about 2 million to 2 billion hours with no saturation reported, and linear probes beat an engineered-feature baseline on 34 of 35 tasks (Narayanswamy, Xu et al. 2026); CoMET found power laws with exponents close to language and a sigmoid-like link from pretraining loss to downstream performance (Waxler et al. 2025) (Scaling behavior and cohorts).
  • Sleep models improve with sample size, capacity and multi-source mixtures (Shuai et al. 2026), and SleepFM-2, pretrained on over two million hours from 26 cohorts, reports C-index of at least 0.75 for 215 incident phenotypes from one night (Thapa et al. 2026, preliminary) (Benchmarks, SleepFM).

The case that data and evaluation bind first.

  • EHR corpora run out of tokens. On MIMIC-IV, readmission performance plateaued beyond about 28M parameters because larger models would need two orders of magnitude more tokens than the data provide (Zhang et al. 2025); W2 sits at 3.8 tokens per parameter (Generative EHR models).
  • Wearable hours are redundant. LSM's gains slowed after about 105 hours, and at fixed total hours fewer subjects with more hours did about as well as more subjects (Narayanswamy et al. 2025). In the book's W1 incident, four times the data and 12 times the compute moved AFib AUROC from 0.930 to 0.935, with a paired interval of −0.004 to +0.014 (Scaling).
  • Objectives and size often tie downstream. On Stanford Sleep Bench most self-supervised methods performed similarly on staging, apnea and age (Kjaer et al. 2025); in All of Us, CEHR-GPT's advantage over simple indicators largely disappeared once wearables were added (Wang et al. 2025) (Benchmarks, Fusing EHR and wearables).
Where it is heading

Scale is two-dimensional. More hours from the same people mostly add repetition; more people add diversity in physiology, devices and behaviour, and person-level clinical targets scale with the second axis. Small sweeps fit loss against parameters and data, but the decision to spend more is taken on paired probe intervals for the clinical tasks, including the subgroups that grew most (in the W1 incident, participants aged 75 and over) (Scaling behavior and cohorts, Task suites, Open problems).

Self-Test: Ten Questions

Each question puts an idea from the book into a situation it does not describe and asks for a computation, a diagnosis, a choice or a design. Questions build on the reference workloads. Answer before opening the worked answer. The "What a memorizer misses" line names the step that separates applying an idea from reciting it.

  1. The W1 data budget. From the specification, compute the number of window slots, the number carrying PPG, the optimiser steps in one epoch, and the size of an fp16 embedding store per window and per participant-hour. The first training run reads 2,100 windows a second from one object per window. How long is an epoch, and what changes?

    Answer 10.8B slots, 6.7B with PPG, 26,368 steps; repack by participant-day

    Each hour holds \(3{,}600/10 = 360\) windows, so \(3 \times 10^7 \times 360 = 1.08 \times 10^{10}\) slots, of which \(0.62 \times 1.08 \times 10^{10} \approx 6.7 \times 10^9\) carry PPG. One epoch samples 1%, \(1.08 \times 10^8\) windows, or \(\lceil 1.08 \times 10^8 / 4{,}096 \rceil = 26{,}368\) steps. An fp16 embedding for every slot takes \(1.08 \times 10^{10} \times 256 \times 2 \approx 5.5\) TB (about 3.4 TB for observed windows only); pooled per participant-hour it is \(3 \times 10^7 \times 512\) bytes \(\approx 15.4\) GB (about 9.5 GB for the 62% of hours that carry PPG). Each window is \(640 \times 4 \times 2 = 5{,}120\) bytes, so an epoch reads about 553 GB, but as \(10^8\) random reads: at 2,100 windows a second the epoch takes about 14 hours with the accelerators mostly idle. A 4-hour epoch needs 7,500 windows a second, which the book's incident reaches by packing each participant-day into one sequential shard of up to 8,640 windows and sampling shards (Definition and scope, Reference architecture).

    What a memorizer misses: that a 1% epoch is small in bytes and large in requests, so the storage layout, not the arithmetic, sets throughput; and that every new encoder version invalidates the whole embedding store.

  2. Reading the InfoNCE curve. What step-0 loss should a W1 run show, and why? After a cluster migration the step-0 loss reads 4.2 nats and the AFib probe falls from 0.93 to 0.90 while age MAE barely moves. Diagnose. Separately, how many same-participant pairs land in a batch by chance, and what should be done with them?

    Answer ln 4,096 = 8.32; 4.2 ≈ ln 64 means negatives were not gathered

    Each anchor is a 4,096-way classification, so an untrained encoder scores about \(\ln 4{,}096 = 8.32\) nats (about 8.5 once the spread of random similarities is included). A step-0 loss of 4.2 matches \(\ln 64 = 4.16\): each of 64 accelerators is computing the loss over its own 64 anchors, because embeddings are no longer gathered across devices. Fewer, easier negatives explain why fine distinctions such as AFib degrade while coarse traits such as age do not; a data-loader change would have moved age too. With 150,000 participants, a batch of 4,096 holds about \(4{,}096 \times 4{,}095 / 2 / 150{,}000 \approx 56\) same-participant pairs; their cross cells are not true negatives and are masked, about 112 cells of 16.8 million. The temperature matters as much as the batch: a positive at cosine 0.8 against negatives at 0.1 costs 1.55 nats at \(\tau = 0.1\), 4.83 at 0.2 and 0.0034 at 0.05 (Contrastive learning and InfoNCE, PPG, ECG and behavior models).

    What a memorizer misses: that the chance level of a contrastive loss is the logarithm of the number of candidates actually in the denominator, which makes the step-0 value a free check on the distributed implementation.

  3. A shortcut that passes the headline metric. A new W1 checkpoint has AFib AUROC 0.93 and RankMe/256 = 0.62, but AUROC 0.86 on the oldest device generation (10% of participants) and device-neighbour purity 0.63. Device shares are 0.4, 0.3, 0.2 and 0.1. Is this a population effect or a shortcut? Which measurement decides, and what is the fix?

    Answer A shortcut: purity 2.1× chance, and it survives excluding the same participant

    Chance purity is \(\sum s_i^2 = 0.30\), so 0.63 is 2.1 times chance. A population explanation (older-device owners differ clinically) predicts that the gap persists in a probe trained only on that slice and that purity falls once same-participant neighbours are excluded; a shortcut predicts that a linear classifier recovers device generation from embeddings and that purity stays high without same-participant neighbours. Here it stays at 0.61, so the objective is encoding the device: with same-participant positives, device identity separates a positive from most negatives in a mixed batch. Fixes: device-stratified batches, so negatives share the device; cross-device positives for participants who wore two generations; per-device calibration of the probe as a stopgap; and a release gate on worst-slice AUROC and purity ratio. The fix is confirmed if device decodability falls toward the majority-class rate while the slice gap closes to within about 0.01 (What makes a good representation, Choosing positives, PPG, ECG and behavior models).

    What a memorizer misses: that a label-free quality score and an aggregate AUROC can both look healthy while the embedding is organised by a nuisance variable, which only a stratified metric and an identity probe reveal.

  4. Is W2 too big? With about 35% of events carrying a value and about 12 gap tokens per 96 events, how many tokens does the median and the 95th-percentile patient occupy, and how many tokens does the corpus hold? Compare W2's tokens per parameter with the EHR evidence, and say what to spend the next budget on.

    Answer 142 and 2,078 tokens; about 0.46B tokens, 3.8 per parameter: more patients, not parameters

    The median patient is \(96 + 34 + 12 = 142\) tokens and the 95th percentile \(1{,}450 + 508 + 120 = 2{,}078\), half the 4,096 context, so context length does not bind. The corpus is about \(310 \times 10^6 \times 1.475 \approx 0.46\) billion tokens, and one epoch costs about \(6 \times 1.2 \times 10^8 \times 4.6 \times 10^8 \approx 3.3 \times 10^{17}\) FLOPs. That is about 3.8 tokens per parameter, against a compute-optimal ratio near 1,000 in CoMET; on MIMIC-IV, with a similar corpus, readmission performance plateaued beyond about 28M parameters. W2 is far from compute-optimal on the data side: more patients (or more sites, through federated training) will help more than more parameters, and a smaller model would likely lose little. A uniform guess over 42,074 tokens costs 10.65 nats, the step-0 check (Clinical events, Sequence and masked models, Generative EHR models, Scaling).

    What a memorizer misses: that compute-optimal ratios for EHR differ from text by a factor of about 50, so a model sized by language-model habit is data-starved.

  5. Risk by simulation. W2 samples 64 one-year futures for a patient; 7 contain a death token. Give the estimate and its uncertainty. On the 2024 holdout, simulated mortality ranks well (AUROC 0.89) but observed mortality is 0.087 against 0.075 predicted, and 14% of rollouts end with an end-of-record token before a year has elapsed. Explain and fix.

    Answer 0.11 ± about 0.04; end-of-record is a competing risk, mask it

    The estimate is \(7/64 \approx 0.11\). For a true risk of 0.10, 64 rollouts give a standard error of about 0.0375 and a Wilson 95% interval of [0.048, 0.198]; 256 rollouts narrow it to [0.069, 0.143]. Ranking tolerates this noise; individual risk communication does not. The calibration gap has a different cause: end-of-record is a learned event that competes with death in the simulation. With a true hazard of 0.12 a year the correct risk is \(1 - e^{-0.12} = 0.113\); if the model has learned an end-of-record rate of 0.3 a year, the simulated risk is \(0.12/0.42 \times (1 - e^{-0.42}) = 0.098\), 13% low, and more rollouts do not help. Masking the end-of-record token at sampling time raises mean predicted risk to about 0.085 and removes most of the calibration error. The production cost is real: 40,000 patients × 64 rollouts × about 300 tokens is about \(7.7 \times 10^8\) generated tokens a night (Generative EHR models, Time-to-event pretraining).

    What a memorizer misses: that a generative model estimates the probability of the outcome under its own simulated process, so any event that ends a simulated record early is a bias, not noise.

  6. An implausible readmission gain. An internal report shows W2 readmission AUROC 0.78 against 0.71 in the release notes, and a gradient-boosting baseline at 0.77. The split was by admission. What happened, what are the correct numbers, and is W2 better than the baseline?

    Answer Patient leakage; 0.71 vs 0.69 with ±0.02 intervals

    41% of test admissions belonged to patients with other admissions in training, so both models partly recognised patients. Re-run on patient-disjoint splits, W2 scores 0.71 and the baseline 0.69, each with a patient-bootstrap interval of about ±0.02 on 9,500 test admissions; a paired comparison is needed to say whether a 0.02 gap is real, and the honest reading is that W2's advantage on this task is small. The leakage explanation is confirmed if AUROC on test patients with no training admissions matches the patient-disjoint result and the inflation concentrates in frequently admitted patients. The temporal holdout adds a second check: the same task on a 2022 patient-disjoint split against 2024 measures drift separately from leakage (EHR benchmarks and evaluation, Leakage).

    What a memorizer misses: that leakage inflates the baseline too, so the comparison between methods is distorted, not just the absolute number.

  7. What κ 0.78 means. Assume stage proportions W 15%, N1 8%, N2 45%, N3 15%, REM 17% for both raters. Convert W3's κ of 0.78, the inter-scorer 0.76 and the wearable-only 0.62 into raw agreement. What does "κ 0.78 against an inter-scorer κ of 0.76" license, and what does it not?

    Answer 84.2%, 82.8% and 72.7% agreement; parity with a scorer, not superiority

    Chance agreement is \(p_e = 0.15^2 + 0.08^2 + 0.45^2 + 0.15^2 + 0.17^2 = 0.2828\), and \(p_o = p_e + \kappa(1 - p_e)\): 0.842 for 0.78, 0.828 for 0.76 and 0.727 for 0.62. A model that always predicts N2 is right 45% of the time with κ = 0, which is why κ, not accuracy, is reported. κ 0.78 against single-scorer labels says the model agrees with one scorer about as well as two scorers agree with each other; it cannot show the model is better than a human, because the reference is itself one noisy scorer. The 0.16 drop to the wearable student is the price of losing EEG, EOG and EMG, concentrated in N1 and in separating N3 from N2. Merging stages to three classes raises raw agreement but also chance agreement, so κ values across class schemes are not comparable (From manual scoring to learned staging, Sleep without the lab, Polysomnography).

    What a memorizer misses: that the reference label sets a ceiling on measurable performance, so the comparison that matters is with inter-scorer agreement on the same data, not with 1.0.

  8. A second hospital. W2's mortality model goes live at a new hospital with an alert threshold of 0.30. The first month's alert rate is 6.1% against 3.8% expected; mean predicted risk is 0.075 against a local historical mortality of 0.05. Retrospective scoring on 2,000 patients gives AUROC 0.88 and ECE 0.09. What kind of shift is this, and what is the remedy?

    Answer Mostly prior shift; recalibrate locally, keep the model

    Discrimination is intact (0.88 against 0.89, within the ±0.03 interval) while every bin above 0.2 is over-predicted and the mean prediction equals the development prevalence: the outcome rate differs, which is a label (prior) shift, possibly with some calibration-slope change. Retraining is not needed. Fit a calibration intercept and slope, or temperature and intercept, on the 2,000 local patients: with intercept −0.4 and slope 0.8, a raw 0.30 (logit −0.847) becomes logit −1.078, a risk of 0.254, and ECE returns to about 0.03 with AUROC unchanged. Then set the alert threshold from the local capacity to act, and monitor calibration-in-the-large monthly as outcomes arrive (Shift, fairness and calibration, Production challenges).

    What a memorizer misses: that a model can transport its ranking and not its probabilities, and that an alert threshold is a probability, so the operational failure appears before any AUROC change.

  9. Ship the new checkpoint? A new W2 checkpoint reports 1-year mortality AUROC 0.90 against 0.89, on a test set with 750 deaths among 10,000 patients. Across the 15-task suite it wins 8 and loses 7; readmission falls from 0.71 to 0.69. Decide, with numbers.

    Answer No: the mortality gain is within noise and readmission regresses

    Each AUROC has a standard error of about 0.008 (Hanley–McNeil with 750 positives and 9,250 negatives), so a 95% interval is about ±0.016. The paired patient bootstrap of the difference gives +0.008 with an interval of [−0.002, +0.018], which includes zero. 8 wins and 7 losses across 15 tasks is what two equivalent models produce. The readmission drop of 0.02 has an interval that excludes zero, so the one statistically supported change is a regression. Keep the release model; if the new checkpoint has another motivation (cost, a new site), report the suite with paired intervals and the worst-task change (Task suites and label scarcity, Benchmarks and pretraining comparisons).

    What a memorizer misses: that two models evaluated on the same patients must be compared with a paired interval, and that a suite is a set of decisions, not an average.

  10. Adding wearables to the EHR. In a linked cohort, W2 predicts 1-year mortality with AUROC 0.89 and a W1-based wearable score alone reaches an assumed 0.75. Under an equal-variance Gaussian model, what does fusion give if the scores are independent? Offline the fused model reaches 0.91, but in production it falls below EHR-only; wearable coverage is 35% instead of 60%, and missing wearables were encoded as zero vectors. Explain and redesign.

    Answer About 0.919 if independent; zeros read as physiology, so add indicators or fuse late

    Convert each AUROC to a separation \(d = \sqrt 2\,\Phi^{-1}(A)\): \(d_1 = 1.414 \times 1.227 = 1.735\) and \(d_2 = 1.414 \times 0.674 = 0.954\). For independent scores \(d = \sqrt{1.735^2 + 0.954^2} = 1.980\), so AUROC \(= \Phi(1.980/\sqrt 2) = \Phi(1.400) = 0.919\), a gain of about 0.03; at a correlation of about 0.55 the gain vanishes, one reading of why a rich EHR encoder's advantage shrank when wearables were added in All of Us. In production, patients without wearable data received zero vectors, which the model read as an unusual physiological state, and their share rose when an app update broke sync on one platform. Redesign: late fusion, in which the EHR score alone ranks patients without wearables (wearable score set to its mean), or early fusion with an explicit missingness indicator; report AUROC separately for patients with and without the modality; and monitor coverage as an input (Fusing EHR and wearables, Scaling and missingness).

    What a memorizer misses: that the value of a second modality depends on its correlation with the first and on its coverage at deployment, and that a missing modality encoded as a value is a new input distribution.

What a Health Foundation Model Is

A health foundation model is a single model trained once, without task labels, on a large and varied body of health data, and then reused for many clinical and wellness questions. The broad data may be millions of patient timelines in an electronic health record (EHR), hundreds of thousands of hours of overnight sleep recordings, or billions of minutes of smartwatch signals. The downstream questions range from scoring sleep stages tonight to estimating the risk of heart failure five years out. The approach pays off because medical labels are expensive, slow and scarce, while unlabelled data accumulates as a by-product of care and of everyday device use.

This chapter fixes two ideas the rest of the book depends on. The first section states what counts as a health foundation model, where the term comes from, and what changed after 2023. The second section states what it means for the model's output, its representation, to be good, and how each property is measured. Later chapters assume both: the data taxonomy, the self-supervised objectives, the model families and the evaluation chapters all judge models against the definition and the six properties set out here.

Pretrain once, adapt many: an unlabelled W1 corpus trains one encoder whose embeddings feed several small task heads.Unlabelled corpus30M participant-hoursPPG + accel, 64 HzSelf-supervisedpretrainingInfoNCE, batch 4,096Frozen encoder50M parameters256-d embeddingAFib probeAUROC 0.93Age probeMAE 6.1 yearsResting-HR probeMAE 2.4 bpmexpensive, done onceversioned artefactcheap, one per task
Fig. The foundation-model pattern in reference workload W1 (illustrative numbers). Pretraining consumes unlabelled data once; each downstream task trains only a small head on frozen 256-dimensional embeddings.
Worked example · W1

The primary reference workload, W1, is a wearable photoplethysmography (PPG) foundation model. It is pretrained on 30 million participant-hours of PPG and accelerometry from 150,000 participants, sampled at 64 Hz and cut into 10-second windows of 640 samples. A 50-million-parameter encoder maps each window to a 256-number embedding. With a linear probe trained on 5,000 labelled participants, the embedding detects atrial fibrillation (AFib) with AUROC 0.93, against 0.88 for a model trained from scratch on the same labels. All W1 numbers are illustrative and are reused unchanged at every level of the book.

This chapter formalises a health foundation model as a pair: an encoder \(f_\theta\) fitted once on unlabelled data by minimising a self-supervised loss, and a family of small task maps \(g_{\phi_t}\) fitted on labelled data for each downstream task \(t\). The first section writes down the two optimisation problems, counts their parameters and inputs for reference workload W1, and shows when the split pays for itself. The second section turns "good representation" into measurable quantities: probe risk, label-efficiency curves, nearest-neighbour nuisance purity, augmentation sensitivity, missingness degradation, and the alignment, uniformity and effective-rank statistics of the embedding geometry.

Notation

\(x\) is an input (a signal window, a patient timeline), \(f_\theta\) an encoder with parameters \(\theta\), and \(z = f_\theta(x) \in \mathbb{R}^d\) its representation. A timeline is a sequence of events \((c_i, t_i)\) with codes \(c_i\) from a vocabulary \(\mathcal{V}\) and times \(t_i\). In contrastive learning, \(s(\cdot,\cdot)\) is a similarity (usually cosine), \(\tau\) a temperature and \(N\) the number of candidates per anchor. \(y\) is a downstream label and \(k\) the number of labelled examples per class.

Worked example · W1

In W1, \(x \in \mathbb{R}^{4 \times 640}\) is one 10-second window at 64 Hz in four channels (PPG plus three accelerometer axes), \(d = 256\), \(\theta\) has \(5 \times 10^7\) entries, the contrastive temperature is \(\tau = 0.1\) and a batch holds 4,096 windows. The corpus contains \(3 \times 10^7 \times 360 = 1.08 \times 10^{10}\) windows, of which 1% is sampled per epoch.

The code in this chapter treats a foundation model as an interface rather than as a particular network. Two snippets carry the chapter. The first defines a frozen encoder with fit on unlabelled windows and embed returning an array of shape (n, d), checks the W1 corpus arithmetic with assertions, and compares a linear probe on embeddings with a model trained on raw windows as the number of labels grows. The second implements a representation audit: probe AUROC, label-efficiency curves, nearest-neighbour purity for a nuisance such as device model, alignment and uniformity on the unit sphere, the RankMe effective rank, and a missingness-degradation helper, each with a test on synthetic embeddings whose answer is known.

All snippets use NumPy and scikit-learn, run in seconds on a laptop, and end in assertions that were executed when this chapter was written. The encoder inside them is deliberately a simple stand-in (principal component analysis); the chapters on objectives and model families replace it with real self-supervised networks without changing the interface.

Worked example · W1

Shapes used throughout: one window (4, 640) (PPG plus three accelerometer axes); one hour of windows (360, 4, 640); embeddings for a batch (4096, 256); one participant-hour after mean pooling (256,). One epoch over 1% of the 10.8 billion windows at batch 4,096 is 26,368 optimiser steps.

In production a health foundation model is a platform component, not a single trained file. It has a versioned encoder, an embedding service that computes and stores representations for millions of people, a registry of task probes that depend on a specific encoder version, and monitoring that detects when new devices, firmware, sites or populations move the embeddings. Two production questions follow from this chapter. First, what infrastructure turns "pretrain once, adapt many" into a reliable service, and what does it cost in storage, compute and re-validation each time the encoder changes. Second, which representation properties must be checked before a new encoder version is released, in what order, and with what thresholds, so that a checkpoint with a good headline score but a hidden device shortcut never reaches downstream users.

Worked example · W1

Storing every W1 window embedding in 16-bit floats takes \(1.08 \times 10^{10} \times 256 \times 2\) bytes, about 5.5 TB; pooling to one embedding per participant-hour reduces this to about 15.4 GB. Every new encoder version invalidates both stores and every probe trained on them, which is why release gating (second section) matters as much as pretraining quality.

Definition and scope

Definition. A foundation model is a model trained on broad data, usually with self-supervision at scale, that can be adapted to a wide range of downstream tasks. The term was introduced by Bommasani et al. (2021), who chose the word "foundation" to stress that such models are central to many applications yet incomplete on their own. Three ingredients make the definition. Broad data means data not collected for one task. Self-supervision means the training signal is manufactured from the data itself, for example by hiding part of an input and predicting it, or by asking two views of the same person to look alike. Adaptation means the trained model is reused for new tasks by adding a small trainable component or by brief further training, instead of building a new model per task.

In health, broad data has three common forms, each treated at length in later chapters: physiological signals from wearables and clinical monitors (PPG, ECG, EEG, accelerometry), coded patient timelines from EHRs (diagnoses, procedures, medications, laboratory results with time stamps), and multichannel overnight polysomnography (PSG) recorded in sleep laboratories. Downstream tasks include detecting arrhythmias, staging sleep, estimating age or fitness, predicting readmission or mortality, and forecasting future measurements.

Motivation. The predecessor is the task-specific supervised model. A team that wants an AFib detector collects labelled recordings, designs features or trains a network, and validates it; a second team that wants a sleep-apnea detector repeats every step on different labels. In medicine each label may need a cardiologist's review, an overnight study or years of follow-up, so labelled sets are small, and models trained on them overfit, transfer poorly across devices and hospitals, and waste the far larger pool of unlabelled data. A foundation model moves most of the learning to the unlabelled pool, where data is plentiful, and leaves each task to learn only a thin mapping from a learned representation to its label.

How it works end to end. First, data is collected without regard to any one task: every hour a participant wears a watch, every encounter recorded in a hospital system. Second, the raw data is cut into model inputs: fixed-length signal windows, or sequences of coded events. Third, a self-supervised objective trains an encoder. The encoder receives an input and produces a vector of numbers, the embedding or representation; the objective scores how useful those vectors are for the manufactured task, and the encoder's parameters are adjusted over billions of examples. Fourth, the encoder is frozen and versioned. Fifth, for each downstream task a small model, often a linear probe (a weighted sum of the embedding entries followed by a threshold or a sigmoid), is trained on the available labels. Sixth, the probe and encoder are evaluated together on held-out people, devices and time periods. Only the fifth and sixth steps repeat per task.

Three health data families that satisfy the same definition of a foundation model.Signals · W1150,000 participantsPPG + accel windowscontrastive objectiveAFib, age, resting HRTimelines · W22M patients310M coded eventsnext-event predictionmortality, readmissionSleep · W330,000 overnight PSGs5 channel groupscross-modal objectivestaging, apnea (AHI)Shared definitionbroad unlabelled data · self-supervised pretraining · adaptation to many downstream tasks
Fig. Scope of the term in this book. The three reference workloads differ in data and objective but share the defining pattern: broad unlabelled data, a self-supervised objective, and reuse across tasks. Numbers are illustrative.
Worked example · W1

W1 collects 30 million participant-hours of PPG and accelerometry from 150,000 participants. Each hour becomes 360 ten-second windows. The objective is contrastive: two windows from the same participant within 24 hours should have similar embeddings, and windows from different participants should not. After pretraining, the 50-million-parameter encoder is frozen. A linear probe trained on 5,000 labelled participants reaches AFib AUROC 0.93; a network trained from scratch on the same 5,000 participants reaches 0.88. The same frozen embeddings also give age estimates with a mean absolute error of 6.1 years and resting heart rate within 2.4 beats per minute on average, each from its own probe.

History and scale. The idea of learning a reusable patient representation predates the term. Choi et al. (2015) trained a recurrent network to predict the codes of a patient's next visit, and Steinberg et al. (2020) showed that a language-model-style objective over EHR codes yields representations that help many prediction tasks. What changed after 2023 is scale and breadth. Wearable models were pretrained on data from about 141,000 participants of the Apple Heart and Movement Study (Abbaspourazad et al. 2023) and on more than 40 million hours from about 165,000 Fitbit and Pixel users (Narayanswamy et al. 2024). A behaviour model trained on about 2.5 billion hours of hourly aggregated wearable metrics from about 162,000 participants was more accurate than a raw-PPG model on sleep, injury and infection tasks, less accurate on others, and best when the two were combined (Erturk et al. 2025). Forecasting models were pretrained on about 100 billion time points (Das et al. 2023) and on a corpus of 36 million series (Liu et al. 2025). Generative EHR models were trained on 118 million patients and 115 billion medical events (Waxler et al. 2025), and a generative model of more than 1,000 diseases trained on about 400,000 UK Biobank participants was validated on 1.9 million Danish records without retraining (Shmatko et al. 2025).

Compare. Against a task-specific supervised model, a foundation model trades a large one-time pretraining cost for cheaper, more label-efficient tasks afterwards. Against a general large language model, a health foundation model usually consumes non-text inputs (signals, codes, epochs) directly and outputs embeddings or forecasts rather than prose; the two meet in multimodal systems, where a language model reads the output of a signal encoder. Against hand-engineered features such as heart-rate variability statistics, a learned representation is not designed by a person and can capture patterns nobody specified, at the price of being harder to interpret.

Contrast and cost. Pretraining requires large compute, data access agreements and careful de-identification, and every new encoder version forces re-embedding and re-validation of every task that depends on it. The scale also makes evaluation harder: a model touched by millions of records can leak information about test patients, and benchmarks rarely reflect what a health system needs. A 2023 survey of clinical foundation models called their evaluation foundations "shaky" (Wornow et al. 2023), noting small or narrow training data and tasks that reveal little about usefulness to health systems. Much of this book is about closing that gap.

Mental model and scope of the book. A health foundation model is a shared, versioned translator from raw health data into a numerical language that many small task models can read. The book follows that translator from its roots to production: its lineage (Chapter 2, Lineage), the data it reads (Chapter 3), the self-supervised objectives that train it (Chapter 4) and the tokenisation of signals and events (Chapter 5); then the model families for time series (Chapter 6), wearables and biosignals (Chapter 7), sleep (Chapter 8) and EHRs (Chapter 9); multimodal and language-model integration (Chapter 10); adaptation and leakage-free evaluation (Chapter 11); and practice (Chapter 12). The next section defines what makes the translator's output good.

The two optimisation problems. Let \(\mathcal{D}_u\) be the distribution of unlabelled inputs (signal windows, timelines), and \(f_\theta : \mathcal{X} \to \mathbb{R}^d\) an encoder with parameters \(\theta\). Pretraining chooses \(\theta\) by minimising a self-supervised loss \(\mathcal{L}_{\text{ssl}}\), a function of the encoder and of a manufactured target computed from \(x\) itself:

\[ \hat\theta = \arg\min_\theta \; \mathbb{E}_{x \sim \mathcal{D}_u}\big[\mathcal{L}_{\text{ssl}}(\theta; x)\big]. \]

For each downstream task \(t = 1,\dots,T\) there is a labelled set \(S_t = \{(x_i, y_i)\}_{i=1}^{n_t}\), with \(n_t\) much smaller than the unlabelled corpus. Adaptation keeps \(\hat\theta\) fixed and fits a task map \(g_{\phi_t} : \mathbb{R}^d \to \mathcal{Y}_t\) with parameters \(\phi_t\), a per-example loss \(\ell\) (for example cross-entropy) and a regularisation weight \(\lambda\):

\[ \hat\phi_t = \arg\min_{\phi} \; \frac{1}{n_t}\sum_{i=1}^{n_t} \ell\big(g_\phi(f_{\hat\theta}(x_i)),\, y_i\big) + \lambda \lVert \phi \rVert^2 . \]

The definition of Bommasani et al. (2021) maps onto this pair: "broad data" is \(\mathcal{D}_u\), "self-supervision" is \(\mathcal{L}_{\text{ssl}}\), and "adaptable to a wide range of tasks" means many \(t\) share one \(\hat\theta\). Fine-tuning, covered in Chapter 11, relaxes the second problem by also updating \(\theta\), usually with a small learning rate or through low-rank adapters.

The linear probe. For a binary label the probe is \(g_\phi(z) = \sigma(w^\top z + b)\), where \(\sigma(u) = 1/(1+e^{-u})\) is the logistic function, \(w \in \mathbb{R}^d\) a weight vector and \(b\) a bias. It has \(d + 1\) parameters. With \(d = 256\) that is 257 numbers per binary task, against \(5 \times 10^7\) in the encoder: a ratio of about \(1.9 \times 10^5\) to 1.

Parameter and data budgets of pretraining versus a linear probe in W1.Pretraining (once)parameters: 5 × 10⁷inputs seen: 1.08 × 10⁸ windows / epochlabels used: 0Linear probe (per task)parameters: 257inputs: 5,000 labelled participantslabels used: 5,000f frozenratio of trainable parameters ≈ 1.9 × 10⁵ : 1
Fig. Where the parameters and the labels go in W1. The 50M-parameter encoder is fitted without labels; each binary task then fits \(d+1 = 257\) parameters on labelled data.

Why fewer trainable parameters help with scarce labels. A crude capacity heuristic says the gap between training and test risk of a well-regularised linear model grows roughly like \(\sqrt{p/n}\), where \(p\) is the number of trainable parameters and \(n\) the number of labelled examples. It is a scaling intuition, not a guarantee, and deep networks routinely beat what parameter counting predicts. Still, it shows the direction: for the probe, \(p/n = 257/5000 \approx 0.051\), so \(\sqrt{p/n} \approx 0.23\); for a from-scratch network with \(p = 5 \times 10^7\) the same ratio is \(10^4\), and only strong inductive bias and regularisation keep it from overfitting. Pretraining moves almost all of \(p\) to a problem where \(n\) is ten billion.

Corpus arithmetic. A window of \(w\) seconds at \(f_s\) Hz holds \(f_s w\) samples; an hour holds \(3600/w\) windows. For a corpus of \(H\) hours the window count is \(N = H \cdot 3600/w\). One epoch that samples a fraction \(\rho\) of windows with batch size \(B\) takes \(\lceil \rho N / B \rceil\) optimiser steps.

Worked example · W1

With \(f_s = 64\), \(w = 10\): 640 samples per window and 360 windows per hour. \(N = 3 \times 10^7 \times 360 = 1.08 \times 10^{10}\). With \(\rho = 0.01\), each epoch sees \(1.08 \times 10^8\) windows; at \(B = 4096\) that is \(\lceil 1.08\times10^8 / 4096 \rceil = 26{,}368\) steps. The probe for AFib has 257 parameters fitted on 5,000 labelled participants.

Reading the headline gain. The area under the ROC curve (AUROC) equals the probability that a randomly chosen positive case receives a higher score than a randomly chosen negative case: \(\text{AUROC} = \Pr\big(s(x^+) > s(x^-)\big)\). Its complement \(1 - \text{AUROC}\) is the fraction of positive–negative pairs ranked the wrong way round. Moving from 0.88 to 0.93 reduces mis-ordered pairs from 12% to 7%, a relative reduction of \((0.12 - 0.07)/0.12 \approx 42\%\).

Worked example · W1

Assume (for illustration only; prevalence is not part of the W1 specification) that 10% of the 5,000 labelled participants have AFib: 500 positives and 4,500 negatives, so \(500 \times 4500 = 2.25 \times 10^6\) positive–negative pairs. The from-scratch model (AUROC 0.88) mis-orders \(0.12 \times 2.25\times10^6 = 270{,}000\) pairs; the probe on W1 embeddings (0.93) mis-orders \(157{,}500\).

When the split pays for itself. Let \(C_{\text{pre}}\) be the pretraining cost, \(C^{\text{probe}}_t\) the cost of adapting task \(t\) (including labels), and \(C^{\text{scratch}}_t\) the cost of building task \(t\) from scratch to the same quality. The foundation model is cheaper in total when

\[ C_{\text{pre}} < \sum_{t=1}^{T} \big(C^{\text{scratch}}_t - C^{\text{probe}}_t\big). \]

Because label cost dominates \(C_t\) in medicine, the right-hand side grows quickly with \(T\) and with how many labels each task saves. The inequality also explains the failure case: if only one task is ever needed and labels are cheap, pretraining may not pay. The EHRSHOT benchmark (Wornow et al. 2023) measured exactly this trade-off for an EHR model pretrained on 2.57 million patients: with \(k \le 64\) labelled examples per class the pretrained model beat a count-feature gradient-boosted baseline across task categories, the advantage narrowed as \(k\) grew, and the baseline overtook it on new-diagnosis tasks above \(k = 64\).

Scale, stated precisely. "At scale" refers to the size of \(\mathcal{D}_u\) and of \(\theta\). Published examples: about 141,000 participants for PPG and ECG encoders (Abbaspourazad et al. 2023); more than 40 million hours from about 165,000 people for a masked wearable model (Narayanswamy et al. 2024); about 100 billion time points for a 200-million-parameter forecaster (Das et al. 2023); 36 million series for Moirai 2.0 (Liu et al. 2025); and 118 million patients, 115 billion events (151 billion tokens) and models up to 1 billion parameters for generative EHR models whose loss followed power laws in compute, data and parameters (Waxler et al. 2025). Scale alone is not the definition: a model trained on a narrow, single-purpose dataset is a pretrained model, not a foundation model, however large it is.

Assumptions and limits. The formulation assumes that test inputs come from a distribution close to \(\mathcal{D}_u\); when a new device or hospital shifts the input distribution, \(f_{\hat\theta}\) may map new inputs to unfamiliar regions and every probe inherits the error. It also assumes that the self-supervised target correlates with the factors downstream tasks need; the next section turns that assumption into measurable properties.

The definition becomes concrete as an interface. A foundation model exposes an encoder with two operations: fit(x_unlabelled), run once, and embed(x), which maps an array of inputs of shape (n, 640) to embeddings of shape (n, d). The toy windows here have one channel; W1's windows carry four channels and have shape (n, 4, 640), which changes the encoder's input layer but not the interface. Each downstream task then fits its own small model on embed(x_labelled). The snippet below makes this executable in four parts.

  1. Corpus bookkeeping. W1's constants (64 Hz, 10-second windows, 30 million hours, 1% per epoch, batch 4,096) are turned into derived counts, and assertions guard them. Such assertions are cheap and catch unit errors (seconds vs. samples) before any GPU time is spent.
  2. Windowing. window_signal reshapes a one-dimensional stream of shape (T,) into non-overlapping windows (T // 640, 640), dropping the incomplete tail. One hour of one channel at 64 Hz gives (360, 640); applied to each of W1's four channels and stacked, it gives (360, 4, 640).
  3. A stand-in encoder. Toy windows are generated as noisy mixtures of 8 latent factors; the label depends on one factor. FrozenEncoder uses principal component analysis (PCA), fitted on 50,000 unlabelled windows only, to produce 16-dimensional embeddings. PCA is not a health foundation model; it is the simplest self-supervised map that learns structure from unlabelled data, and it occupies the same slot a 50-million-parameter contrastive network occupies in W1.
  4. Adaptation. Logistic regression is fitted either on embeddings (a linear probe) or on the raw 640-sample windows, for 100, 1,000 and 5,000 labels, and evaluated by AUROC on 20,000 held-out windows.

In W1 the same interface runs at production scale. One participant-hour flows through the shapes below; only the last step, the probe, differs between tasks.

Array shapes from one hour of W1 signal to a probe output.raw hour(4, 230400)windows(360, 4, 640)embeddings(360, 256)pooled hour(256,) + maskprobep(AFib) scalarwindow_signalembedmasked meansigmoid(w·z+b)
Fig. Shapes along the W1 adaptation path for one participant-hour: four channels (PPG plus three accelerometer axes) of 64 Hz × 3,600 s = 230,400 samples each, 360 windows of 4 × 640 samples, 360 embeddings of width 256, one pooled vector with a missingness mask, one probability.
"""A health foundation model as an interface: pretrain once on unlabelled data,
then adapt cheaply per task. Toy stand-in for W1 (illustrative, not a real PPG model)."""
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

# --- 1. W1 bookkeeping: does the corpus arithmetic add up? -------------------
FS_HZ, WIN_S = 64, 10                      # sampling rate, window length
HOURS = 30_000_000                         # participant-hours of PPG + accelerometry
SAMPLES_PER_WIN = FS_HZ * WIN_S            # 640
WINS_PER_HOUR = 3600 // WIN_S              # 360
N_WINDOWS = HOURS * WINS_PER_HOUR          # 10.8e9
PER_EPOCH = N_WINDOWS // 100               # 1% sampled per epoch
BATCH = 4096
assert SAMPLES_PER_WIN == 640 and N_WINDOWS == 10_800_000_000
steps_per_epoch = -(-PER_EPOCH // BATCH)   # ceiling division
assert steps_per_epoch == 26_368

def window_signal(x: np.ndarray, fs: int = FS_HZ, win_s: int = WIN_S) -> np.ndarray:
    """(T,) samples -> (n_windows, fs*win_s); drops the incomplete tail."""
    w = fs * win_s
    n = len(x) // w
    return x[: n * w].reshape(n, w)

assert window_signal(np.zeros(64 * 3600)).shape == (360, 640)   # one hour

# --- 2. Toy data: windows are noisy mixtures of a few latent physiological factors
rng = np.random.default_rng(0)
D_RAW, D_LATENT = 640, 8
MIX = rng.normal(size=(D_LATENT, D_RAW)) / np.sqrt(D_LATENT)

def make_windows(n: int):
    z = rng.normal(size=(n, D_LATENT))             # latent factors (rhythm, HR, ...)
    x = z @ MIX + 3.0 * rng.normal(size=(n, D_RAW))  # raw window, low SNR per sample
    y = (z[:, 0] + 0.5 * rng.normal(size=n) > 1.0).astype(int)  # label driven by factor 0
    return x, y

# --- 3. "Pretraining": fit an encoder on unlabelled windows only -------------
class FrozenEncoder:
    """Stand-in for f_theta: x (n, 640) -> z (n, d). PCA here; a 50M-param
    contrastive network in W1. The interface, not the internals, is the point."""
    def __init__(self, d: int = 16):
        self.pca = PCA(n_components=d, random_state=0)
    def fit(self, x_unlabelled: np.ndarray) -> "FrozenEncoder":
        self.pca.fit(x_unlabelled); return self
    def embed(self, x: np.ndarray) -> np.ndarray:
        return self.pca.transform(x)

x_u, _ = make_windows(50_000)               # unlabelled corpus (no y used)
enc = FrozenEncoder(d=16).fit(x_u)
x_test, y_test = make_windows(20_000)
z_test = enc.embed(x_test)
assert z_test.shape == (20_000, 16)

# --- 4. Adaptation: linear probe on embeddings vs. a model on raw windows -----
def auroc_probe(n_labels: int, use_encoder: bool) -> float:
    x, y = make_windows(n_labels)
    feats, test = (enc.embed(x), z_test) if use_encoder else (x, x_test)
    clf = LogisticRegression(max_iter=2000, C=1.0).fit(feats, y)
    return roc_auc_score(y_test, clf.decision_function(test))

for n in (100, 1_000, 5_000):
    fm, raw = auroc_probe(n, True), auroc_probe(n, False)
    print(f"labels={n:>5}  probe-on-embedding AUROC={fm:.3f}  raw-window model AUROC={raw:.3f}")
    if n == 100:
        assert fm > raw + 0.05, "pretrained encoder should help most when labels are scarce"
print("steps/epoch:", steps_per_epoch, "OK")

Output of the run used for this chapter:

labels=  100  probe-on-embedding AUROC=0.888  raw-window model AUROC=0.810
labels= 1000  probe-on-embedding AUROC=0.926  raw-window model AUROC=0.847
labels= 5000  probe-on-embedding AUROC=0.928  raw-window model AUROC=0.875
steps/epoch: 26368 OK

The probe on 16-dimensional embeddings is ahead at every label count: by about 0.08 AUROC at 100 labels, where the raw model must estimate 641 weights from 100 examples, and at 1,000 labels, narrowing to about 0.05 at 5,000. As labels grow, the raw model closes part of the gap. That is the shape the EHRSHOT benchmark reports for real EHR models, reproduced here in a setting where the answer is known by construction. The assertion encodes the claim being tested: at 100 labels the embedding must beat raw inputs by more than 0.05 AUROC.

Worked example · W1

The toy AUROC values are not W1 results; their resemblance to W1's 0.93 versus 0.88 is coincidental. What carries over is the structure: the W1 encoder replaces FrozenEncoder, embed returns (n, 256), the AFib probe has 257 weights, and the training loop sees 26,368 steps per epoch, as the assertion on steps_per_epoch checks.

Debugging notes. If the probe on embeddings does not beat raw inputs at small \(n\), check three things in order. First, that the encoder was fitted on unlabelled data from the same distribution as the task (a PCA fitted on different noise levels learns the wrong subspace). Second, that features are on comparable scales: logistic regression with an L2 penalty is sensitive to feature scale, and embeddings with a few very large dimensions dominate the penalty. Third, that train and test windows come from different participants; windows from the same person on both sides inflate every score, a leakage mode treated in Chapter 11. A further check is to fit the probe on embeddings from a randomly initialised encoder: the gap between random and pretrained embeddings isolates what pretraining contributed, as opposed to what the probe and data alone achieve.

In production "pretrain once, adapt many" becomes a platform with six components: a raw-data lake, a pretraining pipeline, a versioned encoder registry, a release gate, an embedding service with batch and online paths, and an embedding store read by task probes. A drift monitor watches the store. The definition's promise, that many tasks share one encoder, is also its operational risk: a defect in the encoder propagates to every task at once, and every encoder upgrade forces every dependent task to be re-validated.

Platform view of a health foundation model: pretraining, registry, release gate, embedding service, store and task probes.Raw signal lake30M h, 38% gapsPretrainingGPU clusterEncoder registryversionedEmbedding servicebatch + onlineEmbedding storehourly pooledTask probesAFib, age, HRRelease gateprobe suite, slices, nuisance checksDrift monitorper firmware, device, site
Fig. Production components around the W1 encoder. A checkpoint reaches the embedding service only through the release gate; the drift monitor compares embedding distributions per firmware, device and site cohort.

Storage and recompute. The problem is that per-window embeddings are large and must be recomputed for each encoder version. The root cause is the corpus size multiplied by the embedding width. In W1, 10.8 billion windows times 256 dimensions times 2 bytes (16-bit floats) is about 5.5 TB per encoder version. Pooling to one vector per participant-hour (a mean over the up to 360 windows with data) reduces this to \(3 \times 10^7 \times 512\) bytes, about 15.4 GB. The remedy is to store pooled embeddings by default and recompute window-level embeddings only for tasks that need them (beat-level arrhythmia review, for example). The trade-off is that pooling discards within-hour timing: a 30-second AFib episode is averaged with 59.5 minutes of sinus rhythm. Validation: compare probe AUROC on pooled and window-level embeddings for each task before choosing; if a task loses more than an agreed margin (for example 0.01 AUROC) it keeps window-level storage.

Backfill cost. Re-embedding the corpus for a new version costs \(N / r\) GPU-seconds for throughput \(r\) windows per GPU-second. With an assumed \(r = 20{,}000\) (an illustrative figure for a 50M-parameter encoder at 640 samples; actual throughput must be measured), W1 needs \(1.08\times10^{10}/2\times10^4 = 5.4\times10^5\) GPU-seconds, about 150 GPU-hours. This is small next to pretraining but it is paid on every version, and it blocks every downstream probe until it finishes.

Missing data in the store. 38% of W1 hours carry no PPG because the device is off the wrist or charging. Writing a zero vector for those hours would silently tell every probe that the participant had an average-looking hour. The store therefore holds an explicit mask per hour and a count of windows with data, and probes either ignore masked hours or receive the mask as an input. Over a 168-hour week this means about 64 masked hours per participant on average.

Service-level objectiveMetricW1 target (illustrative)Diagnoses
Embedding freshnessp95 delay from upload to stored hourly embedding< 6 hpipeline backlog, failed batches
Coveragefraction of worn hours with a stored embedding≥ 99.5%dropped uploads, decoding failures
Version consistencyprobes reading an embedding version they were not validated on0registry or deployment error
Task qualityAFib probe AUROC on monthly labelled audit sample≥ 0.91 overall, ≥ 0.88 worst slicedrift, label shift, encoder defect
Embedding driftmean standardised shift per firmware, device and site cohort< 0.1new hardware, firmware, population
Worked incident · W1

Symptom. After a watch firmware update that changes optical signal processing reaches part of the fleet, the monthly audit shows AFib AUROC 0.92 overall but 0.87 on participants with the new firmware (all incident numbers illustrative). Measurements that separate causes. Two explanations compete: the updated group differs as a population (for example, it skews older), or the signal itself changed. The drift monitor shows a mean standardised shift of 0.31 for the updated cohort against 0.03 for a non-updated control. Comparing the same participants one week before and after their update gives a within-person shift of 0.29, which rules out a population explanation; the label prevalence in the audit sample is unchanged. Remedies. (1) Re-fit each probe with a firmware indicator: minutes of compute, but the embedding stays distorted, so every task must repeat the patch. (2) A learned input normaliser that maps new-firmware windows toward the old distribution: one fix for all tasks, but it needs paired data and can erase genuine signal. (3) Continued pretraining on mixed-firmware data, producing a new encoder version: the root-cause fix, at the cost of pretraining compute, about 150 GPU-hours of backfill and re-validation of all probes. The chosen sequence is (1) as an immediate mitigation for the AFib probe only, then (3) as the fix. Validation. On participants held out of continued pretraining, the hypothesis is supported if new-firmware AUROC returns to at least 0.91 and the cohort drift falls below 0.1 while the non-updated cohort stays at 0.93. It is weakened if AUROC recovers only for participants whose data was used in continued pretraining, which would indicate memorisation rather than an adapted encoder.

Connection to the definition. The incident is the definition's adaptability claim tested in operation: a foundation model is only as reusable as its embeddings are stable under the device, site and population changes that health data undergoes. The release gate in the next section exists to catch such defects before a version is shared, rather than after every probe has inherited them.

"""Release gate for a new encoder checkpoint and a per-cohort embedding drift monitor.
Thresholds are W1 policy choices (illustrative), not published values."""
import numpy as np

GATE = {                                  # metric: (direction, threshold)
    "afib_auroc":            (">=", 0.91),   # W1 production probe is 0.93
    "afib_auroc_worst_slice": (">=", 0.88),  # never below supervised-from-scratch
    "age_mae_years":         ("<=", 6.5),    # W1 is 6.1
    "hr_mae_bpm":            ("<=", 2.8),    # W1 is 2.4
    "device_nn_purity_ratio": ("<=", 1.5),   # purity / chance
    "rankme_frac":           (">=", 0.5),    # RankMe / embedding dim (256)
}

def gate(report: dict) -> list:
    fails = []
    for k, (op, thr) in GATE.items():
        v = report[k]
        ok = v >= thr if op == ">=" else v <= thr
        if not ok:
            fails.append(f"{k}={v} violates {op} {thr}")
    return fails

def cohort_drift(z_ref: np.ndarray, z_new: np.ndarray) -> float:
    """Mean standardised shift of embedding dimensions between a reference cohort
    (e.g. old firmware) and a new one. 0 = no shift; > 0.1 is the W1 alert threshold."""
    mu, sd = z_ref.mean(0), z_ref.std(0) + 1e-8
    return float(np.abs((z_new.mean(0) - mu) / sd).mean())

candidate = {"afib_auroc": 0.93, "afib_auroc_worst_slice": 0.86, "age_mae_years": 6.1,
             "hr_mae_bpm": 2.4, "device_nn_purity_ratio": 2.1, "rankme_frac": 0.62}
fails = gate(candidate)
print(fails)
assert len(fails) == 2 and fails[0].startswith("afib_auroc_worst_slice")

rng = np.random.default_rng(2)
ref = rng.normal(size=(5000, 256))
same = rng.normal(size=(5000, 256))
shifted = rng.normal(size=(5000, 256)); shifted[:, :40] += 0.8   # 40 dims moved
print(f"drift same={cohort_drift(ref, same):.3f} shifted={cohort_drift(ref, shifted):.3f}")
assert cohort_drift(ref, same) < 0.05 < 0.1 < cohort_drift(ref, shifted)

The drift function above is the monitor used in the incident; on synthetic data it reports 0.016 for two samples from the same distribution and 0.140 when 40 of 256 dimensions shift by 0.8 standard deviations. The gate function is described with the release process in the next section.

What makes a good representation

Definition. A good representation makes the downstream tasks that matter easy: a simple model on top of it, often linear, reaches high accuracy with few labels, and keeps that accuracy when the device, site or population changes. "Easy" is the operative word. Any reversible encoding of an input contains all of the input's information, so pretraining cannot create information about a diagnosis that the raw signal did not hold. What it buys is accessibility: the information is arranged so that a small model can read it.

Motivation. Without a working definition, a foundation model is judged by its headline score on one task, and that score hides the ways health representations fail: learning the hospital instead of the patient, discarding the waveform detail a clinician cares about, or collapsing when a sensor goes missing. An earlier tradition of representation learning framed the goal as representations that disentangle the underlying factors of variation in the data (Bengio et al. 2013). Health data adds specific pressures: nuisances such as device firmware and coding habits are strong and structured, and missingness is the rule rather than the exception.

The six properties, end to end. This book checks six properties, roughly in order of how often they fail on health data.

Six properties of a good health representation, each with the test that measures it.1. Linear accessibilitylinear probe on frozen features2. Label efficiencyscore vs. labels per class3. Nuisance invarianceneighbours share device or site?4. Signal sensitivityaugmentation keeps morphology?5. Missingness robustnessdrop hours or channels, re-score6. Retrieval geometryalignment, uniformity, rank
Fig. The six properties used in this book to judge a health representation, ordered roughly by how often they fail on health data, with the measurement that tests each.
  • Linear accessibility. Clinically relevant factors, such as age, heart rate, sleep stage and disease status, should be readable by a linear model. The test is a linear probe: freeze the encoder, fit a weighted sum of embedding entries on labelled data, and score it on held-out people. Linear probing is the standard first test because it measures the representation rather than the capacity of a large head (Chapter 11).
  • Label efficiency. Performance with few labels, from 1 to 128 per class, should beat training from scratch. The test is a curve of score against the number of labels. The EHRSHOT benchmark (Wornow et al. 2023) was built around this curve for 15 tasks on 6,739 patients.
  • Invariance to nuisances. Sensor placement, device model and firmware, hospital coding habits and signal quality should not dominate the embedding. The test: look at each person's nearest neighbours in embedding space. If they are mostly people from the same hospital or with the same watch, the representation has learned the hospital or the watch.
  • Sensitivity to the signal. Invariance can go too far. Self-supervised training often makes the encoder ignore transformations ("augmentations") applied to the input; a PPG augmentation that smooths away pulse-wave shape may also erase the information about vascular ageing the model was meant to capture. PaPaGei (Pillai et al. 2024) was designed around this tension, using differences in PPG pulse morphology between individuals during pretraining. The test: check that features known to matter, such as morphology indices, remain decodable after training.
  • Robustness to missingness. Health data is missing by design: watches come off, laboratory tests are not ordered. A good representation degrades gracefully when hours or channels are absent. LSM-2 (Xu et al. 2025) targets this directly; its authors found no day-long window without missing data among 1.6 million windows, and trained on incomplete data instead of imputing or discarding it. The test: remove hours or channels at evaluation and measure the drop.
  • Geometry that supports retrieval. Contrastive representations spread embeddings evenly over the surface of a sphere while keeping matching pairs close (Wang and Isola 2020). That geometry enables nearest-neighbour search ("patients like this one") and cross-modal retrieval, such as finding the sleep recording that matches an ECG. The test: measure how close matching pairs are, how evenly points spread, and how many directions the embeddings actually use.
Worked example · W1

W1 passes the first two checks on its headline tasks: linear probes reach AFib AUROC 0.93, age MAE 6.1 years and resting heart rate MAE 2.4 bpm, and the AFib probe beats a from-scratch model (0.88) on the same 5,000 labelled participants. The remaining four checks need separate measurements. Because positives in W1 are two windows from the same participant within 24 hours, and participants usually wear one device model, the objective can be partly satisfied by encoding the device; the nuisance check is therefore mandatory. Because 38% of hours have no PPG, the missingness check is mandatory too.

Compare. Hand-engineered features (heart-rate variability, pulse amplitude, step counts) are linearly accessible by construction and interpretable, but cover only what their designers anticipated. Representations from supervised training on one label are excellent for that label and often poor for others, because the network discards whatever did not help. Self-supervised representations sit between: they keep more general structure, which is why they transfer, but nothing in the objective guarantees any one of the six properties.

Contrast and cost. The properties pull against each other. More invariance improves robustness to devices and hurts sensitivity to fine signal; more uniform spreading helps retrieval but can scatter clinically similar people. A representation is therefore judged by a profile, not one number, and the profile is chosen by the uses the model will serve.

Mental model. A good representation is a map on which clinically similar people sit close together, the roads a probe needs are straight, the borders between devices and hospitals are invisible, and gaps in the data blur the map rather than tear it. The next chapter traces where the methods that draw such maps came from, and Chapter 4 shows how each self-supervised objective favours some of these properties over others.

Information present versus accessible. Let \(X\) be the input, \(Y\) a downstream label, and \(I(\cdot\,;\cdot)\) mutual information. The data-processing inequality states \(I(Y; f(X)) \le I(Y; X)\) for any encoder \(f\), with equality when \(f\) is invertible. Pretraining cannot raise the information about \(Y\); it can only make it easier to extract. Accessibility is therefore defined relative to a class of readers. For linear readers, the linear probe risk is

\[ R_{\text{lin}}(f) = \min_{w \in \mathbb{R}^d,\, b \in \mathbb{R}} \; \mathbb{E}\big[\ell(w^\top f(X) + b,\, Y)\big], \]

with \(\ell\) a loss such as cross-entropy. A representation is better than another for \(Y\) if its \(R_{\text{lin}}\) is lower, estimated on held-out people with a regularised fit.

Label efficiency. Let \(A(k)\) be the held-out score (for example AUROC) of a probe trained with \(k\) labelled examples per class, averaged over random draws. A label-efficiency curve plots \(A(k)\) for \(k \in \{1, 2, 4, \dots, 128\}\); EHRSHOT uses \(k \in \{1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128\}\). Two summaries are common: the gap \(A_{\text{FM}}(k) - A_{\text{scratch}}(k)\) at fixed \(k\), and \(k^\ast(a)\), the smallest \(k\) at which a target score \(a\) is reached. A representation that reaches AUROC 0.85 at \(k^\ast = 32\) instead of 256 cuts the labelling budget for that target by a factor of 8.

Invariance to a nuisance. Let \(s_i\) be a nuisance attribute of example \(i\) (device model, site, firmware) and \(\mathcal{N}_k(i)\) its \(k\) nearest neighbours in embedding space. The nearest-neighbour purity is

\[ P_k = \frac{1}{nk}\sum_{i=1}^{n}\sum_{j \in \mathcal{N}_k(i)} \mathbf{1}[s_j = s_i], \qquad P_{\text{chance}} = \sum_{c} \pi_c^2, \]

where \(\pi_c\) is the share of examples with nuisance value \(c\) and \(\mathbf{1}[\cdot]\) is 1 when the condition holds. \(P_{\text{chance}}\) is the purity expected if neighbours were drawn without regard to the nuisance. The ratio \(P_k / P_{\text{chance}}\) near 1 indicates invariance; large values indicate the nuisance organises the space.

Worked example · W1

Assume (illustratively) that W1 participants wear four device generations with shares 0.4, 0.3, 0.2 and 0.1. Then \(P_{\text{chance}} = 0.16 + 0.09 + 0.04 + 0.01 = 0.30\). A checkpoint whose 10 nearest neighbours share the device 63% of the time has \(P_{10}/P_{\text{chance}} = 2.1\): device identity organises the embedding even though overall AFib AUROC is 0.93.

Sensitivity to the signal. Self-supervised objectives encourage \(f(T(x)) \approx f(x)\) for augmentations \(T\) drawn from a set \(\mathcal{T}\). This is harmless only when every \(T \in \mathcal{T}\) preserves the label-relevant content: \(y(T(x)) = y(x)\) for every downstream \(y\) of interest. A time shift of a PPG window satisfies this for heart-rate tasks; a strong low-pass filter that removes the dicrotic notch does not for vascular-age tasks. The measurable consequence is that a morphology index \(m(x)\) known to matter should remain linearly decodable: \(R_{\text{lin}}\) for \(m\) should stay low after pretraining.

Robustness to missingness. Let \(A(\mu)\) be the score when a fraction \(\mu\) of input hours (or channels) is removed at evaluation. The degradation is \(\Delta(\mu) = A(0) - A(\mu)\). Reporting \(\Delta\) at the natural missingness rate, and at higher rates, separates models that merely tolerate the training-time gap pattern from those that degrade gracefully.

Worked example · W1

W1's natural rate is \(\mu = 0.38\). If, illustratively, the AFib probe scores 0.93 on complete participant-weeks and 0.90 when 38% of hours are removed at random, \(\Delta(0.38) = 0.03\). A further check removes 38% of hours in contiguous night-time blocks, the pattern charging actually creates, since random removal underestimates the harm of structured gaps.

Geometry. Let \(u = z/\lVert z\rVert\) denote an embedding normalised to unit length, and \((x, x^+)\) a positive pair. Wang and Isola (2020) decompose contrastive learning into two measurable terms:

\[ \mathcal{L}_{\text{align}} = \mathbb{E}_{(x,x^+)}\big[\lVert u(x) - u(x^+)\rVert_2^2\big], \qquad \mathcal{L}_{\text{unif}} = \log \mathbb{E}_{x,x'}\big[e^{-t\,\lVert u(x) - u(x')\rVert_2^2}\big], \]

with \(t > 0\) (commonly 2) and \(x, x'\) independent samples. Lower alignment means positives are close; lower (more negative) uniformity means points cover the sphere. For unit vectors at angle \(\alpha\), \(\lVert u - v\rVert^2 = 2 - 2\cos\alpha\).

Embeddings on the unit circle: aligned and uniform, collapsed, and clustered by device.aligned and uniformcollapsedclustered by devicefilled accent dots: AFib-positive windows; dark dots: negative
Fig. Geometry of normalised embeddings. Left: positive pairs sit close (good alignment) and points cover the circle (good uniformity). Middle: dimensional collapse, where every input maps to nearly the same direction. Right: points cluster by device, so neighbours share hardware rather than physiology. Schematic.
Worked example · W1

Two windows from the same W1 participant whose embeddings are 20° apart contribute \(2 - 2\cos 20^\circ = 2 - 1.879 = 0.121\) to alignment. Two unrelated windows at 90° contribute \(e^{-2 \cdot 2} = e^{-4} \approx 0.018\) inside the uniformity expectation; if all pairs were orthogonal, \(\mathcal{L}_{\text{unif}} = \log 0.018 = -4.0\). In a collapsed encoder every pair has distance near 0, so \(\mathcal{L}_{\text{unif}} \approx \log 1 = 0\).

Effective rank. A representation can also collapse into a few directions without collapsing to a point. For an embedding matrix \(Z \in \mathbb{R}^{n \times d}\) with singular values \(\sigma_1, \dots, \sigma_d\), RankMe (Garrido et al. 2023) normalises them to \(p_j = \sigma_j / \sum_i \sigma_i\) (plus a small constant) and reports

\[ \text{RankMe}(Z) = \exp\Big(-\sum_{j=1}^{d} p_j \log p_j\Big), \]

a smooth count of the directions in use, between 1 and \(d\). Garrido et al. report that higher RankMe on unlabelled data predicts better downstream probe performance across runs of the same method, so it can guide model selection without labels; they also note that a high rank is necessary but not sufficient.

Worked example · W1

Take four singular values \((4, 2, 1, 1)\). Then \(p = (0.5, 0.25, 0.125, 0.125)\), the entropy is \(0.5\ln 2 + 0.25 \ln 4 + 2 \times 0.125 \ln 8 = 0.347 + 0.347 + 0.520 = 1.213\), and RankMe \(= e^{1.213} \approx 3.36\) of a possible 4. For W1's 256-dimensional embeddings, a release policy might require RankMe of at least 128 (half the dimensions); this threshold is an illustrative policy choice.

Trade-offs in one line. Stronger invariance lowers \(P_k/P_{\text{chance}}\) and can raise \(R_{\text{lin}}\) for signal-dependent labels; stronger uniformity lowers \(\mathcal{L}_{\text{unif}}\) and can raise \(\mathcal{L}_{\text{align}}\). No single scalar summarises a representation; the six quantities together form its profile.

Each property becomes a function that takes embeddings, of shape (n, d), plus labels or nuisance attributes, and returns a number. The snippet below implements all six and tests them on synthetic embeddings whose answers are known:

  • probe_auroc: linear accessibility, a logistic-regression probe scored by held-out AUROC.
  • label_curve: label efficiency, the probe re-fitted on \(k\) examples per class for several \(k\) and averaged over 5 random draws.
  • nn_purity: nuisance invariance, the share of each point's 10 nearest neighbours with the same nuisance value, returned together with the chance level \(\sum_c \pi_c^2\).
  • alignment, uniformity: geometry, the Wang and Isola statistics on L2-normalised embeddings (uniformity on a random subsample of 2,000 points to keep the pairwise matrix small).
  • rankme: effective rank from singular values, a label-free collapse check.
  • missingness_drop: the degradation \(A(0) - A(\mu)\); producing \(A(\mu)\) requires re-embedding with hours removed, which needs the real encoder, so only the bookkeeping is shown.

Signal sensitivity is measured with the same probe_auroc, applied to a morphology target instead of a diagnosis. The synthetic data contrasts two encoders that carry the same AFib signal in dimension 0; the "shortcut" encoder additionally adds a strong per-device offset, imitating an encoder that learned to recognise the watch.

"""Six-property representation audit on embeddings Z (n, d).
Toy data: a 'clean' encoder and a 'shortcut' encoder that also encodes the device model."""
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score
from sklearn.neighbors import NearestNeighbors

rng = np.random.default_rng(1)

# 1. Linear accessibility: held-out AUROC of a logistic-regression probe.
def probe_auroc(z_tr, y_tr, z_te, y_te, C=1.0):
    clf = LogisticRegression(max_iter=3000, C=C).fit(z_tr, y_tr)
    return roc_auc_score(y_te, clf.decision_function(z_te))

# 2. Label efficiency: probe AUROC as a function of labelled examples per class k.
def label_curve(z_tr, y_tr, z_te, y_te, ks=(4, 16, 64, 256), reps=5):
    out = {}
    for k in ks:
        scores = []
        for _ in range(reps):
            idx = np.concatenate([rng.choice(np.flatnonzero(y_tr == c), k, replace=False) for c in (0, 1)])
            scores.append(probe_auroc(z_tr[idx], y_tr[idx], z_te, y_te))
        out[k] = float(np.mean(scores))
    return out

# 3. Invariance to nuisances: how often do k nearest neighbours share the nuisance
#    (device, site) compared with chance = sum_s pi_s^2 ?
def nn_purity(z, s, k=10):
    nn = NearestNeighbors(n_neighbors=k + 1).fit(z)
    _, idx = nn.kneighbors(z)
    same = (s[idx[:, 1:]] == s[:, None]).mean()
    pi = np.bincount(s) / len(s)
    return float(same), float((pi ** 2).sum())

# 6. Geometry: alignment (positives close) and uniformity (spread on the sphere),
#    Wang & Isola (2020), on L2-normalised embeddings.
def l2n(z): return z / np.linalg.norm(z, axis=1, keepdims=True)
def alignment(za, zb, alpha=2):
    return float((np.linalg.norm(l2n(za) - l2n(zb), axis=1) ** alpha).mean())
def uniformity(z, t=2, m=2000):
    u = l2n(z[rng.choice(len(z), min(m, len(z)), replace=False)])
    sq = np.clip(2 - 2 * u @ u.T, 0, None)                 # squared distances on sphere
    iu = np.triu_indices(len(u), 1)
    return float(np.log(np.exp(-t * sq[iu]).mean()))

# Label-free collapse check: RankMe effective rank, Garrido et al. (2023).
def rankme(z, eps=1e-7):
    s = np.linalg.svd(z, compute_uv=False)
    p = s / s.sum() + eps
    return float(np.exp(-(p * np.log(p)).sum()))

# 5. Robustness to missingness: metric drop when a fraction of input hours is absent.
def missingness_drop(score_full, score_masked):
    return score_full - score_masked

# ---------------- toy embeddings ----------------
n, d = 6000, 32
y = rng.integers(0, 2, n)                    # e.g. AFib yes/no
s = rng.choice(4, n, p=[0.4, 0.3, 0.2, 0.1])  # device model (nuisance)
signal = np.zeros((n, d)); signal[:, 0] = 1.5 * y
z_clean = signal + rng.normal(size=(n, d))
dev_dirs = rng.normal(size=(4, d)) * 3.0
z_short = z_clean + dev_dirs[s]               # same signal, plus a strong device code

tr, te = np.arange(4000), np.arange(4000, n)
a_clean = probe_auroc(z_clean[tr], y[tr], z_clean[te], y[te])
a_short = probe_auroc(z_short[tr], y[tr], z_short[te], y[te])
p_clean, chance = nn_purity(z_clean, s)
p_short, _ = nn_purity(z_short, s)
print(f"probe AUROC  clean={a_clean:.3f} shortcut={a_short:.3f}")
print(f"device NN purity clean={p_clean:.2f} shortcut={p_short:.2f} chance={chance:.2f}")
assert abs(chance - 0.30) < 0.01   # population value 0.16+0.09+0.04+0.01 = 0.30
assert abs(p_clean - chance) < 0.03 and p_short > 0.9   # probe AUROC alone would not reveal this

curve = label_curve(z_clean[tr], y[tr], z_clean[te], y[te])
print("label curve:", {k: round(v, 3) for k, v in curve.items()})
assert curve[256] >= curve[4]

# Geometry: positives = two noisy views of the same participant state.
base = rng.normal(size=(3000, d))
va, vb = base + 0.3 * rng.normal(size=base.shape), base + 0.3 * rng.normal(size=base.shape)
collapsed = np.outer(rng.normal(size=3000), rng.normal(size=d)) + 0.01 * rng.normal(size=(3000, d))
print(f"alignment={alignment(va, vb):.3f} uniformity={uniformity(va):.3f} "
      f"uniformity(collapsed)={uniformity(collapsed):.3f}")
assert uniformity(va) < uniformity(collapsed)          # lower = more spread
print(f"RankMe healthy={rankme(va):.1f} collapsed={rankme(collapsed):.1f} (max {d})")
assert rankme(va) > 25 and rankme(collapsed) < 3
assert abs(missingness_drop(0.93, 0.90) - 0.03) < 1e-12
print("all checks passed")

Output of the run used for this chapter:

probe AUROC  clean=0.843 shortcut=0.818
device NN purity clean=0.29 shortcut=1.00 chance=0.29
label curve: {4: 0.663, 16: 0.664, 64: 0.773, 256: 0.827}
alignment=0.170 uniformity=-3.752 uniformity(collapsed)=-0.724
RankMe healthy=32.0 collapsed=1.5 (max 32)
all checks passed

The key result is in the first two lines. The shortcut encoder's probe AUROC (0.818) is only slightly below the clean encoder's (0.843), so a single headline metric would not raise an alarm, yet its device purity is 1.00 against a chance level of 0.29: every neighbour comes from the same device. The purity test catches what the probe misses. The geometry checks behave as derived at Level 2: two noisy views of the same point have small alignment (0.170), healthy embeddings have strongly negative uniformity (\(-3.75\)), and a rank-one collapsed set has uniformity near 0 (\(-0.72\)) and RankMe 1.5 against 32 for the healthy set.

Worked example · W1

Applied to W1, the same functions run on (n, 256) embeddings of held-out participants: probe_auroc for AFib (target 0.93), nn_purity with s set to device generation, and rankme on a 50,000-window sample. With device shares 0.4/0.3/0.2/0.1 the population chance level is 0.30, which the test asserts the synthetic sample reproduces within 0.01.

Debugging notes. Nearest-neighbour purity is sensitive to scale: compute it on the same normalised embeddings the downstream system uses, and compare checkpoints at a fixed \(k\). Purity also rises if the same participant contributes many windows, because a person's windows neighbour each other and share a device; pool to one embedding per participant, or exclude same-participant neighbours, before interpreting it. For label_curve, sample the \(k\) examples per class by participant, not by window, or the curve measures memorisation of individuals. RankMe should only compare runs of the same method and embedding width, as its authors caution; across methods the scale of singular values differs. Finally, uniformity uses an \(m \times m\) pairwise matrix, so memory grows quadratically; the subsample of 2,000 points keeps it at 4 million entries.

In production the six properties become a release gate: an ordered set of checks that every encoder checkpoint must pass before it enters the registry and before any embedding is backfilled. The gate exists because a defect in a shared encoder reaches every task at once, and because the most dangerous defects, shortcuts and slice failures, do not move the headline metric.

Checkpoint release gate: label-free checks, probe suite, slice and nuisance checks, then release.Checkpointstep tLabel-free checksRankMe, uniformityProbe suiteAUROC, MAE, k-curveSlice + nuisanceworst slice, purityReleaseto registryfail: stop, logfail: stop, logfail: stop, logcheap checks run first; the expensive probe suite runs only on survivors
Fig. Order of checks before a W1 encoder checkpoint is released. Each stage is more expensive than the one before; a failure stops the pipeline and is logged against the checkpoint.

Ordering by cost. The problem is that a full probe suite is expensive per checkpoint. The root cause is embedding the evaluation cohort: in W1 the 5,000 labelled participants average 200 hours each (30 million hours over 150,000 participants), so the cohort holds about 1 million hours or 360 million windows. At the assumed 20,000 windows per GPU-second, that is 18,000 GPU-seconds, about 5 GPU-hours per checkpoint. Label-free checks (RankMe and uniformity on a 50,000-window sample) cost seconds. The remedy is to order the gate: run label-free checks at every saved checkpoint during pretraining, the probe suite only on checkpoints that pass, and slice and nuisance checks last. The trade-off is that label-free checks can pass a checkpoint that later fails on probes; they are a filter, not a verdict. Validation: over past training runs, the fraction of checkpoints rejected by probes after passing label-free checks shows whether the filter is too loose.

Gate stageMetricW1 threshold (illustrative policy)Failure it catches
Label-freeRankMe / 256≥ 0.5dimensional collapse
Probe suiteAFib AUROC; age MAE; resting-HR MAE≥ 0.91; ≤ 6.5 y; ≤ 2.8 bpmregression on headline tasks
Probe suitelabel curve at 32 participants per classabove from-scratchloss of label efficiency
Slicesworst-slice AFib AUROC (device, age band, skin tone)≥ 0.88 (never below from-scratch)subgroup failure
Nuisancedevice-neighbour purity / chance≤ 1.5device or site shortcut
MissingnessAFib AUROC drop with night-time blocks removed at 38%≤ 0.03brittleness to gaps
Worked incident · W1

Symptom. A new W1 checkpoint improves overall AFib AUROC to 0.93 and passes label-free checks (RankMe/256 = 0.62), but the gate fails two checks: worst-slice AUROC is 0.86 on the oldest device generation (10% of participants), and device-neighbour purity is 0.63 against a chance level of 0.30, a ratio of 2.1 (illustrative numbers; the gate code in the previous section reproduces this verdict). Root cause. W1's positives are two windows from the same participant within 24 hours. Each participant wears one device, so device identity is a cheap feature that separates positives from most negatives in a mixed batch; the objective rewards encoding it. Measurements that separate causes. If the slice gap were a population effect (older-device owners differ clinically), the gap would persist in a probe trained only on that slice; if it is a shortcut, a linear classifier will predict device generation from embeddings with high accuracy, and purity will stay high even when same-participant neighbours are excluded. Here device is predictable at well above chance and purity stays at 0.61 with same-participant neighbours excluded, which supports the shortcut explanation. Remedies. (a) Device-stratified batches: fill each batch with windows from one device generation, so negatives share the device and device identity no longer separates positives from negatives. It costs only data-loader changes but reduces negative diversity. (b) Device-response augmentation: randomise gain and optical filter response to imitate other generations. Cheap, but if the simulated response is wrong it erases real signal, the sensitivity property. (c) An adversarial device head with gradient reversal: direct, but adds a tuning parameter and can destabilise training. The chosen remedy is (a) plus mild (b), continued from the last good checkpoint. Validation. The fix is supported if purity/chance falls to 1.5 or below, worst-slice AUROC reaches at least 0.88, and overall AUROC stays at or above 0.92 on held-out participants. It is weakened if purity falls but the oldest-device slice does not improve, which would mean the slice gap had a separate cause, such as lower signal quality on older optics, to be addressed with quality-aware probing rather than invariance.

Monitoring during pretraining. RankMe and uniformity computed every 1,000 steps on a fixed unlabelled sample give an early warning of collapse long before a probe suite would run. A falling RankMe with a falling loss is the characteristic signature: the objective is being satisfied by using fewer directions. The response is to stop the run and inspect temperature, batch composition and augmentation strength, the controls examined in Chapter 4. The trade-off is that label-free metrics compare only runs of the same method and width, so they cannot rank a contrastive encoder against a masked one; that comparison needs the probe suite.

Choosing thresholds. Thresholds are policy, not science, and should be anchored to the alternative a downstream user would otherwise have. In W1 the worst-slice floor of 0.88 equals the from-scratch AUROC: a slice served worse by the foundation model than by a task model trained on the same labels is a regression for that slice, whatever the average says. The nuisance ratio of 1.5 is looser than perfect invariance because some device association is legitimate (newer devices are bought by different people); the test of whether a ratio is acceptable is whether worst-slice performance is within the floor.

Connection. The definition promised reuse across tasks; the six properties and the gate are what make that promise checkable. Later chapters return to each property with its own methods: objectives that shape geometry (Chapter 4), missingness-aware training (Chapter 7), and shift, fairness, calibration and leakage-free evaluation (Chapter 11).

Lineage

Health foundation models meet at a point where six older lines of work cross: three from general representation learning and three from health and forecasting. Each line contributes one ingredient. Representation learning supplies what to learn (a reusable embedding of a person, a night or a timeline). Self-supervised objectives supply how to learn it without labels (reconstruct, predict next, contrast, predict in latent space). Forecasting, clinical informatics and sleep medicine supply what the data looks like: long numeric series with seasonality and gaps, sparse coded events with irregular time, and multichannel overnight recordings divided into scored epochs. The health-FM era, roughly 2023 onward, is the combination of the six: tokens and objectives from language and vision, global models from forecasting, event vocabularies from clinical informatics, and the epoch-and-channel structure of sleep medicine.

This chapter is a reference: one dense pass through that lineage, written in the style of a related-work survey, without the four-level treatment used elsewhere in the book. For each paper or system it states the problem it attacked, the mechanism (what each component receives and produces, and how it is trained), the key result with numbers from the source, what it left open, and who picked that up. Dates are first public release (arXiv or journal) as stated by the source. Where a link between two works is our reading rather than something the later authors state, the text says so.

Numbers that belong to the three reference workloads appear only in callouts marked "Worked example". The workloads are defined in the front matter and are illustrative, not published results: W1 is a wearable PPG and accelerometry encoder (150,000 participants, 30 million participant-hours, 50M parameters, InfoNCE with same-participant positives); W2 is a decoder-only generative EHR model (2 million patients, 310 million events, 120M parameters, context 4,096 tokens); W3 is a multimodal sleep PSG encoder (30,000 overnight recordings, about 240,000 hours, five channel groups). Each callout uses the same numbers as every other chapter.

ThreadQuestion it answersOldest root here2025–2026 frontierWorkload that inherits most
RepresentationsWhat is a good reusable embedding?Deep autoencoders (2006)"Foundation model" as a framing (2021); scaling as the default leverall three
Contrastive and latent predictionWhich pairs should agree, and what should the encoder predict?CPC / InfoNCE (2018)JEPA-style latent prediction for ECG and EEGW1, W3
Masked and autoregressive pretrainingHow to turn raw data into a prediction task at scale?GPT, BERT (2018)Masked reconstruction for wearables at billions of hoursW1, W2
ForecastingHow to predict a series' future, and can one model serve all series?Box–Jenkins ARIMA (1970)Covariate-aware, multivariate, in-context forecastersW1 (forecasting heads)
Clinical event modelingHow to model a patient's coded history?Doctor AI (2015)Generative "world models" of timelines at 100M+ patientsW2
Sleep and biosignalsHow to read physiology from overnight and wearable recordings?Rechtschaffen & Kales manual (1968)PSG models predicting future disease; wearable models at billions of hoursW1, W3

Table. The six threads of this chapter, grouped in the next section into four clusters (self-supervision, time series, EHR, biosignals and sleep) plus a cross-cutting strand on language and multimodal models.

The chapter has two sections. The first walks each thread from its root to its 2026 descendants, entry by entry. The second draws the threads on one timeline, maps each reference workload to the ancestors its design choices come from, and gives reading orders for different goals. Later chapters treat each mechanism at four levels; this chapter only places it.

Threads: self-supervision, time series, EHR, biosignals

Each cluster below is ordered by date. Entries are deliberately uniform: problem, mechanism, result, what remained open and which later work took it up. A reader who needs only the shape of the field can read the first sentence of each entry; a reader comparing two methods can read the mechanisms side by side.

A. Self-supervision: representations, objectives and scale. This cluster is not about health at all, and every health model in this book depends on it. It answers three questions in sequence: what a representation should capture, which prediction task forces a network to learn it from unlabelled data, and how much data and compute that task needs.

Deep autoencoders (Hinton & Salakhutdinov, 2006). Problem: principal component analysis (PCA) compresses data with a linear map and misses curved structure. Mechanism: an autoencoder is an encoder network that maps an input to a short code and a decoder that maps the code back; training minimizes reconstruction error, so the code must keep whatever the decoder needs. Deep autoencoders were pretrained layer by layer and then fine-tuned. Result: deep codes reconstructed images and documents better than PCA at the same code size. Left open: reconstruction rewards keeping every detail, including noise; nothing tells the code which details matter. Picked up by: masked reconstruction (BERT, MAE) changed the task from copying the input to filling in hidden parts, which forces the model to use context; wearable models such as LSM are its direct health descendants.

word2vec (Mikolov et al., 2013). Problem: one-hot word vectors share no information between related words. Mechanism: a shallow network learns one vector per word by predicting a word from its neighbors (or neighbors from the word) over a large corpus; words used in similar contexts end up close together. Result: vectors with useful arithmetic structure, learned from raw text alone. Left open: one vector per word ignores context. Picked up by: "embed a code by the codes around it" became a template for medical-code embeddings and, through contextual models, for BEHRT and Med-BERT.

Representation learning as a goal (Bengio et al., 2013). This review framed the objective that later health papers inherit: a good representation disentangles the factors of variation in the data, so that a simple model on top can read out any one factor. Health models restate this as "a linear probe on the frozen embedding should predict age, heart rate or disease", which is the evaluation protocol used by Apple's biosignal models, SleepFM and EHRSHOT.

VQ-VAE (van den Oord et al., 2017). Problem: continuous latent codes are awkward to model with the token-level machinery that works for text. Mechanism: the encoder output is snapped to the nearest entry of a learned codebook, so every input becomes a sequence of discrete code indices; the decoder reconstructs from those. Result: discrete tokens for images, audio and video that a second model can predict. Picked up by: neural tokenizers for physiological signals; LaBraM trains a vector-quantized EEG tokenizer and then pretrains by predicting the codes of masked patches.

Contrastive Predictive Coding and InfoNCE (van den Oord et al., 2018). Problem: predicting raw future values wastes capacity on low-level detail. Mechanism: an encoder maps each window to a latent vector, an autoregressive model summarizes the past into a context vector, and the model must pick the true future latent out of a set of candidates; the loss, InfoNCE, is cross-entropy over that choice. Minimizing it maximizes a lower bound on the mutual information between context and future, a bound that cannot exceed the logarithm of the number of candidates (Poole et al., 2019). Result: strong linear-probe features for speech, images and text from one recipe. Left open: which candidates count as negatives, and the log-N ceiling that ties the objective to batch size. Picked up by: SimCLR, CLIP, and in health, Apple's PPG/ECG models and SleepFM, which use InfoNCE with health-specific positives.

GPT and BERT (Radford et al., 2018; Devlin et al., 2018). Problem: task-specific language models needed large labelled sets. Mechanism: GPT trains a transformer decoder to predict the next token; BERT trains a bidirectional encoder to recover randomly masked tokens. Either model is then fine-tuned on a small labelled task. Result: one pretrained network improved many downstream tasks at once, which established pretrain-then-adapt as the default. Picked up by: every EHR model in cluster C is a BERT or a GPT over medical codes; TimesFM and Chronos are GPT-style decoders over numeric patches.

wav2vec 2.0 (Baevski et al., 2020). Problem: raw audio is continuous and highly redundant. Mechanism: a convolutional feature encoder, span masking over its outputs, and a contrastive task that identifies the true quantized latent for each masked span among distractors. Picked up by: ECG-FM, a 90.9M-parameter model in the wav2vec 2.0 style for 12-lead ECG, which is the clearest case of a speech recipe moved to a biosignal.

SimCLR and BYOL (Chen et al., 2020; Grill et al., 2020). Problem: CPC-style objectives were complex, and it was unclear which components mattered. Mechanism: SimCLR creates two augmented views of each image, encodes both, and applies InfoNCE with all other images in a large batch as negatives; a small projection head sits between the encoder and the loss. BYOL removes negatives: an online network predicts the output of a slowly updated (momentum) target network, which avoids the collapse to a constant embedding. Result: self-supervised linear probes approached supervised baselines on ImageNet. Left open: the augmentations encode the invariances, and image augmentations do not transfer to physiology; collapse prevention without negatives was empirical. Picked up by: health models replaced augmentation-defined positives with structure-defined ones (same participant, adjacent segment, same moment in another modality). Wang & Isola (2020) explained what contrastive objectives optimize: alignment of positives and uniformity of all embeddings on the hypersphere, which became the standard diagnostic for collapse.

Scaling laws and Chinchilla (Kaplan et al., 2020; Hoffmann et al., 2022). Problem: given a compute budget, how large should a model be and how much data should it see? Mechanism: fit power laws of loss against parameters, data and compute from many training runs. Result: Kaplan et al. found smooth power laws; Hoffmann et al. found that compute-optimal language models need far more data per parameter than had been used, on the order of tens of tokens per parameter. Left open: whether the constants transfer to other data. Picked up by: LSM and SensorLM for wearables, and CoMET and a MIMIC-IV study for EHR (entries below), all of which found power laws with different constants.

"Foundation model" (Bommasani et al., 2021). The term was coined for a model trained on broad data, usually with self-supervision at scale, that can be adapted to a wide range of downstream tasks. It named a pattern rather than a method; its value for health was to shift attention from single-task models to reusable encoders and their risks, including homogenization (one model's flaws propagating to every downstream use).

CLIP (Radford et al., 2021). Mechanism: two encoders (image and text) trained with a symmetric InfoNCE loss so that an image and its caption land near each other; the text side then acts as a zero-shot classifier. Picked up by: cross-modal alignment in health takes two forms: signal–signal (SleepFM aligns brain, cardiac and respiratory channels recorded in the same window) and signal–text (SensorLM aligns wearable windows with generated captions).

MAE (He et al., 2021). Problem: BERT-style masking was thought to need discrete tokens. Mechanism: mask a high fraction of image patches (75%), encode only the visible ones, and reconstruct the missing pixels with a light decoder that is discarded after pretraining. Result: strong features at reduced compute, since the encoder sees a quarter of the patches. Picked up by: masked reconstruction for time series (MOMENT masks about 30% of patches) and wearables (LSM, LSM-2, SensorFM), where reconstruction doubles as imputation.

I-JEPA (Assran et al., 2023). Problem: reconstruction in input space spends capacity on unpredictable detail; contrastive learning depends on hand-designed augmentations. Mechanism: a context encoder sees part of an image, a predictor outputs the embedding that a momentum target encoder assigns to masked target blocks, and the loss is computed in embedding space. Result: semantic features without augmentations and without pixel reconstruction. Picked up by (health, 2024–2026): ECG-JEPA (Kim, 2024) pretrains on about 180,000 12-lead ECGs and reports linear-probe AUC 0.912 on PTB-XL multi-label against 0.896 for the masked-reconstruction baseline ST-MEM, with pretraining of about 22 hours on one consumer GPU. Laya (Panchavati et al., 2026) applies the LeJEPA variant to EEG (about 29,000 hours, 17 channel layouts), predicting embeddings of masked 0.5–1 s blocks, and reports a higher clinical mean balanced accuracy than LaBraM (0.597 vs 0.573) and better retention under noise; its own appendix shows LaBraM ahead on plain accuracy, so the advantage depends on the metric.

Five pretraining targets used by health foundation models, each with its ancestors and health descendants.Unlabelled health datasignal windows · PSG epochs · coded event timelinesReconstruct masked inputtarget: raw valuesMAE 2021 · BERT 2018LSM 2024 · MOMENT 2024LSM-2 2025 · SensorFM 2026Predict next token/patchtarget: next elementGPT 2018 · CPC (latent)CLMBR 2020 · TimesFM 2023CoMET 2025 · RAVEN 2026Contrast paired viewstarget: which pair matchesCPC 2018 · SimCLR · CLIPApple PPG/ECG 2023SleepFM 2024 · PaPaGeiPredict masked latentstarget: teacher embeddingI-JEPA 2023ECG-JEPA 2024Laya (EEG) 2026Time-to-eventtarget: hazard per codeCox model (1972)MOTOR 2023TCF (ICML 2026)Each family answers "what must the encoder predict?"; health variants differ mainly in how positives, masks and time are defined.Accent: the latent-prediction family, the most recent to reach physiological signals.
Fig. The five pretraining targets in the self-supervision thread. All start from the same unlabelled data and differ in what the encoder must predict. Each box lists a general-domain ancestor followed by health descendants covered in this chapter.
Worked example · W1 W1's objective is InfoNCE with temperature 0.1, batch 4,096 and positives drawn from the same participant within 24 hours. Its ancestry is CPC (the loss), SimCLR (large in-batch negatives and a projection head) and Apple's 2023 PPG/ECG models (participant-level positives). With 4,096 windows per batch, each anchor is scored against 4,096 candidates (its positive and 4,095 negatives); the InfoNCE bound on mutual information is therefore at most ln 4,096 ≈ 8.32 nats, a ceiling inherited from CPC that explains why W1 uses large batches. The JEPA branch is the main untested alternative for W1: it would remove the dependence on batch size and on the 24-hour positive window, at the cost of a momentum target encoder and a collapse regularizer.

B. Time series: from per-series models to pretrained forecasters. Forecasting is the oldest thread in the chapter and the one with the strongest baselines. It contributes three ideas that health models use directly: sharing one model across many series, cutting series into patch tokens, and evaluating zero-shot against simple statistical methods.

Box–Jenkins ARIMA and exponential smoothing (1970 and earlier). Problem: forecast a single series from its own past. Mechanism: the Box–Jenkins method identifies, fits and checks an ARIMA model (autoregressive terms, differencing, moving-average terms) for each series; exponential smoothing and its state-space form (ETS) weight recent observations more heavily. Result: robust, interpretable baselines that remain hard to beat on short, regular series. Left open: nothing is shared across series, so a new patient with a week of data gets a poorly estimated model. Picked up by: global neural forecasters; and every benchmark in this thread keeps seasonal naive, ETS or ARIMA as reference points.

DeepAR (Salinas et al., 2017). Problem: retailers had thousands of related, short series. Mechanism: one autoregressive recurrent network trained across all series, with series-level scaling, outputs the parameters of a likelihood at each step; forecasts are sampled. Result: related series share statistical strength, and probabilistic forecasts come out of the same model. Picked up by: the "global model" idea that pretrained forecasters take to its limit.

N-BEATS (Oreshkin et al., 2019). Problem: the M4 competition had been won by a hand-crafted statistical–neural hybrid, suggesting pure deep models were not enough. Mechanism: stacks of fully connected blocks, each producing a backcast (removed from the input) and a partial forecast (added to the output). Result: beat a statistical benchmark by about 11% and the M4 hybrid winner by about 3% on M3, M4 and Tourism. Picked up by: confidence that pure deep architectures could compete, which motivated transformer forecasters.

"Are transformers effective?" (Zeng et al., 2022) and PatchTST (Nie et al., 2022). Problem: a wave of long-horizon forecasting transformers claimed large gains. Result: Zeng et al. showed a one-layer linear model beat several of them, a result that made linear and statistical baselines mandatory. PatchTST recovered transformer performance with two changes: split each series into patches of P steps (a sequence of length L becomes L/P tokens, cutting attention cost by about P²) and process each channel independently with shared weights. Picked up by: patch tokenization is now the default in TimesFM, Moirai, MOMENT and in many wearable encoders.

TimesFM (Das et al., 2023). Problem: can one pretrained model forecast any series zero-shot? Mechanism: a decoder-only transformer over input patches of 32 points, predicting output patches of 128 so long horizons need few steps; about 200M parameters, pretrained on roughly 100B time points from Google Trends, Wikipedia pageviews, public datasets and about 3M synthetic series. Result: zero-shot accuracy close to supervised models on Monash, Darts and ETT, improving monotonically from 17M to 200M parameters. Since: the TimesFM repository records TimesFM 2.5 (September 2025: 500M to 200M parameters, 16k context, optional quantile head), restored covariate support (October 2025), a LoRA fine-tuning example (April 2026) and TimesFM 3.0 (August 2026: native multivariate forecasting with past and future covariates, weights under a non-commercial license).

Chronos (Ansari et al., 2024). Problem: how far can an unmodified language model go if numbers become words? Mechanism: mean-scale each series, quantize values into uniform bins over [−15, 15], and train T5 models (about 20M to 710M parameters) with ordinary cross-entropy; forecasts are sampled token sequences. Picked up by: Chronos-Bolt (faster) and Chronos-2 (below), which leave pure language modeling behind.

Lag-Llama and TimeGPT-1 (Rasul et al., 2023; Garza et al., 2023). Lag-Llama builds each token from the current value plus values at fixed lags (one step, one day, one week back) and outputs a parametric distribution; it generalized reasonably zero-shot and became state of the art after fine-tuning on small slices of new data. TimeGPT-1 is an encoder–decoder trained on more than 100B points and offered as a hosted API; it ranked in the top three across frequencies on more than 300,000 series, though its paper notes that comparisons with other foundation models were incomplete. For health data the hosted pattern raises a prior question: whether patient data may leave the institution at all.

Moirai and MOMENT (Woo et al., 2024; Goswami et al., 2024). Problem: real series differ in frequency, number of channels and distribution. Mechanism: Moirai is a masked encoder with several patch sizes chosen by sampling frequency, "any-variate" attention that flattens all channels into one sequence, and a mixture output distribution; it was pretrained on LOTSA (about 27.6B observations, nine domains). MOMENT targets general analysis rather than forecasting: 512-step inputs in 64 patches, about 30% masked, evaluated on forecasting, classification, anomaly detection and imputation, and released with the Time Series Pile. Left open: whether the added flexibility pays for itself. Picked up by: Moirai 2.0 (below) answered "not always".

Time-LLM (Jin et al., 2023) and Toto (Cohen et al., 2024; 2025). Time-LLM reprograms patches into text prototypes for a frozen LLM with a prompt prefix and reported gains over specialized forecasters; such claims need comparison with purpose-built forecasters and simple baselines at equal compute. Toto applies the decoder-only patch design to observability metrics; a 2025 release of a 151M-parameter version came with BOOM, a benchmark of about 350M observations of Datadog telemetry, which shows the recipe transferring to a domain with strong daily and weekly cycles similar to wearable aggregates.

Benchmarks and leakage: GIFT-Eval, fev-bench and Meyer et al. (2024–2025). Problem: zero-shot claims are only meaningful if test series were not in pretraining. Mechanism and result: GIFT-Eval (Aksu et al., 2024) spans 23 datasets, about 144,000 series and 177M points across seven domains and ten frequencies, with a separate pretraining corpus of about 230B points designed not to overlap the test splits. fev-bench (Shchur et al., 2025) has 100 tasks across seven domains, 46 with covariates, and reports win rates and skill scores with bootstrapped confidence intervals. Meyer et al. (2025) argue that much published evaluation suffers from known and unknown information leakage (test series, or series correlated with them, in pretraining), which inflates zero-shot results. Picked up by: health forecasting studies now need patient-level and time-level separation between pretraining and test data, the same discipline as EHR temporal splits.

Chronos-2 and Moirai 2.0 (2025). Problem: univariate zero-shot forecasting ignores the most predictive information in many settings: related series and known future covariates. Mechanism: Chronos-2 (Ansari et al., 2025; 120M parameters) adds a group-attention layer that shares information across related series at each patch position, so one model handles univariate, multivariate and covariate-informed forecasting in context. Moirai 2.0 (Liu et al., 2025) went the other way: a decoder-only model with one patch size, multi-token prediction and a quantile loss, about 30 times smaller than Moirai-Large. Result: Amazon reports Chronos-2 first among pretrained models on GIFT-Eval with the largest gains on covariate tasks in fev-bench (Amazon Science, 2025); Moirai 2.0 beat its larger predecessor on GIFT-Eval, with ablations crediting the decoder-only backbone and quantile decoding. Left open: health-specific covariate benchmarks (medication schedules, meals, activity as covariates for glucose or heart rate).

Health evidence (2025–2026). Direct tests on physiological series are few. Peräkylä et al. (2026) forecast heart rate variability from consumer wearables zero-shot with TimesFM, Chronos-Bolt and Moirai: TimesFM and Chronos beat mean, EWMA and ETS baselines (average MASE about 0.81–0.87 for the foundation models), while Moirai's gain over the mean baseline was not significant. The pattern matches the general lesson of this thread: pretrained forecasters help most when series are regular and history is short, and a statistical baseline must be in every table.

Five steps in the forecasting thread from one model per series to context-aware pretrained forecasters.One model per seriesARIMA, ETS · 1970–fit to each seriesno transferOne global networkDeepAR 2017shared weights acrossrelated seriesPatch tokensPatchTST 2022channel independenceafter Zeng et al. 2022Pretrained zero-shotTimesFM · ChronosMoirai · MOMENT2023–2024Context-awareChronos-2 · Moirai 2.0TimesFM 2.5 / 3.02025–2026many parameters per seriesneeds related seriestokens = L/P patchesleakage risk in benchmarkscovariates, groups, ICLLeft to right: more sharing across series; from box 4 on, the model is trained once and reused without refitting.The wearable test cited in this chapter (heart-rate variability) compares box 4 models with box 1 baselines.
Fig. The forecasting thread. Each step increases how much one model shares across series; the muted line under each box is the cost or caveat that step introduced.
Worked example · W1 W1 is an encoder, not a forecaster, but its resting heart rate head (linear probe MAE 2.4 bpm, an illustrative workload figure) invites a forecasting comparison. The lineage prescribes the test: forecast the next day's resting heart rate per participant with seasonal naive and ETS (box 1 of the figure), with a pretrained zero-shot model (box 4), and with a covariate-aware model given activity as a covariate (box 5), on participants whose data was not in any pretraining set. Because 38% of W1's hours have no PPG, daily aggregates must be computed with explicit gap handling first; a forecaster fed silently imputed zeros would be scored on the imputation, not the physiology.

C. Clinical event modeling: from next visit to simulated futures. Structured EHR data is a sequence of coded events per patient (diagnoses, procedures, medications, lab orders with values, visits), each with a timestamp. It resembles language closely enough that BERT and GPT transferred quickly, but differs in three ways that drive this thread: time between events carries meaning, records are censored when patients leave the system, and chronic codes are re-recorded at visit after visit.

Doctor AI (Choi et al., 2015). Problem: clinical prediction relied on hand-built features for each task. Mechanism: a recurrent network reads a patient's visits as multi-hot code vectors and predicts the diagnosis and medication codes of the next visit and the time until it. Result: it framed the EHR as a multivariate point process over codes and set the agenda of learning from the sequence itself. Left open: the model learns an institution's coding habits along with its medicine, and "next" is poorly defined for sparse, irregular visits. Both problems persist in 2026.

BEHRT and Med-BERT (Li et al., 2019; Rasmy et al., 2020). Mechanism: BERT over codes. BEHRT adds age, position and visit-segment embeddings to each code embedding; Med-BERT pretrains on structured diagnoses with masked-code prediction plus a length-of-stay task. Result: BEHRT, trained on records of nearly 1.6 million people, improved average precision for onset prediction across 301 conditions by 8.0–10.8 points over earlier deep EHR models. Med-BERT, pretrained on 28,490,650 patients, raised AUC by 2.02–7.12% for heart failure in diabetics and pancreatic cancer, and by more than 20% with only 300–500 training samples, matching a training set about ten times larger. Left open: masked encoders cannot generate futures, and position embeddings encode order, not elapsed time.

CEHR-BERT (Pang et al., 2021). Problem: order without spacing. Mechanism: insert artificial time tokens between visits (for example, a token for a gap of a given number of weeks) and add time and age embeddings, so the model sees both sequence and elapsed time. Picked up by: CEHR-GPT, ETHOS and most generative EHR tokenizers, including W2's 64 time-gap tokens.

CLMBR (Steinberg et al., 2020). Problem: are complex objectives needed, or is next-code prediction enough? Mechanism: a clinical language model trained to predict the next day's codes from the history, used as a frozen feature extractor. Result: across five tasks, AUROC improved by 3.5% on average over standard baselines and by 19% when few training records were available. Its transformer successor, CLMBR-T-base (141M parameters, 2.57M Stanford patients), became the reference model released with EHRSHOT. Picked up by: the autoregressive line that leads to CoMET.

Foresight (Kraljevic et al., 2022; Lancet Digital Health, 2024). Mechanism: a GPT over clinical concepts extracted from free-text notes by named-entity recognition and linking, trained on 811,336 patients from King's College Hospital, South London and Maudsley, and MIMIC-III. Result: precision@10 for the next disorder of 0.68–0.88 across sites; clinicians judged the top forecast relevant in 97% of 34 synthetic timelines. Significance: the first widely cited generative timeline model, and a bridge between the clinical-text and structured-event threads.

MOTOR (Steinberg et al., 2023). Problem: next-code prediction ignores censoring and the timing of outcomes, which most clinical questions are about. Mechanism: a 143M-parameter transformer with local causal attention produces a representation at each event; a piecewise exponential head with low-rank task weights predicts the time until each of 8,192 codes next occurs, using the survival likelihood so that censored patients contribute correctly. Pretraining used up to 55M patient records (about 9B events) from EHR and claims. Result: on 19 target tasks, time-dependent C-statistic improved 4.6% over state-of-the-art baselines; time-to-event pretraining beat next-code pretraining by 2.0%; label efficiency improved by up to 95%; the model was more robust to temporal shift and transferred to MIMIC-IV. Picked up by: SleepFM's disease head uses a multi-label Cox loss on frozen PSG embeddings; TCF (2026, below) generalizes multi-horizon timing to a pretraining objective.

EHRSHOT and "shaky foundations" (Wornow et al., 2023; Wornow et al., 2023). Problem: a 2023 review of clinical foundation models found their evaluation foundations "shaky": few shared benchmarks, few released weights. Mechanism: EHRSHOT releases de-identified records of 6,739 Stanford patients (41.6M events, 921,499 encounters) with 15 few-shot tasks in four groups (operational outcomes, lab result anticipation, new diagnoses, chest X-ray findings), evaluated at k ∈ {1, 2, 4, …, 128} labelled examples per class, and releases CLMBR-T-base. Result: the pretrained model beat a count-based gradient-boosting baseline at k ≤ 64, but its advantage shrank as k grew and the baseline won on new-diagnosis tasks above k = 64. Picked up by: k-shot curves became the standard EHR evaluation, and the result fixed the expectation that pretraining matters most when labels are scarce.

CEHR-GPT and ETHOS (Pang et al., 2024; Renc et al., 2024). CEHR-GPT carries CEHR-BERT's time tokens into a GPT that generates synthetic patient timelines while preserving visit timing. ETHOS represents each patient as a tokenized Patient Health Timeline, with value tokens for labs, and predicts future trajectories zero-shot, without labelled data or fine-tuning (npj Digital Medicine, 2024). Significance: both make prediction a matter of simulation: sample many futures from the history and count how often the outcome occurs.

Context Clues (Wornow et al., 2025; arXiv December 2024, ICLR 2025). Problem: EHR models used short contexts inherited from early BERTs. Mechanism: GPT, Llama, Mamba and Hyena models (about 120M parameters each, about 2.5M patients) pretrained at context lengths up to 16k tokens. Result: Mamba at 16k reached the best mean AUROC on 14 EHRSHOT tasks (0.807 vs a prior best of 0.777). Three EHR properties made modeling harder than text: copy-forwarded repetition, irregular time intervals, and perplexity that rises later in a timeline rather than falling.

MEDS and MEDS-Tab (MEDS; MEDS-Tab, 2024). The Medical Event Data Standard represents every dataset as (subject, time, code, value) rows, with tooling for strong tabular baselines and a public MIMIC-IV demo. Its role in the lineage is infrastructural: it lets tokenizers, models and task definitions move between institutions, which the generative models below rely on for external validation.

Delphi-2M (Shmatko et al., 2025). Mechanism: a modified GPT trained on about 0.4M UK Biobank participants to predict the rates of more than 1,000 diseases from a person's history. Result: validated without changes on about 1.9M Danish individuals (Nature, 2025), with accuracy comparable to single-disease models; the model samples synthetic health trajectories up to 20 years ahead. The authors explicitly report biases inherited from the training population. Significance: external validation across national registries without retraining.

Repeated codes (Rajamohan et al., 2025). Problem: a model rewarded for predicting the next code learns to copy chronic diagnoses that are re-recorded at every visit. Result: unless new onsets are distinguished from repeats, metrics are inflated; the authors added a regularizer for repeated events. Picked up by: RAVEN (2026, below), from an overlapping NYU group.

EHR scaling laws (Zhang et al., 2025). Problem: do LLM scaling laws hold for EHR data? Mechanism: Llama-architecture models from under 10M to nearly 1B parameters trained from scratch on MIMIC-IV timelines (267,773 patients; about 267M training tokens, ETHOS tokenization, 2,048-token context), with IsoFLOP sweeps. Result: U-shaped loss curves at fixed compute with clear optima; optimal parameters scale roughly as C0.58 and optimal tokens as C0.44, exponents that differ from those reported for LLMs. Lower validation loss tracked better zero-shot ICU mortality prediction (ROC AUC about 0.68 to 0.75 as loss fell from 1.0 to 0.85). Readmission performance plateaued beyond about 28M parameters, which the authors attribute to data scarcity: larger models would need more than 1010 tokens, two orders of magnitude more than MIMIC-IV provides.

CoMET (Waxler et al., 2025). Problem: what happens when a generative event model is trained at national scale? Mechanism: decoder-only models of 62M to 1B parameters trained on Epic Cosmos: 118M patients, about 115B events and 151B tokens; tasks are answered zero-shot by Monte Carlo simulation of future timelines. Result: across 78 tasks (diagnosis, prognosis, operations), the largest model generally matched or beat task-specific supervised models; scaling followed power laws with a compute-optimal ratio near 1,000 tokens per parameter, far above the tens of tokens per parameter for text; lower pretraining loss predicted downstream performance through a sigmoid-like relationship. Left open: the weights and data are not public; simulation is expensive per query; calibration and subgroup behavior at this scale need independent study.

RAVEN (Gao et al., 2026). Problem: next-token EHR models echo chronic codes and are evaluated without regard to recurrence. Mechanism: a 144M-parameter decoder-only transformer predicts the full set of events at the next visit, conditioned on history and visit timing, with a recurrence-aware regularizer that down-weights repeated events; trained on about 1.29 million NYU Langone patients with a 42,337-token vocabulary. Result: zero-shot 2-year disease forecasting macro AUROC 0.780 across seven conditions, against 0.767 for a fine-tuned BERT and 0.659 for MedGemma-27B; at 5 years the fine-tuned BERT was slightly ahead (0.757 vs 0.752). Platt scaling reduced mean ECE at 2 years from 0.0132 to 0.00085 without changing AUROC. On EHRSHOT, with only about a quarter of its rows mappable to the vocabulary, zero-shot AUROC exceeded supervised baselines trained with up to 128 labels per class for lupus (0.763) and hypertension (0.705). The authors also report that larger models did not help without more data, consistent with the MIMIC-IV scaling result.

Time-Conditioned Foreseeing (Kang et al., ICML 2026). Problem: EHR pretraining borrowed language methods that ignore irregular timing and clinically meaningful value ranges. Mechanism: density-based "pathology-focused" binning that gives finer resolution to clinically significant lab ranges; a dual-calendar rotary position embedding that encodes absolute time and intervals; and an objective that forecasts events across several future horizons. Result (as summarized on the conference page): better than existing foundation models on eleven downstream tasks, with up to 54% AUPRC improvement, on two public hospital datasets. It is the most direct 2026 descendant of CEHR-BERT's time tokens and MOTOR's timing objective; independent replication was not available at the time of writing.

EHR foundation models by objective (rows) and era (columns), 2015 to 2026.2015–20192020–20222023–20242025–2026Masked encoderBEHRT 20191.6M peopleMed-BERT · CEHR-BERT28.5M patientsNext code / visitDoctor AI 2015RNN, next visitCLMBR 2020next code, 141M (-T)Context Clues 202416k context, MambaRAVEN 2026next visit, recurrence-awareGenerate futuresForesight 2022concepts from notesETHOS · CEHR-GPTsimulate timelinesDelphi-2M · CoMET118M patients (CoMET)Time-to-eventMOTOR 20238,192 TTE tasksTCF (ICML 2026)multi-horizon foreseeingBenchmarks, formatsEHRSHOT · MEDSfew-shot k = 1…128EHR scaling lawsMIMIC-IV · CoMETArrows join successive models with the same objective; accent marks 2025–2026 work.
Fig. The EHR thread by objective and era. Masked encoders came first and then stalled as the field moved to autoregressive, generative and time-to-event pretraining; benchmarks and a common event format arrived in 2023–2024.
Worked example · W2 W2 has 310 million events from 2 million patients (mean 155 events per patient; median 96, p95 1,450) and a 120M-parameter decoder. Assuming roughly one token per event plus interleaved time-gap and value tokens, W2 sees on the order of 300–500 million tokens per epoch, or about 2.5–4 tokens per parameter. The two published EHR scaling studies point in the same direction: CoMET's compute-optimal ratio near 1,000 tokens per parameter would suggest a model well under 1M parameters for this data, and the MIMIC-IV study, with a similar 267M-token corpus, saw downstream gains plateau beyond about 28M parameters. Ratios from different tokenizations and multi-epoch schedules are not directly comparable, so this is a hypothesis rather than a conclusion. The lineage-informed test is an IsoFLOP sweep at W2's budget (for example 10M, 30M and 120M parameters at equal compute) evaluated on the temporal holdout (train ≤ 2022, test 2024): if the 30M model matches the 120M model on 1-year mortality AUROC 0.89 and readmission AUROC 0.71, W2 is data-limited, and more patients will help more than more parameters. Rajamohan et al. and RAVEN add a second test: report new-onset and repeated-code performance separately before trusting either number.

D. Sleep and biosignals: from scoring rules to wearable foundation models. This cluster has two roots: sleep medicine, which defined how overnight recordings are divided and labelled, and cardiac and wearable signal processing. They merged in self-supervised models from 2023 onward, and their central technical problems (multiple channels, missing data, device shift) differ from those of language.

Rechtschaffen & Kales and AASM scoring (1968; 2007). Problem: standardize how human experts score polysomnography (PSG), the overnight recording of brain, eye, muscle, cardiac and respiratory signals. Mechanism: the Rechtschaffen & Kales manual (1968) divided the night into 30-second epochs, each assigned one stage by visual rules; the American Academy of Sleep Medicine revised the rules in 2007 (de Chazal et al., 2022, review). Result: a shared label space and an epoch length that every later model inherits. Left open: human scorers disagree, so labels carry an agreement ceiling, and 30 seconds is a convention for human scoring, not a physiological unit. Public cohorts such as SHHS, MESA and MrOS, distributed through the National Sleep Research Resource, made learned models possible.

DeepSleepNet and U-Sleep (Supratak et al., 2017; Perslev et al., 2021). Problem: manual staging is slow and expensive. Mechanism: DeepSleepNet learned staging from a single raw EEG channel with convolutional layers for each epoch and a recurrent layer for context across epochs. U-Sleep trained one fully convolutional model across many cohorts and channel configurations and could output stages at a higher frequency than 30 seconds. Left open: supervised models need scored data and solve one task; they do not produce a general representation of the night.

CLOCS (Kiyasseh et al., 2021). Problem: image-style augmentations are not meaningful for ECG. Mechanism: contrastive learning in which temporally adjacent ECG segments and different leads of the same recording are positives, so invariances come from the structure of the recording. Picked up by: ECG-FM, which combines adjacent-segment contrast with wav2vec-style masking, and the general move to structure-defined positives.

Apple PPG/ECG foundation models (Abbaspourazad et al., 2023). Problem: can self-supervised pretraining on consumer wearable signals produce embeddings with health information? Mechanism: separate PPG and ECG encoders trained on data from about 141K participants of the Apple Heart and Movement Study over about three years; two segments from the same participant form a positive pair, with a stochastic augmentation module, a regularized contrastive loss and a momentum encoder. Result: frozen embeddings encoded demographics and health conditions well enough for simple heads to predict them; PPG was generally the stronger modality (ICLR 2024). Picked up by: distillation to accelerometry (Abbaspourazad et al., 2024: about 20M minutes from about 172K participants; 99.2% top-1 retrieval of the matching PPG embedding; 23–49% better than accelerometer-only encoders on heart rate and HRV) and the behavior model WBM.

LaBraM (Jiang et al., 2024). EEG pretraining with a vector-quantized neural tokenizer and masked code prediction over channel patches, on about 2,500 hours from about 20 datasets (ICLR 2024). It is the VQ-VAE and BERT lines applied to EEG, and the baseline that 2026 JEPA work (Laya) measures against.

SleepFM (Thapa et al., 2024). Problem: learn a general representation of a night of PSG across modalities. Mechanism: separate encoders for brain activity, ECG and respiratory signals, pretrained on more than 100,000 hours from over 14,000 participants with a leave-one-out contrastive objective: each modality's embedding is aligned with the average of the other modalities' embeddings for the same window. Result: leave-one-out beat pairwise contrast; logistic regression on SleepFM embeddings beat an end-to-end CNN on staging (macro AUROC 0.88 vs 0.72) and sleep-disordered breathing (0.85 vs 0.69); cross-modal retrieval reached 48% top-1 among 90,000 candidates (ICML 2024).

PaPaGei (Pillai et al., 2024). Problem: no open PPG foundation model existed, and subject-level positives can discard pulse morphology. Mechanism: pretraining on about 57,000 hours of PPG (about 20M segments from 13,517 subjects in VitalDB, MIMIC-III and MESA); the morphology-aware variant defines positives by bins of a PPG morphology index (sVRI) rather than by subject. Result: evaluated on 20 tasks across 10 datasets with public code and weights (ICLR 2025). Significance: the open baseline for later PPG work.

LSM (Narayanswamy et al., 2024). Problem: how do wearable foundation models scale? Mechanism: a masked-reconstruction vision transformer over multimodal minute-level Fitbit and Pixel Watch data, more than 40M hours from about 165,000 people. Result: performance improved with compute, data and model size with sublinear gains; at fixed total hours, more hours per person mattered more than more people; one model handled imputation, interpolation, forecasting and classification, and few-shot activity recognition beat supervised baselines with 5–10 labelled examples (Google Research, 2024; ICLR 2025).

ECG-FM and Pulse-PPG (2025). ECG-FM (McKeen et al., 2025) is a 90.9M-parameter open transformer pretrained on about 1.4M 12-lead ECG segments with masked span prediction, adjacent-segment contrast and random lead masking, evaluated on ECG interpretation and reduced ejection fraction (JAMIA Open). Pulse-PPG (Saha et al., 2025) pretrained only on raw PPG from a 100-day field study of 120 people and found field pretraining beat a clinically pretrained model on many tasks: noisy free-living data can be a better pretraining source than clean clinical data for free-living deployment.

LSM-2 (Xu et al., 2025). Problem: wearable data is missing most of the time, and imputing before training hides that. Mechanism: Adaptive and Inherited Masking (AIM) treats natural gaps and artificial masks alike: a fixed number of masked tokens is dropped before the encoder for efficiency, the rest (natural gaps included) is hidden by attention masking, and the loss is computed only on artificially masked tokens whose values are known. Result: trained on about 40M hours from more than 60,000 participants, LSM-2 beat LSM-1 on hypertension, anxiety and 20-class activity recognition and degraded less when whole sensors or parts of the day were removed (Google Research, 2025).

WBM (Erturk et al., 2025). Problem: raw sensor models ignore behavior. Mechanism: a foundation model of 27 hourly HealthKit quantities (activity, cardiovascular, vitals, gait, body measurements, fitness) from about 162K people and more than 2.5B hours; each week is a 168 × 27 matrix plus missingness indicators; a dense tokenizer with a bidirectional Mamba-2 encoder won among three tokenizers and three backbones. Result: across 57 tasks it beat a baseline on 39 of 47 static outcomes and all 8 time-varying ones; it beat the PPG model on 18 of 47 static outcomes (beta-blocker use is one example) and was consistently stronger on the time-varying sleep tasks; concatenating WBM and PPG embeddings was best on 42 of 47. The authors note selection bias, self-reported labels and unreleased weights.

Stanford Sleep Bench and OSF/SleepBench (Kjaer et al., 2025; Shuai et al., ICML 2026). Problem: PSG pretraining methods had not been compared on equal terms. Result: Stanford Sleep Bench assembled 17,467 recordings (over 163,000 hours) with 13 disease-prediction tasks plus staging, apnea and age; most self-supervised methods performed similarly on staging, apnea and age, while contrastive learning did noticeably better and converged faster for mortality and disease prediction. OSF built SleepBench (about 166,500 hours from nine public sources) and found that existing models handle missing channels poorly, channel-invariant features matter during pretraining, and sample size, capacity and multi-source diversity all improve results.

SleepFM in Nature Medicine (Thapa et al., 2025 preprint; published January 2026). Problem: move from "what stage is this epoch?" to "what will happen to this person?". Mechanism: about 585,000 hours of PSG from more than 65,000 participants (Stanford Sleep Clinic with 35,052 studies, BioSerenity, MESA, MrOS), with SHHS (6,441 adults) held out; 5-second tokens at 128 Hz, channel-agnostic attention pooling within modality groups, a transformer over 5-minute context; Stanford recordings linked to EHR diagnoses mapped to 1,041 phecodes, with a multi-label Cox head on frozen embeddings. Result: 130 conditions predicted with reasonable accuracy, with C-indices such as 0.84 for all-cause mortality and 0.85 for dementia (Stanford Bio-X, 2026); press coverage of the published paper also lists 0.89 for Parkinson's disease and prostate cancer and 0.81 for heart attack (News-Medical, January 2026). It beat a demographics-only baseline by about 5–17% AUROC depending on disease category. Left open: a sleep-clinic population is sicker than the general public, phecode labels inherit coding noise and differential follow-up, and prognostic signal is not yet clinical utility.

2026 wearable models: MMR, OpenMHC and SensorFM. Masked Multiscale Reconstruction (Thukral et al., 2026) masks coefficients of a wavelet multiresolution decomposition of PPG rather than time-domain patches, so the encoder must combine temporal and spectral scales; pretrained on about 17M 10-second segments from about 32,000 smartwatch users, it matched or improved on open PPG foundation models, time-series foundation models and other self-supervised baselines on 17 of 19 tasks (the abstract gives no per-task effect sizes). OpenMHC (Schuetz et al., 2026) released more than 60M hours from 19 sensor channels with up to 169 linked health and behavior variables for 11,894 My Heart Counts participants, with a benchmark that pits classical methods against wearable and multivariate time-series foundation models on prediction, imputation and forecasting; it is the first large open wearable cohort designed for this purpose. SensorFM (Liu & McDuff, Google Research, July 2026) builds on LSM-2's AIM and scales masked reconstruction to about five million consented participants and over two billion hours of minute-level data (34 features from PPG, accelerometry, electrodermal activity, skin temperature and altimetry), with models from 100K to 100M parameters; the post reports that the largest model reduced reconstruction loss by 31% over the smallest, gained on average 9% AUC on classification and 21% Pearson correlation on regression, and that frozen-encoder linear probes beat a feature-engineered supervised baseline on 34 of 35 tasks in 13,985 participants. These SensorFM figures are taken from the blog post; the accompanying technical report (Narayanswamy, Xu et al., 2026) is an arXiv preprint that had not been peer reviewed at the time of writing.

Sleep and wearable biosignal models by era, with the open transfer from lab PSG to wearables.Rules (1968–2007)Deep learning (2017–21)SSL FMs (2023–24)Scale, gaps (2025)Open, huge (2026)Sleep (PSG)R&K → AASM30-s epochs, 5 stagesDeepSleepNetU-Sleep (many cohorts)SleepFM (ICML)>100k h, LOO contrastSleep BenchSleepBench (OSF)SleepFM (Nat Med)585k h, 130 conditionsWearables, ECG, EEGCLOCSECG contrastiveApple · LSM · LaBraMPaPaGei · ECG-JEPALSM-2 · WBMECG-FM · Pulse-PPGSensorFM · OpenMHCMMR · LayaPSG → wearable transfer (open)Row 1 inherits the 30-second epoch from manual scoring; row 2 inherits participant-level positives and masking from general SSL.The dashed link is a research direction, not a published pipeline.
Fig. The sleep and biosignal thread. Sleep models keep the epoch structure that manual scoring defined; wearable models grew from contrastive ECG work into very large masked-reconstruction models whose central problem is missing data.
Worked example · W1 and W3 W1 (150,000 participants, 30 million participant-hours) has about 200 hours per participant; LSM had about 240 hours per person (40M hours, about 165,000 people) and SensorFM about 400 (two billion hours, five million participants). LSM's finding that, at fixed total hours, more hours per person beat more people suggests that extending W1's follow-up would help more than recruiting additional participants with short records; this is an extrapolation from one study and should be tested by subsampling W1 both ways at equal hours. W1's 38% of hours without PPG is the problem LSM-2's AIM was designed for: masking natural gaps rather than imputing them. W3 (30,000 PSGs, about 240,000 hours, 8 hours per night) is about 41% the size of SleepFM's 585,000-hour corpus and about 1.5 times Stanford Sleep Bench. Its staging κ of 0.78 against single-scorer labels already exceeds the inter-scorer κ of about 0.76, so the R&K/AASM label ceiling, not model capacity, bounds further staging gains; SleepFM's lineage points W3's remaining headroom toward disease prediction (W3's AHI ≥ 15 detection AUROC 0.91) and toward the open PSG-to-wearable transfer, where W3 drops to κ 0.62.

E. Cross-cutting: language models and multimodal integration. Clinical language models are the most mature health foundation models, and by 2025 they had become the interface to the others. Three patterns appear: models over clinical text, LLMs reading serialized sensor data, and joint signal–text embeddings.

Clinical text models. NYUTron (Jiang et al., 2023) pretrained on 4.1B words of inpatient notes from 387,144 NYU Langone patients and was fine-tuned for readmission, in-hospital mortality, comorbidity, length of stay and insurance denial. Med-PaLM (Singhal et al., 2022) introduced the MultiMedQA benchmark for medical question answering (Nature, 2023). For structured data the evidence so far favors dedicated EHR models for prediction and LLMs for explanation and interaction; RAVEN's comparison, where MedGemma-27B reached 0.659 against RAVEN's 0.780 zero-shot macro AUROC, is one 2026 data point.

LLMs over wearable data. Liu et al. (2023) showed that few-shot tuning lets an LLM ground physiological and behavioral time series for cardiac analysis, activity recognition, calorie estimation and mental-health screeners. PH-LLM (Cosentino et al., 2025), a Gemini model fine-tuned for sleep and fitness coaching, scored 79% in sleep medicine and 88% in fitness on multiple-choice exams, above a sample of experts (76% and 71%), performed similarly to experts for fitness on 857 case studies, and predicted self-reported sleep quality through a multimodal encoder-plus-adapter (Nature Medicine, 2025).

Sensor–language models. SensorLM (Zhang et al., 2025) trained on about 59.7M hours from 103,643 people in 127 countries, with automatically generated hierarchical captions (statistics, trends, events) as the paired text, combining a CLIP-style contrastive loss with generative captioning; it classified 20 activities zero-shot and showed scaling with data, model size and compute (NeurIPS 2025). SensorFM's 2026 post describes the encoder grounding a personal health agent, the same encoder-plus-language pattern at larger scale.

Fusion and its limits. Wang et al. (2025) combined All of Us EHRs with Fitbit data for ten conditions: adding wearables improved AUROC for all ten (about 8.9% on average), but CEHR-GPT's advantage over simple OMOP indicators largely disappeared once wearables were added, and hand-engineered wearable statistics beat MOMENT embeddings. A 2026 position paper (Wu et al., 2026) argues that wearable foundation models built as static window encoders suit short, well-defined tasks but not chronic or progressive conditions, and calls for longitudinal multimodal data, long-context personalized modeling and agentic inference. Read together, the two papers mark where the threads have not yet joined: the timeline view of the EHR thread and the window view of the biosignal thread.

Lineage map and reading order

The map below places the main works of the previous section on one timeline, one lane per thread. Reading along a lane shows one idea maturing; reading down a column shows what the field could do in a given year. The axis is compressed before 2012 because the roots (sleep scoring in 1968, ARIMA in 1970, deep autoencoders in 2006) are decades apart while the health-FM era fits into four years.

Six lineages converging on health foundation models, 1968 to 2026.1970199020122014201620182020202220242026scale expands →health-FM erayear of first public release (arXiv or journal); axis compressed before 2012Representationsdeep autoencoderword2vecVQ-VAE"foundation model"Contrastive / latentCPCSimCLRCLIPI-JEPAECG-JEPALayaMasked / AR + scaleGPTBERTscaling lawsMAEChinchillaForecastingBox–JenkinsDeepARN-BEATSPatchTSTTimesFMChronos-2TimesFM 3.0Clinical eventsDoctor AIBEHRTMed-BERTMOTOREHRSHOTCoMETRAVENSleep & biosignalsR&K manualAASMDeepSleepNetU-SleepApple PPGSleepFMLSM-2SensorFM
Fig. Six lineages that converge on health foundation models. Each lane runs from its root idea to a recent descendant; the shaded band marks the health-FM era (2023 onward). Years are first public release (arXiv or journal); the axis is compressed before 2012. Extended with Chinchilla and 2024–2026 entries (ECG-JEPA, Laya, TimesFM 3.0, RAVEN, LSM-2, SensorFM).

Four cross-lane links. Some of the most important connections run between lanes and are easier to state than to draw without crossing lines.

  1. InfoNCE runs from the contrastive lane into both health lanes. CPC's loss is the objective of Apple's PPG/ECG models, SleepFM and SensorLM, and survival losses are structurally similar: the Cox partial likelihood is a softmax over the patients still at risk at each event time, which is why SleepFM's disease head and MOTOR's pretraining look alike once written down.
  2. Masked reconstruction runs from the masked lane into wearables. MAE's high-mask-ratio recipe became LSM, whose missing-data problem produced AIM in LSM-2, which SensorFM inherits. In this lineage the objective doubles as the imputation method.
  3. Patch tokens run from forecasting into the biosignal lane. PatchTST's patches and channel independence underlie most wearable encoders; conversely, wearable data is now a test domain for forecasters (Peräkylä et al., 2026).
  4. Scaling laws run from language into EHR and wearables, with different constants. CoMET's compute-optimal ratio near 1,000 tokens per parameter, the MIMIC-IV IsoFLOP exponents (about 0.58 for parameters, 0.44 for tokens) and LSM's "hours per person beat more people" all depart from the text constants; the shared lesson is that health models are data-limited sooner than language models.
EraWhat a health model could doRepresentative workMain limitation of the era
Rules (1968–2012)Experts scored epochs by manual; forecasters fit one model per seriesR&K, AASM; Box–Jenkins, ETSNo learning across patients or series
Supervised deep (2015–2021)Predict one task end to end from raw codes or signalsDoctor AI, DeepSleepNet, U-Sleep, DeepAROne model per task; labels required
Pretrain-then-adapt (2019–2022)Reuse a pretrained encoder; gains largest with few labelsBEHRT, Med-BERT, CLMBR, CLOCSSmall cohorts; order without elapsed time
Health foundation models (2023–2024)One encoder for many tasks; zero-shot forecasting; time-to-event pretrainingApple PPG/ECG, LSM, SleepFM, MOTOR, EHRSHOT, TimesFM, ChronosWeak benchmarks; missingness handled ad hoc
Scale and simulation (2025–2026)Simulate patient futures; predict disease from one night; billions of wearable hours; covariate-aware forecastingCoMET, Delphi-2M, RAVEN, SleepFM (Nature Medicine), LSM-2, SensorFM, Chronos-2Closed weights and data; data-limited scaling; unproven clinical utility

Table. Capability by era. Each era's limitation is the problem that the next era's representative works addressed.

From lineage to design. The three reference workloads are not new designs; each decision in them is inherited. The figure below names, for each workload, the ancestor that supplies its cohort design, tokenization, objective and evaluation protocol, and the failure mode that ancestor documented. The last column is the most useful one in practice: every ancestor that reported a result also reported, or later work exposed, a specific way the result could mislead.

For each reference workload, the ancestor that supplies its data design, tokens, objective, evaluation and main known risk.Data / cohortTokensObjectiveEvaluationKnown riskW1Apple AHMS · LSMconsented wearable cohort10-s windowsPatchTST-style patchesInfoNCE, same personCPC → Apple 2023Linear probeSimCLR / PaPaGei protocolMissingness 38%LSM-2 AIMW2Cosmos · UK BiobankCoMET · Delphi-2MCodes + time + decilesCEHR-BERT · ETHOSNext tokenCLMBR → CoMETk-shot, temporal splitEHRSHOT · MOTORRepeated codesRajamohan 2025W3NSRR cohortsSHHS, MESA, MrOS30-s epochs, 5 groupsR&K → AASMLOO contrastiveSleepFM 2024κ vs scorer, C-indexSleep BenchClinic populationSleepFM caveatBox titles are W1–W3 design choices; muted lines name the published ancestor. Accent: the risk each ancestor documented.
Fig. Inheritance map for the three reference workloads. Each design decision in W1 (wearable PPG), W2 (generative EHR) and W3 (sleep PSG) traces to a specific prior work; the last column is the failure mode that ancestor reported.
Worked example · W1, W2, W3 Reading the figure row by row gives one validation test per workload, each taken from the ancestor's documented risk. W1: remove whole sensors and parts of the day at evaluation time, as LSM-2 did, and check that AFib AUROC (0.93 in W1, against 0.88 for the supervised-from-scratch model) degrades less than the supervised model's; a larger drop would mean the 38% missingness was absorbed as a shortcut rather than modeled. W2: split 1-year mortality and other onset tasks into new-onset and repeated-code cases, following Rajamohan et al.; if AUROC 0.89 falls sharply on new onsets, the model is copying, not forecasting. W3: report disease-prediction C-indices separately for sleep-clinic and community cohorts (SHHS-style), since SleepFM's caveat is a sicker clinic population; a C-index that holds in the community cohort supports generalization, one that drops toward the demographics-only baseline weakens it.

Reading orders. The lineage is long, and few readers need all of it. The table gives a minimal path for five goals, in the order the papers should be read; each path starts from a root that explains the mechanism and ends at the work closest to the 2026 frontier. Chapter numbers point to where this book treats each mechanism at four levels.

GoalReading path (in order)Book chapters
Build a wearable encoder (W1)CPC → SimCLR → Wang & Isola → Apple PPG/ECG (2023) → LSM → LSM-2 → WBM → PaPaGei (open baseline) → SensorFM → OpenMHC (benchmark)4, 5, 7
Build a generative EHR model (W2)Doctor AI → BEHRT → CEHR-BERT → CLMBR → EHRSHOT → MOTOR → ETHOS → Context Clues → Rajamohan et al. → EHR scaling laws (MIMIC-IV) → CoMET → RAVEN5, 9, 11
Build a sleep model (W3)R&K/AASM review → DeepSleepNet → U-Sleep → CLIP → SleepFM (2024) → Stanford Sleep Bench → OSF/SleepBench → SleepFM (Nature Medicine, 2026)3, 4, 8
Use a pretrained forecaster on health seriesBox–Jenkins/ETS → DeepAR → Zeng et al. → PatchTST → TimesFM → Chronos → GIFT-Eval → Meyer et al. → Chronos-2 → Peräkylä et al.6
Evaluate any health FMBengio et al. (probing goal) → Wornow et al. ("shaky foundations") → EHRSHOT → Meyer et al. (leakage) → fev-bench → Stanford Sleep Bench → Wang et al. (fusion baselines) → OpenMHC6, 11

Table. Minimal reading paths. Entries are the works described in the previous section; links are there.

What the lineage leaves open. Each thread ends at a problem that its most recent work names but does not solve. These are the questions later chapters return to.

Open problemThreadClosest workWhat would count as progress
Data-limited scaling outside the largest systemsEHR, wearablesEHR scaling laws (MIMIC-IV); RAVEN; CoMETCompute-optimal recipes for corpora of 108–109 tokens, validated on temporal holdouts
Missing and heterogeneous channelsBiosignals, sleepLSM-2 AIM; OSF/SleepBenchGraceful degradation under sensor removal, reported as standard
Lab-to-wearable transferSleep, biosignalsApple PPG→accelerometer distillation; SleepFMA PSG-trained teacher improving wearable-only staging and risk prediction
Leakage-free zero-shot claimsForecasting, EHRGIFT-Eval; Meyer et al.; EHRSHOTBenchmarks with documented separation by patient, site and time
Longitudinal, timeline-level wearable modelsWearables, EHRWu et al. (2026) position; WBM; Wang et al. (2025)Models over months of wearable data that add value beyond EHR indicators
Open weights and cohortsAllPaPaGei, ECG-FM, OpenMHC, CLMBR-T-baseReleased models within reach of closed results on shared benchmarks

Table. Open problems at the end of each thread, with the work closest to solving each and a concrete criterion for progress.

Caveats on this map. Dates are first public release, so a paper may appear a year or more before its journal version (SleepFM's disease-prediction work was a 2025 preprint and a January 2026 journal paper; Foresight was a 2022 preprint and a 2024 journal paper). Several 2026 entries rest on thin evidence: SensorFM on a research blog post and an arXiv preprint that had not been peer reviewed, TCF on a conference abstract page, and some SleepFM C-indices on press coverage of the published paper. Lineage links not stated by the authors (for example, reading TCF as a descendant of CEHR-BERT and MOTOR, or RAVEN as a response to Rajamohan et al., which shares authors) are interpretation. Results quoted here are as reported by their authors; the benchmark entries in each thread exist because several of those results did not survive stricter evaluation.

A Taxonomy of Health Data

Health data is not one modality but at least six, and they differ from each other in sampling rate, structure and missingness more than images differ from text. A modality here means a kind of recording with its own physics and its own way of being stored: coded events in an electronic health record (EHR), free-text clinical notes, high-rate waveforms such as the electrocardiogram (ECG), the photoplethysmogram (PPG) and the electroencephalogram (EEG), the overnight multichannel sleep study called polysomnography (PSG), minute- or hour-level summaries from consumer wearables, and medical images. Each modality calls for a different tokenizer (the step that turns raw data into the units a model reads) and a different notion of what counts as "similar", so the first design decision for a health foundation model is which of these it consumes.

The earlier generation of clinical machine learning sidestepped this choice. A team picked one outcome, extracted a few dozen hand-made features from whichever data were at hand, and fitted one supervised model. That works for a single task, but every new task restarts feature engineering, and the features rarely transfer between hospitals or devices. A foundation model instead learns a general representation from large amounts of unlabelled data, which only pays off if the input is described faithfully: timestamps that mean what they say, values with consistent units, gaps that are marked as gaps rather than filled with zeros.

Two axes organize the taxonomy. The first is time scale: the interval between samples (2 ms for a hospital ECG, a day or more between clinic visits) and the span one person's record covers (ten seconds for an ECG strip, decades for an EHR). The figure below places the modalities on these axes. The second is structure: dense and regular (waveforms), sparse and irregular (events), unstructured (text) or spatial (images). The table lists, for each modality, what it demands of a model and how it is usually pretrained.

Health data modalities placed by sampling interval and per-patient observation span.1 ms1 s1 min1 h1 day1 mo1 yr10 yrtime scale (log): from interval between samples (circle) to span of one record (square)ECG (12-lead, Holter)EEG / polysomnographyPPG (smartwatch)AccelerometryWearable aggregatesEHR codes and eventsClinical notesImaging (snapshots)
Fig. Health modalities by time scale. Each bar runs from the typical interval between samples (circle) to the typical span of one patient's record (square), on a log axis. Ranges are approximate and illustrative, not measurements. High-rate waveforms come in short windows; EHR events are sparse but span decades; wearables cover about nine orders of magnitude.
ModalityStructureWhat it demandsTypical pretrainingExamples
EHR codes and eventsIrregular sequence of discrete codes (diagnoses, drugs, labs) with timestamps and valuesTime-aware tokens, huge vocabularies, censoring, long contextsMasked codes; next code; time-to-event; next visitBEHRT, Med-BERT, CLMBR, MOTOR, CEHR-GPT, CoMET
Clinical textFree-text notes, reportsDomain vocabulary, negation, de-identification, copied textMasked or causal LMNYUTron, Med-PaLM
Waveforms (ECG, PPG, EEG)Dense, 64–500+ Hz, one to dozens of channelsPatching, channel handling, noise and artifact robustnessContrastive; masked reconstruction; wav2vec-styleApple PPG/ECG, PaPaGei, ECG-FM, LaBraM
PolysomnographyOvernight multichannel recording (EEG, EOG, EMG, ECG, respiratory)Variable channel sets across clinics, 30-s epochs, cross-modal structureCross-modal contrastiveSleepFM, OSF
Wearable time seriesMinute- or hour-level aggregates (steps, HR, HRV, sleep) over monthsHeavy missingness, device heterogeneity, behavior vs physiologyMasked autoencoding; contrastiveLSM, LSM-2, WBM
Medical imaging2D/3D imagesResolution, 3D context, report alignmentMAE; image–report contrastiveRETFound, Merlin (treated briefly here)

Table. Health data modalities and what each demands of a foundation model. Imaging is listed for completeness; this book focuses on sequences.

The three reference workloads used throughout the book sit at different points of this map. W1 is a wearable PPG model (64 Hz signals, 10-second windows), W2 a generative EHR model (sparse coded events over years), and W3 a sleep model (eight-hour PSG nights cut into 30-second epochs). Compared with a single-task pipeline, a modality-aware design costs more up front, because each data source needs its own cleaning and tokenization, but the cost is paid once and every later task reuses it. The sections that follow take the six modalities in turn, from the most language-like (EHR codes and text) through the dense signals to imaging, and the next chapter builds the self-supervised objectives on top of them.

A compact way to compare modalities is to describe each as a stochastic process observed at a set of times. For one person, a modality \(m\) yields observations \(\{(t_i, x_i)\}_{i=1}^{n_m}\), where \(t_i\) is a timestamp and \(x_i\) is the observed value: a vector of channel amplitudes for a waveform, a code (and possibly a number) for an EHR event, a string for a note. Three quantities summarize the shape of the data.

Sampling interval. For a regularly sampled signal with rate \(f_s\) (samples per second), the interval is \(\Delta = 1/f_s\). For irregular events the interval is a random variable \(\Delta_i = t_{i+1} - t_i\) whose distribution is wide and heavy-tailed. Span. \(T = t_{n} - t_1\), the time one record covers. Count. For a regular signal, \(n = T f_s\) per channel; with \(C\) channels the record holds \(nC\) numbers. The ratio \(T/\Delta\) spans many orders of magnitude across modalities, which is why a log axis is needed to place all modalities on one chart.

A model consumes fixed-size units, so each modality is cut into windows of length \(w\) seconds (signals) or into a token budget of \(L\) tokens (events). The number of model inputs a corpus yields is

\[ N_{\text{units}} = \frac{H \cdot 3600}{w}, \qquad \text{samples per unit} = f_s\, w, \]

where \(H\) is the total number of recorded hours. For events, the relevant quantity is the token count per patient, \(\ell = n_{\text{events}} \cdot \bar\tau\), where \(\bar\tau\) is the mean number of tokens one event expands into (a code alone, or a code plus a time-gap token and a value token).

Worked example · W1, W2, W3

W1. \(f_s = 64\) Hz and \(w = 10\) s give \(64 \times 10 = 640\) samples per window. With \(H = 30\) million participant-hours, \(N = 30\times10^6 \times 3600 / 10 = 1.08\times10^{10}\), the 10.8 billion windows of the reference sheet; sampling 1% per epoch gives 108 million windows per training epoch. Since 38% of hours carry no PPG, about \(0.62 \times 10.8 \approx 6.7\) billion windows contain signal.

W2. 310 million events over 2 million patients is a mean of 155 events per patient, against a median of 96 and a 95th percentile of 1,450: the distribution is right-skewed, so the mean overstates the typical patient. At about two tokens per event, the p95 patient needs roughly 2,900 tokens, inside the 4,096-token context; the longest records do not fit.

W3. 240,000 hours of PSG in 30-s epochs is \(240{,}000 \times 120 = 28.8\) million epochs, from 30,000 nights of 8 hours each.

The same arithmetic exposes the main trade-off. A shorter window or a finer time-gap vocabulary preserves detail but multiplies the number of units and the sequence length; a coarser one is cheaper but discards the fine structure (beat morphology, the timing of a repeated lab) that may carry the signal. The sections below derive these quantities for each modality.

A data layer that serves several modalities needs a small, explicit description of each one, so that window counts, storage and vocabulary sizes are computed rather than guessed. The sketch below distinguishes the two families that cover almost all of this book: dense signals (a rate, a channel count, a window length) and sparse events (patients, events and a vocabulary). It checks the reference-sheet numbers for W1, W2 and W3, including the W1 channel count of four (one PPG channel and three accelerometer axes) that the storage estimate depends on.

from dataclasses import dataclass

@dataclass(frozen=True)
class SignalSpec:
    """A dense, regularly sampled modality (waveform or sensor stream)."""
    name: str
    rate_hz: float        # samples per second per channel
    channels: int         # physical channels stored
    unit_s: float         # length of one model input (window or epoch), seconds
    hours: float          # total recorded hours in the corpus

    def samples_per_unit(self) -> int:
        return round(self.rate_hz * self.unit_s)

    def units(self) -> float:
        return self.hours * 3600 / self.unit_s

    def raw_bytes(self, bytes_per_sample: int = 2) -> float:
        return self.hours * 3600 * self.rate_hz * self.channels * bytes_per_sample

@dataclass(frozen=True)
class EventSpec:
    """A sparse, irregular modality (coded clinical events)."""
    name: str
    patients: int
    events: int
    vocab_codes: int
    gap_tokens: int
    value_tokens: int

    def vocab(self) -> int:
        return self.vocab_codes + self.gap_tokens + self.value_tokens

# W1: 64 Hz, 10-s windows, 30 M participant-hours, 4 channels (1 PPG + 3 accelerometer axes).
w1 = SignalSpec("W1 PPG+accel", rate_hz=64, channels=4, unit_s=10, hours=30e6)
# W3: 30-s epochs over 240,000 hours of PSG. Rate and channels are PLACEHOLDERS
# (they vary by clinic); only the epoch count is used.
w3 = SignalSpec("W3 PSG", rate_hz=256, channels=1, unit_s=30, hours=240_000)
w2 = EventSpec("W2 EHR", patients=2_000_000, events=310_000_000,
               vocab_codes=42_000, gap_tokens=64, value_tokens=10)

assert w1.samples_per_unit() == 640
assert abs(w1.units() - 10.8e9) < 1e3            # 10.8 billion windows
assert abs(w3.units() - 28.8e6) < 1               # 28.8 million epochs
assert w2.vocab() == 42_074
print(f"W1 windows {w1.units()/1e9:.1f} B, per epoch (1%) {0.01*w1.units()/1e6:.0f} M, "
      f"raw 16-bit storage {w1.raw_bytes()/1e12:.1f} TB")
print(f"W1 windows with PPG (62% of hours) {0.62*w1.units()/1e9:.2f} B")
print(f"W3 epochs {w3.units()/1e6:.1f} M, hours per study {w3.hours/30_000:.0f}")
print(f"W2 mean events/patient {w2.events/w2.patients:.0f} (median 96, p95 1,450), vocab {w2.vocab():,}")

Output:

W1 windows 10.8 B, per epoch (1%) 108 M, raw 16-bit storage 55.3 TB
W1 windows with PPG (62% of hours) 6.70 B
W3 epochs 28.8 M, hours per study 8
W2 mean events/patient 155 (median 96, p95 1,450), vocab 42,074

The assertions tie the code to the reference workloads: 640 samples per W1 window, 10.8 billion windows, 28.8 million W3 epochs and a W2 vocabulary of 42,074 tokens (42,000 codes, 64 time-gap tokens, 10 value-decile tokens). The storage figure, 55.3 TB at 16 bits per sample, counts all four channels over the full 30-million-hour grid; since 38% of that grid carries no PPG, the stored signal is closer to 34 TB if empty hours are not written.

Shapes. Signals become arrays of shape (windows, samples, channels); events become per-patient lists of tokens of variable length. Keeping both behind one record type keyed by subject identifier makes patient-level splitting, covered in each section below, a single operation rather than one per modality.

Debugging tip. When a window count disagrees with expectations by a round factor (2, 4, 1,000), check the sampling rate recorded in the file header against the device specification and the unit of the time column (seconds versus milliseconds); both errors are common and silent.

Problem. A program that trains models on several modalities usually starts with one ingestion script per source. Each script encodes its own idea of time zones, units, missing values and patient identity, and each produces its own train/test split. Models trained from these outputs cannot be compared or combined, and errors in one script stay invisible.

Why it matters. Most failures of health foundation models trace back to the data layer, not the architecture: a split that lets one person appear in train and test, a lab value whose unit changed mid-study, a timestamp shifted by hours. These errors inflate offline metrics and surface only after deployment.

Root cause. The modalities differ in structure, so each team builds a bespoke path. What they share is a small common core: every observation belongs to a subject, happens at a time and has a code or a channel and a value.

Ingestion pipeline: four source systems feed one canonical store, then quality gates, patient-level splits and tokenized shards.EHR tablesOMOP, FHIR, vendorClinical notestext + note metadataWaveforms, PSGWFDB, EDF filesWearablesraw streams, aggregatesCanonical storeevents: subject,time, code, valuesignals: subject,start, rate, channelsQuality gatesschema, units,clock, SQISplitspatient-level+ temporalShardstokens,windowsSplits are assigned before tokenization,so no patient crosses train and test.
Fig. A modality-agnostic ingestion pipeline. Every source is converted into one of two canonical forms (timestamped events or timestamped signal segments) keyed by subject; quality gates and split assignment run once on the canonical store, before any tokenizer, so all models trained from it share the same splits.

Remedy. Convert every source into one of two canonical forms: timestamped events (subject, time, code, value), as in the Medical Event Data Standard (MEDS), or timestamped signal segments (subject, start time, rate, channel list, file pointer). Run quality gates and split assignment once, on the canonical store, before any modality-specific tokenizer. MEDS illustrates the design: its schema has required subject_id, time and code columns, optional numeric and text values, a null time for static facts, and a separate split file with the sentinel names train, tuning and held_out.

Worked incident · W1, W2

A team links W1 wearable embeddings to W2 EHR outcomes for 5,000 participants. The wearable pipeline split participants by a hash of the device identifier; the EHR pipeline split by medical record number. About 6% of participants had two devices, so some of them landed in the training split of one pipeline and the test split of the other, and the combined model's 1-year mortality AUROC rose by an implausible margin on the test set. Diagnosis: a join of the two split tables on the person identifier counted subjects present in both train and test. Remedy: a single person-level split table, assigned in the canonical store and read by every pipeline. Cost: one re-run of every downstream evaluation. Validation: the overlap count must be zero, and the test AUROC should fall back toward the single-modality numbers; a result that stays high after the fix would point to a different leak. The 6% figure is illustrative.

Capacity. In the reference workloads, W1 raw storage at 16 bits is about 55 TB for four channels over the full hour grid (about 34 TB for the 62% of hours that carry PPG), W2 is about 310 million event rows (around 620 million tokens at two tokens per event), and W3 is 28.8 million epochs. The dominating cost is the signal store; the event store is small, but its correctness determines the labels.

Trade-off. A canonical store adds a conversion step and forces agreement on identifiers and time conventions across teams. The return is that splits, audits and leakage checks are written once. The test that supports the design: two independently trained models (for example W1 and W2) can be joined on subjects with no train/test overlap and no unit or time-zone mismatches on a sampled audit of linked records.

EHR codes and events

Structured EHR data is a sequence of coded events per patient: diagnoses (ICD-10 codes), procedures, medications, laboratory orders with their results, and visits, each with a timestamp. A code is an entry from a controlled vocabulary maintained outside the hospital, such as ICD-10 for diagnoses, LOINC for laboratory tests or RxNorm for drugs, so the same concept carries the same identifier across sites that use the same system. An event is one recorded fact: this code, for this patient, at this time, sometimes with a value (a creatinine of 1.4 mg/dL) or a unit.

The record is produced as a by-product of care and billing, in a fixed order. A patient arrives and a visit is opened. Clinicians order tests and drugs; the orders, and later the results, are written with times. At discharge, coders assign diagnosis and procedure codes for reimbursement, often time-stamped at the end of the stay even though the condition was present at admission. Each step reflects a decision as well as the patient's state: a test appears because someone suspected a problem. The record therefore describes the care process as much as the disease, and a model learns both.

Such a sequence is closer to language than to signals, which is why BERT- and GPT-style models transferred so easily: codes play the role of words and a patient's history plays the role of a document. It differs from language in three ways that matter. Time between tokens carries meaning: a lab repeated after an hour is a different situation from one repeated after a year, while word order in a sentence has no such clock. Records are censored: a patient leaves the health system and the outcome is never seen, so absence of a death record is not evidence of survival. Repetition is common: chronic diagnoses are copied forward visit after visit. Wornow et al. (2025) measured three such properties (copy-forwarded diagnoses that repeat tokens, irregular time intervals between events, and disease progression that makes later events harder to predict) and found that higher levels of each were associated with worse model performance, while longer-context models were more robust to them. They also noted that most EHR foundation models of the time used context windows under 1,000 tokens, while full records can run to tens of thousands of events.

One patient timeline from the W2 example: coded events with timestamps become a token sequence with time-gap and value tokens, and the record ends in censoring.Coded events (MEDS-style rows: subject, time, code, value)Day 0, 09:00ED visit[VISIT//ED]Day 0, 09:40diagnosis I48.91(atrial fibrillation)[GAP_14][ICD10//I48.91]Day 0, 10:05lab HbA1cvalue 7.9 %[GAP_12][LAB//HbA1c][Q10]Day 1, 08:00drug apixaban[GAP_27][RX//apixaban]Day 330inpatient admission[GAP_50][VISIT//IP]Tokens fed to the sequence model (shaded boxes above)observed record (median 96 events, p95 1,450 in W2)after last contact: censoredoutcome not observedlast observed event
Fig. From events to tokens (W2, illustrative patient). Each event is a timestamped code with an optional value. Tokenization adds one of 64 log-spaced time-gap tokens between events and a per-lab decile token after a numeric value (here the top decile, Q10); a static token such as sex precedes the sequence. The record stops at the last contact; whatever happens afterwards is unobserved (censored), not absent.
Worked example · W2

W2 is a decoder-only model trained on 2 million patients and 310 million events. Its vocabulary has 42,000 codes, 64 time-gap tokens and 10 value-decile tokens, 42,074 in all. A median patient has 96 events and a patient at the 95th percentile has 1,450. The patient in the figure above arrives in the emergency department, is diagnosed with atrial fibrillation, has an HbA1c of 7.9% (top decile, token Q10), starts apixaban the next day and is admitted again 330 days later. Each event becomes one code token, preceded by a gap token when time has passed, and the lab adds a value token. For 1-year mortality (AUROC 0.89 in the reference sheet), a patient last seen eight months after the prediction time is neither a death nor a survivor; the label is unknown.

Data sources. Public research data comes mostly from MIMIC-IV (Johnson et al. 2023), the UK Biobank, and institutional datasets released under data use agreements. MIMIC-IV covers patients admitted to the emergency department or intensive care unit of one Boston hospital between 2008 and 2022: per its PhysioNet page, 364,627 individuals, 546,028 hospitalizations and 94,458 ICU stays. Its dates are shifted into the future by one random offset per patient, so intervals inside a patient are exact but calendar dates across patients are not comparable, a detail that matters for temporal splits.

Compared with tabular features, the earlier approach of summarizing a record into counts (number of admissions, last creatinine), the event sequence keeps order and timing and lets a model discover which patterns matter. The cost is a huge, site-specific vocabulary and sequences whose lengths vary by more than an order of magnitude. Coding practice also differs by site and changes over time (United States hospitals switched from ICD-9 to ICD-10 in 2015, so MIMIC-IV contains both), so the same disease can look different in two records. A useful mental model: an EHR is a log written by the health system about its own actions on a patient, with gaps whenever the patient is elsewhere. The next section turns to the free text that accompanies these codes and records the reasoning the codes leave out.

Write one patient's record as a sequence \(\mathcal{R} = \big((t_1, c_1, v_1), \dots, (t_n, c_n, v_n)\big)\) sorted by time, where \(t_i\) is a timestamp, \(c_i \in \mathcal{V}\) is a code from vocabulary \(\mathcal{V}\), and \(v_i\) is an optional value (a number, or empty). Three modelling problems follow from this form: encoding the gaps \(\Delta_i = t_{i+1} - t_i\), encoding the values \(v_i\), and defining labels when follow-up ends.

Time-gap tokens. Gaps range from seconds to decades, so equal-width bins waste resolution. Log-spaced bins give equal relative resolution at every scale. With \(K\) bins from \(g_{\min}\) to \(g_{\max}\), the ratio between consecutive edges is

\[ r = \left(\frac{g_{\max}}{g_{\min}}\right)^{1/(K-1)}, \qquad k(\Delta) = \min\!\left(K-1,\ \left\lfloor \frac{\ln(\Delta/g_{\min})}{\ln r} \right\rfloor\right), \]

and a gap below \(g_{\min}\) produces no token. Each bin covers a gap range that is a fixed multiple \(r\) wider than the previous one, so the relative error of the time information is bounded by roughly \(r - 1\).

Value tokens. For a lab code \(c\), let \(q_{c,j}\) be the \(j\)-th decile of its values in the training data. A value maps to token \(Q_{j+1}\) where \(j = \#\{j' : q_{c,j'} \le v\}\). Using per-code deciles makes the tokens unit-free inside one code (an HbA1c in the top decile is "high" whatever the unit) but they must be fitted on training patients only, or test values shape the bins.

Censoring. Let \(D\) be the time of death (or of any outcome) and \(C\) the time of last contact. Only \(\min(D, C)\) and the indicator \(\delta = \mathbf{1}[D \le C]\) are observed. A binary label at horizon \(h\) from prediction time \(t_0\) is defined only when it is determined:

\[ y = \begin{cases} 1 & t_0 < D \le t_0 + h \\ 0 & D > t_0 + h \text{ and } C \ge t_0 + h \\ \text{undefined} & C < t_0 + h,\ D \text{ not observed.} \end{cases} \]

Treating "undefined" as 0 labels unobserved deaths as survivors and biases the model toward patients who leave the system. Excluding them avoids that error but discards information and can shift the population; survival losses, used by time-to-event pretraining later in the book, use the partial follow-up directly.

Worked example · W2

W2 has \(K = 64\) gap tokens. Taking \(g_{\min} = 1\) minute and \(g_{\max} = 20\) years (10,519,200 minutes), \(\ln r = \ln(10{,}519{,}200)/63 = 16.169/63 = 0.2567\), so \(r = 1.293\): each bin is 29% wider than the last. A 40-minute gap gives \(\lfloor \ln 40 / 0.2567 \rfloor = \lfloor 3.689/0.2567 \rfloor = \lfloor 14.37 \rfloor = 14\), token GAP_14; a 328-day gap (472,320 minutes) gives \(\lfloor 13.065/0.2567 \rfloor = 50\), GAP_50. The bin edges are a design choice, not part of the reference sheet.

For censoring, consider an assumed cohort of 100,000 patients at prediction time with 3,000 deaths observed within a year and 15,000 patients who leave before a year has passed. If those who leave had the same 3% annual risk and were observed on average for half the year, roughly \(15{,}000 \times 0.03 \times 0.5 \approx 225\) deaths fall in the unobserved half-years. Labelling all 15,000 as survivors records those 225 deaths as negatives, about 7% of the 3,225 true positives; excluding the 15,000 avoids the mislabels. These counts are illustrative.

Sequence length. With \(\bar\tau\) tokens per event, a patient with \(n\) events needs \(\ell = n\bar\tau\) tokens. The illustrative W2 patient (an emergency visit, a diagnosis, a lab, a drug and a readmission) has five events and ten event tokens (\(\bar\tau = 2.0\)) plus one static token. At \(\bar\tau = 2\), the W2 median patient needs about 192 tokens and the p95 patient about 2,900, both within the 4,096-token context; patients beyond about 2,048 events must be truncated, usually keeping the most recent events. The trade-off is direct: more gap bins and value tokens raise \(\bar\tau\), which improves time and value resolution and shortens the history that fits in the context.

The code below implements the three operations from the event representation: sorting events and placing static facts first, inserting log-spaced gap tokens and per-lab decile tokens, and building a censoring-aware 1-year label. Input rows follow the MEDS layout (MEDS schema): subject_id, time (null for static facts such as sex), code, and an optional numeric_value. The decile edges are given as constants here; in practice they are computed from training patients only.

import bisect, math
from datetime import datetime, timedelta

# MEDS-style rows: (subject_id, time, code, numeric_value). time=None marks static data.
rows = [
    (7, None, "GENDER//F", None),
    (7, datetime(2023, 3, 1, 9, 0), "VISIT//ED", None),
    (7, datetime(2023, 3, 1, 9, 40), "ICD10//I48.91", None),
    (7, datetime(2023, 3, 1, 10, 5), "LAB//HbA1c", 7.9),
    (7, datetime(2023, 3, 2, 8, 0), "RX//apixaban", None),
    (7, datetime(2024, 1, 25, 14, 0), "VISIT//IP", None),
]

# 64 time-gap bins, log-spaced from 1 minute to 20 years (gaps under 1 min get no token).
G_MIN, G_MAX, N_GAP = 1.0, 20 * 365.25 * 24 * 60, 64
RATIO = (G_MAX / G_MIN) ** (1 / (N_GAP - 1))

def gap_token(minutes: float) -> str | None:
    if minutes < G_MIN:
        return None
    k = min(N_GAP - 1, int(math.log(minutes / G_MIN) / math.log(RATIO)))
    return f"GAP_{k:02d}"

# Per-lab decile edges, fitted on TRAINING patients only (9 inner cut points).
LAB_EDGES = {"LAB//HbA1c": [5.0, 5.2, 5.4, 5.6, 5.8, 6.1, 6.5, 7.0, 7.8]}

def value_token(code: str, v: float) -> str:
    return f"Q{bisect.bisect_right(LAB_EDGES[code], v) + 1}"   # Q1..Q10

def tokenize(rows):
    static = [c for _, t, c, _ in rows if t is None]
    events = sorted((r for r in rows if r[1] is not None), key=lambda r: r[1])
    out, prev = list(static), None
    for _, t, code, v in events:
        if prev is not None:
            g = gap_token((t - prev).total_seconds() / 60)
            if g: out.append(g)
        out.append(code)
        if v is not None:
            out.append(value_token(code, v))
        prev = t
    return out

def one_year_mortality(t0, death_time, last_seen):
    """1 / 0 label, or None when the patient is censored before the horizon."""
    horizon = t0 + timedelta(days=365)
    if death_time is not None and t0 < death_time <= horizon:
        return 1
    if last_seen >= horizon:
        return 0
    return None   # left the system early: outcome unknown, exclude (or use a survival loss)

toks = tokenize(rows)
print(toks)
assert toks[0] == "GENDER//F" and toks[-1] == "VISIT//IP"
assert "Q10" in toks                       # 7.9 % is above the 9th edge (7.8)
print("gap 40 min ->", gap_token(40), "| gap 328 days ->", gap_token(328 * 24 * 60))
assert gap_token(0.5) is None and gap_token(G_MAX * 2) == "GAP_63"
t0 = datetime(2023, 3, 2)
assert one_year_mortality(t0, None, datetime(2024, 1, 25)) is None   # seen < 1 year: censored
assert one_year_mortality(t0, None, datetime(2024, 6, 1)) == 0
assert one_year_mortality(t0, datetime(2023, 9, 1), datetime(2023, 9, 1)) == 1
print("tokens per event:", round((len(toks) - 1) / 5, 2))

Output:

['GENDER//F', 'VISIT//ED', 'GAP_14', 'ICD10//I48.91', 'GAP_12', 'LAB//HbA1c', 'Q10', 'GAP_27', 'RX//apixaban', 'GAP_50', 'VISIT//IP']
gap 40 min -> GAP_14 | gap 328 days -> GAP_50
tokens per event: 2.0

The token list reads: the static GENDER//F token first, then each event, with GAP_14 (40 minutes), GAP_12 (25 minutes), GAP_27 (21 hours 55 minutes) and GAP_50 (328 days) between events, and Q10 after the HbA1c of 7.9%. The three label assertions cover the cases of the censoring definition: a patient seen for less than a year without death has no label, one seen beyond a year is a negative, and a death inside the horizon is a positive.

Shapes and data flow. Input: an unordered list of rows for one subject. Output: a list of string tokens of variable length (here 11 for 5 events plus one static fact), later mapped to integer ids through a vocabulary table of 42,074 entries in W2. Labels are produced per (subject, prediction time) pair, separately from the token stream, so that the model never sees events after the prediction time.

Correctness checks worth keeping in the test suite. (1) Every event time is non-decreasing after sorting. (2) No token is derived from data after the prediction time: assert max(event_time) <= t0 for the input of every labelled example. (3) The decile edges are fitted on training subjects only: store the list of subject ids used to fit them and assert it is disjoint from the test split. (4) Every code in the data appears in the code metadata table; MEDS requires this of its codes.parquet file.

Debugging tips. If GAP_00 dominates the token counts, many events share near-identical timestamps (for example, all orders of a visit written at the same second); grouping events at the same time into one step and skipping the gap token inside a group shortens sequences. If one value token dominates a lab, the edges were fitted on mixed units (mg/dL and mmol/L for the same code); normalize units before fitting deciles. If the share of undefined labels is high, check that death records from outside the hospital (state registries, where linked) are joined before labels are built.

Problem. An EHR model that looks strong on a random split often loses much of its edge on later data or at another hospital. W2 reports 30-day readmission AUROC 0.71 and 1-year mortality AUROC 0.89 on a patient-level split plus a temporal holdout (trained on data up to 2022, tested on 2024). Holding such numbers in production depends on the event stream being stable and free of information from the future.

Why it matters. EHR events are written by people and billing systems whose habits change. A model that learned "code X appears" also learned "this hospital used code X in 2021", and a change in coding, unit or timestamp convention shifts the input distribution without any change in patients.

Root causes, by frequency in practice. (1) Timestamp semantics: diagnoses coded at discharge but stored with the admission time make the future visible at admission. (2) Vocabulary drift: code-system transitions (ICD-9 to ICD-10), local codes added or retired, new lab assays. (3) Unit and reference changes for labs. (4) Repetition: copied-forward codes lengthen sequences without new information, pushing older informative events out of a fixed context. (5) Censoring handled as negative labels.

Worked incident · W2

During development, a readmission model built on W2 embeddings reaches AUROC 0.80 on the random patient-level split, well above the 0.71 reference. Diagnosis. A feature-time audit takes 1,000 labelled examples and, for each, lists the tokens whose source rows were recorded (not dated) after the prediction time. 18% of examples contain discharge diagnosis codes that the source system time-stamps at admission. Ablating those codes returns AUROC to 0.72. Remedy. Re-time billing diagnoses to the discharge timestamp in the canonical store, keep only diagnoses with a documented "present on admission" flag at their original time, and rebuild the tokens. Cost. Re-tokenizing 310 million events and re-running pretraining evaluation. Validation. The audit must find no post-prediction-time tokens; AUROC on the 2024 temporal holdout should agree with the patient-level split to within its confidence interval. A remaining large gap between the two splits would indicate drift rather than leakage. All incident numbers are illustrative.

Observability. The checks below run on every refresh of the event store, before tokenization. Thresholds are illustrative starting points to be tuned per site.

MetricWhat it detectsExample alert rule
Out-of-vocabulary code rate per monthNew local codes, code-system transitionsAbove 0.5% of events, or doubling month over month
Per-lab unit mix and value quantilesUnit changes, new assaysA lab's median moves by more than 3 training IQRs
Share of events with date-only timestampsCoarse timing that collapses orderingAny increase over the trailing three months
Recorded-time minus event-time distributionBack-dated entries (future leakage risk)p99 lag exceeds the prediction horizon
Truncation rate at the context limitRepetition and growing historiesMore than 5% of patients exceed 4,096 tokens
Share of undefined labels per taskCensoring, broken outcome linkageChange of more than 2 points between refreshes

Table. Data-quality metrics for an EHR event store. Each one maps to a root cause above.

Choosing among remedies for long, repetitive records. Three options exist. Deduplication (dropping a chronic code repeated within the same visit or within a fixed window) shortens sequences cheaply but removes the signal that a condition is still being treated. Truncation to the most recent tokens keeps the current state but forgets old events such as a past cancer. Longer context keeps everything at higher compute cost; Wornow et al. (2025) found that longer contexts improved prediction and that a Mamba-based model beat the prior state of the art on 9 of 14 EHRSHOT tasks. In W2, the p95 patient (1,450 events, about 2,900 tokens) fits in 4,096 tokens, so the decision affects only the tail: measure truncation rate first, and if it is under a few percent, truncation is the cheapest choice. The test that settles it is to compare task AUROC on the truncated subgroup against the rest; a gap that closes with deduplication favors deduplication.

Standards as a remedy for site variation. Converting each site into a common schema reduces engineering cost but does not harmonize coding behavior. Jeanselme et al. (2025) standardized records of about 6.7 million patients from one academic center (through OMOP, then converted to MEDS), together with MIMIC-IV, to benchmark six EHR foundation models on 14 clinically defined tasks under a fixed patient split, an example of the payoff: comparisons that do not depend on each team's private preprocessing. The next section covers the free text that sits beside these codes.

Clinical text

Clinical text is the free-text part of the record: admission and progress notes, discharge summaries, radiology and pathology reports, nursing notes, letters. Notes and reports carry the reasoning that codes leave out: why a drug was stopped, what the clinician suspected but did not confirm, what the patient said about their symptoms, which findings were explicitly absent. A diagnosis code says that atrial fibrillation was billed; the note says that it was found incidentally, that the patient declined anticoagulation, and why.

Before language models, this text reached prediction models through hand-written rules and extractors that turned phrases into binary features ("mentions sepsis"). Those systems needed per-concept engineering and broke on abbreviations, misspellings and phrasing such as "no evidence of". A language model pretrained on a health system's own notes learns the local vocabulary, abbreviations and templates directly. Jiang et al. (2023) trained NYUTron on NYU Langone's notes and fine-tuned it for 30-day readmission, in-hospital mortality, length of stay and insurance denial, showing that one language model can serve as a general prediction engine for a health system. According to NVIDIA's account of the project, pretraining used more than 4 billion words of notes from about 400,000 patients over ten years, and the readmission model has been applied to more than 50,000 discharged patients in the health system.

The path from a written note to a model input has several steps, each of which can change what the model learns (figure below). De-identification replaces names, dates, record numbers and other identifiers with placeholders, because a model can memorize and later reproduce what it was trained on. Copy removal deals with text carried forward from earlier notes: Steinkamp et al. (2022) analyzed more than 104 million notes for nearly 2 million patients at Penn Medicine and found that 50.1% of all text was duplicated from earlier notes, rising from 33% in 2015 to 54.2% in 2020. Section and negation handling decides which mentions are findings: "denies chest pain" mentions chest pain but asserts its absence. Tokenization then splits the text into subword units for a masked or causal language model.

Clinical text preparation: raw notes pass through de-identification, removal of copied-forward text, section and negation handling, then tokenization.Raw notesprogress, discharge,radiology, nursingDe-identifyreplace names, dates,IDs with tagsRemove copiesdrop text repeatedfrom earlier notesSections, negation"denies chest pain"is not a findingTokenize, modelsubword tokens;masked or causal LMAt Penn Medicine, about half of all note text was duplicated from earlier notes (Steinkamp et al. 2022).Duplicated text inflates token counts and lets copied sentences leak across a prediction cut-off.
Fig. Preparing clinical text. De-identification and copy removal happen before any model sees the text; negation and section handling decide which mentions count as findings. The order matters: duplicates should be removed per patient in time order, so that only the first appearance of a passage is kept.
Worked example · W2 with notes (assumed extension)

Suppose the 2 million W2 patients also had their notes available, and the duplication rate matched the Penn Medicine measurement of about 50%. A language model trained on the raw notes would spend half its tokens on repeated passages. In a two-note example, a progress note that copies the emergency-department history of present illness keeps only "today rate controlled, no bleeding" as new text; 43% of all words across the two notes are duplicates. The W2 reference model itself is code-only; this extension is illustrative.

Compared with codes, text is richer and closer to how clinicians think, and it is where general large language models such as Med-PaLM (Singhal et al. 2023) are strongest. The cost is noise and risk: copied passages, templates, abbreviations, negation and uncertainty ("cannot rule out"), identifiers that must be removed, and timing that is less precise than for coded events, since a note may be signed hours after the encounter it describes. Text is also the natural interface between health foundation models and people: a later chapter on multimodal models and LLM integration uses language as the bridge to signals and events. The mental model: notes are the clinician's narrative of the same timeline the codes record, written partly by copying the previous chapter of that narrative. The next section moves from these language-like modalities to dense physiological waveforms.

Three quantities govern how clinical text behaves as training data: how much of it is new, how often a mention means presence, and when it became available.

Duplication. For a patient with notes \(d_1, \dots, d_m\) in time order, split each into words and let \(S_n(d)\) be the set of its \(n\)-word windows (shingles). A word of \(d_j\) is a duplicate if it lies inside a shingle that occurs in some earlier note \(d_{j'}\), \(j' < j\). The duplicate fraction is

\[ \rho = \frac{\sum_j \#\{\text{duplicate words in } d_j\}}{\sum_j |d_j|}. \]

Removing duplicates shrinks the corpus to \((1-\rho)\) of its size. The window length \(n\) sets the trade-off: small \(n\) flags common phrases ("no acute distress") as copies, large \(n\) misses lightly edited copies.

Hashing. Shingles are compared through 64-bit hashes. For \(N\) distinct shingles, the expected number of colliding pairs is about \(N^2 / (2 \cdot 2^{64})\). At \(N = 10^{10}\), that is \(10^{20} / (3.69 \times 10^{19}) \approx 2.7\) collisions in the whole corpus, negligible against billions of true duplicates. Hashing per patient rather than globally keeps \(N\) far smaller.

Negation and precision. If a fraction \(\nu\) of mentions of a finding are negated or hypothetical, a feature that treats any mention as presence has precision at most \(1 - \nu\) even with perfect recall. A negation rule with sensitivity \(s\) (share of negated mentions it catches) and false-trigger rate \(f\) (share of affirmed mentions it wrongly negates) gives presence precision

\[ P = \frac{(1-\nu)(1-f)}{(1-\nu)(1-f) + \nu (1-s)}. \]

Timing. A note has an encounter time \(t_e\) and a sign time \(t_s \ge t_e\), sometimes followed by addenda. For a prediction at time \(t_0\), only notes with \(t_s \le t_0\) were available; using \(t_e\) instead admits text written after \(t_0\).

Worked example · text statistics

Duplication. With the Penn Medicine figure \(\rho = 0.501\), deduplication keeps 49.9% of tokens. For a two-note example in which a progress note copies the emergency-department history (\(n = 8\)), 20 of 47 words are duplicates, \(\rho = 0.43\).

Negation. Assume half of all chest-pain mentions in a corpus are negated (\(\nu = 0.5\)), a common pattern for symptoms asked about routinely. Without negation handling, presence precision is 0.50. A rule with \(s = 0.9\) and \(f = 0.05\) gives \(P = (0.5 \times 0.95)/(0.5 \times 0.95 + 0.5 \times 0.1) = 0.475/0.525 = 0.905\). The values of \(\nu\), \(s\) and \(f\) are assumptions for illustration.

Language-model pretraining on the deduplicated text minimizes the usual objective (masked-token cross-entropy, or next-token cross-entropy \(-\sum_k \log p_\theta(w_k \mid w_{<k})\)). Duplicates distort it twice: repeated passages are weighted more heavily than their information warrants, and, if notes of one patient fall in both training and evaluation data, the evaluation loss rewards memorization. Splitting by patient, and deduplicating within each patient in time order, addresses both.

The code implements two preprocessing steps for one patient's notes. drop_copied hashes every 8-word window (shingle) and, walking through the notes in time order, removes words covered by a shingle already seen in an earlier note, so only the first appearance of a passage is kept. mentions is a deliberately minimal negation rule in the spirit of trigger-based systems: a term counts as negated when a trigger word ("no", "denies", "without", "negative for", "ruled out") precedes it in the same sentence. De-identification is assumed to have happened upstream.

import re, hashlib

def shingles(text: str, n: int = 8):
    """Hashes of every n-word window (lower-cased, punctuation stripped)."""
    w = re.findall(r"[a-z0-9.%]+", text.lower())
    return [hashlib.blake2b(" ".join(w[i:i+n]).encode(), digest_size=8).digest()
            for i in range(max(0, len(w) - n + 1))], w

def drop_copied(notes, n: int = 8):
    """notes: list of (time, text) for ONE patient. Keep only words not covered by an
    n-gram already seen in an earlier note. Returns new texts and the duplicate fraction."""
    seen, out, total, dup = set(), [], 0, 0
    for t, text in sorted(notes):
        hs, words = shingles(text, n)
        covered = [False] * len(words)
        for i, h in enumerate(hs):
            if h in seen:
                for j in range(i, i + n): covered[j] = True
        out.append((t, " ".join(w for w, c in zip(words, covered) if not c)))
        total += len(words); dup += sum(covered)
        seen.update(hs)
    return out, dup / max(total, 1)

NEG = re.compile(r"\b(no|denies|without|negative for|ruled out)\b")
def mentions(text: str, term: str):
    """Very small NegEx-style rule: a term is negated if a trigger occurs earlier
    in the same sentence. Real systems use curated trigger lists and scope rules."""
    res = []
    for sent in re.split(r"[.;]\s*", text.lower()):
        k = sent.find(term)
        if k >= 0:
            res.append((term, "negated" if NEG.search(sent[:k]) else "affirmed"))
    return res

hpi = ("70 year old woman with new atrial fibrillation started on apixaban "
       "denies chest pain reports palpitations for two weeks")
notes = [(1, "ED note. " + hpi + "."),
         (2, "Progress note. " + hpi + ". today rate controlled, no bleeding.")]
clean, frac = drop_copied(notes)
print(f"duplicate fraction {frac:.2f}")
print("note 2 kept:", clean[1][1])
assert "rate controlled" in clean[1][1] and "palpitations" not in clean[1][1]
print(mentions(notes[1][1], "chest pain"), mentions(notes[1][1], "palpitations"))
assert mentions(hpi, "chest pain")[0][1] == "negated"
assert mentions(hpi, "palpitations")[0][1] == "negated"   # known limitation: scope runs to sentence end

Output:

duplicate fraction 0.43
note 2 kept: progress today rate controlled no bleeding.
[('chest pain', 'negated')] [('palpitations', 'negated')]

The second note keeps only its new content. The duplicate fraction across both notes is 0.43 (20 of 47 words). The last assertion documents a known failure of simple negation rules: "denies chest pain reports palpitations" negates palpitations too, because the scope of "denies" runs to the end of the sentence. Production rule sets add scope terminators (here, "reports" or a clause boundary) and are validated against annotated sentences.

Shapes. Input: a list of (time, text) pairs for one patient. Output: the same list with copied words removed, plus one scalar duplicate fraction. Memory grows with the number of distinct shingles per patient, typically thousands to hundreds of thousands, so the step parallelizes trivially across patients.

Tests to keep. (1) Idempotence: running drop_copied twice changes nothing the second time. (2) Order dependence is intended: reversing the note order must keep the passage in the earlier note, so assert that the earliest note of each patient is unchanged. (3) A synthetic note containing a known fake name and date must come out of the de-identification step with both replaced; run this canary on every release of the de-identification model.

Debugging tips. If the duplicate fraction is near 1.0 for a note type, check whether a template header ("Patient seen and examined...") is counted as copied; strip known templates first so that they do not dominate. If it is near 0 for progress notes, check that notes are sorted by sign time and grouped by the correct patient identifier, since a per-encounter identifier would hide copying across encounters.

Problem. A clinical language model has three production risks that codes do not: it can reproduce identifiers from its training data, it can learn from text that was written after the moment it is supposed to predict, and its training signal is dominated by copied and templated text.

Why it matters. A leaked identifier is a privacy breach regardless of model accuracy. Future text produces evaluation numbers that cannot be reproduced at prediction time. Duplication wastes roughly half the compute at the rates measured by Steinkamp et al. (2022), and it lets the same sentence appear in training and test notes of one patient.

Root causes. De-identification models are imperfect and degrade on unusual formats (names in signatures, identifiers in tables). Note timestamps are ambiguous: encounter time, creation time, sign time and addendum time differ, and many extracts keep only one. Copying is a documentation habit encouraged by the editing tools.

Worked incident · notes for readmission

A readmission model fine-tuned on discharge summaries (as in the NYUTron task set) scores AUROC 0.84 offline but 0.74 when run on summaries at the moment of discharge. Diagnosis. The training extract stamped each summary with the discharge time, but 30% of summaries were signed one to three days later, and 4% had addenda written after a readmission had already occurred ("patient returned to ED on..."). A search for readmission phrases in training-set summaries, split by whether an addendum existed, shows those phrases almost only in addended notes. Remedy. Use the sign time of the original note, drop addenda written after the prediction time, and rebuild the training set. Cost. Fewer training notes for patients with late signatures, and an extract that must carry sign and addendum times. Validation. Offline AUROC on the rebuilt set should approach the at-discharge number; a remaining gap larger than the confidence interval suggests other future text, such as follow-up letters. All numbers are illustrative.

Remedies and their trade-offs.

RiskRemedyCostValidation
Residual identifiersAutomated de-identification plus surrogate replacement (realistic fake names and shifted dates, so missed identifiers hide among fakes)Some clinical terms are wrongly removed; dates lose calendar meaningManual audit of a random sample of notes per release, with a target of zero residual direct identifiers; canary strings inserted before training and probed after
Future textIndex notes by sign time; exclude addenda after the prediction timeRequires sign and addendum timestamps in the extractOffline and at-prediction-time AUROC agree within confidence intervals
DuplicationPer-patient shingle deduplication in time orderDrops the signal that a problem is still being documentedPretraining loss on a deduplicated validation set improves per compute unit; downstream task AUROC unchanged or better
Note-type shiftStratify training and evaluation by note type and departmentSmaller strata, wider intervalsPer-type metrics reported; no type falls far below the pooled metric

Table. Production risks of clinical text and how to check each remedy.

Scale. At the NYUTron scale of more than 4 billion words, 50% duplication means about 2 billion words that add little new information. Deduplication at that scale is a per-patient map job, and its cost is negligible next to pretraining. The privacy audit does not scale the same way, because it needs human reviewers: a fixed sample per release (for example, a few hundred notes stratified by note type) gives a bound on the residual rate rather than a guarantee.

Connection. Text and codes describe the same encounters, so they can be checked against each other: a diagnosis code with no supporting mention in any note of the stay is a candidate coding error, and a strongly asserted finding with no code is a candidate omission. The next section turns to waveforms, where the data are produced by sensors rather than people and the dominant problems are noise and identity rather than copying and timing.

Waveforms: ECG, PPG, EEG

Biosignal waveforms are dense, quasi-periodic signals sampled tens to hundreds of times per second. An electrocardiogram (ECG) measures the heart's electrical activity through electrodes on the skin. An optical photoplethysmogram (PPG), the green light on the back of a smartwatch, measures changes in blood volume under the skin with each heartbeat. An electroencephalogram (EEG) measures cortical electrical activity through scalp electrodes. "Quasi-periodic" means the signal repeats approximately: one ECG complex or one PPG pulse per heartbeat, with shape and spacing that vary slightly from beat to beat. That variation carries information (heart-rate variability, arrhythmias), so the model must see individual beats, not just averages.

A waveform reaches a model in a fixed sequence. A sensor samples voltage or light intensity at a fixed rate; the device filters and stores the samples, sometimes compressed or downsampled; a pipeline cuts the stream into windows of fixed length (10 seconds in W1); a quality check decides whether a window is usable; and the model reads each window as a short multichannel array. Hospital ECGs are usually 10-second, 12-lead recordings at a few hundred hertz. The MIMIC-IV-ECG release on PhysioNet holds about 800,000 such diagnostic ECGs from nearly 160,000 patients, each 10 seconds at 500 Hz, and the PTB-XL dataset holds 21,799 12-lead records from 18,869 patients with cardiologist statements. Watch PPG, by contrast, comes as long, intermittent streams from one or a few optical channels.

Three seconds of synthetic ECG, PPG and EEG, with the PPG strip showing a motion-artifact segment.ECGelectrical activity250-500 Hz typical12 leads or 1 leadPPGoptical blood volume25-64+ Hz on watches1 to a few channelsEEGcortical activity100-500 Hz typicalfew to dozens of channelstime: 3 s shown (synthetic signals). Dashed box: motion artifact on the PPG strip.
Fig. Biosignal waveforms (synthetic, for shape only). ECG has sharp QRS complexes, PPG a smooth pulse per heartbeat, EEG a broadband oscillation. Sampling rates and channel counts are typical ranges, not specifications. A wrist movement (dashed box) can swamp the PPG pulse entirely.

All three waveforms share three challenges. Noise: motion artifacts and poor skin contact can swamp the physiological signal, as the dashed box in the figure shows. In a study of 41 adults wearing a PPG smartwatch in everyday life, Merschel and Reinhardt (2022) found that on average 71.5% of one-minute segments were analyzable, above 94% at night but only about 55–60% during the day, with analyzability falling as activity rose. Channel heterogeneity: a 12-lead hospital ECG and a single-lead watch ECG measure the same heart from different angles, and EEG montages differ between labs; LaBraM (Jiang et al. 2024) handles differing electrode sets by cutting EEG into per-channel patches, pretraining on about 2,500 hours from around 20 datasets. Subject identity leakage: a person's waveform is a fingerprint that a model can memorize instead of learning physiology. If windows from the same person appear in both training and test data, a model can score well by recognizing the person.

Worked example · W1

W1 records PPG and accelerometry at 64 Hz from 150,000 participants and cuts the stream into 10-second windows of 640 samples. A resting heart rate of 72 beats per minute puts 12 pulses in each window, about 53 samples apart. The accelerometer is stored alongside so that windows recorded during wrist motion can be detected and down-weighted. The pretraining objective (InfoNCE contrastive learning) treats two windows of the same participant within 24 hours as a positive pair, which deliberately uses identity as a training signal; for evaluation, the 5,000 labelled participants of the linear probe must therefore be split by participant, so that no test participant has windows among those used to fit the probe. With that split, AFib detection reaches AUROC 0.93 against 0.88 for a model trained from scratch.

Compared with EHR events, waveforms are produced by physics rather than by people, so they are free of coding habits, but they are high volume and noisy, and each window covers seconds, not years. Open foundation models now exist for each signal type: PaPaGei for PPG (Pillai et al. 2025, pretrained on more than 57,000 hours and 20 million segments from 10 datasets), ECG-FM for ECG (McKeen et al. 2025) and LaBraM for EEG, alongside Apple's large-scale PPG and ECG models (Abbaspourazad et al. 2024). The cost of working at the waveform level is storage and compute, plus a quality-control step that discards a large share of daytime wearable data. The mental model: a waveform is a short, repeated physiological shape seen through a noisy and device-specific lens. The next section combines many waveforms into one overnight recording, the polysomnogram.

A single-channel waveform sampled at rate \(f_s\) is a sequence \(x[k] = x(k/f_s)\), \(k = 0, 1, \dots\). Three relations from signal processing set the design choices.

Sampling rate. The Nyquist criterion requires \(f_s > 2 f_{\max}\) to represent frequencies up to \(f_{\max}\) without aliasing. A PPG pulse's useful content lies mostly below about 10 Hz, so 64 Hz suffices for pulse shape and timing; ECG QRS complexes contain energy at tens of hertz, which is why diagnostic ECGs use several hundred hertz. A window of length \(w\) seconds holds \(f_s w\) samples per channel.

Periodicity. For a pulse at heart rate \(h\) beats per minute, the period in samples is \(P = 60 f_s / h\). The normalized autocorrelation

\[ R[\tau] = \frac{\sum_k \tilde x[k]\,\tilde x[k+\tau]}{\sum_k \tilde x[k]^2}, \qquad \tilde x = x - \bar x, \]

peaks near \(\tau = P\). The height of that peak, searched over lags corresponding to plausible heart rates, is a simple signal quality index (SQI): close to 1 for a clean periodic pulse, near 0 for noise. For a plausible band of 36–210 bpm (0.6–3.5 Hz), the lag range is \(\tau \in [f_s/3.5,\ f_s/0.6]\).

Identity leakage. Let a test window come from person \(p\). If training contains other windows of \(p\), a model can predict \(p\)'s label by matching the window to \(p\)'s training windows. For a person-level label \(y_p\) (such as a diagnosis), a nearest-neighbour classifier then reaches accuracy close to \(\Pr[\text{nearest training window belongs to } p]\), regardless of whether the signal contains any information about \(y_p\). Under a subject-wise split this probability is zero, and accuracy reflects only information that generalizes across people.

Window-wise versus subject-wise splitting: in the window-wise split the same participants appear in train and test.Window-wise split (leaks identity)Subject-wise split (no shared people)P1P1P2P2P3P3P4P4training windowtest windowevery test person is unseen in training
Fig. Two ways to split windows from four participants. Left: windows are split at random, so every test window has sibling windows from the same person in training and a model can score well by recognizing the person. Right: whole participants are held out, which measures generalization to new people.
Worked example · W1

Samples. \(f_s = 64\) Hz, \(w = 10\) s: 640 samples per window. At 72 bpm, \(P = 60 \times 64/72 = 53.3\) samples, 12 pulses per window. The search band 0.6–3.5 Hz maps to lags \(\lfloor 64/3.5 \rfloor = 18\) to \(\lfloor 64/0.6 \rfloor = 106\) samples.

Leakage. In a small simulation, 200 synthetic participants each have a random binary label that is unrelated to their signal, and each window is the participant's fingerprint plus noise. A nearest-neighbour classifier reaches accuracy 1.000 on a window-wise split and 0.520 on a subject-wise split, which is chance. Real data show the same effect: Brookshire et al. (2024) report EEG Alzheimer's classification at 99.8% test accuracy with a segment-based holdout split and 53.0% with a subject-based one, and found that only 17 of 63 reviewed deep-learning EEG studies (27%) clearly avoided subject-level leakage.

Channels. A recording with \(C\) channels is an array \(X \in \mathbb{R}^{C \times f_s w}\). When \(C\) and the channel meaning vary between devices (12 leads versus 1; different EEG montages), a model either fixes a canonical channel set and masks absent channels, or treats each channel as a separate sequence of patches with a learned channel embedding, as LaBraM does. The first is simpler but discards extra channels; the second handles any montage at the cost of \(C\) times longer sequences.

The code implements the three operations a waveform pipeline needs before any model: cutting a stream into fixed windows, scoring each window's quality, and assigning whole participants to splits. The SQI combines two signals: the autocorrelation peak in the heart-rate lag band (computed with an FFT for speed), and accelerometer energy, which marks windows recorded during motion as unusable. The motion threshold is an assumed value; in practice it is tuned against labelled clean and corrupted windows. A second part reproduces the identity-leakage effect on synthetic data.

import numpy as np, hashlib
FS, WIN = 64, 640                     # W1: 64 Hz, 10-s windows

def windows(x: np.ndarray, win: int = WIN) -> np.ndarray:
    """(T,) or (T, C) signal -> (N, win[, C]) non-overlapping windows; tail dropped."""
    n = len(x) // win
    return x[: n * win].reshape(n, win, *x.shape[1:])

def sqi(ppg_w: np.ndarray, acc_w: np.ndarray, hr_band=(0.6, 3.5)) -> np.ndarray:
    """Per-window quality in [0,1]: height of the autocorrelation peak inside the plausible
    heart-rate band, zeroed when accelerometer energy says the wrist is moving."""
    x = ppg_w - ppg_w.mean(1, keepdims=True)
    f = np.fft.rfft(x, n=2 * WIN, axis=1)
    ac = np.fft.irfft(f * np.conj(f), axis=1)[:, :WIN]
    ac = ac / np.maximum(ac[:, :1], 1e-9)
    lo, hi = int(FS / hr_band[1]), int(FS / hr_band[0])     # lags 18..106 samples
    peak = ac[:, lo:hi].max(1)
    moving = acc_w.std(axis=(1, 2)) > 0.15                   # g units, ASSUMED threshold
    return np.where(moving, 0.0, np.clip(peak, 0, 1))

def split_of(pid: str, test_frac=0.2) -> str:
    """Deterministic subject-level split: a person's every window lands in one split."""
    h = int(hashlib.sha256(pid.encode()).hexdigest(), 16) % 1000
    return "test" if h < test_frac * 1000 else "train"

# --- synthetic check: 60 s of clean pulse at 72 bpm, then 30 s of wrist motion -----
rng = np.random.default_rng(0)
t = np.arange(90 * FS) / FS
ppg = np.sin(2 * np.pi * 1.2 * t) + 0.05 * rng.standard_normal(t.size)
acc = 0.02 * rng.standard_normal((t.size, 3))
ppg[60 * FS:] += 1.5 * rng.standard_normal(30 * FS); acc[60 * FS:] += 0.5 * rng.standard_normal((30 * FS, 3))
P, A = windows(ppg), windows(acc)
q = sqi(P, A)
print("windows", P.shape, A.shape, "SQI", np.round(q, 2))
assert P.shape == (9, 640) and A.shape == (9, 640, 3)
assert (q[:6] > 0.8).all() and (q[6:] == 0).all()

# --- identity leakage demo: participant-level labels, windows carry a fingerprint ---
n_p, per, d = 200, 20, 16
finger = rng.standard_normal((n_p, d)); label = rng.integers(0, 2, n_p)   # label unrelated to physiology
X = np.repeat(finger, per, 0) + 0.3 * rng.standard_normal((n_p * per, d)); y = np.repeat(label, per)
pid = np.repeat(np.arange(n_p), per)
def nn_acc(tr, te):
    D = ((X[te, None, :] - X[None, tr, :]) ** 2).sum(-1)
    return (y[tr][D.argmin(1)] == y[te]).mean()
idx = rng.permutation(len(y)); cut = int(0.8 * len(y))
window_wise = nn_acc(idx[:cut], idx[cut:])
is_test = np.array([split_of(f"p{p}") == "test" for p in pid])
subject_wise = nn_acc(np.where(~is_test)[0], np.where(is_test)[0])
print(f"1-NN accuracy, window-wise split {window_wise:.3f}, subject-wise split {subject_wise:.3f}")
assert window_wise > 0.95 and abs(subject_wise - 0.5) < 0.1
assert not set(pid[is_test]) & set(pid[~is_test])

Output:

windows (9, 640) (9, 640, 3) SQI [0.91 0.91 0.91 0.91 0.91 0.91 0.   0.   0.  ]
1-NN accuracy, window-wise split 1.000, subject-wise split 0.520

The first six windows (clean pulse at 72 bpm) score 0.91 and the last three (motion) score 0. In the leakage demonstration the labels carry no physiological information at all, yet the window-wise split reports perfect accuracy; the subject-wise split reports chance. The final assertion confirms that no participant appears in both splits.

Shapes. windows maps a (T,) or (T, C) array to (N, 640) or (N, 640, C). sqi takes (N, 640) PPG and (N, 640, 3) accelerometer windows and returns (N,) scores. split_of maps a participant id to a split name deterministically, so a participant's windows land in the same split on every machine and every rerun, with no shared state.

Why hash-based splits. A split table is the alternative and is preferable when splits must be stratified (by age, device or site). Hashing is useful at ingestion time, when windows stream in and no table exists yet; its limitation is that the test fraction is only approximately 20% and cannot be stratified.

Debugging tips. If the SQI is high for almost every window, check that the mean is removed per window (otherwise a DC offset dominates the autocorrelation). If it is low for clean data, check the sampling rate: a stream labelled 64 Hz but recorded at 25 Hz places the pulse at the wrong lags. If a downstream task scores implausibly well, first count participants shared between train and test; this check costs one set intersection.

Problem. At W1 scale, about 6.7 billion windows contain PPG, and many of them are corrupted by motion. The model must be trained on the usable part, deployed on devices whose sensors and firmware change, and evaluated without identity leakage.

Why it matters. Corrupted windows waste compute and teach the encoder to represent noise. Sensor changes silently shift inputs: a new firmware filter or LED current changes pulse amplitude and shape, and the encoder's embeddings move even though physiology did not. Identity leakage makes every offline number optimistic.

Root causes. Motion corrupts PPG most during the day, when people move (analyzability around 55–60% in daytime versus above 94% at night in the Merschel and Reinhardt (2022) study, on one device model). Device fleets mix hardware generations. Contrastive pretraining with same-person positives, as in W1, explicitly encodes identity, so leakage risk is built into the design.

Worked incident · W1

Three months after deployment, the W1 AFib probe's weekly AUROC on newly labelled cases falls from 0.93 to 0.89. Diagnosis. The dashboard splits windows by device firmware version. The share of windows passing the SQI gate is stable overall, but on a new firmware version (22% of windows) the mean PPG amplitude is 30% lower and the mean embedding has moved by several standard deviations along its first principal component, while windows from older firmware are unchanged. AUROC on old-firmware participants is still 0.93. Remedy options. (a) Per-window amplitude normalization in preprocessing: cheap, but it also removes any amplitude information that carried physiology. (b) Fine-tune or recalibrate the probe with labelled data from the new firmware: needs new labels. (c) Add firmware-like amplitude and filter augmentations during pretraining: robust for future changes but requires retraining the 50-million-parameter encoder. The team applies (a) immediately and schedules (c). Validation. After (a), AUROC on new-firmware participants should recover to within the confidence interval of 0.93 and the embedding shift should fall below the alert threshold; if AUROC recovers only partly, the firmware change also altered pulse shape, which favors (c). Numbers are illustrative.

Metric (per device model and firmware)PurposeExample alert
SQI pass rate, day and night separatelySensor or fit problems; behavior changesDrop of more than 5 points week over week
Amplitude and dominant-frequency quantilesFirmware and hardware changesMedian outside the training 1st–99th percentile band
Embedding mean shift (in training standard deviations)Input drift that reaches the encoderShift above 1 SD on any of the top principal components
Participant overlap between train and evaluation setsIdentity leakageAny non-zero count
Probe AUROC by stratum, with confidence intervalsOutcome-level impactInterval excludes the reference value

Table. Monitoring a waveform model in production. Thresholds are illustrative starting points.

Quality gating trade-off. A strict SQI threshold keeps clean windows and speeds training, but it removes daytime and high-activity windows, which are exactly those where people with some conditions differ; the model then learns resting physiology only. A practical compromise is to keep all windows, store the SQI as metadata, sample training windows with probability increasing in SQI, and report downstream metrics by SQI band. The test: if a probe trained on all SQI bands beats one trained on high-SQI windows only, on a high-SQI test set, the noisy windows add information rather than noise.

Connection. Waveforms in the clinic come singly; in a sleep laboratory they come as a synchronized set of a dozen or more channels for a whole night, which is the subject of the next section.

Polysomnography

Polysomnography (PSG) is the overnight clinical sleep study. It records, together and time-synchronized for about eight hours, the EEG (brain activity), the electrooculogram or EOG (eye movements), chin and leg electromyograms or EMG (muscle tone and limb movements), the ECG, nasal airflow, chest and abdominal respiratory effort, and blood oxygen saturation. Every channel is a waveform, but the set of channels, their montage (which electrode pairs are recorded) and their sampling rates vary by clinic and era. PSG is the richest routinely collected multimodal physiological recording, and resources such as the National Sleep Research Resource (NSRR) make tens of thousands of studies available for research.

The clinical workflow defines the data's structure. A technologist attaches the sensors in the evening; the recording runs overnight; afterwards, a trained scorer divides the night into 30-second epochs and assigns each epoch one sleep stage under the rules of the American Academy of Sleep Medicine (AASM): wake, N1, N2, N3 (deep sleep) or REM. The scorer also marks events such as apneas (pauses in breathing), hypopneas (shallow breathing), arousals and limb movements. Summary numbers follow from these annotations, most importantly the apnea–hypopnea index (AHI), the number of apneas and hypopneas per hour of sleep, which grades sleep apnea severity. The resulting data object is a grid of channel groups by epochs with one stage label per epoch, as the figure shows.

Polysomnography as five channel groups cut into 30-second epochs, with one sleep-stage label per epoch shown as a hypnogram.Channel group30-s epochs (16 shown of about 960 in an 8-hour night)EEGEOGEMGECGRespiratoryHypnogram (label per epoch)WN1N2N3REMStages per AASM rules: wake, N1, N2, N3 (deep), REM. One human scorer labels every epoch.Dashed cells: a channel missing for some epochs, as happens when a lead detaches or a montage differs.
Fig. A polysomnogram as a grid. Rows are channel groups (several physical channels each), columns are 30-second epochs, and the clinical label is one sleep stage per epoch (bottom). A model must accept missing rows and different channels within a row across clinics.

Two features make PSG distinctive for foundation models. First, its labels are noisy in a measurable way: two experienced scorers agree on the stage of an epoch only part of the time, so a model compared against one scorer cannot be expected to exceed the agreement between scorers. de Chazal et al. (2022) asked whether automated staging had reached exactly this ceiling. Second, its channels are complementary views of one night: brain, eyes, muscles, heart and breathing all change together at sleep-stage transitions and during apneas. That cross-modal structure is what contrastive pretraining exploits: SleepFM (Thapa et al. 2024) learns by matching embeddings of different channel groups recorded at the same time.

Worked example · W3

W3 is trained on 30,000 overnight PSGs, about 240,000 hours, grouped into five channel groups (EEG, EOG, EMG, ECG, respiratory) and cut into 30-second epochs: about 28.8 million epochs, 960 per eight-hour night. Against single-scorer labels, its five-class staging reaches Cohen's κ (a chance-corrected agreement score) of 0.78, close to the inter-scorer κ of about 0.76; it detects AHI ≥ 15 (moderate or severe apnea) with AUROC 0.91. When only wearable-like channels are available, κ falls to 0.62.

Scale and outcomes. Sleep models now go beyond staging to disease risk. The published version of SleepFM in Nature Medicine (Thapa, Kjaer et al. 2026) was trained on about 585,000 hours of PSG from roughly 65,000 participants, and, according to Stanford's announcement and press coverage, could predict about 130 conditions from one night with reasonable accuracy (for example, a C-index of 0.84 for death and 0.85 for dementia). Benchmarks such as Stanford Sleep Bench (Kjaer et al. 2025) and OSF (Shuai et al. 2026) compare pretraining choices on PSG.

Compared with a single waveform, PSG adds synchronization and cross-channel structure but brings heterogeneity: a model trained at one clinic meets different electrode derivations, filter settings and sampling rates at the next. The cost is a harmonization layer that maps hundreds of channel labels into a small set of groups and tolerates missing groups. The mental model: a PSG is a multichannel movie of one night, cut into 30-second frames, each captioned by one human with a stage. The next section leaves the laboratory for consumer wearables, where nights and days are recorded for months but with far fewer sensors.

A PSG recording is a set of channels \(\{x_c\}_{c=1}^{C}\), each with its own rate \(f_c\). Channels are grouped into \(G\) groups \(g(c) \in \{1, \dots, G\}\), and the night is cut into epochs of \(E = 30\) seconds. Epoch \(e\) of channel \(c\) holds \(f_c E\) samples. A presence mask \(M \in \{0,1\}^{N_e \times G\}\) records which groups are available in each epoch, where \(N_e\) is the number of epochs. For a night of \(T\) hours, \(N_e = 3600 T / E = 120 T\).

Agreement. Staging is evaluated with Cohen's \(\kappa\), which corrects raw agreement for agreement expected by chance. With confusion proportions \(C_{ij}\) between reference stage \(i\) and predicted stage \(j\) (summing to 1), observed agreement is \(p_o = \sum_i C_{ii}\) and chance agreement is \(p_e = \sum_i r_i c_i\), where \(r_i\) and \(c_i\) are the row and column totals. Then

\[ \kappa = \frac{p_o - p_e}{1 - p_e}, \qquad p_o = p_e + \kappa (1 - p_e). \]

\(\kappa = 0\) is chance and \(\kappa = 1\) perfect agreement. Because N2 dominates most nights, \(p_e\) is substantial and raw accuracy overstates skill.

Label noise ceiling. If the model's errors and the scorer's errors were independent, agreement with one scorer could not exceed what two scorers achieve; observing model–scorer \(\kappa\) close to inter-scorer \(\kappa\) therefore suggests the model is near the measurement limit, not that it is perfect. Distinguishing the two needs consensus labels from several scorers.

Apnea–hypopnea index. With \(A\) apneas, \(H\) hypopneas and total sleep time \(S\) hours, \(\text{AHI} = (A + H)/S\). The threshold AHI ≥ 15 marks moderate or severe obstructive sleep apnea.

Worked example · W3

Epochs. An eight-hour night gives \(N_e = 120 \times 8 = 960\) epochs; 30,000 nights give 28.8 million. At an (assumed) 128 Hz EEG rate, one EEG channel contributes \(128 \times 30 = 3{,}840\) samples per epoch.

Kappa. Assume stage proportions W 0.15, N1 0.08, N2 0.45, N3 0.15, REM 0.17 for both reference and prediction (the same assumed mix as in the sleep chapter). Then \(p_e = 0.15^2 + 0.08^2 + 0.45^2 + 0.15^2 + 0.17^2 = 0.2828\). W3's \(\kappa = 0.78\) corresponds to raw agreement \(p_o = 0.2828 + 0.78 \times 0.7172 = 0.842\); the inter-scorer \(\kappa \approx 0.76\) corresponds to 0.828; the wearable-only \(\kappa = 0.62\) to 0.727. Under these proportions, a model that always predicts N2 would be right 45% of the time with \(\kappa = 0\).

AHI. With 6.5 hours of sleep and 98 apneas and hypopneas (assumed), AHI = 98/6.5 = 15.1, just over the threshold; one fewer hour of scored sleep with the same events would give 17.8. AHI depends on both counts and the sleep-time denominator, so staging errors propagate into apnea severity.

Cross-modal pretraining signal. For epoch \(e\), let \(z^{(g)}_e\) be the embedding of group \(g\). A contrastive objective scores the matching pair \((z^{(g)}_e, z^{(g')}_e)\) against pairs from other epochs or nights, so the encoder must extract what the groups share at the same moment. Absent groups (\(M_{e,g} = 0\)) are excluded from the loss rather than filled with zeros, which would teach the encoder that a flat line is a valid view of sleep.

The harmonization step is the core engineering of PSG data. The function below maps each channel's header label to one of five groups through an alias table, resamples each channel to a group-specific target rate with a polyphase filter, cuts the result into 30-second epochs, and records a per-epoch presence mask, marking flat-lined (lead-off) epochs absent. Channels with unknown labels are returned in a list rather than dropped silently. Target rates are an assumed design choice. A Cohen's κ function and the κ–agreement conversion reproduce the worked numbers: with assumed stage proportions W 0.15, N1 0.08, N2 0.45, N3 0.15, REM 0.17, chance agreement is 0.283, so κ 0.78 corresponds to 84.2% raw agreement.

import numpy as np
from math import gcd
from scipy.signal import resample_poly

GROUPS = ["EEG", "EOG", "EMG", "ECG", "RESP"]
ALIAS = {  # header label (upper-cased) -> group; real tables hold hundreds of variants
    "C3-M2": "EEG", "C4-M1": "EEG", "EEG C3-A2": "EEG", "F4-M1": "EEG", "O2-M1": "EEG",
    "E1-M2": "EOG", "LOC": "EOG", "ROC": "EOG", "CHIN": "EMG", "CHIN1-CHIN2": "EMG",
    "LLEG": "EMG", "ECG": "ECG", "EKG": "ECG", "AIRFLOW": "RESP", "THOR": "RESP",
    "ABDO": "RESP", "SPO2": "RESP", "NASAL PRESSURE": "RESP"}
TARGET_HZ = {"EEG": 128, "EOG": 128, "EMG": 128, "ECG": 128, "RESP": 8}   # ASSUMED design choice
EPOCH_S = 30

def to_epochs(channels: dict, rates: dict):
    """channels: label -> 1-D array; rates: label -> Hz.
    Returns {group: (n_epochs, n_ch, samples)} and a (n_epochs, 5) presence mask."""
    by_group, unknown = {g: [] for g in GROUPS}, []
    for lab, x in channels.items():
        g = ALIAS.get(lab.strip().upper())
        if g is None: unknown.append(lab); continue
        fs, ft = rates[lab], TARGET_HZ[g]
        k = gcd(int(fs), ft)
        by_group[g].append(resample_poly(x, ft // k, int(fs) // k))
    n_ep = min(len(x) // (TARGET_HZ[g] * EPOCH_S) for g, xs in by_group.items() for x in xs)
    out, mask = {}, np.zeros((n_ep, len(GROUPS)), bool)
    for j, g in enumerate(GROUPS):
        if by_group[g]:
            L = TARGET_HZ[g] * EPOCH_S
            arr = np.stack([x[: n_ep * L].reshape(n_ep, L) for x in by_group[g]], 1)
            out[g] = arr
            # lead-off check: an epoch whose samples are mostly ~0 is marked absent
            mask[:, j] = (np.abs(arr) < 1e-3).mean(axis=(1, 2)) < 0.5
    return out, mask, unknown

def kappa(a, b, k=5):
    C = np.zeros((k, k)); np.add.at(C, (a, b), 1); C /= C.sum()
    po, pe = np.trace(C), C.sum(1) @ C.sum(0)
    return (po - pe) / (1 - pe), po, pe

# A 2-minute toy study from a clinic with its own labels and rates; no ECG channel.
rng = np.random.default_rng(1); T = 120
chans = {"C4-M1": rng.standard_normal(T * 256), "LOC": rng.standard_normal(T * 256),
         "Chin": rng.standard_normal(T * 200), "Thor": rng.standard_normal(T * 25),
         "Pleth": rng.standard_normal(T * 256)}
rates = {"C4-M1": 256, "LOC": 256, "Chin": 200, "Thor": 25, "Pleth": 256}
chans["Chin"][T * 200 // 2:] = 0.0                       # chin lead detaches halfway
ep, mask, unk = to_epochs(chans, rates)
print({g: a.shape for g, a in ep.items()}, "unknown:", unk)
print(mask.astype(int))
assert ep["EEG"].shape == (4, 1, 3840) and ep["RESP"].shape == (4, 1, 240)
assert not mask[:, 3].any() and mask[:2, 2].all() and not mask[2:, 2].any()

# Kappa: illustrative marginals W .15, N1 .08, N2 .45, N3 .15, REM .17 (ASSUMED; same mix as Chapter 8)
p = np.array([.15, .08, .45, .15, .17]); pe = p @ p
for k_ in (0.78, 0.76, 0.62):
    print(f"kappa {k_:.2f} <-> raw agreement {pe + k_ * (1 - pe):.3f} (chance {pe:.3f})")
ref = rng.choice(5, 20000, p=p)
pred = np.where(rng.random(20000) < 0.78, ref, rng.choice(5, 20000, p=p))
k_hat, po, _ = kappa(ref, pred)
print(f"simulated: agreement {po:.3f}, kappa {k_hat:.3f}")
assert abs(k_hat - 0.78) < 0.02

Output:

{'EEG': (4, 1, 3840), 'EOG': (4, 1, 3840), 'EMG': (4, 1, 3840), 'RESP': (4, 1, 240)} unknown: ['Pleth']
[[1 1 1 0 1]
 [1 1 1 0 1]
 [1 1 0 0 1]
 [1 1 0 0 1]]
kappa 0.78 <-> raw agreement 0.842 (chance 0.283)
kappa 0.76 <-> raw agreement 0.828 (chance 0.283)
kappa 0.62 <-> raw agreement 0.727 (chance 0.283)
simulated: agreement 0.840, kappa 0.776

The toy study has no ECG channel, so the ECG column of the mask is all zeros; the chin EMG detaches halfway, so its last two epochs are absent; a pulse-oximeter waveform labelled "Pleth" is not in the alias table and is reported as unknown. The simulated predictions, which copy the reference 78% of the time and otherwise draw from the stage proportions, give κ ≈ 0.78, matching the closed form.

Shapes. Output per group: (epochs, channels in group, samples per epoch), for example (4, 1, 3840) for EEG at 128 Hz and (4, 1, 240) for respiratory at 8 Hz; mask: (epochs, 5) booleans. A model that consumes groups separately (one encoder per group, then a fusion step) can take these arrays directly.

Tests to keep. (1) Every header label across the corpus is either in the alias table or in an explicit ignore list; the unknown list must be empty in production. (2) Epoch counts agree across groups, since a mismatch means one channel's rate was wrong in the header. (3) The number of epochs times 30 seconds matches the scored hypnogram length; a mismatch of a few epochs usually comes from lights-off and lights-on offsets in the annotation file.

Debugging tips. Resampling a channel whose header rate is wrong produces a plausible-looking signal at the wrong time scale; check the dominant frequency of EEG (alpha rhythm near 10 Hz during relaxed wake) and of ECG (heart rate near 1 Hz) after resampling. If κ is much lower at one site, compare stage proportions first: a site whose scorers label more N1 changes \(p_e\) and the meaning of a fixed κ.

Problem. A PSG model that performs well at the training clinics meets new sites with different montages, sensors, scoring conventions and patient mixes. Performance can drop without any error being raised, because missing or misnamed channels are handled by the same mask that handles genuinely absent sensors.

Why it matters. Sleep models are moving from research to disease-risk prediction at scale (SleepFM trained on about 585,000 hours from roughly 65,000 participants). At that scale, site heterogeneity is the norm, and a silent channel mapping failure at one site removes the most informative signal for every patient there.

Root causes. Header labels are free text set by each laboratory ("C4-M1", "C4-A1", "EEG C4-REF"). Sampling rates and hardware filters differ. Scoring manuals are revised, and sites differ in how they apply them. Patient populations differ: a clinic for suspected apnea has a far higher AHI distribution than a population cohort.

Worked incident · W3

W3 is deployed at a new clinic. After 400 nights, five-class κ against that clinic's scorers is 0.61, well below 0.78. Diagnosis. The ingestion dashboard shows the presence mask by site: at the new clinic, the EEG group is present in only 9% of epochs. The unknown-label log lists "EEG F4-A1" and "EEG C4-A1" in every study; the alias table expected "C4-M1". The model was therefore staging from EOG, EMG, ECG and respiration, close to its wearable-like setting (κ 0.62). Remedy. Map the A1/A2 (ear) references to the same groups as M1/M2 (mastoid) references, a common harmonization choice that should be documented because the two reference sites are not identical, re-ingest, and add a gate that blocks a site whose unknown-label count is non-zero or whose per-group presence falls more than 20 points below the training average. Cost. Re-ingesting 400 nights and one alias-table release. Validation. EEG presence should rise above 95% of epochs and κ toward the training range; if κ stays near 0.70 with EEG present, the remaining gap is more likely scoring convention or population, to be checked by having a sample of nights scored by a second scorer. Numbers are illustrative.

Check (per site, per week)DetectsExample gate
Unknown channel labelsAlias table gapsMust be zero before a site is enabled
Group presence share per epochMissing or misnamed channels; lead-offNo group more than 20 points below training average
Dominant frequency of EEG and ECG after resamplingWrong header sampling rateWithin physiological ranges in at least 95% of nights
Predicted stage proportions versus site scorersScoring convention and population shiftN1 or N3 share differs by more than 5 points
κ on a double-scored sampleModel versus human ceiling at the siteModel κ within interval of inter-scorer κ

Table. Site onboarding checks for a PSG model. Thresholds are illustrative.

Choosing a channel strategy. A fixed canonical montage (one EEG derivation, one EOG, one chin EMG, and so on) is simple to validate but discards information and fails when the chosen derivation is missing. Group-level encoders with a per-epoch presence mask (one encoder per channel group, absent groups excluded rather than zero-filled) accept any subset and degrade gradually. Fully channel-agnostic models that embed each channel with a learned identifier accept any montage but need more data and compute. The decision rule: measure κ with each group removed in turn (a leave-one-group-out ablation); if removing EEG costs far more than any other group, as in the incident, the deployment must guarantee EEG presence or fall back explicitly to a model trained for the reduced setting.

Connection. The reduced setting is the bridge to the next section: consumer wearables record a subset of PSG's signals (PPG and movement, sometimes temperature), every night for months, without a technologist or a scorer.

Wearable time series

Consumer wearables (smartwatches, fitness bands, rings) produce two layers of data. The first is raw or lightly processed sensor streams: accelerometer, PPG, skin temperature, electrodermal activity, sampled tens of times per second. The second is derived aggregates computed on the device or in the vendor's cloud: step counts, heart rate, heart-rate variability, sleep duration and stages, active minutes, at minute or hour resolution. Raw streams are what the waveform section described; this section concerns the aggregates and the long records they form.

Aggregates exist because raw streams are expensive to keep and transmit for months. The device runs vendor algorithms that turn seconds of signal into one number per minute or hour, and only those numbers are synchronized to the phone. The result is long (months to years per person), low-rate and multivariate, and it is riddled with gaps whenever the device is off-wrist or charging. The gaps are not random: people charge their watches at habitual times, take them off for some activities, and stop wearing them when ill or on holiday. A model that fills gaps with averages hides that structure and can introduce bias, because the hours that are missing differ systematically from those that are observed (figure below).

One week of hourly wearable data for one participant; filled cells are hours with data, empty cells are hours with none.DayHour of dayDay 1Day 2Day 3Day 4Day 5Day 6Day 70003060912151821hour with datano data (charging, off-wrist)64 of 168 hours missing (38%), close to the 38% of hours without PPG in the W1 example
Fig. Missingness in a week of wearable data (illustrative). Gaps are structured: a nightly charging slot, a night the device was not worn, and a full day off-wrist. Gaps that depend on behavior are informative, so a model that silently fills them with averages hides a signal and can introduce bias.

Behavioral aggregates can be as predictive as raw physiology for some outcomes. Erturk et al. (2025) trained a wearable behavior model (WBM) on about 2.5 billion hours of hourly data, 27 HealthKit quantities for 161,855 participants of the Apple Heart and Movement Study, with one week (168 hours) per input. The behavior model beat a PPG model on infection, injury and three of four sleep metrics, while PPG was stronger for diabetes, pregnancy and deep-sleep duration, and for 29 of 47 baseline medical-history outcomes; combining the two was best on 42 of those 47. Missingness has become a modelling target in its own right: LSM-2 (Xu, Narayanswamy et al. 2025) was pretrained on 40 million hours from more than 60,000 Fitbit and Pixel users, and, as the accompanying blog reports, none of its 1.6 million day-long windows was complete. Its masking scheme treats naturally missing segments the same way as segments hidden for training, so the model learns from incomplete data instead of discarding it.

Worked example · W1

In W1, 38% of hours have no PPG because the device is off-wrist or charging. The week in the figure is constructed with that rate: 64 of 168 hours missing, including a nightly charging slot at 19:00–21:00, one night without the watch and one full day off-wrist. Its downstream targets include resting heart rate (probe MAE 2.4 bpm) and age (MAE 6.1 years). Resting heart rate is estimated mostly from night and quiet hours, so a participant who rarely wears the watch at night contributes fewer usable hours to exactly the quantity being predicted.

Compared with clinical data, wearables observe ordinary life continuously and cheaply, for people who rarely see a clinician, and capture behavior (activity, sleep timing) that EHRs record only as occasional notes. Large wearable models such as LSM (Narayanswamy et al. 2025) have shown improving results with more data and compute. The cost is heavy, informative missingness, device and algorithm heterogeneity (two vendors' "sleep duration" are different measurements), and labels that are usually self-reported or linked from elsewhere. The mental model: a wearable record is a daily diary written by a sensor, with pages missing whenever the person took the device off, and the missing pages say something too. The last section turns to imaging, the one modality in this taxonomy that is not a sequence.

Represent one participant's aggregates as a matrix \(X \in \mathbb{R}^{T \times V}\) of \(T\) time steps (hours) and \(V\) variables, with an observation mask \(M \in \{0,1\}^{T \times V}\). An hour counts as observed when enough of its minutes carry data (the code uses at least 30 of 60, an assumed rule). The missing rate is \(1 - \bar M\).

Missingness mechanisms. Statistics distinguishes three cases. Missing completely at random (MCAR): \(M\) is independent of everything. Missing at random (MAR): \(M\) depends only on observed quantities, such as hour of day. Missing not at random (MNAR): \(M\) depends on the unobserved value itself, for example a watch taken off during illness when heart rate would have been high. Under MCAR, averages over observed entries are unbiased; under MAR they can be corrected by reweighting on the observed covariates; under MNAR no reweighting on observed data fully corrects them.

Bias of the observed mean. Let hour-of-day \(h\) have true mean \(\mu_h\) and observation probability \(o_h\). The mean over observed hours is

\[ \hat\mu_{\text{obs}} = \frac{\sum_h o_h \mu_h}{\sum_h o_h}, \qquad \text{whereas} \qquad \mu = \frac{1}{24}\sum_h \mu_h . \]

The two agree only if \(o_h\) is unrelated to \(\mu_h\). The hour-stratified estimator \(\hat\mu_{\text{strat}} = \frac{1}{|\mathcal{H}|}\sum_{h \in \mathcal{H}} \bar x_h\) averages within each hour first; it removes the bias from unequal \(o_h\) (a MAR correction) but can only average over the set \(\mathcal{H}\) of hours observed at least once.

Masked pretraining with inherited masks. A masked autoencoder hides a set \(A\) of observed entries and learns to reconstruct them. With natural missingness, the visible set is \(\{M = 1\} \setminus A\) and the loss is computed only on \(A\):

\[ \mathcal{L} = \frac{1}{|A|}\sum_{(t,v) \in A} \big(\hat x_{t,v} - x_{t,v}\big)^2, \qquad A \subseteq \{(t,v) : M_{t,v} = 1\}. \]

Naturally missing entries are never targets (there is no ground truth for them) and are never shown as zeros; they are excluded through the attention mask. This is the principle behind the adaptive and inherited masking of LSM-2.

Worked example · W1 week

Consider a synthetic week with heart rate 58 bpm during 00:00–07:00 and 75 bpm otherwise, so the true mean is \((7 \times 58 + 17 \times 75)/24 = 70.0\) bpm. With a structured gap pattern (a nightly charging slot at 19:00–21:00, one unworn night, one day off-wrist and several shorter gaps: 64 of 168 hours missing, 38.1%), night hours are observed 69% of the time and day hours 59%. Because the low night values are over-represented among observed hours, the observed mean is 69.3 bpm, 0.7 bpm too low. The hour-stratified mean is 69.5 bpm: it removes most of the bias, but hours 19 and 20 are never observed (nightly charging), so their 75 bpm values cannot enter the average. For resting heart rate, where the W1 probe's MAE is 2.4 bpm, a systematic error of this size is not negligible.

For masked pretraining on this week, 104 hours are observed; masking half of them gives 52 visible and 52 target hours, and the 64 naturally missing hours are neither.

The trade-off in choosing the masking ratio is between task difficulty and information: a high ratio forces the model to learn long-range structure, but with 38% already missing, a further 50% leaves less than a third of the week visible. Tuning the artificial ratio jointly with the natural missing rate, rather than copying the 75% common in image models, is part of the design.

The code builds hourly aggregates with a validity mask from a minute-level series, reproduces the bias of the observed mean under structured missingness, and constructs masks for masked-autoencoder pretraining in which naturally missing hours are inherited as invisible and never used as targets. The gap pattern is a structured week: a nightly charging slot at 19:00–21:00, one unworn night, one day off-wrist and several shorter gaps, 64 of 168 hours in all.

import warnings; warnings.filterwarnings("ignore", "Mean of empty slice")  # all-missing hours -> NaN
import numpy as np
rng = np.random.default_rng(7)

def hourly(minute_vals: np.ndarray, min_cover: int = 30):
    """(days*1440,) minute series with NaN gaps -> (days, 24) hourly means and a validity
    mask. An hour counts as observed if it has >= min_cover valid minutes (ASSUMED rule)."""
    m = minute_vals.reshape(-1, 24, 60)
    cover = np.isfinite(m).sum(-1)
    with np.errstate(invalid="ignore"):
        mean = np.nanmean(np.where(np.isfinite(m), m, np.nan), -1)
    valid = cover >= min_cover
    return np.where(valid, mean, np.nan), valid

def mae_masks(valid: np.ndarray, ratio: float = 0.5):
    """Inherited + artificial masking in the spirit of LSM-2's AIM: naturally missing
    tokens are never targets; a random share of OBSERVED tokens is hidden and predicted."""
    obs = np.flatnonzero(valid.ravel())
    hide = rng.choice(obs, int(ratio * obs.size), replace=False)
    artificial = np.zeros(valid.size, bool); artificial[hide] = True
    visible = valid.ravel() & ~artificial          # encoder attends only to these
    target = artificial                            # loss computed only here
    return visible.reshape(valid.shape), target.reshape(valid.shape)

# One synthetic week of minute heart rate: 58 bpm asleep (00-07), 75 bpm awake.
days = 7
hr = np.tile(np.r_[np.full(7 * 60, 58.0), np.full(17 * 60, 75.0)], days) + rng.normal(0, 3, days * 1440)
gaps = np.zeros((days, 24), bool)
gaps[:, 19:21] = True; gaps[2, 0:9] = True; gaps[5, :] = True        # same pattern as the figure
gaps[6, 7:12] = True; gaps[0, 13:16] = True; gaps[3, 21:24] = True; gaps[1, 6:9] = True
gaps[4, 12:15] = True; gaps[0, 22:24] = True
hr_obs = hr.copy(); hr_obs[np.repeat(gaps.ravel(), 60)] = np.nan
H, valid = hourly(hr_obs)
print(f"missing hours {(~valid).sum()} / {valid.size} = {(~valid).mean():.1%}")
assert (~valid).sum() == 64

true_mean = hr.mean(); naive = np.nanmean(H)
night_obs = valid[:, :7].mean(); day_obs = valid[:, 7:].mean()
print(f"true mean HR {true_mean:.1f}, mean over observed hours {naive:.1f}; "
      f"observed share night {night_obs:.2f} vs day {day_obs:.2f}")
# Re-weight by hour-of-day stratum: average within each hour, then across hours.
strat = np.nanmean(np.nanmean(H, 0))
print(f"hour-stratified mean {strat:.1f}")
assert abs(strat - true_mean) < abs(naive - true_mean) + 1e-9

vis, tgt = mae_masks(valid)
assert not (tgt & ~valid).any() and not (vis & tgt).any()
print("visible", vis.sum(), "targets", tgt.sum(), "never-target missing", (~valid).sum())

Output:

missing hours 64 / 168 = 38.1%
true mean HR 70.0, mean over observed hours 69.3; observed share night 0.69 vs day 0.59
hour-stratified mean 69.5
visible 52 targets 52 never-target missing 64

The output shows 38.1% of hours missing, an observed mean 0.7 bpm below the truth, and an hour-stratified mean that recovers part of the gap. The last assertions check the two properties of inherited masking: no target is a naturally missing hour, and no target is visible to the encoder.

Shapes. Minute input: (days × 1440,) with NaN for gaps. Hourly output: (days, 24) values and a boolean mask of the same shape. In a multivariate setting the arrays become (T, V) with one mask per variable, because different aggregates go missing independently (steps can be present while heart rate is absent if the optical sensor lost contact).

Design notes. The 30-minute coverage rule decides how many partially observed hours count; a lower threshold keeps more hours but makes their means noisier and more dependent on which minutes were observed. The mask, not a fill value, carries missingness into the model; if a fill value is needed for arithmetic, use zero after normalization and always pass the mask alongside.

Debugging tips. If the missing rate is near 0%, check whether the vendor export already imputed gaps (constant runs of identical values are a sign). If hour-of-day profiles look shifted for some participants, check time zones: aggregates are often exported in UTC, while behavior follows local time. If the masked-reconstruction loss is suspiciously low, confirm that targets exclude imputed values.

Problem. Wearable aggregate pipelines draw data from many device models, firmware versions, vendor algorithms and time zones, synchronized with delays and subject to participant behavior. Each of these can change what a number means without any change in the person.

Why it matters. Aggregates are the input to long-horizon models (a week per input in WBM) and to population-scale studies. A change in a vendor's sleep or step algorithm, or in how hours are aligned, shifts every downstream prediction for every affected participant simultaneously, which looks like a population trend.

Root causes. (1) Time alignment: UTC versus local time, daylight-saving transitions, travel. (2) Algorithm versions: vendor updates to derived metrics. (3) Device heterogeneity: sensors and placement differ across models. (4) Informative missingness that changes with season or health state. (5) Sync lag: data arrive hours or days late, so "today's" features are incomplete at prediction time.

Worked incident · W1

After a storage migration, the W1 resting-heart-rate probe's MAE rises from 2.4 to 3.1 bpm, but only for participants outside the time zone of the data center. Diagnosis. The hour-of-day profile of step counts, plotted per time zone, peaks at 03:00 for one group of participants: the new store writes hours in UTC, and the feature code that selects "night hours" for resting heart rate assumes local time. Remedy. Store UTC plus the local offset in effect for each hour (offsets change with travel and daylight saving), derive local hour-of-day from the pair, and add a check that the median step-count peak per participant lies in local daytime. Cost. A schema change and a re-derivation of features over 30 million participant-hours. Validation. MAE should return to the 2.4 bpm reference across all time zones, with no residual difference between zones beyond the confidence interval; a remaining gap in zones with daylight-saving transitions would indicate the offset is applied per day rather than per hour. Numbers are illustrative.

MetricDetectsExample alert
Missing-hour rate by hour of day, device and monthChanges in wear behavior, sync failuresOverall rate moves more than 3 points from the 38% baseline
Hour of peak step count per participant (local time)Time-zone and daylight-saving errorsPeak between 00:00 and 05:00 for more than 1% of participants
Distribution of each derived metric by algorithm versionVendor algorithm changesMedian shift above a pre-set tolerance at a version boundary
Data arrival delay (p50, p95)Incomplete features at prediction timep95 delay exceeds the feature window
Probe error by wear-time quartileBias toward heavy wearersLowest quartile error far above the others

Table. Monitoring a wearable aggregate pipeline. Thresholds are illustrative.

Handling missingness: three options. Exclusion (keep only participant-weeks above a wear-time threshold) is simple, but it removes the least compliant participants, who may differ in health. Imputation before modelling makes arrays complete, but the model then learns from invented values and cannot tell them from real ones. Mask-aware modelling (inherited masks as in LSM-2, or an explicit missingness channel) uses all data and lets the model learn from the pattern of gaps, at the cost of a more complex model and evaluation. The deciding test is the probe-error-by-wear-time row of the table: if exclusion or imputation leaves the lowest-wear quartile with much higher error than mask-aware modelling, the gaps are carrying information, and the mask-aware option is justified.

Connection. Wearables, PSG and waveforms are all sequences in time. Imaging, the last modality, is spatial and episodic, and enters health foundation models mostly through its links to text and codes.

Imaging, briefly

Medical imaging covers radiology (X-ray, computed tomography or CT, magnetic resonance imaging), digital pathology (scanned tissue slides), ophthalmology (retinal photographs and optical coherence tomography or OCT), dermatology and more. Images are spatial rather than temporal: one study is a 2D picture or a 3D volume taken at one moment, and a patient accumulates a few studies over years. Imaging foundation models follow the vision playbook, chiefly masked autoencoders (MAE, He et al. 2022), which hide most of an image's patches and learn to reconstruct them, and image–text contrastive learning in the style of CLIP (Radford et al. 2021), which aligns images with their paired reports. The field deserves its own book; this one focuses on sequences.

Imaging matters here for two reasons. First, it shows the same small set of self-supervised objectives recurring in a different modality, which the next chapter develops in general form. RETFound (Zhou et al. 2023) pretrained an MAE on about 1.6 million unlabelled retinal images (904,170 colour fundus photographs and 736,442 OCT scans), masking 75% of fundus patches and 85% of OCT patches, then fine-tuned it for eye diseases and for the 3-year incidence of systemic conditions such as heart failure, myocardial infarction, ischaemic stroke and Parkinson's disease. Second, imaging is a modality to fuse with EHR and signals: each study sits inside a patient timeline, is described by a report, and is followed by diagnosis codes.

The data path runs as follows. A clinician orders a study; the scanner produces images with technical metadata (device, protocol, slice thickness); a radiologist reads them and writes a report; diagnosis codes are assigned during or after the encounter. Each later product is a candidate supervision signal for the images. Merlin (Blankemeier et al. 2024) used both kinds: it trained a 3D CT model on 15,331 CT scans with more than 1.8 million EHR diagnosis codes as weak labels and more than 6 million report tokens for image–text alignment, without additional manual annotation, and evaluated it on 752 individual tasks.

Imaging foundation model supervision: image encoder trained with EHR diagnosis codes as weak labels and aligned with report text by contrastive learning.EHR diagnosis codesweak labels per studyMulti-label losspredict codes from image3D CT volumehundreds of slicesImage encodervolume to embeddingRadiology reportfindings, impressionText encoderreport to embeddingContrastive alignmentmatched image-report pairspulled together,mismatched pairspushed apart
Fig. Two supervision sources for an imaging foundation model, as in Merlin (Blankemeier et al. 2024): structured EHR codes act as weak labels for the image encoder, and the paired report aligns image and text embeddings. Neither needs manual annotation; both inherit the coding and reporting habits of the source hospital.
Worked example · W2 with imaging (assumed extension)

If W2's patient timelines were linked to imaging, a CT study would enter the token stream only as an order code and possibly a report, while the pixels would go to a separate image encoder. Consider a CT on 1 March 2023, which receives two weak labels from codes recorded within 30 days on either side: atrial fibrillation (coded 20 February) and fatty liver (coded 3 March); a chronic kidney disease code from September falls outside the window. The 30-day window is an assumption, and a code recorded after the study may simply restate what the radiologist wrote.

Compared with the sequence modalities, images carry dense spatial detail but are taken rarely, so they describe a patient's state at a few moments rather than a trajectory. They are also large: one CT volume holds hundreds of slices. The cost of including them is storage, compute and a separate encoder, plus the risk of shortcuts (scanner type or hospital markings that correlate with outcomes). The mental model: an image is a high-resolution snapshot pinned to one point on the patient's timeline, whose meaning is supplied partly by the report written about it. With imaging, the taxonomy is complete; the next chapter turns to the self-supervised objectives that learn representations from all of these modalities.

A 2D image of size \(H \times W\) (with channels) is cut into non-overlapping patches of \(p \times p\) pixels, giving \(N = (H/p)(W/p)\) tokens; a 3D volume \(H \times W \times D\) with cubic patches of side \(p\) gives \(N = (H/p)(W/p)(D/p)\). Transformer attention costs on the order of \(N^2\) per layer, so 3D volumes push token counts, and cost, up quickly.

Masked autoencoding. With mask ratio \(r\), the encoder sees only \((1-r)N\) patches, and a lightweight decoder reconstructs the hidden ones. The encoder's attention cost falls by roughly \((1-r)^2\) relative to processing all patches, which is what makes MAE pretraining affordable at high resolution. The loss is the mean squared error on hidden patches only:

\[ \mathcal{L}_{\text{MAE}} = \frac{1}{|A|} \sum_{i \in A} \lVert \hat{\mathbf{x}}_i - \mathbf{x}_i \rVert^2 , \]

where \(A\) is the set of masked patches, \(\mathbf{x}_i\) the pixel values of patch \(i\) and \(\hat{\mathbf{x}}_i\) the reconstruction.

Image–report alignment. For a batch of \(B\) image–report pairs with normalized embeddings \(u_k\) (image) and \(v_k\) (report), a CLIP-style loss treats each matched pair as the correct answer among \(B\) candidates:

\[ \mathcal{L}_{\text{img}\to\text{txt}} = -\frac{1}{B}\sum_{k=1}^{B} \log \frac{\exp(u_k^\top v_k / \tau)}{\sum_{j=1}^{B} \exp(u_k^\top v_j / \tau)}, \]

with temperature \(\tau\), and symmetrically for text to image. Weak labels from codes add a multi-label loss \(-\sum_c [y_c \log \sigma(s_c) + (1-y_c)\log(1-\sigma(s_c))]\), where \(y_c = 1\) if code \(c\) is recorded within a window around the study and \(s_c\) is the model's score.

Worked example · token counts

2D. A 224 × 224 fundus photograph with 16 × 16 patches gives \(14 \times 14 = 196\) tokens. At RETFound's fundus mask ratio of 0.75, the encoder sees 49; attention cost falls to about \((49/196)^2 = 1/16\) of the full image.

3D. An assumed CT crop of 224 × 224 × 160 voxels with 16-voxel cubes gives \(14 \times 14 \times 10 = 1{,}960\) tokens, ten times the 2D count and about 100 times the attention cost per layer. With 75% masking the encoder sees 490 tokens.

Weak-label noise. If a code window admits a code unrelated to the image (atrial fibrillation for an abdominal CT), the label is noise for that task. The window length trades recall of relevant codes against such noise; a symmetric window also admits codes derived from the report itself.

The same three loss forms (masked reconstruction, contrastive alignment, supervised weak labels) reappear for every modality in this book, with patches of time replacing patches of space. That correspondence is why imaging is worth a brief look in a book about sequences.

Two pieces of imaging data preparation connect directly to the rest of the book: computing token counts for 2D and 3D inputs (which sets memory and compute), and linking imaging studies to EHR codes to form weak labels. The code below does both, with an assumed CT crop size and an assumed ±30-day code window.

from datetime import date, timedelta

def n_patches(shape, patch):
    """Number of non-overlapping patches (tokens) for a 2D or 3D image."""
    n = 1
    for s, p in zip(shape, patch):
        assert s % p == 0, "pad or crop to a multiple of the patch size"
        n *= s // p
    return n

# 2D: a 224x224 fundus photo with 16x16 patches; MAE masks 75% (RETFound used 0.75 for CFP).
fundus = n_patches((224, 224), (16, 16))
# 3D: an ASSUMED CT crop of 224x224x160 voxels with 16x16x16 patches.
ct = n_patches((224, 224, 160), (16, 16, 16))
for name, n, r in [("fundus", fundus, 0.75), ("CT", ct, 0.75)]:
    print(f"{name}: {n} patches, encoder sees {round(n * (1 - r))} after masking {r:.0%}")
assert fundus == 196 and ct == 1960

def weak_labels(study_day: date, codes, before=30, after=30):
    """EHR codes recorded within a window around the imaging study become weak labels
    (window sizes are ASSUMED). Codes after the study may encode the report itself."""
    lo, hi = study_day - timedelta(days=before), study_day + timedelta(days=after)
    return sorted({c for d, c in codes if lo <= d <= hi})

codes = [(date(2023, 2, 20), "ICD10//I48.91"), (date(2023, 3, 3), "ICD10//K76.0"),
         (date(2023, 9, 1), "ICD10//N18.3")]
lab = weak_labels(date(2023, 3, 1), codes)
print("weak labels for CT on 2023-03-01:", lab)
assert lab == ["ICD10//I48.91", "ICD10//K76.0"]

Output:

fundus: 196 patches, encoder sees 49 after masking 75%
CT: 1960 patches, encoder sees 490 after masking 75%
weak labels for CT on 2023-03-01: ['ICD10//I48.91', 'ICD10//K76.0']

The token counts are 196 and 1,960 tokens (49 and 490 visible after 75% masking). The weak-label function returns the two codes within the window and excludes the chronic kidney disease code recorded six months later.

Shapes. A 2D image tensor is (channels, H, W); a 3D CT is (1, H, W, D) after resampling to a fixed voxel spacing. Patch embedding turns it into (N, d) tokens. Weak labels form a (studies, codes) binary matrix, typically very sparse.

Checks. (1) Resample CT volumes to a fixed physical voxel size before cropping, otherwise a 16-voxel patch covers different anatomy on different scanners; assert the spacing in the metadata after resampling. (2) Assert that the patient of each study and of each linked code is the same and that both fall in the same split. (3) Record the window used for weak labels with the dataset version, because changing it changes every label.

Debugging tip. If a weak-label classifier becomes very accurate for one code almost immediately, check whether that code is assigned from the radiology report itself (for example, an incidental finding coded after reading the report); in that case the model learns to reproduce the report's wording via the image only where the two agree, and evaluation against the same codes is circular.

Problem. Imaging adds the largest per-patient storage and compute footprint to a health foundation model program and is the modality most exposed to shortcuts: features of the acquisition (scanner model, protocol, burned-in text, positioning) that correlate with outcomes at the training site.

Why it matters. A shortcut produces strong validation numbers at the training hospital and fails elsewhere. Because images are rarely inspected by the engineers who train models, such failures are found late.

Root causes. Sicker patients are imaged with different equipment and protocols (portable devices, contrast agents, emergency protocols); sites differ in vendors and settings; weak labels from codes and reports encode clinical context as well as image content.

Worked incident · imaging extension (illustrative)

A CT encoder pretrained with code-based weak labels and linked to W2 timelines improves 1-year mortality AUROC from 0.89 to 0.92 at the development site but adds nothing at a second hospital. Diagnosis. A probe that predicts the scanner protocol from the image embedding reaches near-perfect accuracy, and mortality AUROC within each protocol group is barely above the timeline-only model; emergency protocols, used mostly for the sickest patients, explain most of the gain. Remedy. Report performance within protocol strata, add protocol and scanner as explicit covariates so the image's added value is measured beyond them, and augment intensity and resolution during pretraining. Cost. A smaller apparent gain, and more evaluation work. Validation. The within-protocol AUROC gain and the gain at the second hospital should agree; if the gain disappears in both, the image added mainly acquisition information. All numbers are illustrative.

ConcernMeasurementRemedyTrade-off
Storage and computeTokens per study after resampling; GPU hours per epochFixed spacing, cropping to the region of interest, high mask ratiosCropping can remove incidental findings
Acquisition shortcutsAccuracy of a probe predicting scanner or protocol from embeddingsStratified evaluation; covariate adjustment; augmentationLower headline metrics, more honest ones
Circular weak labelsShare of codes assigned after the report was signedUse codes from before the study or from later encounters onlyFewer labels per study
Patient leakagePatients with studies in both splitsSplit by patient in the canonical store, before linkageNone beyond bookkeeping

Table. Production concerns when imaging joins a sequence-based health model.

Scale. The published models give a sense of scale: RETFound pretrained on about 1.6 million 2D retinal images; Merlin on 15,331 3D CT scans, which yielded more than 6 million 2D images. Per study, a 3D volume costs about ten times the tokens of a 2D image (a 224 × 224 × 160 CT crop in 16-voxel cubes gives 1,960 tokens against 196 for a 224 × 224 image in 16 × 16 patches), so the number of studies that fit a fixed compute budget falls by an order of magnitude for 3D.

Choosing whether to include imaging. For a program centred on sequences, the practical test is the marginal value of the image embedding over the timeline model on held-out sites, within acquisition strata. If that value is small, linking report text (already part of clinical text) captures much of the information at a fraction of the cost; if it is large and survives stratification, a dedicated imaging encoder is justified. This closes the taxonomy: six modalities, two canonical forms (events and signals, with images as a third, spatial form), and one shared set of failure modes (leakage across patients and time, heterogeneity across sites and devices, and missingness that carries meaning). The next chapter builds the self-supervised objectives that learn from these data.

Self-Supervised Objectives

A self-supervised objective is a prediction task manufactured from unlabeled data, chosen so that solving it forces an encoder to learn structure that later tasks need. Health data are the setting where this matters most: a wearable fleet produces billions of unlabeled PPG windows, a health system holds hundreds of millions of coded events, and a sleep clinic archives tens of thousands of overnight recordings, while the labels that matter (a diagnosed arrhythmia, a death within a year, an expert-scored apnea event) number in the thousands. Supervised training on the labels alone leaves almost all of the data unused.

Nearly every health foundation model uses one of four tasks, or a combination. Contrastive learning tells matching pairs apart from non-matching ones. Masked reconstruction hides part of the input and fills it back in. Autoregressive prediction forecasts what comes next. Joint-embedding prediction (JEPA) predicts the representation of a hidden part instead of its raw values. Each family fixes what the encoder receives, what it must output and which loss scores it, and each implies a different notion of what is worth remembering.

Four families of self-supervised objectives: contrastive, masked reconstruction, autoregressive and joint-embedding predictive. Contrastive Masked reconstruction Autoregressive Latent prediction (JEPA) two views x, x⁺augment · patient · modality patches / codes15–75% hidden prefix x₁ … xₜtokens, patches or events context block + target blockfrom the same input shared encoder f+ projection head encoder on visible+ light decoder causal transformersees only the past context encodertarget encoder = EMA copy pull positives together,push N−1 negatives apart reconstruct hiddenvalues or codes next token, patch,quantiles or event time predict the target'sembedding, not its values InfoNCEMSE / cross-entropyNLL / pinball / hazardL2 in latent space SimCLR · CLIP · Apple PPGSleepFM · PaPaGei · SensorLM BERT · MAE · BEHRTMOMENT · Moirai · LSM GPT · TimesFM · ChronosCLMBR · MOTOR · CoMET I-JEPA · V-JEPA(early in biosignals) rows: what goes in · what processes it · what it must predict · the loss · representative models
Fig. The four self-supervised objective families: what goes in, what processes it, what it must predict, the loss, and representative models. Many recent models combine two (ECG-FM mixes masked prediction with contrastive learning; SensorLM mixes contrastive and generative captioning). Adapted from the Classic edition.

The families differ less than their names suggest. All of them define two views of the same underlying thing (two windows of one person, the visible and hidden parts of one window, a past and its future) and train the encoder so that one view is informative about the other. What changes is how "informative" is measured: by recognising the partner among distractors, by reproducing its values, by assigning it high probability, or by matching its embedding. The practical differences between published models lie mostly in the tokenizer (Chapter 5) and in what counts as a matching pair, which is why this chapter ends with the choice of positives.

Worked example · W1, W2, W3The chapter traces three reference workloads with illustrative numbers. W1 is a wearable PPG model trained contrastively: 10-second windows of 640 samples at 64 Hz, a 50M-parameter encoder producing 256-dimensional embeddings, InfoNCE with temperature 0.1 and 4,096 anchors per batch, positives drawn from the same participant within 24 hours. W2 is a 120M-parameter decoder-only EHR model trained autoregressively on 310 million events from 2 million patients. W3 is a sleep model over 30,000 polysomnography nights in 30-second epochs across five channel groups, a natural setting for cross-modal and latent-prediction objectives.

The sections proceed from the oldest and most widely used objective (contrastive) through masking and autoregression to latent prediction, and close with the decision that most shapes what a contrastive health model learns: the definition of a positive pair. Chapter 5 then turns to how signals and events become the tokens these objectives operate on.

All four objectives can be written in one template. A data item \(x\) is split or transformed into two views, a source \(u = a(x)\) and a target \(v = b(x)\). An encoder \(f_\theta\) maps the source to an embedding, a head \(g\) maps that embedding to a prediction \(\hat v\), and a loss \(\ell(\hat v, v)\) compares prediction and target. Training minimises \(\mathbb{E}_x[\ell(g(f_\theta(a(x))), b(x))]\). The four families differ in the choice of \(a\), \(b\), \(g\) and \(\ell\):

FamilySource \(u\)Target \(v\)Loss \(\ell\)Chance-level value
Contrastiveone viewwhich of \(N\) candidates is the partnercross-entropy over \(N\) (InfoNCE)\(\log N\)
Maskedvisible patches \(x_{\setminus M}\)hidden values \(x_M\)MSE or cross-entropyvariance of \(x_M\) (MSE)
Autoregressiveprefix \(x_{<t}\)next token \(x_t\)negative log-likelihood\(\log V\) for vocabulary \(V\)
JEPAcontext block \(x_C\)target-encoder embedding of \(x_T\)squared error in latent spaceundefined: target moves

The last column gives the loss of a model that has learned nothing, which is the first number to check in any training curve. It also exposes a structural difference: in the first three families the target is fixed by the data, so the loss has an absolute floor and ceiling; in JEPA the target is produced by a network that is itself changing, so a falling loss is not evidence of learning and collapse must be monitored separately.

Worked example · W1, W2For W1 with 4,096 candidates per anchor, an untrained contrastive model has loss near \(\log 4096 = 8.32\) nats. For W2, with a vocabulary of about 42,074 tokens (42,000 codes, 64 time-gap tokens and 10 value-decile tokens, assuming the deciles are shared across labs), a uniform next-token model has loss \(\log 42{,}074 = 10.65\) nats. A masked model on a unit-variance PPG window that predicts the window mean scores an MSE near the signal variance; in the Level 3 simulation of a noisy 72 bpm sinusoid this is 0.51.

Two further quantities recur across the chapter. The mutual information \(I(u; v)\) between the views bounds how much any of these objectives can extract; contrastive losses estimate a lower bound on it. The invariance induced by the view construction (whatever differs between \(u\) and \(v\) is pushed out of the representation) decides which downstream tasks benefit, and it is set by \(a\) and \(b\), not by the loss.

In code, each objective is a function from a batch of encoder outputs to a scalar loss plus whatever diagnostics reveal failure. Keeping that interface uniform makes it possible to swap objectives behind one training loop and to log comparable health metrics. The chapter's code lives in five small NumPy modules, each with tests that run when the file is executed:

ModuleMain functionInputs (shapes)OutputKey test
contrast.pyinfo_nce(z, zp, tau, pid)anchors \((N, d)\), positives \((N, d)\), participant ids \((N,)\)loss, gradient w.r.t. logits \((N, N)\)random views give \(\approx \log N\)
masked.pymasked_mse(x_hat, x, target)patches \((B, P, p)\), target mask \((B, P)\)scalar MSE over targetssensor gaps never scored
ar.pynext_token_ce, pinballlogits \((B, L, V)\), tokens \((B, L)\)mean NLL; per-quantile lossuniform logits give \(\log V\)
jepa.pytrain, effective_rankviews \((n, D)\), embeddings \((n, d)\)embeddings, loss, rankno stop-gradient collapses
positives.pysample_positiveparticipant ids, timestampsindex of a positive or −1never pairs a window with itself

The chance-level check from the table above is the first test any new objective should pass, because it catches label shifting, masking and normalisation bugs before any GPU time is spent:

import numpy as np
from contrast import info_nce
from ar import next_token_ce

rng = np.random.default_rng(0)
# W1-shaped contrastive batch, untrained encoder: loss should sit near log N.
N, d = 4096, 256
loss, _ = info_nce(rng.normal(size=(N, d)), rng.normal(size=(N, d)), tau=0.1)
print(round(loss, 2), round(np.log(N), 2))     # about 8.5 vs 8.32 (see the InfoNCE section)
# W2-shaped next-token batch with constant logits: exactly log V.
V = 42_074
print(round(next_token_ce(np.zeros((1, 8, V)), rng.integers(0, V, (1, 8))), 3))  # 10.647

An untrained contrastive model scores slightly above \(\log N\) at low temperature, because random cosine similarities divided by 0.1 still vary by several tenths of a nat and the log-sum-exp is convex; a loss well below \(\log N\) at step zero indicates that anchors and positives are leaking into each other (for example, the same window used twice).

At production scale the choice of objective is also a choice of compute profile, failure mode and monitoring. Contrastive training needs large batches and therefore cross-device communication; masked training saves encoder compute by dropping hidden tokens; autoregressive training packs variable-length sequences; JEPA adds a second forward pass through a target network and needs collapse monitoring because its loss is not anchored.

ObjectiveDominant costCharacteristic silent failureFirst metric to watch
Contrastiveencoder on 2 views; all-gather of embeddingsnegatives drawn per device only; shortcut featuresloss relative to \(\log N\); embedding effective rank
Maskedencoder on visible tokens onlylearns local interpolation; gaps scored as targetsMSE relative to a mean predictor, split by mask type
Autoregressivefull causal pass over packed tokenspadding waste; exposure bias in rolloutsper-token NLL by token type; rollout event rates
JEPAcontext pass + target forward passrepresentation collapse with falling lossper-dimension embedding std; effective rank

A pretraining run is accepted on downstream probes, not on its own loss. The standard practice, used throughout this book, is a small fixed canary suite evaluated with frozen embeddings at regular checkpoints: a linear probe is cheap, sensitive to representation quality and comparable across objectives. Its cost is that a linear probe can understate what a fine-tuned model would reach, so a final comparison should include at least one fine-tuned task.

Worked example · W1W1 samples 1% of its 10.8 billion windows per epoch, so an epoch is 108 million anchors, or 26,368 steps at 4,096 anchors per step (108,000,000 / 4,096 = 26,367.2, rounded up to cover the final partial batch); with two views per anchor the encoder runs on 216 million windows per epoch. The canary suite is the linear-probe set from the workload specification on 5,000 labelled participants: AFib AUROC (target 0.93, supervised-from-scratch reference 0.88), age MAE (6.1 years) and resting heart-rate MAE (2.4 bpm). Running it every 2,000 steps on cached embeddings costs one encoder pass over the probe windows, small relative to an epoch. A checkpoint whose contrastive loss improves while AFib AUROC drops by more than the probe's bootstrap interval is treated as a regression, whatever the loss says.

The sections that follow give each objective the full treatment: mechanism, derivation, a tested implementation and the production failure most characteristic of it, ending with positive-pair design, which decides what the contrastive models in Chapters 7 and 8 actually encode.

Contrastive learning and InfoNCE

Definition. Contrastive learning trains an encoder so that two views of the same thing (a positive pair) land close together in embedding space while views of different things (negatives) land far apart. The standard loss, InfoNCE, introduced by van den Oord et al. (2018), turns this into a multiple-choice question: given an anchor, pick its partner out of a set of candidates.

Motivation. Earlier representation learning on signals relied either on labels or on reconstruction. Reconstruction spends model capacity on every detail of the waveform, including sensor noise and baseline wander that no clinical task needs. Contrastive learning avoids that: the encoder only has to keep whatever distinguishes a partner from the distractors, and the designer controls what that is by choosing the pairs.

Mechanism, step by step.

  1. Sample a batch. Draw \(N\) anchors. For each, draw one positive according to a rule (another augmentation of the same window, another window of the same person, a simultaneous recording from another sensor).
  2. Encode. A shared encoder maps every anchor and every positive to a vector. A small projection head (a one- or two-layer network) maps that vector into the space where the loss is computed; after pretraining the head is discarded and the encoder output is used downstream. SimCLR (Chen et al. 2020) showed that the head, strong augmentations and large batches together are what make the method work.
  3. Compare. Normalise every vector to unit length and compute the cosine similarity between each anchor and every positive in the batch, giving an \(N \times N\) table. The diagonal holds true pairs; everything else is a negative, so negatives come free from the batch.
  4. Score. Divide similarities by a temperature (a small positive constant, typically 0.05 to 0.2) and treat each row as a classification over \(N\) candidates whose correct answer is the diagonal. The loss is the cross-entropy of that classification.
  5. Update. Backpropagation pulls each anchor toward its partner and pushes it away from the candidates it currently confuses with the partner, weighting the hardest negatives most.
A batch of eight anchor windows against eight candidate positives; the diagonal holds true positives and two off-diagonal cells are removed because they come from the same participant.candidates: positives of every anchor in the batchp1p2p3p4p5p6p7p8a1a2a3×a4a5a6×a7a8anchorspositive: same participant, another window ≤ 24 hnegative: another participant's positive×removed: a3 and a6 share a participantEach row is a classificationsoftmax over the 8 similarities ÷ temperatureloss = −log probability of the diagonal cellW1 uses 4,096 anchors per batch: each row has one positive and up to 4,095 negatives
Fig. The InfoNCE batch as a matrix. Rows are anchors, columns are the positives of every anchor; each row is a softmax classification whose correct answer is the diagonal. Cells whose column comes from the anchor's own participant are removed because, under a same-participant positive rule, they are not negatives. Eight rows shown; W1 uses 4,096.
Worked example · W1Each W1 batch holds 4,096 anchors, 10-second PPG-plus-accelerometer windows of 640 samples. Each anchor's positive is another window from the same participant within 24 hours. The 50M-parameter encoder maps every window to a 256-dimensional embedding, similarities are divided by a temperature of 0.1, and each of the 4,096 rows is a 4,096-way classification. An untrained encoder scores about 8.5 nats per row, roughly the \(\log 4{,}096 = 8.32\) of guessing. Because 150,000 participants feed a batch of 4,096, about 56 pairs of anchors per batch come from the same participant; their cross cells are not true negatives and are removed from the table.

Comparison with predecessors. CLIP (Radford et al. 2021) applied the same loss symmetrically across two modalities, images and text, and is the template for sensor–text and cross-signal health models. BYOL (Grill et al. 2020) removed negatives entirely, using a slowly updated copy of the encoder as the target; this avoids the false-negative problem below at the cost of needing other means to prevent every input mapping to the same point. SigLIP (Zhai et al. 2023) replaced the row-wise softmax with an independent yes/no decision per cell, which removes the need to normalise over the whole batch and works better at small batch sizes.

Contrast: two health-specific problems. First, negatives can be false negatives: two different patients with the same arrhythmia are pushed apart, and larger batches add more such collisions. This is one reason health models often prefer subject-level or cross-modal positives over augmentations, and why the definition of a positive receives its own section. Second, contrastive training can find shortcuts: any feature that identifies the partner (a device's characteristic noise floor, a time-of-day pattern) solves the task without learning physiology. The Apple biosignal models combined a regularised contrastive loss with momentum training and same-participant positives across about 141K people (Abbaspourazad et al. 2024); PCLR (Diamant et al. 2022) used patient-level positives over more than 3.2 million 12-lead ECGs and reported linear probes that beat training from scratch by 51% on average across tasks and training-set sizes.

Mental model. Contrastive learning is a recognition test whose answer key the designer writes. The encoder learns exactly enough to pass that test, so the choice of pairs and of distractors determines what the representation contains.

The loss. Let \(f_\theta\) be the encoder plus projection head and \(z = f_\theta(x)/\lVert f_\theta(x)\rVert\) the normalised anchor embedding. Let \(z^{+}\) be the embedding of its positive and \(z^{-}_1,\dots,z^{-}_{N-1}\) the negatives (in practice the other positives in the batch). With similarity \(s(a,b) = a^\top b\) (cosine, since vectors are unit length) and temperature \(\tau > 0\), InfoNCE (van den Oord et al. 2018) is

\[ \mathcal{L}_{\text{NCE}} = -\,\mathbb{E}\left[ \log \frac{\exp\big(s(z, z^{+})/\tau\big)}{\exp\big(s(z, z^{+})/\tau\big) + \sum_{j=1}^{N-1} \exp\big(s(z, z_j^{-})/\tau\big)} \right]. \]

It is the cross-entropy of an \(N\)-way softmax whose logits are \(\ell_j = s(z, z_j)/\tau\) and whose correct class is the positive. Writing \(p_j\) for the softmax probability, the gradient with respect to the logits is \(\partial \mathcal{L}/\partial \ell_j = p_j - \mathbb{1}[j = +]\): the positive is pulled with force \(1 - p_+\) and each negative pushed with force \(p_j\), so negatives that currently look like the positive receive most of the gradient. Lower \(\tau\) sharpens the softmax and concentrates this force on the hardest negatives.

Worked example · W1Take \(N = 4{,}096\) and \(\tau = 0.1\). Suppose that midway through training a positive has cosine 0.8 and every negative cosine 0.1. The logits are 8 and 1, so the per-row loss is \(\log(1 + 4095\,e^{1-8}) = \log(1 + 4095 \times 0.000912) = \log 4.73 = 1.55\) nats. At \(\tau = 0.2\) the same similarities give \(\log(1 + 4095\,e^{-3.5}) = 4.83\) nats; at \(\tau = 0.05\), 0.0034 nats. The temperature therefore decides whether a 0.7 cosine margin is treated as a nearly solved row (0.05) or a hard one (0.2), and with it how much gradient continues to flow to rows that are already separated.

Mutual-information view. Draw a positive pair \((x, x^{+}) \sim p(x, x^{+})\) and \(N-1\) negatives independently from \(p(x^{+})\), then shuffle the \(N\) candidates. Because the joint density of the candidate set factorises as \(p(x_i \mid x)\prod_{k \ne i} p(x_k)\), the Bayes-optimal posterior that candidate \(i\) is the positive is

\[ \Pr[i = \text{pos} \mid x, \{x_k\}] = \frac{p(x_i \mid x)/p(x_i)}{\sum_{k=1}^{N} p(x_k \mid x)/p(x_k)}, \]

so the optimal critic \(\exp(s(z, z_k)/\tau)\) is proportional to the density ratio \(p(x_k \mid x)/p(x_k)\). Substituting it yields the bound

\[ I(x; x^{+}) \;\ge\; \log N - \mathcal{L}_{\text{NCE}}, \]

(van den Oord et al. 2018; analysed by Poole et al. 2019). Since \(\mathcal{L}_{\text{NCE}} \ge 0\), the estimate can never exceed \(\log N\), whatever the true mutual information.

The InfoNCE estimate of mutual information is the smaller of log N and the true value; with a true value of 8 nats the cap binds below about 3,000 candidates.0246810122162564,09665,536candidates per anchor N (log scale)natslog Ntrue MI = 8 nats (illustrative)estimate = min(log N, MI)W1: N = 4,096cap 8.32 nats
Fig. The InfoNCE bound \(I \ge \log N - \mathcal{L}\) can never certify more than \(\log N\) nats. With an illustrative true mutual information of 8 nats, any batch with fewer than \(e^8 \approx 2{,}981\) candidates saturates; W1's 4,096 candidates give a cap of 8.32 nats. Redrawn from the Classic edition's computed chart.

Alignment and uniformity. Representation quality does not track the MI estimate closely. Wang & Isola (2020) showed that as \(N \to \infty\)

\[ \mathcal{L}_{\text{NCE}} - \log N \;\to\; -\tfrac{1}{\tau}\,\mathbb{E}\big[s(z,z^{+})\big] + \mathbb{E}_{x}\Big[\log \mathbb{E}_{x^{-}} \exp\big(s(z,z^{-})/\tau\big)\Big]. \]

The first term (alignment) rewards positives that are close; the second, a log-partition, is minimised when embeddings spread uniformly over the unit hypersphere (uniformity). The choice of positives decides what is aligned and therefore what becomes invariant; the temperature trades alignment against uniformity; batch size matters mainly through the quality of the partition estimate.

False negatives. If anchors are drawn uniformly from \(P\) participants, the expected number of anchor pairs in a batch that share a participant is \(\binom{N}{2}/P\). Their cross cells contribute terms that push together-belonging windows apart. Masking them sets those logits to \(-\infty\), i.e. removes them from the denominator.

Worked example · W1With \(N = 4{,}096\) and \(P = 150{,}000\): \(4096 \times 4095 / 2 / 150{,}000 = 55.9\) colliding pairs per batch, i.e. about 112 masked cells out of 16.8 million. The effect on the average loss is small, but every collision is a gradient that directly opposes the positive rule, applied about 56 times per step for the whole run.

Sigmoid variant. SigLIP (Zhai et al. 2023) scores each cell independently, \(\mathcal{L} = -\frac{1}{N}\sum_{i,j} \log \sigma\big(y_{ij}(t\,s_{ij} + b)\big)\) with \(y_{ij} = +1\) on the diagonal and \(-1\) elsewhere, learnable scale \(t\) and bias \(b\). Without a row-wise normaliser it needs no global view of the batch; the authors report that gains from growing the batch diminish quickly and that about 32k is sufficient for their image–text setting.

The implementation follows the matrix picture directly. Inputs are two arrays of shape \((N, d)\): row \(i\) of z is the anchor, row \(i\) of zp its positive. After L2 normalisation, z @ zp.T / tau gives the \((N, N)\) logit matrix; a numerically stable row softmax (subtract the row maximum before exponentiating) gives probabilities; the loss is the mean negative log of the diagonal. The gradient with respect to the logits is the softmax minus the identity, divided by \(N\) for the mean, which an autodiff framework would produce automatically and which the test below verifies by finite differences. Optional participant ids remove same-participant cells from each row.

# InfoNCE for W1: anchors z (N, d) and positives zp (N, d), one positive per anchor.
import numpy as np

def l2norm(x, eps=1e-8):
    return x / (np.linalg.norm(x, axis=1, keepdims=True) + eps)

def info_nce(z, zp, tau=0.1, pid=None):
    """Return (loss, dlogits). Row i: candidates are all N positives; column i is correct.
    pid (N,) optional participant ids: other columns from the same participant are
    removed from the denominator (they are not true negatives)."""
    z, zp = l2norm(z), l2norm(zp)
    logits = z @ zp.T / tau                       # (N, N) cosine / temperature
    if pid is not None:
        same = (pid[:, None] == pid[None, :]) & ~np.eye(len(pid), dtype=bool)
        logits = np.where(same, -np.inf, logits)  # drop false negatives
    m = logits.max(axis=1, keepdims=True)
    p = np.exp(logits - m); p /= p.sum(axis=1, keepdims=True)   # softmax per row
    n = len(z)
    loss = -np.mean(np.log(p[np.arange(n), np.arange(n)] + 1e-12))
    dlogits = (p - np.eye(n)) / n                 # gradient of the mean CE w.r.t. logits
    return loss, dlogits

def align_uniform(z, zp, t=2.0):
    """Wang & Isola (2020) diagnostics on normalized embeddings."""
    z, zp = l2norm(z), l2norm(zp)
    align = np.mean(np.sum((z - zp) ** 2, axis=1))
    d2 = np.sum((z[:, None] - z[None]) ** 2, axis=-1)[np.triu_indices(len(z), 1)]
    uniform = np.log(np.mean(np.exp(-t * d2)))
    return align, uniform

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    N, d, tau = 512, 256, 0.1
    # 1. Unrelated views: loss is close to log N (chance level).
    z, zp = rng.normal(size=(N, d)), rng.normal(size=(N, d))
    loss, _ = info_nce(z, zp, tau)
    assert abs(loss - np.log(N)) < 0.5, loss
    # 2. Perfectly aligned views: loss near 0 (positive dominates every row).
    loss2, _ = info_nce(z, z, tau)
    assert loss2 < 0.05, loss2   # = log(1 + 511 e^{-10} E[e^{s/tau}]) ~ 0.028
    # 3. Gradient check on logits by finite differences (small N).
    zs, zps = rng.normal(size=(6, 8)), rng.normal(size=(6, 8))
    zs, zps = l2norm(zs), l2norm(zps)
    def ce_from_logits(L):
        m = L.max(1, keepdims=True); P = np.exp(L - m); P /= P.sum(1, keepdims=True)
        return -np.mean(np.log(np.diag(P)))
    L = zs @ zps.T / tau; _, g = info_nce(zs, zps, tau)
    num = np.zeros_like(L); h = 1e-5
    for i in range(6):
        for j in range(6):
            E = np.zeros_like(L); E[i, j] = h
            num[i, j] = (ce_from_logits(L + E) - ce_from_logits(L - E)) / (2 * h)
    assert np.allclose(num, g, atol=1e-6)
    # 4. Same-participant masking. Windows 0 and 1 come from the same participant and
    #    look alike, so each row has two near-equal candidates: loss ~ log 2 on those rows.
    e = np.eye(4, 16); e[1] = e[0] + 0.01 * e[3]           # 4 windows, 16-d
    pid = np.array([7, 7, 8, 9])
    l_nomask, _ = info_nce(e, e, tau); l_mask, _ = info_nce(e, e, tau, pid)
    assert abs(l_nomask - 0.5 * np.log(2)) < 0.01 and l_mask < 1e-3
    # 5. Bound: the MI estimate log N - loss never exceeds log N.
    print(f"chance loss {loss:.3f} vs log N {np.log(N):.3f}; aligned {loss2:.4f}")
    print(f"masking same-participant column: {l_nomask:.4f} -> {l_mask:.4f}")
    print("align/uniform random:", [round(float(v), 3) for v in align_uniform(z, zp)])
    print("log 4096 =", round(np.log(4096), 3))
    print("all contrast tests passed")

Running the file prints:

chance loss 6.428 vs log N 6.238; aligned 0.0278
masking same-participant column: 0.3465 -> 0.0001
align/uniform random: [1.999, -3.97]
log 4096 = 8.318
all contrast tests passed

Each test isolates one property. Test 1 confirms the chance level: unrelated 256-dimensional views give about \(\log N\) (slightly above it, because random logits at \(\tau = 0.1\) have a standard deviation near 0.6). Test 2 shows that identical views give near-zero loss but not exactly zero: with 511 negatives at random cosine, \(\log(1 + 511\,e^{-10}\,\mathbb{E}[e^{s/\tau}]) \approx 0.028\). Test 3 checks the analytic gradient. Test 4 builds two near-identical windows from participant 7: without masking each of their rows faces two equally good candidates and pays \(\log 2\); the mean over four rows is \(0.5 \log 2 = 0.347\), and masking removes it.

Worked example · W1For a W1 step, z and zp are \((4096, 256)\) and the logit matrix is \(4096 \times 4096\), 64 MiB in float32: small next to the encoder activations of 8,192 windows. pid holds participant ids so that the expected 56 same-participant collisions are masked.

Debugging. Four checks catch most errors. (1) If step-zero loss is far below \(\log N\), positives leak into anchors (duplicate windows, or no normalisation and one huge-norm vector). (2) If the loss falls but the alignment term stays near 2 (the value for random unit vectors), the model is matching by a shortcut that does not move embeddings together, often a bug in which column is labelled correct. (3) If a row contains -inf everywhere except the diagonal, a participant id array is constant; the loss will read zero. (4) Uniformity rising toward 0 means embeddings are collapsing onto a small region.

Problem: the batch the loss sees is not the batch the configuration states. Contrastive quality depends on the number and difficulty of negatives, but in data-parallel training each device computes the loss on its own shard unless embeddings are explicitly gathered across devices. A run configured for 4,096 anchors may silently train with 64 candidates per row.

Why it matters. With \(N\) candidates the loss cannot certify more than \(\log N\) nats of shared information and, more practically, easy negatives stop producing gradient early. Fine distinctions (a pulse shape associated with arrhythmia versus one associated with age) are only learned when negatives are hard enough to require them.

Root cause. A per-device loss is the default in most frameworks; a correct global loss requires an all-gather of embeddings with gradients routed back to the owning device, and a participant-id gather for false-negative masking.

Per-device contrastive loss sees 64 candidates per row; gathering embeddings across 64 devices restores 4,096.A. Per-device loss (the silent default)Device k64 anchors, 64 positivesLogits 64 × 6463 negatives per rowLoss cap log 64= 4.16 natsB. Global loss with all-gatherDevices 1 … 6464 anchors eachAll-gather4,096 × 256 positives + idsLogits 64 × 4,096per device; mask same idCap log 4,096= 8.32 natsgradients flow back only through each device's own rows and its local share of the gathered columns
Fig. Where the negatives come from in data-parallel training (W1, illustrative 64 devices × 64 anchors). Without an all-gather each row competes against 64 candidates; with it, against 4,096, and same-participant masking can use the gathered participant ids.
Worked incident · W1

Symptom. After a cluster migration (illustrative: 64 accelerators, 64 anchors each), training loss settles near 0.9 nats instead of the previous run's level, and the AFib linear probe falls from 0.93 to 0.90 AUROC (illustrative values) while age MAE barely moves.

Measurements that separate causes. (a) Step-zero loss is 4.2 nats, matching \(\log 64 = 4.16\) rather than \(\log 4096 = 8.32\): the denominator holds 64 candidates. (b) Mean negative cosine within the logged rows is high and stable while positive cosine rises, consistent with too few hard negatives. (c) A data-loader change would also shift age MAE; it did not, which argues against a data cause.

Remedy. Gather embeddings and participant ids from all devices before computing logits (each device computes its 64 rows against all 4,096 columns), keep the local rows' gradient path, and mask same-participant columns globally. Cost: an all-gather of \(4096 \times 256\) bf16 values (2 MiB) per view per step and a \(64 \times 4096\) logit block per device, both small next to encoder compute.

Validation. Step-zero loss returns to about 8.5 nats; the canary AFib probe recovers to within its bootstrap interval of 0.93 after the same number of steps. If the probe does not recover while the loss does, the hypothesis is weakened and the next suspect is a shortcut feature (below).

Problem: shortcut features. Under a same-participant rule, any stable per-person signal solves the task: a device's noise floor, a fixed wear position, the local time at which a person usually wears the watch. The diagnosis is a set of nuisance probes: linear probes from frozen embeddings to device model, firmware version, wrist side and hour of day. High accuracy on a nuisance probe that rises over training, combined with a flat clinical probe, indicates a shortcut. Remedies, in order of cost: per-window normalisation that removes the offending statistic; positives drawn across devices when participants own more than one; an adversarial or decorrelation penalty against the nuisance label. Each removes information, so validate with the clinical canary suite: the fix is confirmed if nuisance accuracy falls and AFib AUROC holds or rises; it is refuted if AFib falls with it, which means the nuisance was entangled with physiology.

Temperature. A fixed \(\tau = 0.1\) is a common default; a learnable temperature can drift to very small values and destabilise training. Logging the effective temperature and capping it is cheaper than diagnosing the resulting loss spikes.

MetricHealthy W1 range (illustrative)Alert whenLikely cause
Step-zero loss≈ 8.5 nats (\(\log 4096\) + noise)< 7 or ≈ \(\log\) per-device batchleakage, or no all-gather
Uniformity (\(t=2\))steady, well below 0rising toward 0collapse onto a region
Effective rank of 256-d embeddingsstable or risingfalls by > 30%dimensional collapse
Nuisance probes (device, hour)low, flatrisingshortcut feature
Canary AFib AUROC≈ 0.93drop beyond bootstrap CIany of the above

The contrastive loss is the only objective in this chapter whose negatives are a design choice. The next section turns to masked reconstruction, which needs no negatives at all and instead asks the encoder to reproduce what was hidden.

Masked reconstruction

Definition. Masked modeling hides part of the input and trains a network to reconstruct the hidden part from the rest. For discrete tokens such as words or diagnosis codes the network predicts which token was hidden; for continuous signals cut into short patches it predicts the hidden samples' values.

Motivation. BERT (Devlin et al. 2018) established masked-token pretraining for text, and EHR models such as BEHRT and Med-BERT carried it to sequences of diagnosis codes. For continuous data the decisive step was the masked autoencoder (MAE) of He et al. (2022), which made a high mask ratio (75% for images) both the source of difficulty and a compute saving, because the encoder processes only visible patches. Unlike contrastive learning, masking needs no definition of a positive pair and no negatives, and its target is fixed by the data, so the loss is directly interpretable.

Mechanism, step by step.

  1. Patchify. Cut the input into tokens: short fixed-length segments of a waveform, or individual codes in a record.
  2. Choose a mask. Select a fraction of tokens to hide, at random or in contiguous spans.
  3. Encode the visible tokens. The encoder, usually a transformer, receives only the visible tokens with their position information.
  4. Decode. A light decoder receives the encoder outputs plus a learned placeholder ("mask token") at every hidden position and predicts the hidden content. The decoder is discarded after pretraining.
  5. Score only the hidden positions. The loss compares predictions with the true hidden values, typically by squared error for signals or cross-entropy for codes.

Time series are more redundant locally than text, so the mask ratio and patch length must be tuned to the signal rather than copied from text models: MOMENT, for example, masks about 30% of 8-step patches (Goswami et al. 2024). Masking is also the natural objective when the downstream task is imputation, which is why Google's wearable model LSM uses it (Narayanswamy et al. 2025).

Real gaps. Wearable data arrive with holes: the watch is charging, off-wrist, or the optical signal is unusable. A naive pipeline fills those holes (with zeros or interpolation) and then treats the filled values as data, which teaches the model to reproduce the filler. LSM-2 (Narayanswamy and Xu, 2025; Xu et al. 2025) instead treats natural gaps as inherited masks: gaps are hidden from the encoder exactly like artificially masked tokens, but they are never scored. Its adaptive and inherited masking (AIM) drops a fixed number of masked tokens before the encoder to save compute and handles the variable remainder with attention masking. Trained on 40 million hours from over 60,000 participants, LSM-2 outperformed its predecessor on classification, regression and reconstruction tasks and degraded less when sensors or parts of the day were removed.

A 10-second W1 window as 40 patches: 8 visible, 24 hidden for reconstruction, and 8 lost to an inherited sensor gap; the encoder sees only the visible patches and the loss covers only the hidden ones.one 10-s window = 640 samples = 40 patches of 16 samplesvisible (8)hidden target (24)sensor gap (8)Encoderruns on 8 visible patchesLight decoderadds 24 mask tokensLossMSE on 24 hidden patches;gap patches never scored75% of the 32 observed patches are hidden; the gap is masked but carries no target
Fig. Masked reconstruction on a W1 window with an inherited gap (the last 8 patches, watch off-wrist). Artificial masking is drawn only among observed patches; the gap is excluded from the encoder and from the loss, the treatment LSM-2 calls adaptive and inherited masking.
Worked example · W1A W1 window of 640 samples becomes 40 patches of 16 samples (a quarter of a second each). In the window shown, the watch came off the wrist for the last 2 seconds, so 8 patches are an inherited gap and 32 are observed. Hiding 75% of the observed patches leaves 8 visible patches for the encoder and 24 reconstruction targets. The gap patches are invisible to the encoder and absent from the loss. Across W1, 38% of hours have no PPG at all; those hours supply no windows, while shorter gaps inside windows are handled by the inherited mask.

Comparison. Contrastive learning keeps only what distinguishes a window from other windows; masked reconstruction keeps whatever predicts the hidden values, including fine waveform detail. That is an advantage for imputation and signal-quality tasks and a cost when much of the signal is noise: the encoder spends capacity predicting artefacts. The objectives are not ranked once and for all. Apple's wearable behaviour model reported that masked autoencoding performed poorly in initial experiments on hourly behavioural features and used a contrastive loss instead (Erturk et al. 2025), whereas LSM-2 builds on masking. Hybrids exist: ECG-FM combines masked prediction with a contrastive term.

Mental model. Masked reconstruction is a fill-in-the-blank exam. The mask ratio sets its difficulty, the patch size sets what a blank is, and the treatment of real gaps decides whether the exam ever asks about something that was never recorded.

The loss. Let \(x = (x_1, \dots, x_P)\) be a sequence of \(P\) patches, each a vector of \(p\) samples. Let \(O \subseteq \{1,\dots,P\}\) be the observed patches (all patches if there are no gaps) and \(M \subseteq O\) the artificially masked targets. The encoder \(f_\theta\) sees \(x_{O \setminus M}\); a decoder \(g_\phi\) predicts every patch. With continuous patches the loss is the mean squared error over targets (He et al. 2022):

\[ \mathcal{L}_{\text{MAE}} = \frac{1}{|M|}\sum_{i \in M} \frac{1}{p}\big\lVert \hat{x}_i - x_i \big\rVert_2^2, \qquad \hat{x} = g_\phi\big(f_\theta(x_{O \setminus M})\big). \]

For discrete codes the summand becomes \(-\log p_\phi(x_i \mid x_{O\setminus M})\). The inherited gaps \(\{1..P\} \setminus O\) appear neither in the encoder input nor in the sum.

What the minimiser learns. Under squared error the optimal prediction is the conditional mean \(\mathbb{E}[x_M \mid x_{O\setminus M}]\), and the minimal loss is the conditional variance averaged over targets. A model that ignores the input entirely can at best predict the unconditional mean and scores the signal variance; the gap between that baseline and the trained loss measures how much the visible context explains. Because the conditional mean blurs over uncertain detail, MAE reconstructions of noisy signals look smooth, and the encoder is rewarded for predicting the predictable part.

Worked example · W1For a simulated unit-amplitude 72 bpm pulse plus noise of standard deviation 0.05, the mean predictor scores 0.51 (the variance of a sinusoid, 0.5, plus noise). A trained model that reaches 0.05 explains about 90% of the variance of hidden patches. With \(|O| = 32\) and ratio 0.75, \(|M| = 24\) and the encoder sees 8 patches; on a gap-free window \(|M| = 30\) and the encoder sees 10.

Compute. Self-attention over \(n\) tokens costs \(O(n^2 d)\) and the feed-forward layers \(O(n d^2)\). Encoding only \(n_v = (1 - r)\,n\) visible tokens at mask ratio \(r\) reduces attention cost by \((1-r)^{-2}\) and feed-forward cost by \((1-r)^{-1}\).

Worked example · W1At \(r = 0.75\) on a 40-patch window the encoder sees 10 tokens: attention cost falls from \(40^2 = 1{,}600\) to \(10^2 = 100\) pairwise interactions (16×) and feed-forward cost by 4×. The decoder runs on all 40 positions but is shallow, so the total step is several times cheaper than encoding the full window.

Why high ratios. If the hidden patch is adjacent to visible ones, interpolation solves it: for a smooth signal sampled at 64 Hz, a 16-sample patch flanked by visible neighbours is nearly determined by them. Raising \(r\), or masking contiguous spans of length \(k\) patches, increases the distance between a target and its nearest visible neighbour and forces the encoder to use longer-range structure such as the pulse period. The ratio trades difficulty against information: at \(r \to 1\) too little context remains for any prediction above the mean.

Per-patch normalisation. MAE implementations often normalise each target patch by its own mean and standard deviation before computing the loss, so that patches with large amplitude do not dominate. For physiological signals this choice discards absolute level (for example the amplitude of a pulse), which can be informative; it is an explicit modelling decision, not a detail.

The code separates three concerns: turning a window into patches, drawing masks that respect inherited gaps, and computing the loss only where it is defined. Shapes: a batch of windows x is \((B, T)\); patchify returns \((B, P, p)\) with \(P = T/p\); masks are boolean \((B, P)\). The essential rule is that artificial targets are sampled only among observed patches, and the encoder's token set is observed-and-not-hidden.

# Masked reconstruction for a W1 window: 640 samples at 64 Hz -> 40 patches of 16 samples.
import numpy as np

def patchify(x, p=16):
    """x: (B, T) -> (B, T//p, p)."""
    B, T = x.shape
    assert T % p == 0
    return x.reshape(B, T // p, p)

def make_masks(observed, ratio, rng):
    """observed: (B, P) bool, False where the sensor had no data (inherited gap).
    Returns target mask (B, P): artificially hidden AND observed patches.
    Artificial masking is drawn only among observed patches so the ratio
    applies to real data; inherited gaps are never targets."""
    B, P = observed.shape
    target = np.zeros((B, P), dtype=bool)
    for b in range(B):
        idx = np.flatnonzero(observed[b])
        k = int(round(ratio * len(idx)))
        target[b, rng.choice(idx, size=k, replace=False)] = True
    return target

def masked_mse(x_hat, x, target):
    """Mean squared error over target patches only. x_hat, x: (B, P, p)."""
    err = ((x_hat - x) ** 2).mean(axis=-1)          # (B, P) per-patch MSE
    return (err * target).sum() / max(target.sum(), 1)

def encoder_tokens(observed, target):
    """Tokens the encoder actually sees: observed and not hidden."""
    return observed & ~target

if __name__ == "__main__":
    rng = np.random.default_rng(1)
    B, T = 8, 640
    t = np.arange(T) / 64.0
    x = np.sin(2 * np.pi * 1.2 * t)[None].repeat(B, 0) + 0.05 * rng.normal(size=(B, T))  # ~72 bpm pulse
    xp = patchify(x); assert xp.shape == (8, 40, 16)
    observed = np.ones((B, 40), dtype=bool); observed[0, 25:] = False   # window 0 loses its last 15 patches
    target = make_masks(observed, 0.75, rng)
    assert not (target & ~observed).any()               # gaps are never targets
    assert target[1].sum() == 30 and target[0].sum() == 19   # 75% of 40 and of 25 observed
    vis = encoder_tokens(observed, target)
    assert vis[1].sum() == 10 and vis[0].sum() == 6
    # A prediction that is perfect on targets but garbage in the gap has zero loss.
    x_hat = xp.copy(); x_hat[0, 25:] = 99.0
    assert masked_mse(x_hat, xp, target) == 0.0
    # Predicting the per-window mean gives roughly the signal variance (~0.5).
    mean_pred = np.repeat(xp.mean(axis=(1, 2), keepdims=True), 40, 1).repeat(16, 2)
    print("mean-predictor MSE:", round(masked_mse(mean_pred, xp, target), 3))
    print("encoder tokens, full window:", vis[1].sum(), "of 40; attention cost ratio",
          round((40 / vis[1].sum()) ** 2, 1))
    print("all masked tests passed")

Output:

mean-predictor MSE: 0.51
encoder tokens, full window: 10 of 40; attention cost ratio 16.0
all masked tests passed

The tests assert the properties that the W1 example relies on: a window with 25 observed patches gets 19 targets and 6 visible tokens; a complete window gets 30 and 10; no target ever falls in a gap; and a prediction that is wrong only inside the gap scores exactly zero, which proves the gap does not enter the loss. The mean-predictor MSE gives the baseline against which a trained model's loss is read.

From mask to transformer. In a real encoder, the variable number of visible tokens per window is handled in two ways that LSM-2's AIM combines. Token dropout gathers a fixed number of visible tokens per window into a dense tensor (cheap, but requires the same count in every row). Attention masking keeps a padded tensor and sets attention logits to \(-\infty\) for hidden or missing keys (flexible, but pays compute for padded positions). A practical scheme drops the fixed artificial fraction and attention-masks the variable inherited remainder:

def attention_bias(keep):           # keep: (B, P) bool, True = token visible to the encoder
    return np.where(keep[:, None, :], 0.0, -np.inf)   # (B, 1, P) added to attention logits

Debugging. If the loss is close to the mean-predictor baseline after many steps, check that positional information reaches the decoder (without it, mask tokens are indistinguishable). If the loss is suspiciously low, check whether interpolated gap values are leaking into targets or whether the mask is applied after normalisation statistics that were computed on the full window (the visible patches then encode the hidden ones' mean).

Problem: a low reconstruction loss that does not transfer. Masked models can reach excellent reconstruction by local interpolation while learning little about longer-range physiology, and the loss alone cannot distinguish the two.

Why it matters. Clinical targets such as rhythm irregularity live at the scale of several beats, not a quarter-second patch. An encoder that solves the task from immediate neighbours has no incentive to represent beat-to-beat structure.

Root cause. Random patch masking at a modest ratio leaves most targets adjacent to a visible patch. Smooth, oversampled signals make that neighbour almost sufficient.

Worked incident · W1

Symptom. A masked variant of W1 (illustrative configuration: random masking at 40%, 16-sample patches) reaches a reconstruction MSE of about 10% of the mean-predictor baseline, but its AFib linear probe trails the contrastive model's 0.93 by a wide margin (illustrative).

Measurements that separate causes. (a) Split validation MSE by distance from the target to the nearest visible patch: error is tiny at distance 1 and rises steeply at distance 3 or more, showing the model relies on neighbours. (b) Probe accuracy for a beat-level quantity (inter-beat interval variability) is low while a window-level quantity (mean amplitude) is high. (c) The loss on windows with long inherited gaps is no worse than on complete windows, which rules out gap handling as the cause.

Remedy. Raise the ratio to 75% and mask contiguous spans of 4 patches (one second), so that a typical target is at least one second from visible data. Encoder compute falls (10 visible tokens instead of 24), which pays for a slightly longer schedule.

Validation. The hypothesis is supported if span-masked training raises the beat-level probe and the AFib probe while the mean-amplitude probe holds. It is weakened if MSE rises but probes do not improve, which would point to the patch size or to normalisation discarding the relevant amplitude information.

Problem: gaps treated as data. Zero-filled gaps produce windows in which a run of exact zeros is easy to reconstruct, deflating the loss and teaching the model that "zero" is a physiological state. Diagnosis: report MSE separately for targets inside, next to and far from inherited gaps, and the fraction of training targets that coincide with filled values (it should be zero). Remedy: inherited masking as above; at inference, apply the same rule so the encoder never sees filler. Cost: variable token counts per window complicate batching; bucketing windows by observed-patch count keeps padding overhead low. Validation: the robustness test LSM-2 reports, removing whole sensors or hours at evaluation time and measuring degradation, is the direct check.

Problem: compute imbalance. With inherited gaps, visible-token counts vary per window, and a padded batch pays for the largest. If a batch mixes complete windows (10 visible tokens at 75%) with heavily gapped ones (2 to 3 tokens), dropping to a fixed count wastes some windows' context while padding to the maximum wastes compute on others. The AIM compromise is to drop a fixed artificial fraction and attention-mask the rest; the trade-off is measured by tokens processed per second against probe quality at a fixed budget.

MetricWhat it showsAlert when
MSE / mean-predictor MSEvariance explained by context< 0.05 early (leakage) or > 0.8 late (no learning)
MSE by distance to nearest visible patchreliance on interpolationflat near zero at distance 1, steep beyond
MSE inside vs outside inherited gapsgap handlingany target inside a gap
Visible tokens per window (p5/p50/p95)batching efficiencyp5 below 2
Canary probes (AFib, age, resting HR)transferdrop beyond bootstrap CI

Masking predicts values that were present at the same time. The next objective predicts values that have not yet happened, which is what forecasting and timeline simulation require.

Autoregressive and next-patch prediction

Definition. An autoregressive model predicts each element of a sequence from the elements before it. Trained over a whole sequence, it learns a probability for every possible next element given any history, and therefore a probability for the whole sequence.

Motivation. Next-token prediction is the objective behind GPT (Radford et al. 2018) and modern language models. It has two properties no other family in this chapter shares. Every position in every sequence is a training example, so supervision is dense. And the trained model can generate: sampling one element, appending it and repeating produces a plausible future, which is what forecasting and simulation of patient timelines need (Chapter 9).

Mechanism, step by step.

  1. Tokenise. Turn the record into an ordered sequence: clinical codes with interleaved time-gap and value tokens for an EHR, or fixed-length patches of a signal (Chapter 5).
  2. Shift. The target sequence is the input shifted one position left: position \(t\) is trained to predict the token at \(t+1\).
  3. Mask the future. A causal transformer lets each position attend only to itself and earlier positions, so no position can see its own target.
  4. Score. An output head turns each position's state into a prediction of the next element, and the loss rewards giving the true next element high probability.
  5. Generate (optional). At inference, sample the next element, append it and continue, producing trajectories from which risks can be estimated by counting.
Next-event prediction over a W2 patient timeline: the causal transformer reads tokens up to position t and predicts the token at t plus one.E11.9 diabetesGAP 1–3 dGAP 1–3 dLAB HbA1cLAB HbA1cDECILE 9DECILE 9RX metforminRX metforminGAP 30–90 dGAP 30–90 dnext: ?Causal transformerposition t attends only to positions ≤ tinput tokens x₁ … x₆targets x₂ … x₇ (shifted by one); loss = −log p(target)
Fig. Autoregressive pretraining on a W2 timeline. The targets are the inputs shifted by one position; every position is a training example, and a causal mask stops any position from seeing its own target. Token names are illustrative.

Output heads differ by data type. For discrete events (CLMBR, Foresight and CoMET over EHR codes) the head is a softmax over the vocabulary. For continuous series the head varies: Chronos scales each series and quantises values into bins so it can keep a softmax and cross-entropy (Ansari et al. 2024); Lag-Llama outputs the parameters of a probability distribution; TimesFM predicts a whole output patch at once (Das et al. 2023); Moirai 2.0 predicts nine quantiles of the future value (Liu et al. 2025). Predicting quantiles means outputting, for example, the value that the truth should fall below 10%, 50% and 90% of the time, which gives an uncertainty band without assuming a distribution's shape.

Worked example · W2A W2 patient timeline reads, in tokens, as a type 2 diabetes code, a 1–3 day gap token, an HbA1c lab token, a value-decile token (decile 9), a metformin prescription token and a 30–90 day gap token. Each position predicts the next: after the HbA1c token the model must spread probability over the ten decile tokens; after the gap token it must predict the next clinical event. The 120M-parameter decoder reads up to 4,096 tokens, enough for the 95th-percentile patient's 1,450 events with their interleaved gap and value tokens under the assumption of roughly two tokens per event (about 2,900 tokens); at three tokens per event the same patient would need about 4,350 tokens and be truncated. A model that knows nothing assigns each of about 42,074 tokens equal probability and pays \(\log 42{,}074 = 10.65\) nats per position.

Scale. For EHR data the strongest recent evidence is CoMET (Waxler et al. 2025): decoder-only models up to 1 billion parameters trained on 115 billion medical events from 118 million patients in Epic Cosmos, with power-law relations between performance and compute, data and model size, the same pattern language models show.

Comparison and contrast. Masked models see context on both sides of a gap and usually produce better single-time-point representations; autoregressive models see only the past but are the only family that can roll forward. That advantage carries a characteristic weakness, exposure bias: during training every prediction is conditioned on true history, but during generation it is conditioned on the model's own earlier samples, so small errors compound over long horizons. A one-year simulated EHR trajectory may contain over a thousand sampled tokens.

Mental model. An autoregressive model is a forecaster that has practised one step ahead at every point of every history. It is only as good over many steps as its one-step errors allow.

Factorisation. Any joint distribution over a sequence \(x_1,\dots,x_T\) factors by the chain rule as \(p(x_{1:T}) = \prod_{t=1}^{T} p(x_t \mid x_{<t})\). An autoregressive model parameterises each factor with a network \(p_\theta\) and maximises the log-likelihood, i.e. minimises

\[ \mathcal{L}_{\text{AR}} = -\frac{1}{T}\sum_{t=1}^{T} \log p_\theta\big(x_t \mid x_{<t}\big). \]

For a vocabulary of size \(V\) the per-token loss of a uniform model is \(\log V\), and \(\exp(\mathcal{L}_{\text{AR}})\), the perplexity, is the effective number of equally likely choices the model is still unsure between.

Worked example · W2With \(V \approx 42{,}074\), the uniform loss is 10.65 nats (perplexity 42,074). A model at 2.5 nats per token (illustrative) has perplexity \(e^{2.5} \approx 12\): on average it is as uncertain as a choice among 12 equally likely next tokens. Averages hide structure: after a lab token only ten decile tokens are plausible, so loss there should approach \(\log 10 = 2.30\) or less, while the first event after a long gap is genuinely uncertain. Reporting loss by token type separates these.

Continuous outputs: the pinball loss. A quantile head outputs \(\hat y_q\) for levels \(q \in (0,1)\) and is trained with

\[ \ell_q(y, \hat{y}_q) = \max\big(q\,(y - \hat{y}_q),\; (q-1)\,(y - \hat{y}_q)\big). \]

Under-prediction (\(y > \hat y_q\)) costs \(q\) per unit, over-prediction costs \(1-q\) per unit. Setting the derivative of the expected loss to zero gives \(q - \Pr[y \le \hat y_q] = 0\), so the minimiser is the \(q\)-quantile of the predictive distribution. Averaged over a dense grid of levels, the pinball loss approximates (up to a factor of 2) the continuous ranked probability score (CRPS) that forecasting benchmarks report.

Pinball loss as a function of the residual for quantiles 0.1, 0.5 and 0.9.0369-10-50510residual u = y − ŷ (bpm)lossq = 0.9q = 0.5q = 0.1ŷ = 58, y = 62: 3.6ŷ = 66: 0.4
Fig. Pinball loss for three quantile levels. The 0.9-quantile head pays 0.9 per bpm when the truth lies above the forecast and 0.1 per bpm when it lies below, so it settles where 90% of outcomes fall below it. Points: W1 resting heart rate of 62 bpm with forecasts of 58 and 66 bpm.
Worked example · W1A forecast of next-day resting heart rate has truth \(y = 62\) bpm. For the 0.9-quantile head, a forecast of 58 gives \(\max(0.9 \times 4, -0.1 \times 4) = 3.6\); a forecast of 66 gives \(\max(0.9 \times (-4), 0.1 \times 4) = 0.4\). For the median head (\(q = 0.5\)) both errors cost 2.0. The asymmetry is what makes the 0.9 head sit high.

Teacher forcing and exposure bias. Training conditions on true prefixes (teacher forcing), so the loss measures one-step error. Under generation, an error at step \(t\) changes the prefix for all later steps. A crude illustration: if each step's sample lies in a region the model handles well with probability \(1 - \epsilon\) independently, a \(T\)-step rollout stays in that region with probability \((1-\epsilon)^T\); with \(\epsilon = 0.001\) and \(T = 1{,}450\) that is \(e^{-1.45} \approx 0.23\). Real errors are neither independent nor fatal, but the exponent explains why rollout quality must be measured directly rather than inferred from the one-step loss.

Patch outputs. TimesFM predicts an output patch longer than its input patch, so a horizon of \(H\) steps needs \(\lceil H / h_{\text{out}} \rceil\) autoregressive calls rather than \(H\), reducing the number of compounding steps (Das et al. 2023).

The two functions that matter are the shifted cross-entropy and the pinball loss. The shift is where most bugs occur: logits at position \(t\) are compared with the token at \(t+1\), so the last logit and the first token are dropped. Padding positions (here id −1) are excluded by a validity mask so that short sequences in a batch do not dilute the average. Shapes: logits \((B, L, V)\), tokens \((B, L)\), output a scalar.

# Autoregressive objectives: next-token cross-entropy (W2 events) and pinball loss (forecast heads).
import numpy as np

def next_token_ce(logits, tokens, pad_id=-1):
    """logits: (B, L, V) produced at positions 0..L-1; tokens: (B, L).
    Position t predicts token t+1, so drop the last logit and the first token."""
    lg, y = logits[:, :-1], tokens[:, 1:]
    m = lg.max(-1, keepdims=True)
    logp = lg - m - np.log(np.exp(lg - m).sum(-1, keepdims=True))   # log-softmax
    valid = y != pad_id
    nll = -np.take_along_axis(logp, np.where(valid, y, 0)[..., None], -1)[..., 0]
    return (nll * valid).sum() / valid.sum()

def causal_mask(L):
    """True where attention is allowed: query t may see keys 0..t."""
    return np.tril(np.ones((L, L), dtype=bool))

def pinball(y, yq, q):
    """Quantile (pinball) loss; y: (...,), yq: (..., Q), q: (Q,)."""
    u = y[..., None] - yq
    return np.maximum(q * u, (q - 1) * u)

if __name__ == "__main__":
    rng = np.random.default_rng(2)
    V = 42_074   # W2: 42,000 codes + 64 gap tokens + 10 shared value-decile tokens (assumed shared)
    tokens = rng.integers(0, V, size=(2, 9)); tokens[1, 6:] = -1     # second sequence padded
    ce = next_token_ce(np.zeros((2, 9, V)), tokens)
    assert abs(ce - np.log(V)) < 1e-9                    # uniform model = log V nats
    print("uniform next-event CE:", round(ce, 3), "nats = log", V)
    M = causal_mask(4); assert M[1, 0] and not M[0, 1]
    # W1 resting-HR forecast at q = 0.9 with truth 62 bpm.
    q = np.array([0.1, 0.5, 0.9])
    print("pinball, forecast 58:", pinball(np.array(62.0), np.array([58.0] * 3), q))
    print("pinball, forecast 66:", pinball(np.array(62.0), np.array([66.0] * 3), q))
    assert np.isclose(pinball(np.array(62.0), np.array([58.0]), np.array([0.9]))[0], 3.6)
    # The minimiser of mean pinball loss is the empirical quantile.
    ys = rng.normal(60, 5, size=20_000); grid = np.linspace(45, 75, 3001)
    best = grid[np.argmin([pinball(ys, np.array([g]), np.array([0.9])).mean() for g in grid])]
    assert abs(best - np.quantile(ys, 0.9)) < 0.05
    print("argmin of q=0.9 pinball:", round(best, 2), "empirical 0.9-quantile:", round(np.quantile(ys, 0.9), 2))
    print("all ar tests passed")

Output:

uniform next-event CE: 10.647 nats = log 42074
pinball, forecast 58: [0.4 2.  3.6]
pinball, forecast 66: [3.6 2.  0.4]
argmin of q=0.9 pinball: 66.42 empirical 0.9-quantile: 66.42
all ar tests passed

The tests mirror the Level 2 claims: constant logits give exactly \(\log V\) even with padded positions; the causal mask lets position 1 see position 0 but not vice versa; the pinball values match the hand calculation; and minimising the mean pinball loss over a grid recovers the empirical 0.9-quantile of simulated heart rates (mean 60, standard deviation 5).

Worked example · W2A W2 batch of 32 sequences at context 4,096 has logits of shape \((32, 4096, 42074)\): about 5.5 billion values, 22 GB in float32. Production code therefore never materialises full logits at once; it computes the loss in chunks of positions, or fuses the final projection with the cross-entropy so only the per-position log-sum-exp and the target logit are kept.

Debugging. A loss that falls almost to zero within a few hundred steps means the causal mask is missing or the shift is wrong, so the model reads its target. A loss stuck at \(\log V\) usually means targets are misaligned with logits by one position in the other direction. Report loss by token class (codes, gap tokens, value tokens); a model that does well on value tokens and poorly on codes is learning the format, not the clinical content.

Problem: padding waste. Patient timelines vary enormously in length. Padding every sequence to the context length spends most compute on padding.

Why it matters and root cause. Attention and feed-forward costs scale with the padded length, not the real one. In W2 the median patient has 96 events and the 95th percentile 1,450; padded to 4,096 tokens, a median sequence of a few hundred tokens uses well under 10% of its slot.

Remedy. Sequence packing concatenates several patients into one 4,096-token row, with a block-diagonal attention mask (or document-boundary resets) so that no patient attends to another, and position ids restarting per patient. Cost: a more complex mask and a loader that bins sequences by length. Validation: tokens of real data per step should approach the row capacity, and per-patient loss should be identical whether the patient is packed or alone (a unit test with one packed row and the same patients run separately).

Worked incident · W2

Symptom. After packing was introduced, validation loss improved, but 1-year mortality AUROC from the fine-tuned head fell from 0.89 to 0.86 and calibration ECE rose from 0.03 to 0.05 (illustrative drift values against the W2 specification).

Measurements that separate causes. (a) Per-patient loss for the same patients computed packed versus unpacked differs, so information is crossing patient boundaries. (b) The improvement is concentrated on the first tokens of each packed patient, which should be the hardest positions; the model is predicting a patient's opening events from the previous patient's history, which is often a relative or a similar encounter in a sorted extract. (c) An attention-map check shows non-zero weight across the boundary.

Remedy. Apply a block-diagonal causal mask and reset positions at boundaries; shuffle patients before packing so that adjacent patients are unrelated even if a mask is later lost.

Validation. Packed and unpacked per-patient losses agree to numerical precision; mortality AUROC and ECE return to specification on the patient-level and temporal holdouts (train ≤ 2022, test 2024). If AUROC stays low after the fix, the drop was not caused by leakage, and the next suspect is the changed data ordering.

Problem: rollouts that drift. Generated trajectories are used to estimate risks by counting outcomes across many samples. Exposure bias shows up as event rates that drift with horizon: too few events per simulated year, or time-gap tokens that lengthen. Diagnosis: compare simulated with observed distributions per horizon bucket (events per month, gap-token histogram, fraction of trajectories reaching a given code) on held-out patients, and compare rollout-based risk against a directly trained head on the same task. Remedies, by cost: sample at temperature 1 rather than greedily (greedy decoding systematically under-represents rare events); predict multi-step patches or time-to-event directly (Chapter 9) for long horizons; fine-tune on the model's own rollouts. Each adds compute or complexity; the validation is calibration of rollout-based risk at the target horizon, not one-step loss.

MetricPurposeAlert when
Real tokens per packed rowpacking efficiency< 85% of 4,096
Packed vs unpacked per-patient lossboundary leakageany difference beyond numerical noise
Loss by token classwhat is being learnedcodes flat while values improve
Simulated vs observed events per month, by horizonexposure biasratio outside 0.9–1.1 at 12 months
Downstream AUROC and ECE on temporal holdouttransferoutside specification (0.89 / 0.03)

Masked and autoregressive objectives both predict raw content, tokens or values. The next family keeps their prediction structure but moves the target into embedding space, which removes the need to model unpredictable detail.

Joint-embedding predictive architectures

Definition. A joint-embedding predictive architecture (JEPA) hides part of the input, as masked modeling does, but predicts the embedding of the hidden part rather than its raw values. The target embedding is produced by a second encoder, so the model is scored on whether it can anticipate an abstract description of the hidden content, never on reproducing its samples.

Motivation. Much of a PPG, EEG or respiratory trace is sensor noise, motion artefact and electrode drift. A pixel-level or sample-level loss obliges the model to spend capacity predicting it. Contrastive learning avoids raw reconstruction but needs negatives and carefully designed positives. JEPA, introduced for images as I-JEPA by Assran et al. (2023), combines masking's simple view construction with a loss that only counts what the target encoder chooses to represent.

Mechanism, step by step.

  1. Split. From one input, select a context block (visible) and one or more target blocks (hidden from the context encoder).
  2. Encode the context. The context encoder, the network being trained, embeds the visible tokens.
  3. Predict. A predictor network receives the context embeddings plus the positions of the target tokens and outputs a predicted embedding for each target position.
  4. Encode the target. A target encoder embeds the full input; its outputs at the target positions are the regression targets. Its weights are not trained by gradient: after every step they are moved a small fraction of the way toward the context encoder's weights, an exponential moving average (EMA).
  5. Score. The loss is the squared distance between predicted and target embeddings. Only the context encoder and predictor are updated.
JEPA on a W3 night: a context encoder and predictor estimate the embeddings that an EMA target encoder assigns to hidden epochs; the loss is measured in embedding space.W3 night30-s epochs,5 channel groupsContext blockvisible epochsTarget blockhidden epochs 7–10Context encoder fθtrained by gradientTarget encoderEMA of fθ, no gradientPredictor hψ+ target positionsTarget embeddingsfixed this stepL2 lossin embedding spaceEMA copy
Fig. Joint-embedding predictive architecture on a W3 polysomnography night. Only the context encoder and predictor receive gradients; the target encoder is a slowly moving average of the context encoder. Nothing is ever decoded back to raw EEG or respiration.

Why the target encoder is frozen and slow. If the target embeddings were produced by the same network with gradients flowing through both branches, the easiest solution would be to map every input to the same constant vector: prediction is then perfect and the loss is zero. This is representation collapse. Stopping the gradient through the target branch and updating it only by EMA removes that shortcut in practice, as in BYOL (Grill et al. 2020). The Level 3 code demonstrates both outcomes on a small linear model. LeJEPA (Balestriero & LeCun 2025) replaces these heuristics with a regulariser, SIGReg, that pushes embeddings toward an isotropic Gaussian distribution; it reports needing no stop-gradient, no teacher–student schedule and a single trade-off hyperparameter, with 79% ImageNet linear-probe accuracy for a ViT-H/14.

Worked example · W3A W3 night is a sequence of 30-second epochs across five channel groups (EEG, EOG, EMG, ECG, respiratory). For a 20-epoch (10-minute) segment, epochs 7 to 10 form the target block and the remaining 16 the context. The context encoder embeds the visible epochs; the predictor, told "positions 7 to 10", outputs four predicted embeddings; the EMA target encoder's embeddings of those epochs are the targets. The model is never asked to reproduce the exact EEG samples of epoch 8, only an embedding from which, for example, its sleep stage or an apneic pattern should be recoverable.

Evidence in health data. Published health results remain early, mostly preprints. ECG-JEPA pretrained on about 180,000 12-lead ECGs from open datasets with a lead-aware attention mask and reported state-of-the-art results on diagnostic classification and segmentation (Kim 2024). EEG-VJEPA treated multichannel EEG as video, pretrained on recordings from 4,438 subjects, and reached 85.8% accuracy and 0.885 AUROC on normal-versus-abnormal EEG after fine-tuning (Hojjati et al. 2025). Laya applied LeJEPA to EEG and reported better linear-probe results than reconstruction-based baselines, arguing that reconstruction biases representations toward high-variance artefacts (Panchavati et al. 2026). These results are promising; they are not yet a body of independent comparisons at the scale of the contrastive and masked literature.

Comparison. Against masked reconstruction, JEPA trades an interpretable, anchored loss for freedom from modelling noise. Against contrastive learning, it needs no negatives and no positive rule beyond the masking pattern, but it needs collapse prevention. Mental model: masked reconstruction asks "what were the values?"; JEPA asks "what would a good summary of the hidden part say?", with the summary defined by a slowly improving copy of the model itself.

The loss. Let \(x\) be the token sequence, \(C\) the context indices and \(T\) the target indices. The context encoder \(f_\theta\) embeds \(x_C\); the predictor \(h_\psi\) takes those embeddings and a positional code \(\mathrm{pos}_i\) for each target; the target encoder \(\bar f_\xi\) embeds the full input. I-JEPA (Assran et al. 2023) minimises

\[ \mathcal{L}_{\text{JEPA}} = \sum_{i \in T} \big\lVert h_\psi\big(f_\theta(x_C), \mathrm{pos}_i\big) - \operatorname{sg}\big[\bar{f}_{\xi}(x)_i\big] \big\rVert_2^2, \]

where \(\operatorname{sg}[\cdot]\) (stop-gradient) means the term is treated as a constant during backpropagation. After each optimiser step the target weights follow the context weights:

\[ \xi \leftarrow m\,\xi + (1 - m)\,\theta, \qquad 0 < m < 1. \]

Time constant. Unrolling the update, the target is a weighted average of past context weights with weight \(m^k (1-m)\) on the weights from \(k\) steps ago, so its memory is about \(1/(1-m)\) steps. With \(m = 0.996\) that is 250 steps; after 1,000 steps the initial weights retain \(0.996^{1000} \approx 0.018\) of their influence. Schedules that raise \(m\) toward 1 during training make the target progressively steadier.

Why collapse is a minimiser without stop-gradient. If the target branch shares weights and receives gradient, any \(\theta\) for which \(f_\theta(x) = c\) for all \(x\) and \(h_\psi(c, \cdot) = c\) gives \(\mathcal{L} = 0\), the global minimum. For a linear encoder \(W\) the gradient of \(\lVert x_C W P - x_T W\rVert^2\) (row-vector convention) with respect to \(W\) includes a term from the target branch that shrinks \(W\) whenever predictions and targets disagree, driving \(W \to 0\). With stop-gradient that term is absent: the target is a fixed regression goal for the step, and the context branch can only reduce the loss by predicting it, which requires keeping information.

Measuring collapse. Because the target moves, the loss is not an absolute measure. Two embedding statistics are: the per-dimension standard deviation across a batch (complete collapse sends it to 0) and the effective rank, \(\exp\big(-\sum_k p_k \log p_k\big)\) with \(p_k = \sigma_k / \sum_j \sigma_j\) the normalised singular values of the centred embedding matrix. Effective rank ranges from 1 (all variance in one direction, dimensional collapse) to \(d\) (isotropic).

SIGReg. LeJEPA (Balestriero & LeCun 2025) adds \(\lambda \cdot \frac{1}{K}\sum_{k=1}^{K} T\big(\{a_k^\top z_n\}_{n}\big)\), where \(a_k\) are random unit directions and \(T\) is the Epps–Pulley statistic comparing the empirical characteristic function of the projected embeddings with that of \(\mathcal{N}(0,1)\): \(T = \int \lvert \hat\varphi(t) - e^{-t^2/2}\rvert^2 w(t)\,dt\). An isotropic Gaussian has \(T \approx 0\) in every direction; a collapsed embedding fails in most directions. The cost is linear in batch size and dimension.

Worked example · W3With a 20-epoch segment, \(|C| = 16\) and \(|T| = 4\). If the target encoder uses \(m = 0.996\), its weights lag the context encoder by roughly 250 steps. With 28.8 million epochs in W3, a 20-epoch segment per sample and (illustratively) 512 segments per batch, one pass over the data is about 2,800 steps, so the target turns over roughly eleven times per pass.

The smallest faithful JEPA is linear. A context view \(x_C\) and a target view \(x_T\) (both 32-dimensional) share a 4-dimensional latent state \(s\) plus independent noise, like two blocks of the same recording. The context encoder is a matrix \(W\) \((32 \times 8)\), the predictor \(P\) \((8 \times 8)\), the target encoder \(\bar W\) an EMA copy. The loss is \(\lVert x_C W P - x_T \bar W\rVert^2\) averaged over the batch. Gradients are written out by hand: with residual \(r\) and \(g = 2r/n\), \(\partial/\partial P = (x_C W)^\top g\) and \(\partial/\partial W = x_C^\top (g P^\top)\). Setting stop_grad=False makes the target branch use \(W\) itself and adds the target-branch gradient \(-x_T^\top g\).

# A linear JEPA: context encoder W, predictor P, target encoder W_bar (EMA of W, no gradient).
import numpy as np

def effective_rank(Z, eps=1e-12):
    """exp(entropy of normalised singular values) of centred embeddings Z (n, d); 1 = collapsed."""
    s = np.linalg.svd(Z - Z.mean(0), compute_uv=False)
    p = s / (s.sum() + eps)
    return float(np.exp(-(p * np.log(p + eps)).sum()))

def ema(W_bar, W, m):
    """Target update after each optimiser step: W_bar <- m W_bar + (1 - m) W."""
    return m * W_bar + (1 - m) * W

def epps_pulley(u, ts=np.linspace(-5, 5, 201)):
    """1-D Gaussianity statistic used by SIGReg (LeJEPA): weighted squared distance between
    the empirical characteristic function of u and that of N(0, 1)."""
    phi = np.exp(1j * np.outer(ts, u)).mean(1)
    w = np.exp(-ts ** 2 / 2)
    return float(np.trapezoid(np.abs(phi - np.exp(-ts ** 2 / 2)) ** 2 * w, ts))

def sigreg_stat(Z, n_dirs=64, rng=None):
    """Average Epps-Pulley statistic over random unit directions (sketched isotropy check)."""
    rng = rng or np.random.default_rng(0)
    A = rng.normal(size=(Z.shape[1], n_dirs)); A /= np.linalg.norm(A, axis=0)
    return float(np.mean([epps_pulley(c) for c in (Z @ A).T]))

def make_data(n, rng, k=4, D=32):
    """Context and target views share a k-dim latent state s; each adds its own noise."""
    s = rng.normal(size=(n, k)); A, B = rng.normal(size=(k, D)), rng.normal(size=(k, D))
    return s @ A + 0.5 * rng.normal(size=(n, D)), s @ B + 0.5 * rng.normal(size=(n, D))

def train(stop_grad=True, steps=3000, lr=0.01, m=0.99, d=8, seed=0):
    rng = np.random.default_rng(seed)
    W = 0.1 * rng.normal(size=(32, d)); P = np.eye(d); W_bar = W.copy()
    for _ in range(steps):
        xc, xt = make_data(256, rng)
        zc, zt = xc @ W, xt @ (W_bar if stop_grad else W)
        r = zc @ P - zt                                  # (n, d) prediction error in latent space
        g = 2 * r / len(r)                               # dL/d(prediction), L = mean ||r||^2
        gP = zc.T @ g; gW = xc.T @ (g @ P.T)
        if not stop_grad:
            gW -= xt.T @ g                               # gradient also flows into the target branch
        W -= lr * gW; P -= lr * gP
        W_bar = ema(W_bar, W, m) if stop_grad else W
    xc, _ = make_data(2000, rng)
    return xc @ W, float((r ** 2).sum(1).mean())

if __name__ == "__main__":
    assert np.allclose(ema(np.zeros(3), np.ones(3), 0.996), 0.004)
    Zc = np.random.default_rng(3).normal(size=(2000, 8))
    assert effective_rank(np.outer(Zc[:, 0], np.ones(8))) < 1.01        # rank-1 = collapsed
    assert effective_rank(Zc) > 7.5                                      # isotropic = healthy
    assert sigreg_stat(Zc) < 0.01 and sigreg_stat(3 * Zc) > sigreg_stat(Zc)
    for sg in (False, True):
        Z, loss = train(stop_grad=sg)
        print(f"stop_grad={sg}: final loss {loss:.4f}, embedding std {Z.std():.4f}, "
              f"effective rank {effective_rank(Z):.2f}")
        if sg: assert Z.std() > 0.1 and effective_rank(Z) > 3.0     # spread over the 4-dim shared state
        else:  assert Z.std() < 1e-3                                 # trivial solution: lowest loss, no information
    print("all jepa tests passed")

Output:

stop_grad=False: final loss 0.0000, embedding std 0.0000, effective rank 1.00
stop_grad=True: final loss 0.4626, embedding std 0.3065, effective rank 3.25
all jepa tests passed

The run shows the central fact of this family: the collapsed model has the lower loss. Without stop-gradient, \(W\) shrinks to zero and predictions match targets trivially. With stop-gradient and EMA, the embeddings keep a spread of 0.31 and an effective rank of 3.25 out of 8, close to the 4 dimensions of shared state that the views have in common. Across four random seeds the stop-gradient run gave effective ranks between 2.3 and 3.4, so partial dimensional collapse also occurs and must be monitored, not assumed away.

The helper sigreg_stat is a diagnostic version of LeJEPA's regulariser (no gradient): it projects embeddings on 64 random directions and averages the Epps–Pulley statistic. The tests confirm that it is near zero for standard Gaussian embeddings and larger for a scaled copy, so it detects departures from isotropy in scale as well as shape. In a training framework it would be added to the loss with weight \(\lambda\).

Worked example · W3For W3 the same structure applies with a transformer over epoch tokens: x_c is a \((B, 16, \text{channels} \times \text{samples})\) tensor of visible epochs, the predictor receives four target position embeddings, and the target encoder output at positions 7 to 10 is detached. The diagnostics are computed on pooled 256-dimensional night-segment embeddings every few hundred steps.

Debugging. If embedding standard deviation falls steadily while loss falls, check that the target branch is detached and that the EMA update runs after, not before, the optimiser step. If effective rank is low from the start, the predictor may be too powerful relative to the masking (it can solve the task without the encoder's help) or the target block too small.

Problem: collapse that the loss cannot see. JEPA training can degrade into complete or dimensional collapse while its loss looks healthy, because the target it regresses onto is itself shrinking or concentrating.

Why it matters. A collapsed encoder transfers poorly, and the failure may be discovered only at downstream evaluation after the full compute budget is spent.

Root cause. Stop-gradient and EMA prevent the trivial solution only dynamically; nothing in the loss forbids it. Too-low EMA momentum (a target that tracks the context encoder too closely), an over-capable predictor, or masks that leave targets easy to predict all push toward collapse.

Worked incident · W3

Symptom. A JEPA variant of W3 (illustrative: 256-dimensional embeddings, \(m = 0.99\)) shows a smoothly falling loss, but the sleep-staging linear probe plateaus at κ 0.55, well below the 0.78 specification, and the AHI ≥ 15 probe below 0.91 AUROC (illustrative values).

Measurements that separate causes. (a) Effective rank of pooled embeddings falls from about 140 early in training to about 15 (illustrative): dimensional collapse. (b) Per-dimension standard deviation is not zero, so collapse is partial. (c) A probe trained on the target encoder's embeddings is no better than one on the context encoder's, ruling out a context-only problem. (d) With \(m = 0.99\) the target memory is 100 steps; logs show rank falling fastest after a learning-rate warm-up ends.

Remedy options. Raise \(m\) to 0.996 with a schedule toward 1 (target memory 250 steps and rising); reduce predictor depth; enlarge target blocks (for W3, from 4 to 6 epochs); or add a distribution regulariser (SIGReg, or a variance–covariance penalty) with weight \(\lambda\). The first three are free in compute; the regulariser adds a projection and a statistic per step (linear in batch and dimension) and one hyperparameter, but it makes collapse a penalised state rather than an avoided one.

Validation. The fix is supported if effective rank stabilises (for example above 100 of 256) and the staging κ probe rises toward the specification at a fixed budget. If rank recovers but κ does not, the representation is spread but not informative about stages, which points to the masking scale (target blocks too short to require stage-level context) rather than collapse.

Cost of the target encoder. The target branch runs a forward pass on the full input every step without a backward pass; since backward costs about twice a forward, this adds roughly a third of the context encoder's training compute when both process inputs of similar length, and an extra copy of the weights in memory (for a 50M-parameter encoder, 200 MB in float32). LeJEPA removes the separate target network, which removes this cost.

MetricPurposeAlert when
Per-dimension embedding std (min, median)complete collapsemedian falling monotonically
Effective rank / embedding dimensiondimensional collapsefalls by > 30% from its peak
Sketched Gaussianity statisticdeparture from isotropyrising trend
EMA momentum and target–context weight distancetarget dynamicsdistance near zero (target tracks too closely)
Canary probes (W3: staging κ, AHI AUROC)transferplateau below specification

JEPA defines its views by masking, so the question of which views to pair is answered by the mask. For contrastive models the question is open and decisive, which is the subject of the final section.

Choosing positives in health data

Definition. In contrastive learning a positive pair is two views that the encoder must map close together. The rule that generates them, the positive recipe, is the most consequential design choice in a contrastive health model, because whatever differs between the two views of a positive becomes something the representation learns to ignore, and whatever they share becomes what it keeps.

Motivation. In image models positives are usually two random augmentations (crops, colour changes) of one photograph, and the augmentations are chosen to change only nuisance properties. Health signals lack an obvious augmentation family: shifting a PPG trace in time is harmless, but stretching it changes heart rate, and smoothing it erases pulse morphology that carries information about vascular ageing. Health data offer something images rarely do instead: natural pairings, such as many recordings of the same person, simultaneous recordings from several sensors, and text that describes a signal.

Six recipes recur.

  • Same participant, different time. Abbaspourazad et al. (2024) paired PPG or ECG segments from the same Apple Heart and Movement Study participant, about 141K people over about three years, so the embedding captures stable traits of the person and discards momentary state; the embeddings encoded demographics and health conditions. PCLR did the same for clinical 12-lead ECGs, and Apple's wearable behaviour model used subject-level positives over hourly behavioural features from 161,855 participants (Erturk et al. 2025).
  • Adjacent segments or other leads. CLOCS (Kiyasseh et al. 2021) treated temporally adjacent ECG segments and different leads of the same recording as positives; ECG-FM combines this with wav2vec-style masking.
  • Different modality, same moment. SleepFM aligns brain, cardiac and respiratory signals recorded in the same window; its extended version, trained on about 585,000 hours of polysomnography from about 65,000 participants, predicted 130 future conditions with reasonable accuracy, with C-index 0.84 for death and 0.85 for dementia (Thapa et al., Nature Medicine 2026). Apple's accelerometer model distils from PPG embeddings of the same time window (Abbaspourazad et al. 2024).
  • Physiologically similar. PaPaGei-S (Pillai et al. 2025) defines positives by bins of a PPG morphology index (sVRI) rather than by subject, and adds auxiliary heads for other morphology metrics. Pulse-PPG (Saha et al. 2025) replaces fixed positives with relative ones: a learned motif-based distance ranks candidates, and each candidate serves as a positive against those farther from the anchor. Trained on about 55K hours of field PPG from 120 participants, it found field pretraining outperforming clinical-data pretraining on many tasks.
  • Sensor and text. SensorLM (Zhang et al. 2025) pairs sensor windows with automatically generated captions describing statistics, trends and events.
  • Augmented copy. Two augmentations of one window: invariant to whatever the augmentations change, so they must be restricted to genuine nuisances.
Six positive-pair recipes, what each lets vary between the two views, and therefore what the embedding keeps.positive pair recipevaries between views → becomes invariantshared by views → preservedSame participant, other timetime of day, activity, momentary statestable traits: age, vascular healthAdjacent segment or other leada few seconds; lead geometryrhythm and recording-level stateOther modality, same momentthe sensor (EEG, ECG, respiration)shared physiological stateSimilar morphology binsubject and devicepulse-shape physiology (sVRI)Sensor window + captionthe medium: signal vs textwhat the captions describeAugmented copywhatever the augmentation changesthe rest: augment nuisances only
Fig. Choosing positives chooses invariances. Whatever differs between the two views of a positive pair is what the contrastive loss teaches the encoder to ignore; whatever they share is what it keeps. W1 uses the first row.

The rule. Positives that differ in time make the embedding about the person; positives that differ in modality make it about the physiological state; positives that differ by augmentation make it invariant to whatever the augmentation changes. The time window sets the balance: positives a few seconds apart share momentary state, positives months apart share only traits.

Worked example · W1W1 pairs windows from the same participant within 24 hours. Within a day, heart rate, activity and posture vary widely, so they become partly invariant; age, sex, vascular properties and a persistent arrhythmia are shared and kept. This suits W1's probes: age (MAE 6.1 years) and AFib (AUROC 0.93, against 0.88 for supervised training from scratch on the 5,000 labelled participants). The rule is less suited to intermittent conditions: a paroxysmal AFib episode present in one window and absent in its positive is pushed toward invariance. The 24-hour cap is therefore a compromise between trait and state, and resting heart rate (MAE 2.4 bpm) survives because it is stable across a day.

Comparison and contrast. Subject-level positives need no augmentation design but risk shortcuts (device signatures identify a person as well as physiology does) and false negatives between people with the same condition. Cross-modal positives tie the embedding to physiology visible in two sensors and are robust to single-sensor artefacts, but require simultaneous recordings and lose information only one modality carries. Relative and morphology-based positives encode an explicit notion of physiological similarity, at the cost of building that notion in.

Mental model. Choosing positives is choosing invariances. Before training, write down which downstream labels must survive and check that each is shared by the two views of a positive.

A latent-factor view. Model each window as generated from shared and view-specific factors: \(x = g(s, n)\) and \(x^{+} = g(s, n')\), where \(s\) is what the positive recipe holds fixed (a participant's traits; the physiological state at one moment) and \(n, n'\) are what it lets vary (time of day, sensor, augmentation). The InfoNCE-optimal critic is proportional to \(p(x^{+} \mid x)/p(x^{+})\) (see the derivation in the InfoNCE section), which depends on \(x\) only through what \(x\) reveals about \(x^{+}\), i.e. about \(s\). von Kügelgen et al. (2021) gave sufficient conditions under which such an encoder recovers \(s\) up to an invertible mapping and discards \(n\). A downstream label \(y\) is therefore linearly decodable only to the extent that \(y\) is a function of \(s\).

Choosing the window. For same-participant positives with a maximum gap \(\Delta\), let a physiological quantity have autocorrelation time \(\tau_y\). If \(\tau_y \gg \Delta\) (age, sex, chronic vascular state), the quantity is nearly constant across a positive pair and belongs to \(s\). If \(\tau_y \ll \Delta\) (heart rate during exercise), it changes between views and is pushed into \(n\). Quantities with \(\tau_y \approx \Delta\) are partially retained. With \(\Delta = 24\) h, daily-stable quantities survive and intra-day ones are attenuated.

Worked example · W1If a sampler picks a positive uniformly among a participant's windows within 24 hours, and a participant wears the watch 15 hours a day (illustrative), the expected gap between anchor and positive is several hours, so most positives cross activity and posture changes. Resting heart rate, stable across a day, belongs to \(s\); the instantaneous heart rate of the anchor window does not.

False negatives at the label level. For a label with prevalence \(\pi\), an anchor with the label faces about \(\pi (N-1)\) negatives that share it, each pushed away although it shares the clinically relevant factor. With \(N = 4{,}096\) and an illustrative prevalence \(\pi = 0.05\), that is \(0.05 \times 4{,}095 \approx 205\) same-label negatives per positive anchor. The repulsive gradient on each is its softmax probability \(p_j\), which is small unless the negative is close; so the damage concentrates on exactly the most similar same-label negatives. Same-participant collisions (55.9 pairs per W1 batch, from \(\binom{N}{2}/P\)) are the extreme case and can be masked; same-label collisions cannot be masked without labels.

Relative positives. Pulse-PPG's RelCon loss (Saha et al. 2025) uses a learned distance \(d(\cdot,\cdot)\) to rank candidates \(c_1, \dots, c_K\) by distance from the anchor and, for each candidate \(c_k\) taken as positive, treats as negatives only those with \(d(x, c_j) > d(x, c_k)\). This replaces the binary positive/negative split with an ordering, so a near-miss is not punished as hard as a far candidate. Its cost is the distance model, trained first by masked reconstruction, whose notion of similarity the encoder then inherits.

Cross-modal pairs. With \(K\) modalities, a leave-one-out scheme contrasts each modality's embedding \(z^{(k)}\) against an aggregate of the others, \(\bar z^{(-k)}\), as in SleepFM. The shared factor \(s\) becomes "what all modalities agree on at this moment", which is physiological state rather than personal identity.

A positive sampler needs three operations: index windows by participant and time, draw a partner within the allowed gap, and report anchors with no valid partner so they can be dropped rather than paired with themselves. Sorting by (participant, time) once lets each lookup use two binary searches. Inputs: arrays pid and t (seconds) of length \(n\); output: an index or −1. A minimum gap of one window (10 s) excludes the anchor and overlapping windows.

# Positive-pair sampling for W1: same participant, different window, within 24 h.
import numpy as np

HOUR = 3600

def build_index(pid, t):
    """Sort windows by (participant, time) and return per-participant slices."""
    order = np.lexsort((t, pid)); pid_s, t_s = pid[order], t[order]
    starts = np.flatnonzero(np.r_[True, pid_s[1:] != pid_s[:-1]])
    ends = np.r_[starts[1:], len(pid_s)]
    return order, t_s, dict(zip(pid_s[starts], zip(starts, ends)))

def sample_positive(i, pid, t, index, rng, max_gap=24 * HOUR, min_gap=10):
    """Return a window index of the same participant with min_gap <= |dt| <= max_gap, or -1."""
    order, t_s, slices = index
    a, b = slices[pid[i]]
    lo = np.searchsorted(t_s[a:b], t[i] - max_gap) + a
    hi = np.searchsorted(t_s[a:b], t[i] + max_gap, side="right") + a
    cand = order[lo:hi]
    cand = cand[np.abs(t[cand] - t[i]) >= min_gap]          # exclude the anchor (and overlaps)
    return int(rng.choice(cand)) if len(cand) else -1

def expected_same_participant_pairs(batch, participants):
    """Expected number of anchor pairs in a batch that share a participant (uniform sampling)."""
    return batch * (batch - 1) / 2 / participants

if __name__ == "__main__":
    rng = np.random.default_rng(4)
    pid = np.array([0, 0, 0, 1, 1, 2])
    t = np.array([0, 3 * HOUR, 30 * HOUR, 0, 10, 0])          # seconds
    idx = build_index(pid, t)
    for _ in range(50):
        j = sample_positive(0, pid, t, idx, rng)
        assert j == 1                                             # 30 h is too far; itself excluded
    assert sample_positive(5, pid, t, idx, rng) == -1             # nobody to pair with: drop anchor
    assert sample_positive(3, pid, t, idx, rng) == 4              # adjacent 10-s window
    print("expected same-participant anchor pairs in a W1 batch:",
          round(expected_same_participant_pairs(4096, 150_000), 1))
    print("all positives tests passed")

Output:

expected same-participant anchor pairs in a W1 batch: 55.9
all positives tests passed

The tests encode the rule's edge cases: a window 30 hours away is never chosen; the anchor itself is never chosen; a participant with a single window yields −1; the adjacent 10-second window is a valid positive. The helper computes the expected collision count used to size the false-negative mask.

Plugging the sampler into the loss. The participant ids of anchors go to info_nce(..., pid=pid) from the InfoNCE section, which removes the collision cells. A cross-modal recipe changes only the sampler (same participant, same time, other modality) and the encoder (one per modality, or a shared encoder with a modality token); a relative recipe changes the loss.

Worked example · W1At W1 scale the index covers 10.8 billion window slots. A row of (participant id as int32, time as int32 seconds, offset into storage as int64) is 16 bytes, so the index is about 173 GB, or about 107 GB if only the 6.7 billion slots that carry PPG are indexed: too large for one host's memory, so it is sharded by participant, and each data-loader worker owns a set of participants and samples anchors and positives locally. Sharding by participant also keeps a participant's windows on one worker, which makes the 24-hour lookup local.

Debugging. Log the distribution of positive gaps \(|\Delta t|\). A spike at the minimum gap means the sampler is effectively choosing neighbours (for example, because only a short recording exists for most participants), which shifts the embedding from traits toward momentary state. A fraction of −1 results above a few percent means many anchors lack partners and the effective batch is smaller than configured.

Problem: the positive distribution drifts from the design. The recipe says "same participant within 24 hours", but the realised distribution of positives depends on wear patterns, data availability and sampler implementation, and it decides which invariances the model learns.

Why it matters. If realised gaps are short, positives share momentary state and the embedding becomes less trait-like (weaker age and long-term risk probes); if they are long, state-like signals are suppressed (weaker activity and acute-event probes). The same configuration can therefore produce different models on different cohorts.

Root cause. Missing data are not random. In W1, 38% of hours have no PPG, concentrated around charging times and nights for some users, so the windows available within 24 hours of an anchor are clustered, and a uniform sampler over available windows inherits that clustering.

Worked incident · W1

Symptom. A retrain on a new cohort extract keeps the contrastive loss and the AFib probe close to specification (0.93) but age MAE worsens from 6.1 to 6.8 years (illustrative).

Measurements that separate causes. (a) The positive-gap histogram shows the median gap fell from several hours to under one hour (illustrative): the new extract has shorter continuous wear sessions, so most in-range windows are near the anchor. (b) A probe for hour of day from embeddings rises, consistent with state information entering \(s\). (c) Cohort age distribution is unchanged, ruling out a label shift.

Remedy. Stratify positive sampling by gap: draw a gap bucket first (for example under 1 h, 1–6 h, 6–24 h) with fixed probabilities, then a window inside the bucket, falling back to the nearest non-empty bucket. This restores the designed mix independently of wear patterns. Cost: more index lookups per anchor and a slightly higher rate of anchors without partners, which reduces effective batch size; track it.

Validation. A pre-registered ablation with identical compute: uniform versus stratified sampling, evaluated on trait probes (age), state probes (hour of day, resting heart rate) and AFib. Support for the hypothesis: age MAE returns toward 6.1 and the hour-of-day probe falls, with AFib unchanged. If age improves but AFib falls, the 6–24 h bucket is suppressing rhythm information and its weight should be reduced.

Choosing among recipes at scale. When several recipes are feasible, the decision is empirical and should be run as a controlled comparison: same encoder, data budget and probe suite, varying only the positive rule. Report both clinical probes and nuisance probes. Recipes that share a cohort can be combined (multiple positive types per anchor, each with its own loss weight), which is how cross-modal and same-subject signals coexist in recent models; the cost is more hyperparameters and an interaction that each ablation must cover.

MetricPurposeAlert when
Positive-gap histogram (p10/p50/p90)realised invariance windowmedian shifts by > 2× between runs
Anchors without a valid positiveeffective batch size> 3% of anchors
Same-participant collisions masked per batchfalse-negative handlingfar from \(\binom{N}{2}/P\) (≈ 56 in W1)
Trait vs state probes (age vs hour of day)what the embedding encodestrait worsens while state rises
Nuisance probes (device, firmware)shortcut via identityrising over training

The positive recipe defines what is shared between views; the tokenizer defines the units those views are made of. Chapter 5 turns to tokenisation of signals and clinical events, which fixes the patch lengths, code vocabularies and time tokens used by every objective in this chapter.

Tokenizing Signals and Clinical Events

A tokenizer is the component that turns raw health data into the sequence of units a model actually reads. Transformers, the backbone of almost every health foundation model, consume sequences of vectors; they never see a waveform or a lab report directly. Something has to decide how many units a recording becomes, what each unit covers, and what information each unit carries. That decision is made once, before any training, and it fixes three properties of the model that no amount of later training can undo: its resolution (the finest detail a token can express), its context length (how much history fits in one input), and its inductive bias (which structure, such as a heartbeat or a clinic visit, the model is handed for free and which it must discover).

Text tokenizers had an easy starting point: language already arrives as discrete symbols, and the only question is how to group characters into subwords. Health data offers no such vocabulary. A photoplethysmography (PPG) sensor produces a continuous voltage 64 times a second; an electronic health record (EHR) produces irregularly timed events, each a code that may carry a number and a unit. Earlier systems avoided the problem by hand-crafting features (heart rate from a waveform, counts of diagnosis codes over a year) and handing those to a classical model. Foundation models replace hand-crafted features with learned representations, but they still need a raw-to-sequence mapping, and that mapping is where the remaining hand design lives.

Two families of input need different tokenizers. Continuous signals (PPG, ECG, EEG, accelerometry, the channels of a sleep study) are regularly sampled numbers with no natural symbols; they are tokenized by cutting the series into fixed windows called patches, by mapping values into a fixed set of bins, by stacking lagged values, by learning a discrete codebook, or by cutting at physiological units such as a heartbeat or a 30-second sleep epoch. Clinical events are already discrete codes, but each carries a time, often a value, and a membership in a visit, none of which a word tokenizer ever represents.

One 10-second PPG window tokenized two ways: cut into ten 1-second patches (left) or mapped value by value to integer bins (right).Patching640 samples → 10 patches of 64 → 10 vectorsp1p2p3p4p5p6p7p8p9p10each patch × W (64 → d) = one token embeddingresolution kept inside the patch;sequence 64× shorterQuantizationscale by mean |x|, snap each value to one of B bins204820492048204420482049204820442048integer ids from a fixed vocabularyone token per sample (or per step);value known only to within a bin
Fig. Two ways to turn a continuous signal into tokens, drawn on one 10-second W1 window (synthetic waveform, 64 Hz). Left: patching cuts the 640 samples into ten 1-second windows that are each linearly projected to an embedding, as in PatchTST, TimesFM, MOMENT and Moirai. Right: quantization rescales the series and snaps every value to one of a fixed set of bins, producing integer ids for a language-model vocabulary, as in Chronos (bins drawn coarse for legibility; ids shown for every 16th sample).
Worked example · W1, W2, W3

In W1, one input is a 10-second window of PPG and accelerometry at 64 Hz, 640 samples per channel. Cut into 1-second patches it becomes 10 tokens; kept at one token per sample it would be 640 tokens. In W2, a patient is a list of timed events (median 96, 95th percentile 1,450), and the vocabulary holds 42,000 codes, 64 time-gap tokens and 10 value-decile tokens whose boundaries are computed separately for each lab; the model reads at most 4,096 tokens. In W3, one night of polysomnography is about 960 thirty-second epochs across five channel groups, and the scoring epoch is the natural unit a tokenizer can respect.

The comparison with predecessors is instructive. A hand-crafted feature pipeline loses information by design but is transparent; a tokenizer loses information too (a bin hides small value changes, a patch hides exact timing within it, a dropped rare code hides a diagnosis), but the loss is easy to overlook because the model trains anyway. The contrast is in where errors appear: a feature bug shows up as an implausible feature value, whereas a tokenizer bug shows up only as a quietly worse model. The mental model for this chapter is a contract: the tokenizer promises the model a fixed unit, a fixed value representation and a fixed treatment of time and missing data, and every downstream number depends on that contract being kept.

The chapter has two sections. The first covers signals: patches, bins, lags, codebooks and physiological units, with normalization and missingness. The second covers clinical events: codes, time, values, visit structure, the MEDS data standard and the repeated-code pitfall. The previous chapter chose the training objective; this one fixes what that objective is computed over, and the next chapter applies both to time-series foundation models.

Formally, a tokenizer is a map \(\tau\) from a raw record \(x\) to a sequence of \(N\) tokens \(\tau(x) = (u_1, \dots, u_N)\). Each token is either an integer id \(u_n \in \{0, \dots, |V|-1\}\) from a vocabulary \(V\), which the model turns into a vector by looking up row \(u_n\) of an embedding table \(E \in \mathbb{R}^{|V| \times d}\), or a continuous vector that is projected directly to the model width \(d\). Three quantities follow from \(\tau\) and govern everything after it.

  • Sequence length \(N\). Self-attention compares every token with every other, so its cost per layer grows as \(N^2 d\), while the feed-forward and projection layers grow as \(N d^2\).
  • Information loss. If two different inputs \(x \ne x'\) map to the same tokens, \(\tau(x) = \tau(x')\), no model can tell them apart. Binning a value with bin width \(\Delta\) loses up to \(\Delta/2\); a dropped rare code loses that code entirely.
  • Vocabulary size \(|V|\) for discrete tokens. The embedding table has \(|V| \cdot d\) parameters, and a generative output layer computes a softmax over \(|V|\) entries per position.

For a regularly sampled signal of length \(L\) cut into non-overlapping patches of \(P\) samples, \(N = \lceil L/P \rceil\), so attention cost falls by roughly \(P^2\). For an event record with \(n_e\) events of which a fraction \(f\) carry numeric values, a design that emits one code token per event, one value token per numeric event and \(g\) time-gap tokens has \(N = n_e + f n_e + g\).

Worked example · W1 and W2

W1: \(L = 640\) samples. With \(P = 1\), \(N = 640\) and attention compares \(640^2 = 409{,}600\) pairs per layer and head; with \(P = 64\), \(N = 10\) and only 100 pairs, a reduction by \(64^2 = 4{,}096\). W2: assume, for illustration, that 35% of events carry a numeric value. A median patient (96 events, 12 gap tokens) becomes \(96 + 34 + 12 = 142\) tokens; a 95th-percentile patient (1,450 events, 120 gap tokens) becomes \(1{,}450 + 508 + 120 = 2{,}078\) tokens, about half the 4,096-token context. The vocabulary has \(|V| = 42{,}000 + 64 + 10 = 42{,}074\) entries (the handful of special tokens, such as padding and beginning-of-sequence, is left out of this count); at an assumed width \(d = 768\) the embedding table holds about 32.3 million parameters, roughly a quarter of the 120M-parameter model.

The trade-off has the same shape in both families: coarser tokens shorten \(N\) and cheapen attention but raise information loss, and larger vocabularies express more distinctions but spend parameters on rare entries that receive few gradient updates. The two sections that follow derive these quantities for signals and for events and work them on the reference workloads.

In code, a tokenizer is a small, deterministic program plus a set of fitted artifacts (vocabulary, quantile edges, scalers). The first thing worth writing is not the tokenizer itself but its specification and a budget calculator that answers two questions before any GPU time is spent: how many tokens does one input become, and how does attention cost scale. The snippet below defines a frozen specification record, computes token counts for patching, and checks the W1 and W2 budgets with assertions. Inputs are plain integers (samples, events); outputs are token counts.

from dataclasses import dataclass
import numpy as np

@dataclass(frozen=True)
class TokenizerSpec:
    """Everything that must be versioned with a pretrained checkpoint."""
    name: str
    unit: str                 # what one token covers, e.g. "1 s PPG patch" or "one event"
    vocab_size: int | None    # None for continuous (projected) tokens
    version: str

def tokens_per_input(n_samples: int, patch: int) -> int:
    """Number of tokens when n_samples are cut into non-overlapping patches."""
    return -(-n_samples // patch)            # ceil division: the last patch is padded

def attention_pairs(n_tokens: int) -> int:
    """Self-attention scores per layer per head grow as n^2."""
    return n_tokens * n_tokens

# W1: 10-s window at 64 Hz = 640 samples
raw  = tokens_per_input(640, 1)    # every sample a token
pat  = tokens_per_input(640, 64)   # 1-s patches
assert (raw, pat) == (640, 10)
assert attention_pairs(raw) // attention_pairs(pat) == 4096   # (640/10)^2

# W2: median and p95 patient lengths against a 4,096-token context
def ehr_tokens(n_events, pct_numeric=35, n_gap_tokens=0):
    """Events + one value token per numeric event (unfused design) + gap tokens.
    Integer arithmetic avoids float rounding surprises (0.35 * 1450 = 507.4999...)."""
    n_values = (n_events * pct_numeric + 50) // 100
    return n_events + n_values + n_gap_tokens
assert ehr_tokens(96, n_gap_tokens=12) == 142
assert ehr_tokens(1450, n_gap_tokens=120) == 2078 <= 4096
print("intro ok", raw, pat, ehr_tokens(96, n_gap_tokens=12), ehr_tokens(1450, n_gap_tokens=120))

Running the file prints intro ok 640 10 142 2078. The integer arithmetic in ehr_tokens is deliberate: 0.35 * 1450 evaluates to 507.4999… in floating point, so round returns 507 and a budget test written against 508 fails on one machine and not on a reader's mental arithmetic. Token budgets feed capacity planning, so they should be exact.

Two debugging habits apply to every tokenizer in this chapter. First, decode a handful of inputs back to human-readable form (patch boundaries drawn on the waveform, token strings for a patient) and inspect them before training. Second, store a hash of the fitted artifacts next to every checkpoint, so that a model can never be evaluated or served with a tokenizer it was not trained with. The signal and event sections build the actual tokenizers on top of this specification.

At scale, the tokenizer stops being a preprocessing script and becomes a versioned artifact with its own failure modes. The problem is that every downstream metric silently depends on it: a checkpoint trained on one set of quantile edges and evaluated on another produces wrong tokens without raising an error. It matters because tokenizer faults are invisible to the usual training dashboards (the loss still falls) and surface only as degraded or biased downstream performance. The root cause is that a tokenizer contains fitted state (vocabulary, quantile edges, normalization constants, gap bins) and implicit assumptions about the input (sampling rate, units, code system version) that change independently of the model.

Data flows left to right from raw records through a versioned tokenizer to token shards and the model; the tokenizer registry and a drift monitor sit below and connect upward.Raw recordsPPG / MEDS rowsunits, ratesTokenizer vNspec + vocab + edgesscalers, gap binshash pinnedToken shardsids / patches+ masks, statsModelpretrain, probeserveTokenizer registryfit on train split onlyversion ↔ checkpointDrift and contract monitortoken shares, PSI, UNK rate,length percentiles, mask fractionloadsreads shards
Fig. The tokenizer as a versioned artifact. Everything fitted from data (vocabulary, quantile edges, scalers, gap bins) is stored with a hash next to the checkpoint that was trained on it, fitted on the training split only, and monitored on every new shard. Arrows show data flow; no component reads the test split.
Worked incident · W2

Illustrative incident. W2 is retrained with tokenizer v4, whose lab decile edges were refitted after a year of new data. The serving job keeps loading tokenizer v3 because the version is configured separately from the checkpoint. About 18% of lab values now fall in a different decile token than the model expects. On the 2024 temporal holdout, 1-year mortality AUROC drops from 0.89 to 0.86 and calibration error (ECE) rises from 0.03 to 0.07. Training loss curves and the offline evaluation (which used v4) look normal; only the serving-side monitor of value-token shares, which shows each decile drifting away from 10%, separates this cause from genuine population drift. The remedy is to bundle the tokenizer artifacts and their hash into the checkpoint and make the serving loader refuse a mismatch. Validation: replaying a week of serving inputs through the bundled tokenizer restores AUROC to within 0.005 of the offline value; if it does not, the drift is real and the model, not the configuration, needs attention.

The diagnosis toolkit is the same for both families: per-token share distributions compared with training (the population stability index, defined in the events section), the unknown-token rate, sequence length percentiles and truncation share, the fraction of masked patches, and a deterministic replay test that tokenizes a fixed set of records and compares hashes. The remedy pattern is also shared: make every assumption an explicit, checked contract (sampling rate, units, code system version, index-time filtering), fit artifacts on the training split only, and version them together with the model. The cost is engineering discipline and some storage; the trade-off is speed of iteration, since a refitted tokenizer forces retraining or at least re-validation.

Tokenizer signalHealthy range (W1 / W2)Alert whenMost likely cause
Tokenizer hash at loadequals checkpoint hashany mismatchconfiguration drift
Unknown-token rate (W2)< 0.5% of code tokensdoubles week over weeknew codes, code-system update
Per-lab decile PSI (W2)< 0.1> 0.25unit change, assay change, leakage of new edges
Masked-patch fraction (W1)stable per device modelshift > 5 pointsfirmware, wear detection change
Dominant frequency per window (W1)0.7–3 Hz (42–180 bpm)mass below 0.7 Hzsampling-rate mismatch
Truncation share (W2)< 5% of patientsrises with new datalonger histories, repeated codes

These checks connect back to the method: each one measures whether the tokenizer contract (fixed unit, fixed value representation, fixed treatment of time and missing data) still holds. The signal section turns them into a concrete ingestion pipeline with a sampling-rate incident; the events section does the same for lab units and value-token drift.

Signals: patches, bins and lags

A continuous signal has no natural vocabulary, so a signal tokenizer must invent its units. Five designs dominate, and each trades resolution against sequence length in a different way.

Patching. The series is cut into consecutive, usually non-overlapping windows of a fixed number of samples, and each window is turned into one vector by a learned linear projection (a matrix multiplication followed by an added bias). The model therefore receives one token per window instead of one per sample. Nie et al. (2022) showed with PatchTST that patching, combined with channel independence (each channel of a multichannel recording is processed as its own sequence with shared weights), made transformers competitive for long-horizon forecasting, because the sequence becomes short enough for attention and each token carries local shape. TimesFM uses input patches of 32 steps and output patches of 128 (Das et al. 2023). Moirai learns separate projections for several patch sizes and picks among them by sampling frequency, from 8 for yearly data up to 64 or 128 for second-level data (Woo et al. 2024). The limitation is that timing inside a patch is not represented as a separate quantity; the projection must learn to read it from the 64 numbers.

Quantization. Each value is rescaled and then mapped to one of a fixed set of bins, so the series becomes a string of integers that a standard language model can read. Chronos divides each series by its mean absolute value, maps values into a fixed vocabulary of uniform bins and trains an unmodified T5 language model with the ordinary cross-entropy loss (Ansari et al. 2024). The output is a probability over bins, so a forecast can have two peaks without assuming any parametric shape. The cost is resolution: a value is known only to within a bin, values beyond the bin range are clipped, and the sequence stays one token per time step.

Lag features. Each token is built from the current value plus values at chosen lags, such as one step, one day and one week back. Lag-Llama does this so a decoder sees seasonal structure explicitly instead of having to attend back across hundreds of positions (Rasul et al. 2023). Lags suit derived, slowly sampled series such as hourly resting heart rate, where daily and weekly rhythms matter; they are meaningless inside a 10-second raw waveform.

Learned codebooks. A vector-quantized autoencoder (VQ-VAE) learns a finite set of prototype vectors, the codebook, and replaces each encoded segment by the index of its nearest prototype (van den Oord et al. 2017). The result is a discrete vocabulary learned from data rather than fixed by bin edges. EEG models such as LaBraM train such a neural tokenizer and then pretrain by predicting the codes of masked patches, using about 2,500 hours of EEG (Jiang et al. 2024); TOTEM applies the same idea to general time series with a 256-entry codebook and reports that its discrete tokens beat a patch-based variant of the same model (Talukder et al. 2024). The limitation is a second model to train and monitor: if the codebook collapses to a few entries, information is lost before the main model starts.

Physiological units. Physiology offers its own units: a heartbeat for ECG and PPG, a breath for respiration, a 30-second epoch for sleep scoring. SleepFM embeds 30-second clips (Thapa et al. 2024), while its 2025 successor tokenizes 5-second windows within a 5-minute context (Thapa et al. 2025 preprint). Aligning tokens to these units keeps clinically meaningful boundaries intact and makes probes simpler, since a label assigned per epoch maps to exactly one token. The cost is a variable number of tokens per window (a fast heart rate produces more beats) and a dependency on a detector, such as a peak finder, that can fail on noisy data.

One W1 window feeds four tokenizers through a shared trunk; each row shows the scheme and its output.W1 window10 s · 64 Hz640 samplesPatchescut into P = 64 samples, project10 tokens × 256-dBinsscale, snap to B bins640 integer idsLags[x_t, x_t−1h, x_t−24h, x_t−1wk]hourly series, 1 token/hBeatssplit at systolic peaks≈ 9–10 tokens + intervalsoutput per windowoperation
Fig. Four signal tokenizers applied to the W1 input. Patching and binning act on the raw 64 Hz window; lag tokens act on a derived hourly series (for example hourly resting heart rate), because lags of an hour, a day and a week are meaningless inside 10 seconds; beat tokens follow physiology and therefore vary in number.

Three further decisions sit around every scheme. Normalization rescales each series so that recordings with very different amplitudes can share one model; the common choices are mean-absolute scaling (Chronos), instance normalization in which each input is standardized and its mean and standard deviation are added back at the output (often called RevIN), or standardization per patch. Normalization removes absolute level, and in physiology level can be the signal: a resting heart rate of 50 versus 90 is clinically meaningful, so the removed statistics should be kept as side inputs where level matters. Missingness is the second decision. There are three options in increasing order of faithfulness: impute the gap and tokenize as if nothing happened; attach a binary mask to every token so the model knows which values are real; or drop missing tokens entirely and use attention masking so the model never reads fabricated values, the approach of LSM-2's Adaptive and Inherited Masking (Xu et al. 2025). A third decision, how multichannel inputs are combined (channel independence with shared weights, all variates flattened into one sequence with variate embeddings as in Moirai, or information exchanged across a group of series at each step as in Chronos-2), trades simplicity against cross-channel structure and is treated with the time-series foundation models in the next chapter.

Worked example · W1

W1 tokenizes each 10-second, 64 Hz window (640 samples per channel) into 10 patches of 64 samples, one second each, which at a resting rate near 60 bpm covers about one heartbeat. Each patch is projected to a 256-dimensional token. A patch that overlaps an off-wrist gap carries mask 0 and is excluded from attention. Because 38% of hours have no PPG at all, the sampler draws windows only from worn hours, and the per-window mean and standard deviation removed by normalization are passed alongside the tokens so that amplitude information is not lost. The same window binned Chronos-style would be 640 integer tokens; cut into beats it would be about 9 or 10 tokens plus the beat-to-beat intervals.

Compared with its predecessors, the patch tokenizer replaced point-wise inputs, in which every sample was a token and long contexts were unaffordable; quantization replaced continuous regression heads with a classification over bins; codebooks replaced fixed bins with learned ones. Recent forecasting models have mostly settled on continuous patches with richer side inputs: Chronos-2 patches the values together with a time index and an observed-value mask per step, after standardizing and applying an inverse hyperbolic sine to damp outliers (Ansari et al. 2025); Sundial keeps continuous patch tokens and models their distribution with a flow-matching head rather than quantizing (Liu et al. 2025). The contrast to keep in mind: bins and codebooks give a discrete vocabulary that suits language-model machinery and multimodal outputs, while patches keep full numeric resolution and shorter sequences. For a health signal the useful mental model is to choose the unit first (a beat, a breath, a second, an epoch), then a value representation that preserves what the clinical target needs, then an explicit treatment of missing data. The next section applies the same three questions to clinical events.

Patch embedding. Let \(x \in \mathbb{R}^{L}\) be one channel of a window with \(L\) samples, and let \(P\) be the patch length. Patch \(n\) is the slice \(x_{(n)} = (x_{(n-1)P+1}, \dots, x_{nP}) \in \mathbb{R}^{P}\), for \(n = 1, \dots, N\) with \(N = \lceil L/P \rceil\) (the last patch is zero-padded). Its token is \[ e_n = W x_{(n)} + b + p_n, \] where \(W \in \mathbb{R}^{d \times P}\) and \(b \in \mathbb{R}^{d}\) are learned, \(d\) is the model width, and \(p_n\) is a position embedding. A transformer layer then costs roughly \(4 N d^2\) multiply-adds for the query, key, value and output projections and \(2 N^2 d\) for computing attention scores and the weighted sum, plus the feed-forward block, which is linear in \(N\).

Worked example · W1

With \(L = 640\), \(P = 64\) and \(d = 256\): \(N = 10\), and \(W\) has \(256 \times 64 = 16{,}384\) weights plus 256 biases. Per layer, projections cost \(4 \cdot 10 \cdot 256^2 \approx 2.6\) million multiply-adds and attention \(2 \cdot 10^2 \cdot 256 = 51{,}200\). With one token per sample (\(P = 1\), \(N = 640\)), projections cost about 167.8 million and attention about 209.7 million: the patch tokenizer cuts the attention term by \(4{,}096\) and the projection term by 64. A 10-minute context at \(P = 64\) is 600 tokens.

Bar chart on a log scale: attention score pairs per layer and head for a 640-sample window at patch lengths 1, 16, 32, 64 and 128.10⁰10¹10²10³10⁴10⁵pairs N²409,600P = 1N = 6401,600P = 16N = 40400P = 32N = 20100P = 64N = 1025P = 128N = 5
Fig. Attention score pairs \(N^2\) per layer and head for one 640-sample W1 window, log scale. Each doubling of the patch length \(P\) halves \(N\) and quarters the attention cost; W1 uses \(P = 64\) (highlighted), a 4,096-fold reduction relative to one token per sample.

Normalization. Instance normalization computes \(\mu = \frac{1}{|O|}\sum_{t \in O} x_t\) and \(\sigma = \sqrt{\frac{1}{|O|}\sum_{t \in O}(x_t - \mu)^2}\) over the observed samples \(O\) only, feeds \(z_t = (x_t - \mu)/(\sigma + \epsilon)\) to the model, and for forecasting maps outputs back with \(\hat{x} = \sigma \hat{z} + \mu\). The pair \((\mu, \sigma)\) is exactly the information normalization removes, so passing it as a side input restores absolute level where the target needs it.

Quantization error. Mean scaling divides by \(s = \frac{1}{L}\sum_t |x_t|\). With \(B\) uniform bins over \([-c, c]\), the bin width is \(\Delta = 2c/B\); a value is replaced by its bin centre, so the rounding error is at most \(\Delta/2 = c/B\) in units of \(s\). If values are spread evenly within bins, the error behaves like uniform noise with variance \(\Delta^2/12\). Values with \(|x_t/s| > c\) are clipped to the edge bin, a real risk for spiky clinical signals such as motion artifacts. Training uses cross-entropy over bins, \(\ell = -\log p_\theta(k^\ast)\), where \(k^\ast\) is the true bin; a point forecast is the expected bin centre \(\hat{z} = \sum_k p_\theta(k)\, m_k\).

Worked example · W1

Chronos trains with \(B = 4{,}094\) bins spread uniformly over \([-15, 15]\) after mean scaling, so that the bins plus two special tokens fill a 4,096-entry vocabulary. With \(c = 15\), \(\Delta = 30/4{,}094 = 0.00733\) and the worst-case error is \(0.00366\) of the window's mean absolute value; the rounding noise has standard deviation \(0.00733/\sqrt{12} \approx 0.0021\). For a synthetic W1 window with \(s = 0.663\), that is at most 0.0024 in signal units. A motion spike 40 times the mean absolute value would be clipped to 15, losing its height entirely.

Lag tokens. For a series sampled once per hour, a lag token is \(u_t = (x_t, x_{t-\ell_1}, \dots, x_{t-\ell_K})\) with lag set \(\{\ell_k\}\), for example \(\{1, 24, 168\}\) hours. The first \(\max_k \ell_k\) steps cannot form a complete token, so a two-week hourly series of 336 points gives \(336 - 168 = 168\) tokens. If the series has an exact daily cycle, the first and third components of every token are equal, which is the structure the model is handed for free.

Missingness as a mask. Let \(m_n \in \{0, 1\}\) mark whether patch \(n\) is fully observed. Masked attention sets the score \(a_{ij} = q_i^\top k_j / \sqrt{d}\) to \(-\infty\) whenever \(m_j = 0\), so after the softmax the missing patch receives zero weight. Dropping masked tokens before the encoder, instead of only masking scores, also removes them from the \(N^2 d\) cost: with a fraction \(\rho\) of tokens missing, attention cost scales by \((1 - \rho)^2\).

Worked example · W1 and W3

In W1, 38% of hours have no PPG. If those hours were kept as masked tokens in an hour-long context, attention would still pay for them; dropping them scales attention cost by \(0.62^2 \approx 0.38\) and the linear terms by 0.62. Physiological units change the count instead of the cost: at 60 bpm a 10-second window holds about 10 beats, at 100 bpm about 16. In W3, a 30-second epoch cut into 5-second tokens gives 6 tokens per epoch per channel group, so an 8-hour night (960 epochs) is 5,760 tokens per group, long enough that per-epoch pooling or a hierarchical encoder is needed before night-level attention.

The choice of \(P\), \(B\) or the lag set is therefore a choice of where to put information loss. A useful rule is to pick \(P\) so that one patch covers a meaningful unit (a beat, a breath, an hour) and the context holds a few hundred to a few thousand tokens, then verify on a downstream probe that the chosen resolution does not limit the target, for example that heart-rate error does not fall when \(P\) is halved.

The code below implements four of the five signal tokenizers (patching, quantization, lags and per-beat units; a learned codebook needs a trained autoencoder and is left out) plus instance normalization on a synthetic W1 window, using only NumPy so that every step is visible. The waveform is a 1 Hz fundamental plus a harmonic and small noise, a stand-in for a 60 bpm PPG pulse. Shapes are noted in each docstring: a window is a 1-D array of 640 samples, patches are (N, P), masks are (N,).

Patching with a mask. Missing samples are stored as NaN. A patch is marked observed only if all of its samples are present; masked patches are zero-filled so their values cannot leak into arithmetic, and the mask tells attention to ignore them.

import numpy as np

FS = 64                      # W1 sampling rate (Hz)
WIN = 10 * FS                # 640 samples per 10-s window

def synthetic_ppg(seconds=10, hr_bpm=60.0, fs=FS, seed=0):
    """A pulse-like waveform: fundamental + harmonic + small noise. Shape: (seconds*fs,)."""
    t = np.arange(seconds * fs) / fs
    f = hr_bpm / 60.0
    x = np.sin(2*np.pi*f*t) + 0.4*np.sin(4*np.pi*f*t + 0.8)
    return x + 0.05*np.random.default_rng(seed).standard_normal(t.size)

# ---------- 1. Patching with a missingness mask ----------
def patchify(x, patch, observed=None):
    """x: (T,) with NaN for missing samples. Returns patches (N, patch), patch mask (N,)
    where mask=1 means the patch is fully observed and safe to attend to."""
    T = x.size
    n = -(-T // patch)
    pad = n * patch - T
    xp = np.concatenate([x, np.full(pad, np.nan)])
    P = xp.reshape(n, patch)
    mask = (~np.isnan(P)).all(axis=1).astype(np.int8)
    P = np.nan_to_num(P, nan=0.0)        # values under mask=0 are never used
    return P, mask

x = synthetic_ppg()
P, m = patchify(x, 64)
assert P.shape == (10, 64) and m.sum() == 10
x_gap = x.copy(); x_gap[200:330] = np.nan          # ~2 s off-wrist
P2, m2 = patchify(x_gap, 64)
assert m2.tolist() == [1, 1, 1, 0, 0, 0, 1, 1, 1, 1]  # patches 3,4,5 touch the gap

Normalization and quantization. Instance normalization uses only observed patches and returns its statistics so they can travel as side inputs. The quantizer follows the mean-scaling recipe: divide by the mean absolute value, clip to \([-c, c]\), and map to integer bin ids. The test checks the bound derived at the math level, error at most half a bin width.

# ---------- 2. Instance normalization (RevIN-style) with side statistics ----------
def instance_norm(P, mask, eps=1e-5):
    """Standardize using observed patches only; return stats so level/scale stay available."""
    obs = P[mask == 1]
    mu, sd = obs.mean(), obs.std() + eps
    return (P - mu) / sd, np.array([mu, sd])

Z, stats = instance_norm(P2, m2)
assert abs(Z[m2 == 1].mean()) < 1e-9

# ---------- 3. Mean scaling + uniform quantization (Chronos-style) ----------
def quantize(x, n_bins=4094, c=15.0):
    """Divide by mean |x|, clip to [-c, c], map to integer bin ids 0..n_bins-1."""
    s = np.abs(x).mean()
    z = np.clip(x / s, -c, c)
    width = 2 * c / n_bins
    ids = np.minimum(((z + c) / width).astype(int), n_bins - 1)
    return ids, s, width

def dequantize(ids, s, width, c=15.0):
    return ((ids + 0.5) * width - c) * s             # bin centres

ids, s, width = quantize(x)
x_hat = dequantize(ids, s, width)
max_err_scaled = np.abs(x / s - x_hat / s).max()
assert max_err_scaled <= width / 2 + 1e-9          # error bounded by half a bin: c / B
print(f"scale={s:.3f} bin width={width:.5f} max scaled error={max_err_scaled:.5f}")

Lags, beats and cost. Lag tokens are built on a derived hourly series because lags of a day and a week only make sense there. The beat tokenizer smooths the waveform, finds systolic peaks with a refractory period of 0.4 s so that noise cannot create double peaks, resamples each beat to 32 points so tokens have fixed width, and returns the inter-beat intervals as a side input. The final loop reproduces the attention-cost table.

# ---------- 4. Lag features (Lag-Llama-style) ----------
def lag_tokens(x, lags):
    """Token t = [x_t, x_{t-l1}, x_{t-l2}, ...]; rows with any missing lag are dropped."""
    L = max(lags)
    rows = [np.r_[x[t], [x[t - l] for l in lags]] for t in range(L, x.size)]
    return np.array(rows)

hourly_hr = 60 + 8*np.sin(2*np.pi*np.arange(24*14)/24)   # two weeks of hourly resting HR
LT = lag_tokens(hourly_hr, lags=[1, 24, 168])
assert LT.shape == (24*14 - 168, 4)
assert np.allclose(LT[:, 0], LT[:, 2])             # 24-h lag repeats a daily cycle exactly

# ---------- 5. Per-beat tokens ----------
def beat_tokens(x, fs=FS, refractory_s=0.4):
    """Split at systolic peaks; each beat is resampled to 32 points.
    Smoothing plus a refractory period stops noise from creating double peaks."""
    xs = np.convolve(x, np.ones(7) / 7, mode="same")       # ~0.1 s moving average
    g = int(refractory_s * fs)
    cand = [i for i in range(1, xs.size - 1)
            if xs[i] >= xs[i-1] and xs[i] > xs[i+1] and xs[i] > 0.5 * xs.max()]
    kept = []
    for p in cand:
        if kept and p - kept[-1] < g:                      # too close: keep the taller peak
            if xs[p] > xs[kept[-1]]:
                kept[-1] = p
        else:
            kept.append(p)
    beats = [x[a:b] for a, b in zip(kept[:-1], kept[1:])]
    toks = np.array([np.interp(np.linspace(0, len(b)-1, 32), np.arange(len(b)), b) for b in beats])
    ibi = np.diff(kept) / fs                                # inter-beat intervals (s): a side input
    return toks, ibi

toks, ibi = beat_tokens(x)
assert 8 <= len(toks) <= 10 and abs(60 / ibi.mean() - 60) < 2
print("beats:", len(toks), "mean HR from IBI:", round(60/ibi.mean(), 1))

# ---------- 6. Attention cost by patch length ----------
for p in (1, 16, 32, 64, 128):
    n = -(-WIN // p)
    print(f"P={p:4d}  tokens={n:4d}  attention pairs={n*n:7d}")

Running the file prints:

scale=0.663 bin width=0.00733 max scaled error=0.00366
beats: 9 mean HR from IBI: 59.9
P=   1  tokens= 640  attention pairs= 409600
P=  16  tokens=  40  attention pairs=   1600
P=  32  tokens=  20  attention pairs=    400
P=  64  tokens=  10  attention pairs=    100
P= 128  tokens=   5  attention pairs=     25
Worked example · W1

The 2-second off-wrist gap (samples 200 to 329) masks patches 3, 4 and 5 (counting from 0), three seconds of tokens for two seconds of missing data, because patches 3 and 5 are only partly missing. The quantizer's worst error is 0.00366 in scaled units, exactly \(c/B\). The beat tokenizer finds 10 peaks, hence 9 complete beats in 10 seconds, and the mean inter-beat interval gives 59.9 bpm against the 60 bpm used to synthesize the waveform.

Debugging tips specific to signal tokenizers. A first version of the beat detector without smoothing and refractory period found 11 peaks on this window, two of them 0.375 s apart, because noise split one peak in two; checking that the implied heart rate is plausible is the quickest test. Plot patch boundaries over the waveform for a few windows from each device model. Assert the sampling rate before windowing, since a 128 Hz stream cut into 640-sample windows silently becomes 5-second windows. Check that the masked-patch fraction per device matches the wear-detection logs. In a deep-learning framework, pass the patch mask as a key-padding mask to attention, so masked positions are excluded from the softmax rather than merely zeroed.

At W1 scale the signal tokenizer is a data pipeline that runs over billions of windows, and its production problems are throughput, silent contract violations and missing data.

Throughput and storage. The problem is input bandwidth. W1 holds about 10.8 billion window slots (30 million participant-hours times 360 windows per hour); reading the series as including unworn time, 38% of hours carry no PPG, leaving about 6.7 billion windows with signal. Sampling 1% per epoch is about 108 million windows. Assuming four channels (PPG plus three accelerometer axes) stored as 16-bit floats, one epoch reads \(108 \times 10^6 \times 640 \times 4 \times 2\) bytes, about 553 GB. Patching is a reshape, so its compute is negligible; the cost is entirely in reading, resampling and quality checks. The remedy is to precompute windows into shards keyed by participant and hour, with masks and normalization statistics stored alongside, and to stream shards rather than random-access raw files. The trade-off: precomputed shards freeze the tokenizer, so a change of patch length or normalization requires a rebuild; keeping raw-to-window on the fly costs CPU but allows ablations. A common compromise stores 10-second windows (the expensive part: resampling, wear detection) and patches on the fly.

Two-row pipeline: device stream, rate check and resampling, wear and quality detection, windowing; then patch and mask, normalization with side statistics, and sharding.Device streamPPG + acceldevice, fw, fsRate contractassert fs = 64anti-alias resampleWear + QCoff-wrist, clippingmotion flagsWindow10 s = 640samplesPatch + maskP = 64 → 10mask per patchNormalizeper windowμ, σ keptShardtokenizer hashper-device stats
Fig. Signal tokenization as a pipeline with explicit contracts. The rate check (highlighted) rejects or correctly resamples any stream that is not 64 Hz before windowing; masks and normalization statistics travel with every patch so missing data and absolute level are never silently lost.

Contract violations. The root cause of the worst signal-tokenizer failures is an unstated assumption about the input: sampling rate, units (raw counts versus normalized), channel order, or firmware filtering. Patching does not check any of these; it reshapes whatever arrives.

Worked incident · W1

Illustrative incident. A new watch generation, worn by about 12% of participants after a rollout, records PPG at 128 Hz. Ingestion skips resampling for that device model, so each 640-sample window covers 5 seconds instead of 10 and a 60 bpm pulse completes one cycle every 128 samples, which the model reads as 30 bpm. Symptom: resting heart rate MAE on the linear probe rises from 2.4 bpm to 6.8 bpm for the new device and stays at 2.4 for others; AFib AUROC is unchanged overall but drops on the new device. Measurements that separate causes: a per-device histogram of the dominant frequency per window, computed assuming 64 Hz, shows the new device's mass at half the expected frequency (0.5 Hz instead of about 1 Hz), whereas a genuine population difference would shift heart rate without halving it; the device metadata field reports 128 Hz. Intervention: a rate contract at ingestion that reads the device's declared rate, applies an anti-aliasing low-pass filter and decimates by 2 (polyphase resampling), and rejects any stream without a declared rate. Re-tokenizing the affected shards touches about 12% of windows. Validation: after re-tokenization, the dominant-frequency histogram for the new device overlaps the old ones, and resting heart rate MAE on the new device returns to within 0.3 bpm of 2.4 without retraining the encoder. If MAE stays high after the fix, the device also differs in waveform morphology (sensor geometry, LED wavelength) and needs device-aware fine-tuning or device as a side input.

Missing data at scale. The problem is that 38% of W1 hours have no PPG, and the treatment of that gap decides what the model learns. Imputing and tokenizing teaches the model to reconstruct the imputer; zero-filling without a mask teaches it that flat lines are physiology. The remedy has three parts: sample windows only from worn time for window-level pretraining; for contexts longer than a window (an hour, a day), drop missing tokens before the encoder and pass a key-padding mask, which is the core of AIM; and expose missingness explicitly as a side feature when it is informative, since charging and off-wrist patterns themselves carry behavioral signal. Diagnosis: track the masked-patch fraction per device model and firmware, the fraction of partially masked windows (wear transitions), and probe performance stratified by wear time. With an assumed average worn segment of 2 hours, only the two windows at each segment boundary are partial, about \(2/720 \approx 0.3\%\) of windows; a sudden rise in that fraction points to a wear-detection change rather than to behavior. Cost: masking adds bookkeeping, and dropping tokens produces variable-length batches that need padding or bucketing. Validation: LSM-2 reports that a model trained this way degrades less when whole sensors or parts of the day are removed (Xu et al. 2025); the W1-specific test is to remove 10%, 30% and 50% of hours from held-out participants and check that probe metrics fall gradually rather than abruptly.

Choosing patch length in production. Patch length sets both cost and the finest detail a token can carry. The diagnosis is a sweep: train small encoders at \(P \in \{32, 64, 128\}\) on the same data budget and compare probe metrics that depend on fine timing (heart-rate error, AFib detection) with those that do not (age). For W1, \(P = 64\) gives 10 tokens per window; \(P = 32\) doubles tokens and roughly quadruples attention cost for a window that is already cheap, so the decision is driven by accuracy, not compute, at window level, and by compute only when contexts grow to hours.

Metric (W1 tokenizer)TargetDiagnoses
Declared vs. assumed sampling rate100% match, rejects loggedrate-contract violations
Dominant frequency per window, by deviceoverlapping distributions, 0.7–3 Hzresampling bugs, sensor faults
Masked-patch fraction, by device and firmwarestable within ±5 pointswear-detection changes
Clipped-value fraction (if quantized)< 0.1% of samplesartifacts, scale errors
Shard read throughput≥ trainer consumption rateinput-bound training
Probe metrics by deviceHR MAE within 0.5 bpm of 2.4device-specific regressions

Each of these measures one clause of the tokenizer contract: the unit (rate and window length), the value representation (normalization, clipping) and missing data (masks). The events section applies the same discipline to codes, units and time.

Clinical events: codes, time and values

An EHR record looks closer to text than a waveform does, because its entries are already discrete codes: a diagnosis code such as ICD-10 E11.9 (type 2 diabetes without complications), a drug, a procedure, a lab test. Yet a word tokenizer would miss three things every clinical event carries: when it happened, what value it had, and which visit it belonged to. Two sentences in a book are adjacent whether they were written a minute or a year apart; two diagnoses in a record are not. EHR tokenization is the set of decisions that makes time, values and visits visible to a sequence model.

The input to the tokenizer is a patient timeline: a list of events, each with a patient identifier, a timestamp, a code and optionally a numeric value. The Medical Event Data Standard (MEDS) fixes exactly this shape: every dataset becomes rows with a subject id, a time and a code, with optional numeric and text values, plus metadata files listing every code and the assignment of subjects to train, tuning and held-out splits (MEDS schema). Because MIMIC-IV, EHRSHOT and institutional data can all be converted to MEDS, a tokenizer written once can be shared across them. The tokenizer's output is a sequence of integer ids, sometimes with parallel arrays such as age or time for each token.

Tokenizing a patient timeline into code, value and time tokens. Visit 1 · Mar 2019 · age 54 Visit 2 · Sep 2019 Visit 3 · Nov 2021 time → [VISIT] DX:E11.9 RX:metformin LAB:HbA1c·Q9 [26 wk] [VISIT] LAB:HbA1c·Q6 [2 yr] DX:I50 visit-1 eventstime tokenvisit-2 eventstime tokennew diagnosis Summed embeddings code + age + position + visit segment BEHRT, Med-BERT Explicit time tokens artificial gap tokens between visits, plus time embeddings CEHR-BERT, CEHR-GPT, ETHOS Values as tokens numeric labs binned into per-test quantiles (Q1–Q10) ETHOS, CoMET-style
Fig. A patient timeline as tokens. Codes become vocabulary items, lab values become quantile tokens, and time gaps become either embeddings added to every token or explicit gap tokens. The three boxes are the main design patterns; real models mix them. The patient and values are invented for illustration.

The design space has narrowed to a few patterns, which real models mix.

  • Codes as vocabulary. Raw code vocabularies run to hundreds of thousands of entries, most of them rare. Typical steps map local codes to a standard ontology (for example OMOP concepts), drop codes below a count threshold or roll them up the hierarchy to a parent, and reserve an unknown token for the rest. Epic's CoMET models (renamed Curiosity in a later version of the paper) used a fixed vocabulary of 7,105 tokens built from ontology codes rather than a learned subword vocabulary (Waxler et al. 2025).
  • Summed embeddings for time and visits. BEHRT (Li et al. 2019) adds a code embedding, an age embedding, a position embedding and a visit-segment embedding for every token, borrowing BERT's segment trick to mark visits. Time is then a property of each token, not a token of its own.
  • Explicit time tokens. CEHR-BERT (Pang et al. 2021) inserts artificial time tokens between visits that state the size of the gap, and also adds time and age embeddings, so the model sees both order and spacing; CEHR-GPT carries the idea into a generative model that must produce the gaps as well as the codes (Pang et al. 2024).
  • Values as tokens. A lab result needs its number. The common answer is to bin each lab's values into quantiles computed separately per test, so "HbA1c in the top decile" becomes a token. Generative models that must output labs need such value tokens; ETHOS represents a patient as a tokenized Patient Health Timeline in which time gaps and values are tokens alongside codes (Renc et al. 2024).
Worked example · W2

W2 uses explicit time and value tokens over MEDS rows. Its vocabulary holds 42,000 codes, 64 time-gap tokens and 10 value-decile tokens, plus a handful of special tokens. A numeric lab emits two tokens: the code, then a decile token whose boundaries are computed separately for each lab on training patients only. A gap between events becomes one of the 64 gap tokens, spaced logarithmically from under an hour to over 20 years. For the timeline in the figure, a diabetes diagnosis, a metformin prescription and an HbA1c of 8.4% become DX//E11.9, RX//metformin, LAB//HbA1c, [Q10]; the 26-week gap to the next visit becomes [GAP44]; the next HbA1c of 6.9% becomes LAB//HbA1c, [Q7]. A median patient (96 events) becomes about 142 tokens; the 95th percentile (1,450 events) about 2,078, inside the 4,096-token context.

One pitfall is specific to EHR tokens: repeated codes. A chronic diagnosis is re-recorded at many visits, often copied forward from the previous note, and a model rewarded for predicting the next code learns to copy. Rajamohan et al. (2025) showed that unless new onsets are distinguished from repeats, metrics are inflated, and added a regularizer for repeated events. Wornow et al. (2025) measured three properties of EHR sequences that text lacks (copy-forwarded repetition, irregular time intervals between events, and disease progression that makes later events harder to predict) and found each associated with lower model performance, with longer-context models more robust.

Work from 2025–2026 has started to compare these choices head to head. In pediatric EHR data, encoding a code and its attributes jointly in one token beat splitting them across tokens on 73 of 74 prediction tasks while needing 39.5% fewer pretraining FLOPs (Guo et al. 2026). In inpatient hospitalization data, fused code-and-decile tokens beat separate code and value tokens on all eight outcome families tested, finer quantization and anchoring bins to reference ranges did not help consistently, and order-based positions gave higher point estimates than explicit time tokens while shortening the input (Lee et al. 2026). On MIMIC-IV, removing time features entirely made no statistically significant difference on any task tested, while removing values hurt mortality prediction (Al Attrach et al. 2025). One reading of these results, an interpretation rather than a finding of any single paper, is that values and local binding of code to value matter almost everywhere, while how time is encoded matters most when histories are long and irregular, as in outpatient records, and least within a single admission.

Compared with a word tokenizer, an EHR tokenizer adds time and values; compared with the hand-built count features of earlier risk models, it keeps order and spacing. The contrast is in cost: every added token type lengthens the sequence or the vocabulary. The mental model is the same contract as for signals: a fixed unit (the event, possibly fused with its value), a fixed value representation (per-lab quantiles), and an explicit treatment of time, all fitted on training patients and applied only to events recorded before the prediction time.

A patient record is a sequence of events \(\{(t_i, c_i, v_i)\}_{i=1}^{n_e}\) with time \(t_i\), code \(c_i \in \mathcal{C}\) and value \(v_i \in \mathbb{R} \cup \{\varnothing\}\). The tokenizer produces ids from a vocabulary \(V = S \cup G \cup Q \cup \mathcal{C}'\): special tokens \(S\), gap tokens \(G\), value tokens \(Q\) and the retained codes \(\mathcal{C}' \subseteq \mathcal{C}\).

Code retention. A code is kept if its training count \(n_c \ge n_{\min}\); otherwise it maps to an unknown token or to its parent. The unknown-token rate on new data, \(\sum_{c \notin \mathcal{C}'} n_c / \sum_c n_c\), measures what the threshold costs.

Value tokens. For a numeric lab \(c\), let \(F_c\) be the empirical distribution of its training values. Decile edges are \(q_{c,k} = F_c^{-1}(k/10)\) for \(k = 1, \dots, 9\), and a value maps to \[ d(v) = 1 + \#\{k : v \ge q_{c,k}\} \in \{1, \dots, 10\}. \] Under the training distribution each decile token has probability 0.1, so a value token carries at most \(\log_2 10 \approx 3.32\) bits. The edges are fitted per lab because the same number means different things for different tests.

Fused versus separate value tokens. A separate design emits a code token and a shared decile token, adding \(|Q| = 10\) entries to \(V\) and one extra token per numeric event. A fused design emits a single token per (lab, decile) pair, adding \(10 \cdot n_{\text{lab}}\) entries and no extra positions. With a fraction \(f\) of events numeric, the separate design's length is \(n_e(1 + f) + g\) and the fused design's is \(n_e + g\).

Worked example · W2

With \(f = 0.35\) (an assumption for illustration), the 95th-percentile patient is \(1{,}450 \times 1.35 + 120 = 2{,}078\) tokens in W2's separate design and \(1{,}450 + 120 = 1{,}570\) fused, 24% shorter. Assuming 1,200 numeric lab codes, fusion replaces those 1,200 code tokens and the 10 shared decile tokens with 12,000 fused tokens, a net 10,790 extra entries, or about 8.3 million parameters at \(d = 768\). An HbA1c of 8.4% against training edges from values distributed around 6.5% with spread 1.2 lies above \(q_{9}\) and maps to Q10; 6.9% lies between \(q_{6}\) and \(q_{7}\) and maps to Q7.

Gap tokens. Let \(\Delta t\) be the time since the previous event, in hours. W2 uses 64 bins: bin 0 for \(\Delta t < 1\) h, bin 63 for \(\Delta t \ge 20\) years \(= 175{,}200\) h, and 62 log-spaced bins in between with edge ratio \(r = 175{,}200^{1/62}\): \[ k(\Delta t) = 1 + \left\lfloor \log_r \Delta t \right\rfloor, \qquad 1 \le \Delta t < 175{,}200. \] Since \(\ln r = \ln 175{,}200 / 62 = 12.074/62 = 0.1947\), \(r \approx 1.215\): each bin spans about 21.5% more time than the previous one, so the relative error of reading a gap from its token is roughly ±10%, at every scale.

A logarithmic time axis from under one hour to over twenty years, divided into 64 gap bins, with two marked gaps: 26 weeks in bin 44 and 2 years in bin 51.1 h1 d1 wk1 mo1 yr20 yrbin 0: < 1 hbin 63: ≥ 20 yr26 wk → GAP442 yr → GAP51edges at 1 h × 1.215^k: every bin spans about 21.5% more time than the one before
Fig. The 64 W2 time-gap tokens on a logarithmic axis. Bin 0 holds gaps under an hour, bins 1–62 are log-spaced between 1 hour and 20 years, and bin 63 holds longer gaps. Equal relative resolution means a 1-hour difference matters at the scale of hours and a 1-month difference at the scale of years.
Worked example · W2

The gap from the first to the second visit in the example timeline is 182 days and 1 hour, \(\Delta t = 4{,}369\) h. Then \(\ln 4{,}369 = 8.382\), \(8.382 / 0.1947 = 43.05\), and \(k = 1 + 43 = 44\): token [GAP44]. A two-year gap (17,532 h) gives \(\ln 17{,}532 / 0.1947 = 50.2\), so \(k = 51\). An alternative to gap tokens is a continuous time embedding, such as sinusoids of age \(\phi(a) = (\sin \omega_j a, \cos \omega_j a)_j\) added to every token, as in BEHRT-style summed embeddings; it costs no positions but gives the model time only implicitly.

Repeated codes and inflated metrics. Let \(\rho\) be the fraction of target tokens that repeat a code already present in the patient's history, and let a model have accuracy \(a_{\text{rep}}\) on repeats and \(a_{\text{new}}\) on new onsets. Overall accuracy is \(\rho\, a_{\text{rep}} + (1 - \rho) a_{\text{new}}\). With illustrative values \(\rho = 0.6\), \(a_{\text{rep}} = 0.9\) and \(a_{\text{new}} = 0.2\), overall accuracy is 0.62 while the clinically relevant new-onset accuracy is 0.2. Reporting \(a_{\text{new}}\) separately, or evaluating on new-onset tasks, removes the inflation that Rajamohan et al. (2025) describe.

Leakage. Two constraints make a tokenized sequence valid for prediction at index time \(t_0\): only events with recording time \(t_i < t_0\) are tokenized, and every fitted quantity (\(\mathcal{C}'\), \(q_{c,k}\)) is computed from training patients only. Edges fitted on all patients encode test-set statistics; for W2's temporal holdout (train up to 2022, test 2024), edges fitted on 2024 data would encode future practice patterns.

Scale. CoMET's largest study reported power-law scaling with a compute-optimal ratio of roughly 1,000 training tokens per parameter (Waxler et al. 2025). For a 120M-parameter model that ratio implies about 120 billion training tokens; W2's 310 million events become, under the 35% numeric assumption and a gap token for roughly one event in ten, about 450 million tokens, so a compute-optimal run would make several hundred passes. Tokenizer choices that shorten sequences, such as fusion, cut the cost of every pass without changing that ratio.

The tokenizer below turns MEDS-like rows into W2 token ids. Its input is a list of dicts with keys subject_id, time, code and numeric_value, the MEDS column names. Its output is a list of integer ids and a parallel list of repeat flags (1 if the code already appeared for this patient), which evaluation uses to report new-onset metrics separately. It implements the 64 log-spaced gap bins, per-lab decile edges fitted on training data only, strict filtering at the index time, and truncation that keeps the most recent history.

import math
from collections import Counter, defaultdict
from datetime import datetime, timedelta
import numpy as np

# ---------- vocabulary pieces (W2 layout) ----------
SPECIAL = ["[PAD]", "[UNK]", "[BOS]", "[VISIT]"]
N_GAP = 64                         # 64 time-gap tokens
GAP_MIN_H, GAP_MAX_H = 1.0, 20 * 365 * 24    # 1 hour .. 20 years
R = (GAP_MAX_H / GAP_MIN_H) ** (1 / (N_GAP - 2))   # ratio between bin edges

def gap_bin(dt_hours: float) -> int:
    """0: < 1 h; 1..62: log-spaced bins between 1 h and 20 y; 63: >= 20 y."""
    if dt_hours < GAP_MIN_H:
        return 0
    if dt_hours >= GAP_MAX_H:
        return N_GAP - 1
    return 1 + int(math.log(dt_hours / GAP_MIN_H, R))

def fit_vocab(train_events, min_count=20, n_dec=10):
    """train_events: MEDS-like dicts (subject_id, time, code, numeric_value).
    Fit ONLY on training patients: codes above min_count, per-lab decile edges."""
    counts = Counter(e["code"] for e in train_events)
    vals = defaultdict(list)
    for e in train_events:
        if e["numeric_value"] is not None:
            vals[e["code"]].append(e["numeric_value"])
    tok = SPECIAL + [f"[GAP{k}]" for k in range(N_GAP)] + [f"[Q{d+1}]" for d in range(n_dec)]
    tok += sorted(c for c, n in counts.items() if n >= min_count)
    edges = {c: np.quantile(v, np.linspace(0, 1, n_dec + 1)[1:-1])
             for c, v in vals.items() if len(v) >= min_count}
    return {t: i for i, t in enumerate(tok)}, edges

def tokenize(events, vocab, edges, index_time, max_len=4096):
    """Tokens for one patient using events recorded strictly before index_time.
    Each numeric event emits its code token followed by a per-lab decile token.
    Also returns a 'repeat' flag per token (code seen before for this patient)."""
    ev = sorted((e for e in events if e["time"] < index_time), key=lambda e: e["time"])
    ids, rep, seen, last = [vocab["[BOS]"]], [0], set(), None
    for e in ev:
        if last is not None and e["time"] > last:
            dt_h = (e["time"] - last).total_seconds() / 3600
            ids.append(vocab[f"[GAP{gap_bin(dt_h)}]"]); rep.append(0)
        ids.append(vocab.get(e["code"], vocab["[UNK]"])); rep.append(int(e["code"] in seen))
        seen.add(e["code"])
        if e["numeric_value"] is not None and e["code"] in edges:
            d = int(np.searchsorted(edges[e["code"]], e["numeric_value"], side="right"))
            ids.append(vocab[f"[Q{d+1}]"]); rep.append(0)
        last = e["time"]
    if len(ids) > max_len:                      # keep [BOS] + the most recent history
        ids, rep = ids[:1] + ids[-(max_len - 1):], rep[:1] + rep[-(max_len - 1):]
    return ids, rep
Two-row data flow of the tokenize function: MEDS rows, index-time filter, sort, per-event emission of gap, code and decile tokens, truncation, and output ids with repeat flags.MEDS rowssubject_id, time,code, numeric_valueIndex filterkeep time < t0(recording time)Sort by timestable orderwithin a timestampGap tokenΔt > 0 → GAP kk = 1 + ⌊log_r Δt⌋Code tokenvocab id or UNKrepeat flagDecile tokennumeric → Q dtrain-only edgesTruncateBOS + last 4,095ids, repeat flags
Fig. Data flow of tokenize() for one W2 patient. The index-time filter (highlighted) runs first, so nothing downstream can see an event recorded at or after the prediction time; gap, code and decile tokens are emitted per event in time order; truncation keeps the beginning-of-sequence token and the most recent history.

The tests build a 500-patient training set in which HbA1c values are drawn around 6.5% with spread 1.2, fit the vocabulary, and tokenize the timeline from the figure with an index time on the day of the heart-failure diagnosis.

# ---------- tests ----------
assert abs(R - 1.2150) < 1e-3                         # ~21.5% relative width per gap bin
assert gap_bin(0.5) == 0 and gap_bin(1.0) == 1 and gap_bin(30 * 365 * 24) == 63
assert gap_bin(26 * 7 * 24) != gap_bin(2 * 365 * 24)   # 26 weeks vs 2 years differ

rng = np.random.default_rng(0)
t0 = datetime(2019, 3, 4)
train = [{"subject_id": s, "time": t0, "code": "LAB//HbA1c", "numeric_value": float(v)}
         for s, v in enumerate(rng.normal(6.5, 1.2, 500))]
train += [{"subject_id": s, "time": t0, "code": c, "numeric_value": None}
          for s in range(500) for c in ("DX//E11.9", "RX//metformin", "DX//I50")]
vocab, edges = fit_vocab(train)
assert len(vocab) == 4 + 64 + 10 + 4                  # specials + gaps + deciles + 4 codes

pt = [
    {"time": datetime(2019, 3, 4, 9),  "code": "DX//E11.9",     "numeric_value": None},
    {"time": datetime(2019, 3, 4, 9),  "code": "RX//metformin", "numeric_value": None},
    {"time": datetime(2019, 3, 4, 9),  "code": "LAB//HbA1c",    "numeric_value": 8.4},
    {"time": datetime(2019, 9, 2, 10), "code": "LAB//HbA1c",    "numeric_value": 6.9},
    {"time": datetime(2019, 9, 2, 10), "code": "DX//E11.9",     "numeric_value": None},
    {"time": datetime(2021, 11, 8, 8), "code": "DX//I50",       "numeric_value": None},
]
inv = {i: t for t, i in vocab.items()}
ids, rep = tokenize(pt, vocab, edges, index_time=datetime(2021, 11, 8))
print([inv[i] for i in ids], rep)
assert "DX//I50" not in [inv[i] for i in ids]         # event at index time is excluded
assert [inv[i] for i in ids][3:5] == ["LAB//HbA1c", "[Q10]"]   # 8.4% is a top-decile value
assert rep[[inv[i] for i in ids].index("DX//E11.9", 6)] == 1   # re-recorded diabetes = repeat
ids_all, _ = tokenize(pt, vocab, edges, index_time=datetime(2022, 1, 1))
assert inv[ids_all[-1]] == "DX//I50"

Running it prints the decoded tokens and repeat flags:

['[BOS]', 'DX//E11.9', 'RX//metformin', 'LAB//HbA1c', '[Q10]', '[GAP44]', 'LAB//HbA1c', '[Q7]', 'DX//E11.9'] [0, 0, 0, 0, 0, 0, 1, 0, 1]
Worked example · W2

The output matches the math level: 8.4% maps to Q10, 6.9% to Q7, and the 4,369-hour gap to [GAP44]. The heart-failure code recorded at 08:00 on the index day is excluded because the index time is midnight of that day; moving the index time to 2022 includes it as the final token. The re-recorded diabetes code carries repeat flag 1, so an evaluation of next-code prediction can separate it from a genuine new onset.

Two details matter more than the model. The filter is strict (e["time"] < index_time), and it must use the time an event was recorded, not its clinical time, when the two differ: a lab drawn before the index time but resulted after it was not available to a clinician at the index time. And fit_vocab receives training patients only; computing quantile edges on all patients leaks test-set statistics into every value token. Debugging tips: decode ten random patients and read them; compare the unknown-token rate on training and held-out data (a large gap means the count threshold or code mapping differs between them); and check that no tokenized sequence contains an event at or after its index time, a test worth running on every new data release.

In production, the EHR tokenizer runs over a living record whose codes, units and documentation habits change. Four problems account for most failures: value-token drift, vocabulary drift, sequence length, and leakage through time.

Value-token drift. The problem is that a decile token means "this value relative to the training distribution of this lab", and anything that changes the number without changing the patient breaks that meaning. The root causes are unit changes (creatinine in mg/dL versus µmol/L differs by a factor of 88.4), assay changes, and reference-range changes. Diagnosis uses the population stability index (PSI): for each lab, compare the share of values in each decile token on new data, \(a_k\), with the training share \(e_k = 0.1\), as \(\text{PSI} = \sum_k (a_k - e_k)\ln(a_k/e_k)\). Values below 0.1 are usually treated as stable and above 0.25 as a material shift; it is cheap, per lab, and needs no labels.

import numpy as np

def decile_shares(values, edges):
    """Share of values in each of the 10 decile tokens defined by training edges."""
    d = np.searchsorted(edges, values, side="right")
    return np.bincount(d, minlength=10) / len(values)

def psi(expected, actual, eps=1e-4):
    """Population stability index between two token-share vectors."""
    e, a = np.clip(expected, eps, None), np.clip(actual, eps, None)
    return float(np.sum((a - e) * np.log(a / e)))

rng = np.random.default_rng(1)
train = rng.lognormal(np.log(1.0), 0.3, 50_000)          # creatinine, mg/dL
edges = np.quantile(train, np.linspace(0, 1, 11)[1:-1])
base = decile_shares(train, edges)

ok_month  = rng.lognormal(np.log(1.0), 0.3, 8_000)
bad_month = np.concatenate([rng.lognormal(np.log(1.0), 0.3, 3_040),
                            88.4 * rng.lognormal(np.log(1.0), 0.3, 4_960)])  # 62% now in umol/L
for name, m in [("normal month", ok_month), ("unit change", bad_month)]:
    sh = decile_shares(m, edges)
    print(f"{name:12s} Q10 share={sh[9]:.2f}  PSI={psi(base, sh):.3f}")
assert psi(base, decile_shares(ok_month, edges)) < 0.02
assert decile_shares(bad_month, edges)[9] > 0.6

The script prints a Q10 share of 0.10 and PSI 0.001 for a normal month, and a Q10 share of 0.66 and PSI 1.601 for the month with the unit change.

Two bar charts of creatinine decile-token shares: a baseline month with ten equal bars and an incident month where Q10 holds 66 percent; a panel to the right shows PSI values.Baseline monthQ1Q2Q3Q4Q5Q6Q7Q8Q9Q10share of creatinine value tokensIncident monthQ1Q2Q3Q4Q5Q6Q7Q8Q9Q10share of creatinine value tokens66%PSIbaseline 0.001incident 1.60alert > 0.25
Fig. A token-share panel from the W2 drift monitor (illustrative incident). Under the training edges each decile token holds 10% of creatinine values; after one site switches to µmol/L, 62% of values arrive about 88 times larger and land in Q10, which then holds 66%. The population stability index (PSI) jumps from 0.001 to 1.60.
Worked incident · W2

Illustrative incident. In 2024 one site in the W2 network switches creatinine reporting from mg/dL to µmol/L, and 62% of new creatinine values arrive about 88 times larger. All of them map to Q10, whose share rises from 10% to 66%; PSI for creatinine jumps from 0.001 to 1.60 while other labs stay below 0.05. Downstream, predicted risk at that site rises because Q10 creatinine signals kidney failure; 30-day readmission calibration at the site worsens while AUROC at other sites is unchanged. Measurements that separate causes: a genuine change in case mix would move several kidney-related labs and diagnoses together and would not produce values near 88 times the training median; a unit change moves one lab, at one site, abruptly, and the raw-value histogram shows a second mode at about 88 times the first. Intervention: normalize units before binning (map every lab to a canonical unit with an explicit conversion table, and reject values whose unit is missing), then re-tokenize the affected records. Cost: maintaining the unit table and re-tokenizing one site's records since the change; no retraining is needed because the model's tokens regain their training meaning. Validation: creatinine PSI returns below 0.1 and the site's calibration error returns to the 0.03 level of other sites; if calibration stays off after the fix, the site differs in population and needs recalibration.

Vocabulary drift. New drugs, new procedure codes and annual code-system updates create codes the tokenizer has never seen. With a frozen vocabulary they become the unknown token, and a growing unknown rate is the symptom. Remedies, in increasing cost: map new codes to an existing parent in the ontology at tokenization time (no retraining; loses specificity); reserve unused vocabulary slots and fine-tune their embeddings on recent data; or rebuild the vocabulary and retrain. A text-based alternative represents each code by an embedding of its description from a language model; on MIMIC-IV, a frozen clinical text encoder came within about one AUROC point of a learned code embedding on post-discharge mortality (Al Attrach et al. 2025), which makes unseen codes representable at the price of a larger encoder at tokenization time. Validation for any remedy is the unknown-token rate on the latest month and probe performance on patients whose histories contain new codes.

Sequence length and repetition. The 4,096-token context holds the W2 95th percentile with room to spare, but the tail grows as records lengthen, and copy-forwarded codes fill context without adding information. Diagnosis: length percentiles per release, truncation share, and the repeat fraction per patient. Remedies: keep the most recent tokens (the default in the code above), deduplicate repeated codes within a visit while keeping the first occurrence and the count, or fuse value tokens to save one position per numeric event. Fusion is the change most supported by recent evidence: joint encoding of code and attributes won on 73 of 74 tasks at 39.5% fewer pretraining FLOPs in Guo et al. (2026), and fused code-value tokens won on all eight outcome families in Lee et al. (2026). For W2 the trade-off is concrete: 24% shorter sequences at the 95th percentile against about 10,790 more vocabulary entries (under the 1,200-lab assumption) and a full retrain. The test that would confirm the switch is a matched-compute comparison of separate and fused tokenizers on W2's temporal holdout; a gain on mortality AUROC beyond seed-to-seed variation supports the switch, while equal AUROC with better calibration would support it only on cost grounds.

Leakage through time. The index-time filter is only as good as the timestamps. Results that are drawn before the index time but finalized after it, discharge codes back-dated to admission, and notes amended later all leak when the tokenizer uses clinical rather than recording time. Diagnosis: for each task, compute performance using only events recorded at least one day before the index time; a large drop relative to the default suggests the model was using events near the boundary that would not be available in deployment. Remedy: tokenize on recording time, and fit all artifacts on the training period only (for W2, data up to 2022).

Metric (W2 tokenizer)TargetDiagnoses
Per-lab decile PSI, per site< 0.1; alert > 0.25units, assays, edge leakage
Unknown-token rate, latest month< 0.5% of code tokensvocabulary drift
Truncation share< 5% of patientsrecord growth, repetition
Repeat fraction of target tokensreported with every next-code metriccopy-driven metric inflation
Events at or after index time0timestamp leakage
Calibration error per siteECE ≈ 0.03site-specific token shifts

These controls close the loop with the chapter's contract: per-lab edges and units keep value tokens meaningful, vocabulary monitoring keeps codes meaningful, and recording-time filtering keeps the sequence causal. The next chapter builds forecasting models on top of tokenized signals and evaluates them zero-shot, where the same normalization and patching choices reappear.

Time-Series Foundation Models

A time-series foundation model (TSFM) is a neural network pretrained on billions of observations drawn from many unrelated domains (retail demand, electricity load, web traffic, weather, server metrics, synthetic signals) so that it can forecast, impute or classify a series it has never seen, without being retrained on it. Classical forecasting fits one model per series; a TSFM fits one model for all series. The chapter follows the path between those two poles and asks what it means for health data.

Health data is unusual inside that story. Wearable heart rate, heart-rate variability (HRV), continuous glucose and bedside vitals are time series, so TSFMs apply to them directly. Yet they are a small slice of TSFM pretraining corpora, they are full of gaps when a device is off the wrist, and in medicine forecasting is rarely the end task: a clinician seldom needs tomorrow's heart rate, but often needs to know whether today's is abnormal for this patient.

From local forecasters to pretrained time-series models and their role in health.Local modelsone model per seriesARIMA, ETS (1970s-)Global modelsone model, many seriesDeepAR, N-BEATSPretrained TSFMsone model, any seriesTimesFM, Chronos, MoiraiHealth usebaseline, imputer,aggregate forecasterWhat is shared across series grows at each stepCh 6 · rootsCh 6 · rootsCh 6 · models, evalCh 6 · healthSpecialized biosignal encoders (Ch 7) are the comparison for the last step
Fig. The arc of the chapter. Each step shares more across series: local models share nothing, global models share parameters across a related collection, pretrained models share parameters across domains. The last box is the health question the chapter ends on.

The chapter has four parts. The roots traces forecasting from local statistical models (ARIMA, exponential smoothing) through global neural models (DeepAR, N-BEATS) and the episode in which a one-layer linear model beat forecasting transformers. The models describes the main TSFM families: decoder-only patch models (TimesFM, Toto, Moirai 2.0), forecasting as language modelling (Chronos), masked encoders (Moirai, MOMENT), lag-feature and hosted models (Lag-Llama, TimeGPT), and the 2025–2026 turn towards covariates and multivariate context (Chronos-2, TimesFM 3). Evaluation covers benchmarks, scale-free metrics and the leakage that makes "zero-shot" claims hard to trust. Health evidence collects what has been measured on physiological data.

Worked example · W1 The reference workload W1 is a wearable PPG foundation model: 150,000 participants, 30 million participant-hours of PPG and accelerometry at 64 Hz, 38% of hours with no PPG because the device is off the wrist or charging. For this chapter W1's PPG is aggregated to an hourly mean heart rate per participant. The forecasting task is: given 7 days (168 hourly values) of context, forecast the next 24 hours. The evaluation set is the 5,000 labelled W1 participants, one held-out week each, taken after any pretraining cutoff. All W1 numbers are illustrative.

The mental model to carry through the chapter: a TSFM is a strong, cheap, general baseline for forecasting smooth physiological aggregates, and a weak substitute for a modality-specific encoder when the goal is a representation of health. Chapter 7 builds those specialised encoders.

Formally, a univariate series is a sequence \(y_1, \dots, y_T\) observed at a fixed sampling interval. A forecaster maps a context of length \(T\) to a predictive distribution over the next \(H\) values, \(p(y_{T+1:T+H} \mid y_{1:T})\). A local model estimates parameters \(\theta_i\) separately for each series \(i\); a global model estimates one \(\theta\) shared by all series in a collection; a foundation model estimates one \(\theta\) on a corpus that spans many collections and then applies it, frozen, to new ones. The chapter derives the quantities that decide whether that transfer works.

QuantitySymbolW1 value (illustrative)Section
Context and horizon\(T, H\)168 h, 24 hRoots
Seasonal period\(m\)24 hRoots
Tokens per context\(\lceil T/P \rceil\)6 patches of 32; raw PPG window: 20Models
Quantization resolution\(30 s / B\)0.513 bpm at \(s = 70\) bpm, \(B = 4{,}094\)Models
Scaled errorMASE0.84 (TSFM) vs 0.93 (ETS)Evaluation
Missing hours\(1-\bar o\)38%Health

Table. The quantities this chapter derives, evaluated for the W1 hourly heart-rate task. W1 values are illustrative workload figures, not published results; patch and bin sizes follow the TimesFM and Chronos papers.

The thread through the sections: the more a model shares across series, the less data it needs per series and the more it depends on the pretraining corpus resembling the target. MASE and quantile losses measure the first effect; the leakage audit and the health evidence measure the second.

This chapter builds a small, dependency-light forecasting and evaluation kit in NumPy around the W1 hourly heart-rate task. It does not train a foundation model; it implements the parts that surround one and that teams most often get wrong: baselines, tokenizers, metrics, the leakage audit and missingness-aware scoring. Each file has a test that runs on synthetic W1-like data and asserts a number quoted in the text.

ts/
  w1sim.py        # synthetic W1 hourly heart rate: circadian cycle + drift + noise
  roots.py        # f-ts-roots: seasonal naive, Holt-Winters, pooled (global) linear model
  tokens.py       # f-ts-models: patchify, Chronos quantizer, masked-patch mask, any-variate flatten
  metrics.py      # f-ts-eval: MASE, pinball, CRPS, WQL, geometric mean, paired bootstrap
  audit.py        # f-ts-eval: leakage audit by name, window and correlation
  health.py       # f-ts-health: off-wrist mask, seasonal fill, masked MASE, summary features
  test_*.py       # one test file per module; all pass with numpy only

The synthetic generator is shared by every test so that numbers are reproducible:

import numpy as np

def w1_hourly_hr(n_participants=200, days=14, seed=0):
    """Synthetic stand-in for W1 hourly mean heart rate (bpm).
    Returns array (n_participants, days*24): circadian cycle + weekly drift + noise."""
    rng = np.random.default_rng(seed)
    t = np.arange(days * 24)
    base = rng.normal(68, 6, size=(n_participants, 1))          # personal resting level
    amp = rng.uniform(6, 14, size=(n_participants, 1))          # day-night swing
    phase = rng.uniform(-2, 2, size=(n_participants, 1))        # chronotype shift (h)
    circ = amp * np.sin(2 * np.pi * (t - 9 - phase) / 24)       # peak in the afternoon
    drift = np.cumsum(rng.normal(0, 0.15, size=(n_participants, t.size)), axis=1)
    noise = rng.normal(0, 3.0, size=(n_participants, t.size))
    return base + circ + drift + noise

Real TSFMs are called through their own packages (for example the timesfm and chronos-forecasting libraries); the kit treats any model as a function from a context array of shape (T,) to quantile forecasts of shape (L, H), so that baselines and foundation models pass through the same scoring code. That single interface is the most useful habit to keep: a model that cannot be scored by the same function as seasonal naive has not been evaluated.

Running TSFMs in a health organisation raises four production questions that the research papers mostly leave open. Licensing and residency: some weights are non-commercial (TimesFM 3.0) and some models are only hosted APIs (TimeGPT), so the legal path for patient data must be settled before accuracy is measured. Cost: a nightly forecast for every participant is a batch inference job whose size is set by participants × variates × context tokens. Evaluation integrity: published zero-shot numbers may be inflated by leakage, so local, post-cutoff evaluation is the only number that should drive a decision. Missingness and drift: wearables go off the wrist, firmware changes alter sampling, and both move error in ways that aggregate dashboards hide.

ConcernSignal to watchW1 threshold (illustrative)Section
Accuracy vs baselineMasked MASE ratio TSFM/ETS, per cohort< 0.95 with bootstrap CI excluding 1Evaluation
CalibrationShare of observed hours inside q10–q900.75–0.85Models
Input healthObserved fraction of context hoursgate at 0.5; alert if median < 0.55Health
ThroughputSeries forecast per nightly run150,000 within the batch windowModels
IntegrityTest windows flagged by the leakage audit0 in the decision setEvaluation

Table. Production signals for a TSFM-backed forecasting service on W1. Thresholds are illustrative design choices, not published standards.

Each section below ends in a worked incident on W1 that shows how one of these signals moves, which measurement separates the competing explanations, and which remedy is chosen. The incidents share one rule: a classical baseline runs alongside the foundation model on every series, because without it neither a regression nor a fallback can be detected.

From ARIMA to global deep forecasters

Forecasting means predicting future values of a series from its past. For most of the twentieth century, forecasting was local: an analyst took one series, studied it, and fitted a small model to it alone. Time-series foundation models are the far end of a movement away from that habit, and the history explains both why they work and where they still lose to simple methods.

Local statistical models. ARIMA (autoregressive integrated moving average) first differences a series, replacing each value by its change from the previous one, so that a drifting series becomes roughly stable. It then predicts each change as a weighted sum of recent changes (the autoregressive part) and of recent prediction errors (the moving-average part). The weights are estimated from that one series. The Box–Jenkins method (1970) turned the process into a procedure: identify the orders of the model from autocorrelation plots, estimate the weights, then check that the leftover errors look like noise. Exponential smoothing (ETS, for error, trend, seasonality) takes a different route: it keeps a running level, optionally a trend and a seasonal profile, and nudges each towards every new observation by a fixed fraction. Its state-space forms give prediction intervals, and it remains a strong baseline for short, seasonal series.

Local models have two structural limits. They cannot learn from other series, so a participant with three days of data gets a poorly estimated model; and they must be fitted, checked and stored once per series, which becomes an operations problem at a hundred thousand series.

Local models fit one model per series; a global model fits one set of parameters on all series.Local: one model per seriesGlobal: one model for all seriesparticipant 1hourly HRmodel 1own parametersparticipant 2hourly HRmodel 2own parametersparticipant 3hourly HRmodel 3own parametersparticipant 1hourly HRparticipant 2hourly HRparticipant 3hourly HRshared modelone parameter setlearned from allcannot learn from neighbours; fails on short seriesnew series borrow patterns learned elsewhere
Fig. Local versus global forecasting, drawn for three W1 participants. A local model (ARIMA, exponential smoothing) estimates its own parameters from one history. A global model (DeepAR, N-BEATS, a pooled linear model) estimates one parameter set from every history and applies it to each; a pretrained foundation model extends the pool to many domains.

Global neural models. DeepAR (Salinas et al. 2017) trained a single recurrent network across thousands of related series. At each step it receives the previous value and any covariates, updates a hidden state, and outputs the parameters of a probability distribution for the next value; it is trained by maximising the likelihood of the observed values. Because one network sees every series, related series share statistical strength and a new series can be forecast from little history. N-BEATS (Oreshkin et al. 2019) went further and dropped time-series-specific components entirely: stacks of fully connected blocks, each predicting part of the past (a "backcast") and part of the future, with residuals passed to the next block. It beat a statistical benchmark by about 11% and the hand-crafted hybrid that won the M4 competition by about 3% on the M3, M4 and Tourism datasets.

Transformers, doubted and rescued. Several forecasting transformers published around 2020–2021 claimed large gains on long-horizon benchmarks. Zeng et al. (2022) showed that a one-layer linear model mapping the context directly to the horizon beat them, a result that reset the field's standards for baselines. PatchTST (Nie et al. 2022) recovered transformer performance with two changes: it cut each series into patches (short contiguous segments treated as tokens) rather than feeding one value per token, and it applied the model to each channel independently. Patching is now the tokenization most foundation models use.

Pretrained forecasters. From 2023, models pretrained on large multi-domain corpora began to forecast unseen series zero-shot, without any training on the target. They are global models whose "collection" is everything the authors could gather. The next section describes them.

Worked example · W1 Each W1 participant has an hourly heart-rate series with a strong daily cycle (low at night, higher in the afternoon), a slow personal drift and noise. A local Holt-Winters model fitted to one participant's 168-hour context needs to estimate a level and 24 seasonal terms from 7 cycles. A pooled linear model fitted once on 300 training participants and applied to 100 held-out participants uses the same 24-hour input for everyone. On synthetic W1-like data the pooled model reaches a mean MASE of 0.78, Holt-Winters 0.86 and seasonal naive 1.04: sharing parameters across people helps even before any deep model is involved.

What this means for health. Forecasting is rarely the clinical end task. TSFMs are most useful in health as encoders, imputers and anomaly detectors, and as baselines for the specialised biosignal models of Chapter 7. The lesson from the roots is that every claim for a deep forecaster must be tested against seasonal naive, ETS and a linear model, because those baselines have repeatedly been harder to beat than papers suggested.

The forecasting problem is to estimate \(p(y_{T+1:T+H} \mid y_{1:T}, x_{1:T+H})\), where \(y_t\) is the target at time \(t\), \(T\) the context length, \(H\) the horizon and \(x_t\) optional covariates. The historical progression is a progression in what is shared across series.

ARIMA. Let \(\nabla y_t = y_t - y_{t-1}\) be the first difference and \(\nabla^d\) its \(d\)-fold repetition. An ARIMA\((p,d,q)\) model states

\[ \nabla^d y_t = c + \sum_{i=1}^{p} \phi_i \nabla^d y_{t-i} + \varepsilon_t + \sum_{j=1}^{q} \vartheta_j \varepsilon_{t-j}, \qquad \varepsilon_t \sim \mathcal N(0,\sigma^2), \]

where \(c\) is a constant, \(\phi_i\) the autoregressive coefficients, \(\vartheta_j\) the moving-average coefficients and \(\varepsilon_t\) white noise. All of \((c,\phi,\vartheta,\sigma^2)\) are estimated per series, typically by maximum likelihood. With \(p=2, d=1, q=1\) that is four coefficients (\(c, \phi_1, \phi_2, \vartheta_1\)) plus the noise variance, all from one history.

Exponential smoothing with seasonality. Additive Holt-Winters without trend keeps a level \(\ell_t\) and seasonal terms \(s_t\) with period \(m\):

\[ \ell_t = \alpha\,(y_t - s_{t-m}) + (1-\alpha)\,\ell_{t-1}, \qquad s_t = \gamma\,(y_t - \ell_t) + (1-\gamma)\,s_{t-m}, \qquad \hat y_{T+h} = \ell_T + s_{T+h-m\lceil h/m \rceil}. \]

Here \(\alpha, \gamma \in (0,1)\) are smoothing weights: a large \(\alpha\) tracks the level quickly, a large \(\gamma\) lets the daily profile change quickly. Unrolling the level recursion shows that \(\ell_T\) is a weighted average of past de-seasonalised values with weights \(\alpha(1-\alpha)^k\), which decay geometrically with age \(k\).

Worked example · W1 With \(\alpha = 0.3\), the weight on the most recent hour is 0.3, on the hour before \(0.3 \times 0.7 = 0.21\), and on the hour 24 h ago \(0.3 \times 0.7^{24} \approx 5.7\times 10^{-5}\): the level forgets within a few hours, while the seasonal term \(s\), updated only once per day per hour slot with \(\gamma = 0.2\), retains information over several days. A participant whose resting heart rate shifts by 6 bpm after starting a beta blocker would see the level adjust within about 6 hours (\(0.7^6 \approx 0.12\) of the old level remains).

Global models. A global model replaces per-series parameters with one parameter vector \(\theta\) fitted on all series \(i = 1..N\):

\[ \hat\theta = \arg\max_\theta \sum_{i=1}^{N} \sum_{t} \log p_\theta\big(y^{(i)}_t \mid y^{(i)}_{DeepAR parameterises \(p_\theta\) with a recurrent network whose hidden state \(h^{(i)}_t = f_\theta(h^{(i)}_{t-1}, y^{(i)}_{t-1}, x^{(i)}_t)\) is mapped to the mean and scale of a Gaussian (or a negative binomial for counts). To make series with different magnitudes comparable it divides each series by a scale \(\nu_i = 1 + \frac{1}{T}\sum_t y^{(i)}_t\) before the network and multiplies outputs back afterwards; the same idea, mean scaling, reappears in Chronos.

The linear baseline. The model that embarrassed early forecasting transformers is a single linear map from the context window to the horizon, \(\hat{\mathbf y}_{T+1:T+H} = W^\top \tilde{\mathbf y}_{T-P+1:T} + b\), with \(W \in \mathbb R^{P \times H}\), shared by all series and fitted by least squares on normalised windows \(\tilde{\mathbf y} = \mathbf y - \bar y\). With \(P = H = 24\) that is \(24 \times 24 + 24 = 600\) parameters. Ridge regularisation gives the closed form \(\hat W = (X^\top X + \lambda I)^{-1} X^\top Y\), where rows of \(X\) are input windows and rows of \(Y\) the corresponding targets.

Why sharing helps. Suppose each series has a true seasonal profile \(\mu_i + \delta_i\), where \(\mu\) is common and \(\delta_i\) personal with variance \(\tau^2\). A local estimate from \(k\) cycles with noise variance \(\sigma^2\) has error variance about \(\sigma^2/k\) per hour slot. A pooled estimate of \(\mu\) from \(N\) series has variance about \(\sigma^2/(Nk)\) but bias \(\tau^2\) from ignoring \(\delta_i\). Pooling wins when \(\tau^2 < \sigma^2/k\), that is, when people are more alike than one person's week is noisy. Foundation models push \(N\) to millions of series and rely on the corpus making \(\tau^2\) small in some learned representation.

Worked example · W1 With hourly noise \(\sigma = 3\) bpm and \(k = 7\) days of context, the local estimate of each hourly seasonal value has standard error \(3/\sqrt 7 \approx 1.13\) bpm. If the personal deviation of the daily profile from the population shape (after removing each person's mean) has standard deviation \(\tau \approx 1\) bpm, pooling is roughly break-even; if a participant has only 3 days of data the local standard error rises to \(3/\sqrt 3 \approx 1.73\) bpm and pooling clearly wins. This is why global models help most for new and sparse W1 participants.

Finally, N-BEATS and PatchTST change the input representation rather than the sharing: N-BEATS predicts a backcast and forecast per block with residual stacking, and PatchTST forms tokens \(\mathbf p_j = y_{(j-1)S+1:(j-1)S+P}\) of length \(P\) with stride \(S\), reducing the sequence length from \(T\) to about \(T/S\) and the attention cost from \(O(T^2)\) to \(O((T/S)^2)\).

The code implements the three baselines that every TSFM result should be compared with: seasonal naive (repeat the last day), additive Holt-Winters with a 24-hour season, and a global linear model (one 24→24 linear map shared by all participants, fitted by ridge regression). Inputs are 1-D arrays of hourly heart rate; the context has shape (168,) and every forecaster returns shape (24,).

import numpy as np

M = 24          # seasonal period for hourly data (one day)
T, H = 168, 24  # context: 7 days; horizon: 1 day

def seasonal_naive(ctx, h=H, m=M):
    """Repeat the last observed season. ctx: (T,) -> (h,)"""
    last = ctx[-m:]
    return np.array([last[i % m] for i in range(h)])

def ses_seasonal(ctx, h=H, m=M, alpha=0.3, gamma=0.2):
    """Additive Holt-Winters without trend: level l_t and m seasonal terms s.
    l_t = alpha*(y_t - s_{t-m}) + (1-alpha)*l_{t-1};  s_t = gamma*(y_t - l_t) + (1-gamma)*s_{t-m}"""
    level = ctx[:m].mean()
    season = list(ctx[:m] - level)
    for t in range(m, len(ctx)):
        s_old = season[t - m]
        new_level = alpha * (ctx[t] - s_old) + (1 - alpha) * level
        season.append(gamma * (ctx[t] - new_level) + (1 - gamma) * s_old)
        level = new_level
    n = len(ctx)
    return np.array([level + season[n - m + (i % m)] for i in range(h)])

def windows(series, p=M, h=H):
    """Cut (N, L) series into (inputs (K, p), targets (K, h)) pairs, each scaled by its input mean."""
    X, Y = [], []
    for s in series:
        for start in range(0, len(s) - p - h + 1, 6):
            x, y = s[start:start + p], s[start + p:start + p + h]
            mu = x.mean()
            X.append(x - mu); Y.append(y - mu)
    return np.array(X), np.array(Y)

def fit_global_linear(train_series, p=M, h=H, ridge=1.0):
    """One linear map W (p+1, h) shared by ALL series: the simplest 'global' model."""
    X, Y = windows(train_series, p, h)
    Xb = np.hstack([X, np.ones((len(X), 1))])
    W = np.linalg.solve(Xb.T @ Xb + ridge * np.eye(p + 1), Xb.T @ Y)
    return W

def predict_global_linear(W, ctx, p=M):
    x = ctx[-p:]; mu = x.mean()
    return np.append(x - mu, 1.0) @ W + mu

Three details matter. windows subtracts each input window's mean from both input and target, so one linear map serves participants with resting rates of 55 or 85 bpm; the mean is added back in predict_global_linear. The stride of 6 hours in windows creates overlapping training samples without making every sample a near duplicate. And the split is by participant: the global model never sees any hour of a test participant, which mirrors the zero-shot setting of a foundation model.

The test fits on 300 synthetic participants, scores 100 others, and checks that both Holt-Winters and the global linear model beat seasonal naive under MASE (defined in the evaluation section as forecast error divided by the in-sample error of seasonal naive):

import numpy as np
from w1sim import w1_hourly_hr
from roots import seasonal_naive, ses_seasonal, fit_global_linear, predict_global_linear, T, H
from metrics import mase

data = w1_hourly_hr(n_participants=400, days=8)    # 8 days = 168 h context + 24 h horizon
train, test = data[:300], data[300:]               # participant-level split: no person in both
W = fit_global_linear(train[:, :T])                # fit only on context weeks of training people
scores = {"seasonal_naive": [], "holt_winters": [], "global_linear": []}
for s in test:
    ctx, y = s[:T], s[T:T + H]
    scores["seasonal_naive"].append(mase(y, seasonal_naive(ctx), ctx))
    scores["holt_winters"].append(mase(y, ses_seasonal(ctx), ctx))
    scores["global_linear"].append(mase(y, predict_global_linear(W, ctx), ctx))
for k, v in scores.items():
    print(f"{k:15s} mean MASE {np.mean(v):.3f}")
assert seasonal_naive(np.arange(48.0)).tolist() == list(np.arange(24.0, 48.0))
assert np.mean(scores["global_linear"]) < np.mean(scores["seasonal_naive"])
assert np.mean(scores["holt_winters"]) < np.mean(scores["seasonal_naive"])
print("roots OK")
$ python3 test_roots.py
seasonal_naive  mean MASE 1.040
holt_winters    mean MASE 0.863
global_linear   mean MASE 0.784
roots OK

Debugging tips. If the global model is worse than seasonal naive, check for a train/test split by window instead of by participant (it inflates training fit and masks overfitting the other way), a missing mean re-addition (forecasts centred on zero), or a window stride of 1 with a tiny ridge (ill-conditioned normal equations). If Holt-Winters diverges, check that the initial seasonal terms sum to roughly zero; an initial level taken from a single hour instead of a full day biases every seasonal term.

Worked example · W1 The ordering in the output (global linear 0.78 < Holt-Winters 0.86 < seasonal naive 1.04) is the pattern the roots section predicts: on short, regular, related series, sharing parameters across participants beats fitting each participant alone. These are synthetic data; the same script run on real W1 hours, after the missingness handling of the health section, is the baseline table any W1 TSFM must beat.

At W1 scale the choice between local and global forecasters is an operations decision as much as an accuracy one.

Problem: local fits fail silently at scale. A nightly job that fits one ARIMA or ETS model per participant runs 150,000 independent optimisations. Some fail to converge, some pick degenerate orders, and some series are too short to fit at all. Why it matters: a failed fit usually falls back to a default (last value or mean) without anyone noticing, and those participants get systematically worse forecasts. Root cause: per-series estimation needs enough complete cycles; off-wrist gaps (38% of W1 hours) and new enrolments both shorten effective history.

Worked incident · W1 After an enrolment drive, the share of W1 participants with fewer than 3 complete days in their 7-day context rises. The nightly local-ETS job reports success, but the median forecast error for new participants is much worse than for established ones. Diagnosis: the job logs a fit status per series; counting statuses shows a block of series fitted with the default parameters because the optimiser stopped at its iteration cap, and nearly all of them have fewer than 72 observed hours. Plotting masked MASE against observed hours in context shows a sharp knee below 72 h for local ETS and a much flatter curve for the global linear model, which borrows the daily shape from other participants. Remedy, step by step: (1) make fit status a first-class output and alert on the share of default fits; (2) route series with fewer than 72 observed context hours to the global model; (3) keep local ETS for established series where it is competitive and cheap; (4) re-score both routes daily. Cost and trade-off: two code paths to maintain and a routing threshold to tune; a global model must be retrained when the population shifts (new device generation), whereas local fits adapt automatically. Validation: a paired comparison on the same new participants, global vs local, with a bootstrap CI over participants (evaluation section); the fix is supported if the CI on the MASE difference excludes zero in favour of the global model for the < 72 h stratum and is near zero above it. It is weakened if the global route helps short series but hurts long ones, which would indicate the threshold is set too high.
OptionCompute per night (W1)Cold startFailure modeMonitoring
Local ETS/ARIMA150,000 small fits, CPU, parallelPoor below a few cyclesSilent default fitsFit status counts, error by history length
Global linear / DeepAROne training job, cheap inferenceGoodPopulation shiftError by cohort and device generation
Pretrained TSFM, zero-shotNo training; GPU or CPU inferenceGoodCorpus mismatch, licence, leakageRatio to ETS on post-cutoff data

Table. Operational profile of the three families for nightly 24-hour forecasts on W1. Qualitative; compute depends on hardware and implementation.

Baseline discipline as a production control. The lesson of Zeng et al. (2022) generalises: a baseline is not a one-off experiment but a permanently running comparator. In production it does three jobs. It is the fallback when the main model fails or its inputs fail a quality gate. It is the denominator of the scaled error that monitoring tracks, so a regression in the main model shows up as a ratio drifting towards 1 even when the absolute error also moves with season or population. And it is the evidence that the expensive model still earns its cost. The cost is small: ETS on 150,000 series of 168 points is a CPU job, and the global linear model is a matrix multiply.

Connection. Pretrained TSFMs remove the training step of the global model but import a new dependency, the pretraining corpus, whose resemblance to W1 cannot be checked by looking at W1 alone. The next section describes the models; the evaluation section describes how to check them.

Time-series foundation models

Time-series foundation models are transformers (and, since 2025, some recurrent models) pretrained on billions of observations from many domains to forecast, impute or classify series they have never seen. They differ along four axes: architecture (decoder-only, encoder–decoder, masked encoder), tokenization (patches, quantized value bins, lag features), output (a point forecast, a set of quantiles, or a full distribution) and input scope (univariate only, or multivariate with covariates).

ModelFirst releaseArchitectureTokensOutputNotes
TimesFM (Google)Oct 2023Decoder-onlyPatches (in 32, out 128)Point (+ quantile head in 2.5)~100B time points incl. synthetic; 2.5 (Sep 2025) 200M params, 16k context
TimeGPT-1 (Nixtla)Oct 2023Encoder–decoderValuesPoint + intervalsCommercial API; >100B data points
Lag-LlamaOct 2023Decoder-only (LLaMA-style)Lag featuresDistributionOpen; univariate probabilistic
Moirai (Salesforce)Feb 2024Masked encoderMulti-size patchesMixture distributionLOTSA (~27.6B obs); any-variate attention
MOMENT (CMU)Feb 2024Masked encoder (T5-style)Patches of 8ReconstructionTime Series Pile; forecasting, classification, anomaly detection, imputation
Chronos (Amazon)Mar 2024Encoder–decoder (T5)Quantized binsCategorical20M–710M params; GP synthetic data
Toto (Datadog)Jul 2024Decoder-onlyPatchesDistributionObservability metrics focus
Sundial (Tsinghua)Feb 2025Decoder-onlyContinuous patchesGenerative (flow matching)TimeBench, ~1 trillion time points
TiRex (NXAI)May 2025xLSTM (recurrent)PatchesQuantilesState-tracking recurrent backbone; strong on GIFT-Eval
Chronos-2 (Amazon)Oct 2025Encoder with group attentionPatchesQuantiles120M params; multivariate, covariates, in-context learning
Moirai 2.0 (Salesforce)Nov 2025Decoder-onlySingle patch size9 quantiles~30× smaller than Moirai-Large, better on GIFT-Eval
TimesFM 3 (Google)Aug 2026Decoder-only, temporal + variate attentionPatches of 329 quantiles330M params; multivariate, past and future covariates; non-commercial weights

Table. Major time-series foundation models. Dates are first arXiv or announcement; details from each paper, repository or announcement as of November 2026.

Three time-series foundation model designs: decoder-only patches, quantized tokens in an encoder-decoder, and a masked encoder. Decoder-only, patches Quantized tokens Masked encoder TimesFM · Moirai 2.0 · Toto Chronos (T5) Moirai 1 · MOMENT p₁p₂p₃p₄ causal transformer patch i attends to patches ≤ i next output patch (128 steps) scale → bin ids: 812 830 901 … T5 encoder–decoder unchanged language model softmax over bins → sample paths p₁[M]p₃[M] bidirectional encoder forecast = mask the future values or distribution at [M] + long horizons in few steps− errors compound if rolled out + any LM recipe, multimodal output− resolution limited by bins + imputation, classification too− forecasting is a special case The 2025–2026 trend: decoder-only or patch encoders with quantile heads, plus covariates and cross-series attention
Fig. Three time-series foundation model designs and their trade-offs. Bin ids and patch counts are illustrative. Based on the descriptions in Das et al. 2023, Ansari et al. 2024, Woo et al. 2024 and Goswami et al. 2024.

Decoder-only patch models. These treat a series like a document of patches and predict the next patch, the way a language model predicts the next word. Das et al. (2023) built TimesFM this way. Input patches are 32 points long and output patches 128, so a long horizon needs few autoregressive steps. The original model had about 200M parameters, pretrained on roughly 100B time points from Google Trends, Wikipedia pageviews, public datasets and about 3M synthetic series (ARMA, seasonal, trend and step patterns), mixed half real and half synthetic. Its zero-shot accuracy came close to supervised models on the Monash, Darts and ETT benchmarks and improved monotonically from 17M to 200M parameters. The TimesFM repository tracks the line since: TimesFM 2.5 (September 2025) cut parameters from 500M to 200M, raised context to 16k and added an optional quantile head; covariate support through XReg was restored in October 2025; a LoRA fine-tuning example was added in April 2026. TimesFM 3 (announced 31 August 2026, 330M parameters) alternates attention within each series over time with attention across series, forecasts several targets jointly, accepts past and known-future covariates, and produces the whole horizon in one forward pass as nine quantiles; Google reports it first among pretrained models on GIFT-Eval and fev-bench. Its code is Apache 2.0 but its weights carry a non-commercial licence, with commercial use offered through Google Cloud (remio 2026). Datadog's Toto applies the decoder-only design to observability metrics, and a 2025 paper released a 151M-parameter version with BOOM, a benchmark of about 350M observations from Datadog telemetry (Cohen et al. 2025). Sundial (Liu et al. 2025) keeps the decoder but drops discrete outputs, generating the next patch with a flow-matching loss trained on TimeBench, about one trillion time points.

Forecasting as language modelling. Chronos asks how far an unmodified language model can go if values are turned into words. Ansari et al. (2024) divided each series by its mean absolute value (mean scaling), assigned each scaled value to one of 4,094 equal-width bins between −15 and 15, and trained T5 models from about 20M to 710M parameters with ordinary cross-entropy on the bin ids. Training mixed public datasets with 1M synthetic series sampled from Gaussian processes (KernelSynth) and 10M mixed-up combinations of real series (TSMixup), which improved generalisation. On a 42-dataset benchmark Chronos was strongest on datasets seen in training and roughly matched dataset-specific models zero-shot on unseen ones. Sampling from the categorical output gives probabilistic forecasts and handles futures with two plausible outcomes. Its successors moved away from pure language modelling: a faster Chronos-Bolt variant followed in 2024, and Chronos-2 (Ansari et al. 2025; 120M parameters) adds a group attention layer that shares information across related series at each patch position. One model then does univariate, multivariate and covariate-informed forecasting by in-context learning, using related series supplied at inference time instead of new training. Amazon reports it first among pretrained models on GIFT-Eval with the largest gains on covariate tasks in fev-bench (Amazon Science 2025).

Masked encoders. These pose forecasting as filling in masked future patches, which also makes imputation and classification first-class tasks. Woo et al. (2024) designed Moirai around heterogeneity: patch sizes chosen by sampling frequency, so hourly and minute data get appropriately sized tokens; any-variate attention, which flattens all variates into one sequence and uses rotary position embeddings for time and learned biases to distinguish variates, so the model accepts any number of channels; and a mixture output (Student's t, negative binomial, log-normal, low-variance normal) that fits counts, positive values and heavy tails. It was pretrained on LOTSA, about 27.6B observations across nine domains, in sizes from 14M to 311M parameters. Moirai 2.0 (Liu et al. 2025) then reversed course: a decoder-only model with a single patch size, multi-token prediction and a quantile loss, about 30 times smaller than Moirai-Large and better on GIFT-Eval, with ablations crediting the decoder-only backbone and quantile decoding. MOMENT (Goswami et al. 2024) targets general analysis rather than forecasting: 512-step inputs split into 64 patches of 8, about 30% masked during pretraining, evaluated on forecasting, classification, anomaly detection and imputation, and released with the Time Series Pile.

Lag features and hosted models. Lag-Llama (Rasul et al. 2023) is a decoder-only model whose tokens are built from lagged values (the value 1 step, 24 steps, 168 steps ago, and so on), aimed at univariate probabilistic forecasting; it generalised reasonably zero-shot and became state of the art after fine-tuning on small slices of new datasets. TimeGPT-1 (Garza et al. 2023) is an encoder–decoder transformer trained on more than 100B data points and offered as a commercial API; it ranked in the top three across frequencies on more than 300,000 series, though its paper notes that comparisons with other foundation models were incomplete. For health data a hosted model raises a prior question: whether patient data may leave the organisation's environment at all.

2025–2026: covariates, multivariate inputs and in-context learning. Univariate zero-shot forecasting is no longer the frontier. The frontier is using context: related series, known future covariates (a medication schedule, a planned procedure) and examples supplied at inference time. Chronos-2's group attention and TimesFM 3's variate attention with past and future covariates are two answers; Moirai 2.0 and recurrent models such as TiRex (Auer et al. 2025) are reminders that simpler or smaller backbones often win once the data and training recipe are right. For health, covariate support matters because the most predictive signals (activity, meals, medication) are usually separate channels.

Worked example · W1 For the W1 task (168 hourly heart-rate values in, 24 out), a decoder-only patch model sees 6 tokens of 32 values (the first partly padded) and emits the 24-hour horizon in a single output patch. A Chronos-style model sees 168 bin ids; with a mean heart rate near 70 bpm each bin is about 0.51 bpm wide. A covariate-aware model can additionally receive hourly accelerometry counts as a second channel, which explains part of the afternoon peak that heart rate alone cannot anticipate. In the illustrative W1 evaluation, a zero-shot TSFM reaches MASE 0.84 against 0.93 for ETS, and 0.78 when accelerometry is added as a covariate.

All TSFMs approximate the conditional distribution \(p_\theta(y_{T+1:T+H} \mid y_{1:T}, x)\) with a single \(\theta\) learned on a corpus \(\mathcal D\) of many series. They differ in how \(y_{1:T}\) becomes tokens, which factorisation of the joint distribution they model, and which loss they train with.

Scaling. Series in \(\mathcal D\) differ in magnitude by orders of magnitude. Every model normalises each context first. TimesFM uses the mean \(\mu\) and standard deviation \(\sigma\) of the first patch, \(\tilde y_t = (y_t - \mu)/\sigma\); Chronos uses mean scaling, \(\tilde y_t = y_t / s\) with \(s = \frac{1}{T}\sum_{t=1}^{T} |y_t|\). Forecasts are mapped back by the inverse transform.

Patch tokens. With patch length \(P\), a context of length \(T\) is left-padded to \(n P\) with \(n = \lceil T/P \rceil\), giving tokens \(\mathbf p_j \in \mathbb R^{P}\) and a padding mask. Each patch is embedded by a small residual MLP, \(\mathbf e_j = \mathrm{MLP}([\mathbf p_j; \mathbf m_j]) + \mathrm{PE}(j)\), where \(\mathbf m_j\) is the patch's padding mask and \(\mathrm{PE}\) a positional encoding. A decoder-only model applies causal attention, so token \(j\) attends only to tokens \(\le j\), and maps each output to a patch of \(Q\) future values. Training minimises the mean squared error over all positions,

\[ \mathcal L_{\text{patch}}(\theta) = \frac{1}{n}\sum_{j=1}^{n} \frac{1}{Q}\big\lVert \tilde y_{jP+1:jP+Q} - \hat{\tilde y}^{(j)}_{1:Q} \big\rVert_2^2 , \]

so one context provides \(n\) training examples. With \(Q > P\) (TimesFM: \(P = 32\), \(Q = 128\)), a horizon of \(H\) needs \(\lceil H/Q \rceil\) decoding steps instead of \(\lceil H/P \rceil\).

How W1 signals become tokens under patching and under Chronos-style quantization.Raw PPG window64 Hz x 10 s = 640 samplesPatches of 32640 / 32 = 20 tokensTimesFM 2.5 context16,384 samples = 256 sHourly mean HR7 days = 168 valuesMean scale, 4,094 binsrange [-15, 15] x 70 bpmBin width30 / 4,094 x 70 = 0.513 bpmPatch tokens (decoder-only, masked encoders)Value tokens (Chronos)Numbers follow the W1 workload; the patch size and bin count follow the TimesFM and Chronos papers
Fig. Token arithmetic for W1. Top: a 640-sample PPG window becomes 20 patch tokens of 32 samples; a 16,384-sample context covers 256 s of 64 Hz signal. Bottom: an hourly heart-rate series scaled by its mean absolute value (about 70 bpm) and quantized into 4,094 uniform bins on [-15, 15] has a resolution of about 0.51 bpm.
Worked example · W1 W1 hourly context: \(T = 168\), \(P = 32\), so \(n = \lceil 168/32 \rceil = 6\) tokens and \(6 \times 32 - 168 = 24\) padded values. Horizon \(H = 24 \le Q = 128\): one decoding step. Raw W1 PPG: a 10-s window at 64 Hz is 640 samples, exactly 20 patches; the 16,384-point context of TimesFM 2.5 covers \(16{,}384 / 64 = 256\) s. Self-attention cost grows with \(n^2\): 36 token pairs for the hourly task against \(512^2 = 262{,}144\) for a full 16k-point context.

Quantized value tokens. Chronos defines bin edges \(b_0 < \dots < b_B\) uniformly on \([-15, 15]\) and maps a scaled value to the token \(z_t = k\) such that \(b_{k} \le \tilde y_t < b_{k+1}\). The model is trained with cross-entropy, \(\mathcal L = -\sum_t \log p_\theta(z_{t} \mid z_{ \[ |y_t - s\,c_{z_t}| \le \frac{s}{2}\cdot\frac{30}{B}. \]

Worked example · W1 With \(B = 4{,}094\) and \(s = 70\) bpm, the bin width is \(30/4{,}094 \times 70 = 0.513\) bpm and the maximum round-trip error 0.256 bpm, small next to the 3 bpm hourly noise. The representable range is \(\pm 15 s = \pm 1{,}050\) bpm, so clipping is irrelevant for heart rate. The same scheme on a series whose mean is near zero (a de-trended HRV residual, for example) has a tiny \(s\) and the range \(\pm 15 s\) can clip real excursions: a known weakness of mean scaling.

Quantile outputs. Moirai 2.0, Chronos-2, TiRex and TimesFM 3 output quantiles \(\hat q_\tau\) for levels \(\tau \in \{0.1, \dots, 0.9\}\), trained with the pinball loss

\[ \rho_\tau(y, \hat q) = \max\big(\tau (y - \hat q),\; (\tau - 1)(y - \hat q)\big), \]

which is minimised in expectation when \(\hat q\) is the true \(\tau\)-quantile. For \(\tau = 0.9\) and a forecast 1 bpm too low the loss is \(0.9\); 1 bpm too high, \(0.1\): under-prediction of the upper quantile costs nine times more, which pushes \(\hat q_{0.9}\) up until only 10% of outcomes exceed it.

Mixture outputs. Moirai 1 outputs a mixture density \(p(y) = \sum_{c} w_c\, f_c(y; \psi_c)\) with weights \(w_c \ge 0, \sum_c w_c = 1\) over Student's t, negative binomial, log-normal and low-variance normal components \(f_c\) with parameters \(\psi_c\), trained by negative log-likelihood. The mixture lets one network express counts (step totals), positive skewed values (glucose excursions) and heavy tails.

Masked reconstruction. A masked encoder replaces a random subset \(\mathcal M\) of patches with a learned mask token and minimises reconstruction error on them only, \(\mathcal L = \frac{1}{|\mathcal M|}\sum_{j \in \mathcal M} \lVert \mathbf p_j - \hat{\mathbf p}_j \rVert^2\). Forecasting is the special case where \(\mathcal M\) is the final patches. MOMENT: \(T = 512\), \(P = 8\), so 64 patches with \(|\mathcal M| \approx 0.3 \times 64 \approx 19\).

Multivariate context. Moirai's any-variate attention flattens \(V\) variates of \(n\) patches each into one sequence of \(Vn\) tokens, with attention score between tokens \(a\) and \(b\)

\[ A_{ab} = \frac{(\mathbf W_Q \mathbf e_a)^\top R_{t_a - t_b} (\mathbf W_K \mathbf e_b)}{\sqrt{d}} + u^{(1)}\,\mathbb 1[v_a = v_b] + u^{(2)}\,\mathbb 1[v_a \ne v_b], \]

where \(R\) is the rotary rotation for the time offset, \(v_a\) the variate of token \(a\), \(d\) the head dimension and \(u^{(1)}, u^{(2)}\) learned scalars. Because the variate term only asks "same or different", the model is invariant to the order of variates and accepts any number of them. The cost is attention over \(Vn\) tokens, \(O(V^2 n^2)\); Chronos-2 and TimesFM 3 instead alternate attention over time within a series (\(O(V n^2)\)) with attention across series at each patch position (\(O(n V^2)\)).

Worked example · W1 Heart rate plus accelerometry (\(V = 2\)) over 168 hours with 24-hour patches gives \(n = 7\) patches per variate and 14 flattened tokens; any-variate attention scores \(14^2 = 196\) pairs. Alternating attention scores \(2 \times 7^2 = 98\) temporal pairs plus \(7 \times 2^2 = 28\) cross-variate pairs, 126 in total. The saving is small here and large for many channels: a 12-channel bedside monitor with 64 patches each would need \(768^2 \approx 590{,}000\) pairs flattened against \(12 \times 64^2 + 64 \times 12^2 = 58{,}368\) alternating.

The code implements the input side of the four model families on W1 shapes: TimesFM-style patching with a padding mask, the Chronos quantizer and its inverse, a MOMENT-style patch mask, and Moirai-style any-variate flattening. Training a TSFM is out of scope; these functions are what a team writes when it adapts or audits one, and they are where shape and scaling bugs hide.

import numpy as np

def patchify(x, p=32):
    """TimesFM-style input patches. Left-pad with zeros to a multiple of p and return
    patches (n, p) plus a padding mask (n, p) where 1 = padded (ignored by attention)."""
    n = -(-len(x) // p)                       # ceil division
    pad = n * p - len(x)
    xp = np.concatenate([np.zeros(pad), x])
    mask = np.concatenate([np.ones(pad), np.zeros(len(x))])
    return xp.reshape(n, p), mask.reshape(n, p)

B, LO, HI = 4094, -15.0, 15.0                 # Chronos: 4,094 uniform bins on [-15, 15]
EDGES = np.linspace(LO, HI, B + 1)
CENTERS = (EDGES[:-1] + EDGES[1:]) / 2

def chronos_tokenize(ctx):
    """Mean scaling then uniform quantization. Returns (token ids, scale)."""
    scale = np.mean(np.abs(ctx)) or 1.0
    ids = np.clip(np.digitize(ctx / scale, EDGES) - 1, 0, B - 1)
    return ids, scale

def chronos_detokenize(ids, scale):
    return CENTERS[ids] * scale

def masked_patch_mask(n_patches=64, ratio=0.3, seed=0):
    """MOMENT-style random patch mask: True = patch replaced by [MASK]."""
    rng = np.random.default_rng(seed)
    m = np.zeros(n_patches, bool)
    m[rng.choice(n_patches, int(round(ratio * n_patches)), replace=False)] = True
    return m

def any_variate_flatten(X, p):
    """Moirai-style flattening of a (V variates, L) array into one token sequence.
    Returns tokens (V*n, p), time index (for rotary encoding) and variate id (for attention bias)."""
    V, L = X.shape; n = L // p
    tok = X[:, :n * p].reshape(V, n, p).reshape(V * n, p)
    time_idx = np.tile(np.arange(n), V)
    var_id = np.repeat(np.arange(V), n)
    return tok, time_idx, var_id

The tests assert the numbers derived at the other levels: 20 patches for a 640-sample PPG window, 6 patches and 24 padded values for 168 hours, a round-trip quantization error within half a 0.513-bpm bin, the 9:1 asymmetry of the 0.9 pinball loss, 19 masked patches out of 64, and 14 flattened tokens for two variates. The pinball loss is imported from metrics.py (shown in the evaluation section).

import numpy as np
from tokens import patchify, chronos_tokenize, chronos_detokenize, masked_patch_mask, any_variate_flatten, B
from metrics import pinball

# W1 raw PPG window: 10 s at 64 Hz = 640 samples -> 20 patches of 32, no padding
ppg = np.sin(np.linspace(0, 20 * np.pi, 640))
P, mask = patchify(ppg, 32)
assert P.shape == (20, 32) and mask.sum() == 0
# W1 hourly heart rate: 168 h context -> 6 patches, first 24 values padded
P, mask = patchify(np.full(168, 70.0), 32)
assert P.shape == (6, 32) and mask.sum() == 24

# Chronos round trip on heart rate with mean ~70 bpm: error <= half a bin (in bpm)
hr = 70 + 10 * np.sin(np.arange(168) * 2 * np.pi / 24)
ids, scale = chronos_tokenize(hr)
half_bin_bpm = 0.5 * 30 / B * scale
err = np.max(np.abs(chronos_detokenize(ids, scale) - hr))
print(f"scale {scale:.1f} bpm, bin width {2*half_bin_bpm:.3f} bpm, max round-trip error {err:.3f} bpm")
assert err <= half_bin_bpm + 1e-9

# Pinball loss: the 0.9-quantile is penalized 9x more for under- than over-prediction
y = np.array([70.0])
assert np.isclose(pinball(y, np.array([69.0]), 0.9), 0.9)
assert np.isclose(pinball(y, np.array([71.0]), 0.9), 0.1)

# MOMENT: 512 steps -> 64 patches of 8, ~30% masked
m = masked_patch_mask(64, 0.3)
assert m.sum() == 19

# Moirai any-variate: HR + accelerometry (2 variates), 168 h, patch 24 -> 14 tokens
tok, ti, vi = any_variate_flatten(np.vstack([hr, np.zeros(168)]), 24)
assert tok.shape == (14, 24) and ti.tolist()[:8] == [0, 1, 2, 3, 4, 5, 6, 0] and vi.sum() == 7
print("tokens OK")
$ python3 test_tokens.py
scale 70.0 bpm, bin width 0.513 bpm, max round-trip error 0.242 bpm
tokens OK

Calling real models. The released packages (timesfm, chronos-forecasting, uni2ts for Moirai, momentfm) each take a batch of context arrays and return point or quantile forecasts; their exact function signatures change between versions, so a thin adapter is worth writing once: a function forecast(contexts: list[np.ndarray], horizon: int) -> np.ndarray of shape (batch, n_quantiles, horizon), implemented per package and tested against seasonal naive on a series with a known answer (a pure 24-hour sine, which every model should forecast almost exactly). The adapter is also where the context length is set explicitly, never left at a default: a package default of 512 points, for example, silently drops most of a 960-minute context, and published measurements put the cost of such truncation above 20% on GIFT-Eval configurations for some models.

Debugging tips. Left-padding versus right-padding matters: decoder-only models expect the most recent value last, and right-padding with zeros places a fake drop to zero at the end of the context. NaN values must be masked, not passed through; most packages accept NaN as missing but some convert it to zero silently. A quantile output whose \(q_{0.1} > q_{0.9}\) for any hour indicates swapped axes in the output array.

Deploying a TSFM for W1 means running a nightly batch job that forecasts the next 24 hours for every active participant, storing quantiles, and scoring them the following day.

Nightly batch forecasting pipeline for W1 with a missingness gate and monitoring.Hourly HRfrom PPG windowsGate>= 50% observedBatch inferTSFM + ETSQuantilesq10, q50, q90Storeper participantMonitor next daymasked MASE by cohort, coverage of q10-q90Fallback: ETS onlyif gate fails or model errorsDashed: series that fail the gate skip the TSFM and get a labelled baseline forecast
Fig. A nightly batch pipeline for W1-style forecasting. The gate decides which series are forecast by the foundation model; a classical baseline runs for every series so that a fallback and a comparison are always available; monitoring scores the forecasts the next day on observed hours only.

Sizing. The job's work is set by participants × variates × tokens. For W1: 150,000 participants, 1–2 variates, 6–7 patch tokens each. That is a small transformer workload; the cost is dominated by data loading and per-request overhead, not by attention. Throughput should be measured, not assumed: run the adapter on a sample of 10,000 real contexts on the target hardware, record series per second at several batch sizes, and size the job from the measured rate. As an illustration only, a measured rate of 1,000 series per second would forecast all 150,000 participants in 150 s; the baseline ETS run is a CPU job of similar wall time when parallelised.

Licence and data residency. TimesFM 3 weights are non-commercial, so a commercial health product cannot ship them without the Google Cloud route; source code and weights up to TimesFM 2.5 remain Apache 2.0, and TimesFM 3 weights are restricted to non-commercial, non-production use, according to the TimesFM repository. Hosted APIs such as TimeGPT send data to a third party, which for identifiable health data requires a data-processing agreement and, in many settings, de-identification first. These checks belong before benchmarking: the best model on GIFT-Eval is irrelevant if it cannot legally see the data.

Worked incident · W1 A team extends W1 forecasting to minute-level heart rate during sleep, with a context of two nights (2 × 8 h × 60 = 960 minutes) and a horizon of 60 minutes. Offline, the TSFM beat ETS clearly; after deployment the ratio of masked MASE TSFM/ETS drifts from well below 1 to roughly 1. Measurements that separate causes: (a) data drift would show up as a change in the input distribution (mean heart rate, observed fraction), which is flat; (b) a model change would show a new model hash, which is unchanged; (c) a configuration change shows up in the adapter log, which records an effective context of 512 points: the serving container used the package's default maximum context instead of the 960 used offline, silently truncating the first night. Published evidence supports the size of the effect: Sikder and Pillutla (2026) report that shortening history to 512 steps worsened TimesFM-2.5 by 22.2% and Toto by 20.6% on GIFT-Eval configurations, more than the 9.3% spread of the leaderboard's top ten. Remedy, step by step: (1) set context length explicitly in the adapter and fail the job if the effective context differs from the configured one; (2) log effective context per batch as a metric; (3) add a canary series (a known 960-point sinusoid whose last 60 points are only predictable from the first night) whose error is checked on every run. Cost: longer contexts raise attention cost roughly with the square of the token count, here from 16 to 30 patches of 32 (about 3.5 times the pairs), still small. Validation: a replay of the last week with the corrected context; the fix is supported if the TSFM/ETS ratio returns to its offline value with a bootstrap CI excluding 1, and weakened if it does not, which would point back to drift or to an offline evaluation that was itself leaky.

Calibration in production. A model that outputs q10 and q90 should see about 80% of observed hours fall between them. Monitor the empirical coverage per cohort daily. Coverage well below 80% (intervals too narrow) is common when the target population is noisier than the pretraining corpus; a simple remedy is conformal recalibration: on a recent calibration window, compute the absolute residuals of the median forecast and widen intervals by their empirical 80th percentile. It costs one held-out window and assumes the near future resembles the recent past; it is validated if coverage on the following week returns to 0.75–0.85 without the interval width doubling.

Choosing a model family. For W1-like univariate aggregates, any of the 2025–2026 quantile models is a reasonable start, and the choice is driven by licence, context length and covariate support more than by leaderboard rank, because leaderboard gaps among the top entries are often within noise (evaluation section). For multichannel bedside data, prefer models with explicit cross-variate attention (Chronos-2, TimesFM 3) and measure their gain over the same model run univariately; if the gain is within the bootstrap CI, the simpler path wins.

Zero-shot evaluation and its pitfalls

Zero-shot means the model was never trained on the evaluation series. As pretraining corpora absorb every public dataset, that has become hard to guarantee. A trustworthy TSFM evaluation therefore needs three things: a broad benchmark with strong baselines, probabilistic metrics normalised against a naive forecast, and an explicit audit of overlap between pretraining data and test windows.

Benchmarks. Two benchmarks have become the common reference points, and both were designed with leakage in mind. GIFT-Eval (Aksu et al. 2024) spans 23 datasets, about 144,000 series and 177M points across seven domains and ten frequencies, with univariate and multivariate tasks at short to long horizons. It ships a pretraining corpus of about 230B points designed not to leak into its test splits, and normalises point and probabilistic errors against seasonal naive. fev-bench (Shchur et al. 2025) has 100 tasks across seven domains, 46 of them with covariates, and reports win rates and skill scores with bootstrapped confidence intervals so that small leaderboard gaps are not over-read. Neither contains much physiological data, which is why a health team must also build its own evaluation set.

Metrics that travel. Averaging raw errors across series is meaningless when one series is heart rate in beats per minute and another is step counts in thousands. Scale-free metrics fix this. The mean absolute scaled error (MASE) divides a forecast's mean absolute error by the mean absolute error that seasonal naive (repeat the last season) achieves inside the context; below 1 means the forecast beats repeating yesterday. For probabilistic forecasts, the continuous ranked probability score (CRPS) measures how far the whole predicted distribution is from the outcome; in practice it is approximated by averaging the pinball loss (an asymmetric absolute error, one per quantile) over a set of quantiles. The weighted quantile loss (WQL) is the same sum normalised by the size of the actual values. Across datasets, report the geometric mean of each model's error relative to a baseline: an arithmetic mean is dominated by the one or two datasets where everything fails.

Leakage and familiarity. Meyer et al. (2025) identify two leakage types that inflate reported zero-shot performance. In sample overlap, the test window of a series also appears in the pretraining corpus. In temporal overlap of correlated series, a test series was not itself in the corpus, but a series strongly correlated with it over the same period was (neighbouring sensors, sibling hospital units, two wearables on the same cohort): the model has effectively seen the answer.

Two kinds of leakage in time-series foundation model evaluation, and a clean test. 20162018202020222024 pretraining cutoff Pretrainingcorpus Leakybenchmark Cleanbenchmark series A (2015–2021) series B (2018–2021) A, test 2020: sample overlap C, correlated with B, same period D: unseen, after cutoff
Fig. Two leakage types in TSFM evaluation identified by Meyer et al. (2025): the test window of a series also appears in pretraining (sample overlap), and a test series is correlated with a pretraining series over the same period (temporal overlap of correlated series). A clean test uses series absent from the corpus and windows after its cutoff. Series and dates are invented.

The practical consequences: ask every model card for its pretraining datasets and exclude overlaps from the evaluation set by name and by time window; for correlated domains, evaluate only on windows after the pretraining cutoff; and keep statistical baselines (seasonal naive, ETS, ARIMA) and a linear model in every table, as Zeng et al. (2022) taught the field.

Leaderboard resolution. A ranked list suggests that every step down is a real difference. Sikder and Pillutla (2026) measured how small a difference the GIFT-Eval board can actually detect: it resolves about 6.2 rank places while the median gap between neighbours is 0.91 places, no neighbouring pair in the top ten separates statistically, and replaying the board's history showed third-party submissions reversing 20 pairs of entries without any re-run. The geometric mean of scaled error, which depends only on each entry's own scores, reversed none. The practical reading: treat the top of a leaderboard as a tie group, and pick within it on licence, context length, covariates and cost.

Worked example · W1 The W1 evaluation set is 5,000 participants, one week each, recorded after the pretraining cutoff of every candidate model, with any public wearable dataset named in a model card removed. In the illustrative results, seasonal naive scores MASE 1.05, ETS 0.93, the global linear model 0.90, a zero-shot TSFM 0.84 and the same TSFM with accelerometry as a covariate 0.78. On a public heart-rate dataset that appears in one model's pretraining list, the same TSFM scores 0.70: a gap that the leakage audit flags rather than celebrates. The decision table reports only the clean set.

Let a test set contain series \(i = 1..N\), each with context \(y^{(i)}_{1:T}\) and target \(y^{(i)}_{T+1:T+H}\). Evaluation needs a per-series error that is comparable across series, an aggregation across series and datasets, a statement of uncertainty, and a check that the test data is genuinely unseen.

MASE. With seasonal period \(m\),

\[ \mathrm{MASE} = \frac{\tfrac{1}{H}\sum_{h=1}^{H} |y_{T+h} - \hat{y}_{T+h}|}{\tfrac{1}{T-m}\sum_{t=m+1}^{T} |y_t - y_{t-m}|}. \]

The numerator is the forecast MAE over the horizon \(H\); the denominator is the in-sample MAE of seasonal naive over the context of length \(T\). MASE is unit-free, defined whenever the context is not exactly periodic, and below 1 means the forecast is better than seasonal naive would have been in-sample.

Worked example · W1 A participant's 168-hour context has an average day-over-day absolute change of 5.0 bpm (the denominator, with \(m = 24\) and \(T - m = 144\) pairs). The TSFM's 24-hour forecast has MAE 4.2 bpm. MASE \(= 4.2/5.0 = 0.84\). ETS with MAE 4.65 bpm would score 0.93. The same ratios hold if heart rate is recorded in beats per hour, which is the point of scaling.

CRPS and its quantile approximation. For a predictive CDF \(F\) and outcome \(y\),

\[ \mathrm{CRPS}(F, y) = \int_{-\infty}^{\infty} \big(F(z) - \mathbb 1[z \ge y]\big)^2\,dz = 2\int_0^1 \rho_\tau\big(y, F^{-1}(\tau)\big)\,d\tau, \]

where \(\rho_\tau\) is the pinball loss. With quantile levels \(\tau_1..\tau_L\) the integral is approximated by \(\widehat{\mathrm{CRPS}} = \frac{2}{L}\sum_{l} \rho_{\tau_l}(y, \hat q_{\tau_l})\). For a point forecast (all quantiles equal), CRPS reduces to absolute error, so CRPS and MAE share units. The weighted quantile loss over a dataset is

\[ \mathrm{WQL} = \frac{\sum_{i,h} \tfrac{2}{L}\sum_l \rho_{\tau_l}\big(y^{(i)}_{T+h}, \hat q^{(i)}_{\tau_l, T+h}\big)}{\sum_{i,h} |y^{(i)}_{T+h}|}, \]

a scale-free CRPS that weights series by their magnitude.

Aggregation. For datasets \(d = 1..D\) with model error \(e_d\) and baseline error \(b_d\), the relative score is the geometric mean \(\bar r = \exp\big(\tfrac1D \sum_d \log(e_d/b_d)\big)\). The log makes a halving and a doubling cancel, and a single dataset with ratio 4.0 cannot dominate. With ratios \((0.8, 0.8, 0.8, 4.0)\) the arithmetic mean is 1.6 (the model looks much worse than baseline) and the geometric mean \(\exp(\tfrac14(3\ln 0.8 + \ln 4)) \approx 1.20\).

Uncertainty by paired bootstrap. Per-series scores of two models on the same series are correlated, so their difference \(\delta_i = e^{A}_i - e^{B}_i\) is the right quantity. Resample the \(N\) series with replacement \(R\) times, compute \(\bar\delta^{*(r)}\) each time, and report the 2.5th and 97.5th percentiles as a 95% CI. The unit of resampling must be the independent unit: in health, the participant, not the hour or the window.

Worked example · W1 With \(N = 5{,}000\) participants, mean MASE 0.93 for ETS and 0.84 for the TSFM, and a per-participant standard deviation of the difference of about 0.15, the standard error of \(\bar\delta\) is \(0.15/\sqrt{5{,}000} \approx 0.0021\) and the 95% CI about \(-0.09 \pm 0.004\). The same difference measured on 50 participants would have a CI of about \(\pm 0.04\), still excluding zero; a 0.01 gap would need on the order of \(\big(1.96 \times 0.15/0.01\big)^2 \approx 860\) participants to resolve.

Leakage as a distribution shift in the evaluation. Let \(\mathcal D\) be the pretraining corpus with cutoff date \(c\). A test window \(w = (i, [t_0, t_1])\) has sample overlap if series \(i \in \mathcal D\) and \([t_0, t_1]\) intersects its span in \(\mathcal D\); it has correlated overlap if some \(j \in \mathcal D\) with \(|\mathrm{corr}(y^{(i)}, y^{(j)})| \ge \rho^*\) over the window covers the same period. A window is clean if neither holds and \(t_0 > c\). The reported zero-shot score should be \(\mathbb E[\text{error} \mid \text{clean}]\); averaging in leaky windows estimates a mixture \(\pi\,\mathbb E[\cdot \mid \text{leaky}] + (1-\pi)\,\mathbb E[\cdot\mid\text{clean}]\) that is biased downward in proportion to the leaky share \(\pi\).

Worked example · W1 If 20% of a mixed evaluation set is a public dataset in the pretraining corpus where the TSFM scores 0.70, and the clean 80% scores 0.84, the mixed score is \(0.2 \times 0.70 + 0.8 \times 0.84 = 0.812\): an apparent 3.3% improvement that is entirely leakage.

The evaluation kit has two modules. metrics.py implements MASE, pinball loss, the quantile approximation of CRPS, WQL, the geometric mean of relative errors and a paired bootstrap over participants. audit.py implements the leakage audit as a pure function from test windows, pretraining spans and an optional correlation table to a flag per window.

Evaluation pipeline: audit, forecast, score, aggregate, report with uncertainty.Model cardpretraining setscutoff dateLeakage auditname, window,correlationForecastmodel + baselinessame windowsScore per seriesMASE, CRPS, WQLobserved hoursAggregategeometric mean ofratios to baselineUncertaintypaired bootstrapover participantsReportwin/tie/loss with CIleaky rows separatedaudit.py · metrics.pyEvery step uses the same windows; resampling happens only inside the bootstrap
Fig. The evaluation pipeline implemented by the code in this section. The leakage audit runs before any forecast so that leaky windows are separated, not silently averaged in; uncertainty is computed by resampling participants, the unit that is independent.
import numpy as np

def mase(y, yhat, ctx, m=24):
    """Forecast MAE divided by in-sample MAE of the seasonal-naive forecast on the context."""
    scale = np.mean(np.abs(ctx[m:] - ctx[:-m]))
    return np.mean(np.abs(y - yhat)) / scale

def pinball(y, q_pred, q):
    """Quantile (pinball) loss for one quantile level q. y, q_pred: (H,)"""
    d = y - q_pred
    return np.mean(np.maximum(q * d, (q - 1) * d))

def crps_from_quantiles(y, Q, levels):
    """CRPS approximated as 2 x mean pinball loss over quantile levels. Q: (len(levels), H)"""
    return 2 * np.mean([pinball(y, Q[i], q) for i, q in enumerate(levels)])

def wql(Y, Q, levels):
    """Weighted quantile loss over many series: sum of pinball losses / sum |y|. Y: (N,H), Q: (N,L,H)"""
    num = sum(2 * np.sum(np.maximum(q * (Y - Q[:, i]), (q - 1) * (Y - Q[:, i]))) for i, q in enumerate(levels))
    return num / (len(levels) * np.sum(np.abs(Y)))

def geo_mean_relative(model_err, base_err):
    """Geometric mean over datasets of model/baseline error ratios (< 1 beats baseline)."""
    r = np.asarray(model_err) / np.asarray(base_err)
    return float(np.exp(np.mean(np.log(r))))

def paired_bootstrap(a, b, n_boot=2000, seed=0):
    """95% CI of mean(a - b) by resampling series (participants) with replacement."""
    rng = np.random.default_rng(seed)
    d = np.asarray(a) - np.asarray(b)
    idx = rng.integers(0, len(d), size=(n_boot, len(d)))
    means = d[idx].mean(axis=1)
    return float(d.mean()), tuple(np.percentile(means, [2.5, 97.5]))
from dataclasses import dataclass
from datetime import date
import numpy as np

@dataclass
class Span:
    name: str          # dataset or series identifier
    start: date
    end: date

def leakage_audit(test_windows, pretrain, cutoff, corr=None, rho_max=0.8):
    """Flag each test window as clean or by leakage type.
    test_windows, pretrain: lists of Span; cutoff: pretraining data cutoff date.
    corr: optional dict {(test_name, pretrain_name): correlation over the overlap period}."""
    report = {}
    pre_by_name = {p.name: p for p in pretrain}
    for w in test_windows:
        flags = []
        p = pre_by_name.get(w.name)
        if p and w.start <= p.end and w.end >= p.start:
            flags.append("sample_overlap")                 # same series, overlapping window
        for q in pretrain:
            r = (corr or {}).get((w.name, q.name))
            if r is not None and abs(r) >= rho_max and w.start <= q.end and w.end >= q.start:
                flags.append(f"correlated_with:{q.name}")  # related series, same period
        if w.start <= cutoff and not flags:
            flags.append("before_cutoff")                  # not proven leaky, not proven clean
        report[w.name] = flags or ["clean"]
    return report

The audit returns three kinds of flag. sample_overlap and correlated_with:<name> are positive evidence of leakage. before_cutoff marks windows that are not proven leaky but cannot be proven clean, because the model card may not list every source; they are reported separately, not discarded. The correlation table is computed outside the function, for example as the Pearson correlation of daily means over the shared period, so that the audit itself stays deterministic and testable.

The tests reproduce the worked examples: MASE 0.84 from a 5.0-bpm denominator and a 4.2-bpm error, scale invariance of WQL, the arithmetic-versus-geometric gap for ratios (0.8, 0.8, 0.8, 4.0), a paired bootstrap over 5,000 participants whose CI excludes zero, and the three leakage outcomes (sample overlap, correlated overlap and a clean window).

import numpy as np
from datetime import date
from metrics import mase, crps_from_quantiles, wql, geo_mean_relative, paired_bootstrap
from audit import Span, leakage_audit

# MASE on the W1 worked example: in-sample seasonal-naive MAE 5.0 bpm, forecast MAE 4.2 bpm
ctx = np.tile(np.r_[np.zeros(24), np.full(24, 5.0)], 4)[:168]     # |y_t - y_{t-24}| = 5 everywhere
y, yhat = np.zeros(24), np.full(24, 4.2)
assert np.isclose(mase(y, yhat, ctx), 0.84)

# CRPS of a perfect, sharp quantile forecast is 0; a biased one is positive
lv = [0.1, 0.5, 0.9]
assert crps_from_quantiles(y, np.zeros((3, 24)), lv) == 0
assert crps_from_quantiles(y, np.ones((3, 24)), lv) > 0

# WQL is scale-free: multiplying data and forecasts by 60 (bpm -> beats/hour) leaves it unchanged
Y = np.random.default_rng(1).normal(70, 5, (10, 24)); Q = np.stack([Y - 3, Y, Y + 3], axis=1)
assert np.isclose(wql(Y, Q, lv), wql(60 * Y, 60 * Q, lv))

# Geometric vs arithmetic mean: one hard dataset dominates the arithmetic mean
model, base = [0.8, 0.8, 0.8, 4.0], [1.0, 1.0, 1.0, 1.0]
print("arith ratio", np.mean(np.array(model) / base), "geo ratio", round(geo_mean_relative(model, base), 3))
assert geo_mean_relative(model, base) < np.mean(np.array(model) / base)

# Paired bootstrap over 5,000 participants: per-person MASE of model vs ETS
rng = np.random.default_rng(0)
ets = rng.gamma(9, 0.93 / 9, 5000); tsfm = ets * rng.normal(0.84 / 0.93, 0.15, 5000)
diff, ci = paired_bootstrap(tsfm, ets)
print(f"mean MASE diff {diff:.3f}, 95% CI ({ci[0]:.3f}, {ci[1]:.3f})")
assert ci[1] < 0                                      # the model is better, and the CI excludes 0

# Leakage audit
pre = [Span("public_hr_A", date(2015, 1, 1), date(2021, 12, 31)), Span("public_hr_B", date(2018, 1, 1), date(2021, 12, 31))]
tests = [Span("public_hr_A", date(2020, 1, 1), date(2020, 6, 30)),
         Span("site_C", date(2020, 3, 1), date(2020, 12, 31)),
         Span("w1_week", date(2024, 3, 4), date(2024, 3, 11))]
rep = leakage_audit(tests, pre, cutoff=date(2021, 12, 31), corr={("site_C", "public_hr_B"): 0.91})
print(rep)
assert rep == {"public_hr_A": ["sample_overlap"], "site_C": ["correlated_with:public_hr_B"], "w1_week": ["clean"]}
print("eval OK")
$ python3 test_eval.py
arith ratio 1.6 geo ratio 1.196
mean MASE diff -0.090, 95% CI (-0.094, -0.085)
{'public_hr_A': ['sample_overlap'], 'site_C': ['correlated_with:public_hr_B'], 'w1_week': ['clean']}
eval OK

Debugging tips. A MASE of infinity or NaN means the context is exactly periodic or constant (the denominator is zero); flag such series instead of dropping them silently, because a device stuck at a constant value is itself a data-quality signal. A bootstrap CI that is implausibly narrow usually means the resampling unit was a window or an hour rather than a participant. If a model's WQL looks excellent but its MASE does not, check whether the quantiles are in the original units: WQL computed on scaled forecasts against unscaled targets is meaningless.

Evaluation in production has two jobs: deciding whether to adopt or replace a model, and detecting when an adopted model stops earning its place. Both fail in the same ways: leakage, wrong resampling unit, and over-reading small gaps.

Worked incident · W1 A candidate TSFM is proposed to replace the current one because its published GIFT-Eval rank is three places higher, and an internal comparison on a mixed set (internal W1 weeks plus two public wearable datasets) shows MASE 0.81 against 0.84. Problem: the decision would rest on a 0.03 gap. Why it matters: switching models costs validation work, a new licence review and re-tuned monitoring thresholds. Diagnosis: (1) the leakage audit against the candidate's model card flags one public dataset as sample overlap; (2) splitting the result shows the candidate's advantage comes almost entirely from that dataset; on the clean, post-cutoff W1 weeks both models score 0.84 and the paired bootstrap CI on the difference spans zero; (3) the published rank gap is three places, within the roughly six-place resolution reported for GIFT-Eval by Sikder and Pillutla (2026). Remedy: keep the current model; record the comparison; add the flagged dataset to a permanent exclusion list keyed by name and time span. Trade-off: the audit depends on model cards being complete; for models whose corpus is undocumented, only post-cutoff internal data can be trusted, which shrinks the evaluation set. Validation: the decision is supported if a second clean set (the next month of W1 weeks) again shows a CI spanning zero; it is weakened if the candidate then wins with a CI excluding zero, which would indicate a real but small advantage worth a cost-benefit review.

Designing the decision set. A decision set for W1 has four properties. It is post-cutoff: every window starts after the latest pretraining cutoff among the candidates. It is participant-disjoint from anything used to tune the system (thresholds, conformal calibration windows). It is stratified by the variables that move error: device generation, observed fraction, age band, sex and site. And it is sized for the effect of interest: with a per-participant standard deviation of the MASE difference of about 0.15, resolving a 0.03 difference at 95% confidence needs about \((1.96 \times 0.15/0.03)^2 \approx 96\) participants per stratum, and a 0.01 difference about 860. Strata smaller than that should be reported with their CIs, not ranked.

Dashboard panelComputationAlert rule (illustrative)Distinguishes
Relative errorGeometric mean of masked MASE ratio TSFM/ETS, daily, per cohort7-day mean > 0.95Model regression from seasonal or population change
Absolute errorMedian masked MAE in bpmShown, not alertedContext for the ratio
CoverageShare of observed hours inside q10–q90Outside 0.75–0.85 for 3 daysCalibration drift
ScorabilityShare of series with defined masked MASEDrop > 5 pointsInput-quality problems
Audit statusLeaky or unproven windows in decision setAny > 0Contaminated evidence

Table. A monitoring dashboard for W1 forecasting. The ratio is the primary signal because it cancels effects that move the TSFM and the baseline together.

Connection. Everything in this section assumes errors can be computed on the hours that exist. In wearable health data, 38% of hours do not, and how they are handled changes both the forecasts and the scores. The next section turns to that and to the published health evidence.

What the evidence says for health data

Health is a small slice of TSFM pretraining corpora, and health time series have three properties that general benchmarks rarely test: they are personal (what is normal differs between people), gappy (devices come off, sensors saturate, patients leave the ward) and instrumental (forecasting is usually a means to detecting something, not the goal). The direct evidence on how general TSFMs handle this is still thin and mixed.

Forecasting physiological aggregates. Peräkylä et al. (2026) forecast heart-rate variability from consumer wearables zero-shot with TimesFM, Chronos-Bolt and Moirai. TimesFM and Chronos beat mean, exponentially weighted moving average and ETS baselines, with average MASE of about 0.81–0.87 for the foundation models, while Moirai's gain over the mean baseline was not significant. For smooth, slowly varying daily or nightly aggregates, general TSFMs are therefore reasonable zero-shot forecasters.

Representations for prediction. Wang et al. (2025) combined All of Us electronic health records with Fitbit data for ten conditions. Adding wearables improved AUROC for all ten, but simple hand-engineered wearable statistics generally outperformed MOMENT embeddings (the authors report this across all ten outcomes, though their supplementary table shows MOMENT slightly ahead for two conditions in the wearable-only setting). When the goal is a representation of a person's health rather than a forecast, a general TSFM's embedding was not the best input in this study.

Benchmarks and domain-specific models. OpenMHC (Schuetz et al. 2026) released more than 60M hours from 11,894 My Heart Counts participants with a benchmark that pits classical methods against wearable and multivariate TSFMs on prediction, imputation and forecasting. A 2026 preprint, SOTER (Chen et al. 2026), pretrains a 50M-parameter generative model on about 226B time points of public physiological recordings (MIMIC-III waveforms, Sleep-EDF, PTB-XL, WESAD, Chapman ECG) and reports lower zero-shot forecasting error than Chronos-2, TimesFM 2.5 and Moirai 2.0 on most of six physiological datasets (best MAE on five, best RMSE on four), higher linear-probe classification AUROC than general models, and the lowest imputation error at 75% missingness. The exception, MMASH, has low-complexity dynamics by the authors' permutation-entropy measure and was won by the general models. Read together with the HRV result, the pattern is that general TSFMs do well on smooth, low-complexity signals and worse on raw, fast physiological waveforms; SOTER is a single-group preprint and this pattern should be treated as provisional.

Which tool fits which health question: forecasting aggregates, imputation, or representation for diagnosis.Health time-series taskwhat is the output?Forecast an aggregatenext-day HR, HRV, glucoseFill gaps / flag anomaliesoff-wrist hours, artefactsPredict a conditionAFib, age, sleep apneaGeneral TSFM is a fair startbeats mean/ETS on HRVTSFM or masked modelscore on observed hours onlyModality-specific encoderand summary statistics
Fig. Matching the tool to the question. Published evidence supports general time-series foundation models as zero-shot forecasters of smooth physiological aggregates; for predicting conditions, modality-specific encoders and well-chosen summary statistics have outperformed general TSFM embeddings.

Missingness. Wearable data is missing in blocks, not at random: off-wrist while charging, during showers, overnight for some users. A model that receives missing hours as zeros sees a heart rate of 0 bpm and forecasts accordingly; one that receives them as "not a number" depends on whether the package masks them or silently fills them. Scoring is affected too: an error computed on filled hours measures the filling method, not the forecast. The safe rule is to fill the context with a method that does not invent structure (the same hour on the nearest observed day), and to score only hours that were actually observed.

Worked example · W1 38% of W1 hours have no PPG. On synthetic W1-like data with 38% of hours removed in off-wrist blocks, an ETS forecaster given zero-filled contexts scores a masked MASE of 9.3, a disaster caused entirely by the fake zeros; with same-hour seasonal filling it scores 0.90, close to its 0.87 on complete data. For representations, the W1 encoder's linear probe reaches AFib AUROC 0.93 (0.88 for a model trained from scratch). An illustrative comparison in the spirit of Wang et al. would add two rows to that table: a probe on hand-engineered daily heart-rate statistics and a probe on a general TSFM's embeddings, both required baselines before the W1 encoder's gain can be credited to its pretraining.

Reading the evidence. General TSFMs are reasonable zero-shot forecasters for smooth physiological aggregates, but as representations of health they have lost to modality-specific models and even to well-chosen summary statistics. They are best treated as strong baselines and as imputers, not as the answer. Chapter 7 describes the modality-specific encoders that are the alternative, and Chapter 11 the adaptation and evaluation methods for both.

Two quantitative questions decide whether a general TSFM is useful for a health task: does it forecast better than baselines once missingness is handled correctly, and do its embeddings carry more predictive information than cheap summary statistics?

Observed-hours scoring. Let \(o_t \in \{0,1\}\) indicate that hour \(t\) was observed. The masked MASE scores only observed target hours and builds the scale only from observed pairs:

\[ \mathrm{MASE}_o = \frac{\sum_{h} o_{T+h}\,|y_{T+h} - \hat y_{T+h}| \big/ \sum_h o_{T+h}}{\sum_{t=m+1}^{T} o_t o_{t-m}\,|y_t - y_{t-m}| \big/ \sum_{t=m+1}^{T} o_t o_{t-m}}. \]

If observations are missing independently with probability \(\pi\), the expected number of usable pairs in the denominator is \((1-\pi)^2 (T-m)\), and the numerator averages over about \((1-\pi) H\) hours.

Worked example · W1 With \(\pi = 0.38\), \(T = 168\), \(m = 24\), \(H = 24\): usable scale pairs \(0.62^2 \times 144 \approx 55\), and scored target hours \(0.62 \times 24 \approx 15\). Because W1 gaps come in blocks, the realised counts vary more than this independent-missingness estimate suggests; a participant with a 30-hour charging gap can lose most of a day. A scorer that returns "not scorable" when fewer than 24 scale pairs exist removed 8 of 300 synthetic W1-like participants with 38% of hours missing in blocks.

Why zero-filling is catastrophic. If a missing hour is set to 0 in the context, an exponentially smoothed level absorbs \(\alpha \times (0 - \ell)\) at each such hour: with \(\ell = 70\) bpm and \(\alpha = 0.3\), a single missing hour moves the level by \(-21\) bpm, and a 6-hour gap leaves \(0.7^6 \approx 12\%\) of the original level. The forecast collapses toward zero and its error, divided by a scale of about 5 bpm, gives a masked MASE near 9 (9.3 for ETS on synthetic W1-like data with 38% of hours missing). Transformer TSFMs are not immune: mean scaling with zeros lowers \(s\), and the zeros themselves are patterns the model will try to continue.

Seasonal filling. Fill missing hour \(t\) with \(y_{t + km}\) for the integer \(k \ne 0\) of smallest \(|k|\) such that hour \(t+km\) was observed. This preserves the daily shape and personal level, adds no new information, and leaves observed values untouched. Its bias is the day-to-day change in that hour slot, of the order of the scale (about 5 bpm in W1), much smaller than the 70-bpm error of zero-filling.

Comparing representations. For a binary condition with \(n_1\) positives and \(n_0\) negatives, AUROC is the probability that a random positive scores above a random negative. Its standard error is approximately (Hanley–McNeil)

\[ \mathrm{SE}(\mathrm{AUC}) \approx \sqrt{\frac{A(1-A) + (n_1 - 1)(Q_1 - A^2) + (n_0 - 1)(Q_2 - A^2)}{n_1 n_0}}, \quad Q_1 = \frac{A}{2-A},\; Q_2 = \frac{2A^2}{1+A}. \]
Worked example · W1 Suppose the W1 probe set of 5,000 participants contains 250 with AFib (5%, an illustrative prevalence). At \(A = 0.93\): \(Q_1 = 0.93/1.07 = 0.8692\), \(Q_2 = 2(0.8649)/1.93 = 0.8963\), so \(Q_1 - A^2 = 0.0043\) and \(Q_2 - A^2 = 0.0314\), and \(\mathrm{SE} \approx \sqrt{(0.0651 + 249 \times 0.0043 + 4{,}749 \times 0.0314)/(250 \times 4{,}750)} \approx \sqrt{150.1/1{,}187{,}500} \approx 0.011\). A gap of 0.05 between the W1 encoder (0.93) and a from-scratch model (0.88) is several standard errors; a gap of 0.01 between two baselines is not. Paired methods (DeLong's test or a paired bootstrap over participants) shrink these errors because the same participants are scored by both models.

Summary statistics as a baseline. A feature vector \(\phi(y) = (\bar y, \mathrm{sd}(y), \min_{\text{night}} y, \overline{\mathrm{range}}, \bar o)\) costs nothing to compute and captures resting level, variability, nocturnal minimum, daily amplitude and adherence. Its linear-probe AUROC sets the floor that any learned embedding \(z(y)\) must clear by more than its standard error to justify the cost of the encoder.

The health module implements the four operations the evidence calls for: a realistic missingness generator (off-wrist blocks until a target fraction is missing), seasonal filling of the context, masked MASE that scores only observed hours, and the summary-statistics feature vector that serves as the representation baseline.

import numpy as np

def offwrist_mask(L, frac=0.38, mean_block=6, seed=0):
    """Missingness as contiguous off-wrist/charging blocks until ~frac of hours are missing.
    Returns bool (L,), True = observed."""
    rng = np.random.default_rng(seed)
    obs = np.ones(L, bool)
    while 1 - obs.mean() < frac:
        start = rng.integers(0, L); length = max(1, int(rng.exponential(mean_block)))
        obs[start:start + length] = False
    return obs

def seasonal_fill(x, obs, m=24):
    """Fill missing context hours with the same hour on the nearest observed earlier/later day,
    falling back to the observed mean. Returns filled copy; never touches observed values."""
    y = x.copy(); L = len(x); fallback = x[obs].mean()
    for t in np.where(~obs)[0]:
        cands = [t + k * m for k in range(-7, 8) if k and 0 <= t + k * m < L and obs[t + k * m]]
        y[t] = x[min(cands, key=lambda c: abs(c - t))] if cands else fallback
    return y

def masked_mase(y, yhat, y_obs, ctx, ctx_obs, m=24):
    """MASE computed only on observed target hours; scale only from pairs where both hours were observed."""
    pairs = ctx_obs[m:] & ctx_obs[:-m]
    if pairs.sum() < m or y_obs.sum() == 0:
        return np.nan                                   # too little data: report, do not guess
    scale = np.mean(np.abs(ctx[m:] - ctx[:-m])[pairs])
    return np.mean(np.abs(y - yhat)[y_obs]) / scale

def summary_features(hr, obs):
    """Hand-engineered daily statistics: the baseline any learned representation must beat."""
    d = np.where(obs, hr, np.nan).reshape(-1, 24)
    night = np.nanmean(d[:, 1:5], axis=1)               # 01:00-05:00 as a resting proxy
    return np.array([np.nanmean(d), np.nanstd(d), np.nanmin(night),
                     np.nanmean(np.nanmax(d, 1) - np.nanmin(d, 1)), obs.mean()])

The test compares three conditions on 300 synthetic W1-like participants with 38% of hours removed: zero-filled context, seasonally filled context, and the same participants without missingness. It asserts that seasonal filling beats zero filling, that the mask hits the target fraction within tolerance, that observed values are never modified by the filler, and that the feature vector has the expected shape and a plausible mean heart rate.

import numpy as np, warnings
from w1sim import w1_hourly_hr
from roots import ses_seasonal, T, H
from metrics import mase
from health import offwrist_mask, seasonal_fill, masked_mase, summary_features

warnings.simplefilter("ignore", RuntimeWarning)
data = w1_hourly_hr(n_participants=300, days=8, seed=3)
naive_fill, seas_fill, clean, nan_count = [], [], [], 0
for i, s in enumerate(data):
    obs = offwrist_mask(T + H, 0.38, seed=i)
    ctx, y, c_obs, y_obs = s[:T], s[T:], obs[:T], obs[T:]
    # (a) wrong: treat missing hours as 0 bpm (what a raw export with zero-fill looks like)
    f0 = ses_seasonal(np.where(c_obs, ctx, 0.0))
    # (b) seasonal fill of the context, scored only on observed hours
    f1 = ses_seasonal(seasonal_fill(ctx, c_obs))
    a, b = masked_mase(y, f0, y_obs, ctx, c_obs), masked_mase(y, f1, y_obs, ctx, c_obs)
    if np.isnan(b): nan_count += 1; continue
    naive_fill.append(a); seas_fill.append(b); clean.append(mase(y, ses_seasonal(ctx), ctx))
print(f"zero-fill {np.mean(naive_fill):.2f}  seasonal-fill {np.mean(seas_fill):.2f}  no-missingness {np.mean(clean):.2f}  skipped {nan_count}")
assert np.mean(seas_fill) < np.mean(naive_fill)
obs = offwrist_mask(168, 0.38, seed=1)
assert abs((1 - obs.mean()) - 0.38) < 0.08
filled = seasonal_fill(data[0, :168], obs)
assert np.allclose(filled[obs], data[0, :168][obs])                 # observed values untouched
f = summary_features(data[0, :168], obs)
assert f.shape == (5,) and 40 < f[0] < 100
print("health OK")
$ python3 test_health.py
zero-fill 9.27  seasonal-fill 0.90  no-missingness 0.87  skipped 8
health OK

Reading the output. The masked MASE of 9.27 with zero-filling is not a modelling failure but an input-handling failure; the same forecaster on the same data scores 0.90 when gaps are filled sensibly. The 8 skipped participants had too few observed day-over-day pairs to define a scale; they are counted and reported, never imputed into the score. The no-missingness score (0.87) is computed on all hours and is therefore only approximately comparable; the meaningful comparison is between the two filled conditions.

Using the features. summary_features returns a 5-vector per participant-week. Stacked over the 5,000 W1 probe participants it gives a (5000, 5) matrix for a logistic-regression probe, scored with the same participant-level split and bootstrap as the encoder's probe. NaN-safe reductions (nanmean, nanmin) matter: a day with no observed night hours would otherwise produce NaN for the whole participant.

Debugging tips. If seasonal filling barely improves on zero filling, check that the mask's convention is consistent (here True = observed) across generator, filler and scorer; an inverted mask fills observed hours and scores missing ones. If masked MASE is NaN for many participants, the minimum-pairs threshold is too strict for the gap pattern, or gaps align with the seasonal lag (a device charged at the same hour every day removes the same slot from every pair).

In production the health-specific risks are input quality and over-interpretation: missingness changes without warning, and a forecast that is good on average can be useless for the participants who matter clinically.

Worked incident · W1 A device firmware update changes off-wrist detection. The next week the daily masked MASE ratio TSFM/ETS rises from about 0.90 to about 1.0, and coverage of the q10–q90 interval falls. Measurements that separate causes: (a) observed fraction of context hours drops from a median of 0.62 to 0.50 for updated devices only; (b) stratifying masked MASE by observed fraction shows that within each stratum the ratio is unchanged, so the model has not regressed; the population has moved into strata where the TSFM's advantage is smaller; (c) the adapter log shows that for updated devices some gaps arrive as zeros rather than missing values, because the new firmware reports 0 for "no reading". Remedy, step by step: (1) treat 0 bpm as missing at ingestion, with a unit test on a recorded firmware sample; (2) apply seasonal filling and the observed-fraction gate (0.5) before the TSFM; (3) route series below the gate to the labelled ETS fallback; (4) add observed fraction by firmware version as a dashboard panel. Cost and trade-off: a stricter gate sends more participants to the baseline, reducing the TSFM's coverage; treating 0 as missing would hide a genuine asystole reading, which is acceptable for a consumer wellness forecast but not for a clinical alarm, where a separate validated pipeline must handle it. Validation: after the fix, the ratio within each observed-fraction stratum should match its pre-update value with overlapping bootstrap CIs, and the share of zero values reaching the model should be exactly zero; a persistent gap in the 0.5–0.6 stratum would indicate that filling, not the firmware, now limits accuracy.

Clinical relevance over average error. A forecast service for W1 is usually a means to anomaly detection: flag a participant whose observed heart rate leaves the forecast's q10–q90 band for several consecutive hours. Average MASE says little about this use. The metrics that do are the false-alert rate per participant-week, the share of clinically confirmed events (for example a documented infection or arrhythmia episode) preceded by an alert, and the lead time. These need labelled events, which are scarce; the OpenMHC benchmark (Schuetz et al. 2026) is one public source of wearable data for testing such pipelines before internal data is available.

UseGeneral TSFMEvidenceRequired comparator
Forecast daily or nightly aggregates (HR, HRV)Reasonable zero-shotPeräkylä et al. 2026Mean, EWMA, ETS
Impute gapsPlausible; domain models better at high missingnessChen et al. 2026 (preprint)Seasonal fill, domain model
Embeddings for condition predictionWeakWang et al. 2025Summary statistics, modality-specific encoder
Raw waveform forecasting (PPG, ECG)Weak versus domain modelsChen et al. 2026 (preprint)Domain-pretrained model

Table. Where general time-series foundation models fit in a health pipeline, with the evidence behind each row. The evidence base is small; each row should be re-tested on local, post-cutoff data.

Connection. The chapter's conclusion is operational: deploy a general TSFM where it forecasts smooth aggregates and fills gaps, measure it against classical baselines on clean local data, and do not use its embeddings as the health representation without beating summary statistics first. The specialised wearable and biosignal encoders of Chapter 7 are built to clear that bar.

Wearable and Biosignal Foundation Models

A biosignal foundation model is an encoder pretrained without labels on large volumes of physiological signals, such as photoplethysmography (PPG, the optical pulse signal from a watch's green LEDs), electrocardiography (ECG), accelerometry and electroencephalography (EEG), or on the minute- and hour-level aggregates that wearables derive from those signals (heart rate, step counts, sleep estimates). The encoder turns a stretch of signal into a fixed-length vector, an embedding, and small supervised models called probes read health targets from that vector.

The approach exists because of a mismatch in volume. A watch records continuously, but a diagnosis, a lab value or a questionnaire answer arrives rarely. Before 2023 the standard approach was one supervised network per task: a network for atrial fibrillation (AFib) from PPG, another for sleep stage from accelerometry, each limited by its own labelled set. The foundation-model approach pretrains once on the large unlabelled cohort and then probes for many targets with the few labels available.

The chapter follows the components of such a system in order: what the encoder learns from and how positive pairs are defined (section 7.1), how it copes with data that is missing much of the time and how it behaves as data grows (7.2), which open models exist for PPG, ECG and EEG (7.3), and what scaling laws and cohort composition imply for generality (7.4).

Worked example · W1

Reference workload W1 is a wearable PPG foundation model: 150,000 participants, 30 million participant-hours of PPG plus accelerometry at 64 Hz, cut into 10-second windows of 640 samples each (about 10.8 billion windows, 1% sampled per epoch). A 50-million-parameter encoder produces a 256-number embedding per window and is trained contrastively. Linear probes trained on 5,000 labelled participants reach AFib AUROC 0.93 (0.88 for a supervised model trained from scratch), age error 6.1 years and resting heart-rate error 2.4 bpm. In 38% of enrolled hours the device records no PPG. All W1 numbers are illustrative.

From a wearable cohort to many downstream tasks: windows, a label-free encoder, embeddings and light probes.Cohort150k participants30M h PPG + accelWindows10 s at 64 Hz640 samplesEncoder50M parametersno labelsEmbedding256 numbersper windowProbesAFib, age,resting HRpretraining datatrained oncelabels needed only here38% of enrolled hours carry no PPG (off-wrist, charging): missingness is part of the input.All numbers are illustrative values of reference workload W1.
Fig. The chapter in one picture. A cohort of continuous recordings is cut into windows; an encoder is pretrained once without labels; its embeddings feed small supervised probes for many targets. Sections 7.1 to 7.4 cover what the encoder learns from (physiology, behavior, distillation), how it copes with missing data, which open models exist, and how performance scales with data and cohort. Numbers are from reference workload W1 and are illustrative.

The mental model for the chapter: the encoder is a compression of physiology and behavior learned from volume; the probe is a cheap reader of that compression. The quality of the result depends on what the encoder was taught to treat as "the same" (positives), what it was allowed to ignore (gaps, noise), and whose bodies and devices it saw (the cohort).

Let a recording be a matrix \(x \in \mathbb{R}^{C \times T}\) with \(C\) channels and \(T\) samples at sampling rate \(f_s\). Windowing cuts it into segments \(x_j \in \mathbb{R}^{C \times w}\) of \(w = f_s \cdot \Delta\) samples, where \(\Delta\) is the window length in seconds. An encoder \(f_\theta: \mathbb{R}^{C \times w} \to \mathbb{R}^{d}\) with parameters \(\theta\) maps each window to an embedding \(z_j = f_\theta(x_j)\). Pretraining chooses \(\theta\) to minimize a self-supervised loss that needs no labels; downstream, a probe \(g_\phi(z) = \sigma(\phi^\top z + b)\) (a logistic regression for a binary target) is fitted on the labelled subset with \(\theta\) frozen.

The budget of a pretraining run is set by counting windows. With \(H\) recorded hours, the number of non-overlapping windows is \(N_w = 3600 H / \Delta\); sampling a fraction \(\rho\) per epoch gives \(N_w \rho\) windows and \(\lceil N_w \rho / B \rceil\) optimizer steps at batch size \(B\).

Worked example · W1

With \(f_s = 64\) Hz and \(\Delta = 10\) s, \(w = 640\). For \(H = 3 \times 10^7\) hours, \(N_w = 3600 \cdot 3\times10^7 / 10 = 1.08 \times 10^{10}\) windows. At \(\rho = 0.01\) an epoch sees \(1.08 \times 10^8\) windows, which at \(B = 4{,}096\) is \(\lceil 26{,}367.2 \rceil = 26{,}368\) steps. The embedding has \(d = 256\), so a linear AFib probe has 257 parameters, fitted on 5,000 participants.

Three quantities recur in the chapter: the self-supervised loss (which pairs or which masked values define the training signal), the missingness mask \(m \in \{0,1\}^{C \times T}\) (which entries exist), and the scaling of loss with parameters \(N\) and data \(D\), \(L(N, D)\). The trade-off running through all of them is that the pretraining loss is cheap to measure and the clinical metric (AUROC, mean absolute error) is what matters; the two are linked only empirically.

The first piece of code in any biosignal pipeline turns continuous multichannel recordings into fixed-length windows and checks that the counts used to plan compute are right. The array convention is channels first: a recording is (C, T); a batch of windows is (n_windows, C, w).

import numpy as np

FS = 64                 # samples per second (PPG + accelerometry)
WIN_S = 10              # window length in seconds
WIN = FS * WIN_S        # 640 samples per window

def make_windows(x, fs=FS, win_s=WIN_S):
    """x: (C, T) multichannel recording -> (n_windows, C, fs*win_s).
    Trailing samples that do not fill a whole window are dropped."""
    w = fs * win_s
    n = x.shape[1] // w
    return x[:, : n * w].reshape(x.shape[0], n, w).transpose(1, 0, 2)

def corpus_budget(hours, sample_frac=0.01, batch=4096):
    windows = int(hours * 3600 // WIN_S)          # 360 windows per hour
    per_epoch = int(windows * sample_frac)
    return windows, per_epoch, -(-per_epoch // batch)   # ceil division

# one hour of PPG + 3 accelerometer axes = 4 channels
hour = np.random.default_rng(0).standard_normal((4, 3600 * FS)).astype(np.float32)
win = make_windows(hour)
assert win.shape == (360, 4, 640)
assert np.array_equal(win[1, 0], hour[0, 640:1280])   # window 1 = samples 640..1279

windows, per_epoch, steps = corpus_budget(30e6)
print(f"windows={windows:.3e} per_epoch={per_epoch:.3e} steps/epoch={steps}")
assert windows == 10_800_000_000 and per_epoch == 108_000_000

Output:

windows=1.080e+10 per_epoch=1.080e+08 steps/epoch=26368

Reading it. make_windows reshapes rather than copies, so windowing a day of four-channel 64 Hz data is cheap. The assertion on window 1 guards against the most common bug: transposing to (C, n, w) in the wrong order silently interleaves channels and time.

Worked example · W1

One hour of four-channel data (PPG plus three accelerometer axes) yields 360 windows of shape (4, 640). For 30 million hours the budget function returns 1.08 × 1010 windows, 1.08 × 108 per epoch at 1% sampling and 26,368 steps per epoch at batch 4,096.

Debugging tips. Count windows per participant and compare with recorded wear time; a ratio far from 360 per hour indicates dropped files or duplicated uploads. Keep the participant id and window start time beside every window from the start: section 7.1 needs them to form positive pairs, and evaluation needs them for participant-level splits.

At production scale the first constraint is storage and input throughput, not model compute. Raw 64 Hz signals are large, and a contrastive objective needs random access to pairs of windows from the same participant.

Worked example · W1

Four channels stored as 16-bit integers: 3 × 107 h × 3,600 s × 64 Hz × 4 channels × 2 bytes ≈ 55.3 TB. One epoch at 1% sampling reads 1.08 × 108 windows × 640 × 4 × 2 bytes ≈ 553 GB, which is modest in bytes but consists of 1.08 × 108 random reads of about 5 KB each. If each read is a separate object-store request at 50 ms latency with 64 requests in flight, the loader delivers 1,280 windows per second and one epoch takes 1.08 × 108 / 1,280 ≈ 84,400 s, about 23 hours. Packing windows into sequential shards of 10,000 windows (about 51 MB) cuts the request count to 10,800 per epoch. The latency and concurrency figures are assumptions for illustration.

Diagnosis and remedy. If accelerator utilization stays low while the data loader's queue is empty, the input pipeline is the bottleneck. The usual remedy, in order: (1) pre-shard by participant so both members of a positive pair are in the same shard; (2) write shards in a sequential format and shuffle at the shard level plus a bounded in-memory buffer; (3) decode and normalize on CPU workers ahead of the accelerator. The trade-off is reduced randomness: a shuffle buffer smaller than a few participants' data makes consecutive batches correlated. A validation is to compare the InfoNCE loss curve against a fully shuffled small run; a persistent gap points to correlated batches.

MetricTarget in W1What a breach suggests
Accelerator utilization> 85%Input pipeline or pair sampling is the bottleneck
Windows per participant-hour360 ± 1%Dropped or duplicated files
Share of hours with PPG62%Firmware or upload change altered missingness
Probe AUROC on fixed AFib set≥ 0.93Representation regression; block release

The sections that follow each add their own production view: positive-pair construction and device shifts (7.1), missingness that is not random (7.2), adopting open checkpoints (7.3) and planning scaling sweeps against cohort bias (7.4).

PPG, ECG, accelerometry and behavior models

Definition. The clearest example of scaling a biosignal foundation model on a single consented cohort is a research line from Apple built on the Apple Heart and Movement Study (Truslow et al. 2024), a remote study that began enrolment in November 2019 and whose first-year baseline cohort already counted 82,809 participants. Three model families came out of it: encoders of raw physiology (PPG and ECG), an accelerometer encoder taught by the PPG encoder, and an encoder of hourly behavior.

Motivation. Earlier wearable models were trained per task on labelled subsets, so each new question (blood pressure, pregnancy, a medication effect) needed a new labelled dataset. A pretrained encoder whose embedding already carries physiological information can be probed for new targets with a small labelled set, and the same embedding serves many targets at once.

Physiology encoders, end to end. Abbaspourazad et al. (2023) pretrained separate PPG and ECG encoders on data from about 141,000 participants collected over about three years. The training loop works as follows. Two segments are drawn from the same participant; this is a participant-level positive pair, the assumption being that two recordings of the same person share stable traits (vascular properties, age-related pulse shape) that the encoder should capture. Each segment passes through a stochastic augmentation module (random perturbations such as noise and cropping) so that the encoder cannot match pairs by trivial details. One segment goes through the online encoder; the other through a momentum encoder, a slowly updated copy of the online encoder whose weights are a running average of the online weights, which keeps the comparison targets stable across steps. A regularized contrastive loss rewards the encoder when each segment's embedding is closer to its partner than to the embeddings of other participants in the batch. After training, the momentum encoder is discarded and the online encoder's embeddings are frozen.

Result. Simple heads on the frozen embeddings predicted demographics and a range of self-reported health conditions, and the PPG model was generally the stronger of the two modalities. The paper appeared at ICLR 2024.

Three model lines on one cohort: physiology encoders, an accelerometer encoder distilled from the PPG encoder, and a behavior encoder; physiology and behavior embeddings are concatenated for probes.PPG / ECG segmentsraw waveformsPhysiology encoderparticipant positivesPPG embeddingAccelerometerraw, low powerAccel. encoderstudentaccel. embeddingWeekly behavior168 h x 27 quantitiesBehavior encoderWBM, Mamba-2behavior embeddingConcatenatethen linearprobeteacherused alone
Fig. The physiology, distillation and behavior lines described in this section. Arrows show data flow; the dashed arrow is the teacher signal used only during distillation training. The accelerometer embedding is used on its own where PPG is unavailable; WBM and PPG embeddings combined gave the best results in Erturk et al. (2025).

Distillation to low-power sensors. PPG is power-hungry; accelerometers run almost always. Abbaspourazad et al. (2024) trained an accelerometer encoder (the student) to produce embeddings that match the frozen PPG encoder's embeddings (the teacher) for simultaneous segments, using about 20 million minutes of unlabelled data from about 172,000 participants. A useful check is retrieval: given an accelerometer embedding, find the PPG embedding from the same moment among many candidates. On unseen data this succeeded in 99.2% of cases (top-1 accuracy), and the distilled encoders beat accelerometer-only self-supervised or supervised encoders by 23–49% on heart-rate and heart-rate-variability prediction. The limitation is that retrieval accuracy depends on how many candidates are searched, and matching a teacher caps the student at what the teacher knows.

Behavior rather than physiology. Erturk et al. (2025) built the Wearable Behavior Model (WBM) on 27 hourly HealthKit quantities (activity, cardiovascular, vitals, gait, body measurements, fitness) from about 162,000 people and more than 2.5 billion hours. A week becomes a 168 × 27 matrix plus indicators of which entries are missing. After comparing three tokenizers and three backbones, a dense tokenizer with a bidirectional Mamba-2 encoder (a state-space model whose cost grows linearly with sequence length) performed best.

WBM's results are the most useful for practitioners. Across 57 tasks it beat a baseline on 39 of 47 static outcomes and on all 8 time-varying ones; it beat the PPG model on 18 of 47 static outcomes, mostly sleep-related; and concatenating WBM and PPG embeddings was best on 42 of 47. Behavior and physiology are complementary. The authors list selection bias, self-reported labels and unreleased weights as limitations.

Worked example · W1

W1 follows the physiology recipe: positives are two 10-second windows from the same participant recorded within 24 hours, the batch is 4,096 windows, and the encoder output is a 256-number embedding. Its linear AFib probe reaches AUROC 0.93 against 0.88 for a supervised model trained from scratch on the same 5,000 labelled participants. A behavior encoder over W1's hourly aggregates would be a separate model; the WBM result suggests concatenating the two embeddings before probing.

Compare and contrast. Against per-task supervised models, the foundation approach moves most of the cost to one pretraining run and makes each new target cheap. What it costs: the encoder learns whatever separates participants, which includes device type, wear habits and demographics, so a probe can succeed for the wrong reason. The mental model: participant-level positives teach "who is this and in what state", distillation transfers that to cheaper sensors, and behavior encoders add "what does this person do", which physiology alone misses.

The contrastive objective. For a batch of \(B\) positive pairs, let \(u_i\) and \(v_i\) be the L2-normalized embeddings of the two windows of pair \(i\), and \(s_{ik} = u_i^\top v_k\) their cosine similarity. With temperature \(\tau > 0\), the InfoNCE loss for anchor \(i\) is

\[ \ell_i = -\log \frac{\exp(s_{ii}/\tau)}{\sum_{k=1}^{B} \exp(s_{ik}/\tau)} = \log\Big(1 + \sum_{k \ne i} \exp\big((s_{ik} - s_{ii})/\tau\big)\Big), \]

and the batch loss is the mean of \(\ell_i\). The second form shows what is optimized: every negative \(k\) contributes in proportion to how close it comes to the positive, scaled by \(1/\tau\). A small \(\tau\) concentrates the gradient on the hardest negatives.

Two reference values. If embeddings carry no information, the similarities of random unit vectors in \(d\) dimensions have standard deviation about \(1/\sqrt{d}\), so the logits \(s/\tau\) have spread \(\sigma = 1/(\tau\sqrt{d})\). The expected loss is then about \(\log B + \sigma^2/2\) (the second term is the log-normal correction to a sum of exponentials). If the positive has similarity \(s_+\) and negatives are random, \(\ell \approx \log\big(1 + \exp(\log(B-1) + \sigma^2/2 - s_+/\tau)\big)\).

Worked example · W1

With \(B = 4{,}096\), \(\tau = 0.1\) and \(d = 256\): \(\sigma = 1/(0.1 \cdot 16) = 0.625\), so the uninformative loss is \(\log 4096 + 0.195 = 8.318 + 0.195 = 8.513\) nats. If positives reach \(s_+ = 0.917\), the positive logit is 9.17 against a negative log-sum of \(\log 4095 + 0.195 = 8.512\), giving \(\ell \approx \log(1 + e^{-0.66}) = 0.42\). A loss of 0.42 therefore already means well-aligned positives at this batch size; it does not mean the encoder is failing.

Momentum encoder. The partner embedding \(v_i\) comes from a second network with weights \(\xi\) updated as \(\xi \leftarrow \mu \xi + (1-\mu)\theta\) after each step, where \(\theta\) are the online weights and \(\mu\) is close to 1. This exponential moving average changes slowly, so targets do not shift abruptly; gradients flow only through the online branch.

Distillation. Let \(p_j\) be a PPG window and \(a_j\) the simultaneous accelerometer window. The teacher \(f\) is frozen; the student \(g_\psi\) is trained with the same InfoNCE form where \(u_j = g_\psi(a_j)\) and \(v_j = f(p_j)\), so the student must pick the teacher embedding of the same moment among \(B\) candidates. Top-1 retrieval accuracy over a gallery of \(M\) segments is \(\frac{1}{M}\sum_j \mathbb{1}\big[\arg\max_k u_j^\top v_k = j\big]\); chance is \(1/M\), so 99.2% must be read against the gallery size.

Behavior encoder input. WBM represents a week as \(X \in \mathbb{R}^{168 \times 27}\) with mask \(M \in \{0,1\}^{168 \times 27}\) (1 where the quantity was recorded). A dense tokenizer turns each hour into one token, so the backbone sees a sequence of length 168; a bidirectional state-space model processes it in \(O(L)\) time for sequence length \(L\), against \(O(L^2)\) for full self-attention.

Combining embeddings. With physiology embedding \(z_p \in \mathbb{R}^{d_p}\) and behavior embedding \(z_b \in \mathbb{R}^{d_b}\), the concatenated probe is \(\sigma(\phi^\top [z_p; z_b] + b)\) with \(d_p + d_b + 1\) parameters. Complementarity shows up as a gain of the joint probe over both single probes on the same split, as in WBM's 42 of 47 outcomes.

The code implements the three ingredients of this section: the InfoNCE loss, participant-level positive sampling with a 24-hour window, and the top-1 retrieval check used to validate distillation. Shapes: embeddings are (B, d); participant ids and timestamps are (n,).

import numpy as np

def l2norm(z):
    return z / np.linalg.norm(z, axis=1, keepdims=True)

def info_nce(za, zb, tau=0.1):
    """za, zb: (B, d) embeddings; row i of za and row i of zb come from the
    same participant (the positive pair); every other row of zb is a negative.
    Returns the mean cross-entropy of picking the positive among B candidates."""
    za, zb = l2norm(za), l2norm(zb)
    logits = za @ zb.T / tau                       # (B, B) cosine / temperature
    logits -= logits.max(axis=1, keepdims=True)    # numerical stability
    logp = logits - np.log(np.exp(logits).sum(axis=1, keepdims=True))
    return -np.mean(np.diag(logp))

def sample_pairs(participant, t_hours, rng, max_gap_h=24.0):
    """For each anchor window, pick a positive from the same participant
    recorded within max_gap_h hours (never the anchor itself).
    participant: (n,) ids; t_hours: (n,) timestamps. Returns index array."""
    pos = np.empty(len(participant), dtype=int)
    for i in range(len(participant)):
        ok = np.flatnonzero((participant == participant[i]) &
                            (np.abs(t_hours - t_hours[i]) <= max_gap_h))
        ok = ok[ok != i]
        pos[i] = rng.choice(ok)
    return pos

def top1_retrieval(student, teacher):
    """Fraction of student embeddings whose nearest teacher embedding
    (cosine) is the one from the same time segment (same row)."""
    s, t = l2norm(student), l2norm(teacher)
    return np.mean(np.argmax(s @ t.T, axis=1) == np.arange(len(s)))

rng = np.random.default_rng(0)
B, d = 4096, 256
# 1) random embeddings: loss ~ log(B) + s^2/2, where s = 1/(tau*sqrt(d)) is the
#    spread of random cosine logits (log-normal correction to log-sum-exp)
rand = info_nce(rng.standard_normal((B, d)), rng.standard_normal((B, d)))
expect = np.log(B) + 0.5 * (1 / (0.1 * np.sqrt(d))) ** 2
print(f"random InfoNCE = {rand:.3f}  log(B) = {np.log(B):.3f}  expected = {expect:.3f}")
assert abs(rand - expect) < 0.05

# 2) participant-aligned embeddings: a shared participant vector plus noise
base = rng.standard_normal((B, d))
good = info_nce(base + 0.3 * rng.standard_normal((B, d)),
                base + 0.3 * rng.standard_normal((B, d)))
print(f"aligned InfoNCE = {good:.4f}")
assert 0.3 < good < 0.6   # cos(pos) ~ 0.92 still pays ~0.42 nats against 4,095 negatives

# 3) positive sampling respects participant and the 24 h window
pid = np.array([0, 0, 0, 1, 1, 2, 2])
t = np.array([0.0, 5.0, 28.0, 1.0, 2.0, 0.0, 23.5])
pos = sample_pairs(pid, t, rng)
assert all(pid[pos] == pid) and all(np.abs(t[pos] - t) <= 24) and all(pos != np.arange(7))
print("positives:", pos.tolist())

# 4) distillation check: accelerometer student vs PPG teacher
teacher = rng.standard_normal((1000, d))
for noise in (3.0, 5.0):          # noise std relative to unit-variance signal
    student = teacher + noise * rng.standard_normal((1000, d))
    print(f"noise {noise}: top-1 retrieval = {top1_retrieval(student, teacher):.3f}")
assert top1_retrieval(teacher, teacher) == 1.0

Output:

random InfoNCE = 8.521  log(B) = 8.318  expected = 8.513
aligned InfoNCE = 0.4184
positives: [1, 2, 1, 4, 3, 6, 5]
noise 3.0: top-1 retrieval = 0.965
noise 5.0: top-1 retrieval = 0.463

Reading it. The first check reproduces the derived uninformative loss (8.521 measured against 8.513 expected), which is the right sanity test for a fresh training run: if the step-0 loss is far from this value, normalization or the temperature is wrong. The second check shows that aligned positives at batch 4,096 still give about 0.42 nats. The sampler never returns the anchor itself and never crosses participants or the 24-hour limit. The retrieval check shows how quickly top-1 accuracy falls as the student's error grows relative to the signal.

Worked example · W1

In W1 a training dashboard that shows step-0 loss near 8.5 and a plateau near 0.4 is behaving as predicted: at batch 4,096, temperature 0.1 and 256 dimensions the uninformative loss is \(\log 4096 + 0.195 \approx 8.5\) nats, and positives with cosine similarity about 0.92 leave about 0.42 nats. A plateau near 8.3 instead would indicate collapse or a pairing bug, for example positives drawn from different participants.

Debugging tips. (1) Evaluate the loss with the positive column shuffled; it should jump to the uninformative value. (2) Check that a participant never appears twice in a batch as an anchor, or else true positives are counted as negatives. (3) For distillation, report retrieval at several gallery sizes rather than one.

Problem. Participant-level positives teach the encoder whatever is constant within a participant over 24 hours. That includes physiology, but also the device model, strap fit and firmware version, because a participant rarely changes devices within a day. When a new device generation arrives, embeddings can shift for reasons unrelated to health.

Why it matters. Probes are trained once on embeddings from the old devices; a shift in the embedding distribution moves scores and breaks calibration for the new device population without any change in the participants.

Worked incident · W1

Symptom. After a new watch generation reaches 18% of active participants, the AFib probe's AUROC on newly adjudicated cases is 0.87 for new-device users and 0.93 for old-device users. Measurements that separate causes. A logistic probe that predicts device generation from the frozen embedding reaches 97% accuracy, so the embedding encodes the device strongly. Signal-quality scores are unchanged, which argues against simple noise. AFib prevalence is similar in both groups, which argues against label shift. Root cause. All W1 positives are within one participant and 24 hours, so device identity is a free feature for the contrastive loss. Remedy. (1) For the roughly 6,000 participants who wore both generations within a month, add cross-device positives (one window from each device). (2) Add device-generation balancing within each batch so device cannot separate negatives. (3) Refit the probe's intercept and calibration per device generation as a stopgap. Cost. A continued-pretraining run on 10% of an epoch, plus a release gate. Validation. The fix is supported if the device-generation probe drops toward the majority-class rate (82%) while the AFib gap closes to within 0.01 AUROC; it is weakened if device accuracy drops but the AFib gap persists, which would point to a genuine signal difference in the new sensor. All numbers are illustrative.

Distillation in deployment. The distilled accelerometer encoder runs where PPG is off. Two diagnostics matter: retrieval accuracy against held-out PPG at a fixed gallery size, tracked per device and activity type, and the gap between probes on student and teacher embeddings for the same targets. A typical remedy when the student underperforms during high motion is to oversample motion-heavy segments in distillation; the cost is a weaker match during rest, so both strata must be reported.

Privacy. Because participant-level contrastive training makes embeddings identify participants, an embedding store is a quasi-identifier. Access control and retention rules should treat embeddings like raw data, and any shared release should test re-identification by nearest-neighbour matching across days.

SignalHealthy range in W1Action on breach
Step-0 InfoNCE8.5 ± 0.1Check normalization and temperature
Converged InfoNCE0.3–0.6Near 8.3: pairing bug or collapse
Device-generation probe accuracyNear majority rateAdd cross-device positives, rebalance
AFib AUROC gap across devices< 0.01Recalibrate per device; block release
Distillation top-1 at fixed galleryStable per activityOversample failing activity strata

The incident ties back to the method: the definition of a positive pair is the specification of what the encoder should ignore. The next section adds a second thing the encoder must ignore, missing data, and shows how masking makes it explicit.

Scaling and missingness

Definition. Wearable data is incomplete by construction: the watch is charged, taken off, put into a power-saving mode, or a derived quantity such as heart-rate variability cannot be computed during motion. Missingness handling is the set of decisions about what a model does with absent values: discard incomplete windows, fill them in (imputation), or represent the absence explicitly. Google's Large Sensor Model (LSM) line studies this together with a second question: how wearable foundation models improve as data, model size and compute grow.

Motivation. Discarding incomplete windows wastes most of the data, since almost no day is complete. Imputing values, for example with the mean or by interpolation, feeds the encoder numbers that were never measured, and the encoder can learn the imputation method's artefacts instead of physiology.

LSM, end to end. Narayanswamy et al. (2024) trained LSM on up to 40 million hours of multimodal data from about 165,000 people wearing Fitbit and Pixel Watch devices (Google Research 2024). The sensors (PPG, accelerometer, skin conductance, skin temperature, altimeter) are summarized as 26 per-minute signals. A training example is a five-hour window, split into patches of 10 minutes by 5 signals; 80% of patches are hidden and a Vision Transformer (ViT) must reconstruct them from the rest. Model sizes ranged from about 2 million to 328 million parameters. The findings:

  • Performance improved with compute, data and model size, with sublinear gains. Gains from more data slowed after roughly 105 hours, and the paper reports saturation near 107 hours for the models studied; larger models needed more data to avoid overfitting and kept improving when data was sufficient.
  • For a fixed total number of hours, spreading them over fewer subjects with more hours each performed similarly to more subjects with fewer hours; the authors suggest scaling both.
  • One model handled imputation, interpolation, forecasting and classification. In 8-class activity recognition with 5 labelled examples per class, the fine-tuned model reached 19.4% accuracy against 10.3% for a supervised baseline; with full labels it reached 68.5% against 53.2%. The paper appeared at ICLR 2025.

LSM-2 and adaptive and inherited masking. LSM-2 makes missingness part of the method (Xu et al. 2025; Google Research 2025). Its training data, about 40 million hours from more than 60,000 participants, contained 1.6 million day-long windows, and not one of them was complete. Adaptive and Inherited Masking (AIM) treats a natural gap (inherited from the data) and an artificial mask (added for training) the same way: both are hidden from the encoder. For efficiency, a fixed number of hidden tokens is removed from the sequence before the encoder; the remaining hidden tokens, natural gaps included, stay in the sequence but are excluded through attention masking, so no other token can read them. The reconstruction loss is computed only on artificially masked tokens, whose true values are known. At fine-tuning and evaluation time no artificial masks are added; only natural gaps are attention-masked. The model therefore never sees an imputed value. LSM-2 beat LSM-1 on hypertension and anxiety and was about level with it on 20-class activity recognition (slightly higher F1, slightly lower AUROC in the paper's table), and degraded less when whole sensors or parts of the day were removed; it continued to improve with more data where LSM-1 appeared to plateau.

Adaptive and inherited masking: natural gaps and artificial masks are both hidden from the encoder.Heart rateHRVStepsAccel. energySkin temp.EDA0:006:0012:0018:0023:00observed: encoder sees itnatural gap: hidden, no lossartificial mask: hidden, lossBoth kinds of hidden token are dropped or attention-masked; the model never sees an imputed value.
Fig. The idea behind adaptive and inherited masking (AIM). A day of wearable data as tokens (channels by hours). Some tokens are missing naturally (charging at 7:00 and 8:00, skin temperature off in the afternoon, EDA off at night, HRV not computable during motion); others are masked on purpose for the reconstruction loss. Both are hidden from the encoder by dropping or attention masking, and the loss is computed only on artificially masked tokens whose true values are known. The gap pattern is invented. (Concept adapted and redrawn from Google Research 2025.)

SensorFM (2026). The same line then scaled the AIM recipe to about 50 times the hours and 80 times the participants of LSM-2. Narayanswamy, Xu et al. (2026) pretrained SensorFM on about 2 billion hours (the paper's abstract also says "more than one trillion minutes", which does not reconcile with 2 billion hours, about 120 billion minutes; the hour figure is the one used in its scaling analysis) from about 5 million Fitbit and Pixel Watch users, using 34 one-minute features from five sensor modalities and models from about 100,000 to 100 million parameters (Google Research 2026). Loss fell predictably over data from about 2 million to 2 billion hours with no sign of saturation reported; the largest model had 31% lower reconstruction error than the smallest. Linear probes on frozen embeddings beat an engineered-feature supervised baseline on 34 of 35 tasks across 13,985 participants in three studies. With 60 contiguous minutes of a day removed, the model retained 99.7% accuracy in predicting daily step counts.

Worked example · W1

In W1, 38% of enrolled hours have no PPG. Under an AIM-style scheme a day of W1 is 8,640 ten-second tokens, of which about 3,283 are natural gaps; half of the 5,357 observed tokens are masked for training. The loss is computed on those 2,678 tokens only, and the natural gaps contribute neither input nor loss.

Compare and contrast. LSM-1 needed complete or imputed inputs; AIM removes that requirement and turns the masking machinery of masked autoencoders into a missing-data mechanism. What it costs: the model still learns from where data is missing only through which tokens are absent, and missingness that depends on health (sleeping without the watch, removing it when unwell) is not corrected by masking. The mental model: hide what is absent, predict only what is known, and evaluate with realistic gap patterns.

Masks. Let a sequence have \(n\) tokens with values \(x_t\). The natural mask \(m^{\text{nat}}_t \in \{0,1\}\) is 1 where the data is missing. The artificial mask \(m^{\text{art}}_t\) is sampled only among observed tokens: \(m^{\text{art}}_t = 1\) for a random fraction \(r\) of tokens with \(m^{\text{nat}}_t = 0\). The hidden set is \(\mathcal{H} = \{t : m^{\text{nat}}_t = 1 \lor m^{\text{art}}_t = 1\}\).

Loss. With reconstructions \(\hat{x}_t\), the training loss is

\[ \mathcal{L} = \frac{1}{\sum_t m^{\text{art}}_t} \sum_{t=1}^{n} m^{\text{art}}_t \, \lVert \hat{x}_t - x_t \rVert^2 . \]

Natural gaps have \(m^{\text{art}}_t = 0\), so they never enter the loss, which is necessary because \(x_t\) is undefined there.

Dropping and attention masking. AIM removes a fixed number \(K\) of hidden tokens before the encoder, leaving \(n - K\) tokens. A fixed \(K\) keeps every sequence in a batch the same length, which simple dropping of all hidden tokens would not, because the number of natural gaps varies by day. The remaining hidden tokens are excluded by setting their attention scores to \(-\infty\): for queries \(q_s\) and keys \(k_t\),

\[ a_{st} = \frac{\exp(q_s^\top k_t/\sqrt{d_k}) \, \mathbb{1}[t \notin \mathcal{H}]}{\sum_{t'} \exp(q_s^\top k_{t'}/\sqrt{d_k}) \, \mathbb{1}[t' \notin \mathcal{H}]} , \]

so the output at every position is a weighted sum over visible tokens only and is invariant to whatever placeholder value sits in a hidden token. Self-attention cost scales with the square of sequence length, so dropping \(K\) tokens reduces it by a factor of about \(((n-K)/n)^2\).

Worked example · W1

A W1 day has \(n = 8{,}640\) tokens. With 38% missing, \(\sum_t m^{\text{nat}}_t = 3{,}283\), leaving 5,357 observed. With \(r = 0.5\), 2,678 observed tokens are artificially masked, so \(|\mathcal{H}| = 5{,}961\). Dropping \(K = 4{,}000\) leaves 4,640 tokens in the encoder, of which 1,961 are attention-masked and 2,679 are visible. Attention cost falls to \((4{,}640/8{,}640)^2 \approx 0.29\) of the full day. \(K\) must not exceed the smallest \(|\mathcal{H}|\) in a batch; with \(r = 0.5\) and no natural gaps, \(|\mathcal{H}| = 4{,}320\), so \(K = 4{,}000\) is feasible on every day.

Token accounting for one W1 day under AIM-style masking.visible 2,679attention-masked 1,961dropped 4,000One day of W1 tokens: 8,640 ten-second windowsobserved in the data: 5,357 (2,678 of them masked on purpose)natural gaps: 3,283Encoder sequence = 4,640 tokens; attention cost about (4,640 / 8,640)² = 0.29 of the full day.Bar order is by role, not by time; the bracket below shows the observed/missing split of the same 8,640 tokens.
Fig. Token accounting for one day of reference workload W1 under the masking scheme computed in the text and code of this section (38% natural missingness, half of the observed tokens masked on purpose, 4,000 hidden tokens dropped). Illustrative numbers.

Why imputation is not neutral. If a fraction \(p\) of values of a signal with variance \(\sigma^2\) is replaced by its mean, the variance of the filled series is \((1-p)\sigma^2\) (ignoring estimation error in the mean). At \(p = 0.38\) the encoder sees 62% of the true variance, and long flat stretches that never occur physiologically. Linear interpolation across an 8-hour charging gap fabricates a smooth trend. Masking avoids both distortions.

Missing not at random. Masking assumes that what is hidden can be ignored. If the probability of a gap depends on the unobserved value, \(P(m^{\text{nat}}_t = 1 \mid x_t) \ne P(m^{\text{nat}}_t = 1)\), the observed data are a biased sample. For example, if participants with poor sleep remove the watch more often at night, nightly averages computed from observed tokens are biased toward good nights. The mask pattern itself is then informative and can be supplied as an input feature, at the cost of the model learning device habits.

The code implements AIM-style mask construction, attention that ignores hidden keys, and a reconstruction loss restricted to artificial masks. It then runs the two tests that define correct missingness handling: outputs must be invariant to values placed in hidden tokens, and the loss must ignore natural gaps. Shapes: masks are (n,) booleans; attention inputs are (n, d).

import numpy as np

def aim_masks(natural, mask_ratio, n_drop, rng):
    """natural: (n,) bool, True where the token is missing in the data.
    Chooses artificial masks among OBSERVED tokens (mask_ratio of them),
    then drops n_drop hidden tokens before the encoder (dropping saves compute).
    Returns (artificial, dropped, attn_masked), each (n,) bool."""
    obs = np.flatnonzero(~natural)
    art_idx = rng.choice(obs, size=int(round(mask_ratio * len(obs))), replace=False)
    artificial = np.zeros_like(natural); artificial[art_idx] = True
    hidden = np.flatnonzero(natural | artificial)
    drop_idx = rng.choice(hidden, size=min(n_drop, len(hidden)), replace=False)
    dropped = np.zeros_like(natural); dropped[drop_idx] = True
    attn_masked = (natural | artificial) & ~dropped      # stay in sequence, masked in attention
    return artificial, dropped, attn_masked

def masked_attention(q, k, v, key_hidden):
    """Single-head attention in which hidden keys get -inf scores, so their
    (possibly garbage) values cannot influence any output. q,k,v: (n, d)."""
    s = q @ k.T / np.sqrt(q.shape[1])
    s[:, key_hidden] = -np.inf
    s -= s.max(axis=1, keepdims=True)
    w = np.exp(s); w /= w.sum(axis=1, keepdims=True)
    return w @ v

def recon_loss(pred, target, artificial):
    """MSE only on artificially masked tokens: their true values are known.
    Natural gaps have no target, so they contribute nothing."""
    return np.mean((pred[artificial] - target[artificial]) ** 2)

rng = np.random.default_rng(1)
n = 8640                                    # one day of 10-s windows
natural = np.zeros(n, bool)
natural[rng.choice(n, size=int(0.38 * n), replace=False)] = True   # 38% missing
art, drop, att = aim_masks(natural, mask_ratio=0.5, n_drop=4000, rng=rng)
kept = n - drop.sum()
print(f"natural={natural.sum()} artificial={art.sum()} dropped={drop.sum()} "
      f"kept={kept} attn-masked={att.sum()} visible={kept - att.sum()}")
assert not (art & natural).any()                      # never mask what is not there
print(f"attention cost vs full sequence: {(kept / n) ** 2:.2f}")

# Invariance test: whatever value sits in a hidden token cannot change outputs.
d = 16
x = rng.standard_normal((32, d)); hid = np.zeros(32, bool); hid[[3, 7, 20]] = True
out1 = masked_attention(x, x, x, hid)
x2 = x.copy(); x2[hid] = 1e6                          # garbage "imputed" values
out2 = masked_attention(x2, x2, x2, hid)
assert np.allclose(out1[~hid], out2[~hid])
print("hidden-token invariance: OK")

# Loss ignores natural gaps
target = rng.standard_normal(n); pred = target.copy(); pred[natural] = 99.0
assert recon_loss(pred, target, art) == 0.0
print("loss ignores natural gaps: OK")

Output:

natural=3283 artificial=2678 dropped=4000 kept=4640 attn-masked=1961 visible=2679
attention cost vs full sequence: 0.29
hidden-token invariance: OK
loss ignores natural gaps: OK

Reading it. aim_masks samples artificial masks only from observed tokens, asserted by the check that artificial and natural masks never overlap. Dropped tokens are chosen among all hidden tokens, natural or artificial. In a full masked autoencoder the decoder later re-inserts placeholder tokens at the dropped positions (with their position encodings) to produce reconstructions; that step is omitted here. The invariance test writes 106 into hidden tokens and verifies that no visible output changes, which is the property that "the model never sees an imputed value" requires.

Worked example · W1

On one simulated W1 day the masks produce 3,283 natural gaps, 2,678 artificial masks, 4,000 dropped tokens, 4,640 tokens in the encoder sequence and 2,679 visible tokens, with attention cost 0.29 of the full sequence.

Debugging tips. (1) Missing values often arrive as NaN; a single NaN in a hidden token still propagates through a matrix multiply before masking, so replace hidden values with zero before the attention product, as the score masking alone does not stop 0 × NaN. (2) Check that a row with every key hidden cannot occur; it produces a division by zero. (3) Log the per-batch minimum of |H| to catch days where K exceeds the number of hidden tokens.

Problem. Masking handles absent values mechanically, but in deployment the gap pattern is not stable. Firmware, charging habits and power-saving defaults change missingness by time of day and by population, and missingness is often related to the health targets themselves.

Root cause. Gaps are not missing at random. Charging is concentrated at night or in the morning; watches are removed during illness, hospital stays or travel. A model trained under one gap pattern and evaluated under another sees a different input distribution even when physiology is unchanged.

Worked incident · W1

Symptom. A probe for nightly resting heart rate built on W1 embeddings degrades from MAE 2.4 bpm to 3.3 bpm in a new month. Measurements. Stratifying errors by the share of the night that is missing shows MAE 2.3 bpm when under 10% of the night is missing and 4.6 bpm when over 50% is missing; the share of nights with more than 50% missing rose from 9% to 31% after a firmware update moved the default charging reminder to 22:00. Error at fixed missingness did not change, which isolates the shift to the gap pattern rather than to the encoder. Remedy. (1) Report every probe metric stratified by missingness bucket on a dashboard. (2) Continue pretraining with artificial masks drawn from the new gap pattern (contiguous evening blocks rather than random tokens). (3) Add the observed fraction of the night as a probe input and abstain when it exceeds 60%. Cost. Abstention lowers coverage; at the new pattern, 18% of nights would receive no estimate. Validation. The fix is supported if MAE in the over-50%-missing bucket falls well below 4.6 bpm on a held-out month; if only the aggregate improves because of abstention, the encoder has not improved. All numbers are illustrative.

Choosing among remedies. Contiguous-block artificial masking matches real gaps better than uniform token masking, at the cost of a harder reconstruction task that can slow convergence. Imputation pipelines remain tempting for downstream consumers who need complete series; if used, they should be evaluated with synthetic gaps placed on fully observed stretches so that the error is measurable.

MetricPurposeAlert rule in W1
Hours with PPG, by hour of dayDetects gap-pattern shiftAny hour moves > 10 points from baseline
Probe error by missingness bucketSeparates encoder regressions from gap shiftsAny bucket worsens > 15%
Abstention rateTracks coverage cost of abstaining> 20% of nights
Synthetic-gap reconstruction errorTests imputation and reconstruction qualityRises > 10% on fixed probe set

At the scale of SensorFM, missingness and scaling interact: more users bring more device types and habits, so the gap distribution widens with the cohort. The open models of the next section face the opposite situation, clinical recordings with few gaps and very different noise.

Open PPG, ECG and EEG models

Definition. An open biosignal foundation model is one whose weights, and usually code, are released, typically trained on public or clinical recordings rather than on a private consumer cohort. Open models matter because most large wearable cohorts cannot release data or weights; without open checkpoints, every group outside those companies starts from scratch, and results cannot be reproduced.

Motivation and predecessors. Public physiological data come mostly from hospitals and research studies: intensive-care monitors (finger PPG, bedside ECG), sleep studies and EEG archives. These recordings are cleaner, shorter per person and collected at higher sampling rates than consumer wearable data. Several groups built foundation models on them, each making a different choice about what counts as "the same" during pretraining.

PPG models.

  • PaPaGei (Pillai et al. 2024) pretrained on about 57,000 hours of PPG, about 20 million segments from 13,517 subjects in the VitalDB, MIMIC-III and MESA datasets, and was evaluated on 20 tasks across 10 datasets. Its morphology-aware variant defines positives by pulse shape rather than by subject: two segments whose pulse waveforms have similar shape descriptors are pulled together even if they come from different people. Code and weights are public.
  • Pulse-PPG (Saha et al. 2025) pretrained only on raw PPG from a 100-day field study of 120 people and found that field pretraining beat a clinically pretrained model on many tasks, a reminder that noise in pretraining data can be a feature when the deployment data is noisy too.
  • SiamQuality (Ding et al. 2024) pretrained a convolutional network on more than 36 million pairs of 30-second ICU PPG signals, pairing a high-quality and a low-quality signal from similar physiological states, so that the representation becomes robust to signal quality.
  • Masked Multiscale Reconstruction (MMR) (Thukral et al. 2026) pretrained a transformer on about 17 million 10-second PPG segments from about 32,000 smartwatch users by masking coefficients of a wavelet decomposition (a representation of the signal at several time and frequency scales) and reconstructing them. It improved on or matched open PPG foundation models, time-series foundation models and other self-supervised baselines on 17 of 19 health tasks.

ECG models. ECG-FM (McKeen et al. 2025, JAMIA Open) is a 90.9-million-parameter transformer in the style of wav2vec 2.0 (Baevski et al. 2020), a speech model that learns by predicting masked stretches of audio. ECG-FM was pretrained on about 1.4 million 12-lead ECG segments with three combined signals: masked span prediction, contrastive learning across adjacent segments of the same recording, and random masking of whole leads. It was evaluated on ECG interpretation and on detecting reduced ejection fraction. A contrasting design is ECGFounder (Li et al. 2025), trained on more than 10 million ECGs from the Harvard-Emory ECG Database with expert annotations covering 150 label categories, so it is supervised rather than self-supervised; it reported AUROC above 0.95 for 80 diagnoses on internal validation and was extended to single-lead ECGs, the format of watches.

EEG models. LaBraM (Jiang et al. 2024, ICLR) pretrained on about 2,500 hours of EEG from about 20 datasets. A vector-quantized tokenizer first maps each channel patch to one of a finite set of learned codes; the encoder then predicts the codes of masked patches. CBraMod (Wang et al. 2025, ICLR) uses a criss-cross transformer that models spatial (across electrodes) and temporal dependencies with separate parallel attention, plus a positional encoding that adapts to different electrode layouts, and was evaluated on up to 10 brain-computer-interface tasks across 12 public datasets.

Open and recent biosignal foundation models grouped by modality, with corpus and the key design choice of each.PPGPaPaGei57k h; positives by pulse shapePulse-PPGfield data, 120 people, 100 daysSiamQuality36M ICU pairs, quality-robustMMR (2026)17M segments; wavelet maskingECGECG-FM1.4M segments; wav2vec 2.0-styleECGFounder10M+ ECGs; 150 expert labelsEEGLaBraM2,500 h; VQ codes, maskedCBraModcriss-cross spatial/temporalCorpora are public or clinical recordings; weights and code are public for most, so they can be fine-tuned on a private cohort.
Fig. The open and recent models discussed in this section, grouped by modality. ECGFounder is trained with expert labels rather than self-supervision and is included as a strong pretrained ECG starting point. MMR is a 2026 PPG model trained on smartwatch data; release status of its weights is not stated in the abstract.
Worked example · W1

Before training W1's encoder from scratch, an open PPG checkpoint can be probed on W1's 5,000 labelled participants as a baseline. Two adaptation steps are needed: W1's 64 Hz windows must be resampled to the checkpoint's expected input rate, and wrist PPG with motion must be compared with the finger PPG from intensive care that dominated the checkpoint's pretraining.

Compare and contrast. Consumer-cohort models win on scale and on matching deployment conditions; open models win on reproducibility and on access. The choice of positives differs sharply: participant identity (section 7.1), pulse shape (PaPaGei), signal-quality pairs (SiamQuality), adjacency in time (ECG-FM), or masked reconstruction in a transformed space (MMR, LaBraM). The mental model: each design states which variation the encoder should ignore, and it transfers best to deployments where that variation is the nuisance.

Corpus arithmetic. Published corpus sizes are easier to compare when converted to common units. With \(H\) hours, \(S\) segments and \(P\) subjects, the mean segment length is \(3600H/S\) seconds and the mean hours per subject is \(H/P\).

Worked example · W1

PaPaGei: \(3600 \cdot 57{,}000 / (2 \times 10^{7}) \approx 10.3\) s per segment and \(57{,}000 / 13{,}517 \approx 4.2\) hours per subject. W1: \(3 \times 10^7 / 150{,}000 = 200\) hours per participant, about 48 times more per person but on 11 times as many people. Resampling a W1 window from 64 Hz to a model that expects \(f'\) Hz changes its length from 640 to \(10 f'\) samples, for example 1,250 samples if \(f' = 125\) Hz (an assumed rate for illustration).

Morphology-aware positives. Let \(\psi(x) \in \mathbb{R}^q\) be a vector of pulse-shape descriptors of a segment (for example, the fraction of a beat spent in the upstroke) and \(b(x) = \text{bucket}(\psi(x))\) a quantization into cells. A pair \((x_i, x_j)\) is positive if \(b(x_i) = b(x_j)\), independent of subject. Compared with subject positives, the invariance changes: subject positives make embeddings constant within a person across states; morphology positives make embeddings constant across people with similar vascular waveform, which suits targets like blood pressure or vascular age that are expressed through shape.

wav2vec 2.0-style objective. A convolutional feature encoder maps the raw signal to latent vectors \(h_t\); a quantizer maps each \(h_t\) to a discrete code vector \(q_t\); a span of \(h_t\) is masked and a transformer produces context vectors \(c_t\). For each masked position the loss is contrastive over a candidate set \(Q_t\) containing the true \(q_t\) and distractors sampled from other masked positions:

\[ \ell_t = -\log \frac{\exp(\text{sim}(c_t, q_t)/\kappa)}{\sum_{\tilde q \in Q_t} \exp(\text{sim}(c_t, \tilde q)/\kappa)} , \]

with cosine similarity and temperature \(\kappa\). ECG-FM adds a segment-level contrastive term in which two adjacent segments of one recording are positives, and random lead masking, which zeros whole leads so the model cannot rely on any single lead.

Vector-quantized masked code prediction. A tokenizer with codebook \(\{e_1, \dots, e_K\}\) assigns patch embedding \(z\) to \(k(z) = \arg\min_k \lVert z - e_k \rVert^2\). The encoder sees patches with some masked and outputs a distribution \(p(k \mid \text{context})\) for each masked patch; training minimizes cross-entropy \(-\log p(k(z_t) \mid \text{context})\). Chance accuracy is \(1/K\): for \(K = 8{,}192\) (an illustrative codebook size) it is about 0.012%. Predicting discrete codes rather than raw values removes high-frequency noise from the target, at the cost of a separate tokenizer-training stage and possible codebook collapse (few codes used).

Criss-cross attention. For \(C\) electrodes and \(T\) time patches, full attention over all \(CT\) tokens costs \(O((CT)^2)\). Attending across electrodes within a time step and across time within an electrode costs \(O(CT(C+T))\). For \(C = 19\) and \(T = 30\) this is \(570 \cdot 49 = 27{,}930\) pair interactions per layer against \(570^2 = 324{,}900\), about 12 times fewer.

The code implements two building blocks that distinguish open models from the participant-contrastive recipe: positives defined by pulse morphology, and vector quantization as used by masked-code objectives. Shapes: a segment is a (640,) array at 64 Hz; features are (n, 2); patch embeddings are (n, d) and the codebook (K, d).

import numpy as np

def pulse_features(seg, fs=64):
    """Crude pulse-shape descriptors for one PPG segment (1-D array).
    Returns (rise_frac, skew): fraction of each beat spent rising, and the
    sample skewness of the waveform. Stand-ins for published morphology indices."""
    seg = np.convolve(seg, np.ones(5) / 5, mode="valid")    # light smoothing
    seg = (seg - seg.mean()) / (seg.std() + 1e-8)
    d = np.diff(seg)
    rise_frac = np.mean(d > 0)
    skew = np.mean(seg ** 3)
    return np.array([rise_frac, skew])

def morphology_buckets(feats, edges_rise, edges_skew):
    """Quantize features into a 2-D grid; segments in the same cell are positives
    regardless of which subject they came from."""
    r = np.digitize(feats[:, 0], edges_rise)
    s = np.digitize(feats[:, 1], edges_skew)
    return r * (len(edges_skew) + 1) + s

def vq_assign(patches, codebook):
    """Vector quantization: map each patch embedding (n, d) to the index of its
    nearest codebook vector (K, d). Masked-code prediction then becomes a
    K-way classification target."""
    d2 = ((patches[:, None, :] - codebook[None, :, :]) ** 2).sum(-1)   # (n, K)
    return d2.argmin(1)

fs, t = 64, np.arange(640) / 64
def beat(t, hr_hz, sharp):        # synthetic pulse train; sharp>1 => fast upstroke
    ph = (t * hr_hz) % 1.0
    return np.where(ph < 1 / sharp, ph * sharp, (1 - ph) / (1 - 1 / sharp))

rng = np.random.default_rng(0)
segs = [beat(t, 1.1, 5) + 0.02 * rng.standard_normal(640),   # subject A, fast rise
        beat(t, 1.3, 5) + 0.02 * rng.standard_normal(640),   # subject B, fast rise
        beat(t, 1.1, 1.6) + 0.02 * rng.standard_normal(640)] # subject A, slow rise
F = np.stack([pulse_features(s) for s in segs])
b = morphology_buckets(F, edges_rise=[0.35, 0.5], edges_skew=[0.5])
print("features:", F.round(3).tolist(), "buckets:", b.tolist())
assert b[0] == b[1] != b[2]       # positives by shape, not by subject

codebook = rng.standard_normal((8192, 64))
idx = rng.integers(0, 8192, size=50)
noisy = codebook[idx] + 0.01 * rng.standard_normal((50, 64))
assert np.array_equal(vq_assign(noisy, codebook), idx)
print("VQ round-trip OK; chance accuracy for masked-code prediction =", 1 / 8192)

Output:

features: [[0.247, -0.008], [0.25, 0.002], [0.602, -0.0]] buckets: [0, 0, 4]
VQ round-trip OK; chance accuracy for masked-code prediction = 0.0001220703125

Reading it. Three synthetic segments are generated: two from different "subjects" (heart rates 66 and 78 bpm) with a fast upstroke, and one from the first subject with a slow upstroke. The rise-fraction descriptor (0.247, 0.250, 0.602) places the first two in the same cell and the third elsewhere, so the positives cross subjects and separate states of one subject, which is the intended invariance. The descriptors here are crude stand-ins; published morphology-aware models use established pulse-wave indices. The vector-quantization test checks that slightly perturbed codebook vectors map back to their own indices.

Worked example · W1

Applied to W1's 640-sample windows, the same bucketing would group windows by waveform shape across the 150,000 participants. Comparing a W1 encoder trained with morphology positives against the participant-positive encoder on the same AFib, age and resting-heart-rate probes is a direct test of which invariance suits each target.

Debugging tips. (1) Plot a histogram of bucket occupancy; if one cell holds most segments, the descriptors or edges need adjusting, or positives become nearly random. (2) For VQ tokenizers, track codebook usage (the share of codes assigned at least once per epoch); a small share indicates collapse. (3) When loading a checkpoint, verify the expected sampling rate, normalization and segment length from its configuration rather than assuming them.

Problem. Adopting an open checkpoint is cheaper than pretraining, but the checkpoint was trained on different sensors, body sites, sampling rates and populations. The risk is a probe that looks reasonable in aggregate and fails in the strata that matter for the product.

Worked incident · W1

Setting. A team evaluates an open PPG checkpoint pretrained mostly on intensive-care finger PPG as a replacement for W1's encoder. Symptom. On W1's 5,000-participant labelled set, its linear AFib probe reaches AUROC 0.84 against 0.93 for W1. Measurements. Stratified by accelerometer activity, the gap is 0.02 at rest and 0.15 during movement; stratified by a signal-quality index, the gap is concentrated in the lowest-quality tercile. Resampling was verified by checking that heart rate estimated from resampled windows matches the original within 0.5 bpm, ruling out a preprocessing error. Root cause. Domain gap: the checkpoint never saw motion-corrupted wrist PPG. Remedy. (1) Continue pretraining the open checkpoint on W1's unlabelled data for a fraction of an epoch, keeping its objective; (2) alternatively, adopt a design whose pretraining used noisy field data (the Pulse-PPG finding) or quality pairs (SiamQuality). Cost. Continued pretraining needs W1's data pipeline and compute, which removes much of the saving of adoption. Validation. The domain-gap explanation is supported if the motion-stratum gap shrinks after continued pretraining while the rest-stratum AUROC stays within 0.01; it is weakened if the gap persists, which would point to architectural limits such as a receptive field too short for motion-robust features. All numbers are illustrative.

Adoption checklist, as ordered steps. (1) Read the license and the data-use terms of the pretraining corpora; clinical datasets often restrict commercial use. (2) Reproduce one published downstream number with the released code before touching private data. (3) Match input conventions (rate, filtering, normalization, segment length) and test them with a physiological invariant such as heart rate. (4) Probe on the private labelled set with participant-level splits, stratified by activity, signal quality, device and demographics. (5) Decide between frozen use, continued pretraining and training from scratch using the stratified gaps, not the aggregate.

CheckPass criterion in W1If it fails
Heart rate after resamplingWithin 0.5 bpm of sourceFix filter or resampling ratio
Reproduced published metricWithin reported intervalConfiguration mismatch; do not proceed
AUROC gap, rest vs motion< 0.03Continued pretraining on field data
Codebook or embedding usageNo collapse on private dataDomain gap; consider retraining tokenizer

Open checkpoints make a field comparable, but each was trained on a cohort with its own population and devices. The last section turns that into a quantitative question: how loss and downstream metrics scale with data, and whose data it is.

Scaling behavior and cohorts

Definition. A scaling law is an empirical regularity relating a model's pretraining loss to the resources spent on it: number of parameters, amount of data and compute. In language modelling, Kaplan et al. (2020) found that loss falls as a power law in each resource when the other two are not bottlenecks, and Hoffmann et al. (2022) derived the compute-optimal balance between parameters and data, which for text came out near 20 tokens per parameter. A cohort is the set of people whose data trained the model; for health models it determines whose physiology the model represents.

Motivation. Scaling laws let a team predict the return of a larger run from small runs instead of paying for it blind. For health data the question is whether the language regularities hold, and what "more data" means when the data are highly repetitive signals from a limited number of people.

What the health evidence shows. Health foundation models do show scaling laws, but with different constants. LSM and LSM-2 report improvement with data, compute and model size (section 7.2). SensorLM (Zhang et al. 2025), a sensor–language model trained on more than 59.7 million hours from 103,643 people with sensor encoders from about 3 million to 1.27 billion parameters, reports the same. SensorFM (2026) reported loss falling predictably from about 2 million to 2 billion hours with no saturation. The largest EHR study, CoMET (Waxler et al. 2025), trained models on 118 million patients and 115 billion medical events and found power laws with exponents close to language, but a compute-optimal ratio of roughly 1,000 tokens per parameter, far more than text.

Why health data differ.

  • Redundancy. Physiological signals are highly autocorrelated, so an hour of PPG carries far fewer independent "effective tokens" than an hour of text. LSM's finding that gains slow after about 105 hours for smaller models is consistent with this.
  • Subjects versus hours. LSM found that, at fixed total hours, fewer subjects with more hours each did about as well as more subjects with fewer hours. For person-level downstream tasks such as disease status, the number of distinct people may matter more. Both axes need to be measured.
  • Token-hungry EHR models. A fitted optimum of about 1,000 tokens per parameter means the best EHR models at a given compute are relatively small and trained on very many events, which suits health systems that have data but limited accelerators.
  • Loss to task. Waxler et al. report that lower pretraining loss predicts downstream performance through a sigmoid-like relationship, so small loss improvements near saturation can still move tasks. In sensor models the link between reconstruction loss and clinical utility is less established; validation should rely on probes, not on loss alone.

Cohorts. Wearable foundation models are only as general as their cohorts, and most are trained on volunteers who own a particular brand of device. Apple's models come from the Apple Heart and Movement Study; Google's from consented Fitbit and Pixel users; the open models from intensive-care and clinical recordings. An open benchmark arrived in 2026: OpenMHC (Schuetz et al. 2026) releases more than 60 million hours from 19 sensor channels with up to 169 linked health, lifestyle, mood and behavior variables for 11,894 participants of the My Heart Counts study, with access for qualified researchers, three benchmark tracks (downstream prediction, imputation and forecasting) and released implementations and weights of recent wearable foundation models.

Wearable pretraining cohorts placed by number of participants and hours per participant.10⁰10¹10²10³10⁴10⁵10³10⁴10⁵10⁶10⁷participants (log scale)hours per participant (log)PaPaGeiOpenMHCSensorLMLSMW1WBM (hourly)SensorFM
Fig. Two axes of scale. Each point is a pretraining corpus placed by participants (horizontal) and hours per participant (vertical); total hours is their product. Values are computed from the published totals cited in this section (PaPaGei 57,000 h from 13,517 subjects; OpenMHC 60M+ h from 11,894; SensorLM 59.7M h from 103,643; LSM 40M h from about 165,000; WBM 2.5B+ hourly records from about 162,000; SensorFM about 2B h from about 5M). Units differ: WBM counts hours of hourly aggregates, the others hours of minute-level or raw signal. W1 is the illustrative reference workload.
Worked example · W1

W1 has 150,000 participants and 200 hours per participant. On the figure it sits next to LSM; SensorFM has about 33 times as many people, and OpenMHC about 25 times as many hours per person. If W1's AFib probe set contains 200 positive participants (an assumed 4% of the 5,000 labelled participants), a 95% interval on its AUROC of 0.93 is about ±0.025, so a scaled-up model must beat 0.93 by more than that margin, or be compared on a paired test, before the gain is credible.

Compare and contrast. In language, more tokens almost always means more diverse content. In wearables, more hours from the same people mostly adds repetition, while more people adds diversity in physiology, devices and behavior. The mental model: scale is two-dimensional, and the clinical metric scales with the dimension the task depends on.

The functional form. With \(N\) parameters and \(D\) training tokens, a common joint form, used by Hoffmann et al. (2022), is

\[ L(N, D) = E + \frac{A}{N^{\alpha}} + \frac{B}{D^{\beta}}, \]

where \(E\) is the irreducible loss (the entropy of the data given perfect modelling) and \(A, B, \alpha, \beta > 0\) are fitted to a sweep of runs. Training compute is approximately \(C \approx 6ND\) floating-point operations (forward and backward passes over \(D\) tokens with \(N\) parameters).

Compute-optimal allocation. Minimizing \(L\) subject to \(6ND = C\): substitute \(D = C/(6N)\), differentiate with respect to \(N\) and set to zero, giving \(\alpha A N^{-\alpha} = \beta B D^{-\beta}\). Solving,

\[ N^* = G\left(\frac{C}{6}\right)^{\frac{\beta}{\alpha+\beta}}, \quad D^* = \frac{C}{6N^*}, \quad G = \left(\frac{\alpha A}{\beta B}\right)^{\frac{1}{\alpha+\beta}} . \]

The exponents say how to grow each resource with compute; when \(\alpha \approx \beta\), both grow as \(C^{1/2}\) and the ratio \(D^*/N^*\) stays roughly fixed. Waxler et al. fitted \(N_{\text{opt}} \propto C^{0.520}\) and \(D_{\text{opt}} \propto C^{0.512}\) for EHR, against about 0.49 and 0.51 for language, so the proportional rule holds but the constant (about 1,000 tokens per parameter) differs.

Worked example · W1

Assume each 10-second W1 window becomes 40 tokens (patches of 16 samples; an illustrative tokenization). One epoch of \(1.08 \times 10^8\) windows is \(4.32 \times 10^9\) tokens, and with \(N = 5 \times 10^7\) the compute is \(C = 6 \cdot 5\times10^7 \cdot 4.32\times10^9 = 1.296 \times 10^{18}\) FLOPs, a ratio of 86 tokens per parameter. Plugging this \(C\) into the text fit of Hoffmann et al. (\(A = 406.4\), \(B = 410.7\), \(\alpha = 0.34\), \(\beta = 0.28\)) gives \(N^* \approx 9.1 \times 10^7\) and \(D^* \approx 2.4 \times 10^9\) (26 tokens per parameter); a 1,000:1 rule gives \(N = \sqrt{C/6000} \approx 1.5 \times 10^7\) and \(D \approx 1.5 \times 10^{10}\). The two answers differ by a factor of six in model size, which is why a sensor-specific sweep is needed before sizing W1; neither fit was estimated on wearable data.

Illustrative power-law loss curves for a small and a large model as data grows.0.300.450.600.750.9010³10⁴10⁵10⁶10⁷pretraining hours (log scale)small modelfloor E (small)large modelfloor E (large)
Fig. Loss \(L(D) = E + B D^{-\beta}\) versus pretraining hours for a small and a large model, with \(B = 3\) and \(\beta = 0.35\) for both and floors \(E = 0.56\) and \(0.40\). All parameters are illustrative, chosen to mimic the qualitative pattern LSM reported: smaller models flatten earlier; larger ones keep benefiting from more data.

Diminishing returns in data. At fixed \(N\), \(L(D) = E' + BD^{-\beta}\) with \(E' = E + A/N^\alpha\). Each tenfold increase in \(D\) multiplies the reducible term by \(10^{-\beta}\). With \(B = 3\) and \(\beta = 0.35\) (the illustrative curves above), going from \(10^5\) to \(10^6\) hours lowers loss by 0.0295 and from \(10^6\) to \(10^7\) by 0.0132, a factor of \(10^{-0.35} = 0.447\). A larger model has a lower floor \(E'\), so it keeps benefiting where the smaller model has flattened.

Redundancy and effective sample size. If consecutive windows have lag-1 correlation \(\rho\) under a first-order autoregressive model, \(n\) windows carry the information of about \(n_{\text{eff}} = n(1-\rho)/(1+\rho)\) independent ones. At \(\rho = 0.9\) (an illustrative value), \(n_{\text{eff}}/n = 0.053\): a 30-million-hour corpus behaves for estimation purposes like about 1.6 million hours of independent windows. Sampling 1% of windows per epoch, as W1 does, exploits this redundancy.

Loss to task and evaluation noise. A sigmoid link \(m(L) = m_0 + (m_1 - m_0)/(1 + e^{k(L - L_0)})\) describes downstream metric \(m\) as a function of loss: flat far above \(L_0\), steep near it, flat again near the ceiling \(m_1\). Whether a change in \(m\) is real depends on evaluation noise. For AUROC \(A\) with \(n_1\) positives and \(n_0\) negatives, the Hanley–McNeil standard error is \(\sqrt{[A(1-A) + (n_1-1)(Q_1 - A^2) + (n_0-1)(Q_2 - A^2)]/(n_1 n_0)}\) with \(Q_1 = A/(2-A)\), \(Q_2 = 2A^2/(1+A)\). With \(A = 0.93\), \(n_1 = 200\), \(n_0 = 4{,}800\) (W1's probe set at an assumed 4% prevalence) the standard error is 0.0126 and the 95% half-width 0.025. Comparisons of two models on the same participants should use a paired test, which is tighter.

The code fits a data-scaling law to a sweep, quantifies diminishing returns, computes a compute-optimal split for W1's budget, and computes the noise floor of the downstream metric. It uses scipy.optimize.curve_fit for nonlinear least squares.

import numpy as np
from scipy.optimize import curve_fit

def loss_data(D, E, B, beta):
    """Data-scaling law at fixed model size: L(D) = E + B * D**(-beta)."""
    return E + B * D ** (-beta)

def compute_optimal(C, A, B, alpha, beta):
    """Minimize L(N, D) = A/N^alpha + B/D^beta subject to C = 6 N D.
    Closed form: N* = G * (C/6)^(beta/(alpha+beta)), D* = (C/6) / N*,
    with G = (alpha*A / (beta*B))^(1/(alpha+beta))."""
    G = (alpha * A / (beta * B)) ** (1 / (alpha + beta))
    N = G * (C / 6) ** (beta / (alpha + beta))
    return N, (C / 6) / N

# 1) Fit a sweep: recover known parameters from noisy points at 10^3..10^7 hours
rng = np.random.default_rng(0)
hours = np.logspace(3, 7, 9)
true = dict(E=0.40, B=3.0, beta=0.35)
obs = loss_data(hours, **true) * (1 + 0.005 * rng.standard_normal(hours.size))
p, cov = curve_fit(loss_data, hours, obs, p0=(0.3, 1.0, 0.3), maxfev=20000)
print("fitted E, B, beta:", p.round(3), "+/-", np.sqrt(np.diag(cov)).round(3))
assert abs(p[2] - 0.35) < 0.05 and abs(p[0] - 0.40) < 0.02

# 2) Marginal value of data: loss gain from 10x more hours shrinks geometrically
for D in (1e5, 1e6):
    print(f"gain from {D:.0e} -> {10*D:.0e} h: {loss_data(D, **true) - loss_data(10*D, **true):.4f}")

# 3) Compute-optimal split at a fixed FLOP budget, using a published text fit
C = 6 * 50e6 * 4.32e9               # W1-sized budget: 50M params x 4.32B tokens
N, D = compute_optimal(C, A=406.4, B=410.7, alpha=0.34, beta=0.28)  # Hoffmann et al. fit
print(f"C={C:.3e} FLOPs -> N*={N:.3e} params, D*={D:.3e} tokens, D*/N*={D/N:.0f}")
assert np.isclose(6 * N * D, C)

# 4) Is a downstream gain larger than its noise? Hanley-McNeil AUROC standard error
def auroc_se(A, n_pos, n_neg):
    q1, q2 = A / (2 - A), 2 * A * A / (1 + A)
    var = (A * (1 - A) + (n_pos - 1) * (q1 - A * A) + (n_neg - 1) * (q2 - A * A)) / (n_pos * n_neg)
    return np.sqrt(var)

se = auroc_se(0.93, n_pos=200, n_neg=4800)       # W1 probe set, 4% AFib prevalence (assumed)
print(f"AUROC 0.93: SE={se:.4f}, 95% CI half-width={1.96*se:.3f}")
assert 0.010 < se < 0.015

# 5) Redundancy: effective sample size of AR(1)-correlated windows
rho = 0.9
print(f"n_eff / n for lag-1 correlation {rho}: {(1 - rho) / (1 + rho):.3f}")

Output:

fitted E, B, beta: [0.401 2.999 0.35 ] +/- [0.002 0.135 0.007]
gain from 1e+05 -> 1e+06 h: 0.0295
gain from 1e+06 -> 1e+07 h: 0.0132
C=1.296e+18 FLOPs -> N*=9.059e+07 params, D*=2.384e+09 tokens, D*/N*=26
AUROC 0.93: SE=0.0126, 95% CI half-width=0.025
n_eff / n for lag-1 correlation 0.9: 0.053

Reading it. The fit recovers \(E = 0.401\), \(B = 3.0\) and \(\beta = 0.35\) from nine noisy points spanning four decades, with \(\beta\) uncertain to about ±0.007; with fewer decades the uncertainty grows quickly, which is why sweeps should span at least two to three orders of magnitude. The allocation function confirms \(6N^*D^* = C\). The AUROC standard error reproduces the ±0.025 interval used in the text, and the effective-sample-size ratio reproduces 0.053.

Worked example · W1

For W1's budget of \(1.296 \times 10^{18}\) FLOPs the text fit suggests about 91 million parameters on 2.4 billion tokens. A W1 sweep would instead train, for example, encoders of 5, 15, 50 and 150 million parameters on 0.1, 0.3, 1 and 3 epochs, fit \(L(N, D)\) to those runs, and record the AFib, age and resting-heart-rate probes at every point.

Debugging tips. (1) Fit in log space or give curve_fit sensible starting values; power laws with free offsets have flat likelihood surfaces. (2) Use held-out loss, not training loss, so overfitting at small data does not masquerade as saturation. (3) Fix the probe set and its splits across the sweep, or differences in evaluation noise will look like scaling effects.

Problem. Scaling decisions are expensive and are usually justified by pretraining loss. Two things can make a larger run disappointing in production: the clinical metric may sit on a flat part of its link to loss, and a larger cohort may add people unlike those in the evaluation set, or fail to add people like those the product will serve.

Worked incident · W1

Setting. W1 is retrained on four times the data (120 million hours from 300,000 participants) with a 150-million-parameter encoder, at about 12 times the compute. Symptom. Held-out reconstruction loss falls by 3%, but AFib AUROC moves from 0.930 to 0.935 and age MAE from 6.1 to 6.0 years. Measurements. The paired bootstrap 95% interval for the AUROC difference is −0.004 to +0.014, so the gain is not distinguishable from zero. Subgroup probes show the largest gains for participants aged 75 and over (AFib AUROC 0.86 to 0.90), a group that is 3% of the original cohort and 7% of the new one. Interpretation. The aggregate metric is near its ceiling for well-represented groups; the value of the new data is concentrated in groups that were scarce. Remedy. (1) Report subgroup metrics as first-class results of the sweep. (2) Plan the next data acquisition by the subgroups with the widest intervals rather than by total hours. (3) Validate on an external cohort with different devices and recruitment, for example OpenMHC, before claiming generality. Cost. Subgroup reporting needs larger labelled sets: halving the interval width for the 75+ group needs about four times as many labelled participants in it. Validation. The cohort explanation is supported if adding older participants without increasing model size reproduces most of the subgroup gain; it is weakened if the gain appears only with the larger model on the original cohort. All numbers are illustrative.

Planning a sweep, as ordered steps. (1) Fix the evaluation: probe tasks, participant-level and temporal splits, subgroup definitions and the minimum detectable difference from the standard-error formula. (2) Run a grid over model size and data on at least three points per axis spanning two decades. (3) Fit \(L(N, D)\) and the loss-to-metric link per task. (4) Extrapolate one step and test the prediction with a single larger run before committing a full budget. (5) Treat cohort composition as a third axis: record participants, hours per participant and subgroup counts for every run.

Quantity tracked per runWhyDecision it informs
Held-out pretraining lossFits \(L(N, D)\)Model size and data for the next run
Probe metrics with paired intervalsSeparates gains from noiseWhether a larger run is worth deploying
Participants and hours per participantTwo axes of data scaleRecruit people or collect longer
Subgroup counts and metricsDetects cohort biasTargeted recruitment, release gates
External-cohort metricsTests generality across devices and recruitmentClaims made in documentation

Scaling ties the chapter together: the definition of positives (7.1) sets what extra data can teach, missingness handling (7.2) sets how much of the data is usable, open models (7.3) set the starting point, and the cohort sets whom the result applies to. The next chapter applies the same questions to sleep, where the labels themselves come from a noisy scoring process.

Sleep Foundation Models

A sleep foundation model is an encoder pretrained without labels on overnight polysomnography (PSG), the clinical sleep study that records brain activity (EEG), eye movements (EOG), muscle tone (EMG), heart rhythm (ECG) and breathing in parallel for a whole night. Once trained, the encoder turns any stretch of a recording into a vector, and small task heads on top of those vectors serve sleep staging, apnea detection and, increasingly, prediction of future disease.

Sleep is a natural domain for this approach. One night yields about eight hours of synchronized brain, heart, muscle and breathing signals; sleep clinics have recorded hundreds of thousands of studies; and the labels that exist (sleep stages and apnea events, scored by technologists) cover only a sliver of what the signals contain. A model that learns from the signals themselves can use all of them.

The chapter follows the field's arc. It starts with manual scoring and the supervised networks that automated it, then examines SleepFM, the multimodal model that moved the question from "what stage is this epoch?" to "what will happen to this person?". It then covers the benchmarks that compared pretraining methods head to head, and ends with the open problem of carrying lab-grade representations to wearables that measure sleep every night with far fewer channels.

From one overnight polysomnogram to many tasks: channel groups are encoded, pooled into embeddings, and reused by staging, apnea, disease-risk and wearable-transfer heads.INPUTPRETRAINED ENCODEREMBEDDINGSUSESOvernight PSGEEG (brain)EOG (eyes)EMG (muscle)ECG (heart)Respiratory~8 h, 30-s epochsEncoderper-group 1D CNNchannel poolingtransformer over5-s tokensself-supervised(no labels)Vectorsper tokenper 30-s epochper nightSleep staging5 classesApnea severityAHI ≥ 15Disease risksurvival headWearable transferdistillationLabels exist for only a few tasks; the encoder learns from the signals themselves and is shared by every head.
Fig. The sleep foundation model pattern. One night of polysomnography is encoded without labels; the resulting vectors serve several downstream heads, including a wearable student. (Schematic.)
Worked example · W3The reference workload for this chapter is W3, a PSG foundation model trained on 30,000 overnight studies (about 240,000 hours) with five channel groups: EEG, EOG, EMG, ECG and respiratory. Scored in 30-second epochs, the corpus holds about 28.8 million epochs. W3 reaches Cohen's κ 0.78 on five-class staging against single-scorer labels (inter-scorer κ is about 0.76), AUROC 0.91 for detecting moderate-to-severe apnea (AHI ≥ 15), and κ 0.62 when transferred to a wearable-only setting. These numbers are illustrative, not published results.

The chapter uses a small, consistent notation. One night is a multichannel signal \(X \in \mathbb{R}^{C \times T}\): \(C\) channels, each sampled for \(T\) time steps at rate \(f_s\). Channels fall into \(K\) modality groups (brain, eyes, muscle, heart, breathing), and the number of channels per group differs between sites. Clinical scoring cuts the night into epochs of \(\Delta = 30\) s, so a night of duration \(D\) seconds has \(n_e = D/\Delta\) epochs, each labelled with one of five stages \(y_t \in \{\mathrm{W}, \mathrm{N1}, \mathrm{N2}, \mathrm{N3}, \mathrm{REM}\}\).

A sleep foundation model is an encoder \(f_\theta\) that maps a window of \(X\) to an embedding \(z \in \mathbb{R}^d\). It is trained with a self-supervised loss that needs no \(y\); downstream, a head \(g_\phi\) maps \(z\) to a task output (a stage distribution, an apnea probability, a hazard for a disease) and is trained on the few labels available, usually with \(\theta\) frozen.

Worked example · W3W3 has 30,000 nights of about 8 h, so \(30{,}000 \times 8 = 240{,}000\) h. With \(\Delta = 30\) s there are \(3600/30 = 120\) epochs per hour, hence \(240{,}000 \times 120 = 28.8\) million epochs. If the encoder tokenizes each modality group into 5-second tokens, one 8-hour night has \(8 \times 3600 / 5 = 5{,}760\) tokens per group and \(5 \times 5{,}760 = 28{,}800\) tokens over \(K = 5\) groups. Stage labels exist for each epoch, but disease outcomes exist once per person, so the label-to-signal ratio for prognosis is one outcome vector per 28,800 tokens.

The arithmetic explains the design pressure in the rest of the chapter: the signal is abundant, labels for anything beyond staging are scarce and noisy, and the encoder must cope with groups whose channel counts vary.

In code, a night is a dictionary from modality group to an array of shape (channels, samples), resampled to one common rate. Scoring epochs are a reshape of that array; tokens for the encoder are a finer reshape of the same buffer. The snippet below fixes the shapes used throughout the chapter and checks the W3 corpus arithmetic. Channel counts per group are an assumed typical montage; real sites differ, which is why later encoders pool over channels instead of fixing their number.

import numpy as np

# W3 corpus arithmetic (illustrative reference workload)
N_NIGHTS, HOURS_PER_NIGHT, EPOCH_S = 30_000, 8, 30
hours = N_NIGHTS * HOURS_PER_NIGHT                 # 240,000 h
epochs = hours * 3600 // EPOCH_S                   # 28.8 M scoring epochs
assert hours == 240_000 and epochs == 28_800_000

# One night as arrays: channel groups -> (channels, samples) at a common rate
FS = 128                                           # Hz after resampling
GROUPS = {"EEG": 6, "EOG": 2, "EMG": 3, "ECG": 1, "RESP": 4}  # channels per group (varies by site)
n_samp = HOURS_PER_NIGHT * 3600 * FS               # 3,686,400 samples per channel
night = {g: np.zeros((c, n_samp), dtype=np.float16) for g, c in GROUPS.items()}

# Re-shape a group into 30-s scoring epochs: (epochs, channels, samples_per_epoch)
def to_epochs(x, fs=FS, epoch_s=EPOCH_S):
    c, t = x.shape
    spe = fs * epoch_s
    n = t // spe
    return x[:, : n * spe].reshape(c, n, spe).transpose(1, 0, 2)

eeg_ep = to_epochs(night["EEG"])
assert eeg_ep.shape == (960, 6, 3840)              # 8 h = 960 epochs of 3,840 samples
bytes_per_night = sum(a.nbytes for a in night.values())
print(f"{hours:,} h, {epochs:,} epochs, {bytes_per_night/1e6:.0f} MB/night at fp16")

Output: 240,000 h, 28,800,000 epochs, 118 MB/night at fp16. The reshape in to_epochs drops a trailing partial epoch; a common bug is to keep it and shift every later label by one epoch relative to the scorer's hypnogram, which silently lowers agreement. Assert the epoch count against the scoring file before training.

At production scale the first problem is not the model but the corpus. PSG files (usually EDF) arrive with site-specific channel names, sampling rates from 100 to 512 Hz, different reference electrodes and filter settings, and scoring files that may follow older or newer rules. A sleep FM is only as consistent as the ingestion layer that maps all of this onto one schema.

Worked example · W3At 128 Hz and 16 channels in fp16, one 8-hour night occupies about 118 MB; 30,000 nights occupy about 3.5 TB before compression. Pretraining that touches every token once per epoch reads the full 3.5 TB per pass, so data loading, not arithmetic, usually sets throughput. Sharding by night (never by epoch) keeps all tokens of a participant in one shard, which later makes patient-level splits trivial.

The chapter's production sections track a small set of service-level indicators. Each is defined where it is used; the table gathers them.

IndicatorWhat it measuresWhere it matters
Per-stage κ by siteAgreement with scorers, one-vs-rest per stageStaging deployment
Channel-group coverageFraction of nights with each group present and in rangePretraining and inference
C-index by time since PSGRanking of disease onset, stratified to expose referral leakageDisease prediction
Paired difference with CIMethod A minus method B on the same patientsBenchmarking
Stage-proportion driftNightly REM, deep and wake fractions per device cohortWearable deployment

Each indicator is chosen because it separates causes: a global κ drop and an N3-only drop have different remedies, and a C-index that holds only in the first month after the study points at labels rather than physiology.

From manual scoring to learned staging

Sleep staging assigns each 30-second epoch of a recording to one stage of sleep. It began as a manual standard. The 1968 Rechtschaffen and Kales manual divided recordings into 30-second epochs scored by eye, and the American Academy of Sleep Medicine (AASM) manual of 2007 revised the stages to Wake, N1, N2, N3 and REM (de Chazal et al. 2022). The stages are defined by patterns a trained technologist recognizes across channels: wake shows alpha rhythm and eye blinks; N1 is the light transition into sleep; N2 carries sleep spindles and K-complexes in the EEG; N3 is dominated by large slow waves; REM combines rapid eye movements in the EOG with low chin muscle tone in the EMG. The output of scoring is a hypnogram, the sequence of stages across the night, from which clinical summaries such as total sleep time and percent REM are computed.

Why the human standard bounds what models can show. Scoring is a judgment, and judgments differ. A meta-analysis cited by de Chazal et al. put inter-scorer agreement (Cohen's κ, a chance-corrected agreement score where 0 is chance and 1 is perfect) at about 0.76 overall: substantial for wake and REM, moderate for N2 and N3, and only fair for N1. Against a panel of six scorers, a single scorer's κ was 0.57. Automated scorers compared with individual scorers reached κ between 0.73 and 0.86 in a 2019 review the same paper summarizes, and performed worst on N1, mirroring humans. When a model's agreement with a scorer reaches the agreement between scorers, the label noise rather than the model becomes the ceiling. De Chazal et al. frame this as a question of whether automated staging has reached a limit set by manual scoring, and separate uncertainty that more data could reduce from uncertainty inherent in the labels.

How deep learning automated the standard. Two models mark the transition:

  • DeepSleepNet (Supratak et al. 2017) learned staging from a single raw EEG channel. Convolutional layers read each epoch's waveform and extract features such as spindle-like or slow-wave patterns; a recurrent layer then reads the sequence of epochs, because stage transitions follow rules (REM rarely follows wake directly in healthy adults, for example) that a single epoch cannot reveal.
  • U-Sleep (Perslev et al. 2021) trained one fully convolutional model across many cohorts and channel configurations, so the same network could score recordings from different clinics with different montages, and it can output stages at a higher frequency than 30 seconds.
Timeline of sleep staging and sleep foundation models, 1968 to 2026, not to scale.1968R&K manual30-s epochs, by eye2007AASM manualW, N1, N2, N3, REM2017DeepSleepNet1 EEG channel2021U-Sleepmany cohorts2024SleepFM (ICML)multimodal SSL2025Sleep Benchmethods compared2026SleepFM (Nat Med)disease riskManual standard → supervised networks → self-supervised encoders reused across tasks
Fig. From a manual scoring standard to self-supervised sleep foundation models. Sources: de Chazal et al. (2022), Supratak et al. (2017), Perslev et al. (2021), Thapa et al. (2024), Kjaer et al. (2025), Thapa et al. (2026).

What changes with a foundation model. DeepSleepNet and U-Sleep are supervised models of one task: the only thing they learn is what predicts the scorer's label. A foundation model is pretrained on the signals themselves, with no labels, and treats staging as one probe among many. The same encoder then serves apnea detection, age estimation and disease prediction. The cost is a large unlabelled corpus and a pretraining run; the benefit is that the representation is not limited to what scorers chose to annotate, and that each new task needs only a small head.

Worked example · W3W3 reaches κ 0.78 on five-class staging against single-scorer labels, with a linear head on frozen embeddings. Inter-scorer κ on comparable data is about 0.76. The comparison says W3 agrees with one scorer about as well as two scorers agree with each other; it does not say W3 is better than a human, because the reference itself is one noisy scorer. Further staging gains would be hard to demonstrate without multi-scorer labels, which is one reason the field turned to tasks whose labels are not scorer judgments, such as later diagnoses.

The mental model for the rest of the chapter: staging is the task that defined the field and the one where models have caught up with the reference, so it now serves mainly as a sanity check for a pretrained encoder, while prognosis is where the signal's unexplored content is tested.

Agreement between two raters (two scorers, or a scorer and a model) on \(n\) epochs is summarized by a \(k \times k\) confusion matrix \(M\), where \(M_{ij}\) counts epochs that rater A labelled \(i\) and rater B labelled \(j\), with \(k = 5\) stages. The observed agreement is the fraction on the diagonal:

\[ p_o = \frac{1}{n}\sum_{i=1}^{k} M_{ii}. \]

Observed agreement is inflated by imbalance: N2 occupies about half of a typical night, so a rater who always says N2 already agrees often. Cohen's κ subtracts the agreement two independent raters with the same marginal frequencies would reach by chance. With row marginals \(a_i = \tfrac{1}{n}\sum_j M_{ij}\) and column marginals \(b_j = \tfrac{1}{n}\sum_i M_{ij}\),

\[ p_e = \sum_{i=1}^{k} a_i\, b_i, \qquad \kappa = \frac{p_o - p_e}{1 - p_e}. \]

κ is 1 for perfect agreement, 0 for chance-level agreement, and negative for systematic disagreement. The denominator \(1-p_e\) is the room above chance; κ is the share of that room the raters actually achieved.

Worked example · W3Assume both raters label the night with marginals W 15%, N1 8%, N2 45%, N3 15%, REM 17%. Then \(p_e = 0.15^2 + 0.08^2 + 0.45^2 + 0.15^2 + 0.17^2 = 0.0225 + 0.0064 + 0.2025 + 0.0225 + 0.0289 = 0.2828\). W3's κ of 0.78 corresponds to \(p_o = 0.842\): \(\kappa = (0.842 - 0.2828)/(1 - 0.2828) = 0.5592/0.7172 = 0.780\). Raw agreement of 84% therefore means about 78% of the achievable above-chance agreement.

Per-stage agreement. Collapsing \(M\) to a \(2\times 2\) table for "stage \(s\)" versus "any other stage" and applying the same formula gives a one-vs-rest κ per stage. Overall κ hides stage-specific failures: because N1 is rare, a model can score N1 at chance and lose little overall κ.

Why a model can exceed inter-scorer κ without being superhuman. Suppose each scorer independently matches a latent true stage with probability \(q\) and otherwise picks one of the other \(k-1\) stages uniformly. Two scorers then agree with probability approximately \(q^2 + (1-q)^2/(k-1)\), while a model that recovered the true stage perfectly agrees with one scorer with probability \(q\). With \(q = 0.9\) and \(k = 5\): scorer–scorer \(p_o \approx 0.81 + 0.0025 = 0.8125\), model–scorer \(p_o = 0.90\). The perfect model "beats" inter-scorer agreement simply because it carries one rater's noise instead of two. The model is idealized (real errors concentrate at adjacent stages), but it shows why κ near or slightly above inter-scorer agreement is the ceiling region, not proof of superiority.

Two hypnograms of the same synthetic night: scorer labels (top) and model output (bottom); shaded bands mark disagreements, most of them at N1 and transitions.ScorerWREMN1N2N3ModelWREMN1N2N30 h1 h2 h3 h4 h5 h6 h7 h8 h
Fig. A hypnogram plots the stage of each epoch through the night. Comparing two hypnograms epoch by epoch gives the confusion matrix from which observed agreement and kappa are computed. (Synthetic night, 10-minute blocks for legibility.)

Uncertainty. Epochs within one night are strongly correlated (a night has long N2 runs), so treating 960 epochs as independent understates the error of κ. The defensible unit is the night or the patient: compute κ per night, or bootstrap whole nights, and report an interval. This matters again in the benchmark section, where differences between methods are often smaller than such intervals.

The core evaluation of any staging model is an epoch-aligned comparison of two integer sequences. The code builds the confusion matrix with np.add.at, computes κ from its marginals, and computes per-stage one-vs-rest κ. Stages are encoded as integers 0–4 in the order W, N1, N2, N3, REM. The first test reproduces the W3 arithmetic; the second simulates a model whose errors fall on adjacent stages, with N1 kept correctly only 45% of the time, to show how per-stage κ exposes what overall κ hides.

import numpy as np

STAGES = ["W", "N1", "N2", "N3", "REM"]

def confusion(a, b, k=5):
    """a, b: int arrays of shape (n_epochs,) with stage ids 0..k-1 -> (k, k) counts."""
    m = np.zeros((k, k), dtype=np.int64)
    np.add.at(m, (a, b), 1)
    return m

def cohen_kappa(m):
    """Cohen's kappa from a (k, k) confusion matrix of counts."""
    m = m.astype(float); n = m.sum()
    p_o = np.trace(m) / n                             # observed agreement
    p_e = (m.sum(1) @ m.sum(0)) / n**2                # chance agreement from marginals
    return (p_o - p_e) / (1 - p_e), p_o, p_e

def per_stage_kappa(m):
    """One-vs-rest kappa for each stage: collapses to a 2x2 table per stage."""
    out = {}
    for s in range(m.shape[0]):
        tp = m[s, s]; fn = m[s].sum() - tp; fp = m[:, s].sum() - tp
        tn = m.sum() - tp - fn - fp
        out[STAGES[s]] = cohen_kappa(np.array([[tp, fn], [fp, tn]]))[0]
    return out

# --- test 1: the W3 worked numbers (marginals 15/8/45/15/17 %, p_o = 0.842) ---
p = np.array([0.15, 0.08, 0.45, 0.15, 0.17])
p_e = float(p @ p)
kappa = (0.842 - p_e) / (1 - p_e)
assert abs(p_e - 0.2828) < 1e-4 and abs(kappa - 0.780) < 1e-3

# --- test 2: synthetic scorer vs model with stage-dependent confusion ---
rng = np.random.default_rng(0)
n = 960                                               # one 8-h night
truth = rng.choice(5, size=n, p=p)
stay = np.array([0.90, 0.45, 0.88, 0.85, 0.88])      # chance a label is kept per stage
pred = truth.copy()
flip = rng.random(n) > stay[truth]
neighbour = {0: 1, 1: 2, 2: 1, 3: 2, 4: 1}           # errors go to adjacent stages
pred[flip] = [neighbour[t] for t in truth[flip]]
m = confusion(truth, pred)
k, po, pe = cohen_kappa(m)
assert abs(cohen_kappa(confusion(truth, truth))[0] - 1.0) < 1e-12   # perfect agreement -> 1
print(f"kappa={k:.3f} p_o={po:.3f} p_e={pe:.3f}")
print({s: round(float(v), 2) for s, v in per_stage_kappa(m).items()})

Output on the synthetic night:

kappa=0.785 p_o=0.846 p_e=0.283
{'W': 0.93, 'N1': 0.3, 'N2': 0.75, 'N3': 0.9, 'REM': 0.96}

Overall κ is 0.785, close to W3's 0.78, while N1 sits at 0.30. The pattern matches the published one: N1 is the weakest stage for humans and machines alike.

Debugging checklist. (1) Unscored or artifact epochs are often coded with a sentinel value; drop them from both sequences before comparing, never only from one. (2) Recordings start before lights-off; trim both sequences to the scored period. (3) A one-epoch shift between signal and labels is a common ingestion bug; it lowers κ by several points and hits N1 and transitions hardest. Compute κ at shifts of −2…+2 epochs: a peak away from zero identifies the bug. (4) Older recordings scored with Rechtschaffen and Kales rules have stages S3 and S4; merge them into N3 before comparing with AASM-scored data.

Problem. A staging model validated at one clinic is deployed across several sites. Overall κ is reported per release, and a release looks fine on average while one site degrades.

Why it matters. Clinical summaries derived from the hypnogram (percent N3, REM latency, sleep efficiency) feed diagnoses. A stage-specific bias distorts exactly these summaries even when overall κ moves by only a few points.

Root causes fall into two families. Signal-side changes alter what the model sees: amplifier firmware, filter settings, electrode type or sampling rate. Label-side changes alter the reference: a new scorer, a change from older to newer rules, or a change in how arousals are handled. The two families need different remedies, so diagnosis has to separate them.

Worked incident · W3W3's staging head runs at three sites. After site C replaces its amplifiers, site C's overall κ falls from 0.77 to 0.70 while sites A and B hold at 0.76–0.78. The per-stage panel shows N3 κ at site C down from 0.73 to 0.51 and N1 from 0.40 to 0.22, with W and REM unchanged. Predicted N3 falls from 16% to 9% of the night at site C, while scorer-labelled N3 is stable at 15% of the night. Spectral power in the 0.5–2 Hz band of the EEG channels drops by about 40% relative to the site's historical median. A signal-side cause is therefore likely: the new amplifiers apply a stronger high-pass filter that attenuates slow waves, so the encoder sees N3 as N2. (All numbers illustrative.)
Sketch of a staging-quality dashboard: per-stage kappa by site for the current release, with the inter-scorer reference band; site C shows an N1 and N3 drop.0.000.250.500.751.000.860.840.83W0.420.400.22N10.760.750.70N20.740.720.51N30.850.830.82REMPer-stage κ by site (A, B, C left to right in each group)Illustrative values. Site C (accent) replaced its amplifiers; N1 and N3 fall while W and REM hold.
Fig. A per-stage, per-site agreement panel separates a stage-specific degradation from a global one. (Illustrative numbers.)

Diagnosis and observability. Three measurements separate the families. (1) Per-stage κ by site isolates which stages moved. (2) The predicted versus scorer-labelled stage proportions show whether the model or the reference shifted: if scorer proportions are stable and predicted ones moved, the signal changed. (3) Signal statistics per channel group (band power, amplitude percentiles, flat-line fraction) against the site's history confirm a hardware change. If instead scorer proportions moved and signal statistics are stable, the label side changed; double-scoring a sample of nights by a second scorer then measures how far the new reference drifted.

Remedy, in order. First, fix the input where possible: restore the filter setting, or record the new filter and apply a matching filter to all training data so the model never relies on frequencies the site no longer passes. Second, if hardware must stay, fine-tune the head (not the encoder) on a small set of site-C nights scored by the site's technologists; with a frozen encoder, a few dozen nights are often enough to recalibrate a linear head. Third, gate the release: hold site C on the previous calibration until per-stage κ recovers.

Cost and trade-offs. Filtering all training data to the narrowest site's band loses information at other sites; per-site heads multiply maintenance and can overfit small samples. Fixing the hardware setting is cheapest when it is possible.

Validation. The hypothesis "the filter removed slow-wave power" predicts that re-filtering site A data with site C's new filter reproduces the N3 drop at site A. If it does, the cause is confirmed; if site A's N3 κ does not move, the cause lies elsewhere (for example a scorer change at site C coinciding with the hardware swap).

IndicatorTarget (illustrative)Alert when
Overall κ per site, releasewithin 0.03 of validationdrop > 0.03 with night-bootstrap CI excluding 0
Per-stage κ (N1, N3) per sitewithin 0.08 of validationdrop > 0.08
Predicted − scored stage %|Δ| < 3 points per stage|Δ| ≥ 3 points for two weeks
EEG 0.5–2 Hz power vs site medianwithin ±20%outside ±20%

The same per-stage, per-site view is the first check on any pretrained encoder in the next section: if a foundation model's staging probe falls short on N3 at one site, the representation inherited a hardware dependency during pretraining.

SleepFM

SleepFM is a multimodal PSG foundation model from Stanford, published in two stages and followed by a larger successor. Its purpose is to learn one representation of a night of sleep from several physiological systems at once, and to reuse that representation for tasks ranging from staging to predicting diseases years later.

Stage one: learning by agreement across modalities. Thapa et al. (2024, ICML) pretrained on more than 100,000 hours of PSG from over 14,000 participants, with separate encoders for brain activity, ECG and respiratory signals. The training signal is contrastive: windows recorded at the same moment by different modalities should map to nearby vectors, and windows from other moments (other rows of the training batch) should map far away. No stage labels are used. Two ways of arranging this agreement were compared:

  • Pairwise contrastive learning pulls every pair of modalities together (brain with heart, brain with breathing, heart with breathing).
  • Leave-one-out contrastive learning pulls each modality towards the average of the other modalities. Each modality must agree with the consensus of the rest, which is more robust when one modality is noisy or missing, because no single partner can dominate. The leave-one-out variant gave significantly better downstream results.

With the encoder frozen, a logistic regression on SleepFM embeddings beat an end-to-end convolutional network on sleep staging (macro AUROC 0.88 vs 0.72; macro AUPRC 0.72 vs 0.48) and on sleep-disordered breathing detection (AUROC 0.85 vs 0.69; AUPRC 0.77 vs 0.61). Cross-modal retrieval, finding the matching clip of another modality, reached 48% top-1 accuracy among 90,000 candidates.

SleepFM architecture: per-modality channel-agnostic encoders, leave-one-out contrastive pretraining and downstream heads. MODALITYCHANNEL ENCODINGTEMPORAL MODELPRETRAINING Brain (BAS)EEG + EOG CardiacECG MuscleEMG Respiratoryairflow · effort · SpO₂ 1D CNN per channelattention pool over channels 1D CNN per channelattention pool over channels 1D CNN per channelattention pool over channels 1D CNN per channelattention pool over channels transformer5-s tokens, 5-min context transformer5-s tokens, 5-min context transformer5-s tokens, 5-min context transformer5-s tokens, 5-min context Leave-one-outcontrastive each modality vs.the mean of the others,other windows asnegatives frozen Sleep tasksstaging · apnea · age (linear or small heads) Disease predictionpooled embeddings → LSTM → multi-label Cox loss
Fig. SleepFM's design. Each modality's channels are encoded by a 1D CNN and pooled with attention, so the model accepts any number and order of channels; a transformer models 5-second tokens over a 5-minute context; leave-one-out contrastive learning aligns modalities. Downstream heads run on frozen embeddings. (Adapted and redrawn from the descriptions in Thapa et al. 2024 and the 2025 preprint of the Nature Medicine paper.)

What each component does. A one-dimensional convolutional network reads each channel's raw waveform and outputs a feature sequence. An attention pooling layer then combines all channels of one modality into one sequence, with learned weights that depend on content; because pooling works on a set, it accepts any number and order of channels, which is what lets one model read montages from different sites. A transformer models 5-second tokens over a 5-minute context, so each token's vector reflects its neighbours. The leave-one-out loss then aligns the modality vectors. Downstream heads run on the frozen vectors.

Stage two: from stages to prognosis. The second paper scaled the model and changed the question to "what will happen to this person?". Published in Nature Medicine in January 2026, it is summarized here from its preprint, Stanford's announcement and press coverage (Thapa et al. 2025 preprint; Stanford Bio-X 2026; News-Medical 2026):

  • Data: about 585,000 hours of PSG from more than 65,000 participants across Stanford Sleep Clinic (35,052 studies; patients aged 2 to 96, recorded 1999–2024), BioSerenity, MESA and MrOS; SHHS (6,441 adults) was held out for transfer evaluation.
  • Architecture: 5-second tokens at 128 Hz, channel-agnostic attention pooling within modalities (brain, ECG, EMG, respiratory), and a transformer over a 5-minute context.
  • Disease prediction: Stanford recordings were linked to electronic health record diagnoses, with follow-up of up to 25 years for some patients, mapped to 1,041 phecodes (disease groupings built from billing codes). A head on frozen embeddings was trained with a multi-label Cox proportional hazards loss, a survival objective that learns which participants are diagnosed earlier while allowing for those whose follow-up ended without a diagnosis. Stanford reported 130 conditions predicted with reasonable accuracy, with C-indices (the probability that, of two participants, the one diagnosed first was ranked higher) such as 0.84 for all-cause mortality and 0.85 for dementia; press coverage lists 0.89 for Parkinson's disease and prostate cancer, 0.87 for breast cancer and 0.81 for heart attack.
  • Against demographics: SleepFM models beat a demographics-only baseline (age, sex, race/ethnicity, BMI) by about 5–17% AUROC depending on disease category, even when the SleepFM head used only age and sex.
  • Which signals matter: according to the press coverage, cardiac signals contributed most to cardiovascular predictions and brain signals to mental-health predictions, and combining all modalities was most accurate.

Caveats. The cohort is a sleep-clinic population, sicker than the general public, and C-index on EHR-derived phecodes inherits coding noise and differential follow-up. A C-index measures ranking, not calibrated absolute risk. The results show that one night of PSG carries prognostic signal beyond demographics; they do not yet show clinical utility.

The successor. A NeurIPS 2026 workshop paper, SleepFM-2 (Thapa et al. 2026), reports pretraining on 235,865 recordings (over two million hours) out of 282,511 nights from 26 cohorts. From one night plus age, sex and BMI it predicts 215 incident phenotypes with C-index at least 0.75 and Bonferroni-corrected P < 0.01 in two held-out cohorts, one unseen in pretraining, and beats both demographics and a baseline of 480 interpretable features from the same recordings. Its frozen encoder transfers to wakeful EEG, headband and in-ear EEG, wrist PPG and wrist accelerometry. These claims come from the abstract of a workshop paper and should be read as preliminary.

Worked example · W3W3 follows the SleepFM recipe at smaller scale: 30,000 nights, five channel groups (EEG and EOG kept separate, plus EMG, ECG and respiratory), leave-one-out contrastive pretraining, frozen embeddings. Its staging probe reaches κ 0.78 and its apnea probe AUROC 0.91 (AHI ≥ 15). Unlike SleepFM's three-group first version, W3 keeps EMG as its own group because REM detection depends on chin muscle tone. (Illustrative.)

Compared with the supervised stagers of the previous section, SleepFM changes what is learned (agreement across body systems rather than a scorer's label) and what is evaluated (future diagnoses rather than present stages). The benchmarks in the next section ask whether that choice of objective, rather than scale or data, explains the gains.

Contrastive loss. Let a batch contain \(B\) time windows. For modality \(m\), the encoder outputs \(z^{(m)}_i \in \mathbb{R}^d\) for window \(i\), normalized to unit length. InfoNCE between a query set \(q\) and a key set \(k\) with matching rows treats the matching key as the correct class among \(B\) candidates:

\[ \mathcal{L}_{\text{NCE}}(q, k) = -\frac{1}{B}\sum_{i=1}^{B} \log \frac{\exp(q_i^\top k_i/\tau)}{\sum_{j=1}^{B}\exp(q_i^\top k_j/\tau)}, \]

where \(\tau\) is a temperature that sets how sharply similarities are compared. If embeddings carry no information, every candidate is equally likely and the loss equals \(\log B\).

Pairwise versus leave-one-out. With \(K\) modalities, the pairwise objective sums \(\mathcal{L}_{\text{NCE}}(z^{(m)}, z^{(m')})\) over all \(K(K-1)/2\) pairs. The leave-one-out objective instead forms, for each \(m\), the mean of the other modalities,

\[ \bar z^{(\setminus m)} = \frac{1}{K-1}\sum_{m' \ne m} z^{(m')}, \qquad \mathcal{L}_{\text{LOO}} = \sum_{m=1}^{K} \mathcal{L}_{\text{NCE}}\big(z^{(m)}, \bar z^{(\setminus m)}\big), \]

with other windows in the batch as negatives. (This is a simplified statement; see the paper for the exact form.)

Terms in the two contrastive objectives for five modality groups: pairwise uses ten pair terms, leave-one-out uses five terms, each comparing one group with the mean of the other four.Pairwise: K(K−1)/2 = 10 termsLeave-one-out: K = 5 termsEEGEOGEMGECGRespEEGEOGEMGECGRespeach group is paired with every other groupEEGmean(EOG, EMG, ECG, Resp)EOGmean(EEG, EMG, ECG, Resp)EMGmean(EEG, EOG, ECG, Resp)ECGmean(EEG, EOG, EMG, Resp)Respmean(EEG, EOG, EMG, ECG)each group agrees with the consensus of the rest
Fig. Pairwise versus leave-one-out contrastive objectives for five modality groups. Shaded cells on the left are the ten pair terms; on the right each group is contrasted with the mean of the other four.

Why the consensus helps. Model each modality's embedding as a shared physiological state plus modality-specific noise, \(z^{(m)} = s + \varepsilon^{(m)}\), with independent noise of variance \(\sigma^2\) per dimension. A single partner carries noise variance \(\sigma^2\); the mean of \(K-1\) partners carries \(\sigma^2/(K-1)\). Each LOO term therefore aligns a modality with a cleaner target, and a corrupted modality contributes only \(1/(K-1)\) of each consensus it enters, instead of being a full partner in \(K-1\) pair terms.

Worked example · W3With \(K = 5\) groups, pairwise uses \(5 \cdot 4/2 = 10\) terms and LOO uses 5. Each consensus averages 4 groups, so its noise variance is \(\sigma^2/4\). With an assumed batch of \(B = 1{,}024\) windows, the chance-level loss is \(\log 1024 = 6.93\) nats; pretraining progress is read as distance below that line.

Survival head. For a single disease, participant \(i\) has follow-up time \(t_i\) (to diagnosis or to the end of records) and event indicator \(\delta_i\) (1 if diagnosed). A head outputs a risk score \(r_i = w^\top z_i\). The Cox partial likelihood asks, at each diagnosis time, how probable it was that this participant, rather than another still at risk, was the one diagnosed:

\[ \mathcal{L}_{\text{Cox}} = -\frac{1}{\sum_i \delta_i}\sum_{i:\,\delta_i=1}\Big( r_i - \log \sum_{j:\, t_j \ge t_i} e^{r_j} \Big). \]

Censored participants (\(\delta_i = 0\)) never appear as events but stay in the risk sets until their follow-up ends, which is how the loss uses incomplete follow-up without discarding it. The multi-label version averages this loss over all \(D\) phecodes with a head that outputs \(D\) risks. Evaluation uses Harrell's C-index: among comparable pairs (one diagnosed at \(t_i\), the other still undiagnosed after \(t_i\)), the fraction in which the earlier case had the higher risk.

Worked example · W3Four participants for one outcome: follow-up 2, 5, 3, 8 years; events 1, 1, 0, 0; risks 1.2, 0.4, 0.9, −0.3. For the case at 5 years the risk set is {5, 8}: \(0.4 - \log(e^{0.4} + e^{-0.3}) = 0.4 - 0.803 = -0.403\). For the case at 2 years the risk set is everyone: \(1.2 - \log(8.012) = 1.2 - 2.081 = -0.881\). The loss is \((0.403 + 0.881)/2 = 0.642\). The comparable pairs are (2 y vs 3, 5, 8 y) and (5 y vs 8 y); all four are ordered correctly, so C = 1.0. Swapping the two cases' risks drops C to 0.5 and raises the loss to 0.941.

The C-index is invariant to any monotone transformation of risk, so it tests ranking only; a model can have a high C-index and badly calibrated absolute risks.

Three pieces of SleepFM can be written in a few lines of NumPy: channel-agnostic attention pooling, the leave-one-out InfoNCE loss, and the Cox head with its C-index. Shapes: embeddings are (K, B, d) for K modality groups, B windows and d dimensions; per-channel features are (C, d) with C varying by site.

import numpy as np

def l2n(x):
    return x / np.linalg.norm(x, axis=-1, keepdims=True)

def info_nce(q, k, tau=0.1):
    """q, k: (B, d) L2-normalised; row i of q matches row i of k. Mean of both directions."""
    s = q @ k.T / tau                                  # (B, B) similarity logits
    def ce(logits):                                    # cross-entropy with targets on the diagonal
        logits = logits - logits.max(1, keepdims=True)
        return -(np.diag(logits) - np.log(np.exp(logits).sum(1))).mean()
    return 0.5 * (ce(s) + ce(s.T))

def loo_loss(z, tau=0.1):
    """z: (K, B, d) embeddings for K modalities. Each modality vs the mean of the others."""
    K = z.shape[0]; total = 0.0
    for m in range(K):
        rest = l2n((z.sum(0) - z[m]) / (K - 1))       # leave-one-out consensus, (B, d)
        total += info_nce(l2n(z[m]), rest, tau)
    return total / K

def pairwise_loss(z, tau=0.1):
    K = z.shape[0]
    terms = [info_nce(l2n(z[i]), l2n(z[j]), tau) for i in range(K) for j in range(i + 1, K)]
    return float(np.mean(terms)), len(terms)

def attn_pool(x, w):
    """Channel-agnostic pooling. x: (C, d) per-channel embeddings, any C; w: (d,) learned query."""
    a = np.exp(x @ w - (x @ w).max()); a /= a.sum()   # (C,) softmax weights over channels
    return a @ x                                       # (d,)

rng = np.random.default_rng(0)
K, B, d = 5, 256, 64                                   # W3: 5 channel groups
shared = rng.normal(size=(B, d))                       # latent "physiological state" per window
z = np.stack([shared + 0.8 * rng.normal(size=(B, d)) for _ in range(K)])
z_noisy = z.copy(); z_noisy[2] = rng.normal(size=(B, d))   # EMG group replaced by noise

chance = np.log(B)
print(f"chance={chance:.2f}  LOO={loo_loss(z):.3f}  pairwise={pairwise_loss(z)[0]:.3f} ({pairwise_loss(z)[1]} terms)")
print(f"noisy EMG: LOO={loo_loss(z_noisy):.3f}  pairwise={pairwise_loss(z_noisy)[0]:.3f}")
assert loo_loss(z) < chance and pairwise_loss(z)[1] == K * (K - 1) // 2

# Permutation invariance of channel pooling: order and count of channels may vary by site
x, w = rng.normal(size=(6, d)), rng.normal(size=d)
assert np.allclose(attn_pool(x, w), attn_pool(x[::-1], w))
assert attn_pool(x[:3], w).shape == (d,)               # fewer channels still gives one vector

Output:

chance=5.55  LOO=0.389  pairwise=0.923 (10 terms)
noisy EMG: LOO=1.692  pairwise=3.039

With five noisy views of a shared state, both losses sit far below the chance line \(\log 256 = 5.55\). Replacing one group with pure noise raises the pairwise loss more, because four of its ten terms involve the broken group at full weight. The absolute values of different objectives are not comparable as quality measures; methods are compared through downstream probes, as in the next section. The permutation test checks the property that lets one model read different montages.

The survival head and its metric:

import numpy as np

def cox_nll(risk, time, event):
    """Breslow-style negative partial log-likelihood for one outcome.
    risk: (N,) linear predictor; time: (N,) follow-up years; event: (N,) 1 = diagnosed, 0 = censored."""
    order = np.argsort(-time)                       # descending time -> risk sets are prefixes
    r, e = risk[order], event[order]
    log_cumsum = np.logaddexp.accumulate(r)         # log sum_{j: t_j >= t_i} exp(r_j)
    return -np.sum((r - log_cumsum)[e == 1]) / max(e.sum(), 1)

def multilabel_cox(risk, time, event):
    """risk, time, event: (N, D) for D outcomes (phecodes). Mean over outcomes with >= 1 event."""
    losses = [cox_nll(risk[:, d], time[:, d], event[:, d])
              for d in range(risk.shape[1]) if event[:, d].sum() > 0]
    return float(np.mean(losses))

def harrell_c(risk, time, event):
    """Fraction of comparable pairs ordered correctly: the earlier event should have higher risk."""
    conc = ties = comp = 0
    for i in np.where(event == 1)[0]:
        later = time > time[i]                     # j still event-free when i was diagnosed
        comp += later.sum()
        conc += (risk[i] > risk[later]).sum()
        ties += (risk[i] == risk[later]).sum()
    return (conc + 0.5 * ties) / comp

# --- worked example: 4 participants, one outcome ---
time  = np.array([2.0, 5.0, 3.0, 8.0])
event = np.array([1,   1,   0,   0  ])
risk  = np.array([1.2, 0.4, 0.9, -0.3])
c = harrell_c(risk, time, event)
assert abs(c - 1.0) < 1e-12                        # every comparable pair ordered correctly
risk_bad = np.array([0.4, 1.2, 0.9, -0.3])         # swap the two cases
print(f"C={c:.2f}  C(swapped)={harrell_c(risk_bad, time, event):.2f}")
print(f"nll(good)={cox_nll(risk, time, event):.3f}  nll(swapped)={cox_nll(risk_bad, time, event):.3f}")
assert cox_nll(risk, time, event) < cox_nll(risk_bad, time, event)

# --- multi-label: D outcomes share one embedding; a linear head gives D risks ---
rng = np.random.default_rng(1)
N, d, D = 500, 32, 3
emb = rng.normal(size=(N, d)); W = rng.normal(size=(d, D)) * 0.3
true_risk = emb @ W
T = rng.exponential(1 / np.exp(true_risk))          # higher risk -> earlier event
C_ = rng.exponential(1.0, size=(N, D))              # censoring times
time_m, event_m = np.minimum(T, C_), (T <= C_).astype(int)
print(f"multilabel nll: oracle={multilabel_cox(true_risk, time_m, event_m):.3f} "
      f"random={multilabel_cox(rng.normal(size=(N, D)), time_m, event_m):.3f}")
print("oracle C per outcome:", [round(float(harrell_c(true_risk[:, k], time_m[:, k], event_m[:, k])), 2) for k in range(D)])

Output:

C=1.00  C(swapped)=0.50
nll(good)=0.642  nll(swapped)=0.941
multilabel nll: oracle=4.814 random=6.023
oracle C per outcome: [0.84, 0.79, 0.82]

The first two lines reproduce the worked example. Sorting by descending time turns each risk set into a prefix, so logaddexp.accumulate computes all log-sums in one pass. Ties in event time are handled approximately (Breslow-style by sort order); with day-level EHR dates and many phecodes, ties are common and the Efron correction is the safer choice. Even the oracle risk gives C around 0.8 here because censoring and exponential event times add irreducible noise, a reminder that C-indices have a ceiling below 1 set by the outcome process.

Two production problems dominate a SleepFM-style system: inputs that are missing or different from pretraining, and disease labels that leak information about the time of the study.

Problem 1: missing channel groups. Home sleep apnea tests record respiratory channels, oximetry and sometimes ECG, but no EEG or chin EMG. An encoder pretrained only on full PSG has never seen a night without brain signals. Root cause: if every pretraining night contained every group, the downstream head can rely on the brain vector, and at inference that vector is replaced by a default. Remedy: drop whole groups at random during pretraining (for example each group with probability 0.2, never all), so the leave-one-out consensus and the pooled night vector learn to work from subsets. Validation: evaluate every probe on held-out nights with each group masked in turn; the drop in apnea AUROC with brain groups masked should be small, because breathing carries the apnea signal. The benchmark work in the next section found existing models handle missing channels poorly, which makes this test necessary rather than optional.

Problem 2: referral leakage in disease labels. Patients are often sent for a sleep study because a clinician already suspects a condition, and diagnoses recorded days after the study may reflect that pre-existing suspicion rather than future disease.

Worked incident · W3W3's survival head reports C-index 0.86 for heart failure on 30,000 linked nights. A histogram of time from PSG to first heart-failure code shows 31% of events within 30 days of the study. Restricting to events more than 90 days after the PSG and excluding participants with any heart-failure code before the study plus 90 days, the C-index falls to 0.78 on 1,140 remaining events, with a night-level bootstrap 95% interval of about ±0.02. The 0.86 figure mixed prognosis with detection of an already-suspected condition. (Illustrative numbers.)

Diagnosis. Plot C-index by time-since-PSG bin (0–30 days, 30 days–1 year, 1–5 years, beyond). A model that learned prognostic physiology should degrade gradually with horizon; a sharp spike in the first bin indicates detection of prevalent disease. Also compare event rates against the clinic's referral reasons where available.

Remedy. Define a washout window: exclude participants with the outcome recorded before PSG date plus \(w\) days, and start the survival clock at PSG plus \(w\). Report results at more than one \(w\) (0, 90, 365 days). Cost: fewer events, wider intervals, and lower headline numbers. Trade-off: a short washout keeps power but mixes detection with prognosis; a long washout isolates prognosis but discards early outcomes that may be clinically useful to detect. Both are legitimate tasks, but they must be reported separately.

Inference throughput. Embedding extraction is a one-time batch job: at 5-second tokens, W3's corpus is about 28.8 million epochs × 6 tokens × 5 groups ≈ 864 million tokens. The disease head then trains in minutes on pooled night vectors. Re-running extraction is the expensive step, so embeddings should be versioned with the encoder checkpoint and the preprocessing configuration.

IndicatorPurposeAlert condition (illustrative)
Group coverage per nightDetect missing EEG, EMG, ECG at ingestionCoverage of any group falls by > 5 points vs. trailing month
Masked-group probe deltasRobustness to missing groupsApnea AUROC drops > 0.03 with brain groups masked
C-index by time since PSGSeparate prognosis from referral detectionFirst-bin C exceeds later bins by > 0.05
Calibration slope per phecode groupAbsolute-risk useSlope outside 0.8–1.2

Both problems connect back to the method: leave-one-out pretraining is meant to make the representation tolerant of a weak or missing modality, and the Cox head's use of censoring is correct only if the time origin and the cohort definition are.

Benchmarks and pretraining comparisons

A pretraining comparison asks which self-supervised objective produces the most useful sleep representation when everything else is held fixed. Before 2025 this question was hard to answer: each sleep model was trained on its own corpus, with its own channels and its own tasks, so a reported gain could come from the objective, the data, the model size or the evaluation. Two efforts in 2025–2026 compared pretraining methods head to head on large PSG corpora.

The protocol. A fair comparison pretrains several encoders that differ only in their objective (contrastive, masked reconstruction, and so on), on the same data, with the same architecture and compute. Each encoder is then frozen, and the same small heads are trained on the same labelled training patients and tested on the same held-out patients. The comparison reports differences with confidence intervals computed over patients, because nights and epochs of one patient are not independent.

A pretraining comparison protocol (top row) and the two large PSG benchmarks that applied it.Pretrainone SSL methodFreezeencoder weightsProbesmall headsTestheld-out patientsComparepaired CIsEverything except the pretraining method is held fixed: data, encoder size, compute, heads, splits.Stanford Sleep Bench (2025)17,467 PSGs, >163,000 h, one clinicstaging, apnea, age+ 13 disease-prediction tasksmethods tie on staging, apnea, agecontrastive best for disease and mortalityand converges fasterSleepBench / OSF (ICML 2026)~166,500 h from nine public sourcesfour families of SSL objectivesexisting models fail on missing channelschannel-invariant features are essentialmore data, capacity and source mixall improve results
Fig. How pretraining methods are compared fairly, and what the two large 2025–2026 PSG benchmarks found. Sources: Kjaer et al. (2025); Shuai et al. (2026).
  • Stanford Sleep Bench (Kjaer et al. 2025) assembled 17,467 recordings (over 163,000 hours) from one large sleep clinic, with 13 disease-prediction tasks plus staging, apnea diagnosis and age estimation. Most self-supervised methods performed similarly on staging, apnea and age; for mortality and disease prediction, contrastive learning did significantly better and converged faster during pretraining. The authors plan to release the dataset, weights, pipelines and evaluation code.
  • OSF (Shuai et al., ICML 2026) built SleepBench, about 166,500 hours from nine public sources, and evaluated four families of pretraining objectives. It found that existing sleep foundation models handle missing channels at inference poorly, that channel-invariant feature learning is essential during pretraining, and that sample size, model capacity and multi-source data mixture all consistently improve results. Code for the resulting open models (OSF) is public; the conference page does not state whether weights are released.

Why the tasks split. Staging, apnea and age are dominated by strong, local patterns (slow waves, airflow pauses, age-related EEG changes) that most objectives capture. Disease prediction depends on subtler, night-level relationships between systems, such as how heart rhythm behaves across sleep stages; contrastive alignment across modalities rewards exactly those relationships, which is a plausible reason it wins there. The benchmarks do not prove this mechanism; they show the pattern.

A related supervised line. Robustness to heterogeneous inputs is also pursued without self-supervision. wav2sleep (Carter and Tarassenko, ML4H symposium, PMLR 2025) trained one staging model jointly on more than 10,000 overnight recordings from six public PSG datasets including SHHS and MESA, accepting any combination of ECG, PPG and respiratory signals at test time, and reported better results than existing models across those input combinations.

Worked example · W3To decide between contrastive and masked pretraining for W3, both encoders are trained on the same 30,000 nights with the same 5 groups, parameter count and number of tokens seen. Heads are trained on the same labelled patients and tested on the same held-out 20% of patients. On apnea (AHI ≥ 15) the two encoders differ by 0.004 AUROC, inside the patient-bootstrap interval; on the disease tasks the contrastive encoder is ahead on most tasks. The decision follows the downstream use: if disease prediction matters, contrastive. (Illustrative, consistent with the published pattern.)

The common thread with the wearable work in the previous chapter (LSM-2's treatment of missing data, Xu et al. 2025): in physiological data, robustness to missing and heterogeneous channels is not a detail but a core design goal. The next section applies the same lesson to the most extreme case, sleep measured with only a wrist device.

The quantity being compared. For pretraining methods \(a\) and \(b\), a downstream metric \(M\) (AUROC, κ, C-index) is computed on the same test patients with the same head. The estimate of interest is the paired difference \(\hat\Delta = M_a - M_b\). Because both metrics are computed on the same patients, their errors are correlated, and the variance of \(\hat\Delta\) is smaller than the sum of the two variances; a paired test is therefore more powerful than comparing two separate intervals.

Resampling unit. The paired bootstrap draws patients with replacement, \(P^{*} \sim \text{Uniform}(P)^{|P|}\), includes all nights of each drawn patient, recomputes \(\hat\Delta^{*}\), and reports the 2.5th and 97.5th percentiles over many draws. Resampling epochs or nights instead of patients treats correlated observations as independent and makes intervals too narrow.

How small a difference can be resolved. The Hanley–McNeil approximation gives the standard error of an AUROC \(A\) estimated from \(n_1\) positives and \(n_2\) negatives:

\[ \mathrm{SE}(A)^2 = \frac{A(1-A) + (n_1 - 1)(Q_1 - A^2) + (n_2 - 1)(Q_2 - A^2)}{n_1 n_2}, \quad Q_1 = \frac{A}{2-A},\; Q_2 = \frac{2A^2}{1+A}. \]
Worked example · W3W3's held-out test set is 20% of 30,000 nights, 6,000 nights; with an assumed 30% prevalence of AHI ≥ 15, \(n_1 = 1{,}800\) and \(n_2 = 4{,}200\). At \(A = 0.91\): \(Q_1 = 0.91/1.09 = 0.835\), \(Q_2 = 2(0.8281)/1.91 = 0.867\). The numerator is \(0.0819 + 1799(0.0068) + 4199(0.0390) \approx 176\), the denominator \(7.56 \times 10^6\), so \(\mathrm{SE} \approx 0.0048\) and a single AUROC has a 95% interval of about ±0.0095. Two methods differing by 0.004 cannot be separated by comparing separate intervals; a paired bootstrap tightens this, but a difference of a few thousandths remains within noise for most test sets of this size. The formula treats nights as independent; with several nights per patient the true interval is wider.

Scaling. OSF reports that sample size, capacity and data mixture all improve downstream performance. A common way to summarize such curves (used here as an assumption, not a published fit) is a saturating power law for downstream error \(E\) as a function of pretraining hours \(N\):

\[ E(N) = c + \alpha N^{-\beta}, \]

where \(c\) is an irreducible floor (for staging, label noise of the kind analysed in the staging section), \(\alpha\) a scale and \(\beta > 0\) the rate. On a log–log plot of \(E - c\) against \(N\) the curve is a line with slope \(-\beta\). The floor matters: for staging against single-scorer labels the floor is near inter-scorer disagreement, so additional data shows diminishing returns; for disease prediction the floor is unknown, which is why scaling studies emphasise those tasks.

Compute matching. A fair comparison fixes the number of tokens processed, \(N_{\text{tok}} = \text{steps} \times B \times L\) for batch size \(B\) and tokens per example \(L\). Methods that mask a fraction \(\rho\) of tokens and encode only the visible ones process \((1-\rho)L\) tokens per example and can afford more steps at equal compute; reporting both equal-steps and equal-compute results prevents a method from winning by budget alone.

A benchmark harness needs three functions: a patient-level split, a frozen-embedding probe, and a paired bootstrap over patients. The test below builds a synthetic cohort of 2,000 patients with one to three nights each, a per-patient AHI ≥ 15 label, and embeddings with a label signal plus a patient-identity component that repeats across a patient's nights (as real embeddings do: anatomy, electrode placement and baseline physiology are stable across nights).

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score

def patient_split(patient_ids, test_frac=0.2, seed=0):
    """Assign whole patients (all their nights) to train or test."""
    rng = np.random.default_rng(seed)
    pats = np.unique(patient_ids)
    test_p = set(rng.choice(pats, size=int(len(pats) * test_frac), replace=False))
    is_test = np.array([p in test_p for p in patient_ids])
    return ~is_test, is_test

def linear_probe_auroc(emb, y, train, test, C=1.0):
    """Frozen embeddings -> logistic regression -> test-set scores and AUROC."""
    clf = LogisticRegression(C=C, max_iter=2000).fit(emb[train], y[train])
    s = clf.predict_proba(emb[test])[:, 1]
    return roc_auc_score(y[test], s), s

def paired_bootstrap(y, s_a, s_b, groups, n_boot=1000, seed=0):
    """Resample patients (not nights) and return the 95% CI of AUROC(a) - AUROC(b)."""
    rng = np.random.default_rng(seed)
    ug = np.unique(groups); idx_by_g = {g: np.where(groups == g)[0] for g in ug}
    diffs = []
    for _ in range(n_boot):
        pick = np.concatenate([idx_by_g[g] for g in rng.choice(ug, size=len(ug))])
        if y[pick].min() == y[pick].max():
            continue
        diffs.append(roc_auc_score(y[pick], s_a[pick]) - roc_auc_score(y[pick], s_b[pick]))
    return np.percentile(diffs, [2.5, 97.5])

# --- synthetic W3-like cohort: 2,000 patients, 1-3 nights each, AHI >= 15 label per patient ---
rng = np.random.default_rng(0)
n_pat = 2000
nights = rng.integers(1, 4, size=n_pat)
pid = np.repeat(np.arange(n_pat), nights)
y_pat = (rng.random(n_pat) < 0.3).astype(int)            # ~30% with AHI >= 15 (assumed)
y = y_pat[pid]
signal = y[:, None] * 0.5 + rng.normal(size=(len(pid), 16))
patient_fx = rng.normal(size=(n_pat, 256))[pid]     # night-invariant identity component
emb_a = np.hstack([signal, patient_fx])                  # "method A" embedding
emb_b = np.hstack([signal[:, :8], patient_fx])  # weaker "method B"

tr, te = patient_split(pid)
assert set(pid[tr]).isdisjoint(set(pid[te]))             # no patient on both sides
auc_a, s_a = linear_probe_auroc(emb_a, y, tr, te)
auc_b, s_b = linear_probe_auroc(emb_b, y, tr, te)
lo, hi = paired_bootstrap(y[te], s_a, s_b, pid[te])
print(f"A={auc_a:.3f} B={auc_b:.3f}  diff 95% CI [{lo:.3f}, {hi:.3f}]")

# Leaky split for contrast: random nights, so a patient's other night sits in train
rng2 = np.random.default_rng(1); te_leak = rng2.random(len(pid)) < 0.2
y_noise = y_pat.copy(); flip = rng.random(n_pat) < 0.25; y_noise[flip] = 1 - y_noise[flip]
yn = y_noise[pid]                                       # labels with patient-level noise
auc_leak, _ = linear_probe_auroc(emb_a, yn, ~te_leak, te_leak, C=100)
auc_clean, _ = linear_probe_auroc(emb_a, yn, tr, te, C=100)
print(f"noisy labels: night-level split {auc_leak:.3f} vs patient-level split {auc_clean:.3f}")

Output:

A=0.900 B=0.815  diff 95% CI [0.063, 0.111]
noisy labels: night-level split 0.718 vs patient-level split 0.605

Method A's probe reaches AUROC 0.90, close to W3's 0.91, and the paired interval for A − B excludes zero, so the difference is resolved. The second line is the leakage check: with 25% of patient labels flipped (the kind of noise a coding error introduces), a flexible probe evaluated on a night-level split scores 0.718 because it memorizes patients whose other nights it saw in training, while the patient-level split gives the honest 0.605. The assert after the split is the cheapest test in the harness and should never be removed.

Debugging tips. If a paired bootstrap returns intervals much narrower than the Hanley–McNeil estimate, check the resampling unit; if a probe's training AUROC is near 1.0 while test is low, reduce probe capacity (regularization C) before blaming the encoder; and record the exact patient IDs in each split so other methods can be evaluated on identical sets.

Problem. Internal comparisons of pretraining methods drive expensive decisions (which objective to scale), yet small reported differences are often produced by confounders rather than by the objective.

Worked incident · W3A report states that masked pretraining beats contrastive pretraining for W3 by 0.021 AUROC on apnea (0.931 vs 0.910). An audit finds four differences besides the objective: the masked run trained for 1.6× more steps; its test split was drawn by night rather than by patient; 12% of its test patients also appeared in the pretraining corpus; and its encoder used respiratory channels sampled at 256 Hz instead of 128 Hz. Re-running both methods with equal tokens processed, the same patient-level split, test patients excluded from pretraining and identical preprocessing, the difference becomes 0.003 with a paired 95% interval of [−0.006, 0.011]. The original claim is not supported. (Illustrative numbers.)

Root causes and their measurements.

ConfounderHow it inflatesMeasurementRemedy
Unequal computeMore updates, better fitTokens processed per runMatch tokens; report equal-steps and equal-compute
Night-level splitProbe memorizes patientsPatient overlap train/test = 0?Split by patient; store IDs
Test patients in pretrainingEncoder has seen test signals (label-free leakage)Overlap of test IDs with pretraining manifestExclude test patients from pretraining
Different preprocessingInformation differs at inputConfig diff across runsOne versioned preprocessing config
Single seedSeed variance read as method effectSpread over 3–5 seedsReport mean and range across seeds

Remedy, step by step. (1) Freeze a benchmark manifest: patient IDs for pretraining, probe-training and test, and a preprocessing configuration hash. (2) Define the compute budget in tokens processed and run every method to the same budget. (3) Train identical heads with the same hyperparameter search budget per method. (4) Evaluate with the paired patient bootstrap and report per-task intervals. (5) Repeat pretraining with at least three seeds for any decision-relevant comparison.

Cost and trade-offs. Seeds multiply pretraining cost; at W3 scale, three seeds of two methods is six pretraining runs. Where this is unaffordable, a cheaper alternative is to compare at a smaller scale with seeds and at full scale with one seed, accepting that the full-scale result is a single draw. Excluding test patients from pretraining shrinks the corpus slightly but makes reported numbers defensible.

Validation. The audit's hypothesis is that the 0.021 gap came from the confounders. It is supported if the gap shrinks towards zero as each confounder is removed one at a time (an ablation ladder), and weakened if the gap persists after all are removed; in that case the objective really is better on apnea, and the finding should be checked across sites. Public benchmarks with released manifests, such as the ones above, make this kind of audit possible across groups as well as within one.

The benchmark lesson about missing channels sets up the last section, where most channels are missing by design.

Sleep without the lab

Sleep without the lab means estimating sleep stages, sleep quality and sleep-related risk from consumer or clinical wearables (a watch, ring, headband or ear device) instead of a full PSG. PSG is expensive and usually done once; wearables measure sleep every night with far fewer channels, typically optical pulse (PPG) and movement (accelerometry), sometimes skin temperature, and in a few devices a single EEG channel. The gap between the two worlds is the subject of this section.

Why wearables lose information. Stages are defined by brain activity, eye movements and muscle tone, none of which a wrist device measures. A watch infers them indirectly: heart rate and its variability change across stages (more regular in deep sleep, more variable in REM), movement stops in sleep, and breathing rhythm can be read from the pulse. These proxies separate wake, light, deep and REM sleep only partially, so wearable staging usually reports three or four classes rather than five, and agreement with PSG is lower.

Current evidence. Several 2025–2026 results show the direction:

  • Behavior models predict sleep metrics well. Apple's wearable behavior model WBM, trained on hourly HealthKit quantities, showed its largest gains over the PPG model on sleep duration, efficiency, deep and REM sleep (Erturk et al. 2025).
  • WatchSleepNet (Wang et al., CHIL 2025) uses inter-beat intervals (IBI), the time between heartbeats, as a representation shared by ECG in PSG and PPG on a watch. It pretrains on large PSG datasets and fine-tunes on wrist PPG, reaching Cohen's κ 0.684 ± 0.051 and REM F1 0.642 ± 0.072 on three-stage staging.
  • SleepFM-2 (Thapa et al. 2026, workshop abstract) reports that a frozen PSG encoder transfers to wrist PPG and accelerometry, headband and in-ear EEG, outperforming end-to-end supervised staging on these sensors across six cohorts, and performing comparably to accelerometry-pretrained models for disease prediction in UK Biobank.
  • Language models now sit on top of wearable sleep data to coach users: PH-LLM, discussed in the multimodal chapter, scored 79% on sleep-medicine multiple-choice exams and predicted self-reported sleep quality from encoded wearable data (Cosentino et al. 2025).

The bridge: cross-modal distillation. The open problem is linking the two worlds: distilling PSG-trained representations into wearable encoders, as Apple did from PPG to accelerometry (Abbaspourazad et al. 2024). Distillation trains a student model to reproduce the output of a frozen teacher. Here the teacher is a PSG encoder; the student reads watch signals. On nights recorded with both systems at once, the student is trained so that its vector for each epoch matches the teacher's vector for the same epoch. No stage labels are needed, so every paired night is useful. Afterwards the student runs alone on nightly wearable data and inherits whatever the teacher's representation captured that the watch signals can still predict. Its limitation is structural: the student cannot recover information the watch does not sense, so the teacher bounds the student from above and the sensor bounds it from below.

Distilling a PSG teacher into a wearable student: on nights recorded with both systems, the student learns to reproduce the frozen teacher embedding; afterwards it runs alone on nightly wearable data.TRAINING (nights with PSG and watch)DEPLOYMENT (every night)PSG nightlab, 5 groupsPSG encoderfrozen teacherWatch signalsPPG + accelWrist encoderstudent, trainedMatch loss1 − cosinegradients flow tothe student onlyWatch signalshome, nightlyWrist encodercopied from trainingStages, trends, riskAlignment of the two clocks to within one epoch is a precondition for this loss to mean anything.
Fig. Cross-modal distillation from PSG to a wearable. The same pattern Apple used from PPG to accelerometry (Abbaspourazad et al. 2024) applies with a PSG teacher. (Schematic.)
Worked example · W3W3's PSG encoder serves as teacher. A wrist student trained on paired nights reaches κ 0.62 on staging when evaluated against the PSG scorer's labels, compared with W3's 0.78 on full PSG. The 0.16 gap is the cost of losing EEG, EOG and EMG; it is largest for N1 and for separating N3 from N2. (Illustrative.)

Compared with lab staging, the wearable setting trades depth for frequency: one excellent night versus hundreds of approximate ones. For tracking change within one person, nightly approximate measurements can be more informative than a single precise one, which is why the lab-to-wearable bridge is one of the field's most important open problems.

Distillation objective. Let \(x^{\text{psg}}_t\) and \(x^{\text{w}}_t\) be the PSG and wearable signals for epoch \(t\) of a paired night, \(f\) the frozen teacher and \(g_\psi\) the student. The cosine distillation loss is

\[ \mathcal{L}_{\text{dist}}(\psi) = \frac{1}{n}\sum_{t=1}^{n}\Big(1 - \frac{g_\psi(x^{\text{w}}_t)^\top f(x^{\text{psg}}_t)}{\lVert g_\psi(x^{\text{w}}_t)\rVert\, \lVert f(x^{\text{psg}}_t)\rVert}\Big), \]

which is 0 when the two vectors point the same way and about 1 for unrelated vectors in high dimension. Where some paired nights carry stage labels \(y_t\), a combined loss \(\mathcal{L} = \lambda \mathcal{L}_{\text{dist}} + (1-\lambda)\,\mathcal{L}_{\text{CE}}(h(g_\psi(x^{\text{w}}_t)), y_t)\) with \(\lambda \in [0, 1]\) mixes representation matching with direct supervision. A contrastive variant replaces the cosine term with InfoNCE, using the teacher vectors of other epochs as negatives.

Clock alignment. The loss compares epoch \(t\) in both systems, so their clocks must agree. With heart-rate series \(h^{\text{psg}}\) and \(h^{\text{w}}\) sampled once per epoch, the offset is estimated as the lag that maximizes their correlation:

\[ \hat\ell = \arg\max_{|\ell| \le L} \operatorname{corr}\big(h^{\text{psg}}_t,\; h^{\text{w}}_{t+\ell}\big). \]

A misalignment of \(\ell\) epochs makes the student learn to predict the teacher's representation of a different moment, which blurs transitions.

Why κ across class granularities is not comparable. Wearable staging is often reported with three classes (wake, NREM, REM). Chance agreement depends on the class marginals, so the same raw agreement gives very different κ.

Worked example · W3With five-class marginals W 15%, N1 8%, N2 45%, N3 15%, REM 17%, chance agreement is \(p_e = 0.2828\). Collapsing N1–N3 into NREM gives marginals 15%, 68%, 17% and \(p_e = 0.0225 + 0.4624 + 0.0289 = 0.5138\). A three-class raw agreement of \(p_o = 0.85\) yields \(\kappa = (0.85 - 0.5138)/(1 - 0.5138) = 0.691\), while the same \(p_o\) in five classes would yield \(\kappa = (0.85 - 0.2828)/0.7172 = 0.791\). W3's wearable κ of 0.62 is reported on five classes; it should not be compared with a three-class κ such as WatchSleepNet's 0.684 without converting both to the same label set.

An upper bound in words. If the wearable signal \(x^{\text{w}}\) is a noisy function of the PSG signal, then by the data-processing inequality the mutual information between stages and \(x^{\text{w}}\) cannot exceed that between stages and \(x^{\text{psg}}\). Distillation can approach the information the wearable carries; it cannot exceed it. The practical consequence is to measure the student's ceiling per stage, not only overall.

The snippet implements the three pieces a wearable distillation pipeline needs before any deep model: clock alignment by cross-correlation, the cosine distillation loss, and mapping five-class labels to the coarser sets used for wearables. The student here is a ridge regression from watch features to teacher vectors, which is enough to test the loss and the data flow; in practice it is a neural encoder trained by gradient descent on the same loss. Shapes: per-epoch series of length n = 960 (one night), embeddings (n, d).

import numpy as np

def best_lag(ref, x, max_lag):
    """Lag (in samples) that maximises correlation of x shifted against ref; both 1-D, same rate."""
    ref = (ref - ref.mean()) / ref.std(); x = (x - x.mean()) / x.std()
    lags = range(-max_lag, max_lag + 1)
    corr = [np.mean(ref[max_lag:-max_lag] * np.roll(x, -L)[max_lag:-max_lag]) for L in lags]
    return list(lags)[int(np.argmax(corr))], max(corr)

def distill_loss(student, teacher):
    """1 - cosine similarity, averaged over epochs. student, teacher: (n_epochs, d)."""
    s = student / np.linalg.norm(student, axis=1, keepdims=True)
    t = teacher / np.linalg.norm(teacher, axis=1, keepdims=True)
    return float(1 - (s * t).sum(1).mean())

FIVE_TO_THREE = np.array([0, 1, 1, 1, 2])   # W->wake, N1/N2/N3->NREM, REM->REM
FIVE_TO_FOUR = np.array([0, 1, 1, 2, 3])    # W, light (N1+N2), deep (N3), REM

# --- 1. align watch heart rate (1 sample per 30-s epoch) to PSG ECG heart rate ---
rng = np.random.default_rng(0)
n = 960                                             # one 8-h night of epochs
hr_psg = 60 + np.cumsum(rng.normal(0, 0.8, n))      # slowly drifting nocturnal HR
true_offset = 7                                     # watch clock is 7 epochs (3.5 min) late
hr_watch = np.roll(hr_psg, true_offset) + rng.normal(0, 1.5, n)
lag, r = best_lag(hr_psg, hr_watch, max_lag=20)
assert lag == true_offset
print(f"estimated lag={lag} epochs ({lag*30/60:.1f} min), r={r:.2f}")

# --- 2. distillation target: frozen PSG teacher embeddings for the same epochs ---
d = 64
teacher = rng.normal(size=(n, d))                   # PSG encoder output (frozen)
watch_feats = teacher[:, :24] + 0.7 * rng.normal(size=(n, 24))   # watch sees part of the state
X = np.hstack([watch_feats, np.ones((n, 1))])
W = np.linalg.solve(X.T @ X + 1.0 * np.eye(X.shape[1]), X.T @ teacher)   # ridge "student"
print(f"distill loss: untrained={distill_loss(rng.normal(size=(n, d)), teacher):.3f} "
      f"student={distill_loss(X @ W, teacher):.3f}")
assert distill_loss(X @ W, teacher) < distill_loss(rng.normal(size=(n, d)), teacher)

# --- 3. evaluate at the resolution the sensor supports ---
stages5 = rng.choice(5, size=n, p=[0.15, 0.08, 0.45, 0.15, 0.17])
print("3-class counts:", np.bincount(FIVE_TO_THREE[stages5], minlength=3).tolist())

Output:

estimated lag=7 epochs (3.5 min), r=0.90
distill loss: untrained=0.999 student=0.481
3-class counts: [142, 644, 174]

Cross-correlation recovers the injected 7-epoch offset exactly. The untrained student scores about 1.0 (unrelated vectors); the ridge student reaches 0.48, not 0, because the simulated watch sees only part of the teacher's state, which is the information gap described above. The max_lag bound should cover the largest plausible clock drift; if the correlation peak is flat (r below about 0.5), the night is unreliable for distillation and should be excluded rather than aligned at a guessed lag.

Debugging tips. Align on heart rate, not on movement, because movement is near zero for long stretches of sleep and gives flat correlations. Recompute the lag per night, since device clocks drift. When evaluating, map both prediction and reference to the same label set with the same mapping array.

Problem. A wearable sleep model runs on every night of every user, without any reference labels in production. Quality can drift silently through device, firmware or population changes.

Why it matters. Users and clinicians track trends (REM fraction falling, sleep efficiency improving). A device-induced shift looks like a physiological change.

Worked incident · W3W3's wrist student runs on a fleet of watches. After a firmware update, the population median REM fraction rises from 21% to 27% within days, on the updated devices only; users on the previous firmware stay at 21%. The per-night IBI quality score (fraction of beats passing plausibility checks) falls from 0.93 to 0.81 on updated devices. A paired validation sample of 64 nights with simultaneous PSG, collected after the update, gives five-class κ 0.55 (95% interval about ±0.03), down from 0.62. The likely cause: the firmware changed PPG processing so that beat detection fails more often in deep sleep, and the irregular IBI series looks like REM to the student. (Illustrative numbers.)

Diagnosis and observability. With no labels, monitoring relies on distributions and on a small labelled stream. (1) Stage-proportion drift per device cohort (model, firmware, wear location) catches shifts quickly; stratifying by firmware is what separated cause from coincidence in the incident. (2) Signal-quality metrics (IBI plausibility, motion artifact rate, wear time) explain why a cohort shifted. (3) A periodic paired-PSG sample gives an unbiased κ estimate. The sample size follows from the night-level spread: with an assumed between-night standard deviation of κ of 0.12, \(n = 64\) nights gives a standard error of \(0.12/\sqrt{64} = 0.015\) and a 95% interval of about ±0.03, enough to detect a 0.07 drop.

Remedy, step by step. (1) Contain: route updated-firmware nights to a quality gate that withholds stage output when the IBI quality score is below a threshold and reports duration and wake only. (2) Fix the input: if the firmware change is reversible or configurable, restore the previous beat-detection behaviour. (3) Adapt: otherwise, collect paired nights on the new firmware and re-distill the student, or fine-tune its stage head, so it learns the new signal statistics. (4) Release with a cohort-level gate: per-firmware REM fraction must return within 2 points of the reference cohort, and paired κ within 0.03 of 0.62.

Cost and trade-offs. The quality gate reduces coverage (fewer nights with stage output) to protect accuracy; paired PSG nights are expensive, so the validation stream is small and slow; re-distillation costs a pretraining-scale data collection only if the shift is large. A cheaper intermediate is to fine-tune only the head on a few dozen paired nights.

Validation. The hypothesis "beat detection fails in deep sleep" predicts that IBI quality loss concentrates in epochs the PSG scorer labelled N3, and that REM over-prediction occurs mainly in those epochs. If quality loss is uniform across stages, the cause is more likely a general change (for example a sampling-rate change) and the remedy should target preprocessing instead.

IndicatorWindowAlert (illustrative)
Median REM, deep, wake fraction per device cohortDailyShift > 2 points vs. reference cohort
IBI quality score per cohortDailyMedian falls > 0.05
Nights with stage output (coverage)WeeklyFalls > 5 points
Paired-PSG κ (5-class)Per validation batch of 64 nightsBelow 0.59 (0.62 − 0.03)

The incident closes the loop with the rest of the chapter: the same per-stage view used for lab staging, the same robustness to degraded channels that the benchmarks identified, and the same insistence on paired, patient-level evaluation apply when the lab is taken away.

EHR Foundation Models

An EHR foundation model is a model pretrained on the coded event histories in electronic health records (diagnoses, medications, procedures, laboratory results, visits) so that one network can serve many downstream questions: risk prediction, phenotyping, cohort discovery and operational forecasting. Before such models, each question was answered by its own pipeline: an analyst chose a cohort, counted codes over a look-back window, and trained a logistic regression or gradient-boosted tree on a few thousand labelled patients. That approach works, but every task repeats the feature engineering and every task with few labels performs poorly.

The core analogy is a decade old: a patient timeline can be read like a sentence of medical codes. What has changed is the objective the model is trained on and the scale of data. Four objectives organize the field and this chapter: masked prediction of hidden codes and next-code prediction (both covered in the next section), generative simulation of future timelines, and time-to-event pretraining that learns when each code next occurs. The last section covers how these models are compared, which for many years was the weakest part of the field.

From a coded patient timeline to tokens, four pretraining objectives, and the downstream uses they share.RECORDTOKENSPRETRAINING OBJECTIVEUSESPatient timelinediagnosesmedicationsprocedureslabs with valuesvisitsirregular timesToken sequencecode tokenstime-gap tokensvalue tokensage / visitembeddingsMasked codesBEHRT, Med-BERT, CEHR-BERTNext codeDoctor AI, CLMBRGenerative simulationForesight, ETHOS, Delphi, CoMETTime to eventMOTORShared modelrisk predictionphenotypingcohort discoveryoperationssynthetic dataOne pretrained encoder or generator serves many tasks; only the objective differs.
Fig. An EHR foundation model reads a patient's coded timeline as a token sequence and is pretrained with one of four objectives; the resulting model serves many downstream uses. Model names indicate representative examples of each objective.

Three properties make EHR sequences unlike text and unlike the regularly sampled signals of earlier chapters: time between events is irregular and informative; the record reflects how a hospital documents care as much as the patient's biology; and patients leave observation (move, change insurer, reach the end of the data) before outcomes can be seen. Each section returns to these properties.

Worked example · W2The reference workload for this chapter is W2, a decoder-only EHR model of 120 million parameters trained on 2 million patients and 310 million events. Its vocabulary holds 42,000 codes, 64 time-gap tokens and 10 value-decile tokens; the median patient has 96 events and the 95th percentile 1,450; the context window is 4,096 tokens. Evaluation uses patient-level splits plus a temporal holdout (train up to 2022, test 2024), with 1-year mortality AUROC 0.89, 30-day readmission AUROC 0.71 and calibration error 0.03. All W2 figures are illustrative.

An EHR foundation model treats patient \(i\) as a token sequence \(x^{(i)} = (x_1, \dots, x_{L_i})\) drawn from a vocabulary \(V\), produced by a tokenizer from timed events \((t_k, c_k, v_k)\): a time, a code and an optional value. Every objective in this chapter is a likelihood over that sequence or over functions of it. The autoregressive factorization

\[ \log p_\theta(x) = \sum_{n=1}^{L} \log p_\theta(x_n \mid x_{<n}) \]

underlies next-code and generative models; masked models replace the left context \(x_{<n}\) with all unmasked tokens; time-to-event models replace the categorical next-token distribution with a hazard \(\lambda_c(u \mid x_{\le n})\) for each code \(c\), the instantaneous rate at which code \(c\) occurs at time \(u\) after position \(n\).

A useful first calculation is the token budget, because it determines context length and compute. If a fraction \(f_v\) of events carries a numeric value (one extra decile token each) and \(G\) gap tokens are inserted (one each time the clock advances, so fewer than events when several events share an encounter), a patient with \(E\) events has about \(E(1 + f_v) + G\) tokens.

Worked example · W2Assume \(f_v = 0.35\), 12 gap tokens for the median patient and 120 for the 95th-percentile patient (heavy users have many events per encounter, so gaps grow more slowly than events), and on average one gap token per eight events across the corpus. The median patient has \(96 + 34 + 12 = 142\) tokens, the 95th percentile \(1{,}450 + 508 + 120 = 2{,}078\), half the 4,096 context. The whole corpus is about \(310 \times 10^6 \times (1 + 0.35 + 0.125) \approx 0.46\) billion tokens. A uniform guess over \(|V| \approx 42{,}074\) entries (42,000 codes, 64 gap tokens and 10 decile tokens; the handful of special tokens such as [BOS] and [MASK] does not change the figures) has cross-entropy \(\ln 42{,}074 \approx 10.65\) nats per token, the ceiling every objective must beat.

The sections derive the masked and next-code losses, the Monte Carlo estimator behind generative prediction, the censored survival likelihood behind time-to-event pretraining, and the metrics (AUROC, calibration error, C-index) used to compare them.

Every EHR foundation model starts from the same data structure: a per-patient list of timed events, converted to integer token ids. The code below is the W2 tokenizer in miniature. Events that share a timestamp (one encounter) are emitted without a gap token; when time advances, one of 64 log-spaced gap tokens is inserted; a numeric lab emits its code followed by a decile token whose nine cut points were fitted on training patients only. The script ends with the corpus budget that the rest of the chapter reuses.

"""W2: turn one patient's coded events into tokens and check the corpus budget.
Event = (time_hours, code, value or None). Output = list of token strings."""
import math, bisect

H20Y = 20 * 365.25 * 24                     # 20 years in hours

def gap_bin(hours: float) -> int:
    """64 log-spaced gap bins: 0 (<1 h), 1..62 (1 h..20 y), 63 (>= 20 y)."""
    if hours < 1:
        return 0
    if hours >= H20Y:
        return 63
    return 1 + min(61, int(62 * math.log(hours) / math.log(H20Y)))

def decile(value: float, edges: list) -> int:
    """edges = 9 cut points fitted on TRAINING patients for this lab -> 0..9."""
    return bisect.bisect_right(edges, value)

def tokenize(events, lab_edges):
    toks, last_t = ["[BOS]"], None
    for t, code, val in sorted(events, key=lambda e: e[0]):
        if last_t is not None and t > last_t:           # time advanced: one gap token
            toks.append(f"[GAP{gap_bin(t - last_t)}]")
        toks.append(code)
        if val is not None:                              # numeric lab: code + decile
            toks.append(f"Q{decile(val, lab_edges[code])}")
        last_t = t
    return toks

if __name__ == "__main__":
    hba1c_edges = [5.2, 5.4, 5.6, 5.8, 6.0, 6.4, 6.9, 7.6, 8.6]   # illustrative
    events = [(0.0, "DX:E11.9", None), (0.0, "LAB:HbA1c", 8.4),
              (0.0, "RX:metformin", None), (24 * 91, "LAB:HbA1c", 7.1)]
    toks = tokenize(events, {"LAB:HbA1c": hba1c_edges})
    print(toks)
    assert toks == ["[BOS]", "DX:E11.9", "LAB:HbA1c", "Q8", "RX:metformin",
                    f"[GAP{gap_bin(24*91)}]", "LAB:HbA1c", "Q7"]
    assert gap_bin(0.5) == 0 and gap_bin(1e9) == 63 and 1 <= gap_bin(24 * 91) <= 62

    # Corpus budget (assumptions: 35% of events carry a value; on average 1 gap
    # token per 8 events; 12 gaps for the median patient, 120 for the p95 patient)
    events_total, value_frac, gap_per_event = 310e6, 0.35, 12 / 96
    tokens_total = events_total * (1 + value_frac + gap_per_event)
    median = 96 + (96 * 35 + 50) // 100 + 12        # 142
    p95 = 1450 + (1450 * 35 + 50) // 100 + 120      # 2,078
    print(f"corpus tokens ~ {tokens_total/1e9:.2f} B; median {median}; p95 {p95}")
    assert median == 142 and p95 == 2078 and p95 < 4096
    V = 42_000 + 64 + 10           # codes, gaps, deciles: ~42,074 (specials add a handful)
    print("vocab", V, "embedding params at d=768:", V * 768)

Output: the four events become eight tokens, ['[BOS]', 'DX:E11.9', 'LAB:HbA1c', 'Q8', 'RX:metformin', '[GAP40]', 'LAB:HbA1c', 'Q7']; the corpus is about 0.46 billion tokens; the median patient is 142 tokens and the 95th percentile 2,078; the embedding table of about 42,074 entries holds about 32.3 million parameters at an assumed width of 768. Two bugs are common at this stage: sorting events without a stable tie-break (so codes within an encounter shuffle between runs) and fitting decile edges on all patients, which leaks test-set distributions into training. Tokenizer design is treated in depth in Clinical events: codes, time and values.

In production, an EHR foundation model is a data system before it is a model. The record arrives through an extract-transform-load (ETL) pipeline from the hospital's database or a common data model such as OMOP; it is converted to a flat event table, tokenized, and fed to pretraining, then to task heads or simulation services. Most failures that reach clinicians originate upstream of the network: a code system changes version, a lab is renamed, an extract silently drops a table, or a prediction time is computed from a timestamp that was recorded after the fact.

Worked example · W2Compute is modest by language-model standards. With the usual estimate of \(6ND\) floating-point operations for \(N\) parameters and \(D\) tokens, one pass over W2's 0.46 billion tokens costs about \(6 \times 1.2\times10^{8} \times 4.6\times10^{8} \approx 3.3\times10^{17}\) FLOPs, well under an hour per epoch on one modern accelerator at realistic utilization. The binding constraint is data: CoMET's scaling study put the compute-optimal ratio near 1,000 tokens per parameter, which for 120 million parameters would be 120 billion tokens, about 260 times W2's corpus. W2 is therefore data-limited and is trained for many epochs, which makes overfitting to one institution's coding habits the main risk.

The table lists the artefacts that must be versioned together; a mismatch between any two produces silent degradation rather than an error.

ArtefactChanges whenFailure if mismatched
Event extract (ETL version, source tables)Source system upgrade, new feedMissing event types; shifted event rates
Tokenizer (vocabulary, gap bins, decile edges)Refit on new dataCodes map to the wrong ids or to unknown
CheckpointRetrainingEmbedding rows no longer match tokenizer ids
Task definitions (prediction time, horizon, exclusions)Clinical requirementsLabel leakage or non-comparable results
Calibration map per task and sitePopulation or practice driftCorrect ranking, wrong absolute risk

The sections that follow treat each objective's own production problems: vocabulary and coding drift for sequence models, inference cost and learned artefacts for generative simulation, censoring and time origin for time-to-event models, and leakage and transportability in benchmarks.

Sequence and masked models over codes

The first EHR foundation models adapted sequence models from language: read a patient's codes in order, and learn by predicting codes that are hidden or that come next. No outcome labels are needed; the record supervises itself. Two families emerged, distinguished by which codes the model may see when it predicts.

The starting point: next-visit prediction. Choi et al. (2015) introduced Doctor AI, a recurrent neural network (RNN) that reads a patient's visits one at a time and, after each, predicts the diagnosis and medication codes of the next visit together with the time until it. An RNN keeps a running state vector that it updates at every visit, so the state summarizes the history so far. The framing, the EHR as a sequence of timed code sets to be forecast, set the agenda: learn from the sequence itself rather than from hand-built features. Two of its problems persist: the model learns an institution's coding habits along with its medicine, and sparse, irregular visits make "next" a poorly defined target, since the next visit may be tomorrow or in three years.

Masked models. When BERT appeared in language, EHR researchers adapted it within months. A masked model hides a fraction of codes (typically about 15%) and trains a transformer to recover them from all remaining codes, before and after. Because each position can attend in both directions, the output vector at each position summarizes the whole record. Inputs are not just codes: each position's vector is the sum of several learned embeddings, for the code, the patient's age at the event, the position in the sequence, and the visit (segment) it belongs to.

  • Li et al. (2019) trained BEHRT on records of nearly 1.6 million people with code, age, position and visit-segment embeddings. On onset prediction for 301 conditions it improved average precision by 8.0–10.8 points over earlier deep EHR models.
  • Rasmy et al. (2020) pretrained Med-BERT on structured diagnosis data from 28,490,650 patients. Fine-tuned for heart failure in diabetic patients and for pancreatic cancer, it raised AUC by 2.02–7.12%; with only 300–500 training samples it raised AUC by more than 20%, matching a model trained on a set about ten times larger.
  • Pang et al. (2021) trained CEHR-BERT on 2.4 million patients from Columbia's OMOP data, inserting artificial time tokens between visits (week, month and long-term gap tokens) and adding a visit-type prediction objective alongside masking. Time thereby becomes something the model reads directly rather than infers from positions.
Masked-code pretraining predicts hidden codes from both sides; next-code pretraining predicts each following token from the past only.Masked(BERT-style)DX:E11[MASK]predict RX:metforminLAB:HbA1cQ8[MASK]predict DX:I10RX:statinEach hidden code is predicted from codes on both sides of it.Next code(GPT-style)DX:E11RX:metforminRX:metforminLAB:HbA1cLAB:HbA1cQ8Q8[3 mo][3 mo]DX:I10DX:I10(next?)Every position predicts the token after it, seeing only earlier tokens.
Fig. The two classic objectives on the same kind of sequence. Masked pretraining hides codes and predicts them from context on both sides; next-code pretraining predicts each following token from the past. Tokens are invented for illustration.

Next-code (autoregressive) models. Steinberg et al. (2020) argued that the plain language-modelling objective, predict each code from the codes before it, is an effective representation learner, and named the model CLMBR. The output at the last position before a prediction time summarizes everything known up to then and cannot see the future, which matches how a clinical prediction is made. Across five prediction tasks, CLMBR representations improved AUROC by 3.5% on average over standard baselines, and by 19% when few training records were available. Its transformer successor, CLMBR-T-base (141 million parameters, pretrained on 2.57 million Stanford patients), became the reference model released with the EHRSHOT benchmark covered at the end of this chapter.

Worked example · W2For a median W2 patient of 142 tokens, a masked objective hides about 21 tokens per pass and learns from those 21; a next-code objective learns from all 141 next-token predictions. Per token processed, the autoregressive objective extracts more training signal, which matters for a data-limited corpus of 0.46 billion tokens. W2's decoder-only design follows the CLMBR line and also allows the generation used in the next section.

Comparison. Masked models see both sides of every position and give strong whole-record summaries, but a summary computed at a prediction time must be built only from earlier events, which requires care. Next-code models are causal by construction and also generate, at the cost of seeing only one side during training. In both, the recurring empirical pattern is the one Med-BERT showed: pretraining helps most when labelled data is scarce, and the advantage narrows as task labels grow. The mental model: pretraining converts abundant unlabelled records into a starting representation, so that each task needs fewer labels to reach the same accuracy.

Let a patient be a token sequence \(x = (x_1, \dots, x_L)\) with \(x_n \in V\). A transformer with parameters \(\theta\) maps the sequence to hidden vectors \(h_n \in \mathbb{R}^d\), and a softmax over the vocabulary turns each into a distribution \(p_\theta(\cdot \mid \text{context})\).

Input embedding. In BEHRT-style models each position's input is a sum of embeddings,

\[ e_n = E_{\text{code}}[x_n] + E_{\text{age}}[a_n] + E_{\text{pos}}[n] + E_{\text{seg}}[s_n], \]

where \(a_n\) is the patient's age (in years or finer bins) at event \(n\), \(s_n\) alternates between visits, and each \(E\) is a learned table with \(d\) columns. Summation lets the model attend to codes while still knowing when they happened. CEHR-BERT instead inserts gap tokens, so time is part of \(x\) itself.

Masked objective. Choose a random set \(M\) of positions (rate \(\rho\), typically 0.15); replace most of them with a [MASK] token to form \(\tilde x\), and minimize

\[ \mathcal{L}_{\text{MLM}}(\theta) = -\frac{1}{|M|}\sum_{n \in M} \log p_\theta(x_n \mid \tilde x). \]

The common recipe replaces 80% of selected positions with [MASK], 10% with a random token and leaves 10% unchanged, so the model cannot learn that only [MASK] positions matter.

Next-code objective. With causal attention, position \(n\) sees only \(x_{\le n}\) and predicts \(x_{n+1}\):

\[ \mathcal{L}_{\text{AR}}(\theta) = -\frac{1}{L-1}\sum_{n=1}^{L-1} \log p_\theta(x_{n+1} \mid x_{\le n}). \]

Its exponential, \(\exp(\mathcal{L}_{\text{AR}})\), is the perplexity: the effective number of equally likely next tokens. Doctor AI's original target was a set: the multi-hot vector \(y_{t+1} \in \{0,1\}^{|C|}\) of codes in the next visit, trained with a sum of per-code binary cross-entropies, plus a regression loss on the log time to that visit.

Worked example · W2With \(|V| \approx 42{,}074\), an untrained model has loss \(\ln 42{,}074 = 10.65\) nats (perplexity about 42,074). For the median patient (\(L = 142\)) with \(\rho = 0.15\), \(\mathbb{E}|M| = 21.3\) predictions per pass, against \(L - 1 = 141\) for the next-code loss, a factor of about 6.6 more supervised positions per forward pass. If a trained model reached, say, 3.0 nats per token, perplexity would be \(e^{3.0} \approx 20\): on average the next token is as uncertain as a choice among 20 codes, typical of diagnoses within a visit whose order is arbitrary.

Why pretraining helps with few labels. A downstream head fitted on a frozen representation \(h \in \mathbb{R}^d\) has \(d + 1\) parameters per task (logistic regression), against tens of thousands for a model fitted on raw code counts. Its estimation error scales roughly with the number of free parameters divided by the number of labels, so a representation that already separates relevant patients reduces the labels needed. This is the mechanism behind Med-BERT's 300–500-sample result and CLMBR's 19% low-label gain; once labels are plentiful, a count-based model can estimate the same signal directly and the advantage narrows.

Trade-off. The masked objective conditions on future events within the record, so an embedding computed over a whole record must be truncated at the prediction time before use; the causal objective respects time by construction but discards right context. Codes within one visit have no meaningful order, so both objectives spend some capacity predicting arbitrary orderings; gap tokens and visit segments reduce but do not remove this.

The two objectives differ only in which positions are labelled and what the model may attend to. The code builds both label sets from the same id matrix, computes the masked-position cross-entropy shared by both, and assembles BEHRT's summed input embedding. Ids 0–3 are reserved for special tokens ([PAD], [BOS], [EOS], [MASK]) and never masked. Shapes are stated in the docstring; the loss uses natural logarithms, so values are in nats.

"""Masked-code (BERT-style) and next-code (CLMBR/GPT-style) objectives on token ids.
Shapes: ids [B, L] int; logits [B, L, V] float; labels [B, L] int, -100 = ignored."""
import numpy as np

IGNORE, MASK_ID = -100, 3            # ids 0..3 reserved for special tokens

def mask_for_mlm(ids, V, rate=0.15, rng=None):
    """Select `rate` of non-special positions; of those 80% -> [MASK], 10% random, 10% kept."""
    rng = rng or np.random.default_rng(0)
    ids = ids.copy(); labels = np.full_like(ids, IGNORE)
    pick = (rng.random(ids.shape) < rate) & (ids > 3)
    labels[pick] = ids[pick]
    r = rng.random(ids.shape)
    ids[pick & (r < 0.8)] = MASK_ID
    rand = pick & (r >= 0.8) & (r < 0.9)
    ids[rand] = rng.integers(4, V, size=rand.sum())
    return ids, labels

def next_code_targets(ids):
    """Autoregressive: position t predicts token t+1; the last position predicts nothing."""
    labels = np.full_like(ids, IGNORE)
    labels[:, :-1] = ids[:, 1:]
    return labels

def cross_entropy(logits, labels):
    """Mean negative log-likelihood over positions whose label != IGNORE (natural log)."""
    m = labels != IGNORE
    z = logits[m] - logits[m].max(-1, keepdims=True)            # [N, V] stable
    logp = z - np.log(np.exp(z).sum(-1, keepdims=True))
    return float(-logp[np.arange(m.sum()), labels[m]].mean())

def behrt_input(code_emb, age_emb, pos_emb, seg_emb, codes, ages, pos, seg):
    """BEHRT-style input: the four embeddings are summed per position -> [B, L, d]."""
    return code_emb[codes] + age_emb[ages] + pos_emb[pos] + seg_emb[seg]

if __name__ == "__main__":
    rng = np.random.default_rng(1)
    V, B, L, d = 42_074, 64, 142, 16           # W2 vocab, median patient length
    ids = rng.integers(4, V, size=(B, L))
    x, y = mask_for_mlm(ids, V, rng=rng)
    frac = (y != IGNORE).mean()
    print(f"masked fraction {frac:.3f}; masked per median patient ~{0.15*L:.1f}")
    assert abs(frac - 0.15) < 0.01
    assert abs((x[y != IGNORE] == MASK_ID).mean() - 0.8) < 0.03
    # Uniform predictions give loss log V for both objectives
    uni = np.zeros((2, 8, 50))
    lab = next_code_targets(rng.integers(4, 50, size=(2, 8)))
    assert abs(cross_entropy(uni, lab) - np.log(50)) < 1e-9
    print(f"log V for W2 = {np.log(V):.2f} nats")
    # A confident correct model approaches zero loss
    toks = rng.integers(4, 50, size=(1, 8)); lab = next_code_targets(toks)
    good = np.full((1, 8, 50), -10.0); good[0, np.arange(7), toks[0, 1:]] = 10.0
    assert cross_entropy(good, lab) < 1e-6
    # BEHRT input shape
    E = lambda n: rng.normal(size=(n, d))
    h = behrt_input(E(V), E(120), E(512), E(2), ids[:, :10], np.full((B, 10), 67),
                    np.tile(np.arange(10), (B, 1)), np.zeros((B, 10), int))
    assert h.shape == (B, 10, d)
    print("ok")

Output: masked fraction 0.151; masked per median patient ~21.3, log V for W2 = 10.65 nats, ok. The tests check four properties: the selected fraction is close to 0.15, about 80% of selected positions become [MASK], a uniform model scores exactly \(\ln V\), and a confident correct model scores near zero. The attention mask is not shown: in a masked model every position attends to every non-padding position; in a next-code model position \(n\) attends to positions \(\le n\) (a lower-triangular mask).

Debugging. A next-code loss that drops far below what the data could support usually means the causal mask is missing, so position \(n\) sees \(x_{n+1}\). A masked loss stuck at \(\ln V\) usually means labels are misaligned with inputs after padding. A loss that falls quickly and then plateaus high often reflects many identical within-visit codes in arbitrary order; computing loss separately on gap tokens, diagnosis codes and value tokens shows which part of the vocabulary is hard. For deployment, store the representation at the last token before each prediction time and check with a unit test that no token after that time contributed to it.

Sequence models over codes inherit every change in how a health system codes care. Three production problems recur.

Problem 1: code-system drift. When coding practice changes, the same clinical state is written with different tokens. The United States moved from ICD-9-CM to ICD-10-CM diagnosis codes in October 2015; local formularies, lab names and order sets change continually. Why it matters: embeddings for new codes are untrained, and old codes disappear from recent data, so a model's view of recent patients degrades exactly where it is used. Diagnosis: track the share of tokens per month that are unknown or were rare in pretraining (fewer than 100 training occurrences) and the next-code loss per month on held-out patients; a step change aligned with a known coding event identifies the cause. Remedy: map codes to a stable ontology level (for example, three-character ICD-10 categories or RxNorm ingredients) before tokenization, keep a cross-walk for retired codes, and retrain or continue pretraining once enough new data exists. Cost: coarser codes lose specificity, such as laterality or severity.

Problem 2: transfer to another site. A model pretrained at one institution meets another institution's vocabulary and practice patterns. Guo et al. (2024) evaluated CLMBR-T-base (141M parameters, 2.57 million Stanford patients) at SickKids (Toronto) and on MIMIC-IV across eight tasks: off the shelf it matched gradient-boosted models trained on all local data and gave a 13% AUROC gain when labels were scarce; continued pretraining on local data improved performance by about 3% on average, reached the fully trained baseline with 128 labelled examples (64 per class), and was 60–90% more sample-efficient than training a local foundation model from scratch.

Worked incident · W2W2 is deployed to a second hospital. On the first month of the new site's data, 19% of code tokens map to [UNK] (local lab codes not in W2's vocabulary) and 30-day readmission AUROC falls from 0.71 to 0.64 on 3,000 recent discharges. Per-token-type loss shows that diagnosis tokens are near their source-site level while lab tokens are not, which points at vocabulary rather than population. Mapping local lab codes to LOINC codes already in the vocabulary reduces [UNK] to 4%; continued pretraining for one epoch on 200,000 local patients follows. AUROC recovers to 0.70 with a patient-bootstrap 95% interval of about ±0.02. (Illustrative numbers.)

Validation. The mapping hypothesis is supported if AUROC rises in proportion to the reduction in [UNK] across tasks that depend on labs, and unchanged on tasks that depend only on diagnoses. It is weakened if AUROC stays low after mapping; then practice differences (different admission thresholds, different follow-up) are the more likely cause, and local continued pretraining or local recalibration is needed.

Problem 3: copy-forward repetition. Problem lists and medication lists are often re-documented at every encounter. Repeated codes are easy to predict, so they lower the training loss without teaching anything, and they consume context. Wornow et al. (2025) identified copy-forwarded repetition as one of three properties that make EHR sequences hard to model. Diagnosis: the fraction of tokens identical to a token in the previous encounter, and the loss on first occurrences versus repeats. Remedy: deduplicate within a window or down-weight repeats in the loss; NYU's 2025 model added a regularizer that down-weights repeated tokens to favour new onsets (Rajamohan et al. 2025). Trade-off: repetition also carries information (a condition still active), so removal should be validated on tasks that depend on chronic status.

IndicatorDetectsAlert condition (illustrative)
[UNK] and rare-token share per monthCode drift, new site vocabulary> 2 points above the training-period level
Next-code loss by token type and monthWhich part of the record changedAny type up > 0.2 nats against trailing quarter
Repeat-token fractionCopy-forward documentation changesChange > 5 points after an EHR upgrade
Task AUROC on a recent rolling cohortNet effect on usersLower bound of 95% interval below release value

These problems tie back to the objective: a sequence model learns the distribution of tokens it is shown, so any change in how care is written is, to the model, a change in medicine. The generative models of the next section make this explicit, because they sample that distribution directly.

Generative EHR models

A generative EHR model is an autoregressive model of future clinical events that answers questions by simulation. Given a patient's history up to today, it samples the next token, appends it, samples again, and continues until a time horizon is reached, producing one plausible future timeline. Repeating this many times gives a set of futures; the predicted risk of an outcome is the fraction of simulated futures in which that outcome occurs before the horizon. One pretrained model thereby becomes a zero-shot predictor for any outcome expressible in its vocabulary, with no labelled data and no task-specific head.

Why this was new. The masked and next-code models of the previous section produce representations; each task still needs labels and a fitted head. Next-code models were already capable of generation, but early work used them only as encoders. Generative EHR models take the remaining step: if the model has learned the distribution of what happens next, including when, then sampling it estimates outcome probabilities directly. This requires that time be represented in the sequence (as gap tokens, or as a predicted time to the next event), because "within one year" can be checked only if the simulated timeline carries a clock.

Zero-shot prediction by simulating many future patient timelines and counting outcomes. Patient history tokens up to today Generative event model n sampled futures (horizon: 1 year) LAB:BNP·Q9 [3 wk] RX:diuretic HF admit [2 mo] VISIT:clinic [6 mo] no event RX:diuretic [5 mo] HF admit [1 mo] VISIT:clinic [11 mo] end of horizon no event p̂(HF admission within 1 yr) = 2 / 4 in practice n ≈ 16–64+, any outcome in the vocabulary no task-specific training needed
Fig. Prediction by simulation. A generative event model samples many futures for one patient; the predicted risk of an outcome is the fraction of simulated timelines in which it occurs before the horizon. CoMET reported performance largely plateauing around 64 simulations. Tokens are invented for illustration.

The models, in order.

  • Kraljevic et al. (2022) built Foresight, a GPT over clinical concepts extracted from free text by named-entity recognition and linking, on 811,336 patients from King's College Hospital, South London and Maudsley, and MIMIC-III. Precision@10 for the next disorder was 0.68, 0.76 and 0.88 across the three sites (0.80–0.91 for any next biomedical concept), and five clinicians judged the top forecast relevant in 97% of 34 synthetic timelines. It was later published in The Lancet Digital Health (2024).
  • Pang et al. (2024) extended CEHR-BERT's time tokens to a GPT, CEHR-GPT, that generates synthetic patient timelines while preserving visit timing.
  • Renc et al. (2024) proposed ETHOS, a transformer over tokenized Patient Health Timelines in which time gaps and values are tokens, which predicts future trajectories zero-shot, without labelled data or fine-tuning (npj Digital Medicine, 2024).
  • Shmatko et al. (2025) trained Delphi-2M, a modified GPT of about 2.2 million parameters, on about 0.4 million UK Biobank participants to predict rates of 1,256 ICD-10 diseases (at three-character level) from a person's history (Nature, 2025). Two changes adapt GPT to health histories: age is encoded continuously in place of token positions, and an extra output head predicts the time to the next event. Average AUC was about 0.76, falling to about 0.70 for predictions ten years ahead; unchanged validation on about 1.9 million Danish individuals gave about 0.67 (News-Medical 2025). Accuracy was comparable to single-disease models, and the model samples synthetic health trajectories up to about 20 years ahead.
  • Waxler et al. (2025) trained CoMET (models named Curiosity, 62 million to 1 billion parameters), decoder-only transformers on Epic Cosmos: 118 million patients, about 115 billion events and 151 billion tokens, with an 8,192-token context and a vocabulary of 7,105 tokens defined in advance. Across 78 tasks (diagnosis, prognosis, operations) the largest model generally matched or beat task-specific supervised models zero-shot by Monte Carlo simulation; for 30-day readmission it reached AUROC 0.770 against 0.717 for the best supervised model, while on incident-disease tasks it led on precision-recall AUC but less often on AUROC. Loss followed power laws in model size and data, with a compute-optimal ratio near 1,000 tokens per parameter, and accuracy largely plateaued at around 64 simulations per patient.
  • Rajamohan et al. (2025) trained a 1.6-billion-parameter GPT-2-style model on about 1.29 million NYU Langone patients with next-visit (multi-label) prediction; zero-shot it beat a fine-tuned BERT baseline on 2- and 5-year dementia (AUROC 0.814 vs 0.731 at 2 years) but trailed slightly on knee osteoarthritis. Redekop et al. (2025) reported a similar zero-shot GPT pipeline, with average top-1 precision of 0.614 for next medical concepts.
Worked example · W2To estimate one patient's 1-year mortality, W2 samples 64 futures from the patient's tokens up to the prediction time. If 7 of the 64 contain a death token before one year of simulated gap tokens has elapsed, the estimate is 7/64 ≈ 0.11. The same 64 futures also answer "readmission within 30 days" or "new heart-failure diagnosis within a year" by counting different tokens.

Costs and limits. Simulation has three costs. Inference is \(n\) rollouts per patient per question, far more than one forward pass. Errors compound: a slightly wrong next-event distribution, applied hundreds of times, can drift far from realistic trajectories over long horizons. And the model's probabilities are only as good as its reproduction of the process that generated the record, including censoring and care patterns. A generative model trained on one health system's data learns that system's practice, so "what will happen" partly means "what this hospital usually does": if clinicians at the training site routinely order a test, the simulated future contains it whether or not the patient needs it.

Comparison. A supervised head answers one question with a calibrated output after labelled training; a generative model answers any vocabulary-expressible question without labels, at higher inference cost and with calibration that must be checked per outcome. The mental model: a generative EHR model is a learned simulator of the record, and its predictions are frequencies in that simulator.

Let \(x_{\le s}\) be a patient's tokens up to prediction time \(s\), and let \(p_\theta\) be an autoregressive model whose vocabulary includes gap tokens, each mapping to a time increment \(\Delta(g)\) (for example the midpoint of its bin). A rollout samples \(x_{s+1} \sim p_\theta(\cdot \mid x_{\le s})\), then \(x_{s+2}\), and so on; its simulated clock after \(m\) tokens is \(\tau_m = \sum_{j \le m} \Delta(x_{s+j})\), with \(\Delta = 0\) for non-gap tokens. For an outcome code set \(C\) and horizon \(H\), define the indicator

\[ Z^{(r)} = \mathbb{1}\big[\exists\, m : x^{(r)}_{s+m} \in C \text{ and } \tau^{(r)}_m \le H\big] \]

for rollout \(r\). The Monte Carlo estimate of risk is

\[ \hat p = \frac{1}{n}\sum_{r=1}^{n} Z^{(r)}, \qquad \operatorname{SE}(\hat p) = \sqrt{\frac{p(1-p)}{n}}. \]

\(\hat p\) is unbiased for the model's own risk \(p_\theta\), not for the true risk; any gap between the two is model error, which more rollouts cannot reduce. For small \(n\) or extreme \(p\), the Wilson interval is better behaved than \(\hat p \pm 1.96\,\operatorname{SE}\).

Worked example · W2For a patient with \(p = 0.10\): with \(n = 16\), SE = 0.075 and the Wilson 95% interval is [0.024, 0.330]; with \(n = 64\), SE = 0.0375 and [0.048, 0.198]; with \(n = 256\), SE = 0.019 and [0.069, 0.143]. Ranking patients for AUROC tolerates the noise at \(n = 64\) because errors average across many pairs; reporting an individual's risk does not, which is why per-patient intervals should accompany simulated risks.

A learned censoring artefact. Records end for reasons unrelated to health (end of data extraction, patient moves). If training sequences end with an end-of-record token at rate \(e\) per year, and the model reproduces it, a simulated future can stop before the outcome. In a simple model where the outcome arrives at rate \(\lambda\) and end-of-record at rate \(e\), both constant,

\[ p_\theta(H) = \frac{\lambda}{\lambda + e}\big(1 - e^{-(\lambda + e)H}\big) \quad\text{instead of}\quad 1 - e^{-\lambda H}. \]
Worked example · W2With \(\lambda = 0.12\) per year and \(H = 1\), the correct risk is \(1 - e^{-0.12} = 0.113\). If the model has learned an end-of-record rate of 0.3 per year, simulated risk is \(0.12/0.42 \times (1 - e^{-0.42}) = 0.098\), an underestimate of 13% that no number of rollouts fixes. Masking the end-of-record token during sampling restores the intended quantity.

Scaling. CoMET fitted a loss of the form \(L(N, D) \approx E + A/N^{\alpha} + B/D^{\beta}\) in parameters \(N\) and training tokens \(D\), with \(\alpha = 0.520\) and \(\beta = 0.512\), close to natural-language values; minimizing \(L\) at fixed compute \(C \approx 6ND\) gives an optimal ratio \(D/N\) near 1,000. For W2 (\(N = 1.2 \times 10^8\), \(D \approx 4.6 \times 10^8\)), \(D/N \approx 3.8\): W2 is far from compute-optimal and would benefit more from more patients than from more parameters.

Inference cost. With \(T_{\text{gen}}\) tokens generated per rollout until the stop rule fires, the cost per patient-question is \(n \cdot T_{\text{gen}}\) decoding steps plus one prefill of the history. Compounding error grows with \(T_{\text{gen}}\): if each step's distribution has small error, the divergence between simulated and true trajectory distributions can grow roughly linearly in the number of steps, so long horizons are harder than short ones, consistent with Delphi-2M's decline from about 0.76 to 0.70 average AUC at ten years.

The essential logic of simulation fits in a function that knows nothing about transformers: it needs a sampler that returns the next token and the simulated time it consumes. The script abstracts the trained model as sample_next(state, rng) -> (gap_years, token) and tests the estimator on a toy model whose exact answer is known: events arrive at 12 per year, each is the outcome with probability 0.01, so the outcome arrives at rate 0.12 per year and the 1-year risk is \(1 - e^{-0.12} = 0.1131\). A second toy model adds an end-of-record token at 0.3 per year to reproduce the end-of-record bias, whose exact value is \(\frac{\lambda}{\lambda + e}\big(1 - e^{-(\lambda + e)H}\big) = 0.0980\) for \(\lambda = 0.12\), \(e = 0.3\) and \(H = 1\).

"""Zero-shot risk by simulation. A generative event model is abstracted as
sample_next(state, rng) -> (gap_years, token). The estimate is the fraction of
n sampled futures in which the outcome token appears before the horizon."""
import math, numpy as np

def toy_model(rate=12.0, q_outcome=0.01, eor_rate=0.0):
    """Toy stand-in for a trained model: events arrive at `rate`/year; each is the
    outcome with prob q; an end-of-record token arrives at `eor_rate`/year."""
    total = rate + eor_rate
    def sample_next(state, rng):
        gap = rng.exponential(1.0 / total)
        u = rng.random()
        if u < eor_rate / total:
            return gap, "[EOR]"
        return gap, ("OUTCOME" if rng.random() < q_outcome else "OTHER")
    return sample_next

def simulate_risk(sample_next, state, n, horizon, rng, max_steps=10_000):
    hits = 0
    for _ in range(n):                         # in practice: n rollouts batched on GPU
        t = 0.0
        for _ in range(max_steps):
            gap, tok = sample_next(state, rng)
            t += gap
            if t > horizon or tok == "[EOR]":  # stop: horizon passed or record ended
                break
            if tok == "OUTCOME":               # stop early: outcome reached
                hits += 1; break
    p = hits / n
    return p, math.sqrt(max(p * (1 - p), 1e-12) / n)

def wilson(p, n, z=1.96):
    c = (p + z*z/(2*n)) / (1 + z*z/n)
    h = z * math.sqrt(p*(1-p)/n + z*z/(4*n*n)) / (1 + z*z/n)
    return c - h, c + h

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    exact = 1 - math.exp(-12 * 0.01 * 1.0)                    # 0.1131
    p, se = simulate_risk(toy_model(), None, 20_000, 1.0, rng)
    print(f"exact {exact:.4f}  simulated {p:.4f} +/- {se:.4f}")
    assert abs(p - exact) < 3 * se
    # Learned end-of-record token biases risk downward
    lam, e = 0.12, 0.3
    biased = lam / (lam + e) * (1 - math.exp(-(lam + e)))     # 0.0980
    p2, se2 = simulate_risk(toy_model(eor_rate=e), None, 20_000, 1.0, rng)
    print(f"with [EOR] at 0.3/yr: exact {biased:.4f} simulated {p2:.4f}")
    assert abs(p2 - biased) < 3 * se2
    # Monte Carlo error at the n used in practice, for p = 0.10
    for n in (16, 64, 256):
        print(n, round(math.sqrt(0.1 * 0.9 / n), 4), [round(v, 3) for v in wilson(0.1, n)])

Output: exact 0.1131 simulated 0.1088 +/- 0.0022; with [EOR] at 0.3/yr: exact 0.0980 simulated 0.0950; and the Monte Carlo error table: SE 0.075, 0.0375 and 0.0188 at \(n\) = 16, 64 and 256, with Wilson intervals [0.024, 0.33], [0.048, 0.198] and [0.069, 0.143]. Both simulated values lie within three standard errors of their exact values, which is the assertion.

From toy to transformer. With a real model, state is the token prefix plus the attention key-value cache; sample_next runs one decoding step and maps gap tokens to durations. Three details matter. First, batch the \(n\) rollouts as \(n\) rows sharing one encoded prefix rather than re-encoding the history \(n\) times. Second, decide what to do with tokens that would be impossible in reality (a second birth, a lab before a gap is closed); sampling at temperature 1 is required for unbiased frequencies, so filtering must be explicit and logged. Third, use one set of rollouts for all outcomes when the horizon is shared, and stop each rollout at the horizon rather than at the first outcome.

Debugging. If simulated risk is systematically low, count how many rollouts ended by end-of-record or by the token budget before reaching the horizon; both truncate futures. If simulated event rates are implausible, compare the frequency of each token in rollouts with its frequency in held-out real futures over the same horizon, a check that needs no labels.

Simulation moves cost from training to inference and moves error from a fitted head into the generative model's fidelity. Production work therefore centres on throughput, on fidelity checks that need no labels, and on calibration per outcome.

Problem 1: inference cost. Every prediction requires \(n\) generated futures. Why it matters: a nightly risk refresh for a hospital's inpatients multiplies the number of patients, rollouts and generated tokens.

Worked example · W2A nightly job scores 40,000 active patients for 1-year outcomes with \(n = 64\). Assuming about 300 generated tokens per one-year rollout for this sicker-than-median cohort, that is \(40{,}000 \times 64 \times 300 \approx 7.7 \times 10^{8}\) generated tokens per night. At an assumed 20,000 tokens per second of batched decoding for a 120-million-parameter model on one accelerator, the job takes about 38,000 seconds, roughly 11 accelerator-hours. A supervised head on W2's embeddings would need 40,000 forward passes of the history, a small fraction of that. (Throughput and tokens per rollout are assumptions.)

Remedies, in order of effect. (1) Share rollouts across outcomes with the same horizon, so five outcomes cost the same as one. (2) Cache the history's attention keys and values once and branch \(n\) rollouts from it, so the prefill cost is paid once. (3) Choose \(n\) by the decision: for ranking, accuracy plateaus at about 64 rollouts in CoMET's study; for individual risk communication, report an interval or raise \(n\) only for patients near a decision threshold. (4) For high-volume single questions, distil: fit a cheap head on embeddings with simulated risks as targets, then simulate only to audit. Trade-off: distillation restores supervised cost but reintroduces a per-task model that must be maintained.

Serving zero-shot risk by simulation: encode the history once, branch n rollouts that share the cached prefix, stop each at the outcome or horizon, aggregate and recalibrate.Historyup to 4,096tokensPrefill onceKV cacheof the historyn rolloutsbatched, sharedprefix cachen = 64Stop rulesoutcome tokenhorizon passedtoken budgetAggregatep̂ and intervalrecalibrateCost per question ≈ n × (generated tokens until stop); the history is processed once.Monitor: rollouts per second, tokens per rollout, share stopped by budget, p̂ interval width.Version together: model checkpoint, tokenizer, sampling temperature, n, horizon, calibration map.
Fig. A serving path for simulation-based risk. The dominant cost is generated tokens, which stop rules and prefix caching control.

Problem 2: learned artefacts of the record. A generative model reproduces whatever ends or interrupts records. Root cause: training sequences end at the data-extraction date or when patients leave; if an end-of-record token or simply the end of sequence is learned, simulated futures stop early.

Worked incident · W2On the 2024 temporal holdout, W2's simulated 1-year mortality has good ranking (AUROC 0.89) but a calibration plot shows observed mortality above predicted in every decile, with calibration-in-the-large of 0.087 observed against 0.075 predicted. A rollout audit finds 14% of rollouts ending by end-of-record before one year, against 0% expected for an unconditional future. Masking the end-of-record token at sampling time raises mean predicted risk to 0.085 and reduces calibration error from 0.03 to 0.012 on 50,000 holdout patients; AUROC is unchanged at 0.89. (Illustrative numbers.)

Validation. The artefact hypothesis is supported if the gap between observed and predicted risk shrinks in proportion to the share of rollouts that ended early, and if patients whose real records were long show less bias. It is weakened if bias persists after masking; then under-representation of deaths in the record itself (deaths outside the hospital not captured without linkage to a death registry) is the next suspect, which requires data linkage rather than a sampling fix.

Problem 3: practice-pattern dependence. Simulated futures contain the tests and treatments the training institution tends to order. A changed guideline at the deploying site makes simulated futures stale even when patients are unchanged. Diagnosis: compare token frequencies in simulated and real futures by month (no labels needed); a rising divergence for specific orders, with stable diagnosis frequencies, indicates practice drift. Remedy: continued pretraining on recent data, and per-outcome recalibration on a rolling window. Cost: recalibration needs recent outcomes, which arrive only after the horizon.

IndicatorPurposeAlert condition (illustrative)
Rollouts ended before horizon, by reasonTruncation artefacts, token budget too small> 1% ended by end-of-record or budget
Token-frequency divergence, simulated vs real futuresFidelity without labels; practice driftTop-50 code rates differ by > 20% relative
Interval width of \(\hat p\) at decision thresholdEnough rollouts for the decisionWilson interval spans the threshold for > 10% of flagged patients
Observed vs predicted risk per outcomeCalibrationECE > 0.03 or calibration slope outside 0.8–1.2
Generated tokens per secondCapacityNightly job exceeds its window

These problems follow from the method: a generative model's risk is a frequency in a learned simulator, so its cost scales with simulation and its errors are the simulator's errors. Time-to-event pretraining, next, keeps the "when" question but answers it with an explicit hazard instead of sampling.

Time-to-event pretraining

Most clinical questions are about when, not whether: time to diagnosis, to readmission, to death. Time-to-event (TTE) modelling, also called survival analysis, answers such questions while handling censoring: many patients leave observation before an outcome could be seen, because the data ends, they move, or they change insurer. A censored patient is not a negative; their record says only that the event had not happened by the time observation stopped. Time-to-event pretraining makes this structure the pretraining objective, so that representations are shaped by survival from the start rather than by next-token prediction.

The problem with binary labels. The usual shortcut converts a "when" question into a yes/no label at a fixed horizon, such as death within one year. Patients whose follow-up ends before the horizon without an event cannot be labelled: dropping them discards data and can bias the cohort towards patients who stay in the health system; counting them as negatives tells the model that a patient who left after a month was known to survive the year.

Five illustrative patient follow-up lines: three end in an observed event, two are censored before any event was seen.Patient Aevent at 0.6 yPatient Bcensored at 0.8 yPatient Cevent at 2.5 yPatient Dcensored at 5 yPatient Eevent at 4.1 y012345years since prediction time (shaded = event observed, open = censored)1-year horizon
Fig. Censoring. Patients B and D leave observation without an event; whether they would have had one is unknown. A 1-year binary label is defined for A (positive) and for C, D and E (negative: event-free through the first year) but not for B, whose follow-up ends at 0.8 years. Illustrative patients.

How survival models handle censoring. A survival model predicts a hazard: the event rate at each moment for a patient who has not yet had the event. From the hazard follow the probability of remaining event-free to any time (the survival curve) and the risk by any horizon. Training rewards a high hazard at the moment an event was observed and penalizes accumulated hazard over all the time a patient was observed event-free. A censored patient contributes only that second part: the model learns from the months they were observed without an event, and nothing is claimed about the time after. Two classical forms appear in this book. The Cox proportional hazards model learns only how patients' risks compare (one patient's hazard is a fixed multiple of another's), never the absolute rate; SleepFM's disease head in the sleep chapter uses it. The piecewise exponential model divides follow-up into time bins and learns a constant hazard in each, so it predicts absolute risks at any horizon.

MOTOR. Steinberg et al. (2023) built MOTOR (ICLR 2024) on this idea:

  • Pretraining on up to 55 million patient records (about 9 billion clinical events) from EHR and claims data, with 8,192 TTE pretraining tasks, each "time until code \(c\) next occurs", handled by a piecewise-exponential head with low-rank task weights so that thousands of tasks share most parameters.
  • A 143-million-parameter transformer with local causal attention producing a representation at each event; every event is a possible prediction time.
  • On 19 target tasks, time-dependent C-statistic improved 4.6% over state-of-the-art baselines; TTE pretraining beat next-code pretraining by 2.0%; label efficiency improved by up to 95%; the model was more robust to temporal distribution shift and transferred to MIMIC-IV.
Worked example · W2In W2's 1-year mortality task on the 2024 cohort, suppose 6% of patients leave observation within the year without a recorded death. As a binary task, these patients are either dropped or wrongly labelled survivors. A TTE head on W2's representation uses their observed months, and the same pretrained representation can be given TTE heads for readmission, new diagnoses and death without changing the encoder. (Illustrative percentages.)

Evaluation. The standard ranking metric is Harrell's C-index: among pairs of patients where one had the event while the other was still observed and event-free, the fraction the model orders correctly (higher risk for the earlier event); 0.5 is chance. A time-dependent C-statistic restricts this to a horizon. Ranking is not enough: a model can order patients well and still predict risks that are too high or too low, so calibration (observed against predicted risk at fixed horizons, with observed risk estimated by the Kaplan–Meier method, which accounts for censoring) must be reported as well.

Comparison. Next-code pretraining learns which code comes next; TTE pretraining learns how soon each of thousands of codes will occur, a target closer to the clinical question and one that uses censored records correctly. Generative simulation answers the same question by sampling; TTE answers it in one forward pass. The cost is the need for a careful definition of time origin and censoring for every task. The mental model: a TTE model predicts a clock for every outcome at once, and censoring tells it where each patient's clock stopped being observed.

Censored data. For patient \(i\) and one outcome, observation yields \(T_i = \min(\text{event time}, \text{censoring time})\) and an indicator \(\delta_i = 1\) if the event was observed, 0 if censored. The hazard \(\lambda(u \mid x)\) is the instantaneous event rate at time \(u\) given covariates or history \(x\), and the survival function is \(S(u \mid x) = \exp\big(-\int_0^u \lambda(s \mid x)\,ds\big)\). Assuming censoring is independent of the event given \(x\), the log-likelihood of one observation is

\[ \log \mathcal{L}_i = \delta_i \log \lambda(T_i \mid x_i) - \int_0^{T_i} \lambda(s \mid x_i)\,ds. \]

The first term rewards a high hazard at the observed event time; the second penalizes cumulative hazard over the time at risk. Censored patients contribute only the second term, which is why discarding them, or treating "no event observed" as a negative label, biases a model.

Cox proportional hazards. The Cox model assumes \(\lambda(u \mid x) = \lambda_0(u)\exp(\beta^\top h(x))\) with an unspecified baseline \(\lambda_0\) and maximizes the partial likelihood, in which the baseline cancels:

\[ \log \mathcal{L}_{\text{Cox}} = \sum_{i:\,\delta_i=1} \Big[\beta^\top h(x_i) - \log \!\!\sum_{j:\,T_j \ge T_i}\!\! \exp\big(\beta^\top h(x_j)\big)\Big]. \]

Each term is a softmax over the risk set (patients still observed at \(T_i\)), structurally similar to the InfoNCE loss of contrastive learning. It learns relative risk only; absolute risks require a separate baseline estimate.

Piecewise exponential. Partition time with boundaries \(0 = u_0 < u_1 < \dots < u_B\) and assume a constant hazard \(\lambda_b(x)\) in bin \(b\). With \(\Delta_b(T) = \min\!\big(\max(T - u_{b-1}, 0),\, u_b - u_{b-1}\big)\) the time spent in bin \(b\) before \(T\), and \(b(T)\) the bin containing \(T\),

\[ \log \mathcal{L}_i = \delta_i \log \lambda_{b(T_i)}(x_i) - \sum_{b=1}^{B} \lambda_b(x_i)\,\Delta_b(T_i), \qquad S(t \mid x) = \exp\Big(-\sum_b \lambda_b(x)\Delta_b(t)\Big). \]
Piecewise-constant hazard for one patient with bins 0-0.25, 0.25-1, 1-2 and 2-5 years and hazards 0.20, 0.10, 0.08 and 0.05 per year.0123450.00.10.2time since prediction (years)hazard per yearλ₁ = 0.20λ₂ = 0.10λ₃ = 0.08λ₄ = 0.05event at T = 1.5 yexposure 0.25 + 0.75 + 0.5 y
Fig. The piecewise-exponential hazard used in the worked example. Survival to time t is exp of minus the area under this step function up to t; MOTOR predicts such a step function for thousands of codes at once. Illustrative values.
Worked example · W2Take bins [0, 0.25), [0.25, 1), [1, 2), [2, 5) years and hazards 0.20, 0.10, 0.08, 0.05 per year. A patient with an event at \(T = 1.5\) years has exposures 0.25, 0.75, 0.5, 0, so cumulative hazard \(0.05 + 0.075 + 0.04 = 0.165\) and \(\log \mathcal{L} = \ln 0.08 - 0.165 = -2.691\). The same patient censored at 1.5 years contributes \(-0.165\). The 1-year survival is \(e^{-(0.05 + 0.075)} = 0.8825\), so the 1-year risk is 0.1175.

MOTOR's head. MOTOR applies the piecewise-exponential form to thousands of tasks \(t\) at once, with

\[ \log \lambda_{b,t}(x) = w_t^\top h_b(x), \]

a shared per-bin representation \(h_b(x) \in \mathbb{R}^r\) computed from the transformer output and a task vector \(w_t \in \mathbb{R}^r\). With \(K\) tasks the head has \(K r\) task parameters instead of one full linear map per task and bin, so adding tasks is cheap. (This is a simplified statement; the paper gives the exact parameterization and its sparse implementation.) With \(K = 8{,}192\) and \(r = 64\), the task vectors hold about 0.52 million parameters, against about 25 million for separate 768-dimensional maps per task and bin over four bins.

C-index. Harrell's

\[ C = \frac{\sum_{i,j} \mathbb{1}[\delta_i = 1,\, T_i < T_j]\,\big(\mathbb{1}[r_i > r_j] + \tfrac12 \mathbb{1}[r_i = r_j]\big)}{\sum_{i,j} \mathbb{1}[\delta_i = 1,\, T_i < T_j]} \]

for risk scores \(r\). With times (1, 2, 3, 4) years, events (1, 0, 1, 1) and scores (0.9, 0.5, 0.3, 0.4), the comparable pairs are (1,2), (1,3), (1,4) and (3,4); the first three are ordered correctly and (3,4) is not, so \(C = 0.75\). Patient 2 is censored and can only appear as the later member of a pair.

The code implements the three survival pieces this section relies on: the piecewise-exponential log-likelihood and survival curve (the loss and output of a MOTOR-style head), the Cox partial log-likelihood (the loss used by SleepFM's disease head), and Harrell's C-index (the evaluation metric). Times are in years; hazards are per year. Each function takes plain arrays, so the worked numbers can be checked by hand.

"""Time-to-event pieces used by MOTOR-style pretraining and evaluation.
Times in years. Piecewise-exponential (PWE) bins: edges [0, u1, ..., uB]."""
import numpy as np

EDGES = np.array([0.0, 0.25, 1.0, 2.0, 5.0])        # 4 bins

def exposure(T, edges=EDGES):
    """Time spent in each bin before T -> [B]."""
    return np.clip(T - edges[:-1], 0, np.diff(edges))

def pwe_loglik(lam, T, delta, edges=EDGES):
    """lam [B] hazards per year; T observed time; delta 1=event, 0=censored."""
    b = min(np.searchsorted(edges, T, side="right") - 1, len(lam) - 1)
    return delta * np.log(lam[b]) - float(lam @ exposure(T, edges))

def survival(lam, t, edges=EDGES):
    return float(np.exp(-lam @ exposure(t, edges)))

def motor_log_hazards(h_bins, W):
    """MOTOR-style head (simplified): h_bins [B, r] per-bin patient features,
    W [K, r] low-rank task vectors -> log hazards [K, B] for K tasks."""
    return W @ h_bins.T

def cox_partial_loglik(score, T, delta):
    """Breslow form without ties: sum over events of score_i - log sum_{T_j >= T_i} exp(score_j)."""
    ll = 0.0
    for i in np.where(delta == 1)[0]:
        risk = T >= T[i]
        ll += score[i] - np.log(np.exp(score[risk]).sum())
    return float(ll)

def harrell_c(score, T, delta):
    """Fraction of comparable pairs (i had the event first, j still at risk) ordered correctly."""
    num = den = 0.0
    for i in range(len(T)):
        if not delta[i]:
            continue
        for j in range(len(T)):
            if T[i] < T[j]:
                den += 1
                num += 1.0 if score[i] > score[j] else 0.5 if score[i] == score[j] else 0.0
    return num / den

if __name__ == "__main__":
    lam = np.array([0.20, 0.10, 0.08, 0.05])
    ev, ce = pwe_loglik(lam, 1.5, 1), pwe_loglik(lam, 1.5, 0)
    print(f"event at 1.5 y: {ev:.3f}; censored at 1.5 y: {ce:.3f}; 1-y risk {1-survival(lam, 1.0):.4f}")
    assert abs(ev - (np.log(0.08) - 0.165)) < 1e-9 and abs(ce + 0.165) < 1e-9
    assert abs(survival(lam, 1.0) - np.exp(-0.125)) < 1e-12
    # Censored patients only pay the exposure term: higher hazard always lowers their likelihood
    assert pwe_loglik(2 * lam, 1.5, 0) < ce
    T = np.array([1.0, 2.0, 3.0, 4.0]); d = np.array([1, 0, 1, 1])
    s = np.array([0.9, 0.5, 0.3, 0.4])
    print("C-index", harrell_c(s, T, d), "Cox ll", round(cox_partial_loglik(s, T, d), 4))
    assert harrell_c(s, T, d) == 0.75
    assert harrell_c(-s, T, d) == 0.25
    K, r = 8192, 64
    lh = motor_log_hazards(np.random.default_rng(0).normal(size=(4, r)),
                           np.random.default_rng(1).normal(size=(K, r)) * 0.01)
    assert lh.shape == (K, 4)
    print("task-head params:", K * r, "vs full per-task-per-bin linear (d=768):", K * 4 * 768)

Output: event at 1.5 y: -2.691; censored at 1.5 y: -0.165; 1-y risk 0.1175, C-index 0.75 Cox ll -1.7831, and task-head params: 524288 vs full per-task-per-bin linear (d=768): 25165824. The tests confirm the worked example, that doubling hazards lowers a censored patient's likelihood (only the exposure term acts), that reversing scores gives \(1 - C\), and that the low-rank head has the expected shape \([K, B]\).

Implementation notes. Parameterize log-hazards, not hazards, so the network output is unconstrained and \(\lambda = e^{\text{output}}\) is positive. In training, each prediction time needs, for each task, the next occurrence time or the censoring time measured from that prediction time; computing these with a backward scan over each patient's events is linear in record length. With 8,192 tasks most targets are censored at any prediction time, so the loss is dominated by exposure terms; MOTOR's sparse implementation exploits this. The Cox loss above is quadratic in batch size and assumes no tied times; for large batches sort by time and use cumulative sums, and use the Breslow or Efron correction when ties are common (dates without times create many ties).

Debugging. If the C-index is near 0.5 while the loss falls, check the sign convention: some libraries expect higher scores to mean longer survival. If predicted 1-year risks are uniformly too high, check that censoring times were computed from the correct end-of-follow-up date rather than the last recorded event.

TTE models move the hard decisions into the task definition: when the clock starts, when observation ends, and which events count. Errors there produce models that look excellent in evaluation and fail in use.

Problem 1: end of follow-up defined by the last event. A patient's censoring time is when observation stopped, not when the last code was recorded. Root cause: EHR data rarely records disenrollment; using the last recorded event as censoring time shortens follow-up for healthy patients (who generate few events) and inflates their apparent hazard. Diagnosis: compare the distribution of censoring times with known data boundaries; a pile-up of censoring just after routine visits indicates the last-event convention. Remedy: censor at the data-extraction date for patients with evidence of continued care (any later encounter in a linked source), or at the last encounter plus a documented grace period, and report sensitivity to the choice. Trade-off: a long grace period assumes events would have been captured; deaths outside the hospital are often not captured without registry linkage.

Problem 2: time origin and leakage. Every prediction time must use only information available then. Root cause: events with dates earlier than their entry time (backdated diagnoses, results filed days later) let the model see an outcome's precursors that were not yet available.

Worked incident · W2A TTE head on W2 for incident heart failure reports a time-dependent C of 0.86 at one year on the temporal holdout. The C-index by time since prediction shows 0.93 for events in the first 14 days and 0.79 afterwards; 22% of events fall in that first window. An audit finds echocardiogram orders and natriuretic peptide labs, entered before the prediction time, that were placed because heart failure was already suspected. Excluding patients with a heart-failure workup in the 30 days before prediction time and starting the clock 30 days after it, C falls to 0.80 on 2,400 events with a patient-bootstrap 95% interval of about ±0.015. (Illustrative numbers.)

Validation. The leakage hypothesis is supported if C after the washout is close to C for events more than 30 days out in the original analysis, and if feature attribution on the excluded cases concentrates on workup orders. It is weakened if C stays high after the washout, which would indicate genuine prognostic signal. Both the detection task (short horizon, workup visible) and the prognosis task are legitimate, but they must be reported separately.

Problem 3: scaling to thousands of pretraining tasks. MOTOR's 8,192 tasks make every prediction time a multi-task example. Cost driver: computing next-occurrence times for every code at every event is \(O(L \cdot K)\) per patient if done naively. Remedy: sample prediction times per patient (for example a few per sequence), store only tasks whose event occurs within the maximum horizon (all others are censored at the same time and share one exposure term), and select tasks by frequency so that each has enough events. Trade-off: rare codes get no pretraining signal; MOTOR reports gains on rare targets because related frequent codes shape the shared representation, which should be validated on each deployment's rare outcomes.

IndicatorPurposeAlert condition (illustrative)
Share censored before horizon, by monthFollow-up definition, data gapsChange > 3 points against training period
C-index by time since predictionDetection vs prognosis, leakageFirst-window C exceeds later C by > 0.05
Predicted vs Kaplan–Meier risk at 30 d, 1 yAbsolute-risk calibrationDifference > 2 points in any risk decile
Events per pretraining taskTask selectionTasks with < 100 events in training

These checks connect directly to the likelihood: the event term is only as good as the event times, and the exposure term only as good as the censoring times. The final section asks how any of these models should be compared.

EHR benchmarks and evaluation

For years EHR foundation models were evaluated on private data with bespoke tasks, which made comparison between papers nearly impossible: two models reporting "AUROC 0.85 for mortality" could differ in cohort, prediction time, horizon and exclusions. A 2023 review of EHR foundation models counted few shared benchmarks and described the evaluation landscape as shaky (Wornow et al. 2023). Since then, four developments have improved this: a public few-shot benchmark with released weights, a shared data standard, studies of what EHR sequences demand of architectures, and broader evaluations that ask clinically motivated questions such as fairness and transportability.

What an evaluation must fix. A comparable EHR evaluation specifies the cohort (who is eligible), the prediction time (the moment at which the model may use only earlier data), the horizon (how far ahead the outcome is counted), the label budget (how many labelled examples the task head may use) and the split (which patients and which years are held out). Leaving any one of these unstated is enough to make results incomparable.

Evaluation protocol for an EHR foundation model: patient-disjoint and temporally separated data, a frozen model, few-shot heads and reported metrics.Pretraintrain patients onlyevents up to 2022Freeze modelembedding at eachprediction timeFew-shot headsk per classk = 1, 2, 4 ... 1285 resamples per kTest and reportheld-out patientsprediction in 2024AUROC, AUPRC, ECEChecks run before any number is reportedNo patient overlaptrain, few-shot and test ids disjointNo future informationfeatures end at prediction timeIntervals and baselinespatient bootstrap; count-based GBM
Fig. An evaluation protocol in the style of EHRSHOT, with W2's patient-level and temporal splits. The dashed boxes are checks rather than steps.
  • EHRSHOT (Wornow et al. 2023, NeurIPS Datasets and Benchmarks) releases de-identified records of 6,739 Stanford patients (41.6 million events, 921,499 encounters) with 15 few-shot tasks in four groups: operational outcomes, lab result anticipation, new diagnoses and chest X-ray findings. It evaluates heads trained on \(k \in \{1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128\}\) examples per class and releases the pretrained CLMBR-T-base. The pretrained model beat a count-based gradient-boosting baseline at \(k \le 64\), but its advantage shrank as \(k\) grew and the gradient-boosting model won on new-diagnosis tasks above \(k = 64\).
  • Context Clues (Wornow et al. 2025, ICLR) pretrained GPT, Llama, Mamba and Hyena models (about 120 million parameters each, about 2.5 million patients) at context lengths up to 16,000 tokens. Mamba at 16k reached the best mean AUROC on 14 EHRSHOT tasks (0.807 against a prior best of 0.777). Three EHR properties made modelling harder: copy-forwarded repetition, irregular time intervals, and perplexity that rises later in a timeline, the opposite of text, where later tokens are easier to predict.
  • MEDS, the Medical Event Data Standard, puts datasets into a common event format (one row per patient, time, code and optional value), with tooling for tabular baselines (MEDS-Tab) and a public MIMIC-IV demo, so tokenizers, models and task definitions can move between institutions. Its 2025 tutorial describes adoption at more than 15 institutions in 8 countries and MEDS-DEV, a decentralized benchmark to which sites contribute results against shared baselines without sharing data (McDermott et al. 2025).
  • FoMoH (Jeanselme et al. 2025) evaluated six structured-EHR foundation models on more than 6 million patients from Columbia University Irving Medical Center and MIMIC-IV across 14 clinically motivated tasks. The best models beat traditional baselines on discrimination, especially with few labels, and performed more evenly across socio-medical groups, but they could underperform for low-prevalence outcomes, were less well calibrated with few labels, and transported poorly across institutions.

Multi-site studies point the same way: Guo et al. (2024) found the Stanford-trained CLMBR-T-base matched locally trained gradient-boosting models at two external sites off the shelf and improved further with local continued pretraining.

Worked example · W2W2's headline numbers (1-year mortality AUROC 0.89, 30-day readmission AUROC 0.71, calibration error 0.03) are only interpretable with their protocol: patient-disjoint splits, pretraining on data up to 2022, tests on prediction times in 2024, and a stated label budget for each head. Reported in EHRSHOT style, W2 would also show a curve over \(k\) against a count-based gradient-boosting model, revealing where the pretrained representation stops helping.
ModelYearObjectivePretraining data (as reported)Notable result
Doctor AI2015Next-visit codes and time (RNN)Longitudinal visit recordsEarly sequence model of EHR
BEHRT2019Masked codes~1.6M patients+8.0–10.8 APS on 301 conditions
Med-BERT2020Masked codes28.5M patients>20% AUC gain with 300–500 labels
CLMBR2020Autoregressive codesStanford; T-base: 2.57M patients+19% AUROC in low-label regime
CEHR-BERT2021Masked codes + visit type, time tokens2.4M patients (OMOP)Explicit time tokens
Foresight2022Autoregressive concepts from text811K patients, 3 sitesPrecision@10 0.68–0.88 (next disorder), up to 0.91 (any concept)
MOTOR2023Time-to-event (8,192 tasks)55M records, ~9B events+4.6% time-dependent C
CEHR-GPT2024Generative, time tokensOMOP dataSynthetic timelines
ETHOS2024Generative PHT tokensTokenized timelinesZero-shot trajectory prediction
Delphi-2M2025Generative disease history0.4M UK Biobank (+1.9M Danish validation)1,256 disease rates; avg AUC ~0.76
NYU GPT2025Next-visit multi-label, 1.6B params~1.29M patientsZero-shot dementia AUROC 0.814 (2 y)
CoMET2025Generative events, scaled118M patients, ~115B events78 tasks zero-shot; ~1,000 tokens/param optimum

Table. EHR foundation models, by objective. Numbers are as reported by each paper; tasks and cohorts differ, so rows are not comparable to one another.

Comparison and mental model. Earlier evaluation compared a new model with weak baselines on one private task. Current practice compares against a strong count-based baseline at several label budgets, on public or standardized data, with calibration and subgroup results. A useful summary: an EHR foundation model earns its place where labels are scarce, outcomes are many, or transport to new sites is needed; where one task has abundant labels at one site, a well-tuned gradient-boosting model on code counts remains a hard baseline.

Let a frozen model map each (patient, prediction time) pair to an embedding \(z \in \mathbb{R}^d\), and let a task head \(f\) map \(z\) to a risk \(\hat p \in [0, 1]\) for a binary label \(y\).

AUROC is the probability that a randomly chosen positive receives a higher score than a randomly chosen negative,

\[ \text{AUROC} = \frac{1}{n_+ n_-}\sum_{i: y_i = 1}\sum_{j: y_j = 0}\Big(\mathbb{1}[\hat p_i > \hat p_j] + \tfrac12\mathbb{1}[\hat p_i = \hat p_j]\Big). \]

It ignores prevalence and calibration. For scores (0.9, 0.8, 0.3, 0.1) with labels (1, 0, 1, 0), the four positive–negative pairs give 1, 1, 0 and 1, so AUROC = 0.75. AUPRC (area under the precision–recall curve) is sensitive to prevalence: its chance level equals prevalence, so it is informative for rare outcomes where AUROC can look high while few flagged patients are true positives.

Calibration error. Partition predictions into bins \(B_1, \dots, B_M\) by \(\hat p\); the expected calibration error is

\[ \text{ECE} = \sum_{m=1}^{M} \frac{|B_m|}{N}\,\Big|\bar y_{B_m} - \bar{\hat p}_{B_m}\Big|, \]

the weighted average gap between observed rate \(\bar y\) and mean predicted risk \(\bar{\hat p}\) in each bin.

Worked example · W2Ten thousand patients fall in three occupied bins: 8,000 with mean prediction 0.02 and observed rate 0.035; 1,500 with 0.15 and 0.21; 500 with 0.45 and 0.27. ECE \(= 0.8 \times 0.015 + 0.15 \times 0.06 + 0.05 \times 0.18 = 0.012 + 0.009 + 0.009 = 0.030\), W2's reported value. The largest absolute gap (0.18) sits in the smallest, highest-risk bin, which a single ECE number hides; the bin table should be reported too.

Few-shot heads and prior shift. EHRSHOT-style heads are trained on \(k\) positives and \(k\) negatives, a training prevalence of 0.5. If the deployment prevalence is \(\pi\), Bayes' rule gives the corrected log-odds

\[ \operatorname{logit} \hat p_{\text{deploy}} = \operatorname{logit} \hat p_{\text{balanced}} + \ln\frac{\pi}{1-\pi} - \ln\frac{0.5}{0.5}. \]

With \(\pi = 0.05\), a balanced-head output of 0.40 (logit \(-0.405\)) becomes logit \(-0.405 - 2.944 = -3.350\), a risk of 0.034. AUROC is unchanged by this shift; calibration is not, which is one reason few-label foundation-model heads appear poorly calibrated, as FoMoH observed.

Uncertainty. With \(k\) examples per class, the head's estimate varies with which examples were drawn; EHRSHOT repeats each \(k\) over several random draws. The test-set estimate has its own uncertainty, estimated by a bootstrap that resamples patients (not rows) \(B\) times and takes the 2.5th and 97.5th percentiles of the metric. For AUROC near 0.71 with a few hundred positive patients, intervals of about ±0.02–0.03 are typical, larger than many published differences between models.

Time-dependent metrics. For TTE tasks the analogous ranking metric is the C-index restricted to a horizon \(\tau\), and calibration compares predicted risk by \(\tau\) with Kaplan–Meier estimates per risk group, so that censored patients contribute correctly.

A benchmark harness is short but easy to get wrong. The code implements the pieces of an EHRSHOT-style evaluation on frozen embeddings: AUROC by pair counting, ECE, a logistic-regression head, balanced \(k\)-shot sampling with repeated draws, a bootstrap over patients, and assertions that splits are patient-disjoint and temporally separated. The synthetic embeddings carry signal in three of 64 dimensions with about 10% prevalence, which is enough to show the shape of a few-shot curve; the numbers are not those of any real model.

"""EHRSHOT-style few-shot evaluation on frozen patient embeddings.
X [N, d] embeddings at prediction time; y [N] 0/1; pid [N] patient ids; year [N]."""
import numpy as np

def auroc(score, y):
    """P(score of a random positive > score of a random negative), ties count 1/2."""
    pos, neg = score[y == 1], score[y == 0]
    gt = (pos[:, None] > neg[None, :]).mean(); eq = (pos[:, None] == neg[None, :]).mean()
    return float(gt + 0.5 * eq)

def ece(p, y, bins=10):
    """Expected calibration error with equal-width bins."""
    idx = np.minimum((p * bins).astype(int), bins - 1); out = 0.0
    for b in range(bins):
        m = idx == b
        if m.any():
            out += m.mean() * abs(y[m].mean() - p[m].mean())
    return float(out)

def fit_logreg(X, y, l2=1e-2, steps=500, lr=0.5):
    w = np.zeros(X.shape[1]); b = 0.0
    for _ in range(steps):
        p = 1 / (1 + np.exp(-(X @ w + b)))
        w -= lr * (X.T @ (p - y) / len(y) + l2 * w); b -= lr * (p - y).mean()
    return lambda Z: 1 / (1 + np.exp(-(Z @ w + b)))

def k_shot(y, k, rng):
    """k positives and k negatives (EHRSHOT samples k examples per class)."""
    return np.concatenate([rng.choice(np.where(y == c)[0], k, replace=False) for c in (0, 1)])

def bootstrap_ci(score, y, pid, B=500, rng=None):
    """Resample PATIENTS, not rows: a patient's rows move together."""
    rng = rng or np.random.default_rng(0); ups = np.unique(pid); vals = []
    rows = {u: np.where(pid == u)[0] for u in ups}
    for _ in range(B):
        take = np.concatenate([rows[u] for u in rng.choice(ups, len(ups))])
        if 0 < y[take].mean() < 1:
            vals.append(auroc(score[take], y[take]))
    return np.percentile(vals, [2.5, 97.5])

def check_splits(pid_tr, pid_te, year_tr, year_te, cutoff_train=2022, test_year=2024):
    assert not set(pid_tr) & set(pid_te), "patient appears in train and test"
    assert year_tr.max() <= cutoff_train and (year_te == test_year).all(), "temporal leak"

if __name__ == "__main__":
    assert auroc(np.array([.9, .8, .3, .1]), np.array([1, 0, 1, 0])) == 0.75
    p = np.array([.02] * 8000 + [.15] * 1500 + [.45] * 500)
    y = np.zeros(10_000); y[:280] = 1; y[8000:8315] = 1; y[9500:9635] = 1   # 3.5%, 21%, 27%
    print("ECE worked example:", round(ece(p, y), 4)); assert abs(ece(p, y) - 0.030) < 1e-9
    # Synthetic frozen embeddings: signal in 3 of 64 dims, prevalence ~10%
    rng = np.random.default_rng(0); N, d = 6000, 64
    X = rng.normal(size=(N, d)); logit = X[:, :3] @ np.array([1.2, -0.8, 0.6]) - 2.6
    y = (rng.random(N) < 1 / (1 + np.exp(-logit))).astype(int)
    pid = np.arange(N); tr, te = pid[:4000], pid[4000:]
    check_splits(tr, te, np.full(4000, 2022), np.full(2000, 2024))
    for k in (4, 16, 64, 128):
        aucs = []
        for rep in range(5):                     # EHRSHOT also repeats each k with resamples
            idx = tr[k_shot(y[tr], k, np.random.default_rng(rep))]
            aucs.append(auroc(fit_logreg(X[idx], y[idx])(X[te]), y[te]))
        print(f"k={k:3d}  AUROC mean {np.mean(aucs):.3f}  spread {np.ptp(aucs):.3f}")
    s = fit_logreg(X[tr], y[tr])(X[te]); lo, hi = bootstrap_ci(s, y[te], pid[te], B=200)
    print(f"all-label AUROC {auroc(s, y[te]):.3f}  95% CI [{lo:.3f}, {hi:.3f}]  ECE {ece(s, y[te]):.3f}")

Output: ECE worked example: 0.03, then the few-shot curve: mean AUROC 0.566, 0.639, 0.716 and 0.756 at \(k\) = 4, 16, 64 and 128, with spreads across five draws of 0.133, 0.086, 0.080 and 0.082; and the all-label head: AUROC 0.856, patient-bootstrap 95% interval [0.834, 0.877], ECE 0.023. The spread at \(k = 4\) (0.133) is wider than the gap between \(k = 16\) and \(k = 64\), which is why single-draw few-shot results are unreliable.

Correctness notes. The bootstrap resamples patient ids and carries all of a patient's rows together; resampling rows treats repeated admissions of one patient as independent and gives intervals that are too narrow. The split check runs before any metric so that a leaking split fails loudly. The balanced head is evaluated for AUROC as is; for calibration, its logits should first be shifted by the prior-correction term derived for this section, otherwise ECE reflects the sampling scheme rather than the model.

Debugging. If a pretrained model's few-shot advantage disappears at small \(k\), check that the same \(k\)-shot draws were used for the model and the baseline; different draws add variance that can swamp the difference. If AUROC is implausibly high, list the top-weighted embedding dimensions or, for count baselines, the top features: codes recorded at or after the outcome (for example a discharge disposition of "expired") indicate leakage.

A benchmark result becomes a deployment decision only if the protocol matches the deployment. Three production problems recur when foundation-model results are reproduced locally.

Problem 1: split by encounter instead of by patient. Root cause: tasks such as readmission have one row per admission; random row splits put earlier admissions of a test patient in training. Why it matters: the model and the baseline both memorize patient-specific patterns, inflating both, often unequally.

Worked incident · W2An internal report shows W2's 30-day readmission AUROC as 0.78, against 0.71 in the release notes. The report's split was by admission: 41% of test admissions belonged to patients with other admissions in training. Re-running with patient-disjoint splits gives 0.71 for W2 and 0.69 for a count-based gradient-boosting model, with patient-bootstrap 95% intervals of about ±0.02 on 9,500 test admissions; the row-split analysis had shown 0.78 and 0.77. The apparent gap between model and baseline was also distorted. (Illustrative numbers.)

Validation. The leakage explanation is supported if AUROC on the subset of test patients with no training admissions matches the patient-disjoint result, and the inflation concentrates in patients with many admissions. It is weakened if AUROC stays high on patients unseen in training.

Problem 2: temporal drift between pretraining and use. W2 pretrains on data up to 2022 and is evaluated on 2024 prediction times. Diagnosis: report the same task on a 2022 patient-disjoint split and on the 2024 temporal split; the difference measures drift. Population changes, coding changes and practice changes each produce drift; the monitoring in earlier sections (unknown-token share, token-frequency divergence) separates them. Remedy: refresh heads on recent labelled data, continue pretraining periodically, and recalibrate per site. MOTOR's reported robustness to temporal shift is a property to check locally, not to assume.

Problem 3: comparing against the wrong baseline. EHRSHOT showed that a count-based gradient-boosting model catches up as labels grow and wins on some new-diagnosis tasks above 64 examples per class. Remedy: every internal evaluation includes such a baseline at matched label budgets, uses identical \(k\)-shot draws for all models, and reports AUPRC and calibration with AUROC. MEDS tooling (MEDS-Tab for tabular baselines; MEDS-DEV for shared task definitions and results) makes these baselines cheap to run on any MEDS-formatted dataset. Cost: a full curve over \(k \in \{1, \dots, 128\}\) with five draws for 15 tasks is 600 head fits per model, cheap on frozen embeddings but expensive if each requires fine-tuning; freeze the encoder for benchmarking and fine-tune only finalists.

Fairness and transportability. FoMoH's results (more even performance across socio-medical groups for top models, poorer transport across institutions) make two further reports standard: metrics by subgroup with intervals, and metrics at each site separately rather than pooled.

Report elementWhy it is requiredAcceptance check (illustrative)
Patient-disjoint and temporal splitsLeakage; driftSplit assertion passes; 2024 vs 2022 drop stated
Count-based baseline at each \(k\)Whether pretraining helps hereSame draws for all models
AUROC, AUPRC, ECE with patient-bootstrap intervalsRanking, rare outcomes, absolute riskInterval width reported; ECE after prior correction
Subgroup and per-site metricsFairness, transportabilityNo subgroup AUROC lower bound below a preset floor
Versioned task definitions (MEDS / MEDS-DEV style)ReproducibilityTask file hash recorded with results

Benchmarks close the loop on the chapter: masked, next-code, generative and time-to-event models differ in what they learn, but they are compared through the same protocol, and the protocol, not the architecture, determines whether a reported gain survives deployment. The multimodal chapter that follows extends the same questions to models that combine records with signals and text.

Multimodal Models and LLM Integration

A patient is not one modality. The same person produces coded records, free-text notes, laboratory values, wearable signals and spoken questions, and the most useful health models will combine them. Earlier chapters built one foundation model per data type: a wearable encoder, a sleep model, an EHR sequence model. This chapter asks how those models meet each other and how they meet large language models (LLMs), the general text models that have become the default interface for questions, explanations and reports.

Four integration patterns cover almost every published system. Serialize to text: write the data as words and numbers and give it to an LLM, which needs no new model but spends many tokens on numbers. Encoder plus adapter: run a modality-specific foundation model, then train a small projector that turns its embeddings into "soft tokens" an LLM can read; this needs paired training data. Contrastive alignment: train a signal encoder and a text encoder so that a window and its description land near each other in one embedding space, which allows queries in words; what is learned is limited by the captions. LLM with tools: let an LLM plan, call specialized models and run analysis code, which makes computation exact and auditable but adds orchestration errors. Many systems mix patterns.

Four patterns for combining health signals with language models. Serialize to textEncoder + adapterContrastive alignmentLLM with tools "HR: 61, 64, 70 …" LLM (few-shot / tuned) answer in text sensor FM encoder projector → soft tokens(trained; LLM often frozen) LLM reads tokens + text sensor enc. text enc. shared embedding spaceInfoNCE on (signal, caption) zero-shot labels, retrieval user question LLM plannercalls FMs, code, queries grounded answer + no new model− numbers as text, short context + uses signal FMs' strengths− needs paired training data + open-vocabulary queries− captions limit what is learned + exact computation, auditability− orchestration errors Liu et al. 2023PH-LLM · Time-LLMSensorLM · CLIPagent patterns
Fig. Four ways to combine health signals with language models, with their main trade-offs. Many systems mix patterns, for example an aligned sensor encoder whose embeddings also feed an LLM.

The sections follow the patterns: sensor–language alignment first, then LLMs that read wearable data or act as forecasters, then clinical text and medical LLMs, then the fusion of EHR and wearable data, where the evidence shows that complementary information matters more than representational sophistication.

Worked example · W1 and W2Two reference workloads run through the chapter. W1 is a wearable PPG foundation model: 150,000 participants, 30 million participant-hours of PPG and accelerometry at 64 Hz in 10-second windows, a 50-million-parameter encoder with 256-dimensional embeddings, AFib AUROC 0.93 from a linear probe. W2 is a 120-million-parameter decoder-only EHR model over 2 million patients and 310 million events, with a 4,096-token context and 1-year mortality AUROC 0.89. The chapter asks how each would be connected to language and to each other. All workload numbers are illustrative.

Each integration pattern is a different function composition. Let \(x\) be a patient's non-text data (a signal or an event sequence), \(q\) a question in text and \(a\) an answer. An LLM is a conditional distribution \(p_{\text{LLM}}(a \mid \text{tokens})\) over text given a sequence of input token embeddings. The four patterns differ only in how \(x\) becomes tokens:

\[ \text{serialize: } a \sim p_{\text{LLM}}\big(a \mid \text{tok}(s(x)),\, q\big), \qquad \text{adapter: } a \sim p_{\text{LLM}}\big(a \mid P(E(x)),\, q\big), \] \[ \text{alignment: } \hat y = \arg\max_k \cos\big(E_s(x), E_t(c_k)\big), \qquad \text{tools: } a \sim p_{\text{LLM}}\big(a \mid q,\, T(x; \pi(q))\big). \]

Here \(s\) writes the data as text and tok splits it into tokens; \(E\) is a frozen modality encoder and \(P\) a trained projector into the LLM's embedding width; \(E_s\) and \(E_t\) are a signal encoder and a text encoder trained to agree, with \(c_k\) the text description of class \(k\); and in the tool pattern a plan \(\pi(q)\) written by the LLM selects a program \(T\) that runs on \(x\), so the LLM sees only the program's output.

The patterns trade token cost against training cost. Serialization has no training cost but its token count grows with the number of values; the adapter's token count grows with the number of pooled embeddings, which the designer controls; alignment needs no LLM at inference; tools need a few thousand tokens regardless of data size because the data never enter the prompt.

Worked example · W1One day of W1's raw PPG at 64 Hz is \(64 \times 86{,}400 = 5{,}529{,}600\) samples, far beyond any context window if written out. Minute-level heart rate is 1,440 numbers, about 2,900 tokens at roughly two tokens per value, and a 30-day month about 86,000 tokens. W1's encoder instead emits one 256-dimensional embedding per 10-second window, \(8{,}640\) per day; mean-pooling 360 windows gives one soft token per hour, so a month costs \(30 \times 24 = 720\) soft tokens, about 120 times fewer than the text form.

Fusion of two non-text modalities is the same problem without the LLM: combine \(E_1(x_1)\) and \(E_2(x_2)\) so that a predictor improves on either alone. Its gain depends on how much information the second modality adds given the first, a quantity made precise in the fusion section.

In code, the four patterns are four ways of building the model input. The decisive quantity at design time is the input budget: how many tokens a given span of data costs in each pattern. The snippet below makes that concrete for W1. It serializes one synthetic day of minute heart rate to text and counts tokens with a crude proxy (real byte-pair tokenizers differ in detail but agree on the order of magnitude), and it computes how many soft tokens W1's encoder would produce if its 10-second window embeddings were pooled to hours.

Data flow: a (1440,) array of minute values becomes one string; the soft-token path starts from 8,640 window embeddings of shape (8640, 256) and ends with (24, d_llm) after pooling and projection (the projector itself appears in the wearable-LLM section). The assertions encode the conclusions: about two tokens per minute, 24 soft tokens per day, and a month of minute-level text that overflows a 32,000-token context.

"""W1: compare the input budget of the four integration patterns for one day of wearable data.
Text serialization spends tokens per number; an encoder + projector spends one soft token per pooled embedding."""
import numpy as np

def serialize(values, decimals=0):
    """Minute-level series -> compact text, e.g. 'HR: 61,64,70'."""
    fmt = f"{{:.{decimals}f}}"
    return "HR: " + ",".join(fmt.format(v) for v in values)

def approx_tokens(text):
    """Crude tokenizer proxy: digits split into groups of up to 3, each separator is a token.
    Real BPE tokenizers differ; the check below is about orders of magnitude."""
    n = 0
    for chunk in text.replace("HR: ", "").split(","):
        n += max(1, int(np.ceil(len(chunk) / 3))) + 1   # number + comma
    return n + 2                                          # "HR: " prefix

def soft_tokens_per_day(window_s=10, pool_windows=360):
    """W1 emits one 256-d embedding per 10-s window; pooling 360 windows = 1 hour per soft token."""
    windows = 24 * 3600 // window_s                        # 8,640 windows per day
    return windows, windows // pool_windows                # (windows, soft tokens)

rng = np.random.default_rng(0)
day = 62 + 8 * np.sin(np.linspace(0, 2 * np.pi, 1440)) + rng.normal(0, 2, 1440)   # 1,440 minutes
txt = serialize(day)
t_day = approx_tokens(txt)
w, s = soft_tokens_per_day()
print("text tokens/day:", t_day, " per 30 days:", 30 * t_day)
print("W1 windows/day:", w, " soft tokens/day (hourly pooling):", s)
assert 2_500 < t_day < 3_500          # ~2 tokens per minute of HR
assert w == 8_640 and s == 24
assert 30 * t_day > 32_000            # a month of minute HR overflows a 32k context

Output: about 2,900 text tokens per day and 86,000 per month against 24 soft tokens per day. A debugging habit worth keeping from this small check: log the token count of every serialized prompt next to the model's answer, because a silently truncated prompt is the most common cause of a wrong numerical answer in the serialize pattern.

Worked example · W1The same accounting at W1's scale: 30 million participant-hours are 1.25 million participant-days. Serialized as minute heart rate they would be about \(1.25 \times 10^6 \times 2{,}900 \approx 3.6\) billion text tokens; as hourly soft tokens they are \(30 \times 10^6\) soft tokens, one per participant-hour, each a 256-dimensional vector before projection.

In production the choice among patterns is a choice of failure mode, cost profile and audit trail. The table summarizes what each pattern costs per query and what it typically gets wrong, using W1 and W2 as the scale reference.

PatternTraining costTokens per queryTypical failurePrimary metric to monitor
Serialize to textnone or fine-tuninggrows with data span (about 86,000 for a month of minute HR)arithmetic errors, silent truncationnumeric exact-match on a canary question set
Encoder + adapterprojector on paired dataset by pooling (720 per month at hourly pooling)LLM ignores soft tokens; adapter drift after encoder updateanswer change when soft tokens are shuffled (should be large)
Contrastive alignmenttwo towers on (signal, caption) pairsno LLM at inferenceconcepts absent from captions; score calibrationretrieval recall@1 on a frozen canary set
LLM with toolsnone to moderatea few thousand, independent of data sizewrong tool call, wrong codecode execution success and validator rejection rate

Diagnosis before remedy. A wrong answer from a multimodal system has four possible sources: the data (missing or misaligned), the modality encoder, the bridge (serializer, projector, caption space or tool call) and the language model's reasoning. They are separated by logging each stage's output and by targeted ablations: replace the data with a constant and check that the answer changes; shuffle soft tokens between users and check that the answer changes; replace the LLM with a template that reads the tool output and check whether accuracy drops.

Worked incident · W1A coaching feature built on the serialize pattern answers "What was my average resting heart rate last month?" for W1 users. After a template change that switches the data block from hourly to minute-level heart rate and adds two paragraphs of instructions, complaints rise. Logs show that prompts above the 32,000-token limit are truncated from the start, so the model sees about 11 of 30 days and reports their mean as the monthly average. Diagnosis: the token-count log shows 100% of month-scale prompts truncated after the template change and 0% before; numeric exact-match on a 500-question canary set falls sharply on month-scale questions and not on week-scale ones, which isolates the cause from model quality. Remedy, in order: compute the statistic in code and pass only the result (the tool pattern), keep serialization for short summaries, and add a hard check that rejects any answer whose cited value does not appear in the computed results. Cost: one extra model call and a sandbox. Validation: the canary exact-match on month-scale questions must return to the week-scale level; if it does not, the error is in the reasoning stage, not the truncation.

The remaining sections apply the same discipline to each pattern: what it computes, what it costs, how it fails, and which measurement separates the causes.

Sensor–language models

A sensor–language model learns a shared embedding space for sensor data and text, so that a window of wearable data and a sentence describing it land near each other. Once that space exists, a model can be queried in words: "Which of these days contains a swim?" becomes a comparison between each day's embedding and the embedding of the sentence. The approach adapts the image–text recipe popularized by CLIP-style models to physiological and behavioral signals.

Why it exists. Self-supervised wearable models such as W1 learn good representations but have no vocabulary: every new task needs labelled examples and a probe. Large language models have the vocabulary but read numbers poorly. A shared space gives a signal model access to language without forcing raw numbers through an LLM. The bottleneck is paired text. Images on the web come with captions; wearable data almost never do.

The mechanism, end to end. Zhang et al. (2025) trained SensorLM on about 59.7 million hours of data from 103,643 people across 127 countries, collected from Fitbit and Pixel Watch devices. It proceeds in four steps.

  • Caption generation. A hierarchical pipeline writes captions automatically from the data. A statistical level states means, minima, maxima and spreads of each channel; a structural level describes trends, spikes and drops found with sliding windows; a semantic level lists recognized activities and sleep periods with start and end times and user-logged mood. The input is the sensor data; the output is text; nothing is trained.
  • Encoding. A sensor encoder (a vision-transformer-style network over two-dimensional patches of a feature-by-minute grid) turns a day of data into an embedding; a text encoder turns the caption into an embedding.
  • Two losses. A contrastive loss rewards each window for being closer to its own caption than to the other captions in the batch. A generative captioning loss trains a decoder to write the caption from the sensor representation. The architecture generalizes CLIP (contrastive only) and CoCa (both).
  • Use. At inference, class names written as sentences are encoded once; a new window is assigned to the nearest sentence (zero-shot classification), matched to text descriptions (retrieval in either direction), or described by the decoder (captioning).
Sensor-language pretraining: automatic captions pair with sensor windows; a contrastive loss aligns embeddings and a decoder learns to caption.Minute sensor data26 features x 1,440 minCaption pipelinestatistical: mean, maxstructural: trends, spikessemantic: activities, sleepSensor encoderViT over 2-D patchesText encodercaption -> embeddingCaption decoderpredicts caption textContrastive lossmatch window to captionCaptioningdescribe a dayZero-shot labelsand retrievalTotal loss = contrastive term + captioning term; setting either weight to zero gives CLIP-style or caption-only training.
Fig. The sensor-language pattern in the style of SensorLM (Zhang et al. 2025). Captions are generated from the data itself, so pairing costs no human labels; the two losses give retrieval and zero-shot labels on one side and captioning on the other.

What it achieved. SensorLM classified 20 activities zero-shot, supported few-shot learning and cross-modal retrieval in both directions, and its captions were rated more coherent and factual than those of general LLMs. General LLMs given the same data as text performed near chance on the zero-shot activity task. Performance improved with data, model size and compute. The paper appeared at NeurIPS 2025.

Worked example · W1W1 has no text. To add a text tower, each of its 1.25 million participant-days (30 million hours divided by 24) would receive an automatic caption built from features W1 already computes: heart-rate statistics, step counts from accelerometry, sleep periods and the 38% of hours with no PPG. Zero-shot AFib detection would then require captions that mention rhythm irregularity; if the pipeline never writes such phrases, the shared space cannot represent the concept, however good W1's encoder is.

Compared with its predecessor. A contrastive model such as W1 aligns two views of the same signal; a sensor–language model aligns a signal with a description. The first needs no captions and learns whatever distinguishes participants and time; the second inherits the vocabulary and the blind spots of its captions. The mental model: the caption pipeline is the teacher, and the shared space can never be more expressive than what the teacher knows how to say.

Let \(x_i\) be the \(i\)-th sensor window in a batch of size \(B\) and \(c_i\) its caption. Two encoders map them to unit vectors \(u_i = E_s(x_i)/\lVert E_s(x_i)\rVert\) and \(v_i = E_t(c_i)/\lVert E_t(c_i)\rVert\) in \(\mathbb{R}^d\). Their cosine similarity is \(u_i^\top v_j\). The contrastive loss treats the batch as a \(B\)-way classification problem in both directions:

\[ \mathcal{L}_{\text{con}} = -\frac{1}{2B}\sum_{i=1}^{B}\left[\log\frac{e^{u_i^\top v_i/\tau}}{\sum_{j} e^{u_i^\top v_j/\tau}} + \log\frac{e^{u_i^\top v_i/\tau}}{\sum_{j} e^{u_j^\top v_i/\tau}}\right], \]

where \(\tau > 0\) is a temperature that sharpens or flattens the softmax. The captioning loss is the negative log-likelihood of the caption tokens \(c_i = (w_1, \dots, w_T)\) under a decoder that reads the sensor representation:

\[ \mathcal{L}_{\text{cap}} = -\frac{1}{T}\sum_{t=1}^{T} \log p_\theta\big(w_t \mid w_{<t},\, E_s(x_i)\big), \qquad \mathcal{L} = \lambda_{\text{con}}\mathcal{L}_{\text{con}} + \lambda_{\text{cap}}\mathcal{L}_{\text{cap}}. \]

Setting \(\lambda_{\text{cap}} = 0\) gives CLIP-style training and \(\lambda_{\text{con}} = 0\) gives a captioner; SensorLM's main experiments used \(\lambda_{\text{con}} = \lambda_{\text{cap}} = 1\), temperature \(\tau = 0.01\) and batch size 1,024 (Zhang et al. 2025). Its input was 26 minute-level features over a day, a \(26 \times 1{,}440\) grid cut into patches of 2 features by 10 minutes, which gives \(13 \times 144 = 1{,}872\) sensor tokens; encoder sizes ranged from about 3 million to 1.27 billion parameters.

Reading the loss. With random embeddings each softmax is roughly uniform and \(\mathcal{L}_{\text{con}} \approx \ln B\); at \(B = 1{,}024\) that is 6.93 nats. Perfect alignment drives it towards 0. With a very small \(\tau\), random embeddings can produce a loss well above \(\ln B\) because the softmax becomes confident on wrong pairs; this is a sign of an untrained model, not a bug.

Zero-shot classification encodes one prompt \(c_k\) per class and predicts

\[ p(k \mid x) = \frac{\exp(u^\top v_k/\tau)}{\sum_{k'} \exp(u^\top v_{k'}/\tau)}. \]

At \(\tau = 0.01\), a cosine margin of 0.05 between the best and second-best prompt is a logit gap of 5, a probability ratio of \(e^5 \approx 148\): zero-shot scores are very confident and need calibration before they are read as probabilities.

Worked example · SensorLM and W1SensorLM's reported zero-shot AUROC on 20 activity classes was 0.84, against 0.50 for Gemma-3-27B and 0.51 for Gemini 2.0 given the data as text, both at chance. Retrieval among 5,000 candidates reached recall@1 of 98.2% from sensor to text and 96.7% from text to sensor, where chance is \(1/5{,}000 = 0.02\%\). For W1 with a caption tower at its own settings (batch 4,096, temperature 0.1), the untrained contrastive loss would start near \(\ln 4{,}096 = 8.32\) nats. W1's 1.25 million participant-days give about 1,220 batches of 1,024 day-caption pairs per epoch, roughly half SensorLM's ~2.5 million person-days.

Assumptions and trade-offs. The contrastive term assumes that the other captions in a batch are true negatives. Template captions break this: two quiet days produce near-identical statistical captions, so the loss pushes apart windows that should be close. Larger batches add negatives but also add such false negatives; the captioning term does not depend on negatives and partly compensates.

Three components make a sensor–language system at toy scale: a caption generator, the combined loss and a zero-shot classifier. The code mirrors SensorLM's three caption levels and its loss \(\mathcal{L} = \lambda_{\text{con}}\mathcal{L}_{\text{con}} + \lambda_{\text{cap}}\mathcal{L}_{\text{cap}}\), with NumPy arrays standing in for network outputs.

  • captions(hr, steps, events) takes two (1440,) minute series and a list of logged events and returns three strings. The structural level computes hourly means and reports rises and drops larger than a threshold, a simplified version of sliding-window trend detection.
  • info_nce(zs, zt, tau) takes two (B, d) matrices of L2-normalized embeddings, row \(i\) of each forming a matched pair, and returns the symmetric contrastive loss.
  • zero_shot(z_sensor, z_prompts) returns an (N, K) matrix of class probabilities by a softmax over cosine similarities with \(K\) prompt embeddings.
"""Sensor-language pieces in the SensorLM style, at toy scale:
(1) a three-level caption generator (statistical, structural, semantic),
(2) the combined loss L = lam_con * L_con + lam_cap * L_cap,
(3) zero-shot classification by comparing a sensor embedding with prompt embeddings."""
import numpy as np

def captions(hr, steps, events, win=60, thr=8.0):
    """hr, steps: (1440,) minute series for one day. events: list of (label, start_min, end_min).
    Returns three caption strings, one per level."""
    stat = (f"Heart rate mean {hr.mean():.0f} bpm, min {hr.min():.0f}, max {hr.max():.0f}; "
            f"steps total {int(steps.sum())}.")
    hourly = hr.reshape(-1, win).mean(1)                  # (24,) hourly means
    trends = []
    for h in range(1, 24):
        d = hourly[h] - hourly[h - 1]
        if d > thr:  trends.append(f"heart rate rises at {h:02d}:00")
        if d < -thr: trends.append(f"heart rate drops at {h:02d}:00")
    struct = "; ".join(trends) or "heart rate stable"
    sem = "; ".join(f"{lab} from {s // 60:02d}:{s % 60:02d} to {e // 60:02d}:{e % 60:02d}"
                    for lab, s, e in events) or "no logged events"
    return stat, struct, sem

def l2n(x):
    return x / np.linalg.norm(x, axis=-1, keepdims=True)

def info_nce(zs, zt, tau):
    """Symmetric InfoNCE over a batch. zs, zt: (B, d) L2-normalized; row i of each is a matched pair."""
    logits = zs @ zt.T / tau                              # (B, B)
    def ce(lg):                                           # cross-entropy with targets on the diagonal
        lg = lg - lg.max(1, keepdims=True)
        return -(np.diag(lg) - np.log(np.exp(lg).sum(1))).mean()
    return 0.5 * (ce(logits) + ce(logits.T))

def caption_nll(token_logprobs):
    """Captioning loss: mean negative log-likelihood of the reference caption tokens. (T,) -> scalar."""
    return -np.mean(token_logprobs)

def coca_loss(zs, zt, token_logprobs, tau=0.01, lam_con=1.0, lam_cap=1.0):
    return lam_con * info_nce(zs, zt, tau) + lam_cap * caption_nll(token_logprobs)

def zero_shot(z_sensor, z_prompts, tau=0.01):
    """z_sensor: (N, d); z_prompts: (K, d), one per class prompt. Returns (N, K) probabilities."""
    lg = z_sensor @ z_prompts.T / tau
    lg -= lg.max(1, keepdims=True)
    p = np.exp(lg)
    return p / p.sum(1, keepdims=True)

# ---- checks ----
rng = np.random.default_rng(1)
hr = np.full(1440, 60.0); hr[7 * 60:8 * 60] = 120.0       # a run at 07:00-08:00
steps = np.zeros(1440); steps[7 * 60:8 * 60] = 150
stat, struct, sem = captions(hr, steps, [("running", 420, 480)])
print(stat, "|", struct, "|", sem)
assert "rises at 07:00" in struct and "drops at 08:00" in struct

B, d = 1024, 64
z = l2n(rng.normal(size=(B, d)))
aligned = info_nce(z, z, tau=0.01)                        # perfect pairs
random_ = info_nce(z, l2n(rng.normal(size=(B, d))), tau=0.01)
print(f"InfoNCE aligned {aligned:.3f}  random {random_:.2f}  ln B = {np.log(B):.2f}")
assert aligned < 0.05 and random_ > np.log(B) - 1

prompts = l2n(rng.normal(size=(20, d)))                   # 20 activity prompts
labels = rng.integers(0, 20, 500)
zs = l2n(prompts[labels] + 0.15 * rng.normal(size=(500, d)))
acc = (zero_shot(zs, prompts).argmax(1) == labels).mean()
print("zero-shot accuracy on separable toy data:", acc)
assert acc > 0.95
print("CoCa loss:", round(coca_loss(z, z, np.log(np.full(30, 0.5))), 3))  # 0 + ln 2

The checks state what must be true: a one-hour run at 07:00 must appear as a rise at 07:00 and a drop at 08:00; perfectly aligned pairs give a loss near zero; random pairs at \(\tau = 0.01\) give a loss above \(\ln B\); and separable toy data are classified zero-shot. The CoCa loss with perfect alignment and a caption assigned probability 0.5 per token equals \(\ln 2 \approx 0.693\), which confirms that the two terms are added with unit weights.

Debugging tips. Print one caption per level for a handful of days before training; template bugs (units, time zones, off-by-one hours) are easier to see in text than in loss curves. Count duplicate captions in each batch: if many windows share an identical caption, the contrastive term is training on false negatives, and either the captions need more detail or duplicates should be masked from the denominator.

Worked example · W1For W1 the caption generator would read hourly heart rate and step counts derived from its 64 Hz accelerometry, and would emit an explicit statement such as "no PPG 14:00 to 16:00" for gaps, so that the 38% of hours without PPG are described rather than silently imputed. A unit test for that rule: a day with a forced two-hour gap must produce a caption containing that interval.

Problem: the caption pipeline caps what the model can know. Captions are generated from the data, so every concept in the shared space must be computable by the pipeline. Why it matters: a product team will query the model with clinical words ("irregular rhythm", "fever") that the pipeline never wrote. Root cause: the semantic level only knows activities and sleep periods the device already detects and moods users log. Quantified example: SensorLM's zero-shot AUROC was 0.84 on 20 activities, which the pipeline names, but only 0.61 on locomotion versus stationary and 0.64 on environmental context, coarser concepts that its captions plausibly describe less directly (Zhang et al. 2025). Diagnosis: build a concept coverage table that counts how often each query term appears in training captions, and plot zero-shot AUROC against that count. Remedy: extend the pipeline with new detectors or with a small set of human-written captions for target concepts; for concepts that cannot be captioned, use a labelled probe instead of zero-shot. Cost: each new detector is software to maintain and validate. Validation: AUROC on a target concept should rise after its phrase enters the captions and stay flat for a control concept; a rise in the control suggests a general training effect rather than the caption change.

Problem: compute. The sensor encoder reads 1,872 tokens per day. With the usual estimate of \(6N\) floating-point operations per parameter per token, a 114-million-parameter encoder costs about \(6 \times 1.14 \times 10^8 \times 1{,}872 \approx 1.3 \times 10^{12}\) FLOPs per day of data, \(1.3 \times 10^{15}\) per batch of 1,024 and \(6.6 \times 10^{19}\) over 50,000 steps, before the text tower and decoder. At \(4 \times 10^{14}\) sustained FLOP/s per accelerator this is about 45 accelerator-hours for the sensor tower alone; the 1.27-billion-parameter encoder costs about eleven times more. Remedy when budget-bound: larger patches (fewer tokens), or freezing a pretrained signal encoder such as W1 and training only the text side and a projection.

Worked incident · W1A W1 sensor–language model is deployed for retrieval ("show days like this one") and zero-shot tagging of workouts. A firmware update changes the skin-temperature channel's offset on one device model. Symptoms: the daily share of days tagged "sleep disturbed" rises from 6% to 15% on that device model only, and retrieval recall@1 on a frozen 1,000-pair canary set falls from 0.95 to 0.81 for the affected model and is unchanged elsewhere. Measurements that separate causes: per-device-model input statistics show a shift of the temperature mean; the caption pipeline run on the new data produces "temperature elevated" phrases on most nights, so both the input and the training target moved; other channels are stable. Intervention: per-device-model normalization keyed to firmware version, recomputation of affected captions, and a check that blocks scoring when an input channel's daily mean leaves its historical band. Trade-off: normalization hides genuine population shifts if applied blindly, so the band is set per channel from historical variation. Validation: canary recall@1 returns to 0.95 and the tag rate returns to the pre-update share on the affected model; if recall recovers but the tag rate does not, the remaining cause lies in the zero-shot threshold, which then needs recalibration on a small labelled sample.

Calibration and thresholds. Because zero-shot probabilities at \(\tau = 0.01\) are extreme, production systems fit a temperature or isotonic map on a few hundred labelled examples per concept and monitor the tag rate per concept per day. A prompt ensemble (several phrasings per class, embeddings averaged) reduces sensitivity to wording. These steps connect directly to the next section: once signals have a text interface, a general LLM can be put on top of it.

LLMs over wearable data and as forecasters

Large language models can reason over wearable data directly, with modest adaptation. The question is how the data reach the model and what the model is trusted to do with them. Three routes are in use, and a fourth line of work asks whether a general LLM can be repurposed as a time-series forecaster.

Route A: serialize and prompt or fine-tune. The data are summarized as text (daily steps, sleep duration, resting heart rate) and placed in the prompt. Liu et al. (2023) showed that few-shot tuning lets an LLM ground physiological and behavioral time series for cardiac signal analysis, activity recognition, calorie estimation and mental-health screeners. The method needs no new architecture; its weakness is that numbers are written as tokens, so arithmetic over long spans is unreliable and long histories do not fit.

Route B: encoder plus adapter. A signal foundation model encodes the raw data; a small trained network (the projector or adapter) maps each embedding to a vector of the LLM's input width, a "soft token"; the LLM reads these alongside the text. Cosentino et al. (2025) fine-tuned Gemini into PH-LLM for sleep and fitness coaching (Nature Medicine, 2025). On multiple-choice exams it scored 79% in sleep medicine and 88% in fitness, above a sample of human experts (76% and 71%). On 857 real-world case studies it performed similarly to experts for fitness and improved on base Gemini for personalized sleep insights. And it predicted self-reported sleep quality from a multimodal encoding of wearable data, which is route B.

Route C: an agent with tools. The LLM does not read the data at all. It writes analysis code, a sandbox runs the code on the user's data, and the LLM explains the result. Merrill et al. (2024) built the Personal Health Insights Agent (PHIA) this way, combining multistep reasoning, code generation and information retrieval, and released two benchmarks with more than 4,000 health-insight questions. In a 650-hour expert evaluation PHIA answered 84% of objective numerical questions correctly, received favorable ratings on 83% of open-ended questions, and was twice as likely as a strong code-generation baseline to earn the highest quality rating; the paper is listed as accepted at Nature Communications.

Three routes from wearable data to a language model: text serialization, encoder plus projector, and an agent that calls tools.A SerializeB Encoder + projectorC Agent with toolsDaily summariessteps, sleep, RHRText prompt"RHR: 58, 57, 59 ..."LLMfine-tuned or few-shotAnswertextRaw windowsPPG + accelerometrySignal encoderfrozen, 256-d outputProjectorembeddings -> soft tokensLLMreads tokens + textQuestion"Do I sleep less?"LLM plannerwrites analysis codeToolscode, queries, modelsGrounded answernumbers from codeA suits short summaries; B suits long raw signals; C suits exact numerical questions.
Fig. Three routes from wearable data to a language model. Route A is the setting of Liu et al. (2023) and of PH-LLM's text tasks; route B is PH-LLM's sleep-quality prediction; route C is the agent pattern of PHIA (Merrill et al. 2024).

LLMs as forecasters. A parallel line tries to make general LLMs forecast. Jin et al. (2023) proposed Time-LLM, which "reprograms" patches of a series into combinations of learned text prototypes that a frozen LLM can read, adds a prompt prefix describing the task, and projects the LLM's outputs back to forecasts; it reported gains over specialized forecasters, including in few-shot and zero-shot settings. Tan et al. (2024) then ablated three popular LLM-based forecasters: removing the LLM, or replacing it with a single attention layer, did not degrade results and often improved them; pretrained LLMs did no better than the same models trained from scratch, did not capture sequential dependencies and did not help in few-shot settings, while patching-plus-attention encoders matched them at far lower cost. Claims of this kind deserve the scrutiny of zero-shot forecasting evaluation: compare against purpose-built time-series models and simple baselines at equal compute.

Worked example · W1A user asks, "Has my resting heart rate gone up since I started the new medication?" Route A writes 60 days of daily resting heart rate into the prompt, about 300 tokens, and lets the model compare. Route B passes 60 days of W1 embeddings pooled to one soft token per day, letting the model use rhythm and activity context that a single daily number loses. Route C writes code that splits the series at the start date, computes the two means and a confidence interval from the days with PPG coverage, and reports both, so a rise of 2 bpm is not presented as meaningful when W1's own resting-heart-rate error is 2.4 bpm.

Contrast and mental model. Serialization works for short summaries but not for months of minute-level data; the encoder-plus-adapter pattern is how signal foundation models and LLMs are most likely to meet for perception, and tools are how they meet for exact computation. The LLM is best used as the interface and planner, not as the calculator or the forecaster.

The adapter. Let \(h_t \in \mathbb{R}^{256}\) be W1's embedding of window \(t\) and \(m_t \in \{0,1\}\) indicate whether that window has PPG. Pooling \(K\) windows with a masked mean gives

\[ \bar h_j = \frac{\sum_{t \in \mathcal{W}_j} m_t\, h_t}{\max\big(1, \sum_{t \in \mathcal{W}_j} m_t\big)}, \qquad \kappa_j = \frac{1}{K}\sum_{t \in \mathcal{W}_j} m_t, \]

where \(\mathcal{W}_j\) is the \(j\)-th block of \(K\) windows and \(\kappa_j\) its coverage. A two-layer projector maps \(\bar h_j\) to the LLM's input width \(d_{\text{LLM}}\): \(z_j = W_2\,\mathrm{ReLU}(W_1 \bar h_j + b_1) + b_2\). With hidden width \(d_h\), it has \(256\,d_h + d_h + d_h\,d_{\text{LLM}} + d_{\text{LLM}}\) parameters; for \(d_h = 1{,}024\) and an assumed \(d_{\text{LLM}} = 2{,}048\) that is \(262{,}144 + 1{,}024 + 2{,}097{,}152 + 2{,}048 = 2{,}362{,}368\), about 2.4 million, tiny next to the LLM. Training minimizes the LLM's next-token loss on paired (signal, target text) examples with the LLM frozen or lightly tuned, so the projector learns to place signals where the LLM can use them.

Token cost. Let \(n\) be the number of values serialized and \(r\) the tokens per value. Text costs \(n r\) tokens; the adapter costs \(n_w/K\) soft tokens for \(n_w\) windows. With W1, \(K = 360\) (one hour) and a 30-day month, \(n_w = 259{,}200\) windows and the adapter costs 720 soft tokens, while minute heart rate as text costs \(43{,}200 \times 2 \approx 86{,}000\) tokens.

Evaluating a numerical answer. PHIA's 84% accuracy on numerical questions is a proportion \(\hat p\); its standard error is \(\sqrt{\hat p(1-\hat p)/n}\). For an illustrative \(n = 1{,}000\) questions, \(\sqrt{0.84 \times 0.16/1{,}000} = 0.0116\), so a 95% interval is about \(\pm 2.3\) points. A difference between two agents on the same questions should be tested with paired methods (McNemar's test on discordant questions), not by comparing two intervals.

Forecasting claims. A forecast \(\hat y_{T+1:T+H}\) is scored by the mean absolute scaled error

\[ \text{MASE} = \frac{\frac{1}{H}\sum_{h=1}^{H}\lvert y_{T+h} - \hat y_{T+h}\rvert}{\frac{1}{T-m}\sum_{t=m+1}^{T}\lvert y_t - y_{t-m}\rvert}, \]

where the denominator is the in-sample error of the seasonal-naive forecast with period \(m\); MASE below 1 beats that baseline. The ablation logic of Tan et al. is a controlled comparison: hold the input patches, output head, data and training fixed, and compare \(\text{MASE}(\text{with LLM})\) with \(\text{MASE}(\text{LLM removed})\) and \(\text{MASE}(\text{LLM} \to \text{one attention layer})\). The cost side is easy to estimate: a forward pass costs about \(2N\) FLOPs per token for \(N\) parameters, so a multi-billion-parameter frozen backbone costs thousands of times more per patch than a single attention layer with a few hundred thousand parameters. If the ablated models match the full model, the LLM contributes cost but not accuracy.

Worked example · W1On a synthetic 60-day hourly resting-heart-rate series with a daily cycle, a linear forecaster over 96-hour inputs and a 24-hour horizon reaches MASE 0.74 against 0.96 for the seasonal-naive forecast. An LLM-based forecaster for W1 users would have to beat 0.74 by more than the paired bootstrap interval of the difference before its cost is justified.

The code implements one component of each route and the evaluation harness for forecasting claims.

  • Projector (route B) receives W1 window embeddings of shape (T, 256) and a PPG mask of shape (T,), mean-pools only the windows with PPG in blocks of 360 (one hour), and returns soft tokens of shape (T // 360, d_llm) plus the coverage of each block. Coverage is returned so the prompt can state it; an hour with 10% coverage should not be read like an hour with 100%.
  • answer_numeric (route C) stands in for the tool path: the question is mapped to an operation that code executes on the data, the answer states how many days had data, and anything unsupported is refused rather than guessed. In a real agent the LLM writes the code; the principle that numbers come from execution is the same.
  • mase, windows and fit_linear form a minimal forecasting harness. Any LLM forecaster plugs in as one more predictor scored on the same windows.
"""LLMs over wearable data: (1) an encoder + projector that turns W1 embeddings into soft tokens,
(2) a tool-style answer path in which numbers are computed by code and only narrated by the LLM,
(3) an ablation harness for 'LLM as forecaster' claims (Tan et al. 2024 protocol, simplified)."""
import numpy as np

# (1) projector: W1 emits one 256-d embedding per 10-s window; pool to hours, then map to LLM width.
class Projector:
    def __init__(self, d_in=256, d_llm=2048, hidden=1024, seed=0):
        r = np.random.default_rng(seed)
        self.W1 = r.normal(0, d_in ** -0.5, (d_in, hidden)); self.b1 = np.zeros(hidden)
        self.W2 = r.normal(0, hidden ** -0.5, (hidden, d_llm)); self.b2 = np.zeros(d_llm)
    def n_params(self):
        return sum(a.size for a in (self.W1, self.b1, self.W2, self.b2))
    def __call__(self, emb, mask, pool=360):
        """emb: (T, 256) window embeddings; mask: (T,) True where PPG present.
        Returns (T // pool, d_llm) soft tokens and (T // pool,) coverage fractions."""
        T = emb.shape[0] // pool * pool
        e, m = emb[:T].reshape(-1, pool, emb.shape[1]), mask[:T].reshape(-1, pool)
        cov = m.mean(1)
        pooled = (e * m[..., None]).sum(1) / np.maximum(m.sum(1, keepdims=True), 1)  # masked mean
        h = np.maximum(pooled @ self.W1 + self.b1, 0)                                # ReLU MLP
        return h @ self.W2 + self.b2, cov

# (2) tool path: the question is parsed into an operation the code executes exactly.
def answer_numeric(question, daily):
    """daily: dict name -> (D,) array of daily values with NaN for missing days."""
    ops = {"mean": np.nanmean, "max": np.nanmax, "min": np.nanmin}
    for op, f in ops.items():
        for name, arr in daily.items():
            if op in question and name in question:
                return f"{op} {name} = {f(arr):.1f} over {np.isfinite(arr).sum()} days with data"
    return "unsupported question: refuse rather than guess"

# (3) ablation harness: same patches, same head, with and without an expensive middle block.
def mase(y, yhat, y_train, m=24):
    scale = np.mean(np.abs(y_train[m:] - y_train[:-m]))  # in-sample seasonal-naive error
    return np.mean(np.abs(y - yhat)) / scale

def fit_linear(X, Y, lam=1e-2):
    return np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ Y)

def windows(series, L=96, H=24):
    X = np.stack([series[i:i + L] for i in range(len(series) - L - H)])
    Y = np.stack([series[i + L:i + L + H] for i in range(len(series) - L - H)])
    return X, Y

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    P = Projector()
    emb = rng.normal(size=(8640, 256)); mask = rng.random(8640) > 0.38   # W1: 38% missing
    tok, cov = P(emb, mask)
    print("soft tokens", tok.shape, "projector params", P.n_params(), "mean coverage", cov.mean().round(2))
    assert tok.shape == (24, 2048) and abs(cov.mean() - 0.62) < 0.02

    rhr = np.array([58, 57, np.nan, 59, 61, 60, 56.0])
    print(answer_numeric("what was my mean rhr this week", {"rhr": rhr}))
    assert "58.5" in answer_numeric("mean rhr", {"rhr": rhr})
    assert answer_numeric("why am I tired", {"rhr": rhr}).startswith("unsupported")

    t = np.arange(24 * 60)                                  # 60 days of hourly resting-HR-like data
    s = 60 + 5 * np.sin(2 * np.pi * t / 24) + rng.normal(0, 1, t.size)
    tr, te = s[:24 * 45], s[24 * 45 - 96:]
    Xtr, Ytr = windows(tr); Xte, Yte = windows(te)
    W = fit_linear(Xtr, Ytr)
    naive = np.stack([x[-24:] for x in Xte])                 # seasonal naive: repeat last day
    m_lin, m_naive = mase(Yte, Xte @ W, tr), mase(Yte, naive, tr)
    print(f"MASE linear {m_lin:.3f}  seasonal-naive {m_naive:.3f}")
    assert m_lin < m_naive   # any 'LLM forecaster' must beat both at equal data before its cost is justified

The checks confirm a day of W1 windows becomes 24 soft tokens of width 2,048 with a projector of 2,362,368 parameters, matching \(256\,d_h + d_h + d_h\,d_{\text{LLM}} + d_{\text{LLM}}\) at \(d_h = 1{,}024\); mean coverage is about 0.62, consistent with W1's 38% of hours without PPG; the tool path computes 58.5 bpm over the six days with data, skipping the missing day instead of treating it as zero; and the linear forecaster beats seasonal naive.

Debugging tips. For route B, test that the LLM uses the soft tokens: shuffle them between users and confirm that answers change; if they do not, the adapter is being ignored and the model answers from the text prompt alone. For route C, log the generated code with every answer and rerun a sample; nondeterministic code (unsorted dates, time-zone conversions) is a common cause of answers that change between identical questions. For forecasting, always report the ablated variant and seasonal naive in the same table.

Worked example · W1The masked mean matters for W1. Without the mask, an hour with the watch on the charger would be averaged with zero vectors and drift towards the origin of embedding space, which the LLM may read as an unusual physiological state. With the mask and the explicit coverage value, the same hour is represented by the windows that exist and flagged as sparse.

Problem: numerical hallucination. An LLM that reads numbers as text can state a wrong average fluently. Why it matters: in health coaching a wrong number is a wrong recommendation. Root cause: arithmetic over many tokens is not a reliable LLM operation, and long prompts are truncated. Quantified example: PHIA motivates its design by the observation that standard LLMs handle the numerical reasoning required for personal insights poorly; its code-generating agent reached 84% on objective numerical questions (Merrill et al. 2024). Diagnosis: a canary set of numerical questions with exact answers, scored by exact match after unit normalization, broken down by data span (day, week, month). Remedy: the guarded agent loop below, in which every number in the answer must appear in the sandbox output. Cost: two model calls and a sandbox per question. Validation: exact match should be flat across spans; a fall with span points to truncation or serialization, a uniform shortfall to code-generation errors.

A guarded agent loop for numerical wearable questions: planner, sandboxed code, validator, narrator, with a refusal path.Questionuser textPlanner LLMwrites codeSandboxruns on user dataValidatorunits, ranges, coverageNarrator LLMcites computed valuesRefuse or askcoverage too lowLogcode, values, versionEvery number in the answer must appear in the sandbox output; the validator rejects answers that cite anything else.
Fig. A production version of the tool-using pattern. The planner and narrator are language-model calls; the sandbox, validator and log are ordinary software, which is what makes the answer auditable.
MetricDefinitionIllustrative target
Numeric exact matchshare of canary questions whose answer value equals the reference after unit normalizationstable across day, week and month spans
Validator rejection rateshare of answers citing a number absent from sandbox outputlow and stable; a jump signals a prompt or model change
Refusal rateshare of questions refused for low coverage or unsupported operationstracked per question type; a rise after a firmware change signals data loss
Code failure rateshare of generated programs that raise or time outlow; failures retried once, then refused
Soft-token reliance (route B)change in answers when soft tokens are shuffled across userslarge; near zero means the adapter is ignored

Problem: adapter drift. When the signal encoder is retrained (a new W1 version), its embedding space moves and the projector, trained on the old space, maps signals to the wrong regions. Diagnosis: the soft-token reliance metric stays high but answer quality on the canary falls. Remedy: version the encoder and projector together and retrain the projector on every encoder release; keep the previous pair serving until the new pair passes the canary. Trade-off: projector retraining needs paired data each time, which is why route B costs more to maintain than route C.

Problem: unproven forecasting components. An LLM-based forecaster of resting heart rate is proposed for W1. Before deployment, the Tan et al. protocol is run: the same model with the LLM removed and with the LLM replaced by one attention layer, plus seasonal naive and a linear model. Quantified gate: if the LLM variant's MASE improvement over the ablations is smaller than the paired bootstrap interval, the LLM is removed, because at roughly \(2N\) FLOPs per token a multi-billion-parameter backbone multiplies serving cost by orders of magnitude for no accuracy.

Worked incident · W1A W1 coaching assistant uses route C. After an LLM version upgrade, the validator rejection rate rises from about 1% to 7% of answers. Measurements that separate causes: the code failure rate is unchanged, so the sandbox runs; rejected answers cite rounded values ("about 60 bpm") where the sandbox returned 59.6, so the new model paraphrases numbers. Intervention: the narrator prompt is changed to cite values verbatim with a fixed number of decimals, and the validator tolerates rounding to the cited precision. Trade-off: a looser validator could let wrong values through, so tolerance is limited to rounding of the exact sandbox value. Validation: rejection returns near 1% and canary exact match is unchanged; if exact match had fallen as well, the upgrade would have changed planning, not wording, and would be rolled back.

Wearable data are personal and mostly numeric; the next section turns to the modality where language models are native, clinical text, and to how LLMs compare with dedicated EHR models such as W2.

Clinical text and medical LLMs

Language models trained or tuned on clinical text are the most mature health foundation models, and they are increasingly the interface to the others. Clinical text includes admission and progress notes, discharge summaries, radiology and pathology reports and patient messages. It carries what coded data miss: the reasoning behind a diagnosis, social circumstances, uncertainty, and plans.

Before foundation models, clinical prediction from notes meant hand-built features: keyword lists, negation detectors and bag-of-words counts feeding a logistic regression, one pipeline per task. Pretrained language models replaced this with a single encoder that reads text in context.

A health-system language model. Jiang et al. (2023) pretrained NYUTron, a BERT-style model of about 109 million parameters, on 4.1 billion words of inpatient notes from 387,144 NYU Langone patients, then fine-tuned it for 30-day readmission, in-hospital mortality, comorbidity, length of stay and insurance denial. The sequence is: collect a decade of notes; pretrain by predicting masked words; fine-tune one copy per task on labelled admissions; deploy an inference engine connected to the EHR that reads discharge notes once the treating physician signs them. Reported AUCs ranged from 78.7% to 94.9%, up to 14.7% higher than conventional models. In a single-arm prospective test from January to April 2022 the readmission model flagged 2,692 of 3,271 readmissions (recall 82.3%) at a precision of 20.6% (summary of Jiang et al. 2023).

A clinical language model pipeline from unlabelled notes to prospective alerts.Clinical notes4.1B words387,144 patientsPretrainmasked languagemodel, 109MFine-tunereadmission, LOS,mortality, ...Inference enginereads signeddischarge notesAlertsreviewed bycliniciansTRAININGDEPLOYMENTProspective readmission test: 2,692 of 3,271 readmissions flagged (recall 82.3%), precision 20.6%.Numbers from Jiang et al. (2023); the deployment arm ran January to April 2022.
Fig. The NYUTron pipeline (Jiang et al. 2023): one encoder pretrained on a health system's notes, fine-tuned per task, and run inside the EHR on notes as they are signed.

Medical question answering. Singhal et al. (2022) introduced Med-PaLM and the MultiMedQA benchmark for medical question answering (Nature, 2023). Its successor Med-PaLM 2 scored up to 86.5% on MedQA, more than 19 points above Med-PaLM, and physicians preferred its answers to physician-written answers on eight of nine clinical-utility axes in a comparison over 1,066 consumer questions (Singhal et al. 2023, published in Nature Medicine in 2025). Benchmark accuracy does not transfer automatically to use. In a randomized study with 1,298 members of the public across 10 medical scenarios, LLMs alone identified the relevant conditions in 94.9% of cases, but participants using the same LLMs identified them in fewer than 34.5% and did no better than a control group using sources of their choice (Bean et al. 2025). The bottleneck was the human–model interaction, not the model's knowledge.

Structured data: LLM or dedicated model? For coded EHR data the practical question is whether to serialize events as text for an LLM or to use a dedicated EHR foundation model. The Classic evidence favored dedicated models for prediction and LLMs for explanation and interaction. Newer work narrows the gap. Hegselmann et al. (2025) replaced codes with their text descriptions and used general LLM embeddings; across EHRSHOT's 15 tasks these matched CLMBR-T-base, a dedicated EHR model, and generalized somewhat better to UK Biobank, at higher compute cost. Demirel et al. (2026) had an LLM write a "rubric" that restructures serialized records before embedding; on the same 15 tasks this beat both naive serialization and CLMBR-T on average, while CLMBR-T remained stronger on operational outcomes such as ICU transfer and length of stay, and on chest X-ray findings.

Worked example · W2W2's tokens are compact: in its tokenization the median patient takes about 142 tokens and the 95th percentile about 2,078, inside a 4,096-token context. Written as text with code descriptions, an event takes an assumed 12 tokens, so the median patient becomes about 1,150 tokens and the 95th-percentile patient about 17,400, which no longer fits W2-sized contexts and must be truncated or summarized. The text form gains portability (any LLM can read it, and unseen codes have descriptions) and loses compactness.

Mental model. Clinical LLMs are strongest where language is the task: reading notes, explaining, answering questions. For risk prediction from structured histories, dedicated models remain efficient and competitive, and the better LLM pipelines increasingly look like feature extractors that feed ordinary predictors.

Pretraining and fine-tuning. A BERT-style encoder such as NYUTron is pretrained by masked language modeling: a random 15% (the usual BERT setting) of the tokens \(w_t\) in a note are hidden and the model minimizes \(-\sum_{t \in M} \log p_\theta(w_t \mid w_{\setminus M})\), where \(M\) is the masked set. Fine-tuning for a binary outcome \(y\) attaches a linear head to the pooled representation \(h(\text{note})\) and minimizes the cross-entropy \(-[y \log \sigma(\beta^\top h) + (1-y)\log(1-\sigma(\beta^\top h))]\), updating all weights.

Deployment arithmetic. A deployed classifier is judged by recall (sensitivity) \(R = \text{TP}/(\text{TP} + \text{FN})\) and precision (positive predictive value) \(P = \text{TP}/(\text{TP} + \text{FP})\). The number of alerts is \(\text{TP}/P\) and the false alerts per true alert is \((1 - P)/P\).

Worked example · NYUTron prospective testWith \(\text{TP} = 2{,}692\) and 3,271 actual readmissions, recall is \(2{,}692/3{,}271 = 0.823\). At precision 0.2058 the model raised \(2{,}692/0.2058 \approx 13{,}081\) alerts, of which \(13{,}081 - 2{,}692 \approx 10{,}389\) were false, about \(0.7942/0.2058 \approx 3.9\) false alerts per true one. Over the roughly four-month window that is about 3,300 alerts per month for the care team to review. Whether that is acceptable depends on the cost of a review against the cost of a missed readmission, not on the AUC alone.

Serialization budget. Let a patient have \(n\) events, and let a text serialization spend \(r\) tokens per event. The context \(C\) holds \(\lfloor C/r \rfloor\) events. For W2's context \(C = 4{,}096\) and an assumed \(r = 12\), that is 341 events: enough for the median patient (96 events) and about 24% of the 95th-percentile patient's 1,450. W2's own tokenization spends about 1.48 tokens per event (142 tokens for 96 events at the median), so its context holds about 2,770 events, about eight times as many.

Comparing approaches at small label budgets. On EHRSHOT's 15 tasks, averaged AUROC with 40 training examples per task was 0.638 for naive serialization with LLM embeddings, 0.657 for CLMBR-T and 0.717 for a per-patient LLM rubric; with full training data, 0.699, 0.727 and 0.772 (Demirel et al. 2026). The averaged difference of 0.045 to 0.06 AUROC is large for EHR prediction, but an average over tasks hides that the dedicated model kept its advantage on operational outcomes and chest X-ray findings; a per-task paired comparison is the right summary.

Knowledge versus use. Bean et al. separate two probabilities: \(p_{\text{model}}\), the chance the model alone names the right condition (0.949), and \(p_{\text{human+model}}\), the chance a person using the model does (below 0.345). Benchmark scores estimate the first; deployment outcomes depend on the second.

The code implements the plumbing that decides whether an LLM can read structured EHR data at all, and a minimal text-based predictor evaluated correctly.

  • serialize(events) turns (day, code, value) tuples into lines of text, replacing codes with descriptions from a dictionary (a stand-in for a terminology service) and keeping values. Unknown codes fall back to the raw code.
  • fit_context(lines, budget) keeps the most recent lines that fit a token budget, because recent events usually matter most for near-term prediction; it returns how many were dropped so the drop can be logged.
  • embed(text) is a hashed bag-of-words embedder standing in for an LLM embedding model; the pipeline around it (patient-level split, linear head, AUROC) is the same with a real embedder.
  • The last block reproduces the NYUTron deployment arithmetic from the published counts.
"""Clinical text and LLMs over EHR data:
(1) serialize coded events to text (code -> description) and budget the context,
(2) keep the most recent events that fit (truncation from the left),
(3) a text-embedding + linear-head predictor with a patient-level split and AUROC,
(4) the alert arithmetic of a deployed readmission model."""
import numpy as np, re, zlib

DESC = {"E11.9": "type 2 diabetes without complications", "I10": "essential hypertension",
        "LOINC:4548-4": "hemoglobin A1c", "RX:metformin": "metformin 500 mg tablet",
        "N18.3": "chronic kidney disease stage 3", "I50.9": "heart failure, unspecified"}

def serialize(events):
    """events: list of (day, code, value_or_None) sorted by day -> list of text lines."""
    out = []
    for day, code, val in events:
        line = f"day {day}: {DESC.get(code, code)}"
        if val is not None: line += f" = {val}"
        out.append(line + ".")
    return out

def n_tokens(text):                       # proxy: words and punctuation; real tokenizers give more
    return len(re.findall(r"\w+|[^\w\s]", text))

def fit_context(lines, budget):
    """Keep the most recent lines whose total tokens fit in `budget`; return (kept, dropped)."""
    kept, used = [], 0
    for line in reversed(lines):
        t = n_tokens(line)
        if used + t > budget: break
        kept.append(line); used += t
    return kept[::-1], len(lines) - len(kept)

def embed(text, d=512):
    """Stand-in for an LLM text embedder: hashed bag of words, L2-normalized. (str) -> (d,)"""
    v = np.zeros(d)
    for w in re.findall(r"[a-z0-9]+", text.lower()):
        v[zlib.crc32(w.encode()) % d] += 1.0
    return v / max(np.linalg.norm(v), 1e-9)

def auroc(y, s):
    order = np.argsort(s); r = np.empty(len(s)); r[order] = np.arange(1, len(s) + 1)
    pos = y == 1
    return (r[pos].sum() - pos.sum() * (pos.sum() + 1) / 2) / (pos.sum() * (~pos).sum())

def logistic(X, y, lam=1e-2, it=300, lr=0.5):
    w = np.zeros(X.shape[1])
    for _ in range(it):
        p = 1 / (1 + np.exp(-X @ w)); w -= lr * (X.T @ (p - y) / len(y) + lam * w)
    return w

if __name__ == "__main__":
    ev = [(1, "I10", None), (40, "LOINC:4548-4", 7.9), (41, "E11.9", None), (41, "RX:metformin", None)]
    lines = serialize(ev); print(lines)
    per_event = np.mean([n_tokens(l) for l in lines]); print("tokens/event ~", round(per_event, 1))
    # W2 p95 patient: 1,450 events at ~12 tokens each vs a 4,096-token context
    assert 1450 * 12 > 4096
    kept, dropped = fit_context(lines * 400, budget=4096)
    print("kept", len(kept), "dropped", dropped)
    assert sum(n_tokens(l) for l in kept) <= 4096 and kept[-1] == lines[-1]

    # synthetic notes: outcome more likely when heart failure / CKD terms appear
    rng = np.random.default_rng(0); pids = np.arange(2000)
    texts, y = [], []
    for p in pids:
        hf, ckd = rng.random() < 0.2, rng.random() < 0.3
        t = " ".join(rng.choice(list(DESC.values())[:4], 6))
        t += (" heart failure unspecified" if hf else "") + (" chronic kidney disease" if ckd else "")
        texts.append(t); y.append(int(rng.random() < 0.05 + 0.35 * hf + 0.15 * ckd))
    X, y = np.stack([embed(t) for t in texts]), np.array(y)
    test = pids % 5 == 0                                    # split by patient id, never by note
    w = logistic(X[~test], y[~test])
    a = auroc(y[test], X[test] @ w); print("AUROC", round(a, 3))
    assert a > 0.65

    # NYUTron prospective numbers (Jiang et al. 2023): recall 82.30%, precision 20.58%
    tp, pos, prec = 2692, 3271, 0.2058
    flagged = tp / prec; fp = flagged - tp
    print(f"recall {tp/pos:.4f} flagged {flagged:,.0f} false alerts {fp:,.0f} per true {fp/tp:.2f}")
    assert abs(tp / pos - 0.8230) < 1e-3

The checks: the 95th-percentile W2 patient cannot fit a 4,096-token context at 12 tokens per event; truncation keeps the most recent event and respects the budget; the toy predictor learns the planted signal (AUROC about 0.69) on a split by patient identifier; and recall from the published counts is 0.823 with about 3.9 false alerts per true alert. The word-level token proxy gives about 8 tokens per event on these short descriptions; subword tokenizers and longer descriptions push this up, which is why 12 is used as the working assumption.

Debugging tips. Split by patient before anything else: a note-level split lets near-duplicate copy-forwarded notes from the same patient appear in training and test sets and inflates AUROC. Log the number of dropped events per patient; if prediction quality differs between patients with and without truncation, the context is the bottleneck. Check the share of codes without descriptions: each one is a token an LLM reads as an opaque string.

Worked example · W2Applied to W2's 2 million patients at 12 tokens per event, the corpus of 310 million events becomes about 3.7 billion text tokens, roughly eight times W2's own token count of about 0.46 billion. Every downstream LLM call on serialized records pays that factor in compute.

Problem: alert burden. A note-based readmission model at NYUTron's operating point produces about 3.9 false alerts per true one. Why it matters: care-management teams have a fixed number of review slots, and an alert stream they cannot work through is ignored. Root cause: readmission is a low-prevalence outcome and the threshold was set for high recall. Quantified example: about 13,000 alerts over the four-month prospective period, roughly 3,300 per month. Diagnosis: plot precision and alerts per month against threshold, alongside reviewer capacity. Remedy: set the threshold so alert volume equals capacity, then rank within capacity by predicted risk; or tier the alerts, with only the top tier going to humans. Cost: lower recall. Validation: at the new threshold, the share of reviewed alerts that reviewers judge actionable should rise and the number of missed readmissions among unreviewed patients should be measured, not assumed.

Problem: note drift. Note-based models read text whose form changes with templates, documentation tools and, increasingly, AI-drafted notes. Diagnosis: monitor the distribution of note length and of frequent template phrases, and AUROC on a rolling monthly cohort. Remedy: continued pretraining on recent notes and recalibration; reject inputs from unseen templates until they are reviewed. Validation: AUROC on the most recent month returns to the reference level.

Worked incident · W2A hospital runs W2 for 30-day readmission risk (AUROC 0.71) and pilots an LLM-on-serialized-records alternative for the same task. In offline tests the LLM pipeline looks better on recent admissions. Measurements: the comparison used a random split by admission, so earlier admissions of the same patients, with largely copy-forwarded histories, appeared in both training and test sets; under W2's patient-level split with the temporal holdout (train up to 2022, test 2024), the advantage disappears. A second measurement shows that 22% of test patients exceed the LLM's context after serialization and are truncated, and that the LLM pipeline's AUROC on those patients is lower than W2's. Decision: keep W2 for prediction and use the LLM to generate the explanation shown with each alert, from W2's top contributing events. Trade-off: two systems to maintain. Validation: alert explanations are scored by reviewers for correctness against the record; an explanation that cites an event absent from the record counts as a failure, and the pilot proceeds only if the failure rate stays below an agreed bound. The 22% figure is illustrative.

Problem: the human–model gap. Bean et al. found that people using LLMs identified conditions far less often than the LLMs did alone. Production implication: evaluations of patient-facing or clinician-facing assistants must include the human in the loop, with task completion measured on realistic scenarios, not only model accuracy on benchmark questions. Privacy is the other constraint specific to text: notes contain names and free-text identifiers, so training corpora are de-identified and model outputs are screened for leaked identifiers before release.

Text, codes and wearable signals each carry part of the picture. The final section asks when combining them helps, and by how much.

Fusing EHR and wearables

Fusion combines information from two or more modalities in one prediction. For health foundation models the most common pairing is the clinical record, which sees a patient at visits, with wearable data, which sees the same person continuously between visits. Fusion usually helps, but not always in the way the most complex model predicts.

Where to fuse. There are three places to combine modalities. Early fusion concatenates features from both sources and trains one model; it is simple and lets the model learn interactions, but it needs a rule for patients missing one modality. Intermediate fusion runs a foundation model per modality and combines their embeddings with a joint head or cross-attention; it reuses pretrained models. Late fusion trains a separate predictor per modality and combines their scores; it degrades gracefully when one modality is missing because the other predictor still works.

Early, intermediate and late fusion of EHR and wearable data.Early fusionEHRcodes, labsWearablePPG, stepsIntermediate fusionEHRcodes, labsWearablePPG, stepsLate fusionEHRcodes, labsWearablePPG, stepsConcatenate features+ missingness indicatorOne modelprobe or GBMEHR FMembeddingWearable FMembeddingJoint head or cross-attentionEHR modelrisk scoreWearable modelrisk scoreCombine scoresweighted logitssimple; one model sees allreuses FMs; learns interactionsrobust when a modality is missingAll three need the same split discipline: patient-level, and no wearable data after the prediction time.
Fig. Three places to fuse EHR and wearable information. The All of Us study of Wang et al. (2025) compared three strategies of this kind; the Apple study of Erturk et al. (2025) concatenated two embeddings and fit a linear probe.

Two results worth remembering. First, from Apple's Heart and Movement Study: Erturk et al. (2025) trained a foundation model of behavioral data (WBM) on about 2.5 billion hours of hourly aggregates from 161,855 participants. Concatenating its embeddings with those of an earlier PPG foundation model and fitting a linear probe gave the best result on 42 of 47 medical-history and medication outcomes. The combination reduced age-prediction error to 2.46 years against 3.67 for behavior alone and 2.89 for PPG alone, and raised pregnancy detection AUROC to 0.921 from 0.864 and 0.873. The two models see different things: PPG captures cardiovascular physiology, behavior captures activity, sleep and routine.

Second, from the All of Us program: Wang et al. (2025) compared EHR encodings (simple OMOP concept indicators and the CEHR-GPT foundation model) and wearable encodings (hand-crafted Fitbit summaries and MOMENT time-series embeddings) under three fusion strategies. Adding Fitbit features improved prediction of all ten conditions studied, by about 8.9% AUROC on average, with the largest gains for type 2 diabetes, hyperlipidemia and hypertension and the smallest for heart failure. Yet CEHR-GPT's advantage over simple indicators, present in 8 of 10 outcomes with EHR alone, shrank to 5 of 10 and an average of 0.3% once wearables were added, and hand-crafted wearable statistics beat MOMENT embeddings on all ten outcomes. Complementary information matters more than representational sophistication.

Worked example · W1 and W2Assume a linked cohort in which W1 participants also have W2-style records. W2 predicts 1-year mortality with AUROC 0.89. Suppose a W1-based wearable score alone reaches an assumed 0.75. If the two scores carried independent information, the combined AUROC under a simple model would be about 0.92; if they largely measured the same underlying frailty, combining them could add nothing. The gain is set by how much the wearable adds given the record, not by how good either model is alone.

Practical hazards. Fusion multiplies the data problems of each modality. Not every patient wears a device: W1's own data have 38% of hours without PPG, and owners of wearables differ from non-owners in age, income and health. In the All of Us depression example, 8,477 participants had linked Fitbit and EHR data; 3,049 entered the analytic cohort and 2,430 remained after quality control. Time alignment can leak the future: wearable data recorded after the prediction time must be excluded, exactly as future codes are excluded from EHR features.

Mental model. Fusion pays off when the second modality measures something the first does not, and when it is present for the patients who matter. A sophisticated encoder of redundant information adds little; a simple summary of complementary information can add much.

Information view. Let \(Y\) be the outcome, \(X_e\) the EHR representation and \(X_w\) the wearable representation. The best achievable gain from fusion is governed by the conditional mutual information \(I(Y; X_w \mid X_e)\): the information about \(Y\) that \(X_w\) carries beyond \(X_e\). It is zero when the wearable is redundant given the record, however predictive it is on its own (\(I(Y; X_w)\) can be large while \(I(Y; X_w \mid X_e) = 0\)).

A closed-form model of the gain. Assume each modality yields a score that is Gaussian within each class with equal variance, and that the two scores' within-class noise has correlation \(\rho\). The separation (in standard deviations) of score \(i\) between cases and controls is \(d_i\), and AUROC relates to it by \(\text{AUROC}_i = \Phi(d_i/\sqrt 2)\), where \(\Phi\) is the standard normal distribution function, so \(d_i = \sqrt 2\,\Phi^{-1}(\text{AUROC}_i)\). The optimal linear combination has separation

\[ d_{\text{fused}}^2 = \frac{d_1^2 + d_2^2 - 2\rho\, d_1 d_2}{1 - \rho^2}, \qquad \text{AUROC}_{\text{fused}} = \Phi\!\left(d_{\text{fused}}/\sqrt 2\right). \]

With \(\rho = 0\) the separations add in quadrature. The gain is zero exactly when \(\rho = d_2/d_1\): the weaker score is then fully explained by the stronger one's noise. Above that correlation the gain returns, because the optimal combination uses the second score to cancel noise in the first.

Worked example · W1 and W2W2's mortality AUROC of 0.89 gives \(d_1 = \sqrt 2 \times \Phi^{-1}(0.89) = 1.414 \times 1.227 = 1.735\). An assumed wearable AUROC of 0.75 gives \(d_2 = 1.414 \times 0.674 = 0.954\). Independent scores: \(d_{\text{fused}} = \sqrt{1.735^2 + 0.954^2} = \sqrt{3.010 + 0.910} = 1.980\), so \(\text{AUROC} = \Phi(1.400) = 0.919\), a gain of about 0.03. At \(\rho = d_2/d_1 = 0.55\) the fused AUROC is 0.89, no gain. This is one reading of the All of Us result: a richer EHR encoder and a wearable signal can be partly redundant, so the encoder's advantage shrinks when the wearable is added.
Predicted fused AUROC as the correlation between the EHR and wearable scores rises.0.860.880.900.920.940.00.20.40.60.8correlation of the two scores within each class (rho)fused AUROCEHR alone 0.89independent: 0.919rho 0.55: no gainhigh correlation: thesecond score cancels noise
Fig. Equal-variance Gaussian model of fusion with an EHR score of AUROC 0.89 and a wearable score of AUROC 0.75 (illustrative). The gain is largest when the scores are independent, vanishes near rho 0.55 (where rho equals the ratio of the two separations), and returns only at high correlation, where the optimal combination exploits the wearable score as a correction term.

Missing modalities. If a fraction \(\pi\) of patients has wearable data, a late-fusion model's population AUROC is not a simple weighted average of the two subgroup AUROCs, because it also ranks patients across subgroups. Reporting AUROC separately for patients with and without the modality, plus calibration within each subgroup, is the reliable summary.

Testing a gain. The fused and single-modality models are evaluated on the same patients, so their AUROCs are correlated. The paired bootstrap resamples patients \(B\) times with replacement, recomputes \(\Delta = \text{AUROC}_{\text{fused}} - \text{AUROC}_{\text{single}}\) on each resample, and reports the 2.5th and 97.5th percentiles. A gain is supported when the interval excludes zero and is larger than the smallest difference that would change a clinical decision.

The code builds a synthetic linked cohort with W2-like and W1-like embeddings, fits an EHR-only model and an early-fusion model, and tests the gain. It also checks the equal-variance Gaussian formula for the fused AUROC.

  • fused_auc(a1, a2, rho) converts AUROCs to separations, combines them, and converts back.
  • early_features(e_ehr, e_wear, has_wear) receives arrays of shape (N, 32), (N, 32) and (N,); it zeroes the wearable block for patients without data and appends a missingness indicator, giving (N, 65). The indicator lets the model learn a different intercept for patients without wearables instead of treating zeros as measurements.
  • ridge fits a linear score (a stand-in for a linear probe on frozen embeddings); paired_bootstrap resamples patients jointly for both models.
"""Fusing EHR (W2-style) and wearable (W1-style) embeddings for one outcome.
Late fusion with a missing-modality fallback, early fusion by concatenation + indicator,
the equal-variance Gaussian prediction of the fused AUROC, and a paired bootstrap of the gain."""
import numpy as np
from math import erf, sqrt
from statistics import NormalDist

Phi, Phiinv = NormalDist().cdf, NormalDist().inv_cdf

def auc_from_dprime(d):   return Phi(d / sqrt(2))
def dprime_from_auc(a):   return sqrt(2) * Phiinv(a)

def fused_auc(a1, a2, rho=0.0):
    """Two Gaussian scores with separations d1, d2 and noise correlation rho, optimally combined:
    d^2 = (d1^2 + d2^2 - 2 rho d1 d2) / (1 - rho^2)."""
    d1, d2 = dprime_from_auc(a1), dprime_from_auc(a2)
    return auc_from_dprime(sqrt((d1**2 + d2**2 - 2 * rho * d1 * d2) / (1 - rho**2)))

def auroc(y, s):
    order = np.argsort(s); r = np.empty(len(s)); r[order] = np.arange(1, len(s) + 1)
    pos = y == 1
    return (r[pos].sum() - pos.sum() * (pos.sum() + 1) / 2) / (pos.sum() * (~pos).sum())

def ridge(X, y, lam=1.0):
    X1 = np.c_[X, np.ones(len(X))]
    return np.linalg.solve(X1.T @ X1 + lam * np.eye(X1.shape[1]), X1.T @ y)

def predict(w, X): return np.c_[X, np.ones(len(X))] @ w

def early_features(e_ehr, e_wear, has_wear):
    """Concatenate; zero the wearable block where missing and add an indicator column. Shapes:
    (N, d1), (N, d2), (N,) -> (N, d1 + d2 + 1)."""
    return np.c_[e_ehr, e_wear * has_wear[:, None], has_wear.astype(float)]

def paired_bootstrap(y, s_a, s_b, B=500, seed=0):
    """95% interval for AUROC(s_b) - AUROC(s_a), resampling patients (rows) jointly."""
    r = np.random.default_rng(seed); n = len(y); d = []
    while len(d) < B:
        i = r.integers(0, n, n)
        if 0 < y[i].sum() < n: d.append(auroc(y[i], s_b[i]) - auroc(y[i], s_a[i]))
    return np.percentile(d, [2.5, 97.5])

if __name__ == "__main__":
    print("fused AUROC, independent:", round(fused_auc(0.89, 0.75), 3),
          " rho=0.5:", round(fused_auc(0.89, 0.75, 0.5), 3))
    assert abs(fused_auc(0.89, 0.75) - 0.919) < 0.002

    rng = np.random.default_rng(0); N = 8000
    y = (rng.random(N) < 0.1).astype(int)
    e_ehr = rng.normal(size=(N, 32)); e_ehr[:, 0] += 1.73 * y         # d' ~ AUROC 0.89
    e_wear = rng.normal(size=(N, 32)); e_wear[:, 0] += 0.95 * y       # d' ~ AUROC 0.75
    has = rng.random(N) > 0.38                                       # W1-style missingness
    tr = np.arange(N) % 4 != 0; te = ~tr                              # patient-level split
    s_ehr = predict(ridge(e_ehr[tr], y[tr]), e_ehr[te])
    Xe = early_features(e_ehr, e_wear, has)
    s_early = predict(ridge(Xe[tr], y[tr]), Xe[te])
    a0, a1 = auroc(y[te], s_ehr), auroc(y[te], s_early)
    a_has = auroc(y[te][has[te]], s_early[has[te]])
    lo, hi = paired_bootstrap(y[te], s_ehr, s_early)
    print(f"EHR only {a0:.3f}  fused (all) {a1:.3f}  fused (wearable present) {a_has:.3f}  "
          f"gain 95% CI [{lo:.3f}, {hi:.3f}]")
    assert a1 > a0 and lo > 0 and a_has > a1

The checks: the formula gives 0.919 for independent scores and about 0.89 at \(\rho = 0.5\) (the exact no-gain point is \(\rho = 0.55\)); in the synthetic cohort, with the EHR signal planted at the separation of AUROC 0.89 and the wearable at 0.75, the EHR-only model reaches 0.883, early fusion 0.899 over all test patients and 0.909 among those with wearable data, and the paired bootstrap interval for the gain, about [0.006, 0.025], excludes zero. The gain over all patients is smaller than among patients with data because 38% of the cohort has no wearable signal, mirroring W1's missingness.

Debugging tips. Always report the subgroup with the modality present separately; a pooled gain can hide a large gain in a minority or a loss in the majority. Check the split: the code splits by patient index, and with real data the wearable windows must also end before the prediction time. Fit the single-modality and fused models on exactly the same patients; dropping patients without wearables from the fused model only would compare different populations.

Worked example · W1 and W2Replacing early fusion by late fusion in this code amounts to fitting two ridge models and adding their scores with weights fitted on a validation fold; for patients without wearable data the wearable score is set to its mean, so the EHR score alone ranks them. With independent planted signals both strategies reach similar AUROC; late fusion's advantage appears when the wearable model must be retrained or replaced without touching the EHR model.

Problem: coverage and selection. A fused model is deployed to all patients, but only some have linked wearable data, and they are not a random subset. Why it matters: the headline gain is measured among patients with data, while decisions are made for everyone. Root cause: wearable ownership and consent correlate with age, income and health; quality control removes more data from some groups (in Wang et al.'s depression example, 2,430 of 8,477 linked participants, about 29%, remained after cohort selection and quality control). Quantified example: if 40% of a hospital's patients have usable wearable data and the gain among them is 0.03 AUROC, the population benefit is concentrated in that 40%, and the other 60% receive exactly the EHR model. Diagnosis: a dashboard with coverage by age band, sex and payer; AUROC and calibration error within coverage strata. Remedy: report and monitor by stratum; use late fusion or a missingness indicator so that uncovered patients are scored by an unchanged EHR model; set per-stratum thresholds if calibration differs. Validation: W2's calibration error of 0.03 should hold within each coverage stratum; a stratum with error far above it needs recalibration before the fused score is used there.

MonitorWhyAction when it moves
Wearable coverage rate, by stratumsets who receives the fused scorere-estimate expected benefit; check consent and sync pipelines
Fused minus EHR-only AUROC, by stratumthe gain the fusion is deployed forfall to zero suggests redundancy or a broken wearable feed
Calibration error, by stratumthresholds assume calibrated risksrecalibrate per stratum
Latest wearable timestamp vs prediction timedetects look-ahead leakage and stale feedsblock scoring if data postdate the prediction time

Problem: choosing the representation. Wang et al. found that hand-crafted Fitbit summaries beat MOMENT embeddings on all ten outcomes, by about 4% AUROC on average, and that CEHR-GPT's EHR advantage largely vanished after fusion. Remedy: treat representation choice as an experiment per modality, with simple summaries as a required baseline; adopt the foundation-model embedding only where it beats the summary in a paired comparison on the fused task. Cost: more experiments. Validation: the paired bootstrap interval for (foundation-model embedding minus summary) excludes zero on the fused task.

Worked incident · W1 and W2A health system deploys W2 plus a W1 embedding, fused by concatenation without a missingness indicator, for 1-year mortality. Offline, on linked patients, AUROC rises from 0.89 to 0.91. In production, overall AUROC falls below the EHR-only model. Measurements: coverage is 35% instead of the 60% in the development cohort, because a phone-app update broke data sync for one platform; patients with missing wearables receive zero vectors, which the model reads as an unusual physiological state, so their risks are shifted and their calibration error rises well above 0.03. Intervention: add the missingness indicator and retrain; route patients without recent wearable data to the EHR-only score; alert on coverage dropping below a set band. Trade-off: the indicator lets the model learn coverage-related risk, which can encode access to devices rather than health, so its coefficient is reviewed for plausibility. Validation: AUROC and calibration within the no-wearable stratum match the EHR-only model, and AUROC in the covered stratum returns to its offline level; if the covered stratum still underperforms, the wearable feed itself has shifted and W1's input monitors are checked next. All numbers in this incident are illustrative.

Fusion closes the loop of this chapter: language models provide the interface, modality-specific foundation models provide the measurements, and the value of combining them is an empirical question answered per task, per population and per data feed. The next chapter turns to the adaptation and evaluation methods that make such answers trustworthy.

Adaptation and Evaluation

A pretrained health foundation model produces representations, not decisions. Adaptation is the step that turns a general representation into a tool for one clinical question; evaluation is the evidence that the tool works for the people and settings where it will be used. The two belong together because the choice of adaptation method changes what must be evaluated: a frozen encoder with a small head can only fail in a few ways, whereas a fully fine-tuned model can also forget what pretraining taught it.

The right adaptation method depends mostly on two quantities: how many labelled examples exist, and how far the target data lies from the pretraining distribution. In rough order of cost the options are a frozen linear probe, few-shot or in-context use, parameter-efficient fine-tuning such as LoRA, full fine-tuning, continued pretraining, and distillation into a smaller model for deployment. The first section covers these methods and when training from scratch is the better choice.

Evaluating a health foundation model answers five questions. Does it help across many tasks? Does it help when labels are scarce? Does it survive a change of site, device or time? Is it equally good for every group? Are its probabilities trustworthy? Each has a standard protocol, covered in the second and third sections, and one failure can invalidate all five: leakage, where information from the test set reaches training. The final section covers patient-level and temporal splits, the main defence.

Decision flow for adapting or training a health model.New task, new dataIs there a usable FM for this modalityand a similar population or device?Pretrain your ownif unlabeled data is plentiful;else supervised from scratchHow many labels per class?Frozen + probelinear / kNN;in-context for TSFMsLoRA or LP-FTsmall trainablefraction of weightsFull fine-tuneor continued pretrainingon in-domain dataEdge or power budget?distill the adapted FMinto a small studentnoyestenshundreds+many, or big shift
Fig. A decision flow for adapting health foundation models. The label thresholds are rough guides, not rules; EHRSHOT and Med-BERT suggest the pretrained advantage is largest below about a hundred labels per class. Distillation is orthogonal and applies after any branch.

The three reference workloads appear throughout: W1 (a wearable PPG encoder adapted by linear probe), W2 (a generative EHR model evaluated with patient-level and temporal splits) and W3 (a sleep model transferred from the laboratory to a wearable). The mental model for the chapter: adaptation is cheap, and evaluation is where the effort and most of the risk lie.

Formally, a pretrained encoder \(f_\theta : \mathcal{X} \to \mathbb{R}^d\) maps an input (a 10-second PPG window, a patient history up to an index time, an overnight recording) to a \(d\)-dimensional embedding. Adaptation chooses a head \(g_\phi\) and a subset of parameters to update so that the composite \(g_\phi \circ f_\theta\) minimizes a task loss on \(n\) labelled examples drawn from a source distribution \(P_S\). The methods differ in which parameters move: only \(\phi\) (probing), \(\phi\) plus a low-rank set \(\Delta\) (parameter-efficient fine-tuning), or \(\phi\) and all of \(\theta\) (full fine-tuning).

Evaluation estimates the expected loss, or a ranking metric such as AUROC, under the target distribution \(P_T\) where the model will be deployed:

\[ R_T(g_\phi \circ f_\theta) = \mathbb{E}_{(x,y) \sim P_T}\big[\ell\big(y, g_\phi(f_\theta(x))\big)\big]. \]

Every topic in this chapter is a way that the estimate \(\hat R\) computed on a test set can differ from \(R_T\). Label scarcity makes \(\hat R\) noisy because \(n\) is small. Distribution shift means the test set was drawn from \(P_S\) rather than \(P_T\). Subgroup analysis asks whether \(R_T\) differs across groups even when the average is good. Calibration asks whether predicted probabilities equal conditional frequencies. Leakage makes \(\hat R\) optimistic because test examples are not independent of training. The quantities used in the worked examples come from the reference workloads: W1's 256-dimensional embedding and probe on 5,000 labelled participants (AFib AUROC 0.93 against 0.88 from scratch), W2's mortality AUROC 0.89 and ECE 0.03 under a train-through-2022, test-in-2024 split, and W3's staging κ of 0.78 in the laboratory and 0.62 on a wearable.

The code in this chapter is organized around one idea: every evaluation decision is fixed in a specification before any model is scored, and the specification is checked automatically. The snippet below defines such a specification as a frozen dataclass. Its check method rejects the most common protocol errors: splitting by window or visit rather than by person, a test period that does not follow the training period, no non-foundation-model baseline, and no calibration metric. Later sections implement each piece: probes and adapters, \(k\)-shot curves with patient-level confidence intervals, calibration and subgroup reports, and split and leakage checks.

from dataclasses import dataclass, field

@dataclass(frozen=True)
class EvalSpec:
    """One downstream task, fixed before any model is scored."""
    task: str                    # e.g. "w2_mortality_1y"
    workload: str                # "W1" | "W2" | "W3"
    split_unit: str              # "patient" or "participant"; never "window" or "visit"
    train_end: str               # last date allowed in training data (ISO)
    test_start: str              # first date of the test period (ISO)
    adaptation: str              # "probe" | "lora" | "lp-ft" | ...
    ks: tuple = (1, 2, 4, 8, 16, 32, 64, 128)
    metrics: tuple = ("auroc", "auprc", "ece", "brier")
    groups: tuple = ("sex", "age_band", "site")
    baselines: tuple = ("count_gbm",)

    def check(self):
        assert self.split_unit in ("patient", "participant"), "split by person, not by window"
        assert self.train_end < self.test_start, "test period must follow training period"
        assert self.baselines, "at least one non-FM baseline"
        assert "ece" in self.metrics or "brier" in self.metrics, "report calibration"
        return True

if __name__ == "__main__":
    spec = EvalSpec("w2_mortality_1y", "W2", "patient", "2022-12-31", "2024-01-01", "probe")
    assert spec.check()
    try:
        EvalSpec("w1_afib", "W1", "window", "2022-12-31", "2024-01-01", "probe").check()
    except AssertionError as e:
        print("rejected:", e)
    print("ok")

Output: rejected: split by person, not by window followed by ok. Storing the specification next to the results, with the model version, makes every reported number reproducible and makes changes to the protocol visible in review.

In production, adaptation and evaluation form a release pipeline. Each candidate (a new head, adapter or fine-tuned checkpoint) passes a sequence of gates, and each gate produces an artefact that a reviewer can inspect: an audit report, a metrics table with intervals, a subgroup table. Pretraining happens rarely; adaptation and re-evaluation happen whenever a site, device, coding system or population changes, so the evaluation pipeline runs far more often than the pretraining job and deserves the same engineering care.

Release gates for an adapted health model: each candidate passes leakage, suite, shift and subgroup checks before a shadow deployment; production monitoring feeds the next candidate.Candidateadapter or headversionedLeakage auditids, index time,pretrain overlapSuite + k-shotall tasks, CIs,baselinesShift + groupssite, device, time;calibrationShadow runlive inputs,no actionsReleasePCCP-boundedchangeA failed gate returns the candidate with the failing metric attachedProduction monitoringinput drift, calibration on labelled follow-up,subgroup metrics, alert thresholdsEach arrow carries an artefact: a model version, an audit report, a metrics table with intervals.
Fig. Evaluation as a release pipeline. The gates correspond to the sections of this chapter; PCCP refers to a predetermined change control plan, the mechanism the US FDA uses to pre-authorize bounded model updates.

Two external requirements shape the pipeline. Reporting guidelines such as TRIPOD+AI (Collins et al. 2024, a 27-item checklist published in the BMJ) set what a published evaluation must state. For regulated devices in the United States, the FDA's final guidance on predetermined change control plans (December 2024) allows a manufacturer to pre-authorize bounded model updates; a plan describes the planned modifications, the protocol for developing, validating and implementing them, and an impact assessment (Foley 2025). A pipeline that already emits versioned audit and metric artefacts at each gate can satisfy both with little extra work. The sections that follow give the production failure modes and remedies for each gate.

Probing, fine-tuning, PEFT, few-shot, distillation, from scratch

Adaptation methods differ in one respect above all: how much of the pretrained model they allow to change. The less that changes, the fewer labels are needed and the less can go wrong; the more that changes, the further the model can move toward a target that differs from pretraining. Six methods cover practice.

Six adaptation methods ordered by how much of the model they change, with what is trained and the trainable parameter count for the W1 encoder.Linear probeencoder frozentrain: head onlyW1: 257 per taskkNNencoder frozentrain: nothingstore embeddingsIn-contextmodel frozenchoose the contextTSFMs, generatorsLoRA / PEFTbackbone frozentrain: adaptersW1: ~0.2M (assumed)LP-FT / full FTall weights trainprobe first, then FTW1: 50MContinued PTself-supervisedon in-domain datathen probe or FTLESS OF THE MODEL CHANGESMORE OF THE MODEL CHANGESlabels needed, compute, and risk of forgetting pretrained features all grow to the rightDistillation (orthogonal)after any branch: train a small studentto match the adapted teacher for deploymentFrom scratch (the alternative)supervised model or own pretraining;run it as the baseline before adapting
Fig. The adaptation spectrum. Highlighted boxes are the usual first choices: a linear probe when labels are few, LoRA when the representation must move. W1 counts: a probe on the 256-d embedding has 257 parameters per binary task; the LoRA count assumes rank 8 on two projections in each of 12 width-512 attention layers, an assumption about W1's architecture made for illustration.

Linear probe. A linear probe freezes the encoder, computes an embedding for each labelled example, and fits a logistic regression (for a binary label), a Cox model (for time to event) or a ridge regression (for a continuous target) on those embeddings. It is the cheapest adaptation, the most honest measure of representation quality, and often the best choice for small clinical datasets. Its inputs are embeddings and labels; its output is a weight per embedding dimension plus a bias. Because the head is linear, a good probe result means the information is already laid out in the representation, not learned by the head. Most papers in this book (SleepFM, the Apple models, EHRSHOT) report probes as their primary result. The regularization strength must be chosen by cross-validation grouped by patient, so that no patient contributes to both the fitting and the scoring folds. Limitation: a probe cannot fix a representation that lacks the needed information.

Worked example · W1W1's encoder outputs a 256-dimensional embedding. A probe for atrial fibrillation therefore has 257 trainable parameters, fitted on 5,000 labelled participants. It reaches AUROC 0.93, against 0.88 for a supervised model of the same task trained from scratch on the same 5,000 participants. Age regression (MAE 6.1 years) and resting heart rate (MAE 2.4 bpm) use ridge probes on the same frozen embeddings, so three tasks share one encoder pass.

k-nearest neighbours. A kNN classifier on normalized embeddings is a useful second check, because it needs no training: a query is labelled by the majority among its nearest labelled examples. It also exposes whether neighbours share clinical labels or merely share a site or device; if a query's nearest neighbours come mostly from the same hospital regardless of label, the representation encodes provenance strongly.

Full fine-tuning and LP-FT. Fine-tuning updates all weights by gradient descent on the task loss. It wins when labels are plentiful, but it can damage what pretraining learned. Kumar et al. (2022) showed that fine-tuning with a randomly initialized head can distort pretrained features and underperform linear probing out of distribution: across ten distribution-shift benchmarks, fine-tuning averaged about 2% higher accuracy than probing in distribution but about 7% lower out of distribution. The mechanism is that early gradients from a random head are large and essentially arbitrary, so they move the features that in-distribution examples use while leaving features for unseen inputs behind. Their remedy, LP-FT, fits a linear probe first and then fine-tunes the whole model starting from that head; it was about 1% better than fine-tuning in distribution and about 10% better out of distribution. For health models that will meet new sites and devices, LP-FT is a cheap default. The gain from full fine-tuning can be large when the target differs from pretraining: for the GPT-PPG model, Chen et al. (2025) reported that unfreezing the backbone reduced heart-rate MAE on one benchmark from 9.02 to 2.72 bpm compared with a frozen backbone and trained head, and improved AF F1 from 0.762 to 0.823.

Parameter-efficient fine-tuning (PEFT). PEFT trains a small number of new parameters while freezing the backbone. The most widely used method is LoRA (Hu et al. 2022), which adds to selected weight matrices a trainable update constrained to be low rank, that is, the product of two thin matrices. For a 768 × 768 attention projection, rank 8 trains about 12 thousand parameters instead of 590 thousand. The practical benefits in health: one backbone can serve many sites or tasks with a small adapter each; adapters can be trained where the data lives and shipped without the data; and the frozen backbone limits forgetting. TimesFM's repository added a LoRA fine-tuning example in 2026 (TimesFM repository). Limitation: the rank caps how far the model can move, so a large shift in input statistics may need full fine-tuning or continued pretraining.

Few-shot and in-context use. "Prompting" a time-series foundation model means choosing what goes into its context; no weights change. For a zero-shot forecaster, the levers are the context length (more history usually helps until it reaches past a regime change, such as a new medication), which related series and covariates to include (supported by Chronos-2 and by TimesFM 3.0), and how to aggregate sampled forecasts into quantiles. For generative EHR models, the prompt is the patient's history, and the "question" is the outcome counted in simulated futures. Few-shot classification with a frozen encoder (a probe trained on \(k\) examples per class) is a separate regime with its own benchmark protocol, the EHRSHOT \(k\)-shot curves being the template.

Distillation. Distillation trains a small student model to reproduce the outputs or embeddings of a large teacher, which matters when models must run on a watch or within a hospital's inference budget. Apple's accelerometer encoder is a cross-modal example: the student sees only low-power accelerometry but learns to match PPG embeddings from the same time window. Abbaspourazad et al. (2024) distilled using about 20 million minutes of unlabelled data from about 172 thousand participants; the accelerometer embeddings retrieved the matching PPG embedding with 99.2% top-1 accuracy on unseen data, and the distilled encoders outperformed accelerometer-only self-supervised or supervised encoders by 23–49% on heart-rate and heart-rate-variability prediction. The same idea applies to costly generative EHR simulation: distill the simulated risk estimates into a direct predictor for the outcomes needed often. Small models can also be designed for the device from the start: Lee et al. (2025) reported a 0.31-million-parameter PPG model (3.6 MB) pretrained on 80 thousand hours that matched or surpassed baselines of 110 million parameters across ten classification tasks.

When to train from scratch. Pretraining a new model is justified less often than it is attempted. The decision turns on four questions:

QuestionAdapt an existing FM if…Pretrain or train from scratch if…
Modality matchAn FM exists for the signal, sampling rate and channel setThe sensor or coding system is novel (new device, unusual montage)
Data rightsWeights are licensed for the intended use (check non-commercial terms)No usable licence; consent forbids sending data to a vendor
Unlabelled volumeThousands of hours or patients are available105+ hours or millions of patients are available in-domain
EvidenceA probe on the FM beats the supervised baselineHand-crafted features or GBMs match the FM (then neither may be needed)

Table. Adapt versus pretrain. The last row is the one most often skipped: run the simple baseline first.

Comparison and mental model. Probing and kNN measure what the representation already contains; LoRA and LP-FT move it a controlled distance; full fine-tuning and continued pretraining move it as far as the data allows, at the cost of labels, compute and the risk of forgetting. Distillation is orthogonal: it changes the deployment cost, not the task. The next section turns to measuring whether any of these choices helped.

Let \(z_i = f_\theta(x_i) \in \mathbb{R}^d\) be the frozen embedding of example \(i\), with label \(y_i\), for \(i = 1, \dots, n\).

Linear probe. For a binary label the probe predicts

\[ \hat{p}(y=1 \mid x) = \sigma\big(w^\top f_\theta(x) + b\big), \qquad \min_{w,b}\; \sum_i \ell_{\text{BCE}}\big(y_i, \hat{p}_i\big) + \lambda \lVert w \rVert_2^2, \]

where \(f_\theta\) is frozen, \(\sigma(u) = 1/(1+e^{-u})\) is the logistic function, \(\ell_{\text{BCE}}(y,\hat p) = -y\log\hat p - (1-y)\log(1-\hat p)\) is the binary cross-entropy, and \(\lambda\) is a regularization strength chosen by cross-validation grouped by patient. The problem is convex, so it has one optimum, found in a few Newton steps. The number of free parameters is \(d+1\). For a continuous target, ridge regression replaces the loss with squared error and has the closed form \(w = (Z^\top Z + \lambda I)^{-1} Z^\top y\), where \(Z\) is the \(n \times d\) matrix of embeddings.

Worked example · W1With \(d = 256\) the AFib probe has 257 parameters and is fitted on \(n = 5{,}000\) participants, about 19 participants per parameter. A from-scratch model with millions of parameters must learn the features as well as the decision rule from the same 5,000 participants; in the reference workload it reaches AUROC 0.88 against the probe's 0.93. If labels fell to \(n = 200\), the probe would still have about 0.8 participants per parameter and would depend on \(\lambda\) to avoid overfitting, which is why \(\lambda\) is tuned on grouped folds.

kNN. With unit-normalized embeddings, the cosine similarity is \(s(z, z') = z^\top z'\). The kNN score of a query is \(\hat p(x) = \frac{1}{k}\sum_{j \in N_k(x)} y_j\), the label mean over its \(k\) most similar labelled examples \(N_k(x)\). It has no trained parameters, so any gap between kNN and probe accuracy reflects the geometry of the embedding rather than fitting.

Why fine-tuning distorts features (LP-FT). Write the full model as \(g_\phi(f_\theta(x))\) with a linear head \(\phi = (w, b)\). The gradient of the loss with respect to the features of example \(i\) is \(\partial \ell_i / \partial z_i = (\hat p_i - y_i)\, w\). With a random head, \(w\) points in an arbitrary direction and \(\hat p_i - y_i\) is large for most examples, so the first steps move \(\theta\) a long way, but only along directions exercised by the training inputs. Features of inputs unlike the training set (another device, another site) are not updated in the same way and no longer match the head. LP-FT first solves the probe problem above, so at the start of fine-tuning \(w\) is already good and \(\hat p_i - y_i\) is small; feature updates are then small and the pretrained geometry is largely kept. Kumar et al. (2022) prove this for linear two-layer models and confirm it empirically.

LoRA. For a frozen weight matrix \(W_0 \in \mathbb{R}^{d \times k}\), LoRA (Hu et al. 2022) learns

\[ W = W_0 + \frac{\alpha}{r} B A, \qquad B \in \mathbb{R}^{d \times r},\; A \in \mathbb{R}^{r \times k},\; r \ll \min(d, k), \]

where only \(A\) and \(B\) are trained, \(B\) is initialized to zero so training starts at the pretrained model, and \(\alpha\) scales the update so that changing \(r\) does not require retuning the learning rate. The update \(BA\) has rank at most \(r\), and the number of trainable parameters per matrix is \(r(d + k)\) instead of \(dk\). For a 768 × 768 projection with \(r = 8\): \(8 \times 1{,}536 = 12{,}288\) against \(589{,}824\), or 2.1%. After training, \(W\) can be computed once and stored, so inference costs the same as the original model.

LoRA: the frozen weight matrix W0 and a trainable low-rank path B times A act on the same input; their outputs are added.input xk = 512W0 (frozen)512 x 512 = 262,144 weightsA (trained)8 x 512random initB (trained)512 x 8init = 0+output hd = 512scaled by alpha / rTrainable per adapted matrix: r(d + k) = 8 x 1,024 = 8,192 (3.1% of W0). At step 0, B = 0, so h = W0 x.
Fig. A LoRA adapter on one width-512 projection with rank 8. Only A and B are trained; W0 is shared by every task and site. After training, B A can be merged into W0, so inference cost is unchanged. Dimensions are illustrative.
Worked example · W1W1's encoder has 50 million parameters; its internal widths are not part of the workload specification, so assume for illustration 12 attention layers of width 512 with LoRA rank 8 on the query and value projections. Each adapted matrix has \(8 \times (512 + 512) = 8{,}192\) trainable parameters; two per layer over 12 layers gives \(196{,}608\), about 0.39% of the encoder. Stored in 16-bit floats, one adapter occupies about 0.39 MB, against about 100 MB for a full 50-million-parameter copy.

Distillation. Classic distillation (Hinton et al. 2015) trains the student on the teacher's softened class probabilities. With teacher logits \(u\), student logits \(v\) and temperature \(T\),

\[ \mathcal{L}_{\text{KD}} = T^2 \, \mathrm{KL}\big(\mathrm{softmax}(u/T)\,\Vert\,\mathrm{softmax}(v/T)\big), \]

where \(T > 1\) spreads probability over wrong classes so that the student learns which errors the teacher considers plausible, and the factor \(T^2\) keeps gradient magnitudes comparable across temperatures. Cross-modal embedding distillation, as in the Apple accelerometer work, replaces the KL term with a loss that pulls the student embedding of an accelerometer window toward the teacher's PPG embedding of the same window, so that the student inherits the teacher's representation rather than one task's outputs.

When pretraining pays. A rough break-even compares label budgets. If a probe on an existing encoder reaches a target metric with \(n_{\text{FM}}\) labels and a from-scratch model needs \(n_{\text{S}}\), adaptation saves \(n_{\text{S}} - n_{\text{FM}}\) labels per task. Pretraining one's own encoder pays only if the further saving across all intended tasks exceeds the cost of collecting and curating the unlabelled corpus and the compute; with few tasks, or when a gradient-boosted model on counts already reaches the target, it does not.

The snippet implements the four core adaptation computations on NumPy arrays so that each line maps to an equation. fit_probe solves L2-regularized logistic regression on frozen embeddings by Newton's method: each step forms the gradient \(X^\top(p - y) + R\theta\) and the Hessian \(X^\top \mathrm{diag}(p(1-p)) X + R\), with the bias left unpenalized. knn_scores labels queries by cosine similarity to stored embeddings. LoRALinear wraps a frozen matrix with a rank-\(r\) adapter, initialized with \(B = 0\), and can merge the adapter into one matrix for serving. distill_loss computes the temperature-scaled KL divergence between teacher and student logits. The test uses a synthetic stand-in for W1's 256-dimensional embeddings.

import numpy as np

def fit_probe(Z, y, lam=1.0, iters=25):
    """L2-regularized logistic regression on frozen embeddings by Newton's method.
    Z: (n, d) embeddings, y: (n,) in {0,1}. Returns w: (d,), b: float."""
    n, d = Z.shape
    X = np.hstack([Z, np.ones((n, 1))])            # (n, d+1); last column = bias
    theta = np.zeros(d + 1)
    R = lam * np.eye(d + 1); R[-1, -1] = 0.0         # do not penalize the bias
    for _ in range(iters):
        p = 1 / (1 + np.exp(-X @ theta))
        g = X.T @ (p - y) + R @ theta                # gradient of the penalized loss
        H = (X * (p * (1 - p))[:, None]).T @ X + R   # Hessian, (d+1, d+1)
        theta -= np.linalg.solve(H, g)
    return theta[:-1], theta[-1]

def knn_scores(Z_train, y_train, Z_query, k=15):
    """Cosine kNN: fraction of positive labels among the k nearest training embeddings."""
    A = Z_train / np.linalg.norm(Z_train, axis=1, keepdims=True)
    Q = Z_query / np.linalg.norm(Z_query, axis=1, keepdims=True)
    nn = np.argsort(-(Q @ A.T), axis=1)[:, :k]      # (m, k) indices of neighbours
    return y_train[nn].mean(axis=1)

class LoRALinear:
    """h = W0 x + (alpha / r) B A x, with W0 frozen. Shapes: W0 (d, k), A (r, k), B (d, r)."""
    def __init__(self, W0, r=8, alpha=16, rng=None):
        rng = rng or np.random.default_rng(0)
        self.W0, self.r, self.scale = W0, r, alpha / r
        d, k = W0.shape
        self.A = rng.normal(0, 1 / np.sqrt(k), (r, k))   # random init
        self.B = np.zeros((d, r))                        # zero init: step 0 equals W0
    def __call__(self, x):                               # x: (batch, k) -> (batch, d)
        return x @ self.W0.T + self.scale * (x @ self.A.T) @ self.B.T
    def trainable(self):
        return self.A.size + self.B.size
    def merged(self):                                    # fold the adapter into one matrix
        return self.W0 + self.scale * self.B @ self.A

def distill_loss(student_logits, teacher_logits, T=2.0):
    """Mean KL(teacher_T || student_T) * T^2 over a batch; logits: (batch, classes)."""
    def log_softmax(z):
        z = z / T; z = z - z.max(axis=1, keepdims=True)
        return z - np.log(np.exp(z).sum(axis=1, keepdims=True))
    lt, ls = log_softmax(teacher_logits), log_softmax(student_logits)
    return float((np.exp(lt) * (lt - ls)).sum(axis=1).mean() * T * T)

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    # Synthetic stand-in for W1 embeddings: 256-d, label depends on a direction plus noise.
    n, d = 2000, 256
    u = rng.normal(size=d); u /= np.linalg.norm(u)
    y = rng.integers(0, 2, n)
    Z = rng.normal(size=(n, d)) + np.outer(2 * y - 1, u) * 1.5
    w, b = fit_probe(Z[:1500], y[:1500], lam=10.0)
    acc = ((Z[1500:] @ w + b > 0) == y[1500:]).mean()
    knn_acc = ((knn_scores(Z[:1500], y[:1500], Z[1500:]) > 0.5) == y[1500:]).mean()
    print(f"probe params {w.size + 1}; probe acc {acc:.3f}; kNN acc {knn_acc:.3f}")
    assert w.size + 1 == 257 and acc > 0.8
    W0 = rng.normal(size=(512, 512)) / np.sqrt(512)
    lora = LoRALinear(W0, r=8, alpha=16)
    x = rng.normal(size=(4, 512))
    assert np.allclose(lora(x), x @ W0.T)                       # B = 0 at init
    lora.B = rng.normal(size=(512, 8)) * 0.01                   # pretend one update
    assert np.allclose(lora(x), x @ lora.merged().T)            # merge is exact
    print("LoRA trainable", lora.trainable(), "of", W0.size, f"({lora.trainable() / W0.size:.1%})")
    t = rng.normal(size=(8, 2)) * 3
    assert distill_loss(t, t) < 1e-12 and distill_loss(t * 0, t) > 0
    print("ok")

Output: probe params 257; probe acc 0.888; kNN acc 0.850, LoRA trainable 8192 of 262144 (3.1%), ok. The assertions check that the probe has \(d + 1 = 257\) parameters and learns the planted direction, that the adapter reproduces the frozen layer exactly at initialization, that merging \(W_0 + \tfrac{\alpha}{r}BA\) gives the same outputs as the two-path forward pass, and that the distillation loss is zero when student and teacher agree.

Using it for LP-FT. LP-FT is a schedule rather than a new layer: first call fit_probe on frozen embeddings; then initialize the trainable head of the full model with the returned w, b and fine-tune all parameters with a learning rate typically an order of magnitude below the probe's. A practical check is to log the norm of the change in the encoder's weights relative to their pretrained values during the first few hundred steps; under LP-FT it grows slowly, under random-head fine-tuning it jumps.

Debugging. A probe that is far worse than kNN usually means unscaled embeddings and too strong a penalty; standardize each dimension on the training fold. A LoRA model whose outputs differ from the base model at step zero has a non-zero \(B\) initialization. A distilled student that matches teacher outputs on training data but not on held-out participants is memorizing; distill on unlabelled data from many participants rather than on the labelled set.

At scale, adaptation is a fleet of small artefacts (heads, adapters, distilled students) attached to a few large backbones. Three production problems dominate.

Problem 1: fine-tuning that wins in validation and loses at deployment. Why it matters: health models meet new devices, firmware and sites after release, and a fine-tuned model may be less robust than the probe it replaced. Root cause: feature distortion from fine-tuning with a random head, as analysed by Kumar et al. (2022).

Worked incident · W1A team fully fine-tunes W1 for AFib on 5,000 participants from one watch generation. On the in-distribution test set AUROC rises from the probe's 0.93 to 0.94. Two months after a new watch generation launches, AUROC on 1,200 newly labelled participants from that generation is 0.84, below the probe's 0.90 on the same participants. Diagnosis: the per-device dashboard shows the gap only on the new generation; a kNN check on the new device's embeddings finds that fine-tuned embeddings of AFib and non-AFib windows overlap far more than frozen ones. Remedy: retrain with LP-FT (probe first, then fine-tune at a tenth of the learning rate) and add the new device's unlabelled data to a short continued-pretraining step. Result: 0.94 in distribution and 0.91 on the new generation, with patient-bootstrap intervals of about ±0.02. (Illustrative numbers.)

Validation. The distortion hypothesis is supported if LP-FT closes the out-of-distribution gap while leaving in-distribution AUROC unchanged; it is weakened if the frozen probe also drops on the new device, which would point to an input-level change (sampling rate, filtering) that no adaptation method fixes.

Problem 2: serving many adapters. A multi-site deployment may need one adapter per site and task. Cost example: under the illustrative W1 configuration, 40 site-task adapters occupy about 16 MB in total (40 × 0.39 MB), against about 4 GB for 40 full copies. Remedy: keep one backbone in memory, load adapters per request, and batch requests that share an adapter; for latency-critical paths, merge the adapter into the weights offline and serve a dedicated model. Trade-off: unmerged adapters add a small amount of compute per adapted layer and complicate batching across tasks. Observability: log the adapter identifier with every prediction, so that a metric drop can be attributed to one adapter rather than to the backbone.

Problem 3: on-device budgets. A watch has milliwatts and megabytes. Remedy: distill. The accelerometer student of Abbaspourazad et al. (2024) replaces a power-hungry optical sensor with accelerometry, and compact models such as the 0.31-million-parameter PPG model of Lee et al. (2025), which reported roughly 4× CPU and 20× GPU speed-ups over larger baselines, show the size range that is feasible; that work reports no measurements on an actual wearable, so on-device latency and battery cost remain to be measured per product. Validation: compare student and teacher on the same held-out participants per task and per device; a student within the teacher's confidence interval on every task, at the target latency and energy, passes.

MethodTrainable (W1, illustrative)Labels typically neededMain production riskFirst diagnostic
Linear probe257 per tasktens to thousandsrepresentation lacks the signalprobe vs kNN vs baseline
LoRA~0.2M per task or sitehundreds+adapter sprawl, version mix-upsadapter id in prediction logs
LP-FT / full FT50Mthousands+out-of-distribution lossper-device and per-site AUROC
Distilled studentstudent sizenone (teacher labels)student drifts from teacherstudent–teacher agreement per device

Each method changes a different amount of the model, so each needs a different amount of evaluation; the task suites of the next section are the common yardstick.

Task suites and label scarcity

A foundation model is meant to serve many tasks, so a single headline task says little about it. A model can excel at the one task its authors tuned for and be mediocre elsewhere. Two protocols address this: task suites, which measure breadth, and label-scarcity curves, which measure the property that justifies pretraining in the first place.

Task suites. A task suite is a fixed collection of downstream tasks, data splits and an adaptation protocol, published together so that different models are scored identically. A useful suite spans task types (classification, regression, time to event, forecasting), prediction horizons and modalities, and fixes the adaptation method (usually a linear probe) so that models are compared on their representations rather than on tuning effort. The suites in this book are the templates:

  • EHRSHOT (Wornow et al. 2023) for structured EHR: 6,739 Stanford patients, 15 few-shot tasks in four groups (operational outcomes, lab-result anticipation, new diagnoses, chest X-ray findings), evaluated at \(k \in \{1, 2, 4, 8, 12, 16, 24, 32, 48, 64, 128\}\) examples per class (64 at most for one task with few positives), with five random draws per \(k\).
  • Stanford Sleep Bench (Kjaer et al. 2025) and SleepBench, built for OSF (Shuai et al., ICML 2026), for polysomnography.
  • OpenMHC (Schuetz et al. 2026) for wearables, which pits classical methods against wearable and multivariate time-series models on prediction, imputation and forecasting.
  • GIFT-Eval (Aksu et al. 2024) and fev-bench (Shchur et al. 2025) for forecasting; fev-bench reports win rates and skill scores with bootstrapped confidence intervals so that small leaderboard gaps are not over-read.

Every suite must include strong non-foundation-model baselines: count features with gradient boosting for EHR, summary statistics for wearables, exponential smoothing (ETS) for forecasting. Several studies in this book found them hard to beat on at least some tasks. A 2025 Columbia evaluation of six structured-EHR foundation models, each pretrained locally at about 120 million parameters on 5.3 million patients and tested on 14 tasks, found that the foundation models tended to beat traditional baselines, especially when labels were scarce, but could underperform on low-prevalence conditions and were less well calibrated with few labels (Jeanselme et al. 2025, FoMoH).

Label scarcity. The value of pretraining is a function of how many labels exist, so evaluations should report curves, not points. The protocol: for each \(k\) in a grid such as 1, 2, 4, …, 128, draw \(k\) labelled examples per class, fit the adaptation head, score a fixed test set, and repeat the draw several times. Plot the metric against \(k\) for the foundation-model probe and for a from-scratch baseline, with an interval over the repeated draws.

Illustrative few-shot curves: a pretrained probe versus a from-scratch baseline as labelled examples grow.0.50.60.70.80.91248163264128k, labelled examples per class (log scale)AUROCFM + linear probefrom scratch (GBM)crossoverpretraining helps most here
Fig. The typical shape of a few-shot evaluation. The pretrained probe leads at small k; the from-scratch baseline closes the gap and may overtake it with many labels. Curves are illustrative, with parameters chosen to mimic the qualitative pattern reported in EHRSHOT, where a count-based GBM overtook CLMBR-T-base on some tasks above k = 64. The band is a resampling interval for the probe.

The curve has a typical shape. At small \(k\) the pretrained probe leads, because it only has to learn a decision rule in a space where related patients are already close. As \(k\) grows the baseline learns its own features and closes the gap; in EHRSHOT, the count-based gradient-boosting model beat CLMBR-T-base on the new-diagnosis tasks above \(k = 64\). The crossover point, not the best number, is the practical result: it states how many labels a site must collect before the foundation model stops paying for itself.

Worked example · W2W2 is evaluated EHRSHOT-style on one-year mortality and 30-day readmission, with heads trained on patients from the training period (through 2022) and scored on patients predicted in 2024. The full-data probes reach AUROC 0.89 and 0.71. The curve would show the probe's lead at \(k \le 16\) and whether a count-based gradient-boosting model catches up by \(k = 128\); for readmission, where 0.71 is modest, a crossover would suggest the representation adds little for that task.

Comparison. A suite answers "is the model broadly useful?"; a curve answers "when is it worth it?". Neither answers whether the model works at a new site, for every group, or with trustworthy probabilities, which is the subject of the next section.

The AUROC estimator. For a test set with \(n_1\) positives and \(n_0\) negatives and scores \(s\), the area under the ROC curve equals the probability that a random positive outranks a random negative:

\[ \widehat{\mathrm{AUROC}} = \frac{1}{n_1 n_0}\sum_{i:y_i=1}\sum_{j:y_j=0}\Big(\mathbb{1}[s_i > s_j] + \tfrac12\mathbb{1}[s_i = s_j]\Big). \]

It depends only on ranks, so any monotone transformation of the scores leaves it unchanged; this is why AUROC says nothing about calibration.

How noisy is it? A classic approximation (Hanley and McNeil) gives the standard error of an AUROC \(A\):

\[ \mathrm{SE}^2 \approx \frac{A(1-A) + (n_1-1)(Q_1 - A^2) + (n_0-1)(Q_2 - A^2)}{n_1 n_0}, \quad Q_1 = \frac{A}{2-A},\; Q_2 = \frac{2A^2}{1+A}. \]

It assumes independent test examples; with several rows per patient, the patient bootstrap below is the safer choice.

Worked example · W2Take a W2 test set of 10,000 patients with one-year mortality of 7.5% (\(n_1 = 750\), \(n_0 = 9{,}250\)) and \(A = 0.89\). Then \(Q_1 = 0.89/1.11 = 0.802\), \(Q_2 = 2(0.792)/1.89 = 0.838\), and \(\mathrm{SE} \approx 0.008\), so a 95% interval is about \(0.89 \pm 0.016\). For a subgroup of 500 patients with 38 deaths, the same formula gives \(\mathrm{SE} \approx 0.035\), an interval of about \(\pm 0.07\). A difference of 0.01 between two models on the full test set is within noise unless a paired analysis shows otherwise; on the subgroup almost no difference is detectable.

The k-shot protocol. Let \(D_k^{(r)}\) be the \(r\)-th random draw of \(k\) positives and \(k\) negatives from the training pool, \(r = 1, \dots, R\). Fit the head on \(D_k^{(r)}\), score the fixed test set, and report

\[ \bar{m}(k) = \frac{1}{R}\sum_{r=1}^R m\big(D_k^{(r)}\big), \qquad \text{spread}(k) = \max_r m - \min_r m. \]

The spread over draws is large at small \(k\) because which few examples are drawn matters; it shrinks roughly as \(1/\sqrt{k}\). Balanced draws give a training prevalence of 0.5 regardless of the true prevalence, so probabilities from \(k\)-shot heads are not calibrated for the population; AUROC, being rank-based, is unaffected.

Patient bootstrap. To build an interval that respects repeated rows per patient, resample patients (not rows) with replacement \(B\) times, recompute the metric on all rows of the drawn patients, and take the 2.5th and 97.5th percentiles. When comparing two models, resample once per replicate and compute the difference on the same draw (a paired bootstrap); the shared test examples cancel much of the variance.

Crossover. If the probe's curve is \(m_{\text{FM}}(k)\) and the baseline's is \(m_{\text{S}}(k)\), the crossover \(k^*\) solves \(m_{\text{FM}}(k^*) = m_{\text{S}}(k^*)\). For the illustrative curves in the figure, \(m_{\text{FM}}(k) = 0.60 + 0.18(1 - e^{-k/10})\) and \(m_{\text{S}}(k) = 0.52 + 0.31(1 - e^{-k/45})\); at \(k = 4\) they are 0.659 and 0.546, at \(k = 64\) 0.780 and 0.755, and at \(k = 128\) 0.780 and 0.812; solving numerically gives \(k^* \approx 82\). Because both curves carry intervals, \(k^*\) itself is uncertain; a crossover should be reported only where the paired intervals separate.

The snippet implements the three pieces of a label-scarcity evaluation. auroc computes the rank (Mann–Whitney) estimator with average ranks for ties, in \(O(n \log n)\). kshot_curve draws \(k\) positives and \(k\) negatives per repetition from a training pool, fits a head through a caller-supplied fit function (here a ridge probe, a fast stand-in for logistic regression), and returns the mean, minimum and maximum test AUROC over draws. patient_bootstrap_ci resamples patients so that all rows of a patient enter or leave together. Inputs are arrays: embeddings of shape \((n, d)\), labels \((n,)\), and patient identifiers \((n,)\).

import numpy as np

def auroc(y, s):
    """Rank-based AUROC (Mann-Whitney U / n1 n0); ties get average ranks."""
    order = np.argsort(s, kind="mergesort"); ranks = np.empty(len(s))
    ranks[order] = np.arange(1, len(s) + 1)
    for v in np.unique(s):                       # average ranks over ties
        m = s == v
        if m.sum() > 1: ranks[m] = ranks[m].mean()
    n1 = y.sum(); n0 = len(y) - n1
    return (ranks[y == 1].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)

def kshot_curve(Z_tr, y_tr, Z_te, y_te, fit, ks=(1, 2, 4, 8, 16, 32, 64, 128), draws=5, seed=0):
    """For each k: draw k positives and k negatives (balanced), fit, score test AUROC.
    Returns {k: (mean, min, max)} over draws. fit(Z, y) -> scoring function."""
    rng = np.random.default_rng(seed); out = {}
    pos, neg = np.flatnonzero(y_tr == 1), np.flatnonzero(y_tr == 0)
    for k in ks:
        vals = []
        for _ in range(draws):
            idx = np.concatenate([rng.choice(pos, k, replace=False), rng.choice(neg, k, replace=False)])
            score = fit(Z_tr[idx], y_tr[idx])
            vals.append(auroc(y_te, score(Z_te)))
        out[k] = (float(np.mean(vals)), float(np.min(vals)), float(np.max(vals)))
    return out

def patient_bootstrap_ci(pid, y, s, B=1000, seed=0):
    """95% CI for AUROC resampling patients (all rows of a drawn patient move together)."""
    rng = np.random.default_rng(seed)
    ids = np.unique(pid); rows = {i: np.flatnonzero(pid == i) for i in ids}
    stats = []
    for _ in range(B):
        take = np.concatenate([rows[i] for i in rng.choice(ids, len(ids), replace=True)])
        if 0 < y[take].sum() < len(take): stats.append(auroc(y[take], s[take]))
    return tuple(np.percentile(stats, [2.5, 97.5]))

def ridge_fit(Z, y, lam=1.0):
    """Least-squares probe (fast stand-in for logistic regression in the curve)."""
    X = np.hstack([Z, np.ones((len(Z), 1))])
    th = np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ (2 * y - 1))
    return lambda Zq: np.hstack([Zq, np.ones((len(Zq), 1))]) @ th

if __name__ == "__main__":
    assert auroc(np.array([0, 0, 1, 1]), np.array([.1, .2, .3, .4])) == 1.0
    assert auroc(np.array([0, 1, 0, 1]), np.array([.5, .5, .5, .5])) == 0.5
    rng = np.random.default_rng(1)
    d = 32; u = rng.normal(size=d); u /= np.linalg.norm(u)
    def make(n):
        y = (rng.random(n) < 0.3).astype(int)
        return rng.normal(size=(n, d)) + np.outer(y, u) * 1.5, y
    Ztr, ytr = make(4000); Zte, yte = make(2000)
    curve = kshot_curve(Ztr, ytr, Zte, yte, ridge_fit, ks=(1, 4, 16, 64), draws=10)
    for k, (m, lo, hi) in curve.items(): print(f"k={k:3d}  AUROC {m:.3f}  range [{lo:.3f}, {hi:.3f}]")
    assert curve[64][0] > curve[1][0]                          # more labels help on average
    assert (curve[64][2] - curve[64][1]) < (curve[1][2] - curve[1][1])  # and vary less
    pid = np.repeat(np.arange(500), 4); yy = np.repeat(rng.random(500) < 0.3, 4).astype(int)
    ss = yy * 0.8 + rng.normal(size=2000)
    lo, hi = patient_bootstrap_ci(pid, yy, ss, B=300)
    print(f"patient-bootstrap 95% CI [{lo:.3f}, {hi:.3f}]")
    assert lo < auroc(yy, ss) < hi
    print("ok")

Output: AUROC rises from about 0.56 at \(k = 1\) to 0.78 at \(k = 64\), and the range over ten draws narrows from roughly 0.13 at \(k = 1\) to 0.04 at \(k = 64\); the patient-bootstrap interval is printed and contains the point estimate. The tests check AUROC on a perfectly ranked and a fully tied case, that more labels help on average and vary less, and that the bootstrap interval brackets the estimate. The non-monotone means between \(k = 4\) and \(k = 16\) on some seeds are not a bug: they are the draw-to-draw variance the protocol exists to expose.

Debugging. If the curve is flat at 0.5, check that test labels and scores are aligned after any filtering. If the spread at \(k = 128\) is as wide as at \(k = 1\), the test set is too small for the metric to be informative. If the baseline beats the probe even at \(k = 1\), check that the baseline is not seeing features unavailable to the probe, such as codes recorded after the index time (the subject of the last section of this chapter).

An evaluation suite is a workload of its own. Its cost, its noise and its drift must be managed like those of any production system.

Problem 1: cost. An EHRSHOT-shaped protocol with 15 tasks, 11 values of \(k\) and 5 draws needs 825 head fits per model, plus bootstrap replicates for every reported interval. Remedy: compute embeddings once per model version and cache them keyed by (model version, patient, index time); the head fits are then cheap linear models that parallelize trivially. Trade-off: cached embeddings must be invalidated whenever the tokenizer, preprocessing or index-time definition changes, so the cache key must include those versions as well.

Problem 2: over-reading small differences. Leaderboards rank models by point estimates that differ by less than their noise. Diagnosis: for every comparison, report a paired bootstrap interval for the difference. Remedy: adopt aggregate statistics with intervals, as fev-bench does with win rates and skill scores, and pre-register the primary comparison so that the best of many metrics is not selected afterwards.

Worked incident · W2A new W2 checkpoint reports one-year mortality AUROC 0.90 against the release model's 0.89 and is proposed for deployment. The test set has 750 deaths among 10,000 patients, so each AUROC has a standard error of about 0.008. A paired patient bootstrap of the difference gives +0.008 with a 95% interval of [−0.002, +0.018]; across the 15-task suite the new checkpoint wins 8 tasks and loses 7, and its 30-day readmission AUROC falls from 0.71 to 0.69, with an interval for that difference that excludes zero. Decision: the claimed improvement is not established and the readmission regression is; the checkpoint is held back. (Illustrative numbers.)

Validation. The decision rule is supported if, on a second independent test period, the mortality difference again straddles zero and the readmission loss reappears; it is weakened if the second period shows a significant mortality gain, which would argue for a larger primary test set.

Problem 3: the crossover moves. Baselines improve when sites accumulate labels. A site that had 50 labelled AFib cases at launch may have 2,000 a year later, past the crossover. Remedy: re-run the \(k\)-shot curve for each site and task on a schedule tied to label accrual, and switch to the cheaper or better model when the paired interval says so.

IndicatorComputed fromAction threshold (illustrative)
Paired AUROC difference, new vs releasepatient bootstrap, 1,000 replicatesship only if the lower bound > 0 on the primary task and no task's upper bound < −0.01
Win rate over the suiteper-task paired differencesreport with interval; never as a single number
Crossover \(k^*\) per site\(k\)-shot curves, 5+ drawsre-evaluate when site labels exceed \(2k^*\)
Embedding cache hit rateevaluation job logsinvestigate if below 95%

A suite and a curve establish that a model is useful in the population it was tested on. The next section asks what happens when that population changes.

Shift, fairness and calibration

A model evaluated on data like its training data can still fail where it is used. Three properties determine whether a good test-set number carries over: robustness to distribution shift, fairness across groups, and calibration of its probabilities. They are related: shift usually breaks calibration first, and groups are often affected by shift unequally.

Distribution shift. Health data shifts along three axes, and a model should be tested on each separately:

  • Site. Hospitals differ in coding practice, case mix and order sets. The test is to hold out entire sites, as SleepFM did with SHHS and MOTOR did with MIMIC-IV. Transferring a pretrained model without local adaptation can hurt: in the 2025 Columbia evaluation, an externally pretrained Mamba model performed worse than the same architecture pretrained locally and fell below baselines on some phenotypes, which the authors attribute to coding and population differences (Jeanselme et al. 2025).
  • Device. Sensors, firmware and placement change signals. Pulse-PPG's laboratory-versus-field results and LSM-2's sensor-removal tests are examples; the test is to evaluate on the devices that will be deployed.
  • Time. Coding systems, treatments and populations drift. The test is to train on data before a date and evaluate after it; MOTOR reported better robustness to temporal shift than baselines.
Worked example · W3W3 stages sleep with Cohen's κ 0.78 against single-scorer labels on laboratory PSG, slightly above the inter-scorer agreement of about 0.76. Transferred to a wearable-only setting, with no EEG channel, κ falls to 0.62. The drop is a device shift: the information that separates N1 from wake and REM is largely in the EEG, which the wearable does not record. The appropriate report gives both numbers and states which channels each assumes.

Fairness. Fairness failures in health often come from the label, not the model. Obermeyer et al. (2019) showed that a widely used risk algorithm was biased against Black patients because it predicted health-care cost as a proxy for health need; because less is spent on Black patients with the same level of need, the bias cut the number of Black patients identified for extra care by more than half. Foundation models inherit both label proxies and biases in the pretraining population; Delphi-2M's authors explicitly found biases inherited from training data (Shmatko et al. 2025). Pretraining can also narrow some gaps: in the Columbia evaluation, supervised baselines showed the largest performance gaps across levels of health-care utilization, and pretraining on large populations appeared to reduce them (Jeanselme et al. 2025). The practice is to report metrics by age, sex, race and ethnicity, site and device; to check calibration within each group; and to look for proxies in the labels before blaming the encoder. Fairness criteria also conflict: outside restrictive special cases, a risk score cannot simultaneously be calibrated within groups and have equal error rates across groups whose prevalence differs (Kleinberg et al. 2016), so a report must state which criterion it targets.

Calibration. A risk score is used as a probability, so it must be calibrated: among patients given 20% risk, about 20% should have the event. The expected calibration error (ECE) groups predictions into bins and averages the gap between mean prediction and observed frequency, weighted by bin size. A reliability diagram plots the same comparison. The Brier score, the mean squared difference between predicted probability and outcome, combines calibration and discrimination in one number.

Illustrative reliability diagram for W2 one-year mortality: at the development site the bins lie near the diagonal; at a new site the model predicts more risk than occurs.0.00.00.20.20.40.40.60.60.80.81.01.0observed event ratemean predicted probability in bindevelopment site (ECE 0.03)new site, before recalibrationPoints below the diagonal: the modelpredicts more risk than occurs.Ranking (AUROC) can be unchanged whileevery probability is too high.Temperature or isotonic scaling on alocal sample moves points to the diagonal.
Fig. A reliability diagram groups predictions into bins and plots the observed event rate against the mean prediction. Values are illustrative for W2; the development-site curve corresponds to the workload's ECE of 0.03.

Calibration usually breaks first under shift, because a change in prevalence or in measurement moves every probability while leaving the ranking of patients largely intact. It can be repaired cheaply with temperature scaling (dividing the model's log-odds by one fitted number) or isotonic regression (a fitted monotone map from score to probability) on a small local sample, which is one more reason to keep a held-out set from each deployment site. A limitation: recalibration fixes the mapping from score to probability, not the ranking, so a model whose AUROC has fallen at a new site needs adaptation, not recalibration.

Worked example · W2At its development site W2's one-year mortality model has ECE 0.03. At a second hospital the ranking holds (AUROC 0.88), but the predictions are too high in every bin above 0.2, as in the figure: ECE is 0.09. Temperature and intercept fitted on 2,000 local patients restore ECE to about 0.03 without changing AUROC. (Illustrative numbers.)

Connection. Shift tests ask whether performance travels, subgroup reports ask whether it is shared, and calibration asks whether the numbers mean what they say. All three assume that the test set is truly separate from training, which the next section examines.

Types of shift. Write the joint distribution as \(P(x, y) = P(x)P(y \mid x) = P(y)P(x \mid y)\). Three idealized shifts from source \(S\) to target \(T\) are distinguished by what stays fixed:

  • Covariate shift: \(P_T(x) \ne P_S(x)\) but \(P_T(y \mid x) = P_S(y \mid x)\). A new device changes the inputs but not the disease they reflect. Importance weighting by \(w(x) = P_T(x)/P_S(x)\) corrects source estimates when the source covers the target's inputs.
  • Label (prior) shift: \(P_T(y) \ne P_S(y)\) but \(P_T(x \mid y) = P_S(x \mid y)\). A tertiary hospital sees sicker patients with the same presentations.
  • Concept shift: \(P_T(y \mid x) \ne P_S(y \mid x)\). A new treatment changes outcomes for the same history, or a label definition changes. No reweighting fixes this; new labels are needed.

Label-shift correction. Under pure label shift, Bayes' rule implies that the target log-odds equal the source log-odds plus the change in prior log-odds:

\[ \operatorname{logit} p_T(y{=}1 \mid x) = \operatorname{logit} p_S(y{=}1 \mid x) + \log\frac{\pi_T}{1-\pi_T} - \log\frac{\pi_S}{1-\pi_S}, \]

where \(\pi_S, \pi_T\) are the event prevalences. For a prediction of 0.10 at a site with prevalence 5% moved to a site with 8%: \(\operatorname{logit}(0.10) = -2.197\); the shift adds \(\log(0.08/0.92) - \log(0.05/0.95) = -2.442 + 2.944 = 0.502\); the corrected log-odds \(-1.695\) give 0.155.

Expected calibration error. With \(M\) bins \(B_1, \dots, B_M\) of predictions,

\[ \mathrm{ECE} = \sum_{m=1}^{M} \frac{|B_m|}{n}\,\big|\,\bar{y}(B_m) - \bar{p}(B_m)\,\big|, \]

where \(B_m\) is the set of predictions in bin \(m\), \(\bar{p}\) their mean predicted probability and \(\bar{y}\) the observed event rate. It should be reported with reliability diagrams and the Brier score \(\mathrm{BS} = \frac{1}{n}\sum_i (p_i - y_i)^2\). ECE depends on the binning and is dominated by the bins that hold most predictions, which for rare outcomes are the lowest.

Worked example · W2Ten thousand W2 test patients fall into five bins: 9,000 with mean prediction 0.025 and observed rate 0.048; 600 at 0.28 vs 0.21; 250 at 0.50 vs 0.40; 100 at 0.70 vs 0.58; 50 at 0.88 vs 0.76. The weighted gaps are 0.0207, 0.0042, 0.0025, 0.0012 and 0.0006, so ECE \(= 0.029 \approx 0.03\), the workload's value. Most of it comes from the lowest bin, where the model under-predicts by 2.3 points; mean prediction is 0.063 against an observed rate of 0.075.

Temperature and Platt scaling. Given a model's logit \(u\), temperature scaling predicts \(\sigma(u/T)\) with one parameter \(T > 0\) fitted by minimizing the negative log-likelihood on a calibration sample; \(T > 1\) pulls over-confident predictions toward 0.5 without changing their order. A prediction of 0.80 (logit 1.386) becomes \(\sigma(1.386/1.5) = 0.716\) at \(T = 1.5\). Guo et al. (2017) found this one-parameter method surprisingly effective for modern networks. Platt scaling adds an intercept, \(\sigma(a u + b)\), which also corrects calibration-in-the-large after a prevalence change. Isotonic regression fits any monotone map and needs more data.

Subgroup metrics. For a group \(g\) and threshold \(\tau\), the true-positive rate is \(\mathrm{TPR}_g = P(\hat p \ge \tau \mid y{=}1, G{=}g)\) and the false-positive rate is \(\mathrm{FPR}_g\) analogously. Calibration within groups requires \(P(y{=}1 \mid \hat p = p, G{=}g) = p\) for every \(g\). If prevalence differs between groups, the two goals (equal TPR and FPR, and calibration within groups) cannot both hold except in degenerate cases (Kleinberg et al. 2016). Subgroup estimates are noisy: by the Hanley–McNeil approximation, a subgroup with 38 events among 500 patients has an AUROC standard error of about 0.035, so gaps smaller than about 0.07 cannot be distinguished from chance.

The snippet implements the calibration toolkit. ece bins predictions into \(M\) equal-width bins and sums the weighted gaps. brier is the mean squared error of probabilities. fit_platt fits the recalibration map \(\sigma(a u + b)\) by Newton's method on the negative log-likelihood; \(1/a\) is the equivalent temperature. prior_shift adds the change in prior log-odds to every logit. subgroup_report returns, per group, the count, prevalence, mean prediction and ECE. The test simulates a target site where the model's logits are \(1.6\times\) too large and shifted by 0.6, fits the map on a 10% calibration sample (about 2,000 patients) and evaluates on the remaining 90%.

import numpy as np

def ece(y, p, M=10):
    """Expected calibration error with M equal-width bins on [0, 1]."""
    bins = np.minimum((p * M).astype(int), M - 1); total = 0.0
    for m in range(M):
        idx = bins == m
        if idx.any(): total += idx.mean() * abs(y[idx].mean() - p[idx].mean())
    return total

def brier(y, p):
    return float(np.mean((p - y) ** 2))

def fit_platt(y, logit, iters=50):
    """Recalibration map q = sigmoid(a * logit + b) fitted by Newton's method on the NLL.
    a = 1 / T is an inverse temperature; b corrects calibration-in-the-large."""
    X = np.stack([logit, np.ones_like(logit)], axis=1); th = np.array([1.0, 0.0])
    for _ in range(iters):
        q = 1 / (1 + np.exp(-X @ th))
        H = (X * (q * (1 - q))[:, None]).T @ X + 1e-9 * np.eye(2)
        th -= np.linalg.solve(H, X.T @ (q - y))
    return float(th[0]), float(th[1])

def prior_shift(logit, pi_src, pi_tgt):
    """Label-shift correction: add the change in log prior odds to every logit."""
    lo = lambda q: np.log(q / (1 - q))
    return logit + lo(pi_tgt) - lo(pi_src)

def subgroup_report(y, p, g):
    """Per-group n, prevalence, mean prediction, ECE. g: (n,) group labels."""
    rows = []
    for v in np.unique(g):
        m = g == v
        rows.append((v, int(m.sum()), y[m].mean(), p[m].mean(), ece(y[m], p[m])))
    return rows

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    n = 20000
    true_logit = rng.normal(-2.2, 1.4, n)                  # target-site risk, prevalence ~0.16
    y = (rng.random(n) < 1 / (1 + np.exp(-true_logit))).astype(int)
    over = 1.6 * true_logit + 0.6                          # over-confident and too high
    p_over = 1 / (1 + np.exp(-over))
    print(f"before: ECE {ece(y, p_over):.3f}  Brier {brier(y, p_over):.4f}")
    cal = rng.random(n) < 0.1                              # 10% local calibration sample (~2,000)
    a, b = fit_platt(y[cal], over[cal])
    p_c = 1 / (1 + np.exp(-(a * over + b)))
    print(f"a = {a:.2f} (T = {1 / a:.2f}), b = {b:.2f}; after: ECE {ece(y[~cal], p_c[~cal]):.3f}  Brier {brier(y[~cal], p_c[~cal]):.4f}")
    assert 0.5 < a < 0.8 and ece(y[~cal], p_c[~cal]) < ece(y[~cal], p_over[~cal])
    # Prior shift: a 5% -> 8% prevalence change moves a 0.10 prediction to ~0.155
    z = np.log(0.10 / 0.90)
    print(f"0.10 at 5% prevalence -> {1 / (1 + np.exp(-prior_shift(z, 0.05, 0.08))):.3f} at 8%")
    g = rng.integers(0, 2, n)
    for row in subgroup_report(y[~cal], p_c[~cal], g[~cal]): print("group %s n=%d prev=%.3f mean_p=%.3f ECE=%.3f" % row)
    print("ok")

Output: before: ECE 0.039; after fitting, a = 0.75 (T = 1.34), b = -0.34 and ECE 0.020 on the held-out 90%, Brier improving slightly; 0.10 at 5% prevalence -> 0.155 at 8%, matching the hand calculation; and per-group rows. The true values are \(a = 0.625\) (\(T = 1.6\)) and \(b = -0.375\); with about 2,000 calibration patients the estimate of \(a\) varies noticeably between samples, which the assertion tolerates and which is itself a lesson: a few hundred local events give a usable but imprecise recalibration.

Debugging. An ECE that changes a lot with the number of bins means too few predictions per bin; report it at two bin counts or use equal-mass bins. A recalibration that improves ECE but worsens the Brier score on held-out data is over-fitted; use fewer parameters (temperature only). A subgroup ECE far above the overall value with fewer than about 30 events in the group is mostly noise; report its interval rather than its point value.

Shift is a property of deployment, not of a test set, so it is managed with monitoring and a standing recalibration path. Three problems recur.

Problem 1: silent miscalibration after a population or practice change. Why it matters: thresholds for alerts and referrals are set on probabilities; if probabilities rise by a third, alert volume rises with them even though discrimination is unchanged. Root cause: label shift (different prevalence) or a change in measurement that moves the scores. Diagnosis: calibration needs outcomes, which arrive late (one-year mortality needs a year). Two indicators arrive sooner: the mean predicted risk per week compared with the development period, and the distribution of embeddings or scores compared by a population stability index.

Worked incident · W2W2's mortality model goes live at a second hospital with an alert threshold of 0.30. In the first month the alert rate is 6.1% of admissions against 3.8% expected, while the mean predicted risk is 0.075, the development prevalence, against a local historical one-year mortality of 0.05. Outcomes for 2,000 patients from the previous year are available, so the model is scored retrospectively on them: AUROC 0.88 (interval ±0.03), ECE 0.09, with every bin above 0.2 over-predicted. Remedy: fit temperature and intercept on those 2,000 patients and re-derive the threshold for the original alert rate. Result: ECE 0.03 on a separate 1,000 patients, alert rate 3.9%. Cost: one parameter pair per site, refitted when a monitored indicator moves. (Illustrative numbers.)

Validation. The label-shift explanation is supported if the fitted intercept roughly equals the change in prior log-odds (here \(\log(0.05/0.95) - \log(0.075/0.925) \approx -0.43\)) and AUROC is unchanged; it is weakened if AUROC also fell, which would indicate covariate or concept shift that requires local adaptation (an adapter or continued pretraining) rather than recalibration.

Problem 2: device and firmware changes. A firmware update that changes PPG filtering is a covariate shift for W1. Diagnosis: track signal-quality statistics and embedding drift by firmware version; a step change at the release date identifies the cause. Remedy: evaluate every firmware version on a fixed panel of labelled participants before rollout, and gate the model on the result. For W3, the laboratory-to-wearable drop from κ 0.78 to 0.62 is a planned device shift: the product must be specified and validated on the wearable, not on PSG.

Problem 3: subgroup monitoring with small numbers. Subgroup metrics are noisy, so naive alerts fire on noise. Remedy: set the minimum group size for an alert from the interval width (for AUROC near 0.89, about 40 events give a standard error near 0.035), pool over longer windows for small groups, and alert on calibration-in-the-large (observed minus predicted events), which needs fewer events than AUROC. Trade-off: pooling delays detection. For a regulated device, the recalibration procedure and its bounds belong in the predetermined change control plan, so that refitting a site's temperature is a pre-authorized modification rather than a new submission.

IndicatorLatencyDetectsAlert condition (illustrative)
Mean predicted risk vs expecteddayslabel shift, score driftrelative change > 20% over 2 weeks
Score or embedding PSI by site and devicedayscovariate shiftPSI > 0.2
Calibration-in-the-large per groupoutcome delaymiscalibration, group effectsobserved/expected outside [0.8, 1.25] with ≥ 40 events
AUROC per site and groupoutcome delayloss of rankinginterval upper bound below release value

These checks assume the evaluation numbers they are compared with were honest in the first place; leakage, the subject of the next section, is the commonest reason they are not.

Leakage: patient-level and temporal splits

Leakage is any path by which information about the test examples reaches the model or its training decisions. It is the most common reason health machine-learning results fail to replicate. Kapoor and Narayanan (2023) catalogued leakage across machine-learning-based science, finding errors affecting 294 papers in 17 fields and organizing them into eight types, from textbook mistakes to open research problems. Leaked results look excellent on paper and collapse in deployment, because deployment provides no leak.

Health foundation models add three specific risks:

  • The same person in train and test. Windows, nights or visits from one patient are highly correlated. If they are split at random, the model can succeed by recognizing the person (a resting heart-rate pattern, a habitual medication list) rather than by detecting the condition.
  • Future information in features. A code recorded after the prediction time, such as a diagnosis entered at discharge used to predict an outcome of that admission, gives away the answer.
  • Pretraining corpora that include the evaluation patients. Self-supervised pretraining sees no labels, but it can memorize individuals, so a pretrained model may already "know" test patients.
Random window splits leak patient identity; patient-level and temporal splits do not.Random window splitP1P2P3✗ same patient in train and testPatient-level splitP1P2P3✓ unseen patientsTemporal splitP1P2P3cutoff✓ unseen future (+ patient-level: both)time windows →traintestDeployment-like estimate: hold out patients AND the future, ideally at a different site.
Fig. Three ways to split the same data (three patients × twelve time windows). A random window split puts the same patient in train and test, so the model can succeed by recognizing the person. A patient-level split holds out whole patients. A temporal split also holds out the future. For deployment-like estimates, combine patient-level and temporal splits. Schematic.

Splits. A random window split assigns windows independently to train or test, so almost every patient appears on both sides. A patient-level split assigns whole patients, so test patients are unseen. A temporal split trains on data before a cutoff date and tests after it, which also exposes the model to drift in practice and coding. For deployment-like estimates, combine patient-level and temporal splits, and if possible add a held-out site.

The size of the effect is well documented in physiological signals. In an EEG study of post-traumatic stress disorder, Lee et al. (2023) found that with data augmentation, splitting by trial rather than by subject raised EEGNet's balanced accuracy from about 80% to as high as 98%, because cropped segments of the same participant appeared in both sets. A 2025 study training over 100,000 EEG models across three tasks and four architectures again stressed subject-based cross-validation and found that non-nested validation setups can leak and overestimate performance (Del Pup et al. 2025).

Worked example · W1 and W2Each W1 participant contributes on average 200 hours of recording (30 million hours over 150,000 participants), or about 72,000 ten-second windows. Under a random 80/20 window split essentially every participant has windows in both sets, so an AFib probe could score well by recognizing participants with known AFib. W1's AUROC of 0.93 is therefore computed with the 5,000 labelled participants split by participant. W2 uses a patient-level split plus a temporal holdout: models are trained on data through 2022 and tested on predictions made in 2024, with 2023 left as a gap so that no outcome window straddles the boundary.

A leakage audit for health foundation models.

  1. Pretraining overlap. List every dataset in pretraining. Remove evaluation patients from pretraining (or evaluate only on patients and sites never seen). For public time-series models, check the model card for the benchmark datasets and their time windows.
  2. Unit of splitting. Split by patient (or by participant for wearables), never by window or visit. For families or repeated enrolments, split by the highest-level identifier available.
  3. Prediction time. Define an index time per example and drop every event recorded after it, including codes whose recording time is later than their clinical time (billing codes are often entered days later).
  4. Label leakage through codes. Remove codes that encode the label or its treatment (a diagnosis code for the outcome, a drug only given for it). For onset tasks, exclude patients with the condition before index and distinguish new onsets from repeats (Rajamohan et al. 2025).
  5. Temporal hold-out. Keep a test set strictly after the training period, and report the gap between random-patient and temporal splits; a large gap is a warning.
  6. Site and device hold-out. Hold out at least one site or device type entirely.
  7. Hyperparameter hygiene. Tune only on validation folds grouped by patient; never select checkpoints on the test set, including "early stopping on test".
  8. Sanity probes. Train a probe to predict patient identity or site from embeddings. If it succeeds easily, downstream results may be driven by identity or site rather than physiology.

Mental model. A test set is a simulation of deployment. Every piece of information the model could not have at deployment (another window of the same person, a code entered later, the person's records in pretraining) must be absent from the simulation as well. This completes the evaluation chain of the chapter; the next chapter assembles adaptation, evaluation and monitoring into a working system.

Why random window splits leak. Suppose a patient contributes \(m\) windows and each is independently assigned to test with probability \(f\). The patient appears only in test with probability \(f^m\), only in train with probability \((1-f)^m\), and in both with probability

\[ P(\text{both}) = 1 - f^m - (1-f)^m. \]

With \(f = 0.2\): for \(m = 2\), \(P = 0.32\); for \(m = 10\), \(P = 0.89\); for \(m = 100\), \(P\) differs from 1 by less than \(10^{-9}\). Once a patient is on both sides, a model can lower test error by matching patient-specific features, which carry no information about new patients.

Worked example · W1A W1 participant with 200 hours has \(m = 200 \times 3{,}600 / 10 = 72{,}000\) ten-second windows. Even subsampling 1% per epoch leaves \(m = 720\), and \(P(\text{both}) = 1\) to machine precision. A participant-level split is the only way to obtain a test set of unseen people.

Effective sample size. Correlated rows also make naive intervals too narrow. If each of \(N\) patients contributes \(m\) rows with intra-patient correlation \(\rho\) in the quantity being averaged, the variance of the mean equals that of \(n_{\text{eff}}\) independent rows, where

\[ n_{\text{eff}} = \frac{N m}{1 + (m-1)\rho}. \]

The denominator is the design effect. For 5,000 participants with 100 windows each and \(\rho = 0.5\), \(n_{\text{eff}} = 500{,}000 / 50.5 \approx 9{,}900\): the half-million windows carry about as much independent information as twice the number of participants. Window-level standard errors would be about \(\sqrt{50.5} \approx 7\) times too small, which is why intervals are computed with the patient bootstrap.

Temporal leakage. Let each example have an index time \(t_0\), and each event \(e\) a clinical time \(t_e\) and a recording time \(r_e \ge t_e\). The admissible features are

\[ \mathcal{F}(t_0) = \{\,e : t_e \le t_0 \;\text{and}\; r_e \le t_0\,\}. \]

Filtering on \(t_e\) alone admits events that happened before the index time but were recorded after it, which at the time of a real prediction did not yet exist in the record. For a temporal split with training cutoff \(c\) and outcome horizon \(h\), training labels must be observable by \(c\), so training index times satisfy \(t_0 + h \le c\); a test period starting at \(c + h\) or later ensures no outcome window spans both. W2's one-year mortality with training through 2022 and testing on 2024 predictions leaves the required one-year gap.

The identity probe. The sanity probe of the audit fits a classifier from embedding to patient identifier. With \(P\) patients, chance accuracy is \(1/P\); accuracy far above chance means the embedding encodes identity. This is not itself a defect (a good representation of physiology will differ between people), but if identity is easy and the downstream task is evaluated with a leaky split, the task score can be explained by identity alone.

The snippet implements splits and leakage checks on row-level arrays: a patient identifier, a time and, for the probe, embeddings. patient_split assigns whole patients to test. temporal_patient_split combines a patient-level split with a training cutoff and a later test start. assert_no_leak raises if any patient is on both sides or if the time windows overlap. drop_after_index keeps an event only if both its clinical and its recording time are at or before the index time. identity_probe_acc is a nearest-centroid classifier of patient identity, fitted on half of each patient's windows and scored on the other half.

import numpy as np

def patient_split(pid, test_frac=0.2, seed=0):
    """Assign whole patients to test. pid: (n,) patient id per row. Returns boolean test mask."""
    rng = np.random.default_rng(seed); ids = np.unique(pid)
    test_ids = rng.choice(ids, int(round(test_frac * len(ids))), replace=False)
    return np.isin(pid, test_ids)

def temporal_patient_split(pid, t, train_end, test_start, test_ids):
    """Train: rows of non-test patients with t <= train_end. Test: rows of test patients with t >= test_start."""
    is_test_pt = np.isin(pid, test_ids)
    return (~is_test_pt) & (t <= train_end), is_test_pt & (t >= test_start)

def assert_no_leak(pid, train, test, t=None, train_end=None, test_start=None):
    overlap = np.intersect1d(pid[train], pid[test])
    assert overlap.size == 0, f"{overlap.size} patients in both train and test"
    if t is not None:
        assert t[train].max() <= train_end and t[test].min() >= test_start, "time windows overlap"

def drop_after_index(event_time, record_time, index_time):
    """Keep an event only if it happened AND was recorded at or before the index time."""
    return (event_time <= index_time) & (record_time <= index_time)

def identity_probe_acc(Z, pid, seed=0):
    """Nearest-centroid patient-ID probe: fit centroids on half of each patient's windows,
    classify the other half. High accuracy means embeddings encode the person."""
    rng = np.random.default_rng(seed); ids = np.unique(pid)
    half = np.zeros(len(pid), bool)
    for i in ids:
        r = np.flatnonzero(pid == i); half[rng.choice(r, len(r) // 2, replace=False)] = True
    C = np.stack([Z[half & (pid == i)].mean(0) for i in ids])
    q = ~half
    pred = ids[np.argmin(((Z[q][:, None, :] - C[None]) ** 2).sum(-1), axis=1)]
    return float((pred == pid[q]).mean())

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    P, m = 200, 40                                      # 200 participants x 40 windows each
    pid = np.repeat(np.arange(P), m)
    t = np.tile(np.arange(m), P)                        # window index stands in for time
    # Random window split: almost every participant lands in both sets.
    rand_test = rng.random(len(pid)) < 0.2
    shared = np.intersect1d(pid[rand_test], pid[~rand_test]).size
    print(f"random window split: {shared}/{P} participants in both train and test")
    test = patient_split(pid)
    assert_no_leak(pid, ~test, test)
    tr, te = temporal_patient_split(pid, t, 29, 32, np.unique(pid[test]))
    assert_no_leak(pid, tr, te, t, 29, 32)
    print(f"patient+temporal split: train rows {tr.sum()}, test rows {te.sum()}, gap of 2 windows")
    keep = drop_after_index(np.array([1, 5, 9]), np.array([2, 12, 9]), 10)
    assert keep.tolist() == [True, False, True]        # event at 5 recorded at 12 is dropped
    # Embeddings with a strong per-person offset: the identity probe exposes it.
    offs = rng.normal(size=(P, 16)) * 2.0
    Z = offs[pid] + rng.normal(size=(len(pid), 16))
    acc = identity_probe_acc(Z, pid)
    print(f"identity probe accuracy {acc:.2f} (chance {1 / P:.3f})")
    assert acc > 0.5
    print("ok")

Output: random window split: 200/200 participants in both train and test, the patient-plus-temporal split sizes, and identity probe accuracy 0.99 (chance 0.005). The random split result matches \(1 - 0.2^{40} - 0.8^{40} \approx 0.9999\) per participant with 40 windows each. The recording-time test checks that an event at time 5 recorded at time 12 is dropped for an index time of 10.

Use in a pipeline. Run assert_no_leak on every evaluation job, with the split specification saved alongside the results; a split that cannot be reproduced from its specification is treated as failed. For pretraining overlap, the same check applies with the pretraining patient list in place of train.

Debugging. A result that drops sharply when switching from window to patient splits is the classic signature of identity leakage. A result that drops sharply from a random-patient to a temporal split indicates either drift or features recorded late; rerun with drop_after_index on recording times to separate the two. Identifier mismatches between systems (a wearable account id and a hospital record number for the same person) defeat patient-level splits silently; join them before splitting.

Leakage in production pipelines rarely comes from a single wrong line of code; it comes from data joins, delayed recording and shared corpora that no single team owns. Three problems recur.

Problem 1: late-recorded codes. Why it matters: a retrospective evaluation filtered on clinical time sees codes that a live system would not see until days later, so the offline number overstates live performance. Root cause: billing and discharge codes are entered after the encounter, but extracts often carry only the encounter date.

Worked incident · W2A W2 variant for in-hospital mortality reports AUROC 0.94 offline and 0.86 in a silent live run over three months. Diagnosis: the evaluation is rerun with features filtered on recording time instead of encounter date, and AUROC falls to 0.87; the five most important tokens in the offline model are discharge-disposition and palliative-care codes, which are recorded at or after discharge. Remedy: require recording timestamps in the extract, apply \(\mathcal{F}(t_0)\) on both times, and add a unit test that fails if any feature's recording time exceeds its index time. Validation: the hypothesis is supported because the corrected offline number (0.87) now matches the live number (0.86) within the interval; if a gap had remained, a population difference between the retrospective and live cohorts would have been the next suspect. (Illustrative numbers.)

Problem 2: pretraining overlap at scale. Foundation models are pretrained on large pooled corpora, often by another team, and later evaluated on cohorts drawn from the same sources. Diagnosis: maintain a registry of hashed patient identifiers per pretraining corpus version, and intersect it with every evaluation cohort; report the overlap count with the result. Remedy: exclude overlapping patients from evaluation or report results separately for overlapping and non-overlapping patients. Trade-off: hashed identifiers must use the same keyed hash across systems, which requires coordinated key management; identifiers that differ between systems (a wearable account id and a hospital record number for the same person) need a linkage step first.

Problem 3: identity shortcuts. Diagnosis: run the identity and site probes on every model version and track their accuracy over time. For W1, a participant-identity probe far above chance is expected; the alarm condition is a task that performs much better under a window split than under a participant split. Remedy: participant-level splits everywhere, including in hyperparameter search and early stopping; for site shortcuts, site-stratified evaluation and site hold-outs.

Automated checkRuns onFails when
Patient overlap train/testevery evaluation jobany overlapping identifier
Pretraining overlapevery evaluation cohortoverlap not reported or above the agreed limit
Recording time ≤ index timefeature extractionany violating event
Window-vs-patient split gapnew tasksAUROC gap > 0.03 (illustrative)
Random-patient vs temporal gapeach releasegap larger than in the previous release

These checks close the loop opened at the start of the chapter: an adapted model is only as credible as the split it was evaluated on. The practice chapter that follows builds the same checks into a reference architecture.

Health FMs in Practice

The earlier chapters describe how health foundation models are pretrained, adapted and evaluated. This chapter covers what it takes to run one: the system around the model, the problems that appear only after a model leaves a paper, and the order in which a team should spend effort. A health foundation model system here means the full pipeline from raw clinical or sensor data to a monitored prediction that someone acts on. Most of its engineering effort sits outside the network itself: data access under consent, harmonization into shared formats, patient-level split keys, a registry that ties weights to the data and tokenizer that produced them, per-site evaluation, change control and monitoring.

The chapter has three parts. The reference architecture lays out the stages and what each one receives and produces. Production challenges and solutions takes the ten problems that benchmarks do not measure (privacy, data silos, device heterogeneity, missingness, label scarcity, distribution shift, fairness, regulation, licensing, compute) and gives each a mechanism-level remedy. A practical playbook orders the work as an escalation ladder: cheap tests first, pretraining only when evidence demands it.

The three reference workloads appear throughout. W1 is a wearable PPG model with 50 million parameters trained on 30 million participant-hours; W2 is a 120-million-parameter generative model over 2 million patients' coded records; W3 is a polysomnography (PSG) model trained on 30,000 overnight studies. Each raises different production problems: W1 is dominated by device variation and missing data, W2 by site and temporal shift and by data governance, W3 by noisy labels and the transfer from the sleep lab to wearables.

The mental model for the chapter is that a foundation model is a shared asset with many consumers. Each downstream task, site and device is a consumer that needs its own evaluation, calibration and monitoring, while the pretrained weights change rarely and under control.

The quantitative side of practice is a set of budgets and error bars rather than new learning objectives. Three quantities recur in this chapter and are defined where they are used.

Resource budgets. For a signal corpus of \(H\) participant-hours sampled at \(f\) Hz in \(C\) channels with \(b\) bytes per sample, raw storage is \(S = 3600\,H f C b\). For a token corpus of \(D\) tokens and a model of \(N\) parameters, one training pass costs about \(6ND\) floating-point operations. These two formulas size the pretraining stage of the architecture.

Statistical uncertainty of a deployment decision. An AUROC estimated on \(n_+\) positives and \(n_-\) negatives has a standard error that shrinks roughly with the number of positives, not with the number of rows. The playbook uses this to decide whether a foundation model's gain over a baseline is real before money is spent on adaptation.

Drift and calibration. The population stability index \(\mathrm{PSI} = \sum_i (q_i - p_i)\ln(q_i/p_i)\) compares a monitored distribution \(q\) with a reference \(p\); logistic recalibration \(\operatorname{logit}\hat p' = a + b\,\operatorname{logit}\hat p\) repairs a model whose ranking is intact but whose probabilities no longer match observed rates at a site.

Worked example · W1, W2W1's raw grid is \(3600 \times 30\times10^{6} \times 64 \times 4 \times 2\) bytes \(\approx 55.3\) TB at 2 bytes per sample (a storage assumption). W2's code, value and time-gap tokens number about \(310\text{M} \times 1.475 \approx 457\)M (about 0.46 billion), so one pass of the 120M-parameter model costs about \(6 \times 1.2\times10^{8} \times 4.57\times10^{8} \approx 3.3\times10^{17}\) FLOP. W1's AFib probe (AUROC 0.93 against 0.88 from scratch) needs a paired comparison on the same participants to show its gain is real with 100 test positives; the playbook section works this out.

The code in this chapter consolidates the key techniques of the book into small, runnable modules, each with assertions that were executed: a budget calculator for W1 and W2; the stage contracts of the architecture (deterministic patient-level split keys, a tokenizer fitted on training patients only, a strict prediction-time filter, symmetric and leave-one-out InfoNCE, a registry record); a missingness-aware masked-patch encoder; production monitors (population stability index, logistic recalibration, federated averaging with full weights versus LoRA adapters); and the leakage-safe linear probe with an identity probe and AUROC standard errors.

The modules depend only on NumPy, PyTorch and scikit-learn. They favor clarity over speed: the masked-patch model processes a single channel, the federated code averages arrays in memory, and the probe uses scikit-learn's logistic regression. Each section states what must change for production scale, for example sharded sequential storage instead of per-window reads, or key-padding masks instead of mask tokens.

The tests share a pattern: one assertion that the computation is correct on a case with a known answer, and one assertion that guards against the specific failure the section discusses, such as test-set values moving the tokenizer's quantile edges or fabricated values entering the reconstruction loss.

Production work on a health foundation model has three properties that distinguish it from production work on a single-task model. First, one set of weights serves many tasks, sites and devices, so a fault in the shared encoder propagates to every consumer at once, and a change to the encoder requires re-validating all of them. Second, the inputs are regulated personal data whose governance (consent scope, data use agreements, license terms of public weights) constrains where training and inference can run. Third, labels arrive late and are noisy, so most production monitoring must work on inputs and embeddings rather than on outcome metrics.

The chapter treats each of these as an engineering problem with a diagnosis and a measurable remedy. The architecture section sizes storage, input/output and serving for W1 and W2 and explains why an embedding store with versioned back-fills is the main serving pattern. The production section works through incidents for device heterogeneity, missingness, temporal and site shift, federated training and regulation, with the dashboards that detect them. The playbook section turns the book's evidence into ordered steps with acceptance gates and the statistical tests that decide each gate.

Regulatory statements are current as of November 2026 and change often: the US Food and Drug Administration's (FDA) lifecycle guidance for AI-enabled device software remained a draft on the agency's priority list for finalization, and the EU's high-risk obligations for AI in medical devices apply from 2 August 2028 after the 2026 AI Omnibus.

Reference architecture

A reference architecture is a description of the stages a system needs, what each stage receives and produces, and where the boundaries between them sit, independent of any one vendor or codebase. For health foundation models it exists because the earlier way of building clinical models (one cohort, one feature set, one model per question) does not scale to a single pretrained model that serves dozens of tasks. When the model is shared, everything around it must be shared too: the snapshot it was trained on, the tokenizer that turned records into inputs, the split keys that keep evaluation honest, and the registry that records which version produced which prediction.

The architecture below is a synthesis of the systems described in this book, not the design of any single organization. It runs left to right through a build row that stays inside a governed environment, then right to left through a ship row that is repeated per task and per site, with monitoring feeding back into the data layer.

Reference architecture: data sources, harmonization, tokenization, pretraining, registry, adaptation, evaluation and deployment, with a feedback loop and governance layer. BUILD (offline, data stays in the governed environment) ① Data sources EHR events · notesPSG · ECG · EEGwearable streamsregistries · claimsconsent metadata ② Harmonize MEDS / OMOP mappingde-identificationsignal QC, resamplingpatient-level split keysversioned snapshots ③ Tokenize patches · beats · epochscodes · value binstime tokensmissingness masksvocab + scaler stats ④ Pretrain contrastive / maskedAR / TTE / JEPAsmall scaling sweepsprobe-based selectionfederated if multi-site ⑤ Registry weights + tokenizermodel card, data cardembedding storelicense and consent tagslineage to snapshot ⑥ Adapt linear / Cox probesLoRA per site or taskLP-FT · fine-tunecalibration layerdistill for edge ⑦ Evaluate task suite + baselinespatient + temporal splitssite / device hold-outsubgroups · calibrationleakage audit ⑧ Deploy & monitor batch or on-deviceinput drift, missingnessoutcome-based recalibrationchange control (PCCP)clinician feedback SHIP (per task, per site) checkpoints Governance across every stage consent and data-use agreements · access control and audit logs · privacy review · regulatory documentation · incident response
Fig. A reference architecture for health foundation models. The top row builds a pretrained model inside a governed environment; the bottom row ships it per task and site. The dashed path returns monitored data (new missingness patterns, drift, outcomes) to the data layer. A synthesis of the systems discussed in this book, not any single organization's design.

1. Data sources. Coded EHR events and notes; PSG, ECG and EEG recordings; wearable streams; registries and claims; and, as a first-class input, consent metadata stating what each record may be used for. The output is raw data with its use restrictions attached.

2. Harmonize. Records are mapped into a common format, de-identified and quality-checked. For EHR data the common formats are OMOP (a relational common data model used by observational research networks) and MEDS, the Medical Event Data Standard, which represents every dataset as rows of (subject, time, code, value). For signals, harmonization means resampling to a fixed rate, flagging poor-quality segments and recording device and firmware versions. Two decisions made here govern every later result: patient-level split keys, assigned once per patient so that all of a patient's records fall into the same split, and versioned snapshots, frozen copies of the data that a model can be traced back to. The output is a snapshot with split keys.

3. Tokenize. The snapshot is converted into model inputs: patches, beats or 30-second epochs for signals; code tokens, value bins and time tokens for events; and masks that mark missing data. The tokenizer has state (vocabulary, quantile edges for lab values, normalization statistics), and that state must be fitted on training patients only. The output is token sequences plus a versioned tokenizer.

4. Pretrain. A self-supervised objective is chosen to match the intended use: contrastive for person-level traits, masked reconstruction for imputation, autoregressive or time-to-event for prognosis, joint-embedding prediction where abstraction matters. Small scaling sweeps decide model size, and checkpoints are selected by probe performance on held-out tasks rather than by pretraining loss. When data cannot be pooled across institutions, pretraining or adaptation can be federated. The output is checkpoints.

5. Registry. Weights are stored together with their tokenizer, a model card and data card, license and consent tags, and a pointer to the snapshot. The registry may also hold an embedding store: precomputed vectors for every patient or participant, so downstream tasks fit small heads without rerunning the encoder.

6. Adapt. Per task and per site, the cheapest adaptation that meets the target is chosen: a linear or Cox probe on frozen embeddings, LoRA adapters, linear-probe-then-fine-tune (LP-FT), or full fine-tuning; then a calibration layer, and distillation if the model must run on a device.

7. Evaluate. A task suite with baselines, patient-level and temporal splits, site and device hold-outs, subgroup and calibration metrics, and a leakage audit.

8. Deploy and monitor. Batch or on-device inference; monitors for input drift and missingness; outcome-based recalibration as labels arrive; change control under a predetermined change control plan (PCCP) where the model is a regulated device; and clinician feedback. Monitored data returns to stage 1, which is how new missingness patterns, device versions and outcomes enter the next snapshot.

A governance band spans every stage: consent and data use agreements, access control and audit logs, privacy review, regulatory documentation and incident response.

Worked example · W1W1's 30 million participant-hours from 150,000 participants enter stage 1 with consent tags. Stage 2 resamples PPG and accelerometry to 64 Hz and assigns each participant one split key. Stage 3 cuts 10-second windows of 640 samples in four channels, about 10.8 billion window slots, and marks the 38% of the grid without PPG, leaving about 6.7 billion PPG-bearing windows. Stage 4 trains the 50M-parameter encoder with InfoNCE (temperature 0.1, batch 4,096, positives from the same participant within 24 hours) on 1% of windows per epoch. Stage 5 stores the encoder with its normalization statistics and a 256-dimensional embedding per participant-hour. Stage 6 fits a linear probe on 5,000 labelled participants; stage 7 reports AFib AUROC 0.93 against 0.88 for a supervised model trained from scratch, age MAE 6.1 years and resting heart rate MAE 2.4 bpm, each with participant-level splits.

Comparison with a single-task pipeline. A conventional clinical model has stages 1, 2, 6, 7 and 8 but no 3–5: features are hand-built per task, and nothing is shared. The foundation-model architecture adds the tokenizer and registry as shared, versioned assets. That buys reuse (a new task needs only a head) and label efficiency, at the cost of coupling: a change to the tokenizer or encoder invalidates every downstream head and evaluation until they are rerun. Most of the production discipline in the next section exists to manage that coupling.

Mental model. The build row is a factory that produces one expensive, slowly changing artifact; the ship row is a set of small, fast-changing products built on it; the registry is the contract between them.

The architecture is sized by four quantities: storage, read bandwidth during pretraining, pretraining compute, and the size of the embedding store that serves downstream tasks. Each follows from the workload's specification.

Windows and steps. Let \(H\) be participant-hours, \(w\) the window length in seconds, \(\rho\) the fraction of the grid with no signal, \(\phi\) the fraction of windows sampled per epoch and \(B\) the batch size. The number of window slots, signal-bearing windows and optimizer steps per epoch are

\[ M = \frac{3600\,H}{w}, \qquad M_{\text{obs}} = (1-\rho)\,M, \qquad \text{steps} = \frac{\phi\,M}{B}. \]
Worked example · W1With \(H = 3\times10^{7}\), \(w = 10\): \(M = 3600 \times 3\times10^{7} / 10 = 1.08\times10^{10}\) windows. With \(\rho = 0.38\): \(M_{\text{obs}} = 0.62 \times 1.08\times10^{10} \approx 6.7\times10^{9}\). With \(\phi = 0.01\) and \(B = 4096\): \(\lceil 1.08\times10^{8} / 4096 \rceil = 26{,}368\) steps per epoch.

Storage and read volume. With sampling rate \(f\), channels \(C\) and \(b\) bytes per sample, the raw grid occupies \(S = 3600\,H f C b\) bytes, and one epoch reads \(R = \phi M \cdot w f C b\) bytes.

Worked example · W1With \(f = 64\), \(C = 4\) and \(b = 2\) (int16 storage, an assumption): \(S = 3600 \times 3\times10^{7} \times 64 \times 4 \times 2 \approx 5.53\times10^{13}\) bytes, about 55.3 TB. Each window is \(640 \times 4 \times 2 = 5{,}120\) bytes, so one epoch reads \(1.08\times10^{8} \times 5{,}120 \approx 553\) GB. The volume is modest; the access pattern is not. If an epoch is to finish in four hours (an assumption), the loader must serve \(1.08\times10^{8} / 14{,}400 = 7{,}500\) windows per second, which random reads of 5 KB objects handle poorly. Sharding windows into large sequential files and sampling shards rather than windows is the usual remedy.

Pretraining compute for token models. For a transformer with \(N\) parameters trained on \(D\) tokens, one pass costs approximately \(6ND\) floating-point operations (2 for the forward pass and 4 for the backward pass, per parameter per token). For W2 the token count is the number of events times one plus the share of events that carry a value token \(s_v\) plus the number of time-gap tokens per event \(s_g\) (about one per eight events across the corpus, because gaps grow more slowly than events):

\[ D = E\,(1 + s_v + s_g) = 3.1\times10^{8} \times (1 + 0.35 + 0.125) \approx 4.57\times10^{8}. \]

So one pass costs about \(6 \times 1.2\times10^{8} \times 4.57\times10^{8} \approx 3.3\times10^{17}\) FLOP, and the corpus holds about 3.8 tokens per parameter. Waxler et al. (2025) fitted a compute-optimal ratio near 1,000 tokens per parameter for generative EHR models (CoMET). Reaching that ratio for a 120M-parameter model would take \(1000 \times 1.2\times10^{8} / 4.57\times10^{8} \approx 262\) passes over W2's corpus, so in the reference workload W2 is firmly data-limited: more data, not more parameters, is the binding constraint, and the number of passes must be chosen by held-out probe performance to avoid memorization. Training on far fewer tokens per parameter than the fitted optimum is a property of most single-institution EHR models.

Embedding store. With embedding dimension \(d\) and \(b_e\) bytes per value, storing one vector per observed window costs \(M_{\text{obs}}\,d\,b_e\) bytes; pooling to one vector per observed hour costs \((1-\rho)H\,d\,b_e\).

Worked example · W1With \(d = 256\) and fp16 (\(b_e = 2\)): per window, \(6.7\times10^{9} \times 256 \times 2 \approx 3.43\) TB; per hour, \(0.62 \times 3\times10^{7} \times 512 \approx 9.5\) GB. Hourly pooling shrinks the store by a factor of 360 and lets every downstream head train from a single machine's memory, at the cost of losing within-hour structure that tasks such as arrhythmia episode detection may need. Tasks that need window resolution read from the encoder directly.

Trade-offs. Each formula exposes a choice: \(\phi\) trades epoch time against coverage of the corpus; \(b\) and \(b_e\) trade precision against storage; pooling trades resolution against serving cost. The probe-based checkpoint selection in stage 4 is what makes these choices testable: a cheaper configuration is acceptable if held-out probe metrics are unchanged within their confidence intervals.

Two modules implement the architecture in miniature. The first is a budget calculator that encodes the formulas for storage, read volume, embedding store size and token-model compute, with assertions that reproduce the workload numbers. The second implements the contracts between stages 2 to 5: deterministic patient-level split keys, a tokenizer whose statistics are fitted on training patients only, a strict prediction-time filter, the pretraining loss, and a registry record.

Budget calculator. Inputs are the workload constants; outputs are sizes in TB or GB and FLOP counts. Two assumptions are explicit fields: int16 raw storage and fp16 embeddings.

"""Reference-architecture budget for W1 (wearable PPG) and W2 (EHR).
Every number traces to the workload sheet or to a stated storage assumption."""
import math
from dataclasses import dataclass

@dataclass(frozen=True)
class SignalCorpus:                    # W1
    participant_hours: float = 30e6
    hz: int = 64
    window_s: int = 10
    channels: int = 4                  # PPG + 3-axis accelerometry
    missing_ppg: float = 0.38          # share of the grid with no PPG
    epoch_fraction: float = 0.01       # windows sampled per epoch
    batch: int = 4096
    emb_dim: int = 256
    bytes_per_sample: int = 2          # ASSUMPTION: int16 raw storage
    bytes_per_emb: int = 2             # ASSUMPTION: fp16 embeddings

    def windows(self):            return self.participant_hours * 3600 / self.window_s
    def ppg_windows(self):        return self.windows() * (1 - self.missing_ppg)
    def windows_per_epoch(self):  return self.windows() * self.epoch_fraction
    def steps_per_epoch(self):    return self.windows_per_epoch() / self.batch
    def raw_tb(self):             # full 64 Hz grid, all channels
        return self.participant_hours * 3600 * self.hz * self.channels * self.bytes_per_sample / 1e12
    def epoch_read_gb(self):      # bytes actually read per epoch
        return self.windows_per_epoch() * self.window_s * self.hz * self.channels * self.bytes_per_sample / 1e9
    def window_emb_tb(self):      # one embedding per PPG-bearing window
        return self.ppg_windows() * self.emb_dim * self.bytes_per_emb / 1e12
    def hourly_emb_gb(self):      # mean-pooled to one embedding per PPG-bearing hour
        return self.participant_hours * (1 - self.missing_ppg) * self.emb_dim * self.bytes_per_emb / 1e9

@dataclass(frozen=True)
class EventCorpus:                     # W2
    events: float = 310e6
    value_share: float = 0.35          # events that also emit a decile token
    gap_share: float = 0.125           # time-gap tokens per event (about 1 per 8 events)
    params: float = 120e6
    tokens_per_param_opt: float = 1000 # CoMET's fitted compute-optimal ratio

    def tokens(self):                  # code + value + time-gap tokens
        return self.events * (1 + self.value_share + self.gap_share)
    def flops_per_pass(self):          # standard 6 * N * D training estimate
        return 6 * self.params * self.tokens()
    def passes_to_optimum(self):       # how many passes to reach 1,000 tokens/param
        return self.tokens_per_param_opt * self.params / self.tokens()

if __name__ == "__main__":
    w1, w2 = SignalCorpus(), EventCorpus()
    assert round(w1.windows() / 1e9, 1) == 10.8          # 10.8 B windows
    assert round(w1.ppg_windows() / 1e9, 1) == 6.7       # 6.7 B carry PPG
    assert math.ceil(w1.steps_per_epoch()) == 26368      # ceil(108 M windows / 4,096)
    print(f"W1 raw grid {w1.raw_tb():.1f} TB, read/epoch {w1.epoch_read_gb():.0f} GB, "
          f"window embeddings {w1.window_emb_tb():.2f} TB, hourly {w1.hourly_emb_gb():.1f} GB")
    assert abs(w1.raw_tb() - 55.3) < 0.1 and abs(w1.epoch_read_gb() - 553) < 1
    assert abs(w1.window_emb_tb() - 3.43) < 0.01 and abs(w1.hourly_emb_gb() - 9.5) < 0.1
    print(f"W2 tokens {w2.tokens()/1e6:.1f} M ({w2.tokens()/w2.params:.2f} per parameter), 6ND per pass {w2.flops_per_pass():.2e} FLOP, "
          f"passes to 1,000 tok/param {w2.passes_to_optimum():.0f}")
    assert abs(w2.tokens() - 457.25e6) < 1e3              # about 0.46 B tokens
    assert 261 < w2.passes_to_optimum() < 263

Running it prints W1 raw grid 55.3 TB, read/epoch 553 GB, window embeddings 3.43 TB, hourly 9.5 GB and W2 tokens 457.2 M (3.81 per parameter), 6ND per pass 3.29e+17 FLOP, passes to 1,000 tok/param 262; all assertions pass.

Stage contracts. The split function hashes a salted patient identifier into 100 buckets (80 train, 10 validation, 10 test). Because the hash depends only on the patient, every row of that patient lands in the same split, and the assignment is reproducible from the snapshot's salt. fit_lab_edges computes nine decile cut points per lab from training patients only; the test appends 500 extreme values from a test patient and asserts the edges do not move, which is the leakage guard. tokens_before keeps only events strictly before the prediction time; in production the comparison should use the time a value was recorded in the system rather than the clinical time it refers to, since a lab drawn before the prediction time can be resulted after it. info_nce is the symmetric, CLIP-style loss with in-batch negatives; leave_one_out_nce is the SleepFM-style multimodal variant (Thapa et al. 2024), which aligns each modality with the mean of the others.

"""Stage contracts of the reference architecture, in miniature.
snapshot -> split keys -> tokenizer fitted on TRAIN only -> pretraining loss -> registry record."""
import hashlib, json, bisect
import numpy as np
import torch
import torch.nn.functional as F

# 1. Split keys: assigned once per patient, deterministic, never per row.
def split_of(patient_id: str, salt: str = "snapshot-v1") -> str:
    h = int(hashlib.sha256((salt + patient_id).encode()).hexdigest(), 16) % 100
    return "train" if h < 80 else ("valid" if h < 90 else "test")

# 2. Tokenizer statistics fitted on training patients only.
def fit_lab_edges(rows, split):
    """rows: (patient_id, time, code, value). Returns 9 decile cut points per lab."""
    vals = {}
    for pid, _, code, v in rows:
        if v is not None and split[pid] == "train":
            vals.setdefault(code, []).append(v)
    return {c: list(np.quantile(v, np.linspace(0.1, 0.9, 9))) for c, v in vals.items()}

def tokens_before(rows, pid, index_time, edges):
    """Strictly earlier events only (use recording time if it differs from clinical time)."""
    out = []
    for p, t, code, v in sorted(rows, key=lambda r: r[1]):
        if p != pid or t >= index_time:
            continue
        out.append(code)
        if v is not None and code in edges:
            out.append(f"Q{bisect.bisect_right(edges[code], v)}")
    return out

# 3. Pretraining loss for the signal branch: symmetric InfoNCE (CLIP-style).
def info_nce(z_a, z_b, tau=0.1):
    """z_a[i], z_b[i] are a positive pair (W1: two windows of one participant within 24 h)."""
    z_a, z_b = F.normalize(z_a, dim=-1), F.normalize(z_b, dim=-1)
    logits = z_a @ z_b.T / tau                                  # (N, N)
    targets = torch.arange(z_a.size(0))
    return 0.5 * (F.cross_entropy(logits, targets) + F.cross_entropy(logits.T, targets))

def leave_one_out_nce(zs, tau=0.1):
    """SleepFM-style: align each modality with the mean of the others. zs: K tensors (N, d)."""
    loss = 0.0
    for m, z in enumerate(zs):
        others = torch.stack([zs[j] for j in range(len(zs)) if j != m]).mean(0)
        loss = loss + info_nce(z, others, tau)
    return loss / len(zs)

# 4. Registry record: weights are never shipped without their provenance.
def registry_record(name, weights_sha, tokenizer, snapshot, license_, consent_scope):
    tok_sha = hashlib.sha256(json.dumps(tokenizer, sort_keys=True).encode()).hexdigest()[:12]
    return {"model": name, "weights_sha": weights_sha, "tokenizer_sha": tok_sha,
            "snapshot": snapshot, "license": license_, "consent_scope": consent_scope}

if __name__ == "__main__":
    pids = [f"p{i}" for i in range(2000)]
    split = {p: split_of(p) for p in pids}
    assert split_of("p7") == split_of("p7")                      # deterministic
    share = sum(s == "train" for s in split.values()) / len(pids)
    assert 0.76 < share < 0.84, share
    rng = np.random.default_rng(0)
    rows = [(p, float(t), "LAB:K", float(rng.normal(4.2, 0.4))) for p in pids for t in range(3)]
    edges = fit_lab_edges(rows, split)
    # leakage guard: adding extreme TEST values must not move the edges
    test_p = next(p for p in pids if split[p] == "test")
    rows2 = rows + [(test_p, 9.0, "LAB:K", 99.0)] * 500
    assert fit_lab_edges(rows2, split) == edges
    toks = tokens_before(rows, "p0", index_time=2.0, edges=edges)
    assert len(toks) == 4 and toks[0] == "LAB:K"                 # events at t=0,1 only
    # InfoNCE sanity: aligned pairs -> low loss; unrelated pairs -> about log N
    torch.manual_seed(0)
    N, d = 4096, 256                                             # W1 batch and embedding size
    z = torch.randn(N, d)
    aligned = info_nce(z, z + 0.01 * torch.randn(N, d)).item()
    random_ = info_nce(z, torch.randn(N, d)).item()
    print(f"aligned {aligned:.4f}  random {random_:.2f}  log N {np.log(N):.2f}")
    assert aligned < 0.3 and abs(random_ - np.log(N)) < 0.5
    assert leave_one_out_nce([z, z.clone(), z.clone()]).item() < 0.3
    rec = registry_record("w1-ppg-50m", "ab12cd", {"patch": 640}, "snapshot-v1",
                          "internal", "research-only")
    assert rec["consent_scope"] == "research-only"
    print("all pipeline checks passed")

The output is aligned 0.2038 random 8.52 log N 8.32. Unrelated pairs give a loss close to \(\ln 4096 \approx 8.32\), as they should when the model cannot pick the positive out of 4,096 candidates. Nearly identical pairs do not reach zero: at temperature 0.1, random 256-dimensional negatives still have cosine similarities around \(\pm 1/16\), which become logits around \(\pm 0.6\), and 4,095 of them leave a residual of about 0.2. A loss stuck near \(\ln N\) during real training signals collapsed or mis-paired positives; a loss far below the aligned floor signals a shortcut such as positives sharing identical padding.

Debugging tips. Check the split share per snapshot (here 0.76–0.84 train); re-fit the tokenizer whenever the snapshot changes and store its hash in the registry record; and log the number of tokens dropped by the prediction-time filter per patient, since a sudden fall to zero usually means a time-zone or timestamp-unit error rather than a real change.

At scale the architecture fails at its boundaries: the loader cannot feed the trainer, embeddings from two encoder versions are mixed, or a model is served with a tokenizer it was not trained with. Each problem below follows the same pattern of cause, measurement and remedy.

Problem 1: the input pipeline, not the GPU, sets pretraining speed. Why it matters: a contrastive encoder that waits for data costs GPU time without learning. Root cause: per-window objects stored individually turn an epoch into millions of small random reads, and the positive-pair rule (same participant within 24 hours) requires a second read from the same participant for every anchor.

Worked incident · W1An epoch reads 108 million windows (553 GB). The first training run stored one object per window and reached 2,100 windows per second across the loader workers, so an epoch took about 14 hours while GPU utilization averaged 31%. The 4-hour target needs 7,500 windows per second. Profiling showed 80% of loader time in object-store requests. The remedy repacked each participant-day into one sequential shard of up to 8,640 windows (1,440 minutes × 6 windows), sampled shards, then drew anchor and positive from within the shard. Throughput rose to 9,800 windows per second and GPU utilization to 86%. (Illustrative numbers.)

Diagnosis: track loader throughput, GPU utilization and time-in-data-wait per step; a step time that does not change when the model is made smaller is input-bound. Remedy, in order: (1) shard by participant-day so positives are local; (2) decode and normalize on the loader workers, not the GPU; (3) cache the 62% of windows that carry PPG and skip empty slots at shard-build time rather than at read time. Cost and trade-off: participant-day shards make sampling less uniform within an epoch (a shard contributes many windows at once). Validation: the fix is supported if the probe metrics of a checkpoint trained with shard sampling match those of the per-window sampler at equal steps (AFib AUROC within its interval of 0.93); it is weakened if probes degrade, which would indicate that within-shard sampling reduces negative diversity. Mixing windows from several shards in each batch addresses that.

Problem 2: embedding version skew. Root cause: the embedding store is back-filled with a new encoder while heads trained on the old vectors keep serving. Two encoders that differ only by a random seed produce embedding spaces related by an unknown rotation, so a linear head trained on one is meaningless on the other.

Serving W1 embeddings: windows are encoded once in batches, pooled to hourly embeddings, stored with their model version, and read by many small task heads.Device sync10-s windowsQC flagsBatch encoder50M paramsGPU, versionedHourly poolingmean of observedwindows + countEmbedding store256-d fp16keyed by versionTask headsAFib, age, HRlinear, per taskEncode once, read many: a new head costs a linear fit on stored vectors, not a pass over raw signal.A new encoder version means a back-fill; old and new vectors are never mixed in one head.Monitor: windows per hour, share of empty hours, encoder throughput, store freshness lag.
Fig. The W1 serving path. Pooling to hourly vectors reduces the store from about 3.4 TB of window embeddings to about 9.5 GB, at the cost of within-hour detail.

Diagnosis: every stored vector carries the encoder version; every head records the version it was fitted on; the serving layer refuses a mismatch. A cheap canary is a fixed set of 1,000 reference windows whose embeddings are recomputed on every deployment and compared with stored values by cosine similarity. Remedy: blue-green back-fills: write the new version alongside the old, refit all heads on the new version, run the evaluation suite, then switch heads and vectors together. Cost: back-filling 6.7 billion windows is a full inference pass over the corpus; in the reference workload, at an assumed 1 GFLOP per window forward pass and 400 TFLOP/s effective throughput per accelerator, that is about \(6.7\times10^{18} / 4\times10^{14} \approx 16{,}750\) accelerator-seconds of compute, small next to the I/O of reading 34 TB of PPG-bearing windows. Hourly pooled vectors double the storage only briefly during the switch (two copies of 9.5 GB).

Problem 3: tokenizer or normalization drift between training and serving. Root cause: serving code recomputes normalization statistics or lab quantile edges from recent data instead of loading the frozen ones. For W2, a recomputed decile edge set shifts which values map to which of the 10 value tokens; the model's inputs change while the data have not. Diagnosis: hash the tokenizer state and compare the hash at serving time with the registry record; monitor the token-frequency distribution against training. Remedy: ship the tokenizer as part of the model artifact and treat any change to it as a model change.

Problem 4: simulation cost for generative EHR models. W2 can estimate risk by sampling future timelines; cost per question is roughly the number of rollouts times the generated tokens per rollout. Where the same question is asked for every patient daily, distilling the simulated risk into a direct prediction head, trained on the simulator's outputs, replaces many rollouts with one forward pass. The trade-off is that the distilled head answers only the questions it was trained for.

StageService-level metricIllustrative target (W1)Alert when
HarmonizeSnapshot build success; share of windows failing QCQC failure < 5%Share changes by more than 2 points week over week
PretrainLoader windows/s; GPU utilization≥ 7,500 windows/s; ≥ 80%Data-wait > 20% of step time
RegistryTokenizer hash match; encoder version on every vector100%Any mismatch
ServeEmbedding freshness lag; empty-hour share< 24 h; ≈ 38%Lag > 48 h; empty share > 42%
EvaluateProbe metrics per releaseAFib AUROC 0.93 ± intervalDrop outside interval

Table. Stage-level service metrics for the W1 architecture. Targets are illustrative and depend on the deployment.

Connection. The architecture fixes where data, tokenizer and weights live and how they are versioned. The next section addresses the problems that arise even when the architecture is sound: data that cannot be pooled, devices that differ, shifts over time and regulatory change.

Production challenges and solutions

A production challenge, in this section, is a problem that blocks or degrades the use of a health foundation model in a clinic, a hospital network or a consumer device but that standard benchmarks do not measure. Benchmarks fix the data, the split and the label; production does not. Who may see the data, where training may run, which devices produce the signal, how populations and coding change over time, and what a regulator requires all vary, and each can turn a strong published result into a weak deployed one.

Ten challenges recur. The table maps each to the reason it bites and to concrete mitigations; the paragraphs after it explain the mechanism of each remedy.

ChallengeWhy it bitesSolutions
Privacy and consentHealth data is regulated and consent may restrict secondary use or model release (Apple did not release WBM weights for this reason)De-identify at ingestion; train inside the governed environment; tag models with consent scope; release only probes or aggregated results when weights cannot leave
Data access and silosThe data needed for breadth sits in many institutions that cannot pool itFederated averaging (McMahan et al. 2017) for pretraining or LoRA adapters; common formats (MEDS, OMOP) so code travels instead of data; data use agreements for released models (EHRSHOT's approach)
Device heterogeneitySensors, firmware, sampling rates and placement shift signals; models trained on one brand fail on anotherChannel-agnostic encoders (SleepFM's attention pooling); per-device normalization statistics; device hold-out evaluation; small per-device adapters
MissingnessWearables are off-wrist, labs are ordered selectively, PSG channels vary by clinicMask-aware tokenization and attention masking (LSM-2's AIM); missingness indicators as inputs; evaluate with channels and hours removed
Label scarcity and noiseClinical labels are rare, delayed and noisy (inter-scorer κ ≈ 0.76 for sleep staging)Frozen probes and few-shot protocols; time-to-event labels that use censored patients; report label agreement as the ceiling
Distribution shiftPractice patterns, populations and codes drift; site effects dominate embeddingsTemporal and site hold-outs; drift monitors on inputs and embeddings; local recalibration; scheduled re-validation
FairnessProxy labels and skewed cohorts (device owners, sleep-clinic patients) create unequal performanceSubgroup metrics and calibration; audit labels for proxies; reweighting or targeted data collection
RegulationClinical use may make the model a medical device, and FMs change oftenUS: plan updates with a predetermined change control plan (FDA final PCCP guidance, Dec 2024) and follow the draft lifecycle guidance (Jan 2025); for consumer wearables, the revised general wellness policy (Jan 2026). EU: high-risk obligations for AI in medical devices apply from 2 August 2028 after the 2026 AI Omnibus (Regulation (EU) 2026/1744)
LicensingOpen weights may restrict commercial use (TimesFM 3.0's weights are non-commercial; 2.5 and earlier are Apache-2.0)Track licenses in the registry; prefer permissive models for products; use hosted offerings where the license requires
Compute and latencyLong contexts, multimodal encoders and generative simulation (n rollouts per patient) are expensivePatch and context sizing; subquadratic backbones (Mamba-style, as in WBM and Context Clues); cache embeddings; distill simulated risks into direct predictors

Table. Production challenges for health foundation models and the mitigations that address them. Regulatory dates as of November 2026.

Where each production challenge enters the pipeline: six pipeline stages in a row, with the challenges that are decided at each stage listed beneath it.DataaccessconsentPrivacy and consentData silosHarmonizeformatssnapshotDevice heterogeneityMissingnessPretraincomputelicenseCompute and latencyLicensingAdaptlabelssitesLabel scarcityand noiseEvaluatesubgroupsshiftDistribution shiftFairnessDeploymonitorchange controlRegulationDrift monitorsPIPELINE STAGECHALLENGE DECIDED HEREMonitoring returns drift, missingness and outcomes to the data stage.A challenge left open at one stage reappears as a failure at a later one.
Fig. Each production challenge is decided at a specific pipeline stage. The mapping is a simplification: privacy, for example, constrains every stage, but its main design choices are made where data enters.

Privacy and consent. Consent and data use agreements state what data may be used for; a pretrained model's weights may count as a derivative of that data, and in rare cases models can reveal training examples. The remedy therefore works at three points: identifiers are removed when data enters the governed environment; training and inference run inside it; and every model carries a consent-scope tag stating what its training data permits (for example research only, or product use). When weights cannot leave, the organization can still publish what was learned through probes, aggregate results or hosted inference. Erturk et al. (2025) did not release the weights of Apple's wearable behavior model (WBM) for consent reasons, which illustrates the trade-off: compliance at the cost of reproducibility by others.

Data access and silos. No single hospital sees the full breadth of practice. Federated averaging (FedAvg; McMahan et al. 2017) addresses this without pooling records: a coordinating server sends the current model to each site, each site trains for a few steps on its own data, and the server averages the returned parameters, weighted by each site's sample count. Only parameters cross institutional boundaries. Training only small LoRA adapters federatively, rather than all weights, reduces the data sent per round by orders of magnitude. A 2026 preprint simulated a GPT-style EHR model across five non-identically distributed hospital partitions of MIMIC-IV and found that FedAvg recovered about 85% of centralized AUPRC (and 98–100% of per-condition AUROC), while ensembling separately trained site models at inference time recovered about 77% without any training-time exchange (Elemento 2026, not peer-reviewed). The limitation is that federated training is slower, harder to debug and still requires each site to run compatible software, which is why common formats such as MEDS and OMOP matter: they let code travel instead of data. EHRSHOT took a third route, releasing de-identified data under a data use agreement (Wornow et al. 2023).

Device heterogeneity. Different sensors, firmware, sampling rates and wear positions change a signal's amplitude, noise and morphology, so an encoder trained on one device family can fail on another. Remedies operate at input, model and evaluation level: per-device normalization statistics; encoders that accept any subset of channels (SleepFM pools across available channels with attention, Thapa et al. 2024); small per-device adapters; and evaluation that holds out whole devices. Pulse-PPG's comparison of lab and field PPG is an example of measuring this gap explicitly (Saha et al. 2025).

Missingness. Health data is missing by design: watches are off-wrist or charging, labs are ordered when a clinician suspects a problem, PSG montages differ by clinic. Filling gaps with zeros or interpolated values teaches the model fabricated patterns. Mask-aware tokenization instead marks missing segments, keeps them out of attention and out of the loss; LSM-2's adaptive and inherited masking (AIM) does this for wearable streams (Xu et al. 2025). Missingness indicators can also be inputs, because the pattern itself carries information (a lab ordered at 3 a.m. signals concern). Evaluation should report metrics with channels and hours removed.

Label scarcity and noise. Clinical labels are rare, delayed and disagree between experts; two human sleep scorers agree at Cohen's κ of about 0.76. Frozen probes and few-shot protocols make the most of few labels; time-to-event objectives use patients whose follow-up ended before an event (censored patients) instead of discarding them; and inter-rater agreement should be reported as the ceiling against which model agreement is read.

Distribution shift. Practice patterns, populations and coding systems change over time and differ between sites, and site effects often dominate embeddings. Temporal and site hold-outs measure the effect before deployment; drift monitors on inputs and embeddings detect it after; local recalibration repairs probabilities whose ranking is intact; scheduled re-validation catches slow decay.

Fairness. Proxy labels (for example, utilization standing in for illness) and skewed cohorts (device owners, sleep-clinic referrals) produce unequal performance across groups. Subgroup metrics with confidence intervals, subgroup calibration, label audits for proxies, and reweighting or targeted data collection are the remedies; the subgroup sizes must be large enough for the intervals to be informative.

Regulation. A model used for diagnosis or treatment decisions may be a medical device, and foundation models change more often than devices traditionally do. In the US, a predetermined change control plan (PCCP) lets a manufacturer describe in advance which modifications it will make and how it will validate them, so that authorized changes do not each need a new submission; FDA finalized PCCP guidance for AI-enabled devices in December 2024. Its broader lifecycle guidance for AI-enabled device software, issued as a draft in January 2025, was listed as a top priority for finalization in the device center's fiscal 2027 guidance agenda (RAPS 2026). For consumer wearables, FDA's revised general wellness guidance of 6 January 2026 allows non-invasive products that estimate physiologic parameters to remain wellness products if they avoid disease references, clinical thresholds and alerts that prompt clinical action (Covington 2026). In the EU, the AI Omnibus, Regulation (EU) 2026/1744, entered into force on 27 July 2026 and moved high-risk obligations for AI embedded in products such as medical devices to 2 August 2028 (White & Case 2026). Health systems deploying such tools are also expected to validate locally and monitor: the Joint Commission and the Coalition for Health AI (CHAI) issued joint guidance in September 2025 covering governance, local validation and ongoing monitoring (AHA News 2025).

Licensing. Open weights are not always free to use commercially: TimesFM 3.0's weights are non-commercial, while 2.5 and earlier were released under Apache-2.0 (TimesFM repository). The registry should record each model's license and block a non-commercial model from a product pipeline.

Compute and latency. Long contexts, several modality encoders and generative simulation (many sampled futures per patient) are expensive. Remedies are sizing patches and contexts, subquadratic backbones such as Mamba-style state-space models (used in WBM; in Context Clues, Mamba at 16k tokens reached the best mean AUROC on 14 EHRSHOT tasks, 0.807 against a prior best of 0.777), caching embeddings, and distilling simulated risks into direct predictors.

Worked example · W1, W2, W3Each workload meets a different subset. W1's dominant problems are device heterogeneity and missingness: 38% of its grid has no PPG, and every firmware update can shift signal statistics. W2's are silos and shift: its 2 million patients come from several sites, and it is trained on data to 2022 and tested on 2024. W3's is label noise: its staging κ of 0.78 against single-scorer labels is above the inter-scorer κ of about 0.76, so further gains against that label cannot be read as better staging; its transfer to wearable-only input drops to κ 0.62, a device-heterogeneity problem.

Mental model. Each challenge is decided at one stage of the pipeline (the figure), and a challenge left open there reappears later as a deployment failure. The remedies are mostly about data handling, evaluation design and process; few require changing the model.

Four challenges have a compact mathematical core: federated training (aggregation and communication), drift detection, recalibration under shift, and the statistics of subgroup and noisy-label evaluation. Missingness adds a simple accounting argument about the loss.

Federated averaging. Let \(K\) sites hold \(n_k\) examples each, \(n = \sum_k n_k\), and let \(\theta^{(t)}\) be the shared parameters after round \(t\). Each site starts from \(\theta^{(t)}\), runs \(E\) local optimizer steps on its own loss \(L_k\) and returns \(\theta_k^{(t+1)}\). The server sets

\[ \theta^{(t+1)} = \sum_{k=1}^{K} \frac{n_k}{n}\,\theta_k^{(t+1)}. \]

With \(E = 1\) and full-batch gradients this equals one gradient step on the pooled loss \(L = \sum_k (n_k/n) L_k\). With \(E > 1\) and non-identically distributed sites, local models drift toward their own optima (client drift), which is why federated results usually fall short of centralized training.

One round of federated averaging: the server broadcasts the shared parameters, each site trains locally, and the server averages the returned parameters weighted by site sample count.Serverθ(t+1) = Σ (n_k / n) θ_kSite 1n₁ = 900k patientsE local steps on θ(t)Site 2n₂ = 700k patientsE local steps on θ(t)broadcast θ(t)return θ_kSite 3n₃ = 400k patientsE local steps on θ(t)Only parameters (or LoRA adapters) cross site boundaries; records stay inside each site.
Fig. One round of federated averaging over three sites with W2-scale patient counts. Site sizes are illustrative and sum to W2's 2 million patients.

Communication. If \(P\) parameters of \(b\) bytes each are sent down and up to each of \(K\) sites, one round moves \(2PKb\) bytes. A rank-\(r\) LoRA adapter (Hu et al. 2022) on a frozen \(d \times d\) matrix \(W\) learns the update \(\Delta W = BA\) with \(B \in \mathbb{R}^{d\times r}\) and \(A \in \mathbb{R}^{r \times d}\), which is \(2dr\) trainable parameters, so adapting \(m\) matrices in each of \(\ell\) layers trains \(P_{\text{LoRA}} = 2\,\ell\,m\,d\,r\) parameters.

Worked example · W2W2's 2 million patients sit at three sites with 900k, 700k and 400k patients (an illustrative split), so the weights are 0.45, 0.35 and 0.20. If two site models assign a parameter values 1.0 and 2.0 and the third 4.0, the average is \(0.45 + 0.70 + 0.80 = 1.95\). Full-weight FedAvg moves \(2 \times 1.2\times10^{8} \times 3 \times 2 = 1.44\) GB per round in fp16. Assuming a 12-layer model of width \(d = 768\) (consistent with 120M parameters including a 42,074-token embedding table) and rank-8 LoRA on the query and value projections, \(P_{\text{LoRA}} = 2 \times 12 \times 2 \times 768 \times 8 = 294{,}912\), and a round moves \(2 \times 294{,}912 \times 3 \times 2 \approx 3.5\) MB, about 407 times less.

Population stability index. Fix bins on a reference window, with reference proportions \(p_i\) and current proportions \(q_i\). Then

\[ \mathrm{PSI} = \sum_{i} (q_i - p_i)\,\ln\frac{q_i}{p_i}, \]

a symmetrized Kullback–Leibler divergence (\(\mathrm{KL}(q\|p) + \mathrm{KL}(p\|q)\)). It is zero when distributions match and grows with shift in any bin. Common practice treats values below 0.1 as stable and above 0.25 as major shift; these are conventions, not statistical tests, and each deployment should set its own thresholds from the variation seen between stable reference periods.

Worked example · W1Suppose the per-participant daily off-wrist share is summarized in three bins with reference proportions (0.3, 0.4, 0.3), and after a firmware update the proportions are (0.2, 0.4, 0.4). Then \(\mathrm{PSI} = (-0.1)\ln(0.2/0.3) + 0 + (0.1)\ln(0.4/0.3) = 0.0405 + 0.0288 = 0.069\). With ten decile bins and a shift of the mean off-wrist share from 0.38 to 0.45, a simulation of per-participant off-wrist shares gives PSI 0.22, above W1's illustrative action threshold of 0.20.

Recalibration. Shift often preserves ranking (AUROC) but breaks calibration. Logistic recalibration fits two numbers on local outcomes,

\[ \operatorname{logit}\hat p' = a + b\,\operatorname{logit}\hat p, \qquad \operatorname{logit} p = \ln\frac{p}{1-p}, \]

where the intercept \(a\) corrects the overall level (calibration-in-the-large) and the slope \(b\) corrects over- or under-confidence; \(b < 1\) means predictions are too extreme. Because the map is monotone, AUROC is unchanged.

Worked example · W2At a new site, suppose W2's 1-year mortality model has calibration intercept \(-0.4\) and slope 0.8. A raw prediction of 0.30 has logit \(-0.847\); the recalibrated logit is \(-0.4 + 0.8 \times (-0.847) = -1.078\), a risk of 0.254. The model's AUROC of 0.89 is untouched; its ECE, 0.03 at the development site, is restored only after this local fit.

Missingness and the loss. In masked reconstruction, let a fraction \(\rho\) of patches be missing and a fraction \(r\) be masked at random among all patches. If the loss is averaged over all masked patches, a fraction \(\rho\) of the loss terms compares the reconstruction with a fabricated target (a zero or an interpolated value). The correct loss restricts both masking and scoring to observed patches,

\[ \mathcal{L} = \frac{\sum_{j} m_j\,o_j\,\lVert \hat x_j - x_j\rVert^2}{\sum_j m_j\,o_j}, \]

with \(m_j = 1\) if patch \(j\) is artificially masked and \(o_j = 1\) if it is observed. For W1, with \(\rho = 0.38\), the naive loss would draw 38% of its terms from fabricated targets.

Subgroup uncertainty. The Hanley–McNeil approximation gives the standard error of an AUROC \(A\) estimated on \(n_+\) positives and \(n_-\) negatives:

\[ \mathrm{SE}^2 = \frac{A(1-A) + (n_+-1)(Q_1 - A^2) + (n_- - 1)(Q_2 - A^2)}{n_+ n_-}, \quad Q_1 = \frac{A}{2-A},\; Q_2 = \frac{2A^2}{1+A}. \]
Worked example · W1A device subgroup with 400 participants of whom 40 have AFib (an assumed 10% prevalence) gives SE 0.028 at \(A = 0.93\) and 0.038 at \(A = 0.86\). An observed drop from 0.93 to 0.86 is then \(0.07 / \sqrt{0.028^2 + 0.038^2} = 0.07/0.047 \approx 1.5\) standard errors, not conclusive at the 5% level. With 140 positives per group, the 95% half-width at 0.86 shrinks to about 0.04, enough to separate the two.

Noisy labels as a ceiling. Cohen's \(\kappa = (p_o - p_e)/(1 - p_e)\) corrects observed agreement \(p_o\) for chance agreement \(p_e\). With the same stage proportions for both raters (W 15%, N1 8%, N2 45%, N3 15%, REM 17%, an assumption), \(p_e = 0.15^2 + 0.08^2 + 0.45^2 + 0.15^2 + 0.17^2 = 0.2828\), so W3's κ of 0.78 corresponds to \(p_o = 0.2828 + 0.78 \times 0.7172 = 0.842\); inter-scorer κ 0.76 corresponds to \(p_o = 0.828\); the wearable transfer κ 0.62 corresponds to \(p_o = 0.727\). A model that agrees with one scorer more than two scorers agree with each other has reached the label's ceiling; further gains measure fit to that scorer.

Two modules implement the remedies. The first is a masked-patch encoder, corrected so that per-window normalization ignores missing samples, with tests that the loss never scores a fabricated target and does not depend on what sits in a gap. The second implements the monitors and the federated arithmetic: population stability index, logistic recalibration with expected calibration error (ECE), FedAvg, and the communication cost of full weights versus LoRA adapters.

Missingness-aware masked patch pretraining. Inputs: a batch x of shape (B, L) for one channel and a boolean observed of the same shape. The window is cut into P = L / 64 patches; a patch counts as observed only if all its samples are. Artificial masks are drawn among observed patches only; natural gaps are replaced by the mask token so the encoder never sees fabricated values; the loss averages only over artificially masked observed patches. The Classic version normalized each window with a mean and standard deviation computed over all samples, which become NaN when a gap is filled with NaN; the version below computes them over observed samples only.

"""Missingness-aware masked patch pretraining (Classic edition's model,
with per-window normalization computed over observed samples only).
Natural gaps are hidden from the encoder AND excluded from the loss."""
import torch, torch.nn as nn

class MaskedPatchModel(nn.Module):
    def __init__(self, patch_len=64, d=256, depth=6, heads=8, max_patches=1024):
        super().__init__()
        self.patch_len = patch_len
        self.embed = nn.Linear(patch_len, d)
        self.pos = nn.Parameter(torch.zeros(1, max_patches, d))
        self.mask_token = nn.Parameter(torch.zeros(1, 1, d))
        layer = nn.TransformerEncoderLayer(d, heads, 4 * d, batch_first=True, norm_first=True)
        self.encoder = nn.TransformerEncoder(layer, depth, enable_nested_tensor=False)
        self.head = nn.Linear(d, patch_len)          # light decoder, dropped after pretraining

    def forward(self, x, mask_ratio=0.5, observed=None, return_masks=False):
        # x: (B, L) one channel; observed: (B, L) bool, False where data is missing
        B, L = x.shape
        P = L // self.patch_len
        patches = x[:, :P * self.patch_len].reshape(B, P, self.patch_len)
        if observed is None:
            obs = torch.ones(B, P, dtype=torch.bool)
        else:
            obs = observed[:, :P * self.patch_len].reshape(B, P, -1).all(-1)
        # per-window normalization over observed values only (NaN-safe)
        filled = torch.where(obs[..., None], patches, torch.zeros_like(patches)).nan_to_num(0.0)
        n = (obs.sum(1, keepdim=True)[..., None] * self.patch_len).clamp(min=1)
        mu = filled.sum(dim=(1, 2), keepdim=True) / n
        var = (((filled - mu) * obs[..., None]) ** 2).sum(dim=(1, 2), keepdim=True) / n
        patches = (filled - mu) / (var.sqrt() + 1e-5)
        art = (torch.rand(B, P) < mask_ratio) & obs     # artificial mask, observed patches only
        hidden = art | ~obs                             # natural gaps are hidden too
        tok = torch.where(hidden[..., None], self.mask_token.expand(B, P, -1), self.embed(patches))
        recon = self.head(self.encoder(tok + self.pos[:, :P]))
        err = ((recon - patches) ** 2).mean(-1)
        loss = (err * art).sum() / art.sum().clamp(min=1)  # only where a KNOWN value was hidden
        return (loss, art, obs) if return_masks else loss

if __name__ == "__main__":
    torch.manual_seed(0)
    m = MaskedPatchModel(depth=2)
    B, L = 8, 640                                   # W1: 10-s window at 64 Hz = 640 samples
    x = torch.sin(torch.linspace(0, 60, L)).repeat(B, 1) + 0.1 * torch.randn(B, L)
    observed = torch.ones(B, L, dtype=torch.bool)
    observed[:, 320:] = False                       # second half off-wrist
    x_gap = x.clone(); x_gap[~observed] = float("nan")
    loss, art, obs = m(x_gap, observed=observed, return_masks=True)
    assert torch.isfinite(loss)                     # NaNs never reach the loss
    assert not (art & ~obs).any()                   # never score a fabricated target
    assert obs.float().mean().item() == 0.5         # 5 of 10 patches observed
    # the loss must not depend on what sits in the gap
    x_junk = x.clone(); x_junk[~observed] = 1e6
    torch.manual_seed(1); l1 = m(x_gap, observed=observed)
    torch.manual_seed(1); l2 = m(x_junk, observed=observed)
    assert torch.allclose(l1, l2), (l1, l2)
    opt = torch.optim.AdamW(m.parameters(), 1e-3)
    first = None
    for step in range(60):
        opt.zero_grad(); l = m(x_gap, observed=observed); l.backward(); opt.step()
        first = first if first is not None else l.item()
    print(f"loss {first:.3f} -> {l.item():.3f}")
    assert l.item() < first

The script prints loss 1.096 -> 0.037 after 60 steps on a synthetic sine signal whose second half is off-wrist. The key assertion replaces the gap with \(10^6\) and checks that the loss is bit-identical: the gap has no path into either the encoder or the objective. For production, drop hidden tokens before the encoder (MAE-style) or pass a key-padding mask instead of mask tokens, so natural gaps never enter attention, which is the AIM idea in LSM-2; and extend the model to W1's four channels with a per-channel observed mask.

Monitors and federated arithmetic. psi fixes decile bins on the reference sample and scores the current sample into them, with a small \(\varepsilon\) so empty bins do not produce infinite logs. fit_recalibration solves the two-parameter logistic regression of outcome on logit by Newton's method. fedavg computes the sample-weighted average of site parameters, and lora_params counts the adapter parameters \(2\,\ell\,m\,d\,r\).

"""Production checks: input drift (PSI), local recalibration, and federated averaging
with full weights versus LoRA adapters. NumPy only; values are illustrative."""
import numpy as np

# --- 1. Population stability index on a monitored scalar (e.g. a missingness rate) ---
def psi(reference, current, bins=10, eps=1e-4):
    """Bins are fixed on the reference window (deciles); current is scored into them."""
    edges = np.quantile(reference, np.linspace(0, 1, bins + 1))
    edges[0], edges[-1] = -np.inf, np.inf
    p = np.histogram(reference, edges)[0] / len(reference) + eps
    q = np.histogram(current, edges)[0] / len(current) + eps
    return float(np.sum((q - p) * np.log(q / p)))

# --- 2. Logistic recalibration (intercept and slope on the logit) ---
def logit(p): return np.log(p / (1 - p))
def fit_recalibration(p, y, iters=50):
    """Newton steps for y ~ sigmoid(a + b * logit(p)). Returns (a, b)."""
    X = np.c_[np.ones_like(p), logit(p)]; w = np.array([0.0, 1.0])
    for _ in range(iters):
        q = 1 / (1 + np.exp(-X @ w))
        H = X.T @ (X * (q * (1 - q))[:, None]); g = X.T @ (y - q)
        w = w + np.linalg.solve(H + 1e-9 * np.eye(2), g)
    return w
def ece(p, y, bins=10):
    idx = np.minimum((p * bins).astype(int), bins - 1)
    return sum(abs(y[idx == b].mean() - p[idx == b].mean()) * (idx == b).mean()
               for b in range(bins) if (idx == b).any())

# --- 3. Federated averaging: weights from K sites, weighted by sample count ---
def fedavg(site_weights, site_counts):
    n = np.asarray(site_counts, float)
    return sum(w * (k / n.sum()) for w, k in zip(site_weights, n))

def bytes_per_round(params, sites, bytes_per_param=2):
    """Upload + download of the shared parameters for every site, one round."""
    return 2 * params * sites * bytes_per_param

def lora_params(d_model=768, layers=12, rank=8, matrices_per_layer=2):
    """Rank-r adapters B (d x r) and A (r x d) on the q and v projections of each layer."""
    return layers * matrices_per_layer * 2 * d_model * rank

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    # PSI: per-participant daily off-wrist share, before and after a charging-behaviour change
    ref = rng.beta(3.8, 6.2, 20000)                 # mean 0.38 (W1 missingness)
    same = rng.beta(3.8, 6.2, 20000)
    shifted = rng.beta(4.5, 5.5, 20000)             # mean 0.45
    print(f"PSI same {psi(ref, same):.4f}  shifted {psi(ref, shifted):.3f}")
    assert psi(ref, same) < 0.01 and psi(ref, shifted) > 0.1

    # Recalibration: a site where the model is overconfident (true slope 0.7, offset -0.3)
    p_model = 1 / (1 + np.exp(-rng.normal(-2.5, 1.2, 20000)))
    y = rng.random(20000) < 1 / (1 + np.exp(-(-0.3 + 0.7 * logit(p_model))))
    a, b = fit_recalibration(p_model[:2000], y[:2000].astype(float))   # 2,000 local patients
    p_new = 1 / (1 + np.exp(-(a + b * logit(p_model[2000:]))))
    e0, e1 = ece(p_model[2000:], y[2000:]), ece(p_new, y[2000:])
    print(f"recalibration a={a:.2f} b={b:.2f}  ECE {e0:.3f} -> {e1:.3f}")
    assert abs(b - 0.7) < 0.15 and e1 < e0 / 2

    # FedAvg: the weighted mean of identical models is that model; weights follow counts
    w = [np.ones(3) * v for v in (1.0, 2.0, 4.0)]
    assert np.allclose(fedavg(w, [1, 1, 2]), np.ones(3) * 2.75)
    full, lora = 120e6, lora_params()
    print(f"LoRA params {lora:,}; per round, 3 sites: full {bytes_per_round(full, 3)/1e9:.2f} GB, "
          f"LoRA {bytes_per_round(lora, 3)/1e6:.2f} MB, ratio {full/lora:.0f}x")
    assert lora == 294_912

Output: PSI same 0.0003 shifted 0.220; recalibration a=-0.50 b=0.63 ECE 0.034 -> 0.012; LoRA params 294,912; per round, 3 sites: full 1.44 GB, LoRA 3.54 MB, ratio 407x. Two independent samples from the same distribution give PSI near zero, which is the empirical floor against which a threshold is set. The recalibration recovers a slope of 0.63 against a true 0.7 from 2,000 local patients and more than halves ECE on the remaining 18,000; the intercept estimate (−0.50 against −0.3) shows the sampling error of a 2,000-patient fit, which is why recalibration sets should be sized by the number of events, not patients.

Debugging tips. If PSI fires every week, the reference window is too short or bins were fitted on a sample with ties (many identical values collapse deciles). If recalibration makes ECE worse on held-out data, the fit set is too small or comes from a different period than the evaluation set. If FedAvg diverges while each site trains well alone, reduce local steps \(E\) before changing the learning rate; client drift grows with \(E\).

Each challenge produces a recognizable incident. This level works through five with the measurements that separate causes, the remedy chosen and the evidence that would confirm or refute it.

Incident 1: a firmware update shifts the PPG signal (device heterogeneity and missingness). Why it matters: a shared encoder serves every downstream head; a signal change degrades all of them at once and is invisible to outcome metrics for weeks.

A monitoring dashboard sketch for W1: weekly off-wrist share with its alert threshold, embedding drift, AFib AUROC by device model with intervals, and calibration slope against the recalibration band. Illustrative values.Off-wrist share (weekly)alert 0.420.300.50weeks 1–8; firmware update at week 6Embedding drift (PSI, first PC)watch 0.10act 0.20weeks 1–800.25AFib AUROC by device modeldevice A0.93device B0.92device C0.860.800.98Calibration slope (monthly)band 0.90band 1.100.75months 1–6; recalibrate when outside band
Fig. A monitoring dashboard sketch for W1 after a firmware update. The off-wrist share and embedding drift move at the same week; device C's AUROC interval sits below the others; calibration slope leaves its band about three months later. Illustrative values.
Worked incident · W1In week 6 a firmware update reaches one device model (device C). The weekly off-wrist share across all W1 participants rises from 0.38 to 0.45, crossing the 0.42 alert threshold; embedding drift on the first principal component reaches PSI 0.19–0.22, above the 0.20 action level. AFib AUROC on device C, estimated on 1,400 participants with 140 positives, is 0.86 (95% interval about ±0.04), against 0.93 (±0.02) on device A and 0.92 (±0.03) on device B. Calibration slope leaves its 0.90–1.10 band about three months later, when outcome labels catch up. (Illustrative values.)

Diagnosis. Three hypotheses explain the drop: (a) the new firmware marks more windows as off-wrist (a quality-flag change), which removes data; (b) it changes amplitude or filtering, which shifts embeddings for windows that are still present; (c) the participant mix on device C changed. Measurements separate them: if the off-wrist share rises only on device C and AUROC on the remaining windows is unchanged, (a) dominates; if embedding PSI computed on windows present both before and after is high, (b) is present; if demographics of device C users changed, (c). Here both off-wrist share and same-window PSI moved on device C only, which points to (a) and (b) together.

Remedy, in order of cost. (1) Recompute per-device normalization statistics for the new firmware on unlabeled data, which addresses amplitude shifts at no labelling cost. (2) If AUROC does not recover, train a small per-device adapter (a few thousand parameters on the input layer) with the frozen encoder, using a contrastive objective on unlabeled device C data. (3) Only if both fail, add device C data to the next pretraining snapshot. Trade-off: per-device statistics multiply configuration state that must be versioned; adapters add a model per device. Validation: the hypothesis is supported if renormalization alone brings device C's AUROC to within the interval of devices A and B and returns PSI below 0.10; it is weakened if PSI falls but AUROC does not recover, which would point to morphology changes that normalization cannot fix.

Incident 2: federated pretraining stalls (data silos). W2 is extended to three sites that cannot pool records. Full-weight FedAvg with \(E = 50\) local steps reaches a held-out next-token loss well above the centralized run, and mortality probes trained on the federated encoder lag the centralized ones. Root cause: sites differ in case mix and coding, so local models drift toward site-specific optima; averaging drifted models gives a poor shared model. Measurements: the cosine similarity between site updates in each round (low similarity indicates drift), and loss of the averaged model on each site's data. Remedy: reduce \(E\) to 5–10 steps, accepting more rounds; freeze the shared backbone after centralized pretraining on the largest site, and federate only LoRA adapters, which cuts traffic per round from 1.44 GB to about 3.5 MB in the reference workload; consider personalized adapters that separate shared and site-specific components, as proposed for vision foundation models by Tupper and Gagné (2025). Inference-time ensembling of site models is a fallback that needs no training-time exchange; the 2026 MIMIC-IV simulation reported 77% of centralized AUPRC for ensembling against 85% for FedAvg, and a FedProx variant collapsing to the marginal baseline, which shows that the choice of aggregation algorithm must itself be validated. Validation: the client-drift explanation is supported if lowering \(E\) raises update similarity and lowers the averaged loss on every site; it is weakened if the gap persists at \(E = 1\), which would point to a data-format mismatch between sites (for example, different code vocabularies) rather than optimization.

Incident 3: temporal and site shift breaks calibration (distribution shift). W2 is evaluated on the 2024 temporal holdout and at a new site. Mortality AUROC is 0.89 at the development site and 0.88 at the new one; ECE is 0.03 and 0.09. Diagnosis: stable AUROC with worse ECE indicates miscalibration rather than lost discrimination; the calibration intercept and slope, fitted on the site's first 2,000 outcomes, quantify it. Remedy: logistic recalibration per site, refitted on a schedule; size the recalibration set by events (at least a few hundred) rather than patients. Validation: recalibration is sufficient if ECE on a later, disjoint period returns to near 0.03 and the slope stays within 0.9–1.1; it is insufficient if the slope keeps drifting between refits, which indicates ongoing change that needs head refitting or continued pretraining.

Incident 4: a wellness feature becomes a device claim (regulation). W1's product team proposes to show an irregular-rhythm notification computed from the AFib head next to resting heart rate. Why it matters: under FDA's January 2026 general wellness policy, a non-invasive wearable can display physiologic estimates such as heart rate as a wellness product, but references to a specific disease, clinical thresholds or alerts that prompt clinical action move a feature out of that category. An AFib notification names a disease and is therefore a device function in the US. Remedy: separate the two outputs in the registry and in software: the resting heart rate head (MAE 2.4 bpm in the reference workload) ships under the wellness policy; the AFib head goes through a device pathway with a PCCP describing which retraining and recalibration changes are pre-authorized and how each is validated. In the EU, the high-risk obligations under the AI Act apply to such a medical-device function from 2 August 2028. Cost: a device pathway requires the evaluation package described in the playbook (task suite, subgroups, calibration, site and device hold-outs) and change control for every encoder update, because the AFib head depends on the shared encoder.

Incident 5: a noisy-label ceiling hides real progress (label noise). A new W3 checkpoint scores κ 0.79 against single-scorer labels, versus 0.78 for the deployed one. Diagnosis: both exceed the inter-scorer κ of about 0.76, so the difference measures agreement with one scorer's habits. Remedy: evaluate on a subset with consensus labels from several scorers, report agreement with each scorer separately, and treat the AHI ≥ 15 detection task (AUROC 0.91 in the reference workload), whose label is less subjective, as the primary release criterion. Validation: the new checkpoint is better only if it improves against the consensus labels with non-overlapping intervals.

ChallengeLeading indicatorIllustrative thresholdFirst remedy
Device heterogeneityEmbedding PSI per device; AUROC per devicePSI > 0.20; interval below other devicesPer-device normalization
MissingnessOff-wrist share; channels present per studyOff-wrist > 0.42 (W1)Check QC flags, then masks
Silos (federated)Update cosine similarity; per-site lossSimilarity falling across roundsFewer local steps; adapters only
ShiftCalibration intercept and slope per siteSlope outside 0.9–1.1Local recalibration
FairnessSubgroup AUROC and calibration with intervalsInterval disjoint from overallLabel audit; targeted data
RegulationOutput claims inventory per releaseAny disease reference or alertRoute to device pathway
LicensingLicense field in registryNon-commercial in product pipelineBlock deployment

Table. Leading indicators and first remedies for production challenges. Thresholds are illustrative and must be set from each deployment's stable reference periods.

Reporting. For clinical prediction models, the TRIPOD+AI statement lists what a report should contain, including the data sources, handling of missing data, subgroup performance and calibration (Collins et al. 2024). The monitoring dashboards above produce most of that material as a by-product. Connection: the playbook in the next section orders these remedies into a sequence and attaches a decision test to each step.

A practical playbook

A playbook here is an ordered sequence of steps for building and adapting a health foundation model at a hospital or a device company, with a test at each step that decides whether to continue. It exists because the most common failure in this field is not a weak model but wasted effort: pretraining a new model when a public one with a linear probe would have sufficed, or reporting a gain that disappears under a patient-level or temporal split. The sequence starts from the cheapest test of whether a foundation model helps at all and escalates only when evidence says so.

The playbook as an escalation ladder: nine ordered steps, with an evidence gate before each costlier step.1 Decisiontask, time, site2 Snapshotfreeze, split keys3 BaselinesGBM, naive, ETS4 Probe FMfrozen + linear5 Leak auditidentity probegate: clean9 ShipPCCP, monitors8 EvaluateCIs, subgroups7 Pretrainonly with evidence6 AdaptLP-FT, LoRACHEAP, DONE FOR EVERY TASKESCALATE ONLY WHEN THE GATE IS PASSEDGate before 6: probe beats baselines but misses target. Gate before 7: no suitable FM or in-domain data dwarfs public corpora.monitored datareturns to 2
Fig. The nine playbook steps as an escalation ladder. Steps 1–5 are cheap and done for every task; steps 6 and 7 are taken only when the gate before them is passed. Step 7 is dashed because most projects should not need it.

1. Define the decision and the deployment target. Write down the task, the prediction time (the moment at which the model is asked), the horizon (how far ahead it predicts), who acts on the output, and the device or site where it will run. These fix the split design and the metrics: a 30-day readmission model evaluated at discharge needs data up to discharge only, and a model that will run on a watch must be evaluated on that watch's signals.

2. Harmonize and freeze a snapshot. Convert EHR data to MEDS or OMOP, or signals to a standard format with quality-control flags. Assign patient-level split keys once and version the snapshot. Hold out a later time period and at least one site or device now, before anyone looks at results; a hold-out chosen after seeing results is no longer a hold-out.

3. Build the baselines first. Count features with gradient boosting for EHR (tools such as MEDS-Tab, Oufattole et al. 2024, automate this for MEDS data); summary statistics for wearables; seasonal-naive and exponential smoothing (ETS) for forecasting; and whatever supervised model the organization already has. Several studies in this book found these hard to beat: EHRSHOT's gradient-boosting baseline caught up with the pretrained model as labels grew and won on new-diagnosis tasks above 64 examples per class (Wornow et al. 2023).

4. Probe an existing foundation model. Extract frozen embeddings from the closest public model (CLMBR-T-base or MOTOR for EHR; PaPaGei or ECG-FM for signals; a time-series foundation model for forecasting) and fit a linear or Cox probe. A linear probe is a logistic (or linear) regression trained on the frozen embeddings; it is cheap, hard to overfit and isolates what the representation already contains. A Cox probe does the same for time-to-event outcomes. Plot \(k\)-shot curves (performance as a function of the number of labelled examples per class) against the baselines.

5. Run the leakage audit and identity probe. An identity probe tries to predict the patient or site from a single embedding; if that is easy, the embedding encodes who or where rather than physiology, and any downstream gain may come from recognizing individuals seen in training. The leakage audit compares results on a random split with results on patient-level and temporal splits; a large gap means data handling must be fixed before modeling continues.

6. Adapt incrementally. If the probe helps but not enough, try LP-FT (train the linear head first, then fine-tune the whole network from that head, which Kumar et al. 2022 showed distorts pretrained features less than fine-tuning from a random head) or LoRA adapters; for forecasting, add covariates and related series to the context. Fine-tune fully only with ample labels.

7. Pretrain only with evidence. If no foundation model fits the modality, or in-domain unlabeled data dwarfs public corpora, pretrain with the objective that matches the downstream use: masked for imputation, contrastive across modalities or time for person-level traits, time-to-event for prognosis. Run small scaling sweeps and select checkpoints by probe performance, not pretraining loss.

8. Evaluate like a regulator. Report the task suite with confidence intervals, subgroup and per-site metrics, calibration and reliability diagrams, and results with channels or hours removed.

9. Ship with change control. Register weights, tokenizer and data cards; plan updates in a PCCP-style document; deploy with drift and missingness monitors; recalibrate locally; route monitored data back into the snapshot pipeline.

Worked example · W1An AFib task for W1 runs through the ladder as follows. Step 1 fixes the decision (flag participants for follow-up), the unit (participant) and the target device. Step 2 assigns participant-level split keys and holds out one device model. Step 3 trains a supervised model from scratch, which reaches AUROC 0.88. Step 4 probes the frozen W1 encoder with a linear head on 5,000 labelled participants and reaches 0.93. Step 5 checks that a window-level random split does not inflate that figure and that participant identity is not trivially decodable. Because 0.93 meets the target, steps 6 and 7 are skipped; step 8 reports intervals, device-level and subgroup results; step 9 registers the head with the encoder version it depends on.

Comparison. A research workflow typically starts at step 7 and ends at a benchmark table. The playbook reverses the order: pretraining is the most expensive and least often necessary step, so it comes last and only after a public model has been shown insufficient. The cost is that the first results are less novel; the benefit is that every later step is measured against honest baselines on honest splits.

Mental model. Each step buys information about whether the next, more expensive step is worth taking. A step is skipped only when the gate before it says the cheaper option already meets the target.

Each gate in the playbook is a statistical decision: is the foundation model's gain over the baseline real, is the evaluation free of leakage, and is the head's output usable at the deployment prevalence. Three calculations decide them.

Gate after step 4: is the gain real? Let \(A_1\) and \(A_2\) be the AUROCs of the probe and the baseline on the same \(n_+\) positives and \(n_-\) negatives, with standard errors \(\mathrm{SE}_1, \mathrm{SE}_2\) from the Hanley–McNeil formula

\[ \mathrm{SE}^2 = \frac{A(1-A) + (n_+-1)(Q_1 - A^2) + (n_- - 1)(Q_2 - A^2)}{n_+ n_-}, \qquad Q_1 = \frac{A}{2-A},\; Q_2 = \frac{2A^2}{1+A}. \]

Because both models score the same patients, their errors are correlated with some coefficient \(r\), and the standard error of the difference is

\[ \mathrm{SE}_{\Delta} = \sqrt{\mathrm{SE}_1^2 + \mathrm{SE}_2^2 - 2r\,\mathrm{SE}_1\mathrm{SE}_2}, \qquad z = \frac{A_1 - A_2}{\mathrm{SE}_\Delta}. \]
Worked example · W1Take a test set of 1,000 participants with 100 AFib cases (an assumed 10% prevalence). For \(A_1 = 0.93\): \(Q_1 = 0.93/1.07 = 0.869\), \(Q_2 = 2(0.8649)/1.93 = 0.896\), so \(\mathrm{SE}_1^2 = [0.0651 + 99(0.00426) + 899(0.03137)]/90{,}000 = 28.69/90{,}000\), \(\mathrm{SE}_1 = 0.0179\). For \(A_2 = 0.88\), \(\mathrm{SE}_2 = 0.0225\). Treated as independent, \(z = 0.05/\sqrt{0.0179^2 + 0.0225^2} = 0.05/0.0287 = 1.74\), short of 1.96. With a paired analysis and an assumed correlation \(r = 0.5\), \(\mathrm{SE}_\Delta = 0.0206\) and \(z = 2.43\). The gain is established only by the paired comparison; with 100 positives an unpaired comparison of separately evaluated models cannot confirm it. A DeLong test estimates \(r\) from the data instead of assuming it.

How many positives a gate needs. Inverting the formula gives the test size required for a target interval half-width \(h = 1.96\,\mathrm{SE}\). At \(A = 0.93\) and 10% prevalence, \(h \approx 0.035\) with 100 positives, 0.025 with 200 and 0.020 with 300; the half-width scales roughly with \(1/\sqrt{n_+}\). Gates for subgroups and devices need the same number of positives per group, which is usually the binding constraint on step 8.

Gate after step 5: leakage. Define the leakage gap as \(\Delta_{\text{leak}} = A_{\text{random}} - A_{\text{grouped}}\), the AUROC under a row- or window-level random split minus the AUROC under a patient-level (and, where possible, temporal) split, with the same model and data. A gap larger than its standard error indicates that the random split shares individuals between train and test. The identity probe's accuracy is compared with chance, \(1/P\) for \(P\) individuals: an accuracy far above chance shows that embeddings carry enough individual information for leakage to matter.

Gate before step 9: prevalence. Few-shot heads in EHRSHOT-style protocols are trained on \(k\) positives and \(k\) negatives, a training prevalence of 0.5. If the deployment prevalence is \(\pi\), Bayes' rule gives the corrected log-odds

\[ \operatorname{logit}\hat p_{\text{deploy}} = \operatorname{logit}\hat p_{\text{balanced}} + \ln\frac{\pi}{1-\pi} - \ln\frac{0.5}{0.5}. \]

With \(\pi = 0.05\), a balanced-head output of 0.40 (logit \(-0.405\)) becomes \(-0.405 - 2.944 = -3.350\), a risk of 0.034. AUROC is unchanged by this correction; calibration is not, which is why step 8 reports calibration separately and step 9 recalibrates locally.

Gate before step 7: pretraining. Pretraining is justified when the \(k\)-shot curve of the best public model stays below target at the available label budget and in-domain unlabeled data is large. For token models the budget from the architecture section applies: in the reference workload, W2's corpus of about 0.46 billion tokens puts a 120M-parameter model at about 3.8 tokens per parameter per pass, far below CoMET's fitted optimum of about 1,000, so several passes and probe-based early stopping are required. That calculation belongs in the decision before any training run.

The module below implements steps 4 and 5 and the gate statistics. It contains a leakage-safe probe (standardization fitted on training data, regularization chosen by patient-grouped cross-validation, test set touched once), a held-out identity probe, the Hanley–McNeil standard error and the paired \(z\) statistic, and a synthetic demonstration in which a participant "fingerprint" dominates the embeddings.

Data shapes. train_emb is (n, d) frozen embeddings, one row per window or per patient-time; train_y is (n,) binary labels; train_pid is (n,) patient or participant identifiers used as groups so no individual appears in both a training and a validation fold. The function returns the chosen regularization strength, the cross-validated AUROC, and test AUROC and Brier score.

"""Playbook steps 4-5: a leakage-safe frozen-embedding probe, an identity probe,
and the AUROC uncertainty that decides whether a gain is real."""
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold, KFold
from sklearn.metrics import roc_auc_score, brier_score_loss

def probe(train_emb, train_y, train_pid, test_emb, test_y, Cs=(0.01, 0.1, 1.0, 10.0)):
    """Frozen-embedding probe (Classic edition). Patients never cross folds; the test set
    is untouched until the end (ideally later in time and from a held-out site)."""
    mu, sd = train_emb.mean(0), train_emb.std(0) + 1e-6
    Xtr, Xte = (train_emb - mu) / sd, (test_emb - mu) / sd
    best_c, best_auc = None, -1
    for C in Cs:
        aucs = []
        for tr, va in GroupKFold(n_splits=5).split(Xtr, train_y, groups=train_pid):
            m = LogisticRegression(C=C, max_iter=2000).fit(Xtr[tr], train_y[tr])
            aucs.append(roc_auc_score(train_y[va], m.predict_proba(Xtr[va])[:, 1]))
        if np.mean(aucs) > best_auc:
            best_c, best_auc = C, np.mean(aucs)
    m = LogisticRegression(C=best_c, max_iter=2000).fit(Xtr, train_y)
    p = m.predict_proba(Xte)[:, 1]
    return {"C": best_c, "cv_auroc": best_auc,
            "test_auroc": roc_auc_score(test_y, p), "test_brier": brier_score_loss(test_y, p)}

def identity_probe(emb, pid, folds=3):
    """Held-out accuracy of decoding the participant (or site) from one embedding."""
    accs = []
    for tr, va in KFold(folds, shuffle=True, random_state=0).split(emb):
        m = LogisticRegression(max_iter=2000).fit(emb[tr], pid[tr])
        accs.append(m.score(emb[va], pid[va]))
    return float(np.mean(accs))

def hanley_mcneil_se(auc, n_pos, n_neg):
    q1, q2 = auc / (2 - auc), 2 * auc ** 2 / (1 + auc)
    var = (auc * (1 - auc) + (n_pos - 1) * (q1 - auc ** 2) + (n_neg - 1) * (q2 - auc ** 2)) / (n_pos * n_neg)
    return float(np.sqrt(var))

def paired_z(a1, a2, se1, se2, r):
    """z for the difference of two AUROCs on the SAME patients with correlation r."""
    return (a1 - a2) / np.sqrt(se1 ** 2 + se2 ** 2 - 2 * r * se1 * se2)

if __name__ == "__main__":
    # W1 decision numbers: 1,000 test participants, 100 with AFib (ASSUMED prevalence 10%)
    se_fm, se_sup = hanley_mcneil_se(0.93, 100, 900), hanley_mcneil_se(0.88, 100, 900)
    z_unpaired = (0.93 - 0.88) / np.hypot(se_fm, se_sup)
    z_paired = paired_z(0.93, 0.88, se_fm, se_sup, r=0.5)
    print(f"SE {se_fm:.4f} / {se_sup:.4f}; z unpaired {z_unpaired:.2f}, paired(r=0.5) {z_paired:.2f}")
    assert abs(se_fm - 0.0178) < 5e-4 and abs(se_sup - 0.0225) < 5e-4
    assert z_unpaired < 1.96 < z_paired

    # Synthetic embeddings: 300 participants x 8 windows; a participant "fingerprint"
    # dominates the embedding, the label signal is weak and participant-level.
    rng = np.random.default_rng(0)
    P, W, d = 300, 8, 32
    pid = np.repeat(np.arange(P), W)
    y_part = rng.random(P) < 0.3
    finger = rng.normal(0, 1.0, (P, d))
    signal = np.zeros(d); signal[0] = 0.6
    emb = finger[pid] + np.outer(y_part[pid], signal) + rng.normal(0, 0.3, (P * W, d))
    y = y_part[pid].astype(int)
    print(f"identity probe accuracy {identity_probe(emb, pid):.2f} (chance {1/P:.3f})")
    assert identity_probe(emb, pid) > 0.5
    # window-level random split leaks the fingerprint (and with it the label)
    idx = rng.permutation(P * W); tr, te = idx[:1800], idx[1800:]
    leaky = roc_auc_score(y[te], LogisticRegression(C=10, max_iter=2000).fit(emb[tr], y[tr]).predict_proba(emb[te])[:, 1])
    test_part = rng.random(P) < 0.25
    trm, tem = ~test_part[pid], test_part[pid]
    res = probe(emb[trm], y[trm], pid[trm], emb[tem], y[tem])
    print(f"window-split AUROC {leaky:.2f}  participant-split AUROC {res['test_auroc']:.2f}")
    assert leaky > res["test_auroc"] + 0.1

Output: SE 0.0179 / 0.0225; z unpaired 1.74, paired(r=0.5) 2.43, matching the hand calculation; identity probe accuracy 1.00 (chance 0.003); window-split AUROC 0.73 participant-split AUROC 0.56. In the synthetic data each of 300 participants contributes eight windows whose embeddings share a participant-specific vector, and the label is a weak participant-level effect. A window-level random split puts other windows of each test participant in training, so the probe learns to recognize individuals and inherits their labels; the participant-level split removes that path and reveals that the label signal is weak. The identity probe flags the risk before any downstream result is examined.

Correctness checks to keep. Assert that no identifier occurs in both training and test; assert that standardization statistics come from training rows only (the function computes mu and sd before touching test_emb); and when the unit of prediction is the participant, aggregate window scores to one score per participant before computing AUROC, otherwise participants with more windows carry more weight.

Debugging tips. If cross-validated AUROC is much higher than test AUROC, check whether the test set is later in time or from another site (that gap is drift, not overfitting) before changing regularization. If every regularization strength gives the same result, the embeddings may be dominated by a single direction such as device or site; the identity probe with site labels in place of participant labels tests that.

In production the playbook becomes a gated program: each step has an owner, an artifact and an acceptance criterion, and a step is not started until the previous gate passes. The table gives the gates with illustrative criteria for W1's AFib head; the incidents after it show what happens when a gate is skipped.

StepArtifactGate (illustrative, W1 AFib)
1 DecisionTask specification: prediction time, horizon, unit, actor, deviceSigned off by the clinical owner; unit = participant
2 SnapshotVersioned snapshot, split keys, hold-out device and periodHold-outs fixed before any model is run
3 BaselinesSupervised-from-scratch and summary-statistic modelsReproducible; scratch model AUROC 0.88
4 ProbeFrozen-embedding linear probe; \(k\)-shot curvePaired \(z > 1.96\) against best baseline
5 Leakage auditGrouped vs random split; identity probe\(\Delta_{\text{leak}}\) within one SE; participant-level scoring
6 AdaptLP-FT or LoRA run, only if 4 misses targetGain over probe with paired \(z > 1.96\)
7 PretrainOnly if no suitable model; scaling sweepProbe metric, not loss, improves over public model
8 EvaluateReport: intervals, subgroups, devices, calibration, ablations≥ 140 positives per reported subgroup; slope 0.9–1.1
9 ShipRegistry entry, PCCP, monitors, recalibration scheduleEncoder version pinned; monitors live before launch

Table. Gates for the playbook, illustrated with W1's AFib head. Criteria are examples; each deployment sets its own from its decision and data.

Incident 1: a skipped leakage audit (gate 5). Problem: a first W1 report shows AFib AUROC 0.97. Why it matters: a figure this far above the scratch baseline would justify a product decision. Root cause: the split was by window, not by participant; each test participant also had windows in training.

Worked incident · W1The report's split put 10% of windows in test at random. The identity probe decodes participant identity from single windows far above chance (top-1 0.61 among 5,000 participants, against a chance level of 0.0002). Re-running with participant-level split keys and participant-level scoring gives 0.93, the release figure, with the scratch model at 0.88 on the same split. The window-level split had also put the scratch model at 0.94, so both models were inflated and the comparison was distorted. (Illustrative numbers.)

Diagnosis. Compute \(\Delta_{\text{leak}}\) for both models; check identity-probe accuracy; check whether test AUROC is higher for participants with more training windows. Remedy: enforce the split at the data layer (the split function of the architecture section), not in analysis code; make participant-level scoring the default. Validation: the leakage explanation is supported if AUROC on test participants who have no windows in training equals the participant-split result; it is weakened if AUROC stays high for them.

Incident 2: escalation without a gate (gates 6 and 7). Problem: a team proposes pretraining a new EHR model to raise W2's 30-day readmission AUROC of 0.71. Root cause analysis: before training, the playbook requires (a) the gradient-boosting baseline at the same label budget, (b) a probe and LP-FT on the existing W2 encoder, and (c) the token budget. If the baseline reaches 0.69–0.70 and LP-FT reaches 0.72 with overlapping intervals, the task is likely limited by label noise and the information in coded data, not by the representation. W2's corpus already gives only about 3.8 tokens per parameter per pass, so a larger model on the same data is not expected to help. Remedy: invest in better labels (for example, excluding planned readmissions) and in features the records lack, rather than in pretraining. Validation: the diagnosis is supported if a label-quality change moves both baseline and probe together; it is weakened if a public model pretrained on far more data (the role CoMET-scale models play) shows a clear gain on the same split, which would make continued pretraining or a larger corpus worthwhile.

Incident 3: shipping without monitors (gate 9). A head that passed every evaluation is deployed with outcome-based monitoring only. Outcomes for AFib follow-up arrive months later, so the firmware shift described in the production section goes unnoticed until calibration fails. Remedy: gate 9 requires input-side monitors (off-wrist share, embedding PSI per device) to be live before launch, because they react in days rather than months. Cost: input monitors raise false alarms; the thresholds should be set from the PSI observed between stable reference periods, as described for the production monitors.

Program-level trade-off. Gates slow the first deployment, and an organization with strong prior evidence may compress steps 3–5 into one evaluation run. What should not be compressed is the order: baselines and leakage audit before adaptation, adaptation before pretraining, monitors before launch. Connection: the playbook closes the loop of the reference architecture: monitored data from step 9 enters the snapshot of step 2, and the next release starts again at the gate where the evidence changed.

Open Problems

Each problem below is one the chapters encounter and cannot close. Each links to where the evidence stands. Numbers attributed to W1 to W3 are illustrative (Reference workloads).

  • Representations that travel across devices and settings. Same-participant positives let the device stand in for the person; in W1 device-neighbour purity reaches 0.63 against a chance level of 0.30, and an open PPG checkpoint pretrained mostly on intensive-care finger PPG trails W1 by 0.15 AUROC during movement but only 0.02 at rest. Field-trained models such as Pulse-PPG outperformed clinical-data pretraining on many tasks (Saha et al. 2025). Objectives whose invariances provably exclude device, firmware and site, rather than gates that detect them afterwards, do not yet exist (What makes a good representation, Open PPG, ECG and EEG models).
  • Missingness that is both nuisance and signal. Natural-gap masking lets wearable models learn from incomplete days (Xu et al. 2025), and SensorFM scaled the recipe to about 2 billion hours (Narayanswamy, Xu et al. 2026). But wear patterns themselves carry health information, and a firmware change that moves W1's off-wrist share from 0.38 to 0.45 shifts every downstream metric. How to model gaps as informative without letting the model learn device habits is unresolved (Scaling and missingness, Wearable time series).
  • Which axis of scale buys clinical value. Loss follows power laws in wearables and EHR (Waxler et al. 2025), yet EHR performance plateaued beyond about 28M parameters on MIMIC-IV for lack of tokens (Zhang et al. 2025), and in the W1 incident twelve times the compute moved AFib AUROC by an amount indistinguishable from zero. Whether people, hours per person, devices or modalities matter most for person-level targets, and how to predict that before paying for a run, is open (Scaling behavior and cohorts).
  • Calibrated generative simulation. Generative EHR models rank well zero-shot, but simulated risks inherit competing events such as end-of-record (W2's 1-year risk is 13% low under a learned end-of-record rate of 0.3 a year), accuracy plateaus around 64 simulations at real inference cost, and external validation degrades: Delphi-2M's AUC fell from about 0.76 to about 0.67 on Danish registries (Shmatko et al. 2025). Simulation that is calibrated by construction and cheap enough for nightly scoring of whole populations remains a target (Generative EHR models, Time-to-event pretraining).
  • Tokenization for clinical events. Head-to-head comparisons arrived only in 2025–2026: joint code-attribute tokens beat split ones on 73 of 74 pediatric tasks (Guo et al. 2026), and fused code-and-decile tokens beat W2's separate code and value tokens on all eight ICU outcome families tested (Lee et al. 2026). Repeated codes inflate metrics unless onsets are separated from repeats (Rajamohan et al. 2025). A tokenizer that handles time, values, repeats and unit changes, and that survives a site switching creatinine from mg/dL to µmol/L, has no settled design (Clinical events, Signals).
  • Leakage-free zero-shot evaluation. Pretraining corpora absorb public datasets, and correlated series leak even when the test series itself is absent (Meyer et al. 2025); leaderboards resolve far fewer places than they rank (Sikder and Pillutla 2026). In W1, a 20% leaked share turns a clean MASE of 0.84 into 0.812. Benchmarks with documented separation by patient, site and time, and model cards that make the audit possible, are not yet the norm (Zero-shot evaluation, EHR benchmarks).
  • Labels that limit what can be measured. W3's staging κ of 0.78 already matches inter-scorer agreement of about 0.76, so single-scorer labels cannot show further progress; prognostic claims mix detection of suspected disease with prediction, as W3's heart-failure C-index falling from 0.86 to 0.78 shows. Consensus labels, outcome-anchored targets and protocols that separate prognosis from detection are needed for the next gains to be visible (From manual scoring to learned staging, SleepFM).
  • Transport and training across institutions. Structured-EHR foundation models transported poorly across institutions and were less well calibrated with few labels (Jeanselme et al. 2025). Federated averaging recovered about 85% of centralized AUPRC on partitions of MIMIC-IV, and inference-time ensembling about 77% (Elemento 2026, not peer-reviewed). How to pretrain across silos without that loss, and how to adapt with a few thousand local patients, is open (Production challenges, Shift, fairness and calibration).
  • Longitudinal models beyond static windows. Most wearable models encode seconds or hours, while chronic and progressive conditions unfold over months; a 2026 position paper argues that static window encoders do not suit them (Wu et al. 2026). Models over months of wearable data that add value beyond EHR indicators, which simple indicators matched in All of Us once wearables were included (Wang et al. 2025), remain to be shown (Lineage map, Fusing EHR and wearables).
  • Language models that are faithful to the data. LLMs embedded over records now match dedicated EHR models on average (Hegselmann et al. 2025), but numbers written as tokens are unreliable over long spans, truncated prompts silently drop days, and benchmark knowledge did not transfer to members of the public using the same models (Bean et al. 2025). Interfaces whose stated numbers are verifiable against the data and whose benefit is measured with users are an open engineering and evaluation problem (LLMs over wearable data, Clinical text and medical LLMs).
  • Change control for models that keep changing. Foundation models are updated more often than devices traditionally are. A predetermined change control plan lets authorized modifications proceed without a new submission (Ropes & Gray 2024), while the FDA's lifecycle guidance remained a draft as of November 2026 and EU high-risk obligations for AI in medical devices apply from 2 August 2028 (White & Case 2026). How to validate a new encoder version, tokenizer and every head built on it, at the pace foundation models change, has no standard answer (Production challenges, Reference architecture).

Citation

Cited as:

Cheng, Kevin. (Nov 2026). Foundation Models for Health · Ultra. Kevin's Notes.
@article{cheng2026hfmultra,
  title   = "Foundation Models for Health · Ultra",
  author  = "Cheng, Kevin",
  journal = "Kevin's Notes",
  year    = "2026",
  month   = "Nov"
}

References

  1. "Understanding Activity and Physiology at Scale: The Apple Heart & Movement Study." 2024. ncbi.nlm.nih.gov/pmc/articles/PMC11387614
  2. Abbaspourazad, S., et al. "Large-scale Training of Foundation Models for Wearable Biosignals." ICLR 2024 (arXiv 2023). arxiv.org/abs/2312.05409
  3. Abbaspourazad, S., et al. "Wearable Accelerometer Foundation Models for Health via Knowledge Distillation." arXiv 2024. arxiv.org/abs/2412.11276
  4. AHA News. "Joint Commission Unveils First AI Guidance in Partnership with Coalition for Health AI." Sep 2025. aha.org/news/headline/2025-09-18-…
  5. Aksu, T., et al. "GIFT-Eval: A Benchmark for General Time Series Forecasting Model Evaluation." NeurIPS Workshop 2024. arxiv.org/abs/2410.10393
  6. Aksu, T., et al. "GIFT-Eval: A Benchmark for General Time Series Forecasting Model Evaluation." NeurIPS Workshop 2024. arxiv.org/abs/2410.10393
  7. Al Attrach, R., Fani, R., Restrepo, D., et al. "Rethinking Tokenization for Clinical Time Series: When Less is More." ML4H 2025 Findings. arxiv.org/pdf/2512.05217v1
  8. Amazon Science. "Introducing Chronos-2: From univariate to universal forecasting." Blog 2025. amazon.science/blog/introducing-chronos-2…
  9. Ansari, A. F., et al. "Chronos-2: From Univariate to Universal Forecasting." arXiv 2025. arxiv.org/abs/2510.15821
  10. Ansari, A. F., et al. "Chronos: Learning the Language of Time Series." TMLR 2024. arxiv.org/abs/2403.07815
  11. Assran, M., et al. "Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture." CVPR 2023. arxiv.org/abs/2301.08243
  12. Auer, A., Podest, P., Klotz, D., Böck, S., Klambauer, G., & Hochreiter, S. "TiRex: Zero-Shot Forecasting Across Long and Short Horizons with Enhanced In-Context Learning." NeurIPS 2025. arxiv.org/abs/2505.23719
  13. Baevski, A., et al. "wav2vec 2.0: A Framework for Self-Supervised Learning of Speech Representations." NeurIPS 2020. arxiv.org/pdf/2006.11477
  14. Balestriero, R., & LeCun, Y. "LeJEPA: Provable and Scalable Self-Supervised Learning Without the Heuristics." arXiv 2025. arxiv.org/abs/2511.08544
  15. Bean, A. M., Payne, R., Parsons, G., et al. "Clinical Knowledge in LLMs Does Not Translate to Human Interactions." arXiv 2025. arxiv.org/abs/2504.18919
  16. Bengio, Y., Courville, A., Vincent, P. "Representation Learning: A Review and New Perspectives." IEEE TPAMI 2013. arxiv.org/abs/1206.5538
  17. Blankemeier, L., et al. "Merlin: A Vision Language Foundation Model for 3D Computed Tomography." arXiv 2024. arxiv.org/abs/2406.06512
  18. Bommasani, R., et al. "On the Opportunities and Risks of Foundation Models." arXiv 2021. arxiv.org/abs/2108.07258
  19. Brookshire, G., Kasper, J., Blauch, N. M., et al. "Data Leakage in Deep Learning Studies of Translational EEG." Frontiers in Neuroscience 2024. frontiersin.org/…/fnins.2024.1373515
  20. Carter, J. F., & Tarassenko, L. "wav2sleep: A Unified Multi-Modal Approach to Sleep Stage Classification from Physiological Signals." Machine Learning for Health Symposium, PMLR 259, 2025. proceedings.mlr.press/v259/carter25a
  21. Chen, F., Chen, W., Chen, S., & Wei, Z. "SOTER: A Generative Time-Series Foundation Model for Wearable Human Physiological Signals." arXiv 2026. arxiv.org/pdf/2609.16804
  22. Chen, T., et al. "A Simple Framework for Contrastive Learning of Visual Representations." ICML 2020. arxiv.org/abs/2002.05709
  23. Chen, Z., Ding, C., Kataria, S., Yan, R., Wang, M., Lee, R., & Hu, X. "GPT-PPG: A GPT-based Foundation Model for Photoplethysmography Signals." arXiv 2025. arxiv.org/abs/2503.08015
  24. Choi, E., Bahadori, M. T., Schuetz, A., Stewart, W. F., Sun, J. "Doctor AI: Predicting Clinical Events via Recurrent Neural Networks." MLHC 2016 (arXiv 2015). arxiv.org/abs/1511.05942
  25. Cohen, B., et al. "This Time is Different: An Observability Perspective on Time Series Foundation Models." arXiv 2025. arxiv.org/abs/2505.14766
  26. Cohen, B., et al. "Toto: Time Series Optimized Transformer for Observability." arXiv 2024. arxiv.org/abs/2407.07874
  27. Collins, G. S., et al. "TRIPOD+AI Statement: Updated Guidance for Reporting Clinical Prediction Models that Use Regression or Machine Learning Methods." BMJ 2024. ncbi.nlm.nih.gov/pmc/articles/PMC11025451
  28. Collins, G. S., et al. "TRIPOD+AI Statement: Updated Guidance for Reporting Clinical Prediction Models That Use Regression or Machine Learning Methods." BMJ 2024;385:e078378. research.birmingham.ac.uk/…/tripodai-statement…
  29. Cosentino, J., et al. "A Personal Health Large Language Model for Sleep and Fitness Coaching" (PH-LLM). Nature Medicine 2025. research.google/pubs/a-personal-health-…
  30. Covington & Burling. "FDA Issues Revised Guidance on General Wellness Products." Jan 2026. cov.com/news-and-insights/insights/2026/01/…
  31. Das, A., Kong, W., Sen, R., Zhou, Y. "A Decoder-only Foundation Model for Time-series Forecasting." ICML 2024 (arXiv 2023). arxiv.org/abs/2310.10688
  32. de Chazal, P., Mazzotti, D. R., & Cistulli, P. A. "Automated Sleep Staging Algorithms: Have We Reached the Performance Limit Due to Manual Scoring?" Sleep 2022. pmc.ncbi.nlm.nih.gov/articles/PMC9453612
  33. Del Pup, F., Zanola, A., Tshimanga, L. F., Bertoldo, A., Finos, L., & Atzori, M. "The Role of Data Partitioning on the Performance of EEG-Based Deep Learning Models in Supervised Cross-Subject Analysis: A Preliminary Study." arXiv 2025. arxiv.org/abs/2505.13021
  34. Demirel, I., Shi, L., Hussain, Z., & Sontag, D. "LLMs Can Construct Powerful Representations and Streamline Sample-Efficient Supervised Learning." arXiv 2026. arxiv.org/html/2603.11679
  35. Devlin, J., et al. "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding." NAACL 2019. arxiv.org/abs/1810.04805
  36. Diamant, N., Reinertsen, E., Song, S., Aguirre, A. D., Stultz, C. M., & Batra, P. "Patient contrastive learning: A performant, expressive, and practical approach to electrocardiogram modeling." PLoS Computational Biology 2022. dspace.mit.edu/handle/1721.1/143901
  37. Ding, C., et al. "SiamQuality: A ConvNet-Based Foundation Model for Imperfect Physiological Signals." arXiv 2024. arxiv.org/abs/2404.17667
  38. Elemento, O. "Multi-Hospital Electronic Health Record Foundation Models Without Data Sharing: A Comparison of Federated Learning and Inference-Time Ensembling." medRxiv preprint 2026 (author list as given on the institutional page). eipm.weill.cornell.edu/publications/…
  39. Erturk, E., Kamran, F., Abbaspourazad, S., et al. "Beyond Sensor Data: Foundation Models of Behavioral Data from Wearables Improve Health Predictions." arXiv 2025. arxiv.org/abs/2507.00191
  40. Foley & Lardner. "AI-Enabled Device Software Functions: FDA's Final Guidance for Predetermined Change Control Plans." 2025. foley.com/insights/publications/2025/01/…
  41. Gao, X., Rajamohan, H. R., et al. "Scaling Recurrence-aware Foundation Models for Clinical Records via Next-Visit Prediction" (RAVEN). arXiv 2026. arxiv.org/abs/2603.24562
  42. Garrido, Q., Balestriero, R., Najman, L., LeCun, Y. "RankMe: Assessing the Downstream Performance of Pretrained Self-Supervised Representations by Their Rank." ICML 2023. arxiv.org/abs/2210.02885
  43. Garza, A., Challu, C., & Mergenthaler-Canseco, M. "TimeGPT-1." arXiv 2023. arxiv.org/abs/2310.03589
  44. Garza, A., Challu, C., & Mergenthaler-Canseco, M. "TimeGPT-1." arXiv 2023. arxiv.org/abs/2310.03589
  45. Google Research. "LSM-2: Learning from incomplete wearable sensor data." Blog 2025. research.google/blog/lsm-2-learning-from-incomplete-wearable-sensor-data
  46. Google Research. "LSM-2: Learning from incomplete wearable sensor data." Google Research Blog 2025. research.google/blog/lsm-2-…
  47. Google Research. "TimesFM" repository and update log (2.5, 3.0). GitHub 2025–2026. github.com/google-research/timesfm
  48. Google Research. "TimesFM-3: A zero-shot foundation model for multivariate forecasting." Google Research Blog 2026. research.google/blog/timesfm-3
  49. Goswami, M., et al. "MOMENT: A Family of Open Time-series Foundation Models." ICML 2024. arxiv.org/abs/2402.03885
  50. Goswami, M., et al. "MOMENT: A Family of Open Time-series Foundation Models." ICML 2024. huggingface.co/papers/2402.03885
  51. Grill, J.-B., et al. "Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning." NeurIPS 2020. arxiv.org/abs/2006.07733
  52. Guo, C., Pleiss, G., Sun, Y., & Weinberger, K. Q. "On Calibration of Modern Neural Networks." ICML 2017. arxiv.org/abs/1706.04599
  53. Guo, L. L., Arciniegas, S. E., Lee, J. J., et al. "Tokenization Tradeoffs in Structured EHR Foundation Models." arXiv 2026. arxiv.org/abs/2603.15644
  54. Guo, L. L., et al. "A Multi-Center Study on the Adaptability of a Shared Foundation Model for Electronic Health Records." npj Digital Medicine 2024. pmc.ncbi.nlm.nih.gov/articles/PMC11211479
  55. Hanley, J. A., & McNeil, B. J. "The Meaning and Use of the Area under a Receiver Operating Characteristic (ROC) Curve." Radiology 1982. pubmed.ncbi.nlm.nih.gov/7063747
  56. He, K., et al. "Masked Autoencoders Are Scalable Vision Learners." CVPR 2022. arxiv.org/abs/2111.06377
  57. Hegselmann, S., von Arnim, G., Rheude, T., et al. "Large Language Models are Powerful Electronic Health Record Encoders." arXiv 2025. arxiv.org/abs/2502.17403
  58. Hinton, G. E., & Salakhutdinov, R. R. "Reducing the Dimensionality of Data with Neural Networks." Science 2006. pubmed.ncbi.nlm.nih.gov/16873662
  59. Hinton, G., Vinyals, O., & Dean, J. "Distilling the Knowledge in a Neural Network." NIPS 2014 Deep Learning Workshop (arXiv 2015). arxiv.org/abs/1503.02531
  60. Hoffmann, J., et al. "Training Compute-Optimal Large Language Models." NeurIPS 2022. arxiv.org/pdf/2203.15556
  61. Hojjati, A., Li, L., Hameed, I., Yazidi, A., Lind, P. G., & Khadka, R. "From Video to EEG: Adapting Joint Embedding Predictive Architecture to Uncover Visual Concepts in Brain Signal Analysis." arXiv 2025. arxiv.org/abs/2507.03633
  62. Hu, E. J., et al. "LoRA: Low-Rank Adaptation of Large Language Models." ICLR 2022. arxiv.org/abs/2106.09685
  63. Jeanselme, V., Jing, Z., Kashyap, A., Pang, C., et al. "FoMoH: A Clinically Meaningful Foundation Model Evaluation for Structured Electronic Health Records." arXiv 2025. arxiv.org/abs/2505.16941
  64. Jeanselme, V., Jing, Z., Kashyap, A., Pang, C., et al. "FoMoH: A Clinically Meaningful Foundation Model Evaluation for Structured Electronic Health Records." arXiv 2025. arxiv.org/abs/2505.16941
  65. Jeanselme, V., Jing, Z., Kashyap, A., Pang, C., Pollet, F., Choi, Y. S., Jiang, X., Kobayashi, Y., Li, Y., Matijevic, S., Natarajan, K., & Joshi, S. "FoMoH: A Clinically Meaningful Foundation Model Evaluation for Structured Electronic Health Records." arXiv 2025. arxiv.org/abs/2505.16941
  66. Jiang, L. Y., et al. "Health System-Scale Language Models Are All-Purpose Prediction Engines" (NYUTron). Nature 2023. pmc.ncbi.nlm.nih.gov/articles/10338337
  67. Jiang, L. Y., et al. "Health System-Scale Language Models Are All-Purpose Prediction Engines" (NYUTron). Nature 2023. pmc.ncbi.nlm.nih.gov/articles/10338337
  68. Jiang, W.-B., Zhao, L.-M., & Lu, B.-L. "Large Brain Model for Learning Generic Representations with Tremendous EEG Data in BCI" (LaBraM). ICLR 2024. arxiv.org/abs/2405.18765
  69. Jin, M., et al. "Time-LLM: Time Series Forecasting by Reprogramming Large Language Models." ICLR 2024. arxiv.org/abs/2310.01728
  70. Johnson, A. E. W., et al. "MIMIC-IV, a Freely Accessible Electronic Health Record Dataset." Scientific Data 2023. pmc.ncbi.nlm.nih.gov/articles/PMC9810617
  71. Johnson, A., et al. "MIMIC-IV" (v3.1). PhysioNet 2024. physionet.org/content/mimiciv
  72. Kang, B. G., Ahn, J., Han, H., & Yoon, S. "Time-Conditioned Foreseeing: An EHR-Specific Foundation Model for Irregular Dynamics and Calendrical Time." ICML 2026. icml.cc/virtual/2026/poster/64928
  73. Kaplan, J., et al. "Scaling Laws for Neural Language Models." arXiv 2020. arxiv.org/abs/2001.08361
  74. Kapoor, S., & Narayanan, A. "Leakage and the Reproducibility Crisis in Machine-Learning-Based Science." Patterns 2023. pmc.ncbi.nlm.nih.gov/articles/PMC10499856
  75. Kim, S. "Learning General Representation of 12-Lead Electrocardiogram with a Joint-Embedding Predictive Architecture" (ECG-JEPA). arXiv 2024. arxiv.org/abs/2410.08559
  76. Kim, S. "Learning General Representation of 12-Lead Electrocardiogram with a Joint-Embedding Predictive Architecture." arXiv 2024. arxiv.org/abs/2410.08559
  77. Kiyasseh, D., et al. "CLOCS: Contrastive Learning of Cardiac Signals Across Space, Time, and Patients." ICML 2021. arxiv.org/abs/2005.13249
  78. Kjaer, M. R., et al. "Stanford Sleep Bench: Evaluating Polysomnography Pre-training Methods for Sleep Foundation Models." arXiv 2025. arxiv.org/abs/2512.09591
  79. Kjaer, M. R., et al. "Stanford Sleep Bench: Evaluating Polysomnography Pre-training Methods for Sleep Foundation Models." arXiv 2025. arxiv.org/abs/2512.09591
  80. Kleinberg, J., Mullainathan, S., & Raghavan, M. "Inherent Trade-Offs in the Fair Determination of Risk Scores." arXiv 2016. arxiv.org/abs/1609.05807
  81. Kraljevic, Z., et al. "Foresight: Generative Pretrained Transformer for Modelling of Patient Timelines using EHRs." arXiv 2022. arxiv.org/abs/2212.08072
  82. Kraljevic, Z., et al. "Foresight—a generative pretrained transformer for modelling of patient timelines using electronic health records: a retrospective modelling study." The Lancet Digital Health 2024. pmc.ncbi.nlm.nih.gov/articles/PMC11220626
  83. Kumar, A., Raghunathan, A., Jones, R., Ma, T., & Liang, P. "Fine-Tuning can Distort Pretrained Features and Underperform Out-of-Distribution." ICLR 2022. arxiv.org/abs/2202.10054
  84. Lee, H.-T., Cheon, H.-R., Lee, S.-H., Shim, M., & Hwang, H.-J. "Risk of Data Leakage in Estimating the Diagnostic Performance of a Deep-Learning-Based Computer-Aided System for Psychiatric Disorders." Scientific Reports 2023. pmc.ncbi.nlm.nih.gov/articles/PMC10547830
  85. Lee, I., Solo, L., Burkhart, M. C., et al. "Representation Before Training: A Practical Benchmark for Generative Medical Event Model Tokenization." arXiv 2026. arxiv.org/abs/2604.16775
  86. Lee, S., Tanade, C., Zhou, H., Lee, J., Thukral, M., Lu, B., & Desai, S. "Towards On-device Foundation Models for Raw Wearable Signals." NeurIPS 2025 Workshop on Learning from Time Series for Health. neurips.cc/virtual/2025/132300
  87. Li, J., Aguirre, A., Moura, J., et al. "An Electrocardiogram Foundation Model Built on over 10 Million Recordings with External Evaluation across Multiple Domains" (ECGFounder). arXiv 2024–2025; NEJM AI. arxiv.org/abs/2410.04133
  88. Li, Y., et al. "BEHRT: Transformer for Electronic Health Records." Scientific Reports 2020. arxiv.org/abs/1907.09538
  89. Liu, C., et al. "Moirai 2.0: When Less Is More for Time Series Forecasting." arXiv 2025. arxiv.org/abs/2511.11698
  90. Liu, C., et al. "Moirai 2.0: When Less Is More for Time Series Forecasting." arXiv 2025. arxiv.org/abs/2511.11698
  91. Liu, X., & McDuff, D. "SensorFM: Towards a general intelligence and interface for wearable health data." Google Research Blog, July 2026. research.google/blog/sensorfm-…
  92. Liu, X., et al. "Large Language Models are Few-Shot Health Learners." arXiv 2023. arxiv.org/abs/2305.15525
  93. Liu, Y., Qin, G., Shi, Z., Chen, Z., Yang, C., Huang, X., Wang, J., & Long, M. "Sundial: A Family of Highly Capable Time Series Foundation Models." ICML 2025. arxiv.org/abs/2502.00816
  94. Liu, Y., Qin, G., Shi, Z., et al. "Sundial: A Family of Highly Capable Time Series Foundation Models." ICML 2025. arxiv.org/html/2502.00816v3
  95. McDermott, M. B. A., Xu, J., Bergamaschi, T. S., et al. "MEDS: Building Models and Tools in a Reproducible Health AI Ecosystem." KDD 2025 (tutorial). dspace.mit.edu/handle/1721.1/162636
  96. McKeen, K., Masood, S., Toma, A., Rubin, B., & Wang, B. "ECG-FM: An Open Electrocardiogram Foundation Model." JAMIA Open 2025. pmc.ncbi.nlm.nih.gov/articles/PMC12530324
  97. McMahan, H. B., et al. "Communication-Efficient Learning of Deep Networks from Decentralized Data." AISTATS 2017. arxiv.org/abs/1602.05629
  98. Medical Event Data Standard (MEDS). GitHub organization. github.com/Medical-Event-Data-Standard
  99. Medical Event Data Standard. "MEDS: data schema and metadata specification." GitHub. github.com/Medical-Event-Data-Standard/meds
  100. MEDS-Tab: automated tabularization and baseline methods for MEDS datasets. arXiv 2024. arxiv.org/abs/2411.00200
  101. Merrill, M. A., Paruchuri, A., Rezaei, N., et al. "Transforming Wearable Data into Personal Health Insights using Large Language Model Agents." arXiv 2024 (accepted to Nature Communications). arxiv.org/abs/2406.06464
  102. Merschel, S., & Reinhardt, L. "Analyzability of Photoplethysmographic Smartwatch Data by the Preventicus Heartbeats Algorithm During Everyday Life: Feasibility Study." JMIR Formative Research 2022. formative.jmir.org/2022/3/e29479
  103. Meyer, M., Kaltenpoth, S., Zalipski, K., & Müller, O. "Rethinking Evaluation in the Era of Time Series Foundation Models: (Un)known Information Leakage Challenges." arXiv 2025. arxiv.org/abs/2510.13654
  104. Mikolov, T., et al. "Efficient Estimation of Word Representations in Vector Space." arXiv 2013. arxiv.org/abs/1301.3781
  105. Mondaq. "EU Digital Omnibus on AI Enters Into Force" (Regulation (EU) 2026/1744). 2026. mondaq.com/eu-digital-omnibus-on-ai-enters-into-force
  106. Narayanswamy, G., et al. "Scaling Wearable Foundation Models." ICLR 2025 (arXiv 2024); linked summary: Google Research Blog, November 2024. research.google/blog/scaling-wearable-foundation-models
  107. Narayanswamy, G., et al. "Scaling Wearable Foundation Models." ICLR 2025. arxiv.org/pdf/2410.13638
  108. Narayanswamy, G., Xu, M. A., et al. "Towards a General Intelligence and Interface for Wearable Health Data" (SensorFM). arXiv preprint 2026. arxiv.org/abs/2605.22759
  109. National Sleep Research Resource. "About." sleepdata.org/about
  110. News-Medical. "AI model can predict a person's disease risk using sleep data." January 6, 2026 (reporting Thapa et al., Nature Medicine 2026). news-medical.net/news/20260106/…
  111. News-Medical. "AI model maps lifetime disease risks to transform future healthcare planning" (coverage of Delphi-2M). News-Medical 2025. news-medical.net/news/20250918/…
  112. Nie, Y., et al. "A Time Series is Worth 64 Words: Long-term Forecasting with Transformers." ICLR 2023. arxiv.org/pdf/2211.14730
  113. NVIDIA. "NYU, NVIDIA Collaborate on Large Language Model to Predict Patient Readmission." NVIDIA Blog, Jun 2023. blogs.nvidia.com/…/nyu-large-language-model-patient-readmission-nature
  114. Obermeyer, Z., Powers, B., Vogeli, C., & Mullainathan, S. "Dissecting Racial Bias in an Algorithm Used to Manage the Health of Populations." Science 2019. chmi.berkeley.edu/news/…
  115. Oreshkin, B. N., et al. "N-BEATS: Neural Basis Expansion Analysis for Interpretable Time Series Forecasting." ICLR 2020. arxiv.org/abs/1905.10437
  116. Panchavati, S., Panchavati, U., Arnold, C., & Speier, W. "Laya: A LeJEPA Approach to EEG via Latent Prediction over Reconstruction." arXiv 2026 (2603.16281). tldr.takara.ai/p/2603.16281
  117. Panchavati, S., Panchavati, U., Arnold, C., & Speier, W. "Laya: A LeJEPA Approach to EEG via Latent Prediction over Reconstruction." arXiv 2026. arxiv.org/abs/2603.16281
  118. Pang, C., et al. "CEHR-BERT: Incorporating Temporal Information from Structured EHR Data to Improve Prediction Tasks." ML4H 2021. arxiv.org/pdf/2111.08585
  119. Pang, C., et al. "CEHR-GPT: Generating Electronic Health Records with Chronological Patient Timelines." arXiv 2024. arxiv.org/abs/2402.04400
  120. Perslev, M., et al. "U-Sleep: Resilient High-Frequency Sleep Staging." npj Digital Medicine 2021. pmc.ncbi.nlm.nih.gov/articles/PMC8050216
  121. Peräkylä, L., et al. "Zero-Shot Heart Rate Variability Forecasting from Consumer Wearables Using Time Series Foundation Models." arXiv 2026. arxiv.org/pdf/2607.20027
  122. PhysioNet. "MIMIC-IV-ECG: Diagnostic Electrocardiogram Matched Subset" (v1.0). PhysioNet. physionet.org/content/mimic-iv-ecg/1.0
  123. PhysioNet. "PTB-XL, a large publicly available electrocardiography dataset" (v1.0.3). PhysioNet. physionet.org/content/ptb-xl/1.0.3
  124. Pillai, A., Spathis, D., Kawsar, F., Malekzadeh, M. "PaPaGei: Open Foundation Models for Optical Physiological Signals." arXiv 2024. arxiv.org/abs/2410.20542
  125. Poole, B., et al. "On Variational Bounds of Mutual Information." ICML 2019. arxiv.org/abs/1905.06922
  126. Radford, A., et al. "Improving Language Understanding by Generative Pre-Training." OpenAI 2018. cdn.openai.com/…/language_understanding_paper.pdf
  127. Radford, A., et al. "Learning Transferable Visual Models From Natural Language Supervision." ICML 2021. arxiv.org/pdf/2103.00020
  128. Rajamohan, H. R., et al. "Foundation Models for Clinical Records at Health System Scale." arXiv 2025. arxiv.org/abs/2507.00574
  129. Rajamohan, H. R., Gao, X., Zhu, W., Huang, S.-L., Chen, L., Cho, K., Deniz, C. M., & Razavian, N. "Foundation Models for Clinical Records at Health System Scale." arXiv 2025. arxiv.org/abs/2507.00574
  130. RAPS. "FDA's Device Center Releases Guidance Agenda for FY 2027." Oct 2026. raps.org/resource/…
  131. Rasmy, L., Xiang, Y., Xie, Z., Tao, C., & Zhi, D. "Med-BERT: Pretrained Contextualized Embeddings on Large-Scale Structured Electronic Health Records for Disease Prediction." npj Digital Medicine 2021. arxiv.org/abs/2005.12833
  132. Rasul, K., et al. "Lag-Llama: Towards Foundation Models for Probabilistic Time Series Forecasting." arXiv 2023. arxiv.org/abs/2310.08278
  133. Redekop, E., et al. "Zero-shot Medical Event Prediction Using a Generative Pre-trained Transformer on Electronic Health Records." arXiv 2025. arxiv.org/abs/2503.05893
  134. remio. "Google Research launches TimesFM-3, but its best model comes with a commercial catch." 2026. remio.ai
  135. Renc, P., et al. "Zero Shot Health Trajectory Prediction Using Transformer" (ETHOS). npj Digital Medicine 2024. arxiv.org/abs/2407.21124
  136. Ropes & Gray. "FDA Finalizes Guidance on Predetermined Change Control Plans for AI-Enabled Devices." Dec 2024. ropesgray.com/en/insights/alerts/2024/12/…
  137. Saha, M., et al. "Pulse-PPG: An Open-Source Field-Trained PPG Foundation Model for Wearable Applications Across Lab and Field Settings." arXiv 2025. arxiv.org/abs/2502.01108
  138. Saha, M., Xu, M. A., Mao, W., Neupane, S., Rehg, J. M., & Kumar, S. "Pulse-PPG: An Open-Source Field-Trained PPG Foundation Model for Wearable Applications Across Lab and Field Settings." arXiv 2025. arxiv.org/abs/2502.01108
  139. Salinas, D., et al. "DeepAR: Probabilistic Forecasting with Autoregressive Recurrent Networks." International Journal of Forecasting 2020. arxiv.org/abs/1704.04110
  140. Schuetz, N., et al. "OpenMHC: Accelerating the Science of Wearable Foundation Models." arXiv 2026. arxiv.org/abs/2607.16235
  141. Shchur, O., et al. "fev-bench: A Realistic Benchmark for Time Series Forecasting." arXiv 2025. arxiv.org/abs/2509.26468
  142. Shchur, O., et al. "fev-bench: A Realistic Benchmark for Time Series Forecasting." arXiv 2025. arxiv.org/abs/2509.26468
  143. Shmatko, A., et al. "Learning the Natural History of Human Disease with Generative Transformers" (Delphi-2M). Nature 2025. ukbiobank.ac.uk/publications/…
  144. Shmatko, A., Jung, A. W., Gaurav, K., Brunak, S., Mortensen, L. H., Birney, E., Fitzgerald, T., Gerstung, M. "Learning the natural history of human disease with generative transformers." Nature 2025. doi.org/10.1038/s41586-025-09529-3
  145. Shuai, Z., Xu, Z., Yang, D., Wang, W., & Yang, Y. "OSF: On Pre-training and Scaling of Sleep Foundation Models." ICML 2026. icml.cc/virtual/2026/poster/61286
  146. Sikder, A., & Pillutla, S. "What a Forecasting Leaderboard Can Establish: Resolution Reporting for Zero-Shot Time-Series Models." NeurIPS 2026 Workshop on Foundation Models for Temporal Systems. neurips.cc/virtual/2026/175015
  147. Singhal, K., et al. "Large Language Models Encode Clinical Knowledge" (Med-PaLM). Nature 2023. arxiv.org/abs/2212.13138
  148. Singhal, K., Tu, T., Gottweis, J., et al. "Towards Expert-Level Medical Question Answering with Large Language Models" (Med-PaLM 2). Nature Medicine 2025. arxiv.org/abs/2305.09617
  149. Stanford Bio-X. "New AI model predicts disease risk while you sleep." 2026. biox.stanford.edu/highlight/…
  150. Steinberg, E., et al. "Language Models Are an Effective Representation Learning Technique for Electronic Health Record Data" (CLMBR). Journal of Biomedical Informatics 2021. arxiv.org/abs/2001.05295
  151. Steinberg, E., et al. "Language Models Are an Effective Representation Learning Technique for Electronic Health Record Data." Journal of Biomedical Informatics 2021 (arXiv 2020). arxiv.org/abs/2001.05295
  152. Steinberg, E., Fries, J. A., Xu, Y., & Shah, N. "MOTOR: A Time-to-Event Foundation Model for Structured Medical Records." ICLR 2024. arxiv.org/abs/2301.03150
  153. Steinkamp, J., Kantrowitz, J. J., & Airan-Javia, S. "Prevalence and Sources of Duplicate Information in the Electronic Medical Record." JAMA Network Open 2022. pubmed.ncbi.nlm.nih.gov/36156143
  154. Supratak, A., et al. "DeepSleepNet: A Model for Automatic Sleep Stage Scoring Based on Raw Single-Channel EEG." IEEE TNSRE 2017. arxiv.org/abs/1703.04046
  155. Talukder, S., Yue, Y., Gkioxari, G. "TOTEM: TOkenized Time Series EMbeddings for General Time Series Analysis." arXiv 2024. arxiv.org/html/2402.16412v2
  156. Tan, M., Merrill, M. A., Gupta, V., Althoff, T., & Hartvigsen, T. "Are Language Models Actually Useful for Time Series Forecasting?" NeurIPS 2024. proceedings.neurips.cc
  157. Thapa, R., et al. "SleepFM: Multi-modal Representation Learning for Sleep Across Brain Activity, ECG and Respiratory Signals." ICML 2024. arxiv.org/abs/2405.17766
  158. Thapa, R., Kjaer, M. R., et al. "A Multimodal Sleep Foundation Model for Disease Prediction." medRxiv 2025; Nature Medicine 2026. medrxiv.org/content/10.1101/2025.02.04.25321675
  159. Thapa, R., Sun, C., Lehn-Schiøler, W., et al. "Learning transferable human physiology from two million hours of sleep with SleepFM-2." NeurIPS 2026 Workshop on GenAI for Health. neurips.cc/virtual/2026/177323
  160. Thukral, M., Tanade, C., et al. "Wavelet-Driven Masked Multiscale Reconstruction for PPG Foundation Models." arXiv 2026. arxiv.org/abs/2601.12215
  161. Truslow, J., Spillane, A., et al. "Understanding activity and physiology at scale: The Apple Heart & Movement Study." npj Digital Medicine 2024. pmc.ncbi.nlm.nih.gov/articles/PMC11387614
  162. Tupper, A., & Gagné, C. "Personalized Federated Fine-Tuning of Vision Foundation Models for Healthcare." arXiv 2025. arxiv.org/abs/2510.12741
  163. U.S. FDA. "Artificial Intelligence-Enabled Device Software Functions: Lifecycle Management and Marketing Submission Recommendations." Draft guidance, Jan 2025. fda.gov/regulatory-information/…
  164. van den Oord, A., Li, Y., & Vinyals, O. "Representation Learning with Contrastive Predictive Coding." arXiv 2018. arxiv.org/abs/1807.03748
  165. van den Oord, A., Vinyals, O., & Kavukcuoglu, K. "Neural Discrete Representation Learning." NeurIPS 2017. arxiv.org/abs/1711.00937
  166. von Kügelgen, J., Sharma, Y., Gresele, L., Brendel, W., Schölkopf, B., Besserve, M., & Locatello, F. "Self-Supervised Learning with Data Augmentations Provably Isolates Content from Style." arXiv 2021. arxiv.org/abs/2106.04619
  167. Wang, J., Zhao, S., Luo, Z., et al. "CBraMod: A Criss-Cross Brain Foundation Model for EEG Decoding." ICLR 2025. iclr.cc/virtual/2025/poster/29880 · arXiv
  168. Wang, T., Isola, P. "Understanding Contrastive Representation Learning through Alignment and Uniformity on the Hypersphere." ICML 2020. arxiv.org/abs/2005.10242
  169. Wang, W. K., Chen, B., Yang, J., et al. "WatchSleepNet: A Novel Model and Pretraining Approach for Advancing Sleep Staging with Smartwatches." CHIL 2025, PMLR 287. mlanthology.org/chil/2025/wang2025chil-watchsleepnet
  170. Wang, W. K., et al. "Beyond the Clinic: A Large-Scale Evaluation of Augmenting EHR with Wearable Data for Diverse Health Prediction." arXiv 2025. arxiv.org/pdf/2509.22920
  171. Waxler, S., Blazek, P., White, D., et al. "Generative Medical Event Models Improve with Scale." arXiv 2025. microsoft.com/en-us/research (CoMET)
  172. Waxler, S., Blazek, P., White, D., Sneider, D., et al. "Generative Medical Event Models Improve with Scale." arXiv 2025. arxiv.org/abs/2508.12104
  173. White & Case. "EU AI Omnibus Enters into Force, Amending the AI Act." Jul 2026. whitecase.com/insight-alert/…
  174. Wikipedia. "Autoencoder." en.wikipedia.org/wiki/Autoencoder
  175. Wikipedia. "Autoregressive integrated moving average." en.wikipedia.org/wiki/Autoregressive_integrated_moving_average
  176. Wikipedia. "Box–Jenkins method." en.wikipedia.org/wiki/Box–Jenkins_method
  177. Wikipedia. "Exponential smoothing." en.wikipedia.org/wiki/Exponential_smoothing
  178. Wikipedia. "Mutual information." en.wikipedia.org/wiki/Mutual_information
  179. Wikipedia. "Photoplethysmogram." en.wikipedia.org/wiki/Photoplethysmogram
  180. Wikipedia. "Polysomnography." en.wikipedia.org/wiki/Polysomnography
  181. Wikipedia. "Proportional hazards model." en.wikipedia.org/wiki/Proportional_hazards_model
  182. Woo, G., et al. "Unified Training of Universal Time Series Forecasting Transformers" (Moirai). ICML 2024. arxiv.org/abs/2402.02592
  183. Wornow, M., et al. "Context Clues: Evaluating Long Context Models for Clinical Prediction Tasks on EHRs." ICLR 2025. arxiv.org/abs/2412.16178
  184. Wornow, M., et al. "Context Clues: Evaluating Long Context Models for Clinical Prediction Tasks on EHRs." ICLR 2025. arxiv.org/abs/2412.16178
  185. Wornow, M., Thapa, R., Steinberg, E., Fries, J. A., Shah, N. H. "EHRSHOT: An EHR Benchmark for Few-Shot Evaluation of Foundation Models." NeurIPS Datasets and Benchmarks 2023. arxiv.org/abs/2307.02028
  186. Wornow, M., Xu, Y., Thapa, R., et al., Shah, N. H. "The Shaky Foundations of Clinical Foundation Models: A Survey of Large Language Models and Foundation Models for EMRs." npj Digital Medicine 2023 (arXiv 2023). arxiv.org/abs/2303.12961
  187. Wu, Y. Y., Zhang, Y., Yoon, H., Dang, T., Spathis, D., Xia, T., Yang, Q., Han, J., Ma, D., Lee, S.-J., & Mascolo, C. "Wearable Foundation Models Should Go Beyond Static Encoders." arXiv 2026. arxiv.org/abs/2603.19564
  188. Xu, M. A., Narayanswamy, G., Ayush, K., et al. "LSM-2: Learning from Incomplete Wearable Sensor Data." arXiv 2025. arxiv.org/abs/2506.05321
  189. Zeng, A., et al. "Are Transformers Effective for Time Series Forecasting?" AAAI 2023. arxiv.org/pdf/2205.13504
  190. Zhai, X., Mustafa, B., Kolesnikov, A., & Beyer, L. "Sigmoid Loss for Language Image Pre-Training." arXiv 2023. arxiv.org/abs/2303.15343
  191. Zhang, et al. "SensorLM: Learning the Language of Wearable Sensors." NeurIPS 2025 (Google Research blog). research.google/blog/sensorlm-learning-the-language-of-wearable-sensors
  192. Zhang, S., Liu, Q., Usuyama, N., Wong, C., Naumann, T., & Poon, H. "Exploring Scaling Laws for EHR Foundation Models." arXiv 2025. arxiv.org/abs/2505.22964
  193. Zhang, Y., Ayush, K., et al. "SensorLM: Learning the Language of Wearable Sensors." NeurIPS 2025. arXiv 2506.09108
  194. Zhang, Y., Ayush, K., Qiao, S., et al. "SensorLM: Learning the Language of Wearable Sensors." NeurIPS 2025. arxiv.org/abs/2506.09108; research.google/blog; neurips.cc/virtual/2025/poster/117808
  195. Zhou, Y., et al. "A Foundation Model for Generalizable Disease Detection from Retinal Images" (RETFound). Nature 2023. nature.com/articles/s41586-023-06555-x