World Models: From Dreamer to Patient Timelines · Ultra

Ultra deep dive · World Models · Health AI · Concepts, Math, Code, Production

World Models: From Dreamer to Patient Timelines · Ultra

How machines learn to predict what happens next, from agents that plan inside a dream and playable video worlds to GPT-style models that simulate a patient's future one medical event at a time.

World ModelsModel-Based RLGenerative VideoJEPAEHRETHOS

Summary

  • A world model is a learned \(p(\text{next state} \mid \text{history}, \text{action})\). The term now covers five families: control models for planning, interactive video simulators, latent predictive (JEPA) models, language models used as simulators, and domain models such as health timelines.
  • Control world models went from Ha & Schmidhuber's "dream" (2018) through PlaNet, Dreamer and MuZero to Dreamer 4 (2025), which learned to mine diamonds in Minecraft purely from offline data.
  • Video models became world simulators once they took actions and stayed consistent: Genie inferred latent actions from unlabeled video, and Genie 3 (2025) ran at 720p and 24 fps with minutes of memory. JEPA models instead predict in feature space; V-JEPA 2 planned robot actions toward image goals.
  • Health world models apply the GPT recipe to medical records: turn each patient's history into tokens (codes split into pieces, lab values as quantile bins, time-gap tokens), train a decoder to predict the next token, and answer questions by sampling many futures and counting outcomes.
  • ETHOS (2024) did this on MIMIC-IV and, with no task labels, reached AUROC 0.92 for inpatient mortality and 84.8% top-1 accuracy on DRG classes. Delphi-2M (2025) models lifetime histories of 1,000+ diseases; Epic's CoMET (2025) trained on 115B events and found scaling laws close to language.
  • Prediction is not intervention: appending a treatment token gives what happened to patients who got it, not what the treatment would do. Counterfactual use needs causal design.
  • Evaluate a world model by its use, not its next-step loss: closed-loop control, action controllability and long-horizon consistency for simulators; discrimination, calibration, subgroup and privacy checks for health models.

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 page condenses the book into what an expert carries around: five ideas that hold across Dreamer, Genie, JEPA, language-model simulators and ETHOS; three live disagreements where informed people still differ; and ten questions that check whether you can use the ideas rather than recite them. Read it first as a map and come back to it as a test after either half of the book.

Five Core Mental Models

Researchers who agree on almost nothing else about world models agree on these five. Each one explains a recurring design choice in both halves of the book, and together they cover what a world model is, how to judge it, why it fails, how it answers questions, and what it cannot answer.

1. One object, many costumes. A world model is a learned conditional distribution \(p(\text{next state} \mid \text{history}, \text{action})\), and every system in this book is that object with a different choice of state, action and consumer. Experts hold this view because it reduces a zoo of systems to three decisions: what \(s_t\) is, what \(a_t\) is, and who reads the output. Dreamer predicts a latent game state given a controller input for a policy learner; ETHOS predicts the next medical token given the record so far, so a sampler can count outcomes. See The Four Pieces of a World Model and The Patient Timeline as an Environment.

2. Judge it by its use, not its loss. Next-step likelihood is a training signal, not a quality measure, because what the model is for (decisions, controllable worlds, calibrated risks) can diverge from it. The evidence is consistent: Lambert et al. (2020) found lower prediction error did not reliably raise reward, Physics-IQ found visual realism unrelated to physical understanding, and World-in-World found controllability mattered more than visual quality for closed-loop success. On the health side, ETHOS's mortality AUROC of 0.92 says nothing about whether its 20% means 20%. See Evaluating World Models and Evaluating Health World Models.

3. Errors compound, and optimizers find them. A model run on its own outputs accumulates error with horizon, and anything that searches or trains against the model will find the states where it is wrong. Experts treat both as permanent facts to be managed rather than bugs to be fixed: short branched rollouts (MBPO), noise on context and self forcing for video drift, uncertainty penalties for planners, and a learned value beyond the trusted horizon (TD-MPC2). The original World Models controller exploited its dream until the authors raised the sampling temperature; in health, Delphi-style disease models lose discrimination as the horizon stretches from one to ten years. See Model-Based versus Model-Free and Drift and Long-Horizon Consistency.

4. Simulation is Monte Carlo estimation. A generative world model answers a question by sampling many futures and computing a statistic over them, so every answer has two errors: sampling error, which shrinks as \(1/\sqrt{K}\), and model error, which no number of samples removes. This is the same machinery whether CEM scores 512 imagined action sequences in a latent space or ETHOS counts death tokens in 20 sampled hospital stays, and it is why experts ask both "how many samples?" and "how good is \(p_\theta\)?". See Zero-Shot Inference by Simulation and TD-MPC2.

5. Data carry the policy that generated them; conditioning is not intervening. A model trained on logged experience learns the world as acted on by whoever collected the data, so appending an action and resampling shows what followed that action in the data, not what the action causes. In health this is confounding by indication: sicker patients get vasopressors, so a vasopressor token predicts death even if the drug helps. The same logic explains why offline control models fail where the logging policy never went. See Prediction Is Not Intervention and What Counterfactual Use Requires.

How the five connect

Model 1 says what to build, model 2 how to judge it, model 3 why it degrades in use, model 4 how it turns into numbers, and model 5 which numbers it cannot give. Most failures in the book violate exactly one of them.

Three Fundamental Disagreements

The field's sharpest arguments are not about benchmarks but about what a world model should predict, whether next-token prediction is enough to build one, and whether a big observational simulator can answer causal questions. Each debate below gives the strongest case for both sides, using evidence cited elsewhere in the book, and a one-line view of where it is heading.

Debate 1. Should a world model predict observations (pixels, tokens) or abstract latents? Generative models reconstruct the future in full; JEPA-style and value-equivalent models predict only an embedding or the quantities a decision needs (Generative versus Latent Prediction).

The case for generative prediction.

  • Decision-relevant information can live in a few pixels. DIAMOND generated frames with diffusion and reached a mean human-normalized Atari 100k score of 1.46, above token-based IRIS at 1.046, by keeping small visual cues.
  • A generative loss cannot collapse, and its rollouts can be inspected by eye, which makes failures visible; latent failures hide until a downstream task breaks.
  • It scales on the internet's most abundant data and delivers products: Genie 3 runs real-time interactive worlds, and Dreamer 4, trained like a video model, learned Minecraft diamonds offline.

The case for latent prediction.

  • Most pixel detail is unpredictable and irrelevant; forcing a model to predict it wastes capacity and yields blurry averages (LeCun 2022).
  • Planning needs hundreds of cheap rollouts per step. V-JEPA 2-AC planned zero-shot pick-and-place after less than 62 hours of robot video, and DINO-WM reached goals more reliably than IRIS, DreamerV3 and TD-MPC2.
  • A model only has to be right about what the agent will compute (value equivalence); MuZero matched AlphaZero without ever reconstructing a board.
  • Looking right is not being right: Physics-IQ found realism unrelated to physical understanding, undercutting the inspectability argument.

Where it is heading. Toward hybrids judged in closed loop: generative models where a human or renderer consumes the output, latents where a planner does, and a growing share of systems (Dreamer 4, DINO-WM) that mix a strong pretrained representation with action-conditioned dynamics.

Debate 2. Do next-token predictors learn world models, or surface statistics? The question applies to LLMs and equally to ETHOS and CoMET, which are language models over clinical codes (Do Language Models Have World Models?).

The case that they learn world models.

  • Othello-GPT's board state could be probed from activations, and editing it changed the predicted moves, so the representation is used, not merely decodable; Nanda et al. showed it is linear in a "mine versus theirs" basis.
  • LLMs linearly encode real-world coordinates and dates (Gurnee & Tegmark), structure no one asked for.
  • Usefulness as simulators is real: WebDreamer planned competitively with tree search at a fraction of the cost, and CoMET found lower loss predictably improved 78 downstream clinical tasks.

The case that they learn surface statistics.

  • Near-perfect next-step accuracy can coexist with an incoherent model: Vafa et al.'s taxi-route transformers implied impossible street maps and broke on detours.
  • Generalization looks like retrieval: Kang et al. found video models fail out of distribution and scaling did not fix it.
  • As explicit simulators they drift: Wang et al. (2024) judged GPT-4 not yet a dependable text-world simulator, and Agent World Model found database-backed state gave more consistent training signal than LLM-simulated state.

Where it is heading. Away from a yes/no answer toward "which rung": Mitchell (2025)'s ladder (lookup table, map, orrery, simulator) plus compression and distinction tests, with executable state used wherever consistency matters.

Debate 3. Can a large observational health model answer treatment questions? One side expects scale and rich histories to make generative event models usable for "what if"; the other holds that only explicit causal design can (Prediction Is Not Intervention).

The case that the model can carry the causal load.

  • The ETHOS authors present treatment-pathway simulation as a use (Renc et al. 2024), and a richer history makes "no unmeasured confounding" more plausible because more of the severity a clinician saw is in the record.
  • A generative event model is a natural engine for the g-formula: replace the learned clinician policy with a fixed strategy and roll forward. One Patient, Two Futures did this and its lactated Ringer's versus saline comparison landed closer to a randomized trial than two conventional observational analyses.
  • Simulators can reproduce care statistics closely (Akagi et al. 2026: observed-to-expected ratios near 1 on a later year), and the scaling results suggest fidelity keeps improving.

The case that explicit causal structure is required.

  • Conditioning returns \(p(Y \mid H, A{=}a)\), not \(p(Y \mid H, \mathrm{do}(A{=}a))\); the gap is unrecorded severity, and scale reproduces the confounded association more faithfully, not less (confounding by indication).
  • Positivity fails silently: where no similar patient got the treatment, the model generates whatever its inductive biases suggest. Off-policy evaluation from records is fragile (Gottesman et al. 2019), and medDreamer's gains remain off-policy estimates with no patients treated.
  • Common modeling shortcuts create causal blind spots (van Geloven et al. 2024), and the 2026 review by Liu et al. calls for target-trial emulation, sensitivity analysis and prospective testing first.

Where it is heading. Toward generative models as engines inside target-trial emulation, validated against randomized trials and counterfactual calibration (Keogh & van Geloven), with forecasting under usual care as the default output.

DebateSide ASide BEvidence that would move it
What to predictPixels or tokens: inspectable, no collapse, keeps small detailsLatents: efficient, cheap to plan in, ignores the unpredictableHead-to-head closed-loop results at matched compute across many tasks, not a few robot demos
Next-token world modelsProbes and interventions show used internal stateCoherence tests and OOD failures show patchwork heuristicsCompression and distinction tests on large models in open domains; behavior under detours and edits
Causal use of health modelsRich histories plus g-formula rollouts can approximate trialsUnmeasured confounding and positivity need explicit designMany pre-registered comparisons of simulated treatment effects against randomized trials

Table. The three disagreements at a glance. Both sides in each row accept the same facts; they differ on which failure matters more and on what future evidence will show.

Self-Test: Ten Questions

These questions ask you to apply the book's ideas to situations it does not describe: estimate a number, diagnose a failure, choose between designs or plan an evaluation. Answer in a few sentences before opening the model answer; each one ends with the point a memorizer usually misses. Questions 6 to 10 are on the health half.

  1. Compounding error. Using the book's error model \(e_k = \epsilon\,((1+\delta)^k - 1)/\delta\) with \(\delta = 0.1\), team A halves the per-step error \(\epsilon\) and team B halves the amplification \(\delta\). Which team wins at a 5-step horizon, and which at 30 steps?

    Answer Short horizons reward lower \(\epsilon\); long horizons reward lower \(\delta\)

    At \(\delta = 0.1\) the bracket is about 6.1 at \(k = 5\) and 164 at \(k = 30\), so the baseline errors are \(6.1\epsilon\) and \(164\epsilon\). Team A halves both: \(3.1\epsilon\) and \(82\epsilon\). Team B, at \(\delta = 0.05\), gets about \(5.5\epsilon\) and \(66\epsilon\). So team A wins clearly at 5 steps and team B wins at 30; the crossover is around 24 steps. \(\epsilon\) falls with a better one-step model, \(\delta\) with training on self-generated context (noise augmentation, self forcing), so the right investment depends on the deployment horizon, which is why the evaluation protocol asks for error-versus-horizon curves rather than one number.

    What a memorizer misses: "better model, less drift" is not one lever; the two fixes trade places as the horizon grows.

  2. Imagined success, real failure. A vendor's action-conditioned video model has excellent FVD. You train a robot grasping policy inside it and see 90% success in imagination but 20% on the real arm. Diagnose the likely causes and design the checks you should have run first.

    Answer The policy found the model's errors; FVD could not have warned you

    The 70-point gap is the signature of model exploitation: the policy drifted into states the model renders as successful but gets wrong, such as objects that stick to the gripper or ignore contact. FVD compares distributions of clips, so a model can score well while responding weakly or wrongly to actions. Before training, test action sensitivity (different actions should give different futures; a no-op should leave the scene still), run contact and physics probes, check loop closure, and run a closed-loop benchmark in the spirit of World-in-World. After training, report the imagined-versus-real return gap, inspect the highest-scoring imagined trajectories for impossible events, and penalize ensemble disagreement or shorten the horizon.

    What a memorizer misses: the failure lives in the states the policy visits, which the vendor's test set never covered; more training on the same data does not fix it.

  3. Is it a world model? A sleep model predicts dementia from one night of polysomnography with a C-index of 0.85. A clinic wants to use it to show patients how their dementia risk would change if their sleep apnea were treated. What can and cannot the model support, and what would you need to add?

    Answer A hazard model on a snapshot cannot roll out, and its associations are not effects

    As described in SleepFM, the model is a time-to-event head on a representation: it outputs hazards from a snapshot, with no transition between nights and no action input, so there is nothing to roll forward under "treated apnea". Even if you edited the input to look like a treated night, the prediction would reflect people whose sleep looks like that, who differ in many ways from treated patients. You would need longitudinal data with treatment start (CPAP) recorded, a model of night-to-night transitions conditioned on treatment, and a causal design such as a target trial emulation with positivity checks, ideally validated against trial evidence. The C-index supports risk stratification, not counterfactual counseling.

    What a memorizer misses: high discrimination says nothing about rollout ability or causal validity; those are separate rungs on the ladder from representation to simulation.

  4. Pixels or latents for the job. Choose a prediction target (pixel/generative or latent) for each: (a) an Atari-like game where the decisive object is a three-pixel ball; (b) a robot arm reaching goal images with CEM planning at 10 Hz; (c) synthetic rare-event driving videos for human safety reviewers.

    Answer Decide by where the information lives and who consumes the output

    (a) Generative, or at least a representation audited for the ball: tiny decision-relevant cues are exactly what aggressive compression drops, the DIAMOND argument. (b) Latent: CEM needs hundreds of rollouts per step at control rate, which only latent dynamics afford, and goal images map naturally to embedding distance, as in V-JEPA 2-AC and DINO-WM. (c) Generative: the output itself is the product and a human must look at it. In (b), still check for collapse and probe that gripper and object pose are readable from the embedding.

    What a memorizer misses: neither school "wins" in the abstract; the answer flips with the consumer, the compute budget per decision and where decision-relevant bits sit.

  5. Accuracy without a map. A transformer trained on city delivery routes predicts the next legal turn 99.8% of the time. A colleague says it has therefore learned the street map. Design an experiment that could prove them wrong.

    Answer Test whether equal states get equal futures and different states different ones

    Next-turn accuracy is consistent with many internal models, including heuristics that never form a map. Apply the compression and distinction tests of Vafa et al.: find pairs of route prefixes that end at the same intersection with the same heading and check that the model allows the same continuations; find prefixes ending at different intersections and check that it distinguishes them. Reconstruct the implied map from its predictions and compare it with the real graph. Then stress it with detours and closed streets and see whether routing degrades gracefully.

    What a memorizer misses: high next-token accuracy is the weakest evidence of a world model; coherence under rare and altered histories is the real test.

  6. Monte Carlo at low risk. An ETHOS-style model estimates inpatient mortality with \(K = 20\) rollouts. For a patient whose model probability is \(p_\theta = 0.02\), how often is the estimate exactly 0, how often does it cross a 10% alert threshold, and what \(K\) gives a standard error of 0.01 for patients near 10%?

    Answer About 67% zeros, about 6% false alerts, and roughly 900 samples

    The count of death-terminated runs is binomial, so \(\Pr(\hat{p} = 0) = 0.98^{20} \approx 0.67\). Crossing 10% needs at least 2 deaths in 20: \(1 - 0.98^{20} - 20 \cdot 0.02 \cdot 0.98^{19} \approx 0.06\), so about one such patient in sixteen triggers an alert by sampling noise alone. The standard error at \(p = 0.02\) is \(\sqrt{0.02 \cdot 0.98 / 20} \approx 0.031\), larger than the risk itself. For \(\mathrm{SE} = 0.01\) at \(p = 0.1\) you need \(K = 0.09/0.0001 = 900\). Cheaper alternatives: adaptive \(K\) for borderline patients, accumulating per-step outcome-token probabilities along each rollout, or a time-to-event model if the outcome list is fixed. None of this touches the gap between \(p_\theta\) and the true risk.

    What a memorizer misses: at small \(K\), low-risk scores are mostly ties and noise, which hurts AUROC and alerting; and more samples only estimate the model's probability more precisely, not the patient's.

  7. The harmful drug that isn't. A team appends a vasopressor token to ICU timelines and resamples. Simulated 30-day mortality rises from 12% to 30%, and they draft a note that vasopressors may be harmful in this population. What went wrong, and what would a defensible analysis look like?

    Answer They measured who gets vasopressors, not what vasopressors do

    Conditioning on the token returns the outcomes of patients sick enough to receive vasopressors; the jump is confounding by indication. Appending a token after a history that did not warrant one also creates an off-support prompt, so the model may treat the token as evidence of unrecorded shock. A defensible analysis writes a target trial (eligibility, time zero, strategies such as "start vasopressor when MAP falls below a threshold" versus "do not", follow-up), checks positivity along the history, and uses the model as a g-formula engine with the clinician policy replaced by each strategy. It then adds sensitivity analysis for unmeasured confounding and, where possible, compares with randomized evidence.

    What a memorizer misses: a bigger or better-calibrated model makes this worse, not better, because it reproduces the confounded association more faithfully.

  8. Great AUROC, bad probabilities. A health world model has 0.92 AUROC for 30-day readmission, but its reliability diagram is S-shaped: predicted 40% risks see 22% readmissions. It was sampled with top-\(p\) 0.9, and rollouts that hit the token budget were dropped. Explain the pattern and fix it.

    Answer AUROC is blind to monotone distortion; truncation and censoring create it

    AUROC depends only on ranking, so any monotone distortion of the probabilities leaves it unchanged. Top-\(p\) sampling removes the low-probability tail at every step, which sharpens trajectories and distorts outcome frequencies over long rollouts. Dropping incomplete rollouts biases \(\hat{p}\) toward outcomes that occur quickly. Fix the estimator first: sample at temperature 1 without truncation, treat incomplete rollouts as censored and report their rate per task. Then fit an isotonic or Platt recalibration on held-out patients, and confirm calibration by subgroup and on a later year, since a recalibration map can drift with practice.

    What a memorizer misses: the next-token loss is a proper scoring rule per token, but sampling choices and censoring at rollout time can break calibration without changing discrimination.

  9. A tokenizer review. A colleague's ETHOS-style tokenizer uses one-week time buckets, fits lab decile edges on the full dataset, and keeps DRG tokens in prompts for 30-day readmission. Test AUROC looks excellent. List the problems in order of severity.

    Answer Leakage first, then time resolution, then quiet information loss

    Most severe: the DRG is coded after discharge, often days later, so a prediction "at discharge" uses information a deployed system would not have, and its strong link to severity can inflate the score; cut prompts strictly at what is available and audit with leak-prone tokens masked. Second, decile edges fitted on all patients leak test-set distribution into training; fit them on training patients only. Third, one-week buckets make a 30-day stop rule imprecise and blur readmission timing; CEHR-GPT showed that coarse time tokens can wreck time-sensitive synthetic cohorts. Fourth, deciles collapse extremes (a top-decile creatinine covers mild and severe elevation); consider extra bins in clinically important tails.

    What a memorizer misses: tokenization choices are modeling decisions that can both inflate metrics and change what questions the simulator can answer.

  10. Releasing synthetic patients. A hospital wants to share 1 million synthetic timelines from its health world model, and perhaps the weights. Average fidelity metrics look excellent. What tests do you require before release, and what would you refuse?

    Answer Test for memorization of rare patients, not average realism

    Population fidelity says nothing about memorization, which concentrates in rare patients whose timelines the model may reproduce. Require nearest-neighbor distances from synthetic to training timelines compared with synthetic to held-out timelines; exact-continuation tests that prompt with the first part of real, especially rare-code, timelines and check for verbatim completions; and membership- and attribute-inference attacks, as in CEHR-GPT and the memorization tests of Tonekaboni et al. (2025). Suppress or merge rare codes and check fidelity within subgroups, not only on marginals. Weights are riskier than samples because anyone can prompt them adaptively, so share them only under restricted access, if at all.

    What a memorizer misses: "trained on de-identified data" does not make generated timelines private; a timeline can be identifying by its rare combination of events.

Introduction

This book is about one idea that keeps getting reinvented: learn a model of how the world changes, then use it to imagine, plan or forecast instead of learning everything by trial and error. In 1943 the psychologist Kenneth Craik suggested that minds carry "small-scale models" of reality; in 2018 David Ha and Jürgen Schmidhuber trained an agent inside its own learned dream of a racing game; in 2024 a GPT-style transformer trained on hospital records predicted patient mortality by generating each patient's next weeks, many times over.

The book has two halves, written to be read in either order.

  • General world models (Foundations through Building a World Model): what a world model is, where it came from, how control agents learn inside one, how video generators became interactive simulators, why some researchers predict in feature space instead of pixels, whether language models contain world models, and how to evaluate and build one.
  • Health world models (Health World Models through Building a GPT-style Health World Model): the patient timeline as an environment, a detailed walkthrough of ETHOS including its tokenization and simulation-based inference with code, the wider family of generative event models (Delphi-2M, CoMET, Foresight and others), physiological simulators and digital twins, the causal limits of "what if", and an evaluation and build playbook.

If you came for the GPT-style health models, start at What a Health World Model Is and jump back to The Four Pieces of a World Model when you want the general vocabulary. Use the level switch at the top to choose how each section is presented: 1 · Concepts (the narrative), 2 · Math (definitions and derivations), 3 · Code (runnable implementations) or 4 · Production (how systems are built, served and fail).

Every system in this book learns the same mathematical object: a conditional distribution over what happens next, given what has happened so far and, optionally, what is done next. With a history \(x_{\le t}\) of observations and a sequence of actions \(a_{\le t}\), a world model with parameters \(\theta\) defines

\[ p_\theta\big(x_{t+1:t+K}\mid x_{\le t},\, a_{\le t+K-1}\big) \;=\; \prod_{k=1}^{K} p_\theta\big(x_{t+k}\mid x_{\le t+k-1},\, a_{\le t+k-1}\big), \]

a chain of one-step predictions in which each sampled step becomes context for the next. The two halves of the book instantiate this chain differently. In the general half \(x_t\) is an image, a page or a game state and \(a_t\) a controller input, a camera path or a text prompt; the model is used to train or plan a policy, or to render a world. In the health half \(x_t\) is a clinical event token, the action is usually absent, and the model is used to estimate the probability of an outcome \(o\) by sampling \(N\) futures:

\[ \hat p(o) = \frac1N\sum_{n=1}^{N}\mathbb 1\big[o \in \text{future}_n\big],\qquad \operatorname{SE}(\hat p) = \sqrt{p(1-p)/N}. \]

This is how the 2024 ETHOS model scored hospital mortality (Renc et al. 2024): the transformer was never trained on a mortality label, and the estimate is a Monte Carlo average over generated timelines. The standard error makes the cost explicit: for an outcome with probability 0.5, twenty futures give a standard error of 0.11, two thousand give 0.011. The general vocabulary of the next section (state, action, dynamics, heads) applies to both halves; what changes is what counts as a state, what counts as an action, and which functional of the sampled futures decides whether the model is good.

A world model is used by sampling from it repeatedly: each sampled step is fed back as context, and a question about the future is answered by counting over many sampled futures. The snippet below makes that loop concrete with the smallest possible patient-timeline model, a four-state Markov chain (ward, ICU, discharge, death) in which discharge and death end the timeline. It estimates the probability of death for a patient currently in the ICU by generating futures, the same zero-shot procedure ETHOS applies with a transformer over clinical tokens, and compares the estimate with the exact absorption probability.

P = np.array([[0.80, 0.08, 0.11, 0.01],    # ward -> ward, icu, discharge, death
              [0.20, 0.70, 0.00, 0.10],    # icu
              [0, 0, 1, 0], [0, 0, 0, 1]])   # discharge, death: absorbing

def sample_future(start, rng, max_len=500):
    s = start
    for _ in range(max_len):
        s = rng.choice(4, p=P[s])
        if s >= 2: return s              # timeline ends at discharge or death
    return s

def exact_death_prob(start):
    Q, R = P[:2, :2], P[:2, 2:]
    return np.linalg.solve(np.eye(2) - Q, R)[start, 1]

for N in (20, 200, 2000):
    est = np.mean([sample_future(1, rng) == 3 for _ in range(N)])
$ python3 intro_mc.py
exact P(death | now in ICU) = 0.500
N=   20 futures: estimate 0.700, standard error 0.112
N=  200 futures: estimate 0.505, standard error 0.035
N= 2000 futures: estimate 0.498, standard error 0.011

The script prints the exact probability and three Monte Carlo estimates. With twenty futures the estimate is off by 0.2, within two standard errors; with two thousand it is within 0.002. In a real health world model the chain is replaced by a transformer and each "step" is a token, but the estimator, its variance and the trade between futures and compute are unchanged.

The two halves of this book describe models that share a definition but very different production lives. A control world model such as DreamerV3 is a training-time artefact: it is learned alongside a policy, consumed by that policy's optimizer, and judged only by the return the policy achieves in the real environment. An interactive simulator such as Genie 3 is a served product: its budget is frame latency and its failures are visible drift and broken controls. A health world model such as ETHOS or Epic's CoMET is a forecasting service: each query costs many sampled timelines, and its failures are miscalibration under site or time shift and silent errors in subgroups.

Three engineering decisions recur in both halves. The first is what the model is for, written down before training, because it fixes the release test: real return, interactive quality, or calibrated forecasts. The second is the sampling budget: imagined rollouts per policy update, frames per second, or futures per patient, each of which trades compute for accuracy. The third is where the model is allowed to be wrong: control agents exploit model errors, video simulators accumulate them over long sessions, and health models carry the biases of the records they were trained on.

The book follows those decisions through each family. The general half shows how agents, simulators, representation learners and language models handle them; the health half applies the same questions to patient timelines, where the stakes of a confident wrong forecast are clinical rather than a lost game.

What Is a World Model?

A world model is a learned model of how an environment evolves: given what has happened so far and what the agent does next, it predicts what happens next. In its simplest form it is a conditional distribution over the next state, \(p(s_{t+1} \mid s_t, a_t)\), learned from data rather than written down by hand. Everything else in this book (agents that learn in imagination, interactive video simulators, self-supervised video encoders, language models used as simulators, and generative models of patient timelines) is a variation on that one object, differing in what counts as a state, what counts as an action, and what the predictions are used for.

The idea is old. The psychologist Kenneth Craik argued in 1943 that a mind carries a "small-scale model" of external reality and uses it to try out alternatives before acting (mental model). Control engineers formalized the same intuition as state-space models and system identification. What changed in the last decade is that deep networks can learn such models directly from raw, high-dimensional observations (pixels, tokens, clinical codes) at a scale where the model becomes useful on its own: as a training ground for agents, as a game engine, or as a forecaster.

Notation

\(x_t\) is the raw observation at step \(t\) (an image, a text page, a set of clinical events); \(s_t\) is the model's internal state (sometimes split into a deterministic part \(h_t\) and a stochastic part \(z_t\)); \(a_t\) is an action or other conditioning signal; \(r_t\) a reward; \(\gamma\) a discount; \(H\) an imagination or planning horizon. \(\pi(a \mid s)\) is a policy and \(V(s)\) a value function. Hats (\(\hat{x}, \hat{r}\)) mark model predictions.

Formally, a world model is a learned transition distribution \(p_\theta(s_{t+1}\mid s_t, a_t)\) with parameters \(\theta\) fitted to logged data. Observations \(x_t\) rarely reveal the full state, so practical models condition on history and maintain a belief: the state \(s_t\) is a learned summary of \(x_{\le t}\) and \(a_{<t}\). Given a dataset \(\mathcal D\) of trajectories, the default fitting principle is maximum likelihood,

\[ \theta^\ast = \arg\max_\theta \sum_{\tau\in\mathcal D}\sum_t \ln p_\theta\big(x_{t+1}\mid x_{\le t}, a_{\le t}\big), \]

with latent-variable models replacing the exact log-likelihood by a variational lower bound. Once fitted, the model is rolled out: from a state \(s_t\) and actions \(a_{t:t+H-1}\) (fixed, or sampled from a policy \(\pi(a\mid s)\)), it samples \(\hat s_{t+1}, \dots, \hat s_{t+H}\) without new observations. Any quantity of the future \(f\) (a discounted return \(\sum_k\gamma^k \hat r_{t+k}\), a rendered frame, the occurrence of a clinical outcome) is estimated by averaging \(f\) over \(N\) sampled rollouts, with standard error \(\sigma_f/\sqrt N\).

The classical special case makes the definition concrete. In system identification the model is linear-Gaussian, \(s_{t+1} = A s_t + B a_t + w_t\) with \(w_t\sim\mathcal N(0,Q)\), and maximum likelihood reduces to least squares on logged \((s_t,a_t,s_{t+1})\) triples:

\[ [\hat A\;\hat B] = \arg\min_{A,B}\sum_t \big\lVert s_{t+1} - A s_t - B a_t\big\rVert^2 . \]

Modern world models keep this structure and replace each linear map by a deep network, the state by a learned latent or a token context, and the Gaussian by a categorical, diffusion or autoregressive token distribution. The families in this book differ in the choice of \(x\), \(s\), \(a\) and in the functional of the rollouts that is used to judge \(p_\theta\).

A world model is learned from logged transitions and then run forward on its own predictions. The smallest complete example is classical system identification: log transitions of a damped spring (state: position and velocity; action: a force), fit the transition matrices by least squares, and roll the fitted model forward open-loop under an action sequence while the real system runs alongside with its own noise. The fitted model never sees the real states after the start, which is exactly what "imagining" means.

s = rng.standard_normal((2000, 2)); a = rng.uniform(-1, 1, (2000, 1))      # logged data
s_next = s @ A.T + a @ B.T + 0.01 * rng.standard_normal((2000, 2))
W, *_ = np.linalg.lstsq(np.hstack([s, a]), s_next, rcond=None)           # learn the model
A_hat, B_hat = W[:2].T, W[2:].T

s_true = s_img = np.array([1.0, 0.0])
for k in range(1, 101):                                                    # imagine open-loop
    s_true = A @ s_true + B[:, 0] * acts[k-1] + 0.01 * rng.standard_normal(2)
    s_img  = A_hat @ s_img + B_hat[:, 0] * acts[k-1]
$ python3 whatis_sysid.py
max |A_hat - A| = 0.0002
k=  1  |true - imagined| = 0.014
k= 10  |true - imagined| = 0.075
k=100  |true - imagined| = 0.097

The script prints the parameter error of the fitted model and the gap between the real and imagined state after 1, 10 and 100 steps. The parameters are recovered almost exactly, yet the trajectories still separate, because the real system keeps receiving noise that an open-loop rollout cannot see. A deep world model such as Dreamer replaces the matrices with networks and the two-dimensional state with a learned latent, but keeps the same two operations: fit on logged transitions, then roll forward without observations.

A world model in production is a learned predictor of what happens next that is queried far more often than the real environment: an agent trains on imagined rollouts, a game engine renders imagined frames, a forecaster averages imagined patient timelines. That asymmetry defines the engineering problem. The model's value lies in replacing expensive, slow or risky real interaction, and its risk lies in being trusted where its data never reached.

Three design decisions come first. The data contract: what is logged, at what rate, with which actions recorded. A model cannot learn the effect of an action that was never varied in the logs; Dreamer-style agents collect their own data, while video simulators and health models depend on logs whose action coverage was set by someone else (gameplay recordings, clinical practice). The state representation: a compact latent is cheap to roll forward but hard to inspect; pixels and clinical tokens are inspectable but expensive. The use and its test: the release gate must measure the downstream use (policy return, interactive quality, calibrated outcome probabilities), because a model can improve its own prediction loss while getting worse at the job (Lambert et al. 2020).

The scale that made world models useful also changed their cost structure. Dreamer 4 (2025) trained a Minecraft agent entirely from offline data inside a large video-style world model; CoMET (2025) trained next-event models on records from 118 million patients. At that scale the model is a shared asset reused across many downstream uses, so its versioning, evaluation and monitoring look like those of a foundation model rather than of a component inside one agent.

The Four Pieces of a World Model

Most learned world models decompose into four pieces: an encoder that turns observations into a state, a dynamics model that steps the state forward under an action, prediction heads that read quantities of interest off the state, and (optionally) a decoder that maps the state back to observations. Writing them down makes the design space easy to see.

\[ \begin{aligned} &\text{Representation:} && s_t \sim q_\phi(s_t \mid s_{t-1}, a_{t-1}, x_t) \\ &\text{Dynamics:} && \hat{s}_{t+1} \sim p_\theta(s_{t+1} \mid s_t, a_t) \\ &\text{Heads:} && \hat{r}_t \sim p_\theta(r_t \mid s_t), \quad \hat{c}_t \sim p_\theta(c_t \mid s_t) \\ &\text{Decoder (optional):} && \hat{x}_t \sim p_\theta(x_t \mid s_t) \end{aligned} \]

Here \(q_\phi\) is the encoder (it sees the real observation), \(p_\theta\) the parts that must work without it, \(c_t\) a "continue" flag that predicts whether the episode ends, and \(\phi, \theta\) learned parameters. The design choices that separate the families below are almost all choices about these lines: whether the decoder exists (Dreamer: yes; MuZero, TD-MPC2, JEPA: no), whether \(s_t\) is a vector, a grid of discrete tokens or a diffusion latent, whether \(a_t\) is a joystick command, a text prompt, a camera path or a drug order, and whether the dynamics are a recurrent net, a transformer or a diffusion model.

Anatomy of a world model: encoder, latent state, dynamics conditioned on an action, and prediction heads. Observation x_t image, events, text Encoder x_t → s_t State s_t compact belief Dynamics model p(s_t+1 | s_t, a_t) imagined next state s_t+1 (loop without new x) Action a_t or prompt, camera Decoder x̂_t (optional) Reward r̂_t, value Continue episode ends? heads read the state
Fig. The anatomy shared by most learned world models. The encoder grounds the state in a real observation; the dynamics model steps it forward under an action without seeing new observations (the dashed "imagination" loop); heads predict whatever the downstream user needs. Families differ mainly in whether the decoder exists and what form \(s_t\) and \(a_t\) take.

The four pieces are four conditional distributions. Parts that see the real observation carry parameters \(\phi\); parts that must work in imagination carry \(\theta\).

\[ \begin{aligned} &\text{Representation:} && s_t \sim q_\phi(s_t \mid s_{t-1}, a_{t-1}, x_t) \\ &\text{Dynamics (prior):} && \hat{s}_{t} \sim p_\theta(s_{t} \mid s_{t-1}, a_{t-1}) \\ &\text{Heads:} && \hat{r}_t \sim p_\theta(r_t \mid s_t), \quad \hat{c}_t \sim p_\theta(c_t \mid s_t) \\ &\text{Decoder (optional):} && \hat{x}_t \sim p_\theta(x_t \mid s_t) \end{aligned} \]

Training objective. In filtering mode both the posterior \(q_\phi\) and the prior \(p_\theta\) produce a distribution for \(s_t\), but only the posterior has seen \(x_t\). Decoder-based models in the Dreamer family minimise, per step,

\[ \mathcal L_t = -\ln p_\theta(x_t\mid s_t) - \ln p_\theta(r_t\mid s_t) - \ln p_\theta(c_t\mid s_t) + \beta\,\mathrm{KL}\big(q_\phi(s_t\mid\cdot)\,\big\|\,p_\theta(s_t\mid s_{t-1},a_{t-1})\big), \]

with \(s_t\) sampled from the posterior. This is a variational bound on the log-likelihood of the observed sequence. The KL term trains the dynamics, pulling the prior (which predicts without \(x_t\)) towards the posterior (which knows \(x_t\)), and penalises the posterior for storing information the prior cannot anticipate.

Two refinements from DreamerV2 and DreamerV3 control that term. KL balancing splits the gradient with a stop-gradient \(\mathrm{sg}(\cdot)\): \(\alpha\,\mathrm{KL}(\mathrm{sg}(q)\,\|\,p) + (1-\alpha)\,\mathrm{KL}(q\,\|\,\mathrm{sg}(p))\) with \(\alpha = 0.8\), so most of the gradient improves the prior rather than collapsing the posterior onto a weak prior. Free bits replace the KL value \(D\) by \(\max(D, 1\text{ nat})\); below the floor the term is constant and exerts no pressure to erase information from the posterior.

Capacity. With the stochastic state made of 32 categorical variables of 32 classes each, the KL per step is bounded by \(32\ln 32 \approx 110.9\) nats. Decoder-free models (MuZero, TD-MPC2, JEPA) drop the first term and learn \(s_t\) only from what they must predict: rewards, values, or embeddings of future inputs.

A world model has four pieces: an encoder that turns a real observation into a state, a dynamics model that steps the state forward under an action, heads that read reward and episode continuation off the state, and an optional decoder that redraws the observation. The NumPy sketch below wires them together at the shapes of a small DreamerV2/V3-style configuration (64×64 RGB frames, a 512-unit deterministic state, 32 categorical variables of 32 classes, a 6-dimensional action). Weights are random: the point is the data flow, the loss terms and one invariant, that imagination never calls the encoder.

def kl_term(post_logits, prior_logits, free_nats=1.0, balance=0.8):
    kl = kl_cat(post_logits, prior_logits)            # KL(post || prior), summed over 32 variables
    clipped = max(kl, free_nats)                      # free bits: no gradient below 1 nat
    return balance * clipped + (1 - balance) * clipped, kl   # sg() routes gradients in autodiff

class WorldModel:
    def encode(self, h, x):                           # q_phi(z_t | h_t, x_t): needs the real frame
        self.encoder_calls += 1
        emb = np.tanh(x.reshape(-1) @ self.enc)                       # (12288,) -> (256,)
        return (np.concatenate([h, emb]) @ self.post).reshape(32, 32)
    def step(self, h, z, a):                          # dynamics: recurrence, then prior logits
        h1 = np.tanh(np.concatenate([h, z.reshape(-1), a]) @ self.rec)
        return h1, (h1 @ self.prior).reshape(32, 32)
    def imagine(self, h, z, policy, horizon=15):      # prior only: no x, no encoder
        for _ in range(horizon):
            a = policy(h, z)
            h, prior_logits = self.step(h, z, a)
            z = sample_onehot(prior_logits, self.rng)
            traj.append((h, z, a) + self.heads(h, z))     # reward, continue probability
$ python3 run_anatomy.py
h (512,) z (32, 32) rows one-hot: True
step 1: recon MSE 0.358, KL 1.124 nats, KL term 1.124
imagined steps: 15 | encoder calls during imagination: 0
params: total 24.1M, decoder 18.9M (78%)
stochastic capacity per step: 32*ln(32) = 110.9 nats

The run prints the state shapes, the first filtering step's losses, the encoder-call count during a 15-step imagined rollout, and a parameter count. With a dense decoder from the 1,536-dimensional feature to 12,288 pixels, the optional piece holds 78% of the parameters; this is why decoder-free designs are attractive at scale. The single tanh layer stands in for Dreamer's GRU without changing any interface.

The four pieces of a world model (encoder, dynamics, heads, optional decoder) fail in different ways at scale, and failures usually appear in the downstream metric before they appear in any loss. Production practice is to monitor each piece separately so a regression can be attributed to one of them.

  • Encoder and posterior. The KL between posterior and prior is the latent's information budget. A KL pinned at the free-bits floor means the state carries little that the prior cannot guess; a KL that keeps rising means the dynamics cannot keep up with what the encoder stores.
  • Dynamics. Open-loop prediction error measured at several horizons on held-out sequences shows how far imagination can be trusted; the knee of that curve should lie beyond the imagination horizon used for training.
  • Heads. Reward error should be reported separately on steps with nonzero reward, because sparse rewards are easy to ignore in an average. The mean predicted continue probability should match the empirical continuation rate.
  • Decoder. Reconstruction loss split by image region shows whether capacity is spent on background texture rather than on the objects that matter.

The decoder is the main design decision. It gives a dense training signal and a visual debugging tool (imagined rollouts can be watched), which is why DreamerV3 keeps it across Atari, DMC and Minecraft with one set of hyperparameters. It also dominates parameters and compute, and it pulls the state towards appearance. Decoder-free designs such as TD-MPC2 and MuZero avoid both costs but lose the inspection tool, so teams that drop the decoder often train a separate probe decoder on frozen states purely for debugging. In served simulators such as Genie the decoder is the product, and the latency budget per frame is split between token prediction and decoding; profiling per piece decides whether a lighter decoder or fewer tokens per frame buys the headroom.

Model-Based versus Model-Free

The reason to learn a world model at all is that it lets an agent improve without paying for every trial in the real environment. A model-free agent maps experience straight to a policy or value function; a model-based agent first learns how the world responds, then plans or trains its policy against that model. Sutton (1990) captured the trade in the Dyna architecture: real transitions update both the value function and a model, and the model then generates extra simulated transitions that update the value function again. Every modern "train in imagination" method, from Dreamer to LLM-simulated tool environments, is a Dyna loop with a better model.

The Dyna loop: acting in the real environment, logging experience, learning a model, and planning with imagined rollouts. Real environment costly, slow, risky Policy / value π(a | s), V(s) Experience log (x, a, r, x′) tuples World model p(s′, r | s, a) action obs, reward log fit model imagined rollouts Model-free top loop only: every update needs a real interaction Model-based (Dyna) add the bottom loop: learn the model, then plan or train the policy on imagined experience
Fig. The Dyna loop. The top loop is ordinary model-free RL; the bottom loop turns logged experience into a model whose rollouts (dashed) train the policy more cheaply. In Sutton's original version real transitions also update the value function directly; that arrow is omitted for clarity.

The catch is that the policy is now optimized against a model that is wrong in places, and an optimizer is very good at finding the places where it is wrong. Two consequences recur through the book:

  • Compounding error. Small one-step errors accumulate over long rollouts, so imagined trajectories drift away from anything the real environment would produce. Janner et al. (2019) answered with short model rollouts branched from real states (MBPO), trading horizon for trust.
  • Objective mismatch. A model trained to maximize likelihood of the next observation is not trained to make good decisions. Lambert et al. (2020) showed that lower prediction error does not reliably translate into higher task reward, which motivates value-aware models such as MuZero and evaluation that measures decisions, not pixels (see Evaluating World Models).

Reinforcement learning maximises the expected discounted return \(J(\pi) = \mathbb E_{\pi,P}\big[\sum_{t\ge0}\gamma^t r_t\big]\) under the real transition distribution \(P\). A model-free method estimates updates for \(J\) from real samples only. A model-based method learns \(\hat P = p_\theta\) and optimises \(\hat J(\pi)\), the same return under the model.

Dyna. Tabular Q-learning applies \(Q(s,a) \leftarrow Q(s,a) + \alpha\,[r + \gamma\max_{a'}Q(s',a') - Q(s,a)]\) after a real transition. Dyna stores the transition in a model \(\hat M(s,a) = (r,s')\) and applies the same update \(n\) more times to previously seen pairs, using \(\hat M\) instead of the environment. With \(n = 0\) it is Q-learning; each extra update costs computation, not interaction.

Compounding error. Let \(e_k\) be the state error after \(k\) open-loop model steps. If each step adds at most \(\varepsilon\) and the true dynamics amplify an existing gap by at most a Lipschitz constant \(L\), then \(e_{k+1}\le L e_k + \varepsilon\) and

\[ e_k \le \varepsilon\,\frac{L^k-1}{L-1}\quad(L\ne1),\qquad e_k\le k\varepsilon\quad(L=1). \]

For \(\varepsilon = 0.01\) and \(L = 1.05\) the bound is 0.22 at 15 steps and 2.09 at 50. MBPO uses this trade: short rollouts of length \(k\) branched from real states bound the error by \(e_k\) rather than by the episode length.

Training on imagined rollouts. Dreamer-style agents train the critic on \(\lambda\)-returns along an imagined trajectory of length \(H\):

\[ R^\lambda_t = \hat r_t + \gamma\,\hat c_t\big[(1-\lambda)\,v_{t+1} + \lambda R^\lambda_{t+1}\big],\qquad R^\lambda_H = v_H, \]

interpolating between trusting the critic (\(\lambda=0\)) and trusting the model's whole rollout (\(\lambda=1\)). With \(\hat c\equiv1\) the weight on the horizon bootstrap \(v_H\) is \(\gamma(\gamma\lambda)^{H-1}\); for \(\gamma = 0.997\), \(\lambda = 0.95\), \(H = 15\) it is 0.47, so the critic carries everything beyond the imagined window.

Objective mismatch. The model is fitted by likelihood, which weights every predicted dimension; the policy needs \(\hat J\approx J\) only along the dimensions that determine reward. Lambert et al. (2020) found the two weakly correlated, the motivation for value-equivalent models such as MuZero. Richens et al. (2025) show that a sufficiently general goal-conditioned agent with bounded regret implicitly determines an approximate transition model, so the distinction is whether the model is explicit and separately trainable, not whether it exists.

A model-free agent improves only from real interactions; a model-based agent also learns a model from them and replays imagined experience from it. Tabular Dyna-Q (Sutton 1990) on the 6×9 Dyna maze isolates the effect: reward 1 at the goal, \(\gamma = 0.95\), \(\alpha = 0.1\), \(\varepsilon\)-greedy with \(\varepsilon = 0.1\). The only difference between agents is n_plan, the number of simulated updates drawn from the learned model after each real step.

for _ in range(episodes):
    s, done, n = START, False, 0
    while not done:
        a = epsilon_greedy(Q[s])
        s2, r, done = env_step(s, a)                      # one REAL interaction
        Q[s][a] += alpha * (r + gamma * (0 if done else Q[s2].max()) - Q[s][a])
        model[(s, a)] = (r, s2, done)                     # fit the model (deterministic: memorise)
        keys = list(model)
        for _ in range(n_plan):                           # IMAGINED updates, no environment cost
            ps, pa = keys[rng.integers(len(keys))]
            pr, ps2, pd = model[(ps, pa)]
            Q[ps][pa] += alpha * (pr + gamma * (0 if pd else Q[ps2].max()) - Q[ps][pa])
        s, n = s2, n + 1
$ python3 dyna.py          # mean over 10 seeds
n_plan= 0  steps in episode 2:    605   real steps, episodes 1-10:   3194
n_plan= 5  steps in episode 2:    186   real steps, episodes 1-10:   1020
n_plan=50  steps in episode 2:     40   real steps, episodes 1-10:    913

The output shows real steps per episode for three planning budgets. With 50 imagined updates per real step, episode 2 needs 40 real steps instead of 605, because the single goal reward propagates backwards through the stored model. The second script measures the price of imagination with a neural-style model: compounding error and the \(\lambda\)-return that turns an imagined trajectory into critic targets.

def error_bound(eps, L, k):
    return eps * k if L == 1 else eps * (L ** k - 1) / (L - 1)

def lambda_returns(rewards, values, conts, gamma=0.997, lam=0.95):
    H = len(rewards); R = np.zeros(H + 1); R[H] = values[H]
    for t in reversed(range(H)):
        R[t] = rewards[t] + gamma * conts[t] * ((1 - lam) * values[t + 1] + lam * R[t + 1])
    return R[:H]
$ python3 rollout.py
k= 1  bound(eps=0.01, L=1.05) = 0.010
k=15  bound(eps=0.01, L=1.05) = 0.216
k=50  bound(eps=0.01, L=1.05) = 2.093
empirical relative drift at k=1, 15, 50: 0.0062 0.0316 0.1035
lambda-return at t=0 with r=1, V=100 everywhere: 107.379
weight on the horizon bootstrap V_H: 0.4662

The empirical drift comes from a true 8-dimensional orthogonal linear system and a learned copy with 1% matrix error: relative error grows roughly linearly, as the \(L = 1\) bound predicts.

A model-based agent trains its policy on experience imagined by a learned model; a model-free agent uses only real experience. In production the model-based advantage comes with a characteristic failure: model exploitation. The actor maximises the model's estimate of return, not the real return, so any region where the model is optimistic is a region the optimiser will find. The failure is silent in every training loss; only the return measured in the real environment reveals it.

Three signals separate exploitation from ordinary learning. The return gap between the actor's imagined return and the evaluation return, tracked per checkpoint: a stable positive gap is normal optimism, a gap that grows while real return falls is exploitation. Error by horizon: branch \(k\)-step rollouts from held-out real states, compare with the logged continuations, and define the trust horizon as the largest \(k\) whose error stays under tolerance. Ensemble disagreement on the states the current policy visits, which measures how far the policy has left the data.

The standard remedies each have a cost. Shortening the imagination horizon keeps rollouts inside the trust horizon but leans harder on the critic. Lowering the ratio of imagined to real updates slows the policy's drift away from the data at the cost of sample efficiency. An uncertainty penalty (subtracting ensemble disagreement from imagined reward) requires training several dynamics heads and can suppress useful exploration. Collecting targeted real data in the exploited region fixes the model directly but needs environment access.

The balance between model-based and model-free methods has shifted with scale. DreamerV3 showed one fixed configuration working across more than 150 tasks, including collecting diamonds in Minecraft from scratch, and Dreamer 4 (2025) went further by learning entirely from offline data, where exploitation cannot be corrected with fresh interaction and the trust horizon must be enforced by design. In LLM agent training, simulated tool and web environments (DreamGym) face the same trade: cheap imagined episodes, and a policy that learns whatever the simulator gets wrong.

One Term, Several Meanings

"World model" now names at least four different research programs, plus a growing set of domain models, and most confusion in discussions of the topic comes from mixing them up. They share the abstract definition above but differ in what the state is, what conditions the prediction, and how anyone checks that the model is good.

  1. Control world models are trained so that an agent can plan or learn inside them. Success means the agent does well in the real environment (World Models for Control).
  2. Generative video and interactive simulators predict future frames, often conditioned on text, camera motion or controller input, and are judged by how real and consistent the generated world looks and feels (Video and Interactive World Simulators).
  3. Predictive-representation models predict the future in an abstract feature space rather than in pixels, and are judged by how useful those features are for recognition, prediction and planning (Predictive Representations).
  4. Language-model world models are either the implicit state that a language model tracks while it predicts text, or an LLM used explicitly to simulate what a website, tool or game would do next (Language Models as World Models).
  5. Domain world models are trained on one domain's event streams (driving logs, weather fields, electronic health records) and used to forecast or simulate trajectories in that domain. The health half of this book covers patient-timeline models in depth.

All five uses of "world model" learn a conditional distribution \(p_\theta(y\mid \mathcal C)\) of a target \(y\) given a context \(\mathcal C\). They differ in three choices: the target, the context, and the quality functional \(\mathcal Q(p_\theta)\) that decides whether the model is good. The third choice is what makes results incomparable across families.

  1. Control. \(y = (s_{t+1}, r_t, c_t)\), \(\mathcal C = (s_t, a_t)\). With \(\pi^\ast_\theta\) the policy optimised inside the model, \(\mathcal Q = J(\pi^\ast_\theta)\), the return of that policy in the real environment. Likelihood does not appear in \(\mathcal Q\).
  2. Video and interactive simulators. \(y = x_{t+1:t+K}\) (frames), \(\mathcal C\) = past frames plus text, camera or controller input. \(\mathcal Q\) is a distance between distributions of real and generated clips, plus tests of controllability and consistency.
  3. Predictive representations. \(y = \bar f(x_{\text{target}})\), the embedding of a masked or future input under a slowly updated target encoder; the loss is \(\lVert g_\psi(f_\phi(x_{\text{ctx}}), a) - \mathrm{sg}(\bar f(x_{\text{target}}))\rVert\). \(\mathcal Q\) is measured downstream, by probe accuracy or planning success.
  4. Language models. The model is \(p_\theta(w_{t+1}\mid w_{\le t})\). The implicit reading asks whether a world state \(z\) is recoverable from activations and causally used (probing and intervention, as in Othello-GPT); Vafa et al. (2024) formalise the test with Myhill–Nerode-style criteria: histories reaching the same true state should get the same continuations, and histories reaching different states different ones. The explicit reading uses \(p_\theta\) as a simulator of the next page or tool result.
  5. Domain models. \(y = e_{t+1}\), the next event in one domain's stream; \(\mathcal Q\) combines discrimination and calibration of outcome probabilities estimated by simulation.

Two models in different families can share architecture and even weights yet have different \(\mathcal Q\); comparing their numbers is a type error.

"World model" names five families that share one definition but are tested differently. In code, the useful artefact is a small spec card: what the state is, what the action is, what the model predicts and what it is used for. The family, and therefore the primary test, follows from the card, and a card too vague to classify is rejected rather than guessed.

@dataclass
class Spec:
    name: str; state: str; action: str
    predicts: set = field(default_factory=set); used_for: str = ""; domain: str = "general"
    def family(self):
        if self.domain in {"health", "driving", "weather"}: return "domain"
        if self.used_for in {"train_policy", "plan"} and {"reward", "value"} & self.predicts: return "control"
        if "embedding" in self.predicts and "frames" not in self.predicts: return "representation"
        if self.state == "tokens" and self.domain == "text": return "language"
        if "frames" in self.predicts: return "video_sim"
        raise ValueError(f"{self.name}: state the use and the outputs")

MODELS = [Spec("DreamerV3", "latent", "agent", {"reward", "continue", "frames"}, "train_policy"),
          Spec("MuZero", "latent", "agent", {"reward", "value", "policy"}, "plan"),
          Spec("Genie", "tokens", "latent_action", {"frames"}, "generate"),
          Spec("V-JEPA 2", "embedding", "none", {"embedding"}, "represent"),
          Spec("WebDreamer", "tokens", "text", {"next_page"}, "plan_by_simulation", "text"),
          Spec("ETHOS", "events", "none", {"next_event"}, "forecast", "health")]
$ python3 taxonomy.py
DreamerV3   -> control        | real return of a policy trained or planned in the model
MuZero      -> control        | real return of a policy trained or planned in the model
Genie       -> video_sim      | visual quality, consistency, controllability, physics tests
V-JEPA 2    -> representation | probe / downstream accuracy; planning success with the features
WebDreamer  -> language       | probing and intervention; state-prediction accuracy; agent success
ETHOS       -> domain         | discrimination and calibration; fidelity of simulated cohorts
error: vague: state the use and the outputs

The script prints each system's family and primary test, then the error raised for an underspecified card. The rule order encodes the porous boundaries: domain is checked first because ETHOS is also a token model, and control is checked before video because DreamerV3 renders frames yet is judged by return.

"World model" names at least five research programmes, and in production that ambiguity becomes a release-gate problem. A model can improve on the metric its training team watches while regressing on the one its users depend on, because one model is often used in more than one way: a video simulator is also a training environment for agents, a health forecaster is also a cohort simulator, an LLM is both a chat model and a simulator of tool responses.

The practical remedy is an evaluation contract per use. Each deployment states what the model predicts, what conditions it and what it is used for, and the release gate includes the primary test of every family the model is used as. Typical pairings:

  • As a control model: real return at a fixed interaction budget over several seeds, plus the gap between imagined and real return.
  • As a simulator: visual quality at short and long horizons, and controllability, for example whether an action classifier can recover the input action from generated frames.
  • As a training environment: the return of a policy trained in the simulator and tested in the real system. This is expensive, so it runs on release candidates, with a cheap proxy such as controllability on every checkpoint.
  • As a forecaster: discrimination and calibration per outcome, per site and per time period.

The expensive test decides when it disagrees with its proxy, and the proxy is then re-validated. Organisations that ship one model to several uses (Genie-style simulators used both for interactive media and for agent training, or health models used both for risk scores and for synthetic cohorts, as in follow-ups to ETHOS) need both rows of the contract to pass before a checkpoint ships.

A Taxonomy of World Models

The table below is the map for the rest of the book: each row is a family, with what it predicts, what it conditions on, how the field usually evaluates it and representative systems. Read across a row to see why the families rarely share benchmarks: a model judged on Atari reward and one judged on photorealism are optimizing different things even when both are called world models.

FamilyPredictsConditioned onUsually evaluated byExamples
Control world modelsLatent state, reward, episode end (sometimes pixels)Past observations, agent actionsReturn of a policy trained or planned in the model; sample efficiencyWorld Models, PlaNet, Dreamer v1–4, MuZero, IRIS, DIAMOND, TD-MPC2
Video / interactive simulatorsFuture frames or 3D scenesText, image, camera path, controller or latent actionsFVD and VBench-style quality, human preference, consistency, physics testsSora, Genie 1–4, GameNGen, Oasis, Cosmos, GAIA-1/2, GWM-1, Marble
Predictive representations (JEPA)Embeddings of masked or future inputsVisible context, optionally actionsLinear-probe and downstream accuracy; planning success with the learned featuresI-JEPA, V-JEPA, V-JEPA 2(-AC), DINO-WM
Language-model world modelsNext token; implicitly a state of the described world; explicitly the next page, tool result or game stateText history, candidate actionsProbing and intervention; state-prediction accuracy; downstream agent successOthello-GPT, RAP, WebDreamer, Simia, DreamGym, CWM
Domain world modelsNext event or field state in one domain (health, driving, weather)History of that domain's events; sometimes interventionsCalibration and discrimination of forecasts; fidelity of simulated cohorts or scenesBEHRT, ETHOS, Delphi-2M, CoMET (health); GAIA (driving)

Table. Five families of world models. The boundaries are porous: Dreamer 4 is a control model built like a video simulator, DINO-WM is a control model built on a representation model, and patient-timeline models are language models over clinical codes.

Each family's usual evaluation is a different functional of the model, which is why a number from one row cannot be converted into a number from another. Three functionals cover most of the table.

Distribution distance (video simulators). The Fréchet video distance of Unterthiner et al. (2018) embeds real and generated clips with a pretrained video network, fits a Gaussian \((\mu,\Sigma)\) to each set of embeddings, and reports

\[ \mathrm{FVD} = \lVert\mu_r-\mu_g\rVert^2 + \operatorname{Tr}\big(\Sigma_r + \Sigma_g - 2(\Sigma_r\Sigma_g)^{1/2}\big). \]

For isotropic Gaussians \(\mathcal N(0, I)\) and \(\mathcal N(\mathbf 1, 4I)\) in \(d\) dimensions this is \(d + d(1-2)^2 = 2d\). The functional compares marginal distributions of clips and does not condition on actions, so it cannot say whether a simulator responds correctly to controls.

Return of an induced policy (control). \(\mathcal Q = J(\pi^\ast_\theta)\) with \(J\) measured in the real environment, usually at a fixed interaction budget to capture sample efficiency.

Discrimination and calibration (domain models). With outcome probabilities \(\hat p_i\) estimated by simulation and labels \(y_i\), discrimination is the AUROC, \(\Pr(\hat p_i > \hat p_j \mid y_i = 1, y_j = 0)\), and calibration is the expected calibration error over bins \(B_b\):

\[ \mathrm{ECE} = \sum_b \frac{|B_b|}{n}\,\Big|\,\overline{y}_{B_b} - \overline{\hat p}_{B_b}\Big|. \]

AUROC is invariant to any strictly increasing transformation of \(\hat p\); ECE is not. A forecaster whose risks are all inflated by the same factor keeps its AUROC and loses its calibration, which is why health evaluation reports both.

Representation and language families add probe accuracy (a linear classifier on frozen features) and intervention tests, each again a different functional.

Each row of the taxonomy is evaluated with a different functional of the model, and the code makes the difference tangible. The script below implements three of them: the Fréchet distance between Gaussian fits of real and generated features (the core of FVD for video simulators), and AUROC and expected calibration error for forecasts from a domain model such as a patient-timeline transformer. It then shows that a forecaster whose risks are all inflated keeps its ranking quality but loses calibration.

def frechet(fr, fg):
    mr, mg = fr.mean(0), fg.mean(0); Cr, Cg = np.cov(fr, rowvar=False), np.cov(fg, rowvar=False)
    return float(((mr - mg) ** 2).sum() + np.trace(Cr + Cg - 2 * np.real(sqrtm(Cr @ Cg))))

def auroc(y, p):
    pos, neg = p[y == 1], p[y == 0]
    return float((pos[:, None] > neg[None]).mean() + 0.5 * (pos[:, None] == neg[None]).mean())

def ece(y, p, bins=10):
    idx = np.minimum((p * bins).astype(int), bins - 1)
    return float(sum((idx == b).mean() * abs(y[idx == b].mean() - p[idx == b].mean())
                     for b in range(bins) if (idx == b).any()))

risk = rng.beta(1, 6, 20000); y = (rng.random(20000) < risk).astype(int)
over = np.clip(risk * 1.6, 0, 1)        # same ranking, every risk inflated by 60%
$ python3 quality.py
Frechet distance, N(0,I) vs N(1,4I) in 2-D: 3.96  (exact 4.00)
calibrated forecaster:   AUROC 0.767  ECE 0.005
inflated by 60 percent:  AUROC 0.767  ECE 0.084

The output shows the sample Fréchet distance close to its exact value, and two forecasters with identical AUROC but a seventeen-fold difference in calibration error. A video simulator's FVD, a control model's return and a health model's AUROC are therefore not points on one scale; each answers a different question about a different model.

The taxonomy maps five families of world models to what they predict, what conditions them and how they are evaluated. In production its main use is deciding which benchmark results transfer to a deployment and which do not.

Control models are evaluated on fixed suites (Atari 100k, DeepMind Control, Crafter, Minecraft) at fixed interaction budgets; the costly part is that every reported number requires training a policy, over several seeds. Video simulators report FVD and VBench-style scores, which are cheap to compute but reward short-clip appearance; long-horizon consistency, controllability and physics tests (covered later in the book) are needed before a simulator is trusted as a training environment. Predictive-representation models such as V-JEPA 2 are judged by probes and by downstream planning, so a release requires the downstream task suite, not just the pretraining loss. Language-model world models are judged by agent success in the environment they simulate, which is where simulator errors surface. Domain models such as ETHOS on MIMIC-IV, Delphi-2M or CoMET report discrimination and calibration per outcome, and need external validation on another site or period before deployment.

The porous boundaries in the table have operational consequences. A control model built like a video simulator (Dreamer 4) inherits the simulator's drift problems; a control model built on frozen representation features (DINO-WM) inherits the representation's blind spots; patient-timeline models inherit language-model failure modes such as degenerate repetition in long generations. A team adopting a model from one family for use in another must add the evaluation of the new family rather than reuse the old benchmark.

Lineage: Where World Models Come From

World models descend from six threads that ran mostly in parallel for decades and converged after 2018, when deep generative models became good enough to learn dynamics from raw observations. Seeing the threads first makes later sections read as variations on a few old ideas: estimate the hidden state, predict its evolution, and use the prediction to act.

Six lineages converging on modern world models, from 1943 to 2026.
Fig. Six threads behind modern world models. Each lane runs from a root idea to recent systems; the horizontal axis is compressed before 2015. The bottom lane, patient timelines, is covered in the health half of this book. Years are first publication or announcement.
  1. Mental models and predictive brains. Craik's 1943 proposal that minds simulate the world (mental model) became a computational theory with predictive coding (Rao & Ballard 1999), in which cortex continually predicts its inputs and passes up only the errors. LeCun (2022) turned it into an architecture for machines: predict in an abstract representation space, not in pixels.
  2. Control and estimation. The Kalman filter (1960) combined a dynamics model with noisy measurements to track a hidden state, and system identification fit such models from input–output data. Model predictive control then replanned over a short horizon at every step, the recipe that TD-MPC2 (2023) runs in a learned latent space.
  3. Model-based reinforcement learning. Dyna (1990) learned a model and planned with simulated experience. Ha & Schmidhuber (2018) popularized the term "world model" by training a controller inside a learned dream; PlaNet, Dreamer and MuZero (2018–2019) made it competitive, and Dreamer 4 (2025) trained a Minecraft agent purely offline inside one.
  4. Generative modeling of video. Oh et al. (2015) predicted Atari frames conditioned on actions. Scaled diffusion transformers produced Sora (2024), framed explicitly as a world simulator, and controllable world generators such as Genie (2024), Genie 3 (2025) and Genie 4 (2026).
  5. Language models. Othello-GPT (2022) asked whether next-token prediction builds an internal model of the world being described. LLMs were soon used as explicit simulators for planning (RAP, 2023; WebDreamer, 2024) and as synthetic environments for agent RL (DreamGym, 2025; Agent World Model, 2026).
  6. Sequence models of patient timelines. Doctor AI (2015) applied recurrent nets to sequences of clinical visits; BEHRT (2020) brought transformers to electronic health records; ETHOS (2024) tokenized whole patient timelines for zero-shot outcome simulation; Delphi-2M (2025) generated multi-decade disease trajectories; and Epic's CoMET (2025) scaled next-medical-event prediction to 118 million patients. These are world models whose "environment" is a patient; the health half of this book covers them.

The convergence after 2018 has a simple cause: the same architectures (transformers, diffusion, tokenizers) and the same objective (predict what comes next) now work on pixels, text, actions and clinical events. What differs is the conditioning and the test of success, which is why the taxonomy above matters more than any single model.

The six threads share a mathematical core: a hidden state that evolves under a transition model, observations that reveal it partially, and an objective that uses predictions of the future. The control-and-estimation thread wrote that core down first. In the linear-Gaussian state-space model

\[ s_{t+1} = A s_t + B a_t + w_t,\quad w_t\sim\mathcal N(0,Q);\qquad x_t = C s_t + v_t,\quad v_t\sim\mathcal N(0,R), \]

the Kalman filter maintains the exact posterior \(\mathcal N(m_t, P_t)\) of the hidden state with two steps:

\[ \begin{aligned} &\text{Predict:} && m^-_{t} = A m_{t-1} + B a_{t-1}, \qquad P^-_t = A P_{t-1} A^\top + Q, \\ &\text{Update:} && K_t = P^-_t C^\top (C P^-_t C^\top + R)^{-1},\quad m_t = m^-_t + K_t (x_t - C m^-_t),\quad P_t = (I - K_t C)P^-_t . \end{aligned} \]

The predict step is the dynamics prior of a modern world model, the update step is the encoder's posterior, and the innovation \(x_t - C m^-_t\) is the prediction error that predictive coding proposes cortex passes upward. Learned latent models such as the RSSM in PlaNet and Dreamer replace \(A, B, C\) by networks and the exact posterior by an amortised \(q_\phi\), trained with the variational bound.

The other threads add an objective. Model predictive control solves, at every step, \(\min_{a_{t:t+H-1}} \sum_{k=0}^{H-1} \ell(\hat s_{t+k}, a_{t+k})\) under the model and executes only the first action; TD-MPC2 does this in a learned latent space with a learned terminal value. Model-based RL replaces the cost by return and the planner by a policy trained on imagined rollouts. The generative threads (video, language, patient timelines) drop the explicit state and factorise the observation sequence autoregressively, \(p_\theta(x_{1:T}) = \prod_t p_\theta(x_t\mid x_{<t}, a_{<t})\), with the state implicit in the network's context. The convergence after 2018 is the observation that these forms are interchangeable given enough capacity: a transformer over tokens can play the role of \(A\), \(C\) and the filter at once.

Modern world models descend from older ideas, and the oldest working one is the Kalman filter: a dynamics model that predicts a hidden state, corrected by noisy observations. The snippet tracks an object whose position is observed with noise and whose velocity is never observed. The predict step is a world model's dynamics prior, the update step is its encoder posterior, and a third estimate that only runs the dynamics (never correcting with observations) shows what pure imagination does without grounding.

A = np.array([[1, dt], [0, 1]]); C = np.array([[1.0, 0.0]])   # hidden (position, velocity)
Q = 1e-3 * np.eye(2); R = np.array([[0.25]])
for t in range(T):
    s = A @ s + rng.multivariate_normal(np.zeros(2), Q)        # true world
    x = C @ s + rng.normal(0, np.sqrt(R[0, 0]), 1)               # noisy observation
    m, P = A @ m, A @ P @ A.T + Q                                # predict: dynamics (prior)
    K = P @ C.T @ np.linalg.inv(C @ P @ C.T + R)                 # gain: trust in x
    m, P = m + K @ (x - C @ m), (np.eye(2) - K @ C) @ P          # update: posterior
    m_open = A @ m_open                                          # imagination only
$ python3 kalman.py
position RMSE  raw observation 0.488 | filtered 0.161 | open-loop 1.172
steady-state gain K = [0.121 0.059]

The script prints position error for the raw measurements, the filter and the open-loop rollout, plus the converged gain. Filtering cuts error to a third of the measurement noise and also recovers the unobserved velocity (the gain's second entry). The open-loop estimate drifts furthest, which is the compounding-error problem every later thread inherits: PlaNet and Dreamer learn the predict and update steps as networks, and MPC-style planners such as TD-MPC2 replan at every step precisely so that imagined trajectories are re-grounded in fresh observations.

The six lineages behind modern world models (mental models and predictive coding, control and estimation, model-based RL, video generation, language models, and patient-timeline models) left different engineering habits, and production systems in 2025–2026 combine them.

  • From control and estimation: filtering and receding-horizon replanning. Systems that act in the world, such as robot planners built on V-JEPA 2 or TD-MPC2, re-ground imagined trajectories with fresh observations at every step rather than trusting a long open-loop rollout.
  • From model-based RL: the habit of measuring a model by the decisions it supports, and of guarding against a policy that exploits model errors. Dreamer 4 brings this to offline training at scale.
  • From video generation: tokenizers, diffusion decoders and the serving stack of large generative models. Genie introduced latent-action world generation, and its real-time successors are served under per-frame latency budgets, and long-horizon consistency is the dominant failure.
  • From language models: pretraining at scale, then reuse of one model for many tasks. LLM-simulated environments for agent RL (DreamGym, Agent World Model) inherit language-model failure modes such as confident fabrication.
  • From patient-timeline models: tokenised event streams, external validation and calibration. ETHOS, Delphi-2M and CoMET are evaluated per outcome, per site and per period, with privacy and memorisation checks that other families rarely need.

The convergence means a single team now often owns components from several lineages: a tokenizer from video, a transformer and training recipe from language, a filtering loop from control, and an evaluation discipline from clinical prediction. Knowing which lineage a component came from predicts its typical failure, and therefore which monitor it needs.

Learning to Act Inside a Dream

Control world models exist to make agents better at acting, so their design follows from one question: what does a policy need to know about the future to choose well? The line of work from 2018 to 2025 answered it in stages. First, compress observations and learn the dynamics of the compressed state; then make the latent dynamics stochastic and train the policy entirely by backpropagating through imagined rollouts; then scale the recipe until one configuration works across hundreds of tasks; and finally replace the recurrent model with a video-scale transformer trained mostly on unlabeled footage.

Control world models are defined inside a partially observable Markov decision process. At each step \(t\) the agent receives an observation \(x_t\), chooses an action \(a_t\), and receives a reward \(r_t\) and a continuation flag \(c_t \in \{0, 1\}\) that is 0 when the episode ends. The goal is a policy \(\pi\) that maximizes the expected discounted return

\[ J(\pi) = \mathbb{E}_{\pi}\Big[\sum_{t \ge 0} \gamma^{t} r_t\Big], \qquad 0 < \gamma < 1, \]

whose weights sum to the effective horizon \(1/(1-\gamma)\) (about 333 steps for DreamerV3's \(\gamma = 0.997\)). A single observation does not reveal the full state, so the model keeps a latent state \(s_t\) summarizing \(x_{\le t}, a_{<t}\) and learns a transition \(p_\theta(s_{t+1} \mid s_t, a_t)\), a reward model \(p_\theta(r_t \mid s_t)\) and an observation model \(p_\theta(x_t \mid s_t)\). The policy is then improved on the model estimate \(J_\theta(\pi)\), computed from sampled latent trajectories. Writing \(J_\theta(\pi) = J(\pi) + \epsilon(\pi)\), every method below either shrinks the model error \(\epsilon\) or stops the optimizer from searching for policies where \(\epsilon\) is large and positive.

The whole idea fits in four steps on a toy problem: collect a little real experience, fit a dynamics model, choose a policy entirely inside the fitted model, and evaluate that policy in the real system. The system below is linear, \(x' = 0.95x + 0.5u + \text{noise}\), with reward \(-(x^2 + 0.1u^2)\); the world model is a least-squares fit and the policy is a linear gain \(u = -kx\) chosen by grid search in imagined rollouts.

import numpy as np
rng = np.random.default_rng(0)
A_TRUE, B_TRUE, NOISE = 0.95, 0.5, 0.05          # real system: x' = a x + b u + noise

def real_step(x, u):
    return A_TRUE * x + B_TRUE * u + NOISE * rng.standard_normal(x.shape)

def rollout_return(step, k, x0, T=50):
    """Return of the linear policy u = -k x under a dynamics function; reward -(x^2 + 0.1 u^2)."""
    x, R = x0.copy(), 0.0
    for _ in range(T):
        u = -k * x
        R += -(x ** 2 + 0.1 * u ** 2).mean()
        x = step(x, u)
    return R

# 1) Collect a little real experience with a random policy.
x = rng.normal(size=200); u = rng.normal(size=200); x1 = real_step(x, u)
# 2) Learn the world model by least squares: x' ~ a x + b u.
a_hat, b_hat = np.linalg.lstsq(np.stack([x, u], 1), x1, rcond=None)[0]
model = lambda x, u: a_hat * x + b_hat * u
# 3) Improve the policy entirely inside the learned model ("the dream").
x0 = rng.normal(size=500)
gains = np.linspace(0.0, 2.0, 81)
k_best = gains[np.argmax([rollout_return(model, k, x0) for k in gains])]
# 4) Evaluate in the real system.
print(f"learned a={a_hat:.3f} b={b_hat:.3f}  (true 0.95, 0.5)")
print(f"gain chosen in the dream: {k_best:.3f}")
print(f"real return  zero policy: {rollout_return(real_step, 0.0, x0):.2f}   dream policy: {rollout_return(real_step, k_best, x0):.2f}")

Output: the fitted coefficients are 0.953 and 0.503 (true 0.95 and 0.5), the gain chosen in the dream is 1.450, and its real return over 50 steps is −1.37 against −10.68 for the zero policy. With 200 transitions the model is accurate everywhere the policy goes, so the dream transfers; the sections that follow deal with the case where it does not.

A deployed control world model is three coupled learning processes sharing one compute budget: data collection in the environment, world-model training on replayed sequences, and actor-critic training on imagined trajectories started from replayed states. The coupling is the source of most failures. An inaccurate model teaches the policy to exploit its errors; a policy that changes quickly leaves the states covered by the replay buffer; a low replay ratio wastes scarce real data, while a high one overfits the buffer and multiplies cost.

The indicators worth tracking follow from this structure: real return against environment steps and wall-clock time; the dream gap, the ratio of imagined to real return at the same checkpoint; the KL between posterior and prior, which shows whether the latent state carries information; and open-loop prediction error a few steps ahead, which measures the prior actually used for imagination. The 2025 systems split along a data axis: DreamerV3 corrects its model continually with fresh interaction, while Dreamer 4 learns offline from recorded video and must validate the model before any policy is trained in it.

Vision, Memory, Controller

Ha & Schmidhuber (2018) proposed the three-part agent that gave the field its name. Their setup split the agent by function, with almost all parameters in the world model and very few in the policy:

  • V (vision): a variational autoencoder compresses each frame into a small latent vector \(z_t\).
  • M (memory): a recurrent network with a mixture-density output predicts the distribution of \(z_{t+1}\) from \(z_t\), the action and its hidden state \(h_t\).
  • C (controller): a tiny linear policy maps \([z_t, h_t]\) to an action and is trained with an evolution strategy rather than gradients.

The memorable result was that the controller could be trained entirely inside M's "dream" (a rollout of the learned model) and then transferred to the real car-racing and VizDoom tasks. The paper also found the failure mode that every later method had to manage: the controller learned to exploit imperfections in the dream, so the authors raised the model's sampling temperature to make the dream harder to game. The NeurIPS version framed the idea as recurrent world models facilitating policy evolution, linking it to Schmidhuber's work on learned models in the early 1990s.

The agent is three separately trained conditional models. Write \(x_t\) for the frame, \(a_t\) for the action and \(z_t \in \mathbb{R}^{d_z}\) for the frame code.

V is a variational autoencoder with encoder \(q_\phi(z \mid x) = \mathcal{N}(\mu_\phi(x), \operatorname{diag}\sigma^2_\phi(x))\) and decoder \(p_\psi(x \mid z)\), trained on the evidence lower bound

\[ \mathcal{L}_V = \mathbb{E}_{q_\phi(z \mid x)}\big[\log p_\psi(x \mid z)\big] - \mathrm{KL}\big(q_\phi(z \mid x) \,\|\, \mathcal{N}(0, I)\big). \]

M is an LSTM with hidden state \(h_t\) whose output, per code dimension, is a \(K\)-component Gaussian mixture

\[ p(z_{t+1} \mid z_t, a_t, h_t) = \sum_{k=1}^{K} \pi_k \, \mathcal{N}\big(z_{t+1};\, \mu_k, \sigma_k^2\big), \qquad \pi_k^{(\tau)} \propto \exp(\ell_k / \tau), \quad \sigma_k^{(\tau)} = \sigma_k \sqrt{\tau}, \]

trained by negative log-likelihood; the temperature \(\tau\) changes sampling only. With logits \((2, 0)\), raising \(\tau\) from 1 to 1.15 moves the unlikely outcome from 11.9% to 14.9% and widens each Gaussian by about 7%.

C is \(a_t = W_c[z_t, h_t] + b_c\). For car racing (\(d_z = 32\), \(d_h = 256\), three actions) it has \((32 + 256) \times 3 + 3 = 867\) parameters, optimized by CMA-ES on \(J(\theta) = \mathbb{E}[R \mid \theta]\) without gradients. Training in the dream maximizes \(J_{\text{dream}}(\theta) = J_{\text{real}}(\theta) + \epsilon(\theta)\), so the optimizer also searches for large positive model error \(\epsilon\). Raising \(\tau\) does not remove \(\epsilon\); it makes the estimate noisier and more pessimistic, so narrow exploits average out.

V is a standard convolutional autoencoder; the distinctive code is M's temperature-controlled sampler, the linear controller and the gradient-free optimizer. Sizes follow the car-racing agent: code size 32, LSTM hidden size 256, five mixture components per code dimension, three actions. One dream step turns three [32, 5] arrays (mixture logits, means, log standard deviations) into a sampled code of length 32; the controller reads the 288-dimensional \([z, h]\); the evolution strategy sees only one scalar fitness per candidate parameter vector.

import numpy as np
rng = np.random.default_rng(0)

Z, H, K, A = 32, 256, 5, 3          # Car Racing sizes: latent z, LSTM hidden, mixtures, actions

def mdn_sample(logit_pi, mu, log_sigma, tau=1.0, rng=rng):
    """Sample z_{t+1} from M's mixture-density output, one mixture per latent dimension.
    logit_pi, mu, log_sigma: [Z, K].  tau > 1 makes the dream noisier (harder to exploit)."""
    logits = logit_pi / tau                                   # flatter mixture weights
    pi = np.exp(logits - logits.max(-1, keepdims=True)); pi /= pi.sum(-1, keepdims=True)
    k = np.array([rng.choice(K, p=p) for p in pi])            # component per dimension
    idx = np.arange(Z)
    sigma = np.exp(log_sigma[idx, k]) * np.sqrt(tau)          # wider Gaussians
    return mu[idx, k] + sigma * rng.standard_normal(Z)        # [Z]

class LinearController:
    """C: a = tanh(W [z, h] + b). The only part trained with rewards."""
    def __init__(self, params=None):
        self.n = (Z + H) * A + A
        self.params = np.zeros(self.n) if params is None else params
    def act(self, z, h):
        W = self.params[:-A].reshape(A, Z + H); b = self.params[-A:]
        return np.tanh(W @ np.concatenate([z, h]) + b)        # [A] in [-1, 1]

def evolve(fitness, n_params, pop=32, elite=8, sigma=0.1, iters=60, rng=rng):
    """Simple (mu, lambda) evolution strategy: no gradients, only returns of rollouts.
    (World Models used CMA-ES, which also adapts the covariance of the search.)"""
    mean = np.zeros(n_params)
    for _ in range(iters):
        cand = mean + sigma * rng.standard_normal((pop, n_params))
        scores = np.array([fitness(c) for c in cand])
        mean = cand[np.argsort(scores)[-elite:]].mean(0)      # move toward the best candidates
    return mean

if __name__ == "__main__":
    assert LinearController().n == 867                      # matches the paper's 867 parameters
    # Temperature check: higher tau -> larger spread of dreamed latents.
    lp, mu, ls = rng.normal(size=(Z, K)), rng.normal(size=(Z, K)), np.full((Z, K), -1.0)
    spread = lambda t: np.std([mdn_sample(lp, mu, ls, t) for _ in range(400)], axis=0).mean()
    s1, s2 = spread(1.0), spread(1.15)
    print(f"spread tau=1.0: {s1:.3f}  tau=1.15: {s2:.3f}")
    assert s2 > s1
    # ES check on a toy 'dream' whose return peaks at a known parameter vector.
    target = rng.normal(size=10)
    best = evolve(lambda p: -np.sum((p - target) ** 2), 10, sigma=0.3, iters=80)
    print("distance to optimum:", round(float(np.linalg.norm(best - target)), 3))
    assert np.linalg.norm(best - target) < 0.5
    print("ok")

Output: the controller has exactly 867 parameters; the spread of dreamed codes rises from 0.882 at \(\tau = 1.0\) to 0.904 at \(\tau = 1.15\); and the evolution strategy ends 0.27 from the optimum of a toy fitness using fitness values alone, which is the property that lets C be trained inside a non-differentiable dream. The published agent used CMA-ES, which also adapts the covariance of the search; the simple elite-averaging variant here keeps the loop readable.

A policy optimized inside a learned model is optimized against the model's errors as well as the task. The model is accurate only where its data lies; an improving policy moves to new states, where errors are larger and, to an optimizer, systematically favorable. Dreamed return can rise while real return collapses, and nothing inside the dream signals it.

VizDoom survival time in the dream and in the real game at five temperatures0500100015002000solve threshold 7502086193τ = 0.102060196τ = 0.501145868τ = 1.009181092τ = 1.15732753τ = 1.30in the dream (virtual)in the real game (actual)time steps survived
Fig. Dream exploitation measured. Mean survival time of the VizDoom controller inside the learned model and in the real game, for five sampling temperatures \(\tau\) (numbers from Ha & Schmidhuber 2018). At low temperature the controller survives about 2,000 steps in the dream and about 195 in reality, worse than the random policy (210); at \(\tau = 1.15\) the dream is harder than reality and transfer is best.

Three measurements separate exploitation from other causes of poor real returns: a dream gap (imagined over real return, same checkpoint) that is high and rising; model error on the current policy's real rollouts that is much higher than on the training buffer; and a fresh policy trained in the same model that also fails. The remedies trade off against each other. Refreshing the model with data from the current policy removes the cause but costs real interaction; Ha and Schmidhuber proposed this iterative loop for harder tasks, and Dreamer builds it in. Making the dream more stochastic, or shortening the imagined horizon, costs peak performance: in VizDoom the real score falls from 1,092 to 753 when \(\tau\) rises from 1.15 to 1.30. Slowing policy change between model refreshes costs speed where the model is right. The original pipeline also scaled poorly: V and M were trained once on random-policy data, and evolution strategies need populations that grow with parameter count.

PlaNet and the Recurrent State-Space Model

Hafner et al. (2019) introduced PlaNet and with it the recurrent state-space model (RSSM), still the backbone of the Dreamer family. The insight was that a purely deterministic latent state cannot represent uncertainty about the future, while a purely stochastic one struggles to remember information over many steps. The RSSM splits the state in two:

\[ \begin{aligned} &\text{Deterministic path:} && h_t = f_\theta(h_{t-1}, z_{t-1}, a_{t-1}) \\ &\text{Prior (imagination):} && \hat{z}_t \sim p_\theta(\hat{z}_t \mid h_t) \\ &\text{Posterior (filtering):} && z_t \sim q_\phi(z_t \mid h_t, x_t) \\ &\text{Decoder and reward:} && \hat{x}_t \sim p_\theta(x_t \mid h_t, z_t), \quad \hat{r}_t \sim p_\theta(r_t \mid h_t, z_t) \end{aligned} \]

\(f_\theta\) is a GRU, \(h_t\) its deterministic hidden state, and \(z_t\) a stochastic latent (Gaussian in PlaNet and Dreamer v1; a set of categorical variables from DreamerV2 on). The posterior sees the real observation \(x_t\); the prior must guess \(z_t\) from \(h_t\) alone. Training pulls the prior toward the posterior with a KL term, so at test time the agent can roll the model forward using only the prior, which is exactly what imagination means. PlaNet planned with the cross-entropy method over action sequences at every step and learned continuous control from pixels with far fewer environment episodes than the model-free agents of the time.

The recurrent state-space model unrolled over three time steps. t − 1 t t + 1 a_t−1 a_t h_t−1 h_t h_t+1 deterministic deterministic deterministic z_t−1 z_t z_t+1 stochastic stochastic stochastic x_t−1 (obs) x_t (obs) x_t+1 (obs) prior posterior decode
Fig. The RSSM unrolled. The deterministic state \(h_t\) carries memory forward from \(h_{t-1}\), \(z_{t-1}\) and \(a_{t-1}\); the prior predicts \(z_t\) from \(h_t\) alone, while the posterior also sees the observation \(x_t\). During imagination the bottom row disappears and only the prior is used. Decoding (dashed) is drawn for step \(t\) only. (Adapted and redrawn from Hafner et al. 2019.)

The RSSM is a sequential latent-variable model. A GRU \(f_\theta\) carries the deterministic state \(h_t = f_\theta(h_{t-1}, z_{t-1}, a_{t-1})\); the prior \(p_\theta(z_t \mid h_t)\) predicts the stochastic state without the observation, the posterior \(q_\phi(z_t \mid h_t, x_t)\) infers it with the observation, and heads predict \(x_t\), \(r_t\) and the continuation flag \(c_t\) from \((h_t, z_t)\). Training maximizes the evidence lower bound

\[ \mathcal{L}_{\text{ELBO}} = \sum_{t=1}^{T} \mathbb{E}_{q}\Big[ \log p_\theta(x_t \mid h_t, z_t) + \log p_\theta(r_t \mid h_t, z_t) + \log p_\theta(c_t \mid h_t, z_t) \Big] - \mathbb{E}_{q}\Big[ \mathrm{KL}\big(q_\phi(z_t \mid h_t, x_t) \,\|\, p_\theta(z_t \mid h_t)\big) \Big]. \]

Taken naively, the KL trains the prior toward the posterior (useful) and the posterior toward the prior (which can erase information). DreamerV2 and V3 split it with stop-gradients \(\mathrm{sg}(\cdot)\) and clip each copy below one nat ("free bits"):

\[ \mathcal{L} = \beta_{\text{pred}} \mathcal{L}_{\text{pred}} + \beta_{\text{dyn}} \max\!\big(1, \mathrm{KL}(\mathrm{sg}(q) \,\|\, p)\big) + \beta_{\text{rep}} \max\!\big(1, \mathrm{KL}(q \,\|\, \mathrm{sg}(p))\big), \]

with \(\beta_{\text{pred}} = \beta_{\text{dyn}} = 1\) and \(\beta_{\text{rep}} = 0.1\) in DreamerV3. The dynamics term trains only the prior, the representation term only the encoder, and neither produces gradient once the KL is below one nat.

KL balancing: the dynamics loss trains the prior, the representation loss trains the posteriorPosterior q(z_t | h_t, x_t)sees the observation (encoder)Prior p(z_t | h_t)must predict without x_tRepresentation loss · weight 0.1max(1 nat, KL(q ‖ sg(p)))gradient reaches the posterior onlyDynamics loss · weight 1.0max(1 nat, KL(sg(q) ‖ p))gradient reaches the prior onlygradientgradientsame KL value, two copiessg( ) = stop-gradient
Fig. KL balancing with free bits, with the DreamerV3 weights (1.0 for the dynamics term, 0.1 for the representation term). Both terms evaluate the same divergence between posterior and prior; stop-gradients decide which network each copy updates. Clipping each term at 1 nat removes the gradient once the prior is already close enough, which keeps the encoder from squeezing information out of \(z_t\) to make the prior's job easy.

With 32 categoricals of 32 classes the KL is at most \(32 \ln 32 \approx 110.9\) nats; gradients pass through the samples with the straight-through estimator. PlaNet's planner, the cross-entropy method with horizon 12, 1,000 candidates, the top 100 refit and 10 iterations, costs 120,000 prior steps per real action.

The implementation is one step function used in two modes plus the balanced KL loss. Shapes, for batch \(B\): deterministic state h [B, 512]; stochastic state z [B, 1024], 32 one-hot vectors of 32 classes flattened; action a [B, A]; frame embedding embed [B, E]. The step updates h with the GRU, computes prior logits, and, if an embedding is given, samples z from the posterior (filtering); otherwise from the prior (imagination). onehot + probs - probs.detach() equals the one-hot sample in value and has the gradient of the probabilities.

import torch, torch.nn as nn, torch.nn.functional as F
from torch.distributions import Categorical, kl_divergence

class RSSM(nn.Module):
    def __init__(self, act_dim, embed_dim, h_dim=512, z_cls=32, z_cat=32):
        super().__init__()
        self.z_dim = z_cls * z_cat                     # 32 categoricals x 32 classes = 1024
        self.z_cls, self.z_cat = z_cls, z_cat
        self.inp = nn.Linear(self.z_dim + act_dim, h_dim)
        self.gru = nn.GRUCell(h_dim, h_dim)
        self.prior = nn.Sequential(nn.Linear(h_dim, h_dim), nn.ELU(), nn.Linear(h_dim, self.z_dim))
        self.post = nn.Sequential(nn.Linear(h_dim + embed_dim, h_dim), nn.ELU(), nn.Linear(h_dim, self.z_dim))

    def sample(self, logits):
        logits = logits.view(-1, self.z_cls, self.z_cat)
        probs = F.softmax(logits, -1)
        idx = Categorical(probs=probs).sample()
        onehot = F.one_hot(idx, self.z_cat).float()
        z = onehot + probs - probs.detach()            # straight-through gradient
        return z.flatten(1), logits

    def step(self, h, z, a, embed=None):
        """One RSSM step. With embed (encoded x_t): posterior; without: prior (imagination)."""
        h = self.gru(F.elu(self.inp(torch.cat([z, a], -1))), h)   # h_t = f(h_{t-1}, z_{t-1}, a_{t-1})
        prior_logits = self.prior(h)
        if embed is None:
            z, _ = self.sample(prior_logits)
            return h, z, prior_logits, None
        z, post_logits = self.sample(self.post(torch.cat([h, embed], -1)))
        return h, z, prior_logits, post_logits

def kl_loss(post_logits, prior_logits, balance=0.8, free_nats=1.0):
    """KL balancing with free bits. Logits: [B, 32, 32].
    balance of the gradient trains the prior (dynamics), 1 - balance trains the posterior."""
    post = lambda l: Categorical(logits=l)
    kl = lambda q, p: kl_divergence(post(q), post(p)).sum(-1)       # sum over 32 latents -> [B]
    dyn = kl(post_logits.detach(), prior_logits)                       # moves the prior only
    rep = kl(post_logits, prior_logits.detach())                       # moves the posterior only
    dyn = torch.clamp(dyn, min=free_nats).mean()                       # no gradient below 1 nat
    rep = torch.clamp(rep, min=free_nats).mean()
    return balance * dyn + (1 - balance) * rep, kl(post_logits, prior_logits).mean().detach()

if __name__ == "__main__":
    torch.manual_seed(0)
    B, A, E = 16, 6, 1024                                  # batch, action dim, encoder embedding
    m = RSSM(A, E)
    h, z = torch.zeros(B, 512), torch.zeros(B, 1024)
    a, emb = torch.zeros(B, A), torch.randn(B, E)
    h, z, prior_l, post_l = m.step(h, z, a, emb)          # filtering step (sees x_t)
    assert h.shape == (B, 512) and z.shape == (B, 1024) and post_l.shape == (B, 32, 32)
    assert torch.allclose(z.view(B, 32, 32).sum(-1), torch.ones(B, 32))   # one-hot per latent
    h2, z2, _, none = m.step(h, z, a)                      # imagination step (prior only)
    assert none is None and z2.shape == (B, 1024)
    # Free bits: identical distributions -> raw KL 0 but loss clamps at 1 nat with zero gradient.
    l = torch.randn(B, 32, 32, requires_grad=True)
    loss, raw = kl_loss(l, l.detach().clone().requires_grad_(True))
    loss.backward()
    assert abs(raw.item()) < 1e-6 and abs(loss.item() - 1.0) < 1e-6 and l.grad.abs().sum() == 0
    # Above the floor, the prior receives 0.8 and the posterior 0.2 of the gradient scale.
    q = torch.randn(B, 32, 32, requires_grad=True); p = torch.zeros(B, 32, 32, requires_grad=True)
    loss, raw = kl_loss(q, p); loss.backward()
    print(f"raw KL {raw.item():.2f} nats, loss {loss.item():.2f}")
    assert raw.item() > 1.0
    q2, p2 = q.detach().clone().requires_grad_(True), p.detach().clone().requires_grad_(True)
    kl_divergence(Categorical(logits=q2), Categorical(logits=p2)).sum(-1).mean().backward()
    assert torch.allclose(p.grad, 0.8 * p2.grad, atol=1e-6)            # prior gets 80 %
    assert torch.allclose(q.grad, 0.2 * q2.grad, atol=1e-6)            # posterior gets 20 %
    # Straight-through: gradient reaches the logits through the sampled one-hot.
    logits = torch.randn(2, 1024, requires_grad=True)
    zz, _ = m.sample(logits); (zz * torch.randn_like(zz)).sum().backward()
    assert logits.grad.abs().sum() > 0
    print("max KL for 32x32 categoricals:", round(32 * torch.log(torch.tensor(32.)).item(), 1), "nats")
    print("ok")

Output: a raw KL of 14.36 nats for random posterior logits against a uniform prior, and the maximum of 110.9 nats for this latent layout. The assertions check that every latent block is a valid one-hot, that identical distributions give zero gradient at the free-bits floor, that the prior receives exactly 0.8 and the posterior 0.2 of the plain KL gradient in this balanced (DreamerV2-style) form, and that the straight-through sample passes gradient to the logits.

Two consequences of the objective drive most production work. A model with excellent reconstruction can still have a poor prior, and only the prior is used for imagination, so KL and open-loop prediction quality must be monitored separately from reconstruction. And the balance between dynamics and representation weights decides how much the state encodes: small but decision-critical details (a ball in Breakout, a key in a maze) are dropped first, because they contribute little reconstruction gradient. The diagnostic is the KL per latent variable rather than the total; variables with near-zero KL carry nothing beyond what the prior predicts, and a total pinned at the free-bits floor signals collapse.

Remedies each have a cost. Lowering \(\beta_{\text{rep}}\) lets the posterior drift further from the prior. Decoder-free objectives remove pixel reconstruction: R2-Dreamer uses a redundancy-reduction loss and reports gains on tasks built around tiny objects, and NE-Dreamer predicts the next encoder embedding, at the price of losing decoded frames as a debugging tool. The GRU is also sequential in time, which limits GPU utilization; transformer world models such as TWISTER and Dreamer 4 train in parallel over time but use memory that grows with context.

Dreamer: Learning Behaviors by Latent Imagination

Dreamer kept PlaNet's world model but replaced online planning with an actor and a critic trained entirely on imagined latent trajectories, which made acting cheap and let the policy look beyond a short planning horizon. Four versions trace how far the recipe has been pushed:

  • Dreamer v1. Hafner et al. (2020) trained the actor by backpropagating value estimates through the differentiable latent dynamics, on imagined rollouts of horizon \(H\) started from posterior states of real data.
  • DreamerV2. Hafner et al. (2021) switched to discrete categorical latents and KL balancing, and reported the first agent to reach human-level performance on the 55-game Atari benchmark by learning behaviors inside a separately trained world model.
  • DreamerV3. Hafner et al. (Nature, 2025), first released on arXiv in 2023, added normalization and transformation tricks so that a single set of hyperparameters works across more than 150 tasks, and became the first algorithm to collect diamonds in Minecraft from scratch without human data (project page).
  • Dreamer 4. Hafner, Yan & Lillicrap (2025) replaced the RSSM with a scalable transformer world model trained with a "shortcut forcing" objective that runs in real time on a single GPU. It learned mostly from unlabeled video plus a small amount of action-labeled data, and became the first agent to obtain Minecraft diamonds purely from offline data, a task the authors describe as needing over 20,000 mouse and keyboard actions from pixels (project page).

The arc matters beyond Minecraft. Dreamer 4 is the point where control world models and interactive video simulators meet: it is trained like a video model, yet judged by whether an agent trained inside it succeeds in the real game.

The core of every Dreamer is two functions: one RSSM step, used with real observations to infer states, and an imagination rollout, used without observations to train the policy. A compact PyTorch sketch:

import torch, torch.nn as nn, torch.nn.functional as F

class RSSM(nn.Module):
    def __init__(self, act_dim, embed_dim, h_dim=512, z_cls=32, z_cat=32):
        super().__init__()
        self.z_dim = z_cls * z_cat                     # 32 categoricals x 32 classes
        self.z_cls, self.z_cat = z_cls, z_cat
        self.inp = nn.Linear(self.z_dim + act_dim, h_dim)
        self.gru = nn.GRUCell(h_dim, h_dim)
        self.prior = nn.Sequential(nn.Linear(h_dim, h_dim), nn.ELU(), nn.Linear(h_dim, self.z_dim))
        self.post = nn.Sequential(nn.Linear(h_dim + embed_dim, h_dim), nn.ELU(), nn.Linear(h_dim, self.z_dim))

    def sample(self, logits):
        logits = logits.view(-1, self.z_cls, self.z_cat)
        probs = F.softmax(logits, -1)
        idx = torch.distributions.Categorical(probs=probs).sample()
        onehot = F.one_hot(idx, self.z_cat).float()
        z = onehot + probs - probs.detach()            # straight-through gradient
        return z.flatten(1), logits

    def step(self, h, z, a, embed=None):
        """One RSSM step. With embed (encoded x_t): posterior; without: prior (imagination)."""
        h = self.gru(F.elu(self.inp(torch.cat([z, a], -1))), h)   # h_t = f(h_{t-1}, z_{t-1}, a_{t-1})
        prior_logits = self.prior(h)
        if embed is None:
            z, _ = self.sample(prior_logits)
            return h, z, prior_logits, None
        z, post_logits = self.sample(self.post(torch.cat([h, embed], -1)))
        return h, z, prior_logits, post_logits

def imagine(rssm, actor, h, z, horizon=15):
    """Roll the learned dynamics forward from posterior states, choosing actions with the actor."""
    states = []
    for _ in range(horizon):
        a = actor(torch.cat([h, z], -1)).rsample()     # reparameterized action
        h, z, _, _ = rssm.step(h, z, a)                # prior only: no observation
        states.append(torch.cat([h, z], -1))
    return torch.stack(states)                         # [H, B, h_dim + z_dim]

# Training sketch: rewards = reward_head(states); values = critic(states)
# returns = lambda_return(rewards, values, gamma=0.997, lam=0.95)
# actor_loss = -returns.mean()  (plus entropy bonus); critic regresses toward returns.detach()

Write \(s_t = (h_t, z_t)\). From start states inferred by the posterior on replayed data, the actor \(\pi_\psi(a_t \mid s_t)\) and the prior generate \(s_1, \dots, s_H\) with predicted rewards \(\hat r_t\) and continuation probabilities \(\hat c_t\); the critic \(v_\xi(s_t)\) estimates return beyond the horizon. Targets are λ-returns, computed backward:

\[ R^\lambda_t = \hat r_t + \gamma \hat c_t \Big( (1 - \lambda)\, v_\xi(s_{t+1}) + \lambda\, R^\lambda_{t+1} \Big), \qquad R^\lambda_H = v_\xi(s_H). \]

\(\lambda = 0\) gives one-step targets; \(\lambda = 1\) gives the discounted sum of imagined rewards plus \(\gamma^H v_\xi(s_H)\). A critic consistent with the rewards is a fixed point of the recursion. The critic regresses on \(\mathrm{sg}(R^\lambda_t)\). Dreamer v1's actor maximizes the returns by backpropagating through the dynamics,

\[ \mathcal{L}(\psi) = -\,\mathbb{E}\Big[\sum_{t=0}^{H-1} R^\lambda_t + \eta\, \mathrm{H}\big[\pi_\psi(\cdot \mid s_t)\big]\Big]. \]

DreamerV3 makes these losses scale-free. The critic outputs a softmax over 255 bins placed at \(\operatorname{symexp}\) of an even grid on \([-20, 20]\), with \(\operatorname{symlog}(x) = \operatorname{sign}(x)\ln(1 + |x|)\), and is trained by cross-entropy against a twohot target on the two nearest bins. Advantages are divided by \(\max(1, S)\), where \(S\) is a moving average of the 95th minus the 5th percentile of returns, so one entropy weight \(\eta = 3 \times 10^{-4}\) works across reward scales. The world model uses the balanced, free-bits objective with \(\beta_{\text{dyn}} = 1\) and \(\beta_{\text{rep}} = 0.1\).

Behavior learning needs four pieces beyond the RSSM: the imagination rollout, the λ-return, the symlog and twohot transforms used by the critic, and the percentile return normalizer used by the actor. With imagination horizon 15 and \(B\) start states of size 1,536, imagine returns [15, B, 1536]; reward, continuation and critic heads give [15, B], [15, B] and [16, B] (one extra value for the bootstrap); lambda_return walks backward and returns [15, B] targets.

import torch

def lambda_return(rewards, values, conts, gamma=0.997, lam=0.95):
    """TD(lambda) targets along an imagined trajectory, computed backwards.
    rewards, conts: [H, B] (reward and continue flag predicted for step t+1)
    values:         [H+1, B] critic values for states 0..H
    returns:        [H, B]   R_t = r_t + gamma c_t ((1 - lam) v_{t+1} + lam R_{t+1}),  R_H = v_H"""
    H = rewards.shape[0]
    out, nxt = [], values[H]
    for t in reversed(range(H)):
        nxt = rewards[t] + gamma * conts[t] * ((1 - lam) * values[t + 1] + lam * nxt)
        out.append(nxt)
    return torch.stack(out[::-1])

def symlog(x): return torch.sign(x) * torch.log1p(x.abs())
def symexp(x): return torch.sign(x) * torch.expm1(x.abs())

BINS = symexp(torch.linspace(-20, 20, 255))            # exponentially spaced bins (DreamerV3)

def twohot(x, bins=BINS):
    """Encode scalars [N] as soft targets [N, len(bins)] on the two nearest bins."""
    x = x.clamp(bins[0], bins[-1])
    k = torch.searchsorted(bins, x, right=True).clamp(1, len(bins) - 1)   # bins[k-1] <= x < bins[k]
    lo, hi = bins[k - 1], bins[k]
    w_hi = (x - lo) / (hi - lo)
    t = torch.zeros(len(x), len(bins))
    t.scatter_(1, (k - 1)[:, None], (1 - w_hi)[:, None]); t.scatter_(1, k[:, None], w_hi[:, None])
    return t

def decode(probs, bins=BINS): return probs @ bins       # expected value under the softmax

class ReturnNorm:
    """Scale advantages by S = max(1, P95(R) - P5(R)), tracked with an EMA (decay 0.99)."""
    def __init__(self, decay=0.99): self.decay, self.scale = decay, None
    def __call__(self, returns):
        s = torch.quantile(returns.flatten(), 0.95) - torch.quantile(returns.flatten(), 0.05)
        self.scale = s if self.scale is None else self.decay * self.scale + (1 - self.decay) * s
        return torch.clamp(self.scale, min=1.0)

def imagine(rssm, actor, h, z, horizon=15):
    """Roll the learned dynamics forward from posterior states, choosing actions with the actor."""
    states = []
    for _ in range(horizon):
        a = actor(torch.cat([h, z], -1)).rsample()     # reparameterized action
        h, z, _, _ = rssm.step(h, z, a)                # prior only: no observation
        states.append(torch.cat([h, z], -1))
    return torch.stack(states)                         # [H, B, h_dim + z_dim]

if __name__ == "__main__":
    H, B = 15, 4
    r = torch.full((H, B), 1.7); c = torch.ones(H, B)
    v_star = 1.7 / (1 - 0.997)                                         # 566.67: consistent value
    R = lambda_return(r, torch.full((H + 1, B), v_star), c)
    assert torch.allclose(R, torch.full_like(R, v_star), rtol=1e-5)    # fixed point
    v = torch.full((H + 1, B), v_star); v[H] = 500.0                   # pessimistic bootstrap
    R = lambda_return(r, v, c)
    print(f"R_0 with v_H = 500: {R[0, 0]:.1f}   (consistent value {v_star:.1f})")
    # lam = 0 gives one-step TD targets; lam = 1 gives discounted rewards plus bootstrap at H.
    torch.manual_seed(0); rr, vv = torch.randn(H, B), torch.randn(H + 1, B)
    assert torch.allclose(lambda_return(rr, vv, c, lam=0.0), rr + 0.997 * vv[1:])
    mc = sum(0.997 ** k * rr[k] for k in range(H)) + 0.997 ** H * vv[H]
    assert torch.allclose(lambda_return(rr, vv, c, lam=1.0)[0], mc, atol=1e-5)
    # symlog / twohot round trips, including large returns such as 850.
    x = torch.tensor([-850.0, -3.0, 0.0, 0.4, 1.7, 566.7, 850.0])
    assert torch.allclose(symexp(symlog(x)), x, rtol=1e-5)
    assert torch.allclose(decode(twohot(x)), x, rtol=1e-4, atol=1e-4)
    norm = ReturnNorm(); print("scale for small returns:", norm(torch.rand(1000) * 0.2).item())
    # Imagination: 16 start states, H = 15, h 512 + z 1024 -> [15, 16, 1536]; gradients reach the actor.
    from c2_rssm import RSSM
    rssm = RSSM(act_dim=6, embed_dim=1024)
    net = torch.nn.Linear(1536, 6)
    actor = lambda s: torch.distributions.Normal(torch.tanh(net(s)), 0.3)
    traj = imagine(rssm, actor, torch.zeros(16, 512), torch.zeros(16, 1024))
    assert traj.shape == (15, 16, 1536)
    traj.sum().backward(); assert net.weight.grad.abs().sum() > 0
    print("ok")

Output: with constant reward 1.7 and the consistent value 566.7 the recursion is a fixed point; lowering only the bootstrap value to 500 gives \(R^\lambda_0 = 535.6\), because the deficit reaches the start with weight \(\gamma^{15}\lambda^{14} \approx 0.47\); the normalizer leaves a small return spread unscaled (1.0). The assertions confirm that \(\lambda = 0\) and \(\lambda = 1\) reproduce one-step and Monte Carlo targets, that symlog and twohot round-trip values up to ±850, and that gradients reach the actor through the imagined dynamics. The most common bug is an off-by-one between reward and value indices, which these tests catch.

Dreamer's production problems sit at the interfaces between collection, model training and behavior learning. The replay ratio (replayed steps per environment step) sets sample efficiency and cost together and is the hyperparameter routinely retuned: DreamerV3 uses different values per domain, and doubling it doubles the gradient updates per real step. Overfitting shows as a growing gap between model loss on the newest data and on older data.

Reward scale was the main obstacle to a single configuration. Squared-error critics produce gradients proportional to return size, so one learning rate cannot serve returns of 1 and 10,000; a large-reward task typically shows exploding critic loss and collapsing actor entropy while world-model losses stay normal. DreamerV3's twohot critic and percentile normalization remove that dependence, which is why its fixed hyperparameters held across more than 150 tasks.

Dreamer 4 changes where errors are controlled. Its world model, a causal tokenizer plus a dynamics transformer of about two billion parameters trained on TPU pods, learned from roughly 2,500 hours of Minecraft gameplay, and the policy was trained in imagination with the transformer frozen. Diamonds were obtained in a small fraction of episodes, with no environment interaction. Offline, no fresh data corrects the model, so object interactions and the reward model's recognition of success must be validated before policy training. A monitoring dashboard for any Dreamer covers real return per seed, dream gap, KL and open-loop error, critic loss and gradient norm, actor entropy, normalizer scale and updates per second.

Beyond Reconstruction: Value-Equivalent and Token Models

A world model only has to be accurate about what matters for decisions, and three lines of work exploit that in different ways: MuZero drops observation prediction altogether, IRIS and DIAMOND go the other way and model pixels with sequence or diffusion models, and TD-MPC2 keeps a decoder-free latent model but plans in it at every step. The contrast between them is the clearest illustration of objective mismatch in practice.

All the models in this section learn from the same data, trajectories of observations \(o_t\), actions \(a_t\) and rewards \(u_t\). They differ in the prediction targets of the training loss. With internal state \(s_t\), discount \(\gamma\in[0,1)\) and parameters \(\theta\), the four objectives are, schematically:

\[ \mathcal{L}_{\text{recon}} = \sum_t \big[ -\log p_\theta(o_t \mid s_t) - \log p_\theta(u_t \mid s_t) + \beta\,\mathrm{KL}\big(q(s_t \mid s_{t-1}, a_{t-1}, o_t)\,\|\,p_\theta(s_t \mid s_{t-1}, a_{t-1})\big) \big] \] \[ \mathcal{L}_{\text{VE}} = \sum_{k=0}^{K} \big[ \ell^r(u_{t+k}, \hat r^k) + \ell^v(z_{t+k}, \hat v^k) + \ell^p(\pi_{t+k}, \hat p^k) \big] \] \[ \mathcal{L}_{\text{gen}} = -\sum_t \log p_\theta(x_{t+1} \mid x_{\le t}, a_{\le t}) \qquad \mathcal{L}_{\text{latent}} = \sum_{t=0}^{H} \rho^t \big[ \|\hat z_{t+1} - \mathrm{sg}(h(o_{t+1}))\|^2 + \ell^r + \ell^q \big] \]

\(\mathcal{L}_{\text{recon}}\) is the Dreamer objective. In \(\mathcal{L}_{\text{VE}}\) (MuZero) the model is unrolled \(K\) steps and its reward, value and policy are matched to observed rewards, bootstrapped returns \(z\) and search policies \(\pi\). In \(\mathcal{L}_{\text{gen}}\) (IRIS, DIAMOND) \(x_t\) is the frame as tokens or pixels; in \(\mathcal{L}_{\text{latent}}\) (TD-MPC2) \(h\) is the encoder and \(\mathrm{sg}\) a stop-gradient. Only \(\mathcal{L}_{\text{recon}}\) and \(\mathcal{L}_{\text{gen}}\) contain the observation; objective mismatch is the gap between these targets and the return \(\mathbb{E}\big[\sum_t \gamma^t u_t\big]\) the agent maximizes.

Every family except pure reconstruction also learns a value, for a structural reason. The effective horizon is \(1/(1-\gamma)\), about 333 decisions at \(\gamma = 0.997\), while a 15-step model rollout covers only \(1 - \gamma^{15} \approx 4.4\%\) of the discount mass. The remainder must come from a learned estimate of future return.

The difference between the families is easiest to see as data: for one batch of experience, which arrays does each world-model loss compare against? The script below builds one Atari-style segment (64×64 RGB frames, a discrete action, reward and continue flag) and returns each family's targets. The inputs are identical; only the target dictionary changes.

import numpy as np

# One Atari-style training segment: T steps of 64x64 RGB frames, a discrete action, reward, continue flag.
T, H, W, C = 16, 64, 64, 3
rng = np.random.default_rng(0)
seg = {"obs": rng.integers(0, 256, (T, H, W, C), dtype=np.uint8),
       "act": rng.integers(0, 18, T), "rew": rng.normal(size=T).astype(np.float32),
       "cont": np.ones(T, np.float32)}

def prediction_targets(family, seg):
    """Arrays each family's world-model loss is computed against; the input data are identical."""
    T = len(seg["rew"])
    if family == "reconstruction (Dreamer)":
        return {"pixels": seg["obs"], "reward": seg["rew"], "cont": seg["cont"]}
    if family == "value-equivalent (MuZero)":       # value/policy filled by n-step returns and search
        return {"reward": seg["rew"], "value": np.zeros(T), "policy": np.zeros((T, 1))}
    if family == "token (IRIS)":                    # 16 codebook indices per 64x64 frame
        return {"tokens": np.zeros((T, 16), np.int64), "reward": seg["rew"], "cont": seg["cont"]}
    if family == "latent (TD-MPC2)":                # stop-gradient encoder output, 512-d
        return {"next_latent": np.zeros((T, 512)), "reward": seg["rew"], "value": np.zeros(T)}

def targets_per_step(tg):
    return sum(int(np.prod(v.shape[1:])) if v.ndim > 1 else 1 for v in tg.values())

for fam in ["reconstruction (Dreamer)", "value-equivalent (MuZero)", "token (IRIS)", "latent (TD-MPC2)"]:
    print(f"{fam:26s} targets per step = {targets_per_step(prediction_targets(fam, seg))}")

It prints 12,290 targets per step for reconstruction (pixels plus reward and continue flag), 3 for the value-equivalent model, 18 for an IRIS-style token model with 16 tokens per frame, and 514 for a TD-MPC2-style model with a 512-dimensional latent. Two implementation consequences follow. Targets that are not in the data, such as MuZero's values and search policies, must be produced by running the network inside the data pipeline. Latent targets, as in TD-MPC2, need a stop-gradient, because a model allowed to move its own target can collapse it to a constant.

In practice the choice among the three lines is a choice of where computation goes and what is locked in at training time. Four questions can be answered with measurements before committing to an architecture.

QuestionMeasurementFavours
Will the reward change after training?Reward variants expected in deploymentReconstruction or generative models; a value-equivalent model must be retrained
Does decision-relevant information sit in a few pixels?Return drop after downsampling or tokenizing framesPixel-space diffusion (DIAMOND) over coarse tokens
Is there a hard latency budget per action?Milliseconds per decisionA policy trained in imagination over online planning (MuZero, TD-MPC2)
Is training or acting compute scarcer?GPU hours at training versus cost per decisionImagination moves cost to training; planning moves it to acting

Table. Measurable inputs to the choice of world-model family.

The failure common to all three is objective mismatch: the world model's own loss keeps improving while the agent's return stalls. Logging the loss by term, reward-prediction error by unroll depth and real return separates the causes: a falling loss with flat reward error means capacity spent on observations; good one-step but poor five-step error means compounding error. A remedy counts only if real return rises at equal environment steps.

MuZero and Value Equivalence

Schrittwieser et al. (2020) introduced MuZero, which plans with Monte Carlo tree search inside a learned model that never reconstructs observations. The model has three functions: a representation network that encodes the history into a hidden state, a dynamics network that maps a hidden state and action to the next hidden state and a reward, and a prediction network that outputs a policy and value. All three are trained so that, unrolled for several steps, the predicted rewards, values and policies match targets from real play.

  • MuZero needed no knowledge of the rules, yet matched AlphaZero in Go, chess and shogi and set a new state of the art across 57 Atari games.
  • The hidden state is free to ignore anything irrelevant to reward and value, such as background textures, which is both its strength (capacity goes where decisions are made) and a limitation (the model cannot be reused for a different reward).

Grimm et al. (2020) formalized the idea as the value equivalence principle: two models are equivalent if they induce the same Bellman updates for a chosen set of policies and value functions, so a model need only be correct with respect to the values the agent will actually compute. That is the theoretical opposite of a video simulator, which tries to be right about everything.

Model. Given history \(o_1,\dots,o_t\) and actions \(a_{t+1},\dots,a_{t+k}\), MuZero (Schrittwieser et al. 2020) defines

\[ s^0 = h_\theta(o_1,\dots,o_t), \qquad (r^k, s^k) = g_\theta(s^{k-1}, a_{t+k}), \qquad (p^k, v^k) = f_\theta(s^k), \]

and minimizes, over an unroll of \(K\) steps (\(K=5\) in the paper),

\[ \ell_t(\theta) = \sum_{k=0}^{K} \Big[ \ell^r(u_{t+k}, r^k) + \ell^v(z_{t+k}, v^k) + \ell^p(\pi_{t+k}, p^k) \Big] + c\|\theta\|^2, \qquad z_{t+k} = \sum_{i=0}^{n-1}\gamma^i u_{t+k+1+i} + \gamma^n \nu_{t+k+n}, \]

where \(\pi\) is the normalized root visit-count distribution of the search and \(\nu\) a search value. Values and rewards are regressed as categorical distributions after the transform \(\mathfrak{h}(x) = \operatorname{sign}(x)(\sqrt{|x|+1}-1) + 0.001x\), which compresses returns that span orders of magnitude. The tree search selects \(\arg\max_a \big[\bar Q(a) + P(a)\frac{\sqrt{N}}{1+N(a)}\big(c_1 + \log\frac{N+c_2+1}{c_2}\big)\big]\), with \(\bar Q\) min-max normalized, prior \(P\) from \(f_\theta\) and visit counts \(N\).

Value equivalence. For a model \(m\) with reward \(r_m\) and transitions \(P_m\), the Bellman operator is \(\mathcal{T}^\pi_m v = r^\pi_m + \gamma P^\pi_m v\). Grimm et al. (2020) call \(m\) value-equivalent to the true model \(m^\star\) with respect to policies \(\Pi\) and functions \(\mathcal{V}\) if

\[ \mathcal{T}^\pi_m v = \mathcal{T}^\pi_{m^\star} v \quad \text{for all } \pi\in\Pi,\ v\in\mathcal{V}. \]
Nested sets of models: all models, models value-equivalent for a chosen set of policies and value functions, and models value-equivalent for all of them, which contains the true model.All models in the model classValue-equivalent for the chosen policies Π and value functions VValue-equivalent for all Π and Vtrue model m*a model that ignoresthe backgrounda model withwrong dynamicsenlarging Π or Vshrinks the set
Fig. Value equivalence as nested sets. A model that predicts the background wrongly can be value-equivalent when no value function in V depends on the background; a model with wrong reward-relevant dynamics cannot. Growing Π and V shrinks the set toward the true model.

The set \(\mathcal{M}(\Pi,\mathcal{V})\) always contains \(m^\star\) and shrinks as \(\Pi\) or \(\mathcal{V}\) grows. If every \(v\in\mathcal{V}\) depends only on a feature \(x\) of the state, any model that gets the reward and the distribution of \(x\) right qualifies, however wrong it is about everything else. The guarantee covers only the policies and values used in training, which is the formal reason a MuZero model cannot be reused for a different reward. The \(n\)-step target trades bootstrap bias against sampled-reward variance; with \(\gamma\) near 1 the bootstrap term \(\gamma^n\nu\) dominates the target.

Value equivalence can be checked exactly on a small Markov decision process. The state has a reward-relevant bit \(x\) and a background bit \(b\), such as a texture that changes at random. One model predicts both correctly; a second, background-blind model always predicts \(b = 0\) but keeps the dynamics of \(x\). The script applies the Bellman operator \(\mathcal{T}^\pi v = r^\pi + \gamma P^\pi v\) of each model to 20 random policies and two families of value functions, then plans in both models with value iteration. It also prints MuZero's value transform for a return of 850.

import numpy as np

# 4-state MDP: s = 2*x + b. x in {0,1} decides reward; b in {0,1} is a background texture.
gamma, S, A = 0.997, 4, 2
r = np.array([[0.0, 0.0], [0.0, 0.0], [1.0, 0.7], [1.0, 0.7]])     # reward depends on x only

def true_P():
    P = np.zeros((A, S, S))
    for s in range(S):
        b = s % 2
        for a in range(A):
            px1 = 0.9 if a == 0 else 0.3                            # action 0 keeps x = 1
            for x2 in (0, 1):
                for b2 in (0, 1):
                    P[a, s, 2*x2 + b2] = (px1 if x2 else 1 - px1) * (0.8 if b2 == b else 0.2)
    return P

def background_blind_P():
    """Same x-dynamics, but the background is always predicted as b = 0."""
    Pt, P = true_P(), np.zeros((A, S, S))
    for x2 in (0, 1):
        P[:, :, 2*x2] = Pt[:, :, 2*x2] + Pt[:, :, 2*x2 + 1]
    return P

def bellman(P, pi, v):                                   # T^pi v = r_pi + gamma P_pi v
    return (pi * r).sum(1) + gamma * np.einsum("sa,ast->st", pi, P) @ v

def value_equivalent(P1, P2, policies, values):
    return all(np.allclose(bellman(P1, p, v), bellman(P2, p, v)) for p in policies for v in values)

def h(x, eps=1e-3):                                      # MuZero's value transform
    return np.sign(x) * (np.sqrt(np.abs(x) + 1) - 1) + eps * x

rng = np.random.default_rng(0)
pols = [rng.dirichlet(np.ones(A), size=S) for _ in range(20)]
v_x = [np.repeat(rng.normal(size=2), 2) for _ in range(20)]     # value functions of x only
v_any = [rng.normal(size=S) for _ in range(20)]                  # may depend on background
Pt, Pb = true_P(), background_blind_P()
print("VE for value functions of x:  ", value_equivalent(Pt, Pb, pols, v_x))
print("VE for arbitrary functions:   ", value_equivalent(Pt, Pb, pols, v_any))
def value_iteration(P, iters=20000):
    v = np.zeros(S)
    for _ in range(iters):
        v = (r + gamma * np.einsum("ast,t->sa", P, v)).max(1)
    return v
print("optimal values, true model:   ", value_iteration(Pt).round(2))
print("optimal values, blind model:  ", value_iteration(Pb).round(2))
print("h(850) =", round(float(h(850.0)), 2), "-> two-hot on atoms 29 and 30 of [-300, 300]")

Output: the two models are value-equivalent for value functions of \(x\) (True) but not for arbitrary ones (False), and value iteration gives identical optimal values, [299.1 299.1 300.1 300.1], in both. Planning is unaffected by the wrong background, which is MuZero's argument for not reconstructing it. The transform maps 850 to 29.02, well inside the ±300 categorical support. In a full MuZero implementation the same pieces appear as a representation, dynamics and prediction network; a replay buffer that stores search policies and values alongside transitions; and a target builder that computes \(n\)-step returns and two-hot encodings at sampling time.

Three problems dominate value-equivalent models in practice.

Acting cost. Every real decision requires a full tree search, and simulations are sequential because each reads statistics written by the previous one. MuZero used 800 simulations per move in board games and 50 in Atari. Acting systems therefore batch searches across many environments so that each network call serves many trees, distil the search policy into the prior for latency-bound deployment, and, for continuous actions, sample a small set of candidate actions per node, as in Sampled MuZero (Hubert et al. 2021) and the Gumbel-based search of EfficientZero V2 (Wang et al. 2024).

Stale targets. Value and policy targets in the replay buffer were computed by an older network, and with \(\gamma\) near 1 the bootstrap dominates the value target. MuZero Reanalyze re-runs the search on stored trajectories with the latest network, at the cost of one additional search per refreshed sample. The useful monitor is the gap between stored and recomputed values on a fixed probe set, plotted against target age.

No reuse across rewards. Because the hidden state may discard anything irrelevant to the trained reward, a new reward can require information the model never kept. A linear probe from the hidden state to task variables distinguishes "absent" from "unread". Self-predictive consistency losses (EfficientZero) and transformer-based latent models such as UniZero (Pu et al. 2024) retain more of the observation, at the cost of moving away from pure value equivalence. Reward-prediction error by unroll depth, search-versus-prior KL divergence and p99 search latency complete the standard dashboard.

Transformers and Diffusion as World Models

The second line treats world modeling as a generative sequence problem and imports the best generative architectures. Both were evaluated on Atari 100k, a benchmark that allows roughly two hours of real gameplay per game:

  • IRIS. Micheli et al. (2023) tokenized each frame with a discrete autoencoder and modeled the token sequence with an autoregressive transformer. An agent trained entirely in this model reached a mean human-normalized score of 1.046 and beat human players on 10 of 26 games.
  • DIAMOND. Alonso et al. (2024) argued that discrete tokens throw away small visual cues that matter for control and generated frames directly with a diffusion model. It reached a mean human-normalized score of 1.46, the best reported for agents trained entirely in a world model at the time, and the same approach produced a playable neural version of a Counter-Strike map.

The lesson from DIAMOND is a useful counterweight to MuZero: when decision-relevant information lives in a few pixels, a model that reconstructs pixels faithfully can beat one that compresses aggressively. Which approach wins depends on where the task's information is.

Tokens. A tokenizer maps frame \(o_t\) to \(n\) discrete tokens \(x_t = (x_t^1,\dots,x_t^n)\) from a codebook of size \(N\). A VQ-VAE encoder \(E\) outputs vectors \(e_i\), quantized to the nearest code \(c_k\), and is trained with (van den Oord et al. 2017)

\[ \mathcal{L}_{\text{VQ}} = \|o - D(c_x)\|^2 + \|\mathrm{sg}(e) - c_x\|^2 + \beta\|e - \mathrm{sg}(c_x)\|^2 , \]

with gradients copied through the \(\arg\min\) (straight-through estimator). IRIS uses \(n = 16\) and \(N = 512\), so each frame carries at most \(n\log_2 N = 144\) bits; whatever the tokenizer drops cannot be recovered by the world model.

Autoregressive model. The transformer factorizes

\[ p_\theta(x_{t+1}\mid x_{\le t}, a_{\le t}) = \prod_{i=1}^{n} p_\theta\big(x_{t+1}^i \mid x_{t+1}^{trained by cross-entropy, with reward and termination heads. Generating one frame takes \(n\) sequential passes. Block teacher forcing (Dedieu et al. 2025) drops the within-frame conditioning \(x_{t+1}^{

Diffusion. DIAMOND (Alonso et al. 2024) trains a denoiser \(D_\theta\) on noisy next frames \(o^\sigma = o_{t+1} + \sigma\varepsilon\), conditioned on recent frames and actions \(c_t\):

\[ \mathcal{L}_{\text{diff}} = \mathbb{E}_{\sigma,\varepsilon}\big[\lambda(\sigma)\,\|D_\theta(o^\sigma,\sigma,c_t) - o_{t+1}\|^2\big]. \]

The optimal denoiser is \(\mathbb{E}[o_{t+1}\mid o^\sigma, c_t]\); sampling integrates \(\mathrm{d}o/\mathrm{d}\sigma = (o - D_\theta(o,\sigma,c_t))/\sigma\) from large \(\sigma\) to 0 in a few Euler steps (three in DIAMOND). Few steps pull samples toward the conditional mean, harmless for near-deterministic transitions but a loss of diversity for stochastic ones.

Compounding error. If each generated frame adds error \(\epsilon\) and a fraction \(\delta\) of earlier error is amplified when the model consumes its own output, error after \(k\) steps is \(e_k = \epsilon\,((1+\delta)^k - 1)/\delta\): linear at first, exponential later. This is why both IRIS and DIAMOND train agents on short imagined rollouts completed by a learned value.

Two mechanisms carry most of the engineering weight in token and diffusion world models: the attention layout that decides how many sequential passes a frame costs, and the few-step diffusion sampler. The script below implements both. The layout interleaves 16 frame tokens with one action token per step, as in IRIS, and builds a block-causal mask in which a frame token sees every earlier step but not its own frame. The sampler integrates the probability-flow ODE with an EDM noise schedule (Karras et al. 2022), using an exact Gaussian denoiser so that the true next-frame distribution is known.

import numpy as np

def block_causal_mask(T, n):
    """Tokens laid out [frame_1 (n tokens), a_1, frame_2, a_2, ...]. Each frame token sees all
    earlier steps but not its own frame, so a whole frame is predicted in ONE forward pass."""
    L = T * (n + 1); step = np.arange(L) // (n + 1)
    is_act = np.arange(L) % (n + 1) == n
    m = step[:, None] > step[None, :]
    m |= (step[:, None] == step[None, :]) & is_act[:, None] & ~is_act[None, :]   # action sees its frame
    return m

def karras_sigmas(n, smin=0.002, smax=80.0, rho=7.0):     # EDM noise levels, high to low, then 0
    i = np.arange(n)
    return np.append((smax**(1/rho) + i/max(n-1, 1)*(smin**(1/rho) - smax**(1/rho)))**rho, 0.0)

def euler_sample(D, x, sigmas):                          # probability-flow ODE, Euler steps
    for s, s2 in zip(sigmas[:-1], sigmas[1:]):
        x = x + (s2 - s) * (x - D(x, s)) / s
    return x

# IRIS layout: 16 tokens per frame, 1 action token, context of 20 steps.
print("IRIS context tokens:", 20 * (16 + 1))
M = block_causal_mask(T=3, n=4)
print("frame token sees own frame:", bool(M[5, 6]), "| sees previous action:", bool(M[5, 4]))

# Next-frame pixel ~ N(0.3, 0.05^2): the optimal denoiser is the posterior mean.
mu, sd = 0.3, 0.05
D = lambda x, s: (sd**2 * x + s**2 * mu) / (sd**2 + s**2)
rng = np.random.default_rng(0)
for n in (1, 3, 10, 100):
    sig = karras_sigmas(n)
    x = euler_sample(D, sig[0] * rng.standard_normal(200_000), sig)
    print(f"{n:3d} denoising steps: mean {x.mean():.3f}  std {x.std():.4f}  (true std {sd})")

Output: an IRIS context of 20 steps holds 340 tokens; a frame token cannot see its own frame but sees the preceding action, so a whole frame is predicted in one pass. The sampler gets the mean (0.300) right at every step count, but the spread is 0.0000 with one step, 0.0030 with three, 0.0319 with ten and 0.0479 with a hundred, against a true 0.05. Few deterministic steps collapse a stochastic transition toward its mean, which suits Atari's mostly deterministic frames and is the first thing to check when a diffusion world model renders a random event identically every time.

Generative world models change the production question from "is the model accurate enough for the value calculation" to "can it generate frames fast enough, and for how long do they stay usable".

Generation speed. Autoregressive decoding is bound by memory bandwidth: every sequential pass reads all weights, so cost grows with tokens per frame. Systems reduce sequential passes by decoding a frame in parallel (block teacher forcing, or MaskGIT-style iterative rounds, Chang et al. 2022), reduce tokens by encoding only what changes between frames, as Δ-IRIS does (Micheli et al. 2024), and batch many imagined rollouts per pass during training. Diffusion models pay instead in denoising steps per frame, which is why DIAMOND keeps the number small. Each saving must be checked at long horizons, where within-frame independence shows up as inconsistent patches.

Drift. Error grows with horizon because the model is trained on real context but runs on its own outputs (exposure bias) and forgets anything older than its context. Noise augmentation of context frames, credited by GameNGen for its long-run stability (Valevski et al. 2024), and per-frame noise levels as in diffusion forcing (Chen et al. 2024) address the first; short rollouts branched from real states, as in MBPO (Janner et al. 2019), limit the damage to agents. The diagnostic is the gap between teacher-forced and self-generated error curves from the same start states. In 2025, Dreamer 4 (Hafner et al.) carried this line to a transformer over video tokens that trains Minecraft agents purely from offline data.

TD-MPC2: Planning in a Decoder-Free Latent Space

Hansen et al. (2024) combined the two ideas for continuous control. TD-MPC2 learns an implicit, decoder-free latent model (trained to predict future latents, rewards and values, as in MuZero) and runs model predictive control in it: at every step it samples action sequences, scores them with predicted rewards plus a learned terminal value, and executes the first action of the best plan.

  • One set of hyperparameters worked across 104 continuous-control tasks in four domains (DMControl, Meta-World, ManiSkill2, MyoSuite).
  • A single 317M-parameter agent handled 80 tasks across multiple embodiments and action spaces, an early sign that control world models scale with data and parameters like other models do.
ModelLatent stateDecoder?How behavior is obtainedSignature result
World Models (2018)VAE latent + RNN memoryYesEvolution strategy, trained in the dreamCar racing and VizDoom policies trained in imagination
PlaNet (2019)RSSM, GaussianYesCEM planning onlinePixel-based continuous control with few episodes
Dreamer v1–v3 (2020–2025)RSSM, Gaussian then categoricalYesActor-critic on imagined rolloutsHuman-level Atari (V2); 150+ tasks with fixed settings and Minecraft diamonds (V3)
MuZero (2020)Abstract hidden stateNoMCTS in the learned modelGo, chess, shogi, 57 Atari games without rules
IRIS (2023)Discrete frame tokensYesActor-critic in imaginationAtari 100k mean human-normalized 1.046
DIAMOND (2024)Pixel space (diffusion)Is the modelActor-critic in imaginationAtari 100k mean human-normalized 1.46
TD-MPC2 (2024)Implicit latentNoMPPI planning + learned value104 tasks, one hyperparameter set; 317M multi-task agent
Dreamer 4 (2025)Transformer over video tokensYesRL in imagination from offline dataMinecraft diamonds purely offline

Table. Control world models compared. Scores are as reported by each paper on its own protocol and are not directly comparable across rows.

Model and loss. TD-MPC2 (Hansen et al. 2024) learns \(z = h_\theta(s)\), \(z' = d_\theta(z,a)\), reward \(R_\theta(z,a)\), an ensemble of five Q-functions \(Q_\theta(z,a)\) and a policy prior \(p_\theta(z)\). Latents pass through SimNorm, a softmax over groups of \(V = 8\) coordinates that bounds every entry to \((0,1)\). From a replayed sequence it minimizes

\[ \mathcal{L}(\theta) = \sum_{t=0}^{H}\rho^t\Big[c_1\big\|d_\theta(z_t,a_t) - \mathrm{sg}(h_\theta(s_{t+1}))\big\|^2 + c_2\,\mathrm{CE}(\hat r_t, r_t) + c_3\,\mathrm{CE}(\hat q_t, q_t)\Big], \qquad q_t = r_t + \gamma\,\bar Q\big(z_{t+1}, p_\theta(z_{t+1})\big), \]

where \(\bar Q\) is the minimum of two randomly chosen members of a slowly updated ensemble copy, and rewards and values are classified over bins in a log-transformed space. The released configuration (TD-MPC2 repository) uses \(H = 3\), \(\rho = 0.5\), \(c_1 = 20\), \(c_2 = c_3 = 0.1\).

Sampling-based planning. A plan \(A = (a_0,\dots,a_{H-1})\) is scored by

\[ G(A) = \sum_{t=0}^{H-1}\gamma^t R_\theta(z_t,a_t) + \gamma^H Q_\theta\big(z_H, p_\theta(z_H)\big). \]

The cross-entropy method (CEM) keeps a Gaussian \(\mathcal{N}(\mu,\sigma^2)\) over plans, samples \(N\), and refits \(\mu,\sigma\) to the top \(K\) with equal weights. MPPI replaces equal weights by \(w_i \propto \exp(G_i/\lambda)\) over the elites, so \(\mu = \sum_i w_i A_i\), \(\sigma^2 = \sum_i w_i (A_i-\mu)^2\); CEM is the limit \(\lambda\to\infty\) on the top \(K\). TD-MPC2 uses \(N = 512\) samples plus 24 from the prior, \(K = 64\) and 6 iterations, then executes \(\mu_0\) and shifts \(\mu\) by one step for the next decision. With an ensemble, the uncertainty-penalized score \(G - \kappa\,\mathrm{std}_{\text{ens}}(G)\) keeps the optimizer away from states where the model is guessing.

Why the horizon is short. With \(\gamma = 0.997\), three planned rewards carry discount weight about 3 against an effective horizon of about 333, so the terminal \(Q\) dominates \(G\). Short horizons limit compounding model error, but they shift the burden to \(Q\), and any overestimation enters the MPPI weights exponentially: two plans whose scores differ by \(\Delta\) receive weights in the ratio \(e^{\Delta/\lambda}\).

PlaNet, TD-MPC2, DINO-WM and V-JEPA 2-AC all plan the same way: the world model is a black-box simulator, a population-based optimizer searches over action sequences, and the agent replans after every executed action. The function below implements the cross-entropy method and, with a temperature, MPPI's exponential weighting, together with TD-MPC2's SimNorm. It is tested on a toy latent model in which a point moves by 0.1 times the first two action dimensions and the score is the negative distance to a goal.

import torch

def simnorm(z, V=8):
    """TD-MPC2's SimNorm: softmax over groups of V coordinates, so every latent entry is in (0, 1)."""
    return torch.softmax(z.view(*z.shape[:-1], -1, V), -1).view(z.shape)

@torch.no_grad()
def plan(model, s0, act_dim, horizon=12, n=512, k=64, iters=6, score_fn=None, temp=None, mu=None):
    """CEM if temp is None (equal weights on the top k); MPPI weights exp(temp * G) otherwise.
    model.step(s, a) -> (s_next, r); score_fn(s_final) -> terminal value or -distance to goal."""
    mu = torch.zeros(horizon, act_dim) if mu is None else mu
    std = torch.ones(horizon, act_dim)
    for _ in range(iters):
        acts = (mu + std * torch.randn(n, horizon, act_dim)).clamp(-1, 1)
        s, ret = s0.expand(n, -1), torch.zeros(n)
        for t in range(horizon):
            s, r = model.step(s, acts[:, t])
            ret += r                                    # predicted reward
        if score_fn is not None:
            ret += score_fn(s)                          # learned value, or -||emb(s) - emb(goal)||
        top = ret.topk(k)
        elite = acts[top.indices]
        w = torch.full((k,), 1 / k) if temp is None else torch.softmax(temp * top.values, 0)
        mu = (w[:, None, None] * elite).sum(0)
        std = (w[:, None, None] * (elite - mu) ** 2).sum(0).sqrt() + 1e-3
    return mu[0], torch.cat([mu[1:], mu[-1:]])          # first action; shifted plan for warm start

class PointMass:                                        # toy latent model, goal-reaching (reward 0)
    def step(self, s, a):
        return s + 0.1 * a[:, :2], torch.zeros(s.shape[0])

torch.manual_seed(0)
z = simnorm(torch.randn(512))
print("SimNorm: 64 groups, each sums to 1:", bool(torch.allclose(z.view(64, 8).sum(-1), torch.ones(64))))
goal = torch.tensor([0.6, -0.4]); score = lambda s: -(s - goal).norm(dim=1)
for name, temp in [("CEM ", None), ("MPPI", 0.5)]:
    a, _ = plan(PointMass(), torch.zeros(1, 2), act_dim=6, score_fn=score, temp=temp)
    print(name, "first action (dims 0-1):", a[:2].numpy().round(2))
print("latent steps per TD-MPC2 decision (512 samples x 3 steps x 6 rounds):", 512 * 3 * 6)

Output: SimNorm produces 64 groups that each sum to 1; CEM's first action is [0.55 -0.36] and MPPI's [0.44 -0.4], both pointing toward the goal at (0.6, −0.4); a TD-MPC2 decision simulates 9,216 latent steps. Three details decide whether this works on a real model. Warm-start each step with the previous plan shifted by one, which the function returns. Bound the horizon by how far the model stays accurate and let a learned value (passed as score_fn) cover the rest. Penalize uncertainty by subtracting a multiple of ensemble disagreement from the score, which is the planner-side defense against model exploitation.

TD-MPC2 moves world-model computation to decision time, which creates three production concerns.

Planning latency. Each decision runs 6 iterations of 3 sequential latent steps, 18 batched calls plus encoder and prior, and only the samples within a call are parallel. A 50 Hz controller usually has room for this; a kilohertz torque loop does not. The standard remedies are to cut iterations to the point where plan return saturates on validation episodes, rely more on prior-proposed samples once the prior is trained, plan at a lower rate with action repeat, or act from the prior alone and keep planning for data collection.

Value exploitation. Because the terminal value dominates a three-step score, the planner actively seeks actions whose value is overestimated. Monitors: predicted value at episode start minus realized discounted return, and ensemble disagreement on chosen versus random actions; a ratio well above 1 means the optimizer is exploiting model error. The ensemble minimum in the TD target and an uncertainty penalty in the planner are the fixes, at the cost of slower exploration.

Multi-task scaling. In the TD-MPC2 scaling study, the 317M-parameter agent took 33 RTX 3090 GPU-days on 80 tasks against 12 for 48M parameters, for a small gain in normalized score: returns diminish beyond tens of millions of parameters. Newt (Hansen et al. 2025) extended the approach to 200 tasks with language task descriptions and demonstration pretraining. A 2026 counterpoint (Obando-Ceron et al.) reported that MR.Q, a model-free agent that uses latent dynamics and reward prediction only to shape its encoder, matched Newt on the same benchmark. Before paying for planning at scale, the ablation to run is the same encoder and predictive losses with and without the planner, at equal environment steps and equal wall-clock time.

From Video Generation to World Simulation

A video model becomes a world simulator when its predictions can be steered by actions and stay consistent as the user moves around in the generated world. Generating a plausible ten-second clip from a prompt is a much weaker property: the model never has to respond to an intervention, never has to remember what is behind the camera and never has to keep going for minutes. The work in this part is the story of adding those three properties (control, memory and stability) to large video generators.

OpenAI's Sora report, "Video generation models as world simulators" (February 2024), made the framing explicit. Sora compresses video into a latent space, cuts it into spacetime patches that act as tokens, and trains a diffusion transformer to denoise them. The report argued that scaling this recipe produces emergent simulation abilities without explicit 3D modeling:

  • 3D consistency as the camera moves, and objects that persist when occluded or out of frame.
  • Simple interactions that leave lasting effects, such as strokes on a canvas.
  • Admitted failures on basic physics, such as glass shattering, and on state changes like food being eaten.

Sora is a text-to-video model: it is conditioned on a prompt at the start and then generates a whole clip. Its claims about simulation were influential and contested in equal measure, and they set up the question the rest of this part (and the evaluation part) tries to answer: does visual plausibility imply a usable model of the world?

Let \(x_t\) be the frame at step \(t\), \(a_t\) the action applied after it and \(c\) a prompt. A text-to-video model such as Sora (OpenAI 2024) learns a distribution over a whole clip, \(p_\theta(x_{1:T} \mid c)\), and samples every frame jointly. In Sora's recipe an encoder maps the clip to a latent \(z = E(x_{1:T})\), the latent is cut into spacetime patches of size \(p_t \times p \times p\), and a diffusion transformer is trained to remove noise from all patches at once:

\[ \mathcal{L}_{\text{clip}}(\theta) = \mathbb{E}_{z,\,\sigma,\,\epsilon}\, \big\lVert \epsilon - \epsilon_\theta(z + \sigma \epsilon,\ \sigma,\ c) \big\rVert^2, \qquad N = \frac{T}{p_t} \cdot \frac{H}{p} \cdot \frac{W}{p} \ \text{patches}. \]

Full attention over \(N\) patches costs \(O(N^2)\) per denoising step, which bounds clip length, and nothing in the objective refers to an action. An interactive simulator instead learns a conditional one-step distribution and composes it at run time:

\[ p_\theta(x_{t+1} \mid x_{t-W+1:t},\ a_t), \]

with \(W\) the context window in frames. The three properties that separate a simulator from a clip generator become statements about this object:

  • Control: the predictive distribution depends on \(a_t\). One measure is the expected change in the prediction when the action is replaced by another, for example a divergence \(D\big(p_\theta(\cdot \mid h_t, a) \,\Vert\, p_\theta(\cdot \mid h_t, a')\big)\) averaged over histories \(h_t\).
  • Memory: frames generated at a revisited camera pose agree with frames generated at that pose earlier, even when the earlier frames are older than \(W\) steps. A pure window model has no access to them, so memory needs either a larger \(W\) or a separate store.
  • Stability: the error \(e(k)\) between generated and reference frames after \(k\) generated steps grows slowly in \(k\).

Two quantities set the engineering envelope. At frame rate \(f\) the memory span of the window is \(W/f\) seconds, and real-time operation requires the time to produce one frame, \(\tau\), to satisfy \(\tau \le 1/f\): 50 ms at GameNGen's 20 frames per second (Valevski et al. 2024) and 41.7 ms at Genie 3's 24 (DeepMind 2025).

In code, an interactive simulator is a stateful object with two operations: reset, which loads real frames into the context, and step, which takes one action and returns one frame. The context is a fixed-length queue in which appending a new frame drops the oldest one. The strengths and the failure modes of these models live in that one data structure. The returned frame is appended to the context, so every prediction becomes an input to the next (the source of drift), and the queue length fixes how far back the model can see (the source of forgetting).

The sketch wraps any predictor in that interface. A toy predictor that shifts the last frame by the action stands in for a learned dynamics model, so the bookkeeping can be tested on its own; the last loop prints the per-frame time budget and the span of a 16-frame window at the frame rates reported for Genie, GameNGen and Genie 3.

# Interactive world-simulator interface: a rolling context of W frames, one action per step.
from collections import deque
import numpy as np

class FrameSimulator:
    """Holds the last W frames; step(action) predicts the next frame and appends it."""
    def __init__(self, predict_fn, window=16, fps=10):
        self.predict_fn = predict_fn          # (context[W,H,W,3], action) -> frame[H,W,3]
        self.window, self.fps = window, fps
        self.context = deque(maxlen=window)   # oldest frame drops out automatically

    def reset(self, frames):                  # frames: list of [H,W,3] arrays in [0,1]
        self.context.clear()
        for f in frames[-self.window:]:
            self.context.append(f)

    def step(self, action):
        nxt = self.predict_fn(np.stack(self.context), action)
        self.context.append(nxt)              # the prediction becomes context (feedback)
        return nxt

    def memory_seconds(self):
        return self.window / self.fps         # how far back the model can "see"

def toy_predict(ctx, dx):                     # stand-in for a learned dynamics model
    return np.roll(ctx[-1], dx, axis=1)

sim = FrameSimulator(toy_predict, window=16, fps=10)
sim.reset([np.zeros((64, 64, 3)) for _ in range(20)])
for a in [1, 1, -1] * 10:
    frame = sim.step(a)
assert frame.shape == (64, 64, 3) and len(sim.context) == 16
for name, fps in [("Genie", 1), ("GameNGen", 20), ("Genie 3", 24)]:
    print(f"{name:9s} {fps:2d} fps: budget {1000/fps:7.1f} ms/frame, 16-frame window = {16/fps:5.2f} s")

The script prints a budget of 1,000 ms per frame and a 16-second window at 1 frame per second, 50 ms and 0.8 s at 20 frames per second, and 41.7 ms and 0.67 s at 24 frames per second. The same window holds less time as the frame rate rises, so a real-time model needs either a longer window or a separate memory to remember as much as a slow one. A useful debugging habit follows from the interface: log the context length and the age of the oldest frame at every step, because many consistency bugs are frames that have fallen out of the queue.

The two kinds of model are served differently. A text-to-video model such as Sora runs as a batch job: a request produces one clip, latency of tens of seconds or minutes is acceptable, and capacity is planned in clips per hour. An interactive simulator runs as a streaming session: it holds per-session state (the context frames and their attention cache) on an accelerator for as long as the user plays, must meet a deadline on every frame, and capacity is planned in concurrent sessions per accelerator.

A simulator in production therefore carries two kinds of objectives that are gated together, because improving one often degrades the other.

ObjectiveTypical metricWhat a regression looks like
Real timeSustained frames per second; p99 frame timeStutter, input lag
Short-horizon fidelityPSNR or LPIPS at about 1 sTokenizer or decoder artifacts
Long-horizon fidelityPSNR at 10 s and beyond; FVD on long clipsDrift, blur, color shift
MemoryRevisit consistency at a repeated camera poseRooms that change on return
ControlChange in output when actions are swappedA simulator that plays back a video

Table. Objectives for an interactive simulator release. More context improves memory but costs frame rate; more denoising steps improve single frames but cost latency; training on short clips can improve 1-second scores while worsening 10-second ones.

The 2025–2026 systems show how these trade-offs surface as product decisions. Genie 3 reports 720p at 24 frames per second with consistency over a few minutes (DeepMind 2025), and Project Genie (Google 2026) caps generations at 60 seconds, a limit that bounds both serving cost per session and exposure to drift. Matrix-Game 2.0 (Skywork AI 2025) reports 25 frames per second from few-step autoregressive diffusion distilled from a slower model, the usual route to real time. Runway's GWM-1 (Runway 2025) separates explorable worlds, avatars and robotics into separately post-trained variants rather than one model. The common failure in evaluation is to judge an interactive model with clip-level metrics alone: FVD on generated clips says nothing about whether the frames depend on the actions.

Autoregressive Frames and Action Conditioning

Interactive simulators generate one frame (or a short chunk) at a time, conditioned on the previous frames and the user's latest input, and feed each new frame back as context. This is the same next-token structure as a language model, with frames for tokens and controller input as part of the prompt at every step. The canonical demonstrations used games, because games come with clean action labels and unlimited data:

  • GameNGen. Valevski et al. (2024) first trained an RL agent to play DOOM and recorded its sessions, then trained a diffusion model to predict the next frame from past frames and actions. It runs at about 20 frames per second on a single TPU. Human raters distinguished short real and simulated clips only slightly better than chance, and the paper attributes long-run stability to adding noise to context frames during training.
  • Oasis. Decart and Etched released a real-time playable Minecraft-like world model in October 2024, generated frame by frame with no game engine, reported at a continuous 20 frames per second (Tom's Hardware 2024).
  • DIAMOND's CS:GO model (Alonso et al. 2024) and open models such as Matrix-Game 2.0 (2025), which describes itself as an open-source, real-time, streaming interactive world model, pushed the same recipe toward richer 3D games.

Formally, an action-conditioned frame model factorizes a rollout as

\[ p(x_{t+1:T} \mid x_{\le t}, a_{t:T-1}) = \prod_{k=t}^{T-1} p_\theta(x_{k+1} \mid x_{k-W+1:k},\, a_k), \]

where \(W\) is the context window in frames. Two consequences follow from this one line: the model can only remember what fits in \(W\) (or in a separate memory), and every generated frame becomes an input to the next prediction, so errors feed back into the context. Those are the two root causes of the consistency problems discussed below.

Given real frames up to step \(t\) and actions \(a_{t:T-1}\), an action-conditioned frame model factorizes the generated future into one-step terms,

\[ p(x_{t+1:T} \mid x_{\le t}, a_{t:T-1}) = \prod_{k=t}^{T-1} p_\theta(x_{k+1} \mid x_{k-W+1:k},\, a_k), \]

with \(W\) the context window. At generation time each sampled \(\hat{x}_{k+1}\) joins the conditioning set of the next factor.

Training objective. With a discrete tokenizer each frame is a grid of \(N\) tokens \(z_k^{1:N}\) from a vocabulary of size \(V\), and the model is trained by maximum likelihood with teacher forcing, meaning the context is always the real past:

\[ \mathcal{L}_{\text{tok}}(\theta) = -\sum_{k} \sum_{n=1}^{N} \log p_\theta\big(z_{k+1}^{n} \mid z_{k-W+1:k},\, a_k\big). \]

With a diffusion dynamics model (GameNGen, Valevski et al. 2024; DIAMOND, Alonso et al. 2024) the per-step term is a denoising loss: the next frame's latent \(z_{k+1}\) is corrupted to \(z_{k+1} + \sigma\epsilon\) and the network predicts the clean latent from the noisy one, the context and the action,

\[ \mathcal{L}_{\text{diff}}(\theta) = \mathbb{E}_{k,\,\sigma,\,\epsilon}\, \big\lVert D_\theta(z_{k+1} + \sigma\epsilon;\ \sigma,\ z_{k-W+1:k},\ a_k) - z_{k+1} \big\rVert^2 . \]

In both cases the action enters as an extra embedding added to, or attended by, the context tokens. If the data never shows an action changing the outcome, the minimizer ignores it.

Cost per frame. A transformer with \(P\) parameters spends about \(2P\) floating-point operations per token in its dense layers, plus about \(4 L d\, C\) for attention over \(C\) context tokens with \(L\) layers of width \(d\). If the \(N\) tokens of a frame are predicted in parallel and refined over \(S\) passes (MaskGIT-style decoding, Chang et al. 2022, or \(S\) denoising steps),

\[ F_{\text{frame}} \approx S \cdot N \cdot (2P + 4 L d\, C), \qquad C = W N, \qquad M_{\text{KV}} = 2 L d\, C\, b \ \text{bytes}, \]

where \(M_{\text{KV}}\) is the key-value cache at \(b\) bytes per number. Doubling \(W\) doubles the attention term and the cache. Decoding tokens one at a time would instead read all weights \(N\) times per frame rather than \(S\) times, which is why real-time systems predict a frame's tokens jointly and cut \(S\) by distillation.

The implementation has two parts worth testing separately: the tensor bookkeeping (frames to tokens, context window, per-frame cost) and the rollout loop (teacher-forced versus autoregressive). The first script turns frames into patch tokens with a reshape and transpose, checks the shapes, and evaluates the cost model for an illustrative 1.2-billion-parameter transformer (24 layers of width 2,048, 256 tokens per frame, 16 context frames, 8 parallel refinement passes).

# Frames -> patch tokens, and the per-frame compute/memory budget of the 1.2B transformer.
import numpy as np

def patchify(frames, p=16):
    """frames [T,H,W,C] -> tokens [T, (H/p)*(W/p), p*p*C] (one vector per 16x16 patch)."""
    T, H, W, C = frames.shape
    assert H % p == 0 and W % p == 0
    x = frames.reshape(T, H // p, p, W // p, p, C).transpose(0, 1, 3, 2, 4, 5)
    return x.reshape(T, (H // p) * (W // p), p * p * C)

frames = np.random.rand(16, 256, 256, 3).astype(np.float32)   # 16-frame context
tok = patchify(frames)
assert tok.shape == (16, 256, 768)            # 256 tokens per frame, 4,096 in the context
# the first patch of frame 0 is exactly the top-left 16x16 block
assert np.allclose(tok[0, 0].reshape(16, 16, 3), frames[0, :16, :16])

def frame_cost(params=1.2e9, layers=24, d=2048, tokens_per_frame=256,
               ctx_frames=16, steps_per_frame=8, bytes_per=2):
    """Assumed shape: 24 layers x d=2048 (12*L*d^2 ~ 1.2B); parallel (MaskGIT-style) decoding."""
    ctx = tokens_per_frame * ctx_frames
    dense = 2 * params * tokens_per_frame                  # matmul FLOPs for one pass
    attn = 4 * layers * d * ctx * tokens_per_frame         # QK^T and AV over the context
    per_frame = steps_per_frame * (dense + attn)
    kv_bytes = 2 * layers * d * bytes_per * ctx            # K and V for every context token
    return per_frame, kv_bytes

flops, kv = frame_cost()                        # illustrative 1.2B model, 16-frame context
assert abs(12 * 2048**2 * 24 - 1.2e9) / 1.2e9 < 0.01      # the assumed shape matches 1.2B
print(f"{flops/1e12:.2f} TFLOP/frame -> {24*flops/1e12:.0f} TFLOP/s at 24 fps; KV cache {kv/1e9:.2f} GB")
f32, kv32 = frame_cost(ctx_frames=32)
print(f"32-frame context: {f32/flops:.2f}x FLOPs per frame, KV cache {kv32/1e9:.2f} GB")
seq = 256 * 24 * 1.2e9 * 2 / 1e12               # one full weight read per token, 256 tokens, 24 fps
print(f"token-by-token decoding at 24 fps would stream {seq:.1f} TB/s of weights")

It prints 6.56 TFLOP per frame (158 TFLOP/s at 24 frames per second) with a 0.81 GB cache; a 32-frame context costs 1.25 times as much per frame with a 1.61 GB cache; and token-by-token decoding at 24 frames per second would stream 14.7 TB/s of weights, beyond any single accelerator. The assertion on the first patch guards against the most common tokenizer bug, a transpose in the wrong order that scrambles patches while keeping shapes correct.

The second script isolates the effect of feeding predictions back. A 64-dimensional state stands in for a frame, the true dynamics are nearly orthogonal, and the learned model has a small error in its transition matrix. The two rollouts differ in one line: whether the next context entry is the real frame or the model's own prediction.

# Teacher forcing vs autoregressive rollout with an action-conditioned frame model.
# The "frame" is a 64-D state vector so the example runs in milliseconds.
import numpy as np
rng = np.random.default_rng(0)
D, A, W = 64, 6, 16                      # state size, action size, context window (frames)

Q, _ = np.linalg.qr(rng.normal(size=(D, D)))
A_true = 0.999 * Q                        # true dynamics: near-orthogonal, slightly contracting
B_true = rng.normal(scale=0.1, size=(D, A))

def true_step(x, a):
    return A_true @ x + B_true @ a

# an imperfect learned model: small error in the transition matrix (about 1% per entry scale)
A_hat = A_true + rng.normal(scale=0.01 / np.sqrt(D), size=(D, D))
def model_step(context, a):
    """context [W, D] (most recent last), a [A] -> predicted next state [D].
    Uses only the last frame here; a transformer would attend over all W."""
    assert context.shape[1] == D and context.shape[0] <= W
    return A_hat @ context[-1] + B_true @ a

T = 100                                   # 10 s at 10 fps
x0 = rng.normal(size=D)
acts = rng.normal(size=(T, A))
truth = [x0]
for t in range(T):
    truth.append(true_step(truth[-1], acts[t]))
truth = np.array(truth)

def rollout(teacher_forced):
    ctx = [truth[0]]
    preds = []
    for t in range(T):
        x_next = model_step(np.array(ctx[-W:]), acts[t])
        preds.append(x_next)
        ctx.append(truth[t + 1] if teacher_forced else x_next)   # the only difference
    return np.array(preds)

err_tf = np.linalg.norm(rollout(True) - truth[1:], axis=1)
err_ar = np.linalg.norm(rollout(False) - truth[1:], axis=1)
print(f"step 10: teacher-forced {err_tf[9]:.3f}  autoregressive {err_ar[9]:.3f}")
print(f"step 100: teacher-forced {err_tf[99]:.3f}  autoregressive {err_ar[99]:.3f}")
assert err_ar[99] > 5 * err_tf[99]        # feedback makes errors accumulate
assert abs(err_tf[99] - err_tf[9]) < 3 * err_tf[9]   # one-step error stays flat

At step 10 the errors are 0.091 (teacher-forced) and 0.222 (autoregressive); at step 100 they are 0.226 and 1.316, almost six times apart for the same model. Metrics should therefore always be reported in both modes, since teacher-forced evaluation hides drift entirely. When the autoregressive curve rises steeply, a quick check is to set every action to zero and compare rollouts: a model that ignores actions produces identical frames.

An interactive simulator must deliver every frame within \(1/f\) seconds while keeping enough context to stay consistent. Context length, refinement steps and model size compete for the same per-frame budget, and the budget is hard: a missed deadline is visible as stutter, and in policy evaluation it slows every experiment. GameNGen reports 20 frames per second on a single TPU (Valevski et al. 2024); Genie 3 reports 24 frames per second at 720p, about 41.7 ms per frame for the whole pipeline.

Where the time goes. Per-frame cost has a dense part independent of context and an attention part that grows linearly with context tokens, and the key-value cache grows linearly too. Requests to remember more therefore turn directly into lower frame rate and fewer concurrent sessions per accelerator. A per-stage timer (tokenizer encode, dynamics passes, decoder) and a plot of frame time against context length on a fixed prompt show which term dominates.

Design levers, in rough order of cost.

  • Few-step generation. Distilling a many-step diffusion model into a few-step causal student is the standard route to real time; Matrix-Game 2.0 reports 25 frames per second this way (Skywork AI 2025), and Self Forcing reports real-time streaming with sub-second latency on one GPU (Huang et al. 2025).
  • Rolling cache. Keeping a fixed-size key-value cache that evicts the oldest frames bounds memory per session for arbitrarily long play.
  • Retrieval memory instead of a longer window. WorldMem (Xiao et al. 2025) stores past frames with their camera poses and timestamps and retrieves the relevant ones when a view returns, adding a handful of frames rather than doubling the window.
  • Compressed or quantized context. Pooling older frames to fewer tokens, or storing the cache in 8 bits, trades a small fidelity risk for memory.

Failure modes and validation. Fewer steps can blur fine detail such as on-screen text, which GameNGen addressed by fine-tuning the decoder; retrieval can return the wrong frames silently; and a model that responds to actions in short tests can stop responding late in a session. A revisit benchmark (scripted camera paths that leave a location and return after 2, 5 and 10 seconds, scored by agreement between the two views of the same pose) run together with sustained frame rate and p99 frame time is the minimal release check, because it measures memory and serving cost against the same budget.

Genie and Latent Actions

Action labels are the bottleneck for training interactive models on the open internet, since almost no video comes with the controller inputs that produced it. Bruce et al. (2024) addressed this in Genie by inferring the actions. Genie has three components, all trained from video alone:

  • A spatiotemporal video tokenizer that compresses frames into discrete tokens.
  • A latent action model that looks at consecutive frames and explains the change between them with one of only 8 discrete latent actions. The tiny codebook forces the latent action to capture what is controllable (the character moving left or jumping) rather than everything that changed.
  • A dynamics model (a MaskGIT-style transformer) that predicts the next frame's tokens from past tokens and the latent action.

Trained on a filtered set of about 30,000 hours of 2D platformer gameplay, the roughly 11B-parameter model could turn a single image (including a sketch) into a playable world. At play time a human or agent simply picks one of the 8 latent actions. The paper was candid about limits: about one frame per second and only 16 frames of memory. The latent-action idea has a counterpart in control, where Schmidt & Jiang (2024) trained latent action policies from action-free video and then decoded them to real actions with a small labeled set.

Genie's components: video tokenizer, latent action model and dynamics model, with player actions replacing latent actions at play time. Frames x_1..t video, no labels Video tokenizer frames → tokens Dynamics model next-frame tokens Frame t+1 decoded Latent action model (training) Player picks action at play time, replaces ã_t frame tokens latent action ã_t (1 of 8) append the new frame and repeat (autoregressive)
Fig. Genie learns to be controllable from unlabeled video. During training a latent action model explains each frame-to-frame change with one of 8 codes, and the dynamics model learns to predict the next frame given that code. At play time the latent action model is dropped and the player's choice is fed in directly (dashed). (Adapted and redrawn from Bruce et al. 2024.)

Genie's successors traded the discrete-token pipeline for latent diffusion and pushed toward real-time 3D worlds:

  • Genie 2 (DeepMind, December 2024) is an autoregressive latent diffusion model that turns one image into a playable 3D world with keyboard and mouse control. DeepMind reported worlds staying coherent for up to about a minute, with most examples lasting 10–20 seconds, memory for parts of the scene that leave and re-enter view, and a SIMA agent following instructions inside the generated worlds.
  • Genie 3 (DeepMind, August 2025) runs in real time at 720p and 24 frames per second, keeps environments consistent for a few minutes with visual memory reaching back about a minute, and supports "promptable world events" (text that changes weather or adds objects mid-session). DeepMind listed its limits: a constrained action space, weak multi-agent interaction, imperfect geographic accuracy and sessions of minutes rather than hours.
  • Project Genie (Google, January 2026) put Genie 3 in front of paying users as an experimental prototype for creating and exploring worlds, with generations capped at 60 seconds.
  • Genie 4 (Google, October 27, 2026) adds native, generated audio (ambient sound, music and dialogue) and natural-language steering of the scene in real time, and leans on Gemini models for realism and continuity. At the time of writing it is with trusted testers; the announcement gives no resolution or consistency figures, so independent assessment is not yet possible.

Genie's (Bruce et al. 2024) latent action model is a vector-quantized encoder. An encoder \(e_\phi\) sees the past frames and the next frame and outputs a continuous vector \(u_t = e_\phi(x_{\le t}, x_{t+1})\), which is snapped to the nearest of \(|A|\) codebook vectors \(\{c_1, \dots, c_{|A|}\}\):

\[ \tilde{a}_t = \arg\min_{j} \lVert u_t - c_j \rVert_2, \qquad |A| = 8 \text{ in Genie}. \]

A decoder must reconstruct \(x_{t+1}\) from \(x_{\le t}\) and \(c_{\tilde a_t}\) alone. The VQ-VAE objective of van den Oord et al. (2017) combines three terms:

\[ \mathcal{L}_{\text{LAM}} = \big\lVert x_{t+1} - \hat{x}_{t+1}(x_{\le t}, c_{\tilde a_t}) \big\rVert^2 + \big\lVert \mathrm{sg}[u_t] - c_{\tilde a_t} \big\rVert^2 + \beta\, \big\lVert u_t - \mathrm{sg}[c_{\tilde a_t}] \big\rVert^2, \]

where \(\mathrm{sg}[\cdot]\) stops gradients, the second term moves codes toward encoder outputs and the commitment term (weight \(\beta\)) keeps encoder outputs near their code. Gradients cross the \(\arg\min\) by the straight-through estimator, which copies the gradient of the quantized vector to \(u_t\).

Why 8 codes force controllability. The code carries at most \(\log_2 |A| = 3\) bits about the next frame. A frame of \(N\) tokens from a vocabulary of size \(V\) carries up to \(N \log_2 V\) bits, thousands for a typical tokenizer. The reconstruction loss is minimized by spending the 3 bits on the most predictable, recurring component of the change, which in a platformer is the character's movement; the background and other agents must be predicted from context.

Measuring control. Genie scores controllability with \(\Delta_t\text{PSNR}\): generate \(t\) frames with latent actions inferred from a real video, generate again with random latent actions, and compare both to the real frame,

\[ \Delta_t \text{PSNR} = \text{PSNR}(x_t, \hat{x}_t) - \text{PSNR}(x_t, \hat{x}'_t), \qquad \text{PSNR} = 10 \log_{10} \frac{\text{MAX}^2}{\text{MSE}} . \]

A larger gap means the actions steer the output more; the paper reports it at \(t = 4\).

Speed. With MaskGIT decoding the time per frame is roughly \(\tau \approx S \cdot \tau_{\text{pass}}\) for \(S\) parallel passes, so a model with many passes over a large network runs near 1 frame per second, while 24 frames per second leaves 41.7 ms for everything. Mapping to real actions. When real controls are needed, a small labeled set \(\{(\tilde a_t, a_t)\}\) suffices to fit \(a_t \approx g(\tilde a_t, x_t)\), as in Schmidt and Jiang (2024): the unlabeled video teaches the dynamics, and the labels only map between two small action spaces.

The script implements a latent action model on a toy world in which the right answer is known, so the learned codes can be checked against hidden labels. Each 32×32 frame contains a 3×3 bright sprite on a flickering background. Between frames the sprite moves by one of 8 hidden displacements (including standing still), while the background changes randomly and stands in for everything that is not controllable. The labels are used only for evaluation.

The components map onto Genie's. encode is the latent action encoder: it looks at two frames and returns a 2-D summary of the change (here the shift of the sprite's centroid; in Genie a transformer over raw pixels). vq_fit is the codebook update of the vector-quantization bottleneck, implemented as k-means, which is what the codebook and commitment terms converge to for a fixed encoder; it re-seeds any code that receives no inputs, a standard guard against dead codes. dynamics stands in for the dynamics model and moves the sprite by the chosen code's vector.

# A toy latent action model (LAM): infer one of K=8 discrete actions from frame pairs, no labels.
import numpy as np
rng = np.random.default_rng(1)
S, K = 32, 8                                   # frame size SxS, codebook size
MOVES = [(0, 0), (0, -2), (0, 2), (-2, 0), (2, 0), (-2, -2), (-2, 2), (2, 2)]  # true (hidden) actions

def render(pos):
    f = rng.uniform(0, 0.2, size=(S, S))       # flickering background = uncontrollable change
    r, c = pos
    f[r:r + 3, c:c + 3] = 1.0                  # the controllable sprite
    return f

def make_video(n):
    pos, frames, labels = np.array([14, 14]), [], []
    frames.append(render(pos))
    for _ in range(n):
        ok = [k for k in range(K) if 0 <= pos[0] + MOVES[k][0] <= S - 3 and 0 <= pos[1] + MOVES[k][1] <= S - 3]
        k = rng.choice(ok)                       # only moves that stay inside the frame
        pos = pos + MOVES[k]
        frames.append(render(pos)); labels.append(k)
    return np.array(frames), np.array(labels)

def encode(f0, f1):
    """LAM encoder: summarize the change between two frames as a 2-D vector
    (sprite centroid shift). A real LAM is a transformer over raw pixels."""
    def centroid(f):
        m = f > 0.5
        rr, cc = np.nonzero(m)
        return np.array([rr.mean(), cc.mean()])
    return centroid(f1) - centroid(f0)

def vq_fit(z, K, iters=50):
    """k-means = the codebook update of a VQ bottleneck; returns K code vectors."""
    code = z[rng.choice(len(z), K, replace=False)]
    for _ in range(iters):
        idx = np.argmin(((z[:, None] - code[None]) ** 2).sum(-1), axis=1)
        for k in range(K):
            if np.any(idx == k):
                code[k] = z[idx == k].mean(0)
            else:                               # dead code: re-seed on a random input
                code[k] = z[rng.integers(len(z))]
    return code

frames, labels = make_video(4000)
z = np.array([encode(frames[t], frames[t + 1]) for t in range(len(labels))])
fits = [vq_fit(z, K) for _ in range(5)]        # restarts: keep the lowest-distortion codebook
codebook = min(fits, key=lambda c: ((z[:, None] - c[None]) ** 2).sum(-1).min(1).sum())
latent = np.argmin(((z[:, None] - codebook[None]) ** 2).sum(-1), axis=1)   # [N] in 0..7

# purity: how well each latent code corresponds to one true action (labels used ONLY to evaluate)
purity = sum(np.bincount(labels[latent == k]).max() for k in range(K) if np.any(latent == k)) / len(labels)
usage = np.bincount(latent, minlength=K) / len(latent)
entropy_bits = -(usage[usage > 0] * np.log2(usage[usage > 0])).sum()
print(f"purity {purity:.3f}, code-usage entropy {entropy_bits:.2f} of {np.log2(K):.0f} bits")
assert purity > 0.9 and entropy_bits > 2.7

# controllability, Genie-style Delta-PSNR: dynamics driven by inferred vs random latent actions
def psnr(a, b):
    return 10 * np.log10(1.0 / np.mean((a - b) ** 2))
def dynamics(f0, code):                         # "dynamics model": move the sprite by the code vector
    shift = np.round(codebook[code]).astype(int)
    return np.roll(np.roll(np.where(f0 > 0.5, 1.0, 0.1), shift[0], 0), shift[1], 1)
idx = rng.choice(len(labels) - 1, 300, replace=False)
p_inf = np.mean([psnr(frames[t + 1], dynamics(frames[t], latent[t])) for t in idx])
p_rnd = np.mean([psnr(frames[t + 1], dynamics(frames[t], rng.integers(K))) for t in idx])
print(f"PSNR inferred {p_inf:.2f} dB, random {p_rnd:.2f} dB, Delta-PSNR {p_inf - p_rnd:.2f} dB")
assert p_inf - p_rnd > 1.0                      # the latent actions actually steer the model

It prints a purity of 1.000 (every code corresponds to one hidden action), a code-usage entropy of 2.93 of 3 bits (all 8 codes in use), and a controllability gap of 5.86 dB: 24.81 dB with inferred actions against 18.94 dB with random codes. Two details in the code were needed to get there: sampling only moves that keep the sprite inside the frame, since border collisions turn real moves into no-ops, and keeping the best of five k-means restarts.

The same three numbers apply to real latent action models. Code-usage entropy should be close to \(\log_2 |A|\); a value well below means dead codes and fewer actions than intended. Purity against a small labeled subset shows whether codes are consistent. \(\Delta\)PSNR must be clearly positive; near zero means the dynamics model ignores the action and predicts the average future. All three are cheap enough to compute on every checkpoint.

Latent-action training at scale fails quietly. The loss can fall steadily while the action channel carries almost nothing, because a strong dynamics model can predict the average next frame well without any action. The result looks good in passive playback and is unresponsive when played.

Root causes. Codebook collapse: only a few codes receive inputs and the rest never update, which shrinks the action space. Leakage: the dynamics model finds the information it needs in the context (motion blur in the last frame already reveals the direction of movement), so the latent action becomes redundant even when all codes are in use.

Diagnosis. Per-code usage plotted over training reveals collapse as codes whose usage falls to zero and stays there. \(\Delta\)PSNR computed at several context lengths reveals leakage: if it rises when the context shrinks, the model is reading the action from the context. A grid that renders the same context under each of the 8 codes shows, at a glance, whether the outputs differ systematically.

Remedies. Re-seed dead codes on recent encoder outputs and lower the commitment weight so the encoder can move between codes. Feed the latent action model raw pixels rather than tokens; the Genie paper's ablation (Bruce et al. 2024) found pixel input gave better controllability. Train the latent action model with a short decoder-side context, so the code is necessary for prediction, then train the full-context dynamics model with frozen codes. When real controls are needed, fit a small latent-to-real mapping and track how often it is ambiguous. Re-seeding can make codes unstable between checkpoints, which breaks a learned mapping, so codebooks are usually frozen before the mapping is fitted.

Serving. The latent action model is discarded at play time, so its cost falls only on training. The binding constraint is decoding: Genie's discrete-token pipeline ran at about one frame per second, and its successors moved to latent diffusion; Genie 3's 24 frames per second (DeepMind 2025) requires few-step generation, so any remedy that adds passes at inference is ruled out. The same idea now trains control models at scale: Dreamer 4 (Hafner et al. 2025) learns most of its world model from unlabeled video and uses a smaller amount of action-labeled data to ground the actions.

Drift and Long-Horizon Consistency

The central technical problem of interactive simulators is that quality decays the longer they run. Two mechanisms are responsible: exposure bias, in which the model is trained on real context frames but must run on its own imperfect outputs, so small artifacts are fed back and amplified; and limited memory, in which anything that falls outside the context window can be re-imagined differently when the camera returns. The fixes so far attack each mechanism directly:

  • Noise on the context. GameNGen corrupts context frames with noise during training and tells the model the noise level, so it learns to repair rather than copy small errors (Valevski et al. 2024).
  • Per-frame noise levels. Chen et al. (2024) proposed diffusion forcing, which trains a causal model with independent noise levels per token, so the same network can denoise the next frame while treating past frames as partially uncertain; this stabilized long rollouts and enabled guidance over a whole future.
  • Train on your own rollouts. Huang et al. (2025) introduced Self Forcing, which generates the context autoregressively during training and applies a video-level loss, closing the train–test gap that causes drift.
  • Explicit memory and 3D state. Long-term spatial memory (Genie 2 and 3) and, at the extreme, generating a persistent 3D scene instead of frames: World Labs' Marble (November 2025) produces downloadable, editable 3D environments from text, images or video, which removes drift by construction at the cost of dynamics.

The trade-off is between fidelity to interaction and permanence. Frame-by-frame simulators respond to anything but forget; 3D-first generators never forget but are mostly static. Hybrid designs that keep an explicit scene state and use a generative model for dynamics are an active direction rather than a solved one.

Error recursion. Let \(e_k = \hat{x}_k - x_k\) be the error after \(k\) autoregressive steps, measured in some feature space. Linearizing the model around the true trajectory, the next error is the propagated old error plus a new one-step error:

\[ e_{k+1} \approx J_k\, e_k + \varepsilon_k, \]

where \(J_k\) is the Jacobian of the prediction with respect to its context and \(\varepsilon_k\) the error the model would make from perfect context. With \(\lVert J_k \rVert \approx \rho\) and \(\lVert \varepsilon_k \rVert \approx \varepsilon\), the error grows like \(\varepsilon(\rho^k - 1)/(\rho - 1)\): linearly when \(\rho = 1\), geometrically when \(\rho > 1\), and to a plateau \(\varepsilon/(1-\rho)\) when \(\rho < 1\). Teacher forcing trains \(\varepsilon\) only. It puts no pressure on \(J\) in directions the real data never visits, which is exactly where the model's own errors push the context (exposure bias).

Drift in decibels. For pixels in \([0,1]\), \(\text{PSNR} = -10 \log_{10} \text{MSE}\), so a loss of \(\Delta\) dB is a factor \(10^{\Delta/10}\) in mean squared error, and geometric growth of MSE by \(g\) per frame is a straight line falling \(10 \log_{10} g\) dB per frame. The slope in dB per frame is therefore a direct estimate of \(\rho\)'s effect.

Why noise on the context helps. Take a linear model \(\hat{x}_{k+1} = M x_k\), true dynamics \(A\), real frames with covariance \(\Sigma\) and Gaussian noise of variance \(\sigma^2\) added to the context in training. The least-squares solution is

\[ M^\star = A\, \Sigma\, (\Sigma + \sigma^2 I)^{-1}. \]

Along directions where real data varies (eigenvalue \(\lambda \gg \sigma^2\)) \(M^\star \approx A\); along directions real frames never occupy (\(\lambda \approx 0\)) \(M^\star \approx 0\). The trained model removes off-manifold deviations instead of passing them on, making \(\rho < 1\) for exactly the errors that cause drift, at the price of shrinking on-manifold dynamics by \(\lambda/(\lambda + \sigma^2)\).

Diffusion forcing and Self Forcing. Diffusion forcing (Chen et al. 2024) samples an independent noise level \(k_t\) for every frame in training and minimizes \(\mathbb{E}\,\lVert \epsilon_t - \epsilon_\theta(z_{1:T}^{k_{1:T}}, k_{1:T})_t \rVert^2\), so one causal network learns to predict from any mixture of clean and noisy context. Self Forcing (Huang et al. 2025) removes the mismatch at its source: the context is sampled from the model itself, \(\hat{x}_{1:T} \sim p_\theta\), and a video-level loss (such as distribution-matching distillation) is applied to the whole generated rollout, so training and inference see the same inputs.

FVD. The Fréchet Video Distance (Unterthiner et al. 2018) embeds real and generated clips with a pretrained video network, fits Gaussians \((\mu_r, \Sigma_r)\) and \((\mu_g, \Sigma_g)\) to the features, and computes \(\lVert \mu_r - \mu_g \rVert^2 + \operatorname{tr}\big(\Sigma_r + \Sigma_g - 2(\Sigma_r \Sigma_g)^{1/2}\big)\). The first term detects shifted content, the second missing variety or excess noise; the ratio of FVD on long clips to FVD on short clips summarizes how much worse long rollouts are as a population.

Drift is measured and fought with three small tools: a conversion between PSNR and squared error that turns two measurements into a growth rate and a usable horizon; the Fréchet distance computed inside FVD; and a demonstration of why noise on the context stabilizes rollouts. The first script covers the first two. The example horizon uses two hypothetical measurements of a 10 frames-per-second simulator (28 dB at frame 10, 21 dB at frame 100) and a 24 dB requirement. The Fréchet tests check that identical sets give zero, that a mean shift of 0.5 in 16 dimensions gives \(16 \times 0.25 = 4\), and that collapsing variance (the statistical signature of blur) is penalized too.

# Drift diagnostics: PSNR-vs-horizon model and a Frechet distance (the core of FVD).
import numpy as np
from scipy.linalg import sqrtm

def mse_from_psnr(db, peak=1.0):
    return peak ** 2 / 10 ** (db / 10)

def usable_horizon(db_a, k_a, db_b, k_b, need_db):
    """Two PSNR measurements of one rollout -> per-frame MSE growth and the last frame
    meeting need_db. Geometric MSE growth is a straight line in dB."""
    growth = (mse_from_psnr(db_b) / mse_from_psnr(db_a)) ** (1 / (k_b - k_a))
    slope = (db_a - db_b) / (k_b - k_a)                       # dB lost per frame
    last_ok = next(k for k in range(k_a, 10**6) if db_a - slope * (k - k_a) < need_db) - 1
    return growth, slope, last_ok

# hypothetical measurements of a 10 fps simulator: 28 dB at frame 10, 21 dB at frame 100
g, slope, last = usable_horizon(28, 10, 21, 100, need_db=24)
print(f"MSE x{g:.4f} per frame, {slope:.3f} dB/frame, >= 24 dB through frame {last} ({last/10:.1f} s)")
assert last == 61

def frechet(mu1, s1, mu2, s2):
    """Frechet distance between Gaussians N(mu1,s1), N(mu2,s2). FVD applies this to
    I3D features of real and generated clips."""
    covmean = sqrtm(s1 @ s2).real
    return float(((mu1 - mu2) ** 2).sum() + np.trace(s1 + s2 - 2 * covmean))

rng = np.random.default_rng(0)
real = rng.normal(size=(5000, 16))
assert frechet(real.mean(0), np.cov(real.T), real.mean(0), np.cov(real.T)) < 1e-6
shifted = real + 0.5                            # mean shift of 0.5 in 16 dims -> 16*0.25 = 4
fd = frechet(real.mean(0), np.cov(real.T), shifted.mean(0), np.cov(shifted.T))
print(f"Frechet distance after mean shift: {fd:.3f}")
assert abs(fd - 4.0) < 1e-6
blurred = real * 0.5                            # collapsed variety (blur): trace term grows
fd2 = frechet(real.mean(0), np.cov(real.T), blurred.mean(0), np.cov(blurred.T))
print(f"Frechet distance after variance collapse: {fd2:.2f}")   # ~ 16 * (1 - 0.5)^2 = 4

It prints MSE growth of 1.8% per frame (0.078 dB per frame), a horizon at 24 dB ending at frame 61 (6.1 s), and a Fréchet distance of 4.000 for both the mean shift and the halved standard deviations: FVD alone cannot say whether a model drifted in content or lost detail.

The second script tests the claim that noisy-context training makes a model remove its own errors. Real frames lie near a 4-dimensional subspace of a 16-dimensional space, with tiny jitter off the subspace whose true dynamics are unstable (gain 1.05). A clean least-squares fit learns that unstable gain; a fit with noise of standard deviation 0.05 on the context learns to suppress those directions. Each rollout step adds an artifact of size 0.01, standing in for the generator's imperfections.

# Why noise on the context stops drift: a linear "next-frame" model trained clean vs noisy.
import numpy as np
rng = np.random.default_rng(0)
D, r = 16, 4                                   # frames live near a 4-D subspace of R^16
U, _ = np.linalg.qr(rng.normal(size=(D, D)))
on, off = U[:, :r], U[:, r:]
R = np.linalg.qr(rng.normal(size=(r, r)))[0]   # on-manifold dynamics: a rotation
A_true = on @ R @ on.T + 1.05 * off @ off.T    # off-manifold directions are unstable (x1.05)

def sample(n):                                 # training frames: on-manifold + tiny jitter
    x = on @ rng.normal(size=(r, n)) + 1e-3 * off @ rng.normal(size=(D - r, n))
    return x, A_true @ x

def fit(X, Y, sigma):
    """Least squares M = argmin ||M (X + noise) - Y||^2, noise ~ N(0, sigma^2 I) on the context."""
    Xn = X + sigma * rng.normal(size=X.shape)
    return Y @ np.linalg.pinv(Xn)

X, Y = sample(20000)
M_clean, M_aug = fit(X, Y, 0.0), fit(X, Y, 0.05)

def rollout_err(M, steps=100, model_noise=0.01):
    x_true = on @ rng.normal(size=r)
    x_hat = x_true.copy()
    for _ in range(steps):
        x_true = A_true @ x_true
        x_hat = M @ x_hat + model_noise * rng.normal(size=D)   # each step adds a small artifact
    return np.linalg.norm(x_hat - x_true)

e_clean = np.mean([rollout_err(M_clean) for _ in range(50)])
e_aug = np.mean([rollout_err(M_aug) for _ in range(50)])
gain = lambda M: np.linalg.norm(off.T @ M @ off, 2)            # how much off-manifold error is kept
print(f"off-manifold gain: clean {gain(M_clean):.3f}, augmented {gain(M_aug):.3f}")
print(f"error after 100 steps: clean {e_clean:.3f}, augmented {e_aug:.3f}")
assert gain(M_aug) < 0.1 < 1.0 < gain(M_clean)
assert e_aug < 0.5 * e_clean

It prints an off-manifold gain of 1.050 for the clean model against 0.001 for the augmented one, and an error after 100 steps of 13.712 against 0.501. Part of the remaining error is the on-manifold shrinkage \(1/(1 + 0.05^2)\) per step, the bias side of the trade-off. Error should always be plotted against rollout step rather than averaged, since averages hide whether growth is linear or geometric, and the augmentation noise level belongs next to the drift curve in the logs: too little leaves the gain above one, too much blurs every frame.

Short-horizon metrics are the easiest to compute and to improve, and they predict long-horizon behavior poorly. A release process that gates only on 1-second quality will accept models that drift faster. In terms of the recursion \(e_{k+1} \approx J e_k + \varepsilon\), fine-tuning that sharpens single frames lowers \(\varepsilon\) but can raise the gain \(\rho\) if the model learns to copy fine detail from its context, including detail that is wrong. Users and downstream policies experience the long horizon.

Diagnosis. Four measurements separate the causes: PSNR against rollout step for baseline and candidate (crossing curves mean a lower \(\varepsilon\) with a higher \(\rho\)); the same curve under teacher forcing (flat teacher-forced error with rising autoregressive error points to exposure bias rather than capacity); a revisit test that returns to a pose after 2, 5 and 10 seconds (separating memory loss from accumulated error); and an action-swap test at long horizons, since drifting models often stop responding to actions.

RemedyTargetsTraining costInference costRisk
Noise on the context (GameNGen)Gain \(\rho\)NegligibleNoneSlight blur
Per-frame noise levels (diffusion forcing)Gain; flexible conditioningLowNoneSampling schedule to tune
Self ForcingTrain–test gapSequential rollouts in trainingNoneSlower training
Long self-rollouts (Self-Forcing++, Rolling Forcing)Horizons beyond training clipsHigher stillSmallTeacher sees only short windows
Pose-indexed memory (WorldMem)Revisit consistencyMemory moduleRetrieval per stepWrong retrievals
Persistent 3D scene (Marble)All drift, by constructionDifferent pipelineRenderingLittle dynamics

Table. Drift remedies, ordered from cheapest to most invasive.

The 2025 recipes go past the training clip length. Self-Forcing++ (Cui et al. 2025) rolls the student far beyond the teacher's roughly 5-second horizon, re-noises windows of its own long rollouts and lets the short-horizon teacher correct them, reporting videos up to 100 seconds and 255 seconds with a larger budget. Rolling Forcing (Liu et al. 2025) denoises a window of frames jointly at increasing noise levels and keeps the first frames as an attention anchor, reporting multi-minute streaming at about 16 frames per second on one GPU.

Validation. A remedy is supported when the slope in dB per frame falls, long-horizon PSNR and long-clip FVD improve, and 1-second quality stays within its gate; it is weakened if the improvement appears only under teacher forcing or if the ratio of long-clip to short-clip FVD stays high. Gating releases on both the 1-second and 10-second rows is what stops a sharper but faster-drifting model from shipping.

World Simulators for Robots and Cars

For robotics and driving, a world simulator is valuable as a source of training data and as a test bench for policies, so the emphasis shifts from realism to controllability by the right actions (steering, trajectories, robot commands) and coverage of rare events. Four efforts illustrate the range:

  • Wayve GAIA. Hu et al. (2023) built GAIA-1, a driving world model conditioned on video, text and actions (speed and curvature), with a 6.5B-parameter world model plus a video decoder, trained on London driving data and able to generate minutes of driving. GAIA-2 (2025) extended it to controllable multi-camera generation.
  • NVIDIA Cosmos. NVIDIA (2025) released a platform rather than a single model: a video curation pipeline, causal video tokenizers, pretrained diffusion and autoregressive world foundation models, post-training recipes for camera control, robot manipulation and driving, and guardrails, under an open model license.
  • Runway GWM-1. Runway (December 2025) announced an autoregressive, real-time general world model built on its Gen-4.5 video model, with separately post-trained variants for explorable worlds, conversational avatars and robotics (synthetic data and simulated policy evaluation). The announcement provides no independent benchmarks.
  • Dreamer 4 (Hafner et al. 2025) also reported training its world model on a robotics dataset, which hints that the control and simulator lines will share models.
Timeline of interactive and generative world models from 2018 to 2026, colored by family.
Fig. A timeline of the world models discussed in this book, by first public release. The pace after 2024 is the point: in under three years the field went from a 1-frame-per-second platformer model to real-time 720p worlds with audio. The axis is compressed before 2023. Dates are month-level and taken from each paper or announcement.
SystemConditioningGenerationReported consistency / speed
Sora (2024)Text, image, videoDiffusion transformer on spacetime patches, whole clipNot interactive
Genie (2024)Image + 8 latent actionsAutoregressive token transformer~1 fps; 16-frame memory
GameNGen (2024)DOOM controller actionsAutoregressive diffusion~20 fps on one TPU
Genie 2 (2024)Image + keyboard/mouseAutoregressive latent diffusionUp to ~1 minute; most 10–20 s
Genie 3 (2025)Text + navigation + promptable eventsReal-time autoregressive720p, 24 fps; a few minutes
GAIA-1 (2023)Video, text, speed and curvatureAutoregressive tokens + video diffusion decoderMinutes of driving
Marble (2025)Text, images, video, 3D layoutPersistent 3D environmentNo drift by construction; static
GWM-1 (2025)Camera, events, robot pose, speechAutoregressive, real timeVendor claims only

Table. Video and interactive world simulators. Consistency figures are what each developer reported, measured in different ways; treat them as orders of magnitude, not a ranking.

Used as a test bench, a simulator estimates a policy's success rate. Let policy \(\pi\) have real success probability \(p_\pi\). Each of \(n\) simulated episodes yields a judged outcome \(Y_i \in \{0,1\}\), and the estimate is \(\hat q_\pi = \frac{1}{n}\sum_i Y_i\). If simulator plus judge reproduce the real outcome with probability \(\alpha\) and flip it otherwise (a symmetric noise model, an assumption),

\[ q_\pi = \mathbb{E}[\hat q_\pi] = \alpha\, p_\pi + (1-\alpha)(1-p_\pi) = (1-\alpha) + (2\alpha - 1)\, p_\pi . \]

Rankings are preserved in expectation whenever \(\alpha > 0.5\), because \(q\) increases with \(p\), but real gaps shrink: a real difference \(\Delta p\) appears as \((2\alpha - 1)\Delta p\).

Sample size. For two policies with \(p_B > p_A\), the normal approximation gives

\[ P(\hat q_B > \hat q_A) \approx \Phi\!\left( \frac{q_B - q_A}{\sqrt{\big(q_A(1-q_A) + q_B(1-q_B)\big)/n}} \right), \qquad n = \frac{z^2 \big(q_A(1-q_A) + q_B(1-q_B)\big)}{(q_B - q_A)^2}, \]

with \(z = 1.2816\) for a 90% chance of the correct order. Accuracy enters squared through the gap, so raising \(\alpha\) from 0.7 to 0.9 cuts the required episodes about fourfold.

Example1X (1X 2025) states that with a 15-point real success gap a world model with 70% accuracy picks the better policy 90% of the time, without giving the episode count. Under the symmetric model with \(p_A = 0.50\), \(p_B = 0.65\), \(\alpha = 0.70\), the gap shrinks to \(0.4 \times 15 = 6\) points and \(n = 1.2816^2 \times (0.25 + 0.2464)/0.06^2 \approx 227\) episodes per policy; at \(\alpha = 0.90\), \(n \approx 56\). These counts are this book's calculation, not 1X's.

Agreement metrics. Over \(N\) policies with real rates \(r_i\) and simulated rates \(s_i\), Pearson correlation measures linear agreement, and the mean maximum rank violation weights ranking errors by how much they matter:

\[ \text{MMRV} = \frac{1}{N} \sum_{i=1}^{N} \max_{j}\ |r_i - r_j| \cdot \mathbb{1}\big[(s_i < s_j) \neq (r_i < r_j)\big]. \]

Zero means a perfect ranking. WorldEval (Li et al. 2025) reports an average MMRV of 0.044 and Pearson 0.942 across three real-robot tasks. The drift analysis adds a horizon limit: an outcome judged at time \(T\) inherits the rollout's quality at \(T\), which favors short, outcome-focused episodes.

The code turns those statistics into functions that can run on every simulator release. pearson and mmrv compare simulated and real success rates for a set of checkpoints; p_correct_ranking implements the normal approximation for two policies under the symmetric outcome-flip model and is used to choose the number of simulated episodes. The tests use five checkpoints with real success rates from 0.30 to 0.80, scored by one simulator that preserves their order and one that flatters the weakest checkpoint and punishes the best.

# Using a world simulator to rank robot or driving policies: agreement metrics and sample size.
import numpy as np
from scipy.stats import norm

def pearson(a, b):
    return float(np.corrcoef(a, b)[0, 1])

def mmrv(real, sim):
    """Mean Maximum Rank Violation (as used by SIMPLER and WorldEval): for each policy, the largest
    real-success gap to any policy the simulator orders the wrong way; averaged. 0 = perfect ranking."""
    real, sim = np.asarray(real), np.asarray(sim)
    n = len(real)
    worst = [max([abs(real[i] - real[j]) for j in range(n)
                  if (sim[i] < sim[j]) != (real[i] < real[j])] or [0.0]) for i in range(n)]
    return float(np.mean(worst))

real = [0.30, 0.45, 0.50, 0.65, 0.80]           # real-world success of five checkpoints
good = [0.25, 0.40, 0.52, 0.60, 0.85]           # simulator preserves the order
bad = [0.55, 0.40, 0.52, 0.60, 0.45]            # simulator flatters the weakest, punishes the best
print(f"good: r={pearson(real, good):.2f} MMRV={mmrv(real, good):.3f}")
print(f"bad:  r={pearson(real, bad):.2f} MMRV={mmrv(real, bad):.3f}")
assert mmrv(real, good) == 0.0 and mmrv(real, bad) > 0.1

def p_correct_ranking(p_a, p_b, judge_acc, n):
    """Chance that n simulated episodes per policy rank A < B correctly when each episode's
    simulated outcome is flipped with probability 1 - judge_acc (symmetric noise model)."""
    q = lambda p: judge_acc * p + (1 - judge_acc) * (1 - p)   # observed success rate
    qa, qb = q(p_a), q(p_b)
    sd = np.sqrt(qa * (1 - qa) / n + qb * (1 - qb) / n)
    return float(norm.cdf((qb - qa) / sd))

# a 15-point real gap seen through a 70%-accurate simulator shrinks to 0.4 * 15 = 6 points
n90 = next(n for n in range(1, 5000) if p_correct_ranking(0.50, 0.65, 0.70, n) >= 0.90)
print(f"episodes per policy for 90% correct ranking: {n90}")
assert 200 < n90 < 260
print(f"with a 90%-accurate simulator: "
      f"{next(n for n in range(1, 5000) if p_correct_ranking(0.50, 0.65, 0.90, n) >= 0.90)}")

It prints \(r = 0.99\) and MMRV 0.000 for the order-preserving simulator and \(r = -0.10\) with MMRV 0.320 for the flattering one, then 227 episodes per policy to rank a 50% and a 65% policy correctly 90% of the time through a 70%-accurate simulator, and 56 at 90% accuracy.

Two details matter. MMRV uses real gaps, not simulated ones, so misordering two nearly equal policies costs little while misordering very different ones costs a lot; this is what makes it more useful than rank correlation for deciding whether to trust a simulator. And the flip model treats errors as symmetric, whereas real simulators usually hallucinate success more often than failure, which shifts every \(q\) upward and compresses gaps further. When some episodes have labeled real outcomes, the two error rates should be estimated separately. When MMRV is high, printing the offending pairs and watching their simulated episodes often shows the same ending regardless of the actions.

A simulator used as a test bench is valuable only if decisions made with it match decisions made with real trials. When it is wrong it is wrong systematically: every comparison inherits the same bias, and the error surfaces when a promoted policy fails in the field. More episodes reduce variance but not that bias.

Root causes. Weak action conditioning (the simulator renders plausible futures that depend little on the actions, so bad policies still succeed); coverage gaps (a new policy drives the simulator into states absent from its data, where it drifts fastest and falls back on the most common ending, often a success); and judge error (a success classifier or vision-language judge misreads blurred frames).

Diagnosis. An action-swap test replays an episode with another episode's actions and compares final frames; near-identical endings mean the simulator ignores actions. A coverage score (distance of each episode's states and actions from the training data in an embedding) tests whether failures cluster in unfamiliar states. A judge audit, human labels on a sample of simulated episodes, estimates false-success and false-failure rates separately.

Remedies. Post-train on counterfactual pairs (the same start with different logged actions and real outcomes) so the model sees actions change endings; add failed episodes, which are scarce in logs but essential; route policies whose episodes score high on coverage distance to hardware instead of trusting the simulated rate; and recompute the effective accuracy and the episode count after every simulator update. Agreement is then checked on held-out checkpoints whose real rates were not used for tuning.

Systems. Cosmos (NVIDIA 2025) packages this workflow as a platform with post-training recipes for robot manipulation and driving, and GAIA-2 (Wayve 2025) adds multi-camera control for driving. Runway's GWM-1 (Runway 2025) offers a robotics variant for synthetic data and policy evaluation without independent benchmarks. Published agreement evidence remains small: WorldEval covers three tasks, and 1X reports a correlation between predicted and real success without a coefficient. Until larger studies exist, simulator rankings are best treated as a filter that decides which checkpoints earn a real trial, not a replacement for one.

Predicting in Representation Space

The predictive-representation school argues that a world model should predict the future in an abstract feature space, not in pixels, because most pixel-level detail is unpredictable and irrelevant to acting. Where a leaf lands or how a wave breaks cannot be predicted from the past and does not matter for picking up a cup, yet a pixel-reconstruction loss forces the model to spend capacity on exactly those details. Predicting embeddings lets the model ignore what it cannot know and concentrate on what it can.

LeCun (2022) laid out the program in a position paper on autonomous machine intelligence. It describes an agent built from a perception module, a world model, a cost module, a short-term memory and an actor, and makes three technical claims:

  • Energy-based, not probabilistic. Instead of assigning a normalized probability to every possible future, the model learns an energy \(E(x, y)\) that is low when \(y\) is a compatible continuation of \(x\). This sidesteps the need to model a full distribution over high-dimensional futures.
  • Joint-embedding predictive architecture (JEPA). Encode both the context \(x\) and the target \(y\), and train a predictor to map the context embedding (plus a latent variable \(z\) for what is uncertain) to the target embedding. The energy is the prediction error in that space.
  • Hierarchy and planning. Stack JEPAs at multiple time scales and plan by searching for actions whose predicted future minimizes the cost, which is model predictive control in latent space.
\[ E(x, y) = \min_{z} \; \big\| \, g_\psi\big(f_\theta(x), z\big) - \bar{f}(y) \, \big\|, \qquad \bar{f} = \mathrm{EMA}(f_\theta) \]

Here \(f_\theta\) is the context encoder, \(\bar{f}\) the target encoder (in practice an exponential moving average of \(f_\theta\) with no gradient), \(g_\psi\) the predictor and \(z\) a latent capturing information the context cannot determine. The obvious failure is collapse: if every input maps to the same embedding, the prediction error is zero. JEPA-style methods prevent it with an asymmetric design (predictor on one side, stop-gradient EMA target on the other) or with explicit variance and covariance regularizers.

Generative pixel prediction compared with joint-embedding prediction in representation space. Generative: predict pixels JEPA: predict embeddings context x encoder decoder → ŷ pixels target y raw pixels loss on every pixel ‖ŷ − y‖² context x encoder predictor → ŝ_y target y target enc. EMA, no grad embedding s_y loss in feature space ‖ŝ_y − s_y‖
Fig. Two ways to learn by prediction. A generative model (left) must reproduce every pixel of the target, including details it cannot predict. A JEPA (right) predicts the target's embedding from a slowly updated target encoder, so unpredictable detail can be discarded; the asymmetry (predictor on one side, gradient-free EMA encoder on the other) is what prevents collapse.

Write the past as \(x\) and the future as \(y\). A JEPA has a context encoder \(f_\theta\), a target encoder \(\bar f\) with parameters \(\bar\theta\), a predictor \(g_\psi\) and a latent variable \(z\) that carries whatever about \(y\) the context cannot determine. The energy proposed by LeCun (2022) is

\[ E(x, y) = \min_{z} \; \big\| \, g_\psi\big(f_\theta(x), z\big) - \bar{f}(y) \, \big\| . \]

Energy versus density. An energy defines a density through the Gibbs form \(p(y \mid x) = e^{-\beta E(x,y)} / Z(x)\) with \(Z(x) = \int e^{-\beta E(x,y')}\,dy'\). The normalizer integrates over every possible future frame and is intractable at video scale. JEPA training never computes it; it only lowers the energy of observed pairs. The minimum over \(z\) lets one context be compatible with several futures, each reaching low energy with its own value of \(z\).

Collapse. Lowering energy only on observed pairs admits a trivial minimizer: if \(f_\theta(x) = \bar f(y) = c\) for every input and \(g_\psi\) outputs \(c\), then \(E \equiv 0\) and the representation carries no information. Contrastive methods avoid this by also raising the energy of negative pairs, which needs many negatives in high dimension. JEPA-style methods use one of two non-contrastive devices.

EMA asymmetry. The target parameters receive no gradient and follow the context encoder,

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

an average over roughly \(1/(1-m)\) steps. I-JEPA starts at \(m = 0.996\), a window of 250 steps, and raises \(m\) linearly to 1 so that the target freezes as training ends. A predictor on the context side only, with a stop-gradient on the target side, is the device introduced by BYOL (Grill et al., 2020).

Explicit regularizers. For a batch of embeddings \(S \in \mathbb{R}^{N \times d}\) with per-dimension standard deviations \(\sigma_k\) and covariance \(C\), VICReg (Bardes et al., 2022) adds

\[ v(S) = \frac{1}{d}\sum_{k=1}^{d} \max\big(0,\ \gamma - \sigma_k\big), \qquad c(S) = \frac{1}{d}\sum_{k \ne l} C_{kl}^2 . \]

Complete collapse gives \(v = \gamma\); dimensional collapse, where information is packed into a few correlated directions, makes \(c\) large. Balestriero and LeCun (2025) argue that an isotropic Gaussian is the optimal embedding distribution for downstream prediction risk and propose SIGReg, which pushes the distribution of random one-dimensional projections of the embeddings toward \(\mathcal{N}(0,1)\). Their LeJEPA objective adds it to the prediction loss with one trade-off weight and needs no stop-gradient, teacher-student pair or momentum schedule.

Planning. With an action-conditioned predictor \(\hat s_{t+1} = g_\psi(s_t, a_t)\) and a cost \(c\) on embeddings, the actor solves \(\min_{a_{t:t+H-1}} \sum_{h=1}^{H} c(\hat s_{t+h})\), executes the first action and solves again at the next step: model predictive control in latent space. Hierarchy stacks such predictors at coarser time steps, with each level setting sub-goals for the level below.

Two objects come before any network is trained: the energy itself and a collapse detector, because prediction loss alone cannot distinguish a good representation from a collapsed one. The detector summarizes a batch of embeddings by its smallest per-dimension standard deviation, the fraction of dead dimensions and the effective rank (the exponential of the entropy of the normalized squared singular values: \(d\) for well-spread embeddings, 1 for a line, 0 by convention for a constant batch).

"""energy.py -- the JEPA energy E(x,y) = min_z ||g(f(x), z) - fbar(y)|| and a collapse report."""
import numpy as np

def energy(s_x, s_y, predictor, z_grid):
    """s_x, s_y: (d,) context / target embeddings; z_grid: (K, k) candidate latents."""
    errs = np.array([np.linalg.norm(predictor(s_x, z) - s_y) for z in z_grid])
    i = int(errs.argmin())
    return float(errs[i]), z_grid[i]

def collapse_report(S, eps=1e-4):
    """S: (N, d) batch of embeddings -> min per-dim std, fraction of dead dims, effective rank."""
    std = S.std(0)
    sv = np.linalg.svd(S - S.mean(0), compute_uv=False)
    if (sv ** 2).sum() < 1e-10:                      # every row identical
        return dict(min_std=float(std.min()), frac_dead=float((std < eps).mean()), eff_rank=0.0)
    p = sv ** 2 / (sv ** 2).sum(); p = p[p > 0]
    return dict(min_std=float(std.min()), frac_dead=float((std < eps).mean()),
                eff_rank=float(np.exp(-(p * np.log(p)).sum())))

if __name__ == "__main__":
    rng = np.random.default_rng(0); d = 8
    pred = lambda s, z: s + 0.5 * z[0] * np.ones(d)   # z decides "left" or "right" of the context
    z_grid = np.array([[-1.0], [0.0], [1.0]])
    s_x = rng.normal(size=d)
    E_l, z_l = energy(s_x, s_x - 0.5, pred, z_grid)
    E_r, z_r = energy(s_x, s_x + 0.5, pred, z_grid)
    E_bad, _ = energy(s_x, s_x + 3.0, pred, z_grid)
    assert E_l < 1e-9 and E_r < 1e-9 and z_l[0] == -1 and z_r[0] == 1
    print("E(left)=%.3g z=%+d  E(right)=%.3g z=%+d  E(incompatible)=%.3f"
          % (E_l, z_l[0], E_r, z_r[0], E_bad))
    healthy = rng.normal(size=(256, d)); collapsed = np.tile(rng.normal(size=d), (256, 1))
    for name, S in [("healthy", healthy), ("collapsed", collapsed)]:
        print(name, {k: round(v, 3) for k, v in collapse_report(S).items()})

Both futures on either side of the context reach zero energy with opposite latents, an incompatible future gets a high energy, and a constant batch has every dimension dead:

E(left)=0 z=-1  E(right)=0 z=+1  E(incompatible)=7.071
healthy {'min_std': 0.923, 'frac_dead': 0.0, 'eff_rank': 7.833}
collapsed {'min_std': 0.0, 'frac_dead': 1.0, 'eff_rank': 0.0}

The explicit regularizers are equally short. The variance-covariance pair follows VICReg; the second function is a simplified sketch of the SIGReg idea, not the LeJEPA implementation.

"""anticollapse.py -- VICReg-style variance/covariance terms and a sketch of LeJEPA's SIGReg idea."""
import numpy as np

def variance_covariance(S, gamma=1.0, eps=1e-4):
    Z = S - S.mean(0)
    v = np.mean(np.maximum(0.0, gamma - np.sqrt(Z.var(0) + eps)))   # every dim keeps spread
    C = Z.T @ Z / (len(S) - 1)
    c = ((C - np.diag(np.diag(C))) ** 2).sum() / S.shape[1]         # decorrelate dims
    return float(v), float(c)

def sigreg_sketch(S, n_dirs=64, t=np.linspace(-3, 3, 17), seed=0):
    """Project on random unit directions; compare each projection's empirical characteristic
    function with that of N(0,1). A simplified sketch, not the authors' implementation."""
    U = np.random.default_rng(seed).normal(size=(S.shape[1], n_dirs)); U /= np.linalg.norm(U, axis=0)
    ecf = np.exp(1j * (S @ U)[:, :, None] * t).mean(0)
    w = np.exp(-t ** 2 / 2)
    return float((np.abs(ecf - np.exp(-t ** 2 / 2)) ** 2 * w).mean())

if __name__ == "__main__":
    rng = np.random.default_rng(0); N, d = 512, 32
    cases = [("isotropic", rng.normal(size=(N, d))),
             ("rank-2", rng.normal(size=(N, 2)) @ rng.normal(size=(2, d))),
             ("constant", np.tile(rng.normal(size=d), (N, 1)))]
    for name, S in cases:
        v, c = variance_covariance(S)
        print("%-9s var-hinge %.3f  cov %7.3f  sigreg %.4f" % (name, v, c, sigreg_sketch(S)))
isotropic var-hinge 0.013  cov   0.063  sigreg 0.0003
rank-2    var-hinge 0.104  cov  46.286  sigreg 0.0202
constant  var-hinge 0.990  cov   0.000  sigreg 0.1467

The variance hinge barely reacts to the rank-2 batch while the covariance term flags it; the constant batch shows the opposite pattern, which is why VICReg uses both. The SIGReg sketch orders all three cases with one number. The EMA alternative is a frozen copy of the encoder that is excluded from the optimizer and updated after every step:

"""ema.py -- the EMA target encoder in PyTorch: no gradients, not in the optimizer, momentum 0.996 -> 1."""
import copy, torch, torch.nn as nn

enc = nn.Linear(4, 4)
tgt = copy.deepcopy(enc).requires_grad_(False)          # target encoder: a frozen copy
opt = torch.optim.SGD(enc.parameters(), lr=0.1)          # only the context side is optimized

@torch.no_grad()
def ema_update(m):
    for pt, pc in zip(tgt.parameters(), enc.parameters()):
        pt.mul_(m).add_((1 - m) * pc)

steps = 1000
for step in range(steps):
    loss = (enc(torch.randn(8, 4)) - tgt(torch.randn(8, 4))).pow(2).mean()
    opt.zero_grad(); loss.backward(); opt.step()
    ema_update(0.996 + (1.0 - 0.996) * step / steps)      # linear schedule to 1.0
assert all(p.grad is None for p in tgt.parameters())
print("weight kept by a value 250 steps old at m=0.996: %.3f" % 0.996 ** 250)
print("target grads: none; target-context gap: %.4f"
      % sum((a - b).abs().sum() for a, b in zip(tgt.parameters(), enc.parameters())).item())
weight kept by a value 250 steps old at m=0.996: 0.367
target grads: none; target-context gap: 0.4879

The assertion checks the property that matters: the target never receives a gradient. A single parameter shared between the two encoders, or a target accidentally passed to the optimizer, silently removes the asymmetry.

A predictive-representation model is a self-supervised pretraining job whose loss curve cannot be trusted on its own, because a collapsing run also shows a falling loss. Production runs log representation health next to the loss, on the target embeddings that the predictor is chasing.

Logged every few hundred stepsHealthyDeviation suggests
Prediction lossFalls, then flattensFalling fast while rank falls: collapse
Effective rank of target embeddingsStable or rising after warm-upSteady decline: dimensional collapse
Fraction of near-constant dimensions0Dead dimensions
EMA momentumFollows its scheduleFlat or wrong: a configuration bug weakening the asymmetry
Frozen-backbone probe on a held-out taskImproves across checkpointsFlat while loss falls: shortcut or collapse

Compute. Token count drives cost. V-JEPA 2 (Assran et al., 2025) cuts video into 2×16×16 tubelets, so a 16-frame 256×256 clip is 2,048 tokens and a 64-frame 384×384 clip 18,432. Training mostly on the short, low-resolution clips and raising length and resolution only in a final cooldown reduced GPU time by 8.4× in the paper. Masking saves compute as well: only visible context tokens take a backward pass, and the target encoder runs forward only, with no optimizer state, although it is a second copy of the encoder in memory.

Choosing the anti-collapse mechanism. EMA asymmetry is proven at scale in I-JEPA, V-JEPA and V-JEPA 2, but its momentum schedule is a hidden hyperparameter: an override that pins the momentum shortens the averaging window and lets the target follow the context encoder toward a low-rank solution. Explicit regularizers remove the second copy and the schedule. LeJEPA reports 79% ImageNet-1k linear-probe accuracy with a ViT-H/14, and LeWorldModel (Maes et al., 2026) uses SIGReg to train a 15M-parameter world model end to end from pixels on a single GPU. Their weight is the new risk: too large forces variance into noise dimensions.

Failure modes. Three patterns separate cleanly in the logs. Collapse: loss, rank and probe all fall together. Shortcut: rank is healthy and loss is low but the probe is flat, usually because the masking task can be solved by local interpolation. Silent detail loss: aggregate probes are fine but a small, task-relevant feature is absent from the embedding, visible only to a targeted probe. Recovery resumes from the last checkpoint with healthy rank, not from the latest.

The stakes are now commercial: AMI Labs' $1.03 billion seed round in March 2026 (SiliconANGLE 2026) is a bet on models of this kind, whose quality will be judged by planners and probes rather than by watching predicted frames.

I-JEPA and V-JEPA

The first implementations used masking rather than time as the prediction task, which made them representation learners first and world models only implicitly. Assran et al. (2023) introduced I-JEPA: from one context block of an image, predict the embeddings of several masked target blocks. With no hand-crafted augmentations, the learned features transferred well to semantic tasks while training efficiently. Bardes et al. (2024) extended the idea to video with V-JEPA, which predicts the features of masked spatiotemporal regions; their main finding was that feature prediction alone, with no pixel reconstruction, text or negatives, yields video features that work with a frozen backbone on both motion- and appearance-heavy tasks.

Cut an image \(I\) into \(N\) patches. Let \(B_1, \dots, B_M\) be target blocks (sets of patch indices, \(M = 4\)) and \(C\) the context set with every target patch removed, \(C \cap \bigcup_i B_i = \varnothing\). The target encoder embeds the full image, \(s_j = \bar f(I)_j\); the context encoder sees only \(\{I_c\}_{c \in C}\); the predictor takes the context embeddings and a positional token \(p_j\) for each requested target and returns \(\hat s_j\). The I-JEPA loss of Assran et al. (2023) is

\[ \mathcal{L}_{\text{I-JEPA}} = \frac{1}{M} \sum_{i=1}^{M} \sum_{j \in B_i} \big\| \hat s_j - s_j \big\|_2^2 , \]

with gradients into the context encoder and predictor only, and the target updated by EMA. Target blocks have area fraction \(a \sim U(0.15, 0.2)\) and aspect ratio in \((0.75, 1.5)\); the context block has \(a_c \sim U(0.85, 1)\). Large blocks keep most target patches several patches from any visible one, so interpolation fails and the predictor must use global context. V-JEPA (Bardes et al., 2024) replaces patches by spatiotemporal tubelets, extends each spatial mask across all frames of the clip so that hidden content cannot be copied from a neighbouring frame, and uses an L1 distance between predicted and target features.

The mask sampler is the part of an I-JEPA implementation most often written wrongly, and its one invariant is that context and targets are disjoint. The sampler below draws four target blocks and one context block on the 14×14 grid of a 224-pixel image with 16-pixel patches, removes target patches from the context, and measures how far each hidden patch is from the nearest visible one.

"""masks.py -- I-JEPA multi-block masking on an H x W patch grid (14x14 = a 224-px image, 16-px patches)."""
import numpy as np

def sample_block(rng, H, W, scale, aspect):
    s = rng.uniform(*scale) * H * W                                  # block area in patches
    a = np.exp(rng.uniform(np.log(aspect[0]), np.log(aspect[1])))   # aspect ratio h/w
    h = max(1, min(H, round(np.sqrt(s * a)))); w = max(1, min(W, round(np.sqrt(s / a))))
    top, left = rng.integers(0, H - h + 1), rng.integers(0, W - w + 1)
    return {r * W + c for r in range(top, top + h) for c in range(left, left + w)}

def ijepa_masks(rng, H=14, W=14, M=4, t_scale=(0.15, 0.2), t_aspect=(0.75, 1.5), c_scale=(0.85, 1.0)):
    targets = [sample_block(rng, H, W, t_scale, t_aspect) for _ in range(M)]
    context = sample_block(rng, H, W, c_scale, (1.0, 1.0)) - set().union(*targets)  # no leakage
    return np.array(sorted(context)), [np.array(sorted(t)) for t in targets]

def nearest_visible(ctx, tgt, W=14):
    """Grid (Chebyshev) distance from each target patch to the nearest visible context patch."""
    cr, cc = np.divmod(ctx, W); tr, tc = np.divmod(tgt, W)
    return np.maximum(abs(tr[:, None] - cr), abs(tc[:, None] - cc)).min(1)

if __name__ == "__main__":
    rng = np.random.default_rng(0); ctx_n, tgt_n, dist = [], [], []
    for _ in range(2000):
        ctx, tgts = ijepa_masks(rng)
        allt = np.unique(np.concatenate(tgts))
        assert not set(ctx) & set(allt)                              # the core invariant
        ctx_n.append(len(ctx)); tgt_n += [len(t) for t in tgts]; dist += list(nearest_visible(ctx, allt))
    print("target block: mean %.1f patches (range %d-%d) of 196" % (np.mean(tgt_n), min(tgt_n), max(tgt_n)))
    print("visible context after removal: mean %.1f patches" % np.mean(ctx_n))
    print("distance from hidden patch to nearest visible: median %d, 90th pct %d"
          % (np.median(dist), np.percentile(dist, 90)))
    # Same number of hidden patches, scattered at random instead of in blocks:
    dist_r = []
    for _ in range(2000):
        hid = rng.choice(196, size=len(allt), replace=False)
        vis = np.setdiff1d(np.arange(196), hid)
        dist_r += list(nearest_visible(vis, hid))
    print("same count scattered at random: median %d, 90th pct %d"
          % (np.median(dist_r), np.percentile(dist_r, 90)))
target block: mean 34.3 patches (range 25-42) of 196
visible context after removal: mean 90.1 patches
distance from hidden patch to nearest visible: median 2, 90th pct 3
same count scattered at random: median 1, 90th pct 1

Block masking leaves hidden patches a median of two patches from any visible patch; the same number of hidden patches scattered at random, with every other patch visible, sit next to a visible neighbour. That distance is what forces semantic rather than texture-level prediction, and it is worth logging whenever a mask recipe changes.

Masked feature prediction at scale is limited by token throughput, by the quality of the masking task and by evaluation that cannot rely on looking at outputs.

Mask recipes are a failure point. A configuration copied from a masked-autoencoder recipe (many small random masks) makes the loss fall well below that of a block-masked run while frozen probes get worse: the task has become solvable by interpolation. Loss must therefore never be the criterion for choosing mask settings; the distance from hidden to visible tokens and probe scores are.

Evaluation without looking. The standard instrument is a frozen-backbone probe: a light linear or attentive head trained on top of the frozen encoder for tasks spanning appearance (ImageNet, Kinetics-400) and motion (Something-Something-v2). Two rows make a probe table meaningful: the same probe on a randomly initialized encoder, which can score surprisingly well when the labels are simple functions of the input, and a held-out task never used for model selection. The suite runs on every checkpoint and flags any where loss and probe move in opposite directions.

V-JEPA 2: Planning with a Latent World Model

Assran et al. (2025) turned the representation into an explicit, action-conditioned world model and used it to control a robot. The recipe has two stages:

  • Pretraining. V-JEPA 2 is trained by masked feature prediction on more than a million hours of internet video plus images.
  • Action-conditioned post-training. With the encoder frozen, a predictor (V-JEPA 2-AC) is trained on less than 62 hours of unlabeled robot video from the Droid dataset to predict the next frame's embedding from the current embedding and the robot's action.
  • Planning. Given a goal image, the robot searches with the cross-entropy method for an action sequence whose predicted final embedding is closest to the goal's embedding, executes the first action and replans. The paper reports zero-shot pick-and-place on Franka arms in two labs, with no data from those environments and no task-specific reward.

An independent result points the same way. Zhou et al. (2024) built DINO-WM on frozen DINOv2 patch features: a transformer predicts future patch features from past features and actions, trained on offline trajectories without rewards, and plans with MPC and CEM toward a goal image. Across six environments, including rope and granular manipulation, it reached goals more reliably than IRIS, DreamerV3 and TD-MPC2, with the caveat that it needs action-labeled offline data with good coverage.

Model. Let \(E_\phi\) be the frozen V-JEPA 2 encoder and \(s_t = E_\phi(o_t)\) the patch embeddings of frame \(o_t\), with action \(a_t\) and proprioceptive state \(q_t\) (end-effector pose). The action-conditioned predictor of Assran et al. (2025) is a block-causal transformer,

\[ \hat s_{t+1} = P_\psi\big(s_{\le t},\, a_{\le t},\, q_{\le t}\big), \]

so one forward pass over a clip yields every one-step prediction. It is trained with a teacher-forcing loss and a rollout loss in which the predictor consumes its own output for \(k = 2\) steps:

\[ \mathcal L_{\text{tf}} = \frac{1}{T}\sum_{t=1}^{T} \big\| \hat s_{t+1} - s_{t+1} \big\|_1, \qquad \mathcal L_{\text{roll}} = \big\| \hat s^{(k)}_{t+k} - s_{t+k} \big\|_1 . \]

The rollout term exposes the predictor to its own errors, which is the input distribution it meets during planning.

Planning. Given a goal image with embedding \(s_g = E_\phi(o_g)\), the plan over horizon \(H\) solves

\[ a^\star_{1:H} = \arg\min_{a_{1:H}} \big\| \hat s_{t+H}(a_{1:H}) - s_g \big\|_1 \quad \text{s.t.}\ \|a_h\|_1 \le \rho , \]

and only \(a^\star_1\) is executed before re-planning. The cross-entropy method keeps a diagonal Gaussian over plans, draws \(S\) samples, keeps the \(K\) lowest-energy elites and refits mean and standard deviation, for \(I\) iterations. The cost per decision is \(N_{\text{eval}} = S \cdot I \cdot H\) predictor steps; the paper's comparison setting (\(S = 800\), \(I = 10\), \(H = 1\)) gives 8,000. DINO-WM (Zhou et al., 2024) has the same structure on frozen DINOv2 patch features. Because the energy lives in a frozen encoder's space, the cost is only as discriminative as that space: configurations that differ in a detail the encoder does not represent have nearly equal energy.

The planner can be checked line by line with a toy predictor standing in for the transformer: an L1-ball projection for the action constraint, CEM with the paper's comparison settings over a 7-dimensional arm action, a receding-horizon loop, and the teacher-forcing and rollout losses. A real system substitutes frozen-encoder embeddings and the trained predictor; the planner does not change.

"""cem_plan.py -- goal-conditioned CEM planning with an action-conditioned latent predictor.
Energy = L1 distance between the predicted embedding after the plan and the goal embedding.
Settings follow the V-JEPA 2-AC comparison: 800 samples, 10 iterations, horizon 1, ||a||_1 <= 0.075."""
import numpy as np

def project_l1(a, radius):
    n = np.abs(a).sum(-1, keepdims=True)
    return a * np.minimum(1.0, radius / np.maximum(n, 1e-12))

def cem(predict, s0, s_goal, A=7, H=1, samples=800, iters=10, elite=0.1, radius=0.075, rng=None):
    """predict(s (N,d), a (N,A)) -> (N,d). Returns the first action of the refined plan."""
    mu, sigma = np.zeros((H, A)), np.full((H, A), radius)
    k = max(1, int(elite * samples))
    for _ in range(iters):
        plans = project_l1(mu + sigma * rng.standard_normal((samples, H, A)), radius)
        s = np.repeat(s0[None], samples, 0)
        for h in range(H):                                   # batched latent rollout
            s = predict(s, plans[:, h])
        E = np.abs(s - s_goal).sum(-1)
        el = plans[np.argsort(E)[:k]]                         # elite plans
        mu, sigma = el.mean(0), el.std(0) + 1e-6
    return project_l1(mu, radius)[0]

def model_losses(predict, S, acts, k=2):
    """Teacher-forcing and k-step rollout L1 losses. S: (T+1, d) frozen-encoder embeddings, acts: (T, A)."""
    tf = np.mean([np.abs(predict(S[t][None], acts[t][None])[0] - S[t + 1]).mean() for t in range(len(acts))])
    ro = []
    for t in range(len(acts) - k + 1):
        s = S[t][None]
        for j in range(k):
            s = predict(s, acts[t + j][None])                 # consume its own prediction
        ro.append(np.abs(s[0] - S[t + k]).mean())
    return float(tf), float(np.mean(ro))

if __name__ == "__main__":
    rng = np.random.default_rng(1); d, A = 16, 7               # 7-D arm action (pose delta + gripper)
    B = rng.normal(size=(A, d)) * 2.0
    predict = lambda s, a: s + np.tanh(a @ B)                  # toy predictor standing in for the network
    goal = 4 * np.tanh(project_l1(rng.normal(size=A), 0.07) @ B)   # four feasible moves away
    s, hist = np.zeros(d), []
    print("energy before acting: %.3f" % np.abs(goal).sum())
    for step in range(6):                                      # receding horizon: plan, act once, replan
        a = cem(predict, s, goal, A=A, rng=rng)
        assert np.abs(a).sum() <= 0.075 + 1e-9
        s = predict(s[None], a[None])[0]; hist.append(np.abs(s - goal).sum())
    print("energy after each executed action:", " ".join("%.3f" % e for e in hist))
    acts = rng.normal(size=(5, A)) * 0.02; S = [np.zeros(d)]
    for a in acts: S.append(predict(S[-1][None], a[None])[0])
    S = np.stack(S)
    biased = lambda s, a: predict(s, a) + 0.01                 # a slightly biased predictor
    print("tf / 2-step rollout L1, exact model: %.4f / %.4f" % model_losses(predict, S, acts))
    print("tf / 2-step rollout L1, biased model: %.4f / %.4f" % model_losses(biased, S, acts))
energy before acting: 3.398
energy after each executed action: 2.253 1.272 0.456 0.006 0.004 0.005
tf / 2-step rollout L1, exact model: 0.0000 / 0.0000
tf / 2-step rollout L1, biased model: 0.0100 / 0.0200

The goal sits four constrained moves away, and the energy falls to near zero after four executed actions, then stays there as re-planning proposes near-zero moves. The loss check shows the rollout loss doubling a small per-step bias, which is the drift the rollout term is meant to expose. Plotting energy per executed action is the first debugging tool: a flat curve with a non-zero floor means the goal is unreachable in the model or the energy landscape is flat.

Latency. The reported 16 s per action for V-JEPA 2-AC is far from real-time control, though well below the roughly 4 minutes per action reported for a generative video model (Cosmos) in the same comparison. The usual remedies, in order: batch all candidates through the predictor (one call per iteration and horizon step); warm-start CEM from the previous plan, shifted by one step; cut samples and iterations while watching success; seed candidates from a learned policy; and shrink the model. Chahe and Zhou (2026) warm-start planning over a JEPA world model from an Octo-based policy, and LeWorldModel reports planning up to 48× faster than DINO-WM with a 15M-parameter model.

Design choices that move success. Terver et al. (2025) compared JEPA world-model planners systematically: CEM with an L2 energy was the most reliable planner, DINO-family encoders planned better than V-JEPA encoders, proprioceptive input helped consistently, and multistep rollout losses helped most on real-robot data. V-JEPA 2's authors report that training on both Droid camera views without conditioning on camera position degraded performance, because one action moves the arm in different image directions per view; they used one view.

Known limits. Goals must be images; longer tasks needed hand-provided sub-goal images; DINO-WM needs action-labelled offline data with good coverage. Evaluation is also thin: with 10 trials per task per lab, a 95% interval around 7 of 10 successes spans roughly 40% to 89%, so most per-task differences between robot planners are not individually significant. Production comparisons need fixed task suites, tens of paired trials per task and a monitor of the true next frame's energy rank among random actions, which detects an action-insensitive predictor before success drops.

Generative versus Latent Prediction

The generative and latent schools are best seen as answers to different questions rather than rivals for one prize. A generative model is the right tool when the output itself is the product (a game frame, a synthetic driving video, a counterfactual a human will look at); a latent model is the right tool when the output feeds a planner or classifier and nobody will look at it. The practical differences:

  • What is learned. Pixel models must allocate capacity to texture and lighting; latent models can skip them, which is efficient but means important small details can be dropped silently (the DIAMOND argument in reverse).
  • How you inspect it. A generative model can be checked by looking at its rollouts. A latent model needs probes, decoders trained after the fact, or downstream task success, which makes failures harder to see.
  • Collapse and shortcuts. Generative losses cannot collapse but can be satisfied by blurry averages; latent losses can collapse and need architectural or regularization safeguards.
  • Planning cost. Latent rollouts are cheap enough for CEM with hundreds of samples per step; pixel rollouts usually are not, which is why planning-heavy methods (TD-MPC2, DINO-WM, V-JEPA 2-AC) are almost all latent.

The bet is now being funded at scale. In March 2026 LeCun's new company, AMI Labs, announced a $1.03 billion seed round to build world models along these lines (SiliconANGLE 2026). Whether latent world models can match generative ones on breadth, rather than on a few robot tasks, is one of the more consequential open questions in the field.

Why pixel losses blur. Let the future observation be a random vector \(Y\) given context \(x\) and let a generative model output one prediction \(\hat y\). Under squared error,

\[ \mathbb E\big[\|Y - \hat y\|^2 \mid x\big] = \big\|\hat y - \mathbb E[Y\mid x]\big\|^2 + \mathbb E\big[\|Y - \mathbb E[Y\mid x]\|^2 \mid x\big], \]

so the optimum is the conditional mean and the conditional variance is an irreducible floor. When the future is multimodal the mean lies between the modes and matches none of them. Generative models escape by predicting a distribution (autoregressive tokens, diffusion, latent-variable models) and pay in sampling cost. A JEPA escapes differently: if the target encoder maps both outcomes to nearby embeddings, \(\bar f(y_A) \approx \bar f(y_B)\), the target is no longer multimodal and a point prediction is exact; if the outcomes differ in a way the encoder keeps, the latent \(z\) in \(E(x,y) = \min_z \|g_\psi(f_\theta(x), z) - \bar f(y)\|\) lets each be reached with its own \(z\).

What can be dropped silently. If a feature \(u(y)\) of the future is unpredictable from \(x\), keeping it in \(\bar f(y)\) only adds irreducible error, so the objective gives no incentive to retain it. That is the intended benefit (leaf positions) and the risk (a small object whose position is unpredictable from the context but decisive for the task).

Planning cost. For CEM with \(S\) samples, \(I\) iterations and horizon \(H\), on a model producing \(r\) rollout steps per second across \(b\) parallel streams,

\[ T_{\text{plan}} = \frac{S \cdot I \cdot H}{r \cdot b}. \]

Per-step cost \(1/r\) grows with output resolution for a pixel model and with embedding size for a latent one, which is the quantitative content of the observation that planning-heavy methods are almost all latent.

Three facts behind the choice fit in one script: the L2-optimal prediction of a bimodal future is a blurred average with lower loss than either sharp answer; an embedding that discards the unpredictable detail makes a point prediction exact; and the planning cost per decision follows from samples, iterations and horizon.

"""genlat.py -- (1) an L2 pixel loss predicts a bimodal future as its blurry mean;
(2) a latent target that discards the unpredictable detail removes the blur; (3) planning cost."""
import numpy as np

def l2_optimal(futures, probs):
    return (np.asarray(probs)[:, None] * np.asarray(futures)).sum(0)   # conditional mean

def expected_mse(pred, futures, probs):
    return float(sum(p * np.mean((pred - f) ** 2) for f, p in zip(futures, probs)))

if __name__ == "__main__":
    # An 8-pixel frame: an object lands at pixel 1 or pixel 6 with equal probability.
    fut, pr = [np.eye(8)[1], np.eye(8)[6]], [0.5, 0.5]
    mean = l2_optimal(fut, pr)
    print("L2-optimal frame:", mean)
    print("expected MSE: mean %.4f, commit to one mode %.4f"
          % (expected_mse(mean, fut, pr), expected_mse(fut[0], fut, pr)))
    # A target 'encoder' that keeps only "an object is present" maps both futures to one embedding.
    enc = lambda y: np.array([y.sum()])                                  # landing side discarded
    print("embeddings of the two futures:", enc(fut[0]), enc(fut[1]), "-> point prediction is exact")
    # Planning cost per decision = samples x iterations x horizon predictor evaluations.
    n = 800 * 10 * 1                                                      # V-JEPA 2-AC comparison setting
    print("V-JEPA 2-AC: %d evaluations in 16 s reported -> %.0f ms each" % (n, 1000 * 16 / n))
    print("Cosmos: 80 samples in 240 s reported -> %.0fx the time with %.0fx fewer samples"
          % (240 / 16, 800 / 80))
L2-optimal frame: [0.  0.5 0.  0.  0.  0.  0.5 0. ]
expected MSE: mean 0.0625, commit to one mode 0.1250
embeddings of the two futures: [1.] [1.] -> point prediction is exact
V-JEPA 2-AC: 8000 evaluations in 16 s reported -> 2 ms each
Cosmos: 80 samples in 240 s reported -> 15x the time with 10x fewer samples

The ghost frame has half the expected squared error of a sharp guess, so gradient descent on L2 converges to it. The timing lines are derived only from the reported V-JEPA 2 figures.

Inspecting a latent model. Because rollouts cannot be watched, three instruments replace watching: a linear probe from embeddings to known state variables, scored on a held-out split beside a random-init baseline; a post-hoc decoder trained on frozen embeddings with gradients stopped, which renders what the embedding retains without changing it; and a surprise signal, the per-step prediction error on physically plausible versus implausible clips.

In deployment the choice becomes a set of risks. A generative simulator's risks are cost and drift, both visible; a latent model's risks are missing details and collapse, neither visible without instruments.

RequirementFavoursMeasured by
Output viewed by people or fed to a perception stackGenerativeFVD, PSNR over horizon, human ratings
Hundreds of rollouts per decision under a latency budgetLatentSeconds per decision, success rate
Small visual details decide the outcomeGenerative or hybridTargeted probe on the detail
Goals change at run timeLatent with goal energySuccess on held-out goals

Recent evidence. LeWorldModel (Maes et al., 2026), a 15M-parameter JEPA trained end to end from pixels with a next-embedding loss and SIGReg, planned up to 48× faster than DINO-WM and was competitive with it overall. In violation-of-expectation tests its prediction error spiked when objects teleported but not when their colour changed abruptly: a latent model's blind spots are whatever its embedding discarded. VL-JEPA (Chen et al., 2025) carried latent prediction to vision-language, predicting text embeddings instead of generating tokens and decoding only when needed.

Hybrids and auditability. The common production shape trains in latent space and decodes only for inspection: a decoder trained afterwards on frozen embeddings gives viewable rollouts without making pixels the target. A latent model ships with its instruments: a fixed probe suite with random-init baselines, a post-hoc decoder for incident review, a test set of implausible clips for the surprise signal, and training-time rank monitors. When a generative model is required, cost falls by computing the planning cost on its latent tokens rather than decoded pixels, by seeding samples from a policy and by shorter horizons. The rule is the one the comparison implies: if a person consumes the prediction, pay for pixels; if a planner consumes it, pay for instruments.

Do Language Models Have World Models?

Language models enter the world-model story in two distinct ways: as systems that might build an internal model of the world while learning to predict text, and as tools explicitly used to simulate environments for other agents. The first is a scientific question about representations; the second is an engineering practice that works or fails regardless of how the first is answered.

The internal question has a clean test bed in board games, where the true state is known and can be compared with what the network represents. The evidence so far is mixed in an informative way:

  • Othello-GPT. Li et al. (2023) trained a GPT model only to predict legal Othello moves from move sequences. Probes recovered the board state from its activations (nonlinearly), and editing that internal representation changed the model's predicted moves accordingly, suggesting the representation is causally used, not just decodable.
  • Linear after all. Nanda et al. (2023) showed the board state is linearly decodable once squares are encoded relative to the current player ("mine" versus "theirs") rather than as black and white, and that simple vector arithmetic steers the model.
  • Space and time. Gurnee & Tegmark (2024) found that LLM activations linearly encode the real-world coordinates of places and the dates of events, a map-like structure learned from text alone.
  • Coherence tests. Vafa et al. (2024) proposed metrics based on the Myhill–Nerode theorem: a true world model should give the same continuations for histories that reach the same state (compression) and different continuations for histories that reach different states (distinction). Transformers trained on New York taxi routes made nearly perfect next-turn predictions, yet their implied street maps were incoherent and their navigation broke down when detours were introduced.

Melanie Mitchell's summary of the debate (Mitchell 2025) borrows Jacob Andreas's ladder of increasingly strong models (lookup table, map, orrery, simulator) and argues that most positive evidence shows map- or orrery-like structure, with little evidence yet of detailed causal simulators. That framing is a useful corrective to both camps: "has a world model" is not binary, and next-token accuracy is a weak test of which rung a model is on.

The common object. Let an environment emit observations \(o_t\) in response to actions \(a_t\), and let \(h_t = (o_1, a_1, \dots, o_t)\) be the history. A world model is a conditional distribution \(p_\theta(o_{t+1} \mid h_t, a_t)\). A language model over a vocabulary \(\mathcal{V}\) defines \(p_\theta(x_{n+1} \mid x_{1:n})\); once each step is serialized as a block of tokens, its conditional over the next block has exactly this form. The scientific question is whether \(p_\theta\) factors through a compact state: is there an encoder \(f\) with \(p_\theta(\cdot \mid h) = g(f(h))\), where \(f(h)\) tracks the true state \(q(h)\)? Andreas's ladder can be read as successively stronger conditions on \(f\): a map requires that \(q(h)\) be decodable from \(f(h)\); an orrery additionally requires a consistent update rule \(f(hx) \approx \delta(f(h), x)\); a simulator requires that the rule remain correct for interventions and inputs off the training distribution.

Probes. Let \(z(h)\in\mathbb{R}^d\) be the activation at the last token of \(h\) and \(y(h)\) a known state variable, such as the colour \(y\in\{-1,+1\}\) of one Othello square. A linear probe \((w,b)\) minimizes \(\sum_i (w^\top z(h_i)+b-y_i)^2\) and is scored by held-out accuracy of \(\operatorname{sign}(w^\top z+b)\). The basis matters: if the network stores \(u = y\,c\), where \(c\in\{-1,+1\}\) marks the player to move, then \(y = u\,c\) is a product of two features and no linear function of \(z\) recovers it, while a probe for \(u\) succeeds. This is the content of the "mine versus theirs" result. Because a flexible probe can memorize, Hewitt and Liang (2019) define selectivity as task accuracy minus accuracy on a control task with random labels tied to input identity.

Interventions. Given a probe direction, the edit \(z' = z - 2\,\frac{w^\top z+b}{\lVert w\rVert^2}\,w\) reflects the activation across the decision boundary. If the next-token distribution after the edit matches that of histories whose true state has the flipped value, the feature is used, not merely present.

Myhill–Nerode coherence. For a language \(L\) of legal sequences, \(h \equiv_L h'\) when \(hs\in L \iff h's\in L\) for every continuation \(s\); the equivalence classes are the states of the minimal automaton for \(L\). With \(\hat L\) the sequences a model treats as legal, Vafa et al. (2024) estimate

\[ \text{compression} = \Pr\big[\forall s:\ hs\in\hat L \iff h's\in\hat L \;\big|\; q(h)=q(h')\big],\qquad \text{distinction} = \Pr\big[\exists s\in D(h,h'):\ \mathbb{1}[hs\in\hat L]\ne\mathbb{1}[h's\in\hat L] \;\big|\; q(h)\ne q(h')\big], \]

where \(D(h,h')\) is the set of continuations on which the true language separates the two histories. Next-token accuracy constrains neither quantity outside the histories seen in training.

Myhill-Nerode coherence: histories reaching the same state must share continuations; histories in different states must be separable by some continuation.history h1a b b ahistory h2b b ahistory h3b astate q = evenstate q = oddCompression testmodel must accept the samesuffixes after h1 and h2Distinction testsome suffix (e.g. c) must beaccepted after h1, not h3
Fig. The two tests of Vafa et al. (2024), drawn for a parity toy world: the state is the parity of the number of b tokens, and c is legal only in the even state.
ExampleIn that parity world, a heuristic that counts b only in the last three tokens before each c agrees with the truth on every sequence of length at most 3. Enumerating all legal histories up to length 4 and continuations up to length 2 gives compression 0.50 and distinction 0.89 for the heuristic, against 1.00 and 1.00 for the true automaton: a short-context model can be next-token perfect and still hold an incoherent map.

The three tests can be implemented on synthetic data whose ground truth is known, so that each can be checked rather than interpreted. Part 1 builds activation vectors of shape (4000, 64) in which one square is stored relative to the player to move, as in Othello-GPT, and fits least-squares probes for the relative label and for the absolute colour; it then reflects one activation across the probe boundary and asserts that the decoded label flips, the code analogue of an intervention. Part 2 implements Myhill–Nerode compression and distinction for a parity world (state = parity of the count of b; c legal only in the even state) and compares the true automaton with a window heuristic that is next-token perfect on short sequences.

import itertools
import numpy as np
rng = np.random.default_rng(0)

# ---- 1. Linear probes: the probed encoding matters (Othello "mine/theirs") ----
def make_activations(n=4000, d=64):
    """Synthetic residual-stream vectors. Each square's state is stored RELATIVE to the
    player to move: +1 = 'mine', -1 = 'theirs'. Colour = relative * player."""
    player = rng.choice([-1, 1], size=n)          # +1 black to move, -1 white to move
    rel = rng.choice([-1, 1], size=n)             # mine / theirs for one square
    colour = rel * player                         # black(+1) / white(-1)
    w = rng.normal(size=d); w /= np.linalg.norm(w)
    H = rng.normal(scale=1.0, size=(n, d)) + 2.0 * rel[:, None] * w[None, :]
    return H, rel, colour, w

def linear_probe_acc(H, y, train=0.75):
    """Least-squares linear probe with bias; returns held-out sign accuracy."""
    k = int(len(y) * train)
    X = np.c_[H, np.ones(len(H))]
    beta, *_ = np.linalg.lstsq(X[:k], y[:k], rcond=None)
    return float(np.mean(np.sign(X[k:] @ beta) == y[k:])), beta

# ---- 2. Myhill-Nerode coherence tests (Vafa et al. 2024) ----
# True world: state = parity of the number of 'b' tokens so far (0 even, 1 odd).
# Rule: token 'c' is legal only in the even state. Tokens: a, b, c.
TOK = 'abc'
def true_state(h):
    return h.count('b') % 2
def true_accepts(seq):
    """Ground-truth legality of a whole sequence."""
    return all(seq[:i].count('b') % 2 == 0 for i, t in enumerate(seq) if t == 'c')
def window_accepts(seq, W=3):
    """A 'heuristic' model: counts b's only in the last W tokens before each c.
    It is next-token perfect on every sequence shorter than W + 1."""
    return all(seq[max(0, i - W):i].count('b') % 2 == 0 for i, t in enumerate(seq) if t == 'c')
def all_strings(maxlen):
    """Every string over TOK of length 0..maxlen."""
    return [''.join(p) for L in range(maxlen + 1) for p in itertools.product(TOK, repeat=L)]

def compression_precision(accepts, pairs_same, sufs):
    """Histories reaching the SAME true state should admit the same continuations."""
    return sum(all(accepts(h1 + s) == accepts(h2 + s) for s in sufs) for h1, h2 in pairs_same) / len(pairs_same)
def distinction_recall(accepts, pairs_diff, sufs):
    """Histories in DIFFERENT true states should be told apart by some continuation
    on which the true world differs."""
    hit = 0
    for h1, h2 in pairs_diff:
        dist = [s for s in sufs if true_accepts(h1 + s) != true_accepts(h2 + s)]
        hit += any(accepts(h1 + s) != accepts(h2 + s) for s in dist)
    return hit / len(pairs_diff)

if __name__ == "__main__":
    H, rel, colour, w = make_activations()
    acc_rel, beta = linear_probe_acc(H, rel)
    acc_col, _ = linear_probe_acc(H, colour)
    print(f"probe 'mine/theirs' acc={acc_rel:.3f}  probe 'black/white' acc={acc_col:.3f}")
    assert acc_rel > 0.95 and abs(acc_col - 0.5) < 0.05
    # causal intervention: push along the probe direction and the decoded label flips
    h = H[0].copy(); y0 = np.sign(np.r_[h, 1] @ beta)
    h_edit = h - 2 * (np.r_[h, 1] @ beta) / (beta[:-1] @ beta[:-1]) * beta[:-1]
    assert np.sign(np.r_[h_edit, 1] @ beta) == -y0

    hist = [h for h in all_strings(4) if true_accepts(h)]          # legal histories up to length 4
    pairs = [(x, y) for i, x in enumerate(hist) for y in hist[i + 1:]]
    same = [p for p in pairs if true_state(p[0]) == true_state(p[1])]
    diff = [p for p in pairs if true_state(p[0]) != true_state(p[1])]
    sufs = all_strings(2)                                             # continuations up to length 2
    short = [s for s in all_strings(3)]
    nt_acc = sum(window_accepts(s) == true_accepts(s) for s in short) / len(short)
    print(f"heuristic agreement on sequences <= 3 tokens: {nt_acc:.2f}")
    for name, m in [("true model", true_accepts), ("window W=3", window_accepts)]:
        print(f"{name:10s} compression={compression_precision(m, same, sufs):.2f} "
              f"distinction={distinction_recall(m, diff, sufs):.2f}  pairs={len(same)}/{len(diff)}")
    assert nt_acc == 1.0
    assert compression_precision(true_accepts, same, sufs) == 1.0
    assert distinction_recall(true_accepts, diff, sufs) == 1.0
    assert compression_precision(window_accepts, same, sufs) < 1.0

It prints the probe accuracies, the heuristic's agreement on short sequences, and both coherence rates for each model:

probe 'mine/theirs' acc=0.976  probe 'black/white' acc=0.485
heuristic agreement on sequences <= 3 tokens: 1.00
true model compression=1.00 distinction=1.00  pairs=2013/1815
window W=3 compression=0.50 distinction=0.89  pairs=2013/1815

The colour probe sits at chance although the information is fully present in another basis, so candidate encodings must be probed explicitly, and every probe score should be reported beside a control (shuffled labels or a randomly initialized network of the same architecture). With a real language model, accepts becomes a threshold on the probability the model assigns to each continuation token; both coherence rates depend on that threshold, which must therefore be reported. Enumeration is the expensive step: continuation sets grow exponentially with length, so practical studies sample histories and continuations rather than enumerating them.

Outside the laboratory, the internal-state question becomes a reliability question: does whatever state the model tracks survive the inputs it will meet in deployment? Three practices follow.

Probes as monitors. Once activations are cached, linear probes are cheap to fit and to rerun for every model release. The cost lies in labels: each probed variable needs ground truth that the deployment owns, such as the current page of a web session, the open files of a coding agent, or the active problem list of a patient timeline in a model like ETHOS. Probe accuracy, selectivity against a control, and the accuracy gap between familiar and shifted slices are tracked together, because a falling gap is often the first sign of a tokenizer, truncation or prompt-format change that average next-token loss hides.

Coherence before release. The taxi result is the production warning: accurate prediction can coexist with an incoherent map that breaks under detours. The defence is a coherence suite built from the shifts the deployment will produce. Matched pairs that reach the same state by different routes test compression; pairs that differ only in an old but decisive fact test distinction. The second kind exposes the commonest long-sequence failure, in which tokens that fall outside the context window cannot inform the state at all, so two histories that differ in a persistent fact receive identical predictions.

Generalization probes. Vafa et al. (2025) adapt a model to small tasks generated by a postulated world model and check whether its generalization follows that model. Transformers trained on orbital trajectories predicted them well but did not consistently apply Newtonian mechanics on new tasks, behaving as if they had learned task-specific heuristics. The method costs a fine-tuning run per probe and is the closest current test of the orrery and simulator rungs.

CheckSignalTypical action
Probe selectivitytask score minus control scorelow: treat the probe result as uninformative
Context-window gapprobe score for facts inside versus outside the windowlarge: add a persistent summary block or longer context
Matched-pair distinctionshare of different-state pairs given different predictionsfalls after a release: block the release
Matched-pair compressionshare of same-state pairs given matching predictionsfalls: inspect sensitivity to irrelevant detail

None of these checks proves a simulator-grade world model. They bound which rung of the ladder a deployed model can be trusted on, for the inputs that matter.

LLMs as Simulators for Agents

Whatever their internal states, LLMs can be prompted or fine-tuned to predict what an environment would return, and that is enough to make them useful as world models for planning. The pattern is Dyna again, with text in place of pixels:

  • Planning with an LLM world model. Hao et al. (2023) proposed RAP (reasoning via planning), in which the same LLM serves as the agent and as a world model that predicts the next state of a reasoning problem, with Monte Carlo tree search over the resulting tree.
  • How good are LLM simulators? Wang et al. (2024) built ByteSized32-State-Prediction to test whether LLMs can predict how actions change the state of text games, and concluded that even GPT-4 was not yet a dependable text-world simulator.
  • Web agents. Gu et al. (2025) introduced WebDreamer, which asks an LLM to imagine the outcome of each candidate action on a website before committing, then scores the imagined outcomes. It was competitive with tree search in the real sandbox at a fraction of the cost, and a 7B world model fine-tuned on about 3.1 million synthesized interactions performed comparably to GPT-4o in that role on live-website benchmarks.
  • Code. Meta's CWM (2025) is an open-weights 32B coding model trained with program execution traces, explicitly to give it a model of how code changes machine state.
An LLM used as a world model for a web or tool agent: propose actions, simulate their outcomes, score, and act. Current state page, tool output Propose k candidate actions Simulate LLM imagines result Score rate imagined state Act best action, for real real environment returns the next state; repeat all imagined: nothing touches the real site
Fig. Model-based planning for a language agent. The propose, simulate and score steps happen inside the model; only the chosen action reaches the real website or tool, which is what makes the approach cheaper and safer than trying actions for real. (Adapted and redrawn from the WebDreamer design in Gu et al. 2025.)

A minimal implementation is a prompt and a loop. The important design choice is to ask the simulator for a structured state description rather than free text, so that the scorer and later steps can rely on its fields:

SIM_PROMPT = """You simulate a web environment. Given the current page and an action,
describe the resulting page as JSON with keys: url, title, key_elements, task_progress.
Be literal; if the action would fail, say so in task_progress.
PAGE: {page}
ACTION: {action}"""

def plan_step(llm, page, task, k=4):
    candidates = llm.propose_actions(page, task, n=k)            # policy
    scored = []
    for a in candidates:
        imagined = llm.json(SIM_PROMPT.format(page=page, action=a))   # world model
        score = llm.score(task=task, state=imagined)              # value, 0..1
        scored.append((score, a))
    return max(scored)[1]                                         # execute for real, observe, repeat

One-step planning. Let \(\hat P_\theta(s'\mid s,a)\) be the LLM simulator, \(\hat V(s')\in[0,1]\) the scorer, and \(A_k(s)=\{a_1,\dots,a_k\}\) the candidates proposed by the policy. A WebDreamer-style planner selects

\[ a^\star = \arg\max_{a\in A_k(s)} \mathbb{E}_{s'\sim\hat P_\theta(\cdot\mid s,a)}\big[\hat V(s')\big] \approx \arg\max_{a\in A_k(s)} \frac{1}{m}\sum_{j=1}^{m}\hat V(s'_{a,j}), \]

with \(m\) imagined samples per action. Each real step costs one proposal call plus \(k\,m\) simulation and \(k\,m\) scoring calls. RAP replaces the one-step argmax by Monte Carlo tree search, choosing children by the UCT rule \(\arg\max_a Q(s,a) + c\sqrt{\ln N(s)/N(s,a)}\); its cost grows with the number of simulations rather than with \(k\).

Optimizer's curse. If each score equals the true value plus independent noise of standard deviation \(\sigma\), the maximum of \(k\) scores is biased upward by \(\sigma\,e_k\), where \(e_k=\mathbb{E}[\max_{i\le k}\epsilon_i]\) for standard normal \(\epsilon_i\) (\(e_4\approx1.03\), \(e_{16}\approx1.77\), roughly \(\sqrt{2\ln k}\) for large \(k\)). The chosen action looks better than it is, more so as \(k\) grows; a fresh, independent re-score of the chosen action is unbiased.

Compounding error. If each imagined step is correct with probability \(q\) and errors are independent, an \(H\)-step rollout is fully correct with probability \(q^H\). With one-step total-variation error \(\varepsilon\), the imagined state distribution at step \(t\) is within \(t\varepsilon\) of the true one.

Probability that an imagined rollout stays fully correct, q to the power H, for per-step accuracy q of 0.99, 0.95 and 0.90 over horizons 1 to 15.0.250.500.751.00151015imagination horizon H (steps)P(all steps right)q=0.99: 0.86q=0.95: 0.46q=0.90: 0.21
Fig. Compounding error under an independence assumption. A per-step accuracy of 0.95, which looks high on one-step benchmarks, leaves fewer than half of 15-step imagined rollouts fully correct. Language-agent planners therefore mostly look one step ahead, and latent world models such as DreamerV3 keep imagination short and bootstrap a learned value at the horizon.

Measuring a text simulator. ByteSized32-State-Prediction scores the predicted next state field by field against the true one. Separating fields the action changes from fields it leaves alone matters: a simulator can predict the changed fields well and still corrupt the unchanged ones, which is why transition-focused designs such as Chae et al. (2025) predict only the state difference \(\Delta s = s' \ominus s\) and copy the rest.

A planning step is a loop over candidate actions with three model calls each. The important design choice is a structured simulator output: the state is requested as JSON with fixed keys (url, title, key_elements, task_progress), validated on return, and retried once if malformed. An action whose outcome could not be imagined scores zero rather than inheriting a default state. The module below implements that loop with stub components for a checkout task, then checks two quantitative properties of simulate-and-score planning by simulation: the upward bias of the selected score when all candidates are equally good (score noise \(\sigma=0.1\)), and the probability that a 15-step rollout with per-step accuracy 0.95 stays fully correct.

import json, random

# ---- 1. Propose -> simulate -> score -> act, with a schema-checked simulator ----
STATE_KEYS = {"url": str, "title": str, "key_elements": list, "task_progress": str}

def parse_state(raw):
    """Reject simulator output that is not JSON with the required typed fields."""
    try:
        s = json.loads(raw)
    except json.JSONDecodeError:
        return None
    if not isinstance(s, dict) or not all(isinstance(s.get(k), t) for k, t in STATE_KEYS.items()):
        return None
    return s

def plan_step(propose, simulate, score, page, task, k=4, retries=1):
    """propose(page, task, k) -> list[str]; simulate(page, a) -> raw JSON str;
    score(task, state) -> float in [0, 1]. Returns (best_action, table)."""
    table = []
    for a in propose(page, task, k):
        state = None
        for _ in range(retries + 1):                 # one retry on malformed output
            state = parse_state(simulate(page, a))
            if state is not None:
                break
        table.append((score(task, state) if state else 0.0, a, state))
    best = max(table, key=lambda r: r[0])
    return best[1], table

# ---- 2. Optimizer's curse: the max of k noisy scores is biased upward ----
def selection_bias(k, sigma=0.1, trials=50_000, seed=0):
    """All k actions have true value 0.5; scores add N(0, sigma) noise.
    Returns E[score of chosen action] - true value."""
    rng = random.Random(seed)
    return sum(max(0.5 + rng.gauss(0, sigma) for _ in range(k)) for _ in range(trials)) / trials - 0.5

# ---- 3. Compounding error: P(all H imagined steps correct) = q**H ----
def rollout_correct(q, H, trials=50_000, seed=1):
    rng = random.Random(seed)
    return sum(all(rng.random() < q for _ in range(H)) for _ in range(trials)) / trials

if __name__ == "__main__":
    def propose(page, task, k):
        return ["click('Buy now')", "click('Add to cart')", "type('qty','2')", "click('Help')"][:k]
    def simulate(page, a):
        if "Help" in a:
            return "Sorry, I cannot simulate that."              # malformed output
        prog = {"click('Buy now')": "order placed", "click('Add to cart')": "item in cart"}.get(a, "no change")
        return json.dumps({"url": "/shop", "title": "Shop", "key_elements": ["cart"], "task_progress": prog})
    def score(task, s):
        return {"order placed": 0.9, "item in cart": 0.6}.get(s["task_progress"], 0.1)
    best, table = plan_step(propose, simulate, score, "<html>", "buy one mug")
    for r in table:
        print(f"{r[0]:.1f}  {r[1]}")
    assert best == "click('Buy now')" and table[-1][2] is None

    for k in (1, 4, 16):
        print(f"k={k:2d}  optimism of chosen action = {selection_bias(k):+.3f}")
    print(f"q=0.95 H=15: simulated {rollout_correct(0.95, 15):.3f}  closed form {0.95**15:.3f}")

It prints the scored candidate table, the optimism of the chosen action for \(k=1,4,16\), and the compounding-error check:

0.9  click('Buy now')
0.6  click('Add to cart')
0.1  type('qty','2')
0.0  click('Help')
k= 1  optimism of chosen action = +0.000
k= 4  optimism of chosen action = +0.103
k=16  optimism of chosen action = +0.177
q=0.95 H=15: simulated 0.462  closed form 0.463

The malformed simulation for click('Help') scores 0.0 and is never selected. With equally good candidates, choosing the best of 4 inflates the chosen score by about one noise standard deviation and the best of 16 by about 1.8, matching the Gaussian expected maximum. Practical rules: log the full table per step rather than only the chosen action, so optimism can be audited; version the simulator and scorer prompts; and when policy and simulator are the same model, sample them at different temperatures so the simulator does not merely agree with the proposal.

A simulate-and-score planner in production has three problems, each with a measurable signature: cost per real decision, optimism in the chosen action, and silent simulator error on particular kinds of transition.

Cost and latency. With four candidates and one sample each, a step costs one proposal, four simulations and four scorings: nine calls instead of one. The usual remedies, in order of payoff, are to issue the simulation calls in parallel and share the cached page prefix across them; to predict only state changes rather than whole pages, as in the transition-focused web world model of Chae et al. (2025), which shortens both input and output; to distil a small dedicated simulator, as WebDreamer did with a 7B model trained on about 3.1 million synthesized interactions; and to skip simulation when every candidate is read-only and reversible. Distillation trades cost for coverage: a small simulator is only as good as the interaction distribution it was trained on.

Optimism. Because the planner maximizes over noisy scores, imagined success of chosen actions exceeds realized success. The diagnostic is the imagined-versus-realized gap: for each executed action, compare the score of the imagined state with the score of the real next state. A gap that grows with the number of candidates is the optimizer's curse; a gap concentrated on certain action types (form submissions, login flows, pagination) points to simulator error there. Remedies are an independent re-score of the chosen action, a smaller candidate set, or routing those action types to real look-ahead in a sandbox.

Safety. The main operational benefit is that imagined actions never touch the real site, which matters most for irreversible actions such as purchases, deletions and messages. The simulator should therefore be required to predict failure explicitly, and a predicted failure should block execution rather than lower a score.

Code as the easiest domain. For code, the environment is an interpreter whose transitions can be checked exactly. Meta's CWM trains on program execution traces so that the model predicts how code changes machine state, which lets simulated execution be verified against real execution at scale.

MetricDiagnoses
Schema-valid simulator outputsprompt or decoding regressions
Imagined-versus-realized gap, by action typeoptimism; simulator bias on specific transitions
Field-level agreement on unchanged fieldsstate corruption by whole-page regeneration
Calls and tokens per real actioncost growth from larger candidate sets or retries
p95 latency per decisionserial simulation, missing prefix cache

World Models as Training Environments for Agents

The newest use of LLM world models is to replace real environments during agent RL, because building, resetting and scaling real tool environments is expensive. Three 2025–2026 papers bracket the design space:

  • LLM-simulated tools. Li et al. (2025) used a reasoning model to simulate tool outputs, error messages and success rewards (Simia-SFT and Simia-RL), expanding small seed sets into many trajectories. A 32B model fine-tuned this way averaged 58.9 on τ²-bench, above GPT-4o (54.2) in their comparison.
  • An experience model with a curriculum. Meta's DreamGym (2025) trains a reasoning-based experience model that predicts next states and rewards in an abstract text space, grounded by a replay buffer seeded with real trajectories, and proposes new tasks at the edge of the agent's ability. On WebShop and ALFWorld, agents trained only on synthetic rollouts matched PPO and GRPO trained on 80K real interactions; pretraining in DreamGym before real RL gave large gains with under 10% of the real data.
  • Code-executed environments instead. Wang et al. (2026) took the opposite route in Agent World Model: synthesize 1,000 executable environments, each with a SQLite database, an MCP tool interface and verification code. Agents trained only on them improved on three out-of-distribution benchmarks, and the authors report that database-backed state gave more consistent training signal than LLM-simulated state.

The tension between the last two is the tension of the whole book in miniature. A learned simulator is cheap and endlessly flexible but can be inconsistent and exploitable; an executable one is faithful but costly to build and narrow. The likely answer is both: learned models for breadth and curriculum, executable checks for the reward.

Training in a model. Let \(M=(P,R)\) be the real environment and \(\hat M=(\hat P,\hat R)\) the simulator. Agent RL in the style of Simia-RL or DreamGym maximizes \(J_{\hat M}(\pi)=\mathbb{E}_{\hat M,\pi}\big[\sum_t\gamma^t r_t\big]\), while the policy is judged by \(J_M(\pi)\).

Simulation lemma (finite horizon). Suppose rewards lie in \([0,R_{\max}]\), the reward function is exact, and \(\mathrm{TV}\big(\hat P(\cdot\mid s,a),P(\cdot\mid s,a)\big)\le\varepsilon\) for all \(s,a\). Running the same policy in both, the state distributions at step \(t\) differ by at most \(t\varepsilon\), so expected rewards at step \(t\) differ by at most \(t\varepsilon R_{\max}\). Summing over an episode of length \(H\),

\[ \big|J_M(\pi)-J_{\hat M}(\pi)\big| \;\le\; \varepsilon R_{\max}\sum_{t=0}^{H-1}t \;=\; \varepsilon R_{\max}\,\frac{H(H-1)}{2}. \]

The discounted analogue is \(\gamma\varepsilon R_{\max}/(1-\gamma)^2\). The quadratic dependence on horizon is why world-model RL keeps imagined rollouts short, and why multi-turn tool episodes of twenty or more steps are a demanding regime for learned simulators.

Exploitation. The lemma holds for a fixed policy; RL is not fixed. It searches for actions that maximize \(J_{\hat M}\), and regions where \(\hat M\) overestimates reward are the easiest to find. With a model-based reward \(\hat R\) the errors are systematic rather than random (for example, a judge that rewards calling the right tool regardless of its arguments), so the realized gap grows with optimization pressure. Two quantities measure it: the sim-to-real gap \(\Delta=\widehat{\mathrm{SR}}_{\hat M}(\pi)-\widehat{\mathrm{SR}}_{M}(\pi)\) in success rate on the same tasks, and transition agreement \(\Pr[\hat P\text{ output}=P\text{ output}]\) on replayed real or executable transitions, reported per tool.

Executable reward. Agent World Model sets \(\hat R\) by verification code over the database state before and after an episode, so reward error comes only from verifier bugs, which can be tested once per environment rather than per rollout.

How many real checks. A success rate estimated from \(n\) episodes has standard error \(\sqrt{\mathrm{SR}(1-\mathrm{SR})/n}\). Detecting a gap of 0.10 near \(\mathrm{SR}=0.5\) with a two-standard-error margin requires \(2\sqrt{0.25/n}\le0.10\), that is \(n\ge100\) real or executable episodes per check.

ExampleDreamGym's sim-only agents matched PPO and GRPO trained on 80K real interactions on WebShop and ALFWorld; "under 10% of the real data" for its sim-to-real variant therefore means fewer than 8,000 real interactions in that comparison.

The design space can be made concrete with two environments behind one tool interface. ExecutableEnv follows the Agent World Model recipe: state lives in an in-memory SQLite database, tools are functions that run SQL, and the reward is verification code that queries the database. SimulatedEnv stands in for an LLM-simulated environment in the style of Simia or DreamGym: it accepts every tool call agreeably and asks a judge whether the transcript looks successful. The judge is deliberately naive, rewarding any transcript that calls the cancel tool, which is the class of systematic error an RL policy learns to exploit. sim_real_gap runs the same action lists in both environments and returns the two success rates.

import sqlite3, random

class ExecutableEnv:
    """Code-executed environment (Agent-World-Model style): state lives in SQLite,
    tools are functions, and the reward is verification code run against the database."""
    def __init__(self):
        self.db = sqlite3.connect(":memory:")
        self.db.execute("CREATE TABLE orders(id INTEGER PRIMARY KEY, item TEXT, qty INT, status TEXT)")
        self.db.execute("INSERT INTO orders VALUES (1, 'mug', 1, 'placed')")
    def call(self, tool, **kw):                       # tool interface the agent sees
        if tool == "cancel_order":
            cur = self.db.execute("UPDATE orders SET status='cancelled' WHERE id=? AND status='placed'", (kw["id"],))
            return {"ok": cur.rowcount == 1}
        if tool == "get_order":
            row = self.db.execute("SELECT item, qty, status FROM orders WHERE id=?", (kw["id"],)).fetchone()
            return {"ok": row is not None, "order": row}
        return {"ok": False, "error": f"unknown tool {tool}"}
    def verify(self, goal_id):                        # reward = a database check, not an opinion
        row = self.db.execute("SELECT status FROM orders WHERE id=?", (goal_id,)).fetchone()
        return float(row is not None and row[0] == "cancelled")

class SimulatedEnv:
    """LLM-simulated environment (Simia/DreamGym style), stubbed: it predicts tool output
    and a success reward from the text of the transcript. Plausible but exploitable."""
    def __init__(self, llm_judge): self.transcript, self.judge = [], llm_judge
    def call(self, tool, **kw):
        self.transcript.append((tool, kw))
        return {"ok": True}                           # simulators tend to be agreeable
    def verify(self, goal_id): return self.judge(self.transcript, goal_id)

def naive_judge(transcript, goal_id):
    # rewards any transcript that *mentions* cancelling: the exploitable gap
    return float(any(t == "cancel_order" for t, _ in transcript))

def run(env, policy, goal_id=1):
    for tool, kw in policy: env.call(tool, **kw)
    return env.verify(goal_id)

def sim_real_gap(policies, make_sim, make_real):
    """Mean reward in simulator minus mean reward in the executable env on the same action lists."""
    s = [run(make_sim(), p) for p in policies]; r = [run(make_real(), p) for p in policies]
    return sum(s) / len(s), sum(r) / len(r)

if __name__ == "__main__":
    honest = [("cancel_order", {"id": 1})]
    hack = [("cancel_order", {"id": 999})]           # wrong id: nothing really changes
    assert run(ExecutableEnv(), honest) == 1.0 and run(ExecutableEnv(), hack) == 0.0
    assert run(SimulatedEnv(naive_judge), hack) == 1.0     # simulator is fooled
    rng = random.Random(0)
    pols = [[("cancel_order", {"id": rng.choice([1, 1, 7, 999])})] for _ in range(1000)]
    sim, real = sim_real_gap(pols, lambda: SimulatedEnv(naive_judge), ExecutableEnv)
    print(f"simulated success={sim:.2f} executable success={real:.2f} gap={sim-real:.2f}")
    assert sim == 1.0 and 0.4 < real < 0.6

It prints the success rate of 1,000 random action lists in each environment and the gap:

simulated success=1.00 executable success=0.50 gap=0.50

Half of the action lists target a wrong or nonexistent order, so the database does not change and the verifier returns 0, while the simulator rewards all of them. The assertions check both halves of the claim: the executable verifier separates the honest and the reward-hacking policy, and the simulator does not. Implementation rules follow. Keep the tool interface identical across real, simulated and executable environments, so trajectories, policies and the evaluation harness are portable. Store the simulator's predicted output beside the executed output whenever both exist; those pairs are the data for transition-agreement metrics and for fine-tuning the simulator on its disagreements. Condition a learned simulator on retrieved real transitions for the same tool, the role of DreamGym's replay buffer. When reward comes from a model, log the judge's rationale with the score so exploited patterns can be read directly.

Training inside a simulator turns every simulator error into a candidate exploit. Production practice therefore centres on one comparison: success measured in the simulator against success on a held-out set of real or executable tasks, tracked across training iterations, together with per-tool disagreement data that can explain a divergence. The characteristic failure is simulated success that keeps rising while held-out success peaks and falls; the checkpoint chosen by simulated success is then worse than an earlier one. Checkpoints should be selected on the held-out set, never on the simulator.

RemedyAddressesMain costValidated by
Verifier-code reward (Agent World Model)reward hackingengineering per environmentgap stays small; no tool-specific exploit growth
Replay-grounded simulator (DreamGym)transition errorspipeline of real transitionsper-tool agreement rises
Mix of real or executable rolloutsbias in the learning signalwall time, environment capacityheld-out success tracks simulated success
Adversarial curriculumknown exploitscovers only observed failuresshare of exploit calls falls

Scaling. Learned simulators scale with inference capacity: each simulated step is one generation, and a long episode with a reasoning simulator can cost more tokens than the policy's own turns. Executable environments scale with containers and databases; their marginal rollout cost is low once built, but synthesizing a thousand of them is a pipeline that needs its own validation (does each verifier accept a correct solution and reject an incorrect one?). Coverage limits both. UI-Simulator (Wang et al. 2025) trained web and Android agents on LLM-generated UI states and transitions with results rivalling agents trained on real interfaces, and Li et al. (2025, "From Word to World") found that text world models help agents through action verification, synthetic trajectories and RL warm-starts, but that the benefit depends on how well training data covers agent behaviour and on environment complexity. An exploiting policy moves exactly away from that coverage.

Health models as environments. The same pattern applies if a patient-timeline model such as ETHOS were used to train a care policy: a policy rewarded for lower simulated mortality would seek sequences where the model is optimistic, and a model trained on observational records offers no guarantee that its predictions under chosen actions are causal. Such use needs an executable-check equivalent, such as held-out outcome evaluation or causal adjustment.

Evaluating World Models

A world model should be evaluated by what it is for, and prediction error is almost never what it is for. A control model exists to produce good decisions, a simulator to produce worlds that respond correctly to actions, and a forecaster to produce calibrated probabilities. Each of those can diverge from low next-step loss, and the history of the field is a sequence of models that looked good on the cheap metric and failed on the real one.

Three gaps explain most of the divergence, and good evaluation suites probe each separately:

  1. One-step versus multi-step. Teacher-forced next-step error is measured with real context; deployment runs on the model's own outputs, where errors compound. Measure open-loop rollouts at the horizons you will actually use.
  2. Prediction versus decision. Lower likelihood does not reliably mean higher reward (Lambert et al. 2020). Measure the decisions made with the model, in the real environment.
  3. Appearance versus mechanism. A model can render plausible frames while getting physics, object permanence or action effects wrong. Measure the mechanism with targeted tests, not overall realism.
Illustrative growth of rollout error with horizon for a teacher-forced model and a model trained on its own rollouts.
Fig. Why one-step metrics mislead. Two models with similar one-step error diverge sharply over long rollouts when one feeds its own errors back as input (teacher-forced training) and the other was trained to handle them (noise augmentation, self forcing, multi-step losses). The dashed line marks an arbitrary "still useful" threshold; the usable horizon is where each curve crosses it. Illustrative: curves follow \(e_k = \epsilon\,((1+\delta)^k - 1)/\delta\) with made-up \(\epsilon, \delta\).

The curve in the figure comes from a simple model of error feedback: if each step adds a fresh error \(\epsilon\) and amplifies the existing error by a factor \(1 + \delta\), the error after \(k\) steps is \(e_k = \epsilon\,((1+\delta)^k - 1)/\delta\). For small \(\delta\) it grows roughly linearly; once \(\delta k\) approaches 1 it grows exponentially. Training on self-generated context mainly reduces \(\delta\), which is why it extends the usable horizon far more than reducing \(\epsilon\) would.

Let the real environment have transition kernel \(P(s_{t+1}\mid s_t,a_t)\) and the world model \(\hat P_\theta(s_{t+1}\mid s_t,a_t)\). Training usually minimizes a teacher-forced one-step loss, \(\mathcal L_1(\theta) = \mathbb E_{(s_t,a_t,s_{t+1})\sim\mathcal D}\,[-\log \hat P_\theta(s_{t+1}\mid s_t,a_t)]\), in which the conditioning state \(s_t\) is always real. Each of the three gaps is a way in which the quantity of interest differs from \(\mathcal L_1\).

One-step versus multi-step. Let \(e_k\) be the distance between the imagined and the real state after \(k\) self-fed steps. Suppose each step adds a fresh error \(\epsilon\) (what \(\mathcal L_1\) measures) and amplifies the inherited error by \(1+\delta\), with \(\delta\ge 0\) a feedback gain that reflects how badly the model handles slightly wrong inputs. Then

\[ e_{k+1} = (1+\delta)\,e_k + \epsilon,\quad e_0 = 0 \;\;\Longrightarrow\;\; e_k = \epsilon\sum_{j=0}^{k-1}(1+\delta)^j = \epsilon\,\frac{(1+\delta)^k-1}{\delta}. \]

For \(\delta k \ll 1\), \(e_k\approx \epsilon k\); for \(\delta k \gtrsim 1\) growth is exponential. Solving \(e_k = \tau\) for a usefulness threshold \(\tau\) gives the usable horizon

\[ k^\star = \left\lfloor \frac{\ln(1+\tau\delta/\epsilon)}{\ln(1+\delta)} \right\rfloor . \]

The horizon depends on \(\epsilon\) only through a logarithm but on \(\delta\) in both numerator and denominator, so training on self-generated context (noise augmentation, self forcing, multi-step losses), which mainly lowers \(\delta\), buys far more horizon than an equal relative cut in one-step error.

Prediction versus decision. With real return \(J(\pi) = \mathbb E_{P,\pi}[\sum_t\gamma^t r_t]\) and model return \(\hat J_\theta(\pi)\) under \(\hat P_\theta\), a control user cares about \(J(\hat\pi_\theta)\) for \(\hat\pi_\theta = \arg\max_\pi \hat J_\theta(\pi)\). \(\mathcal L_1\) averages over the data distribution \(\mathcal D\), whereas the optimizer concentrates on states where \(\hat J_\theta\) is most optimistic, so a lower \(\mathcal L_1\) need not raise \(J(\hat\pi_\theta)\).

Appearance versus mechanism. A world model is a conditional distribution \(\hat P(x_{1:K}\mid c, a_{1:K})\) over futures given context and actions. A realism metric compares only the marginal \(\mathbb E_{c,a}\hat P(x_{1:K}\mid c,a)\) with the real marginal, and many conditionals, including ones that ignore \(a\), share the same marginal. Testing mechanism means testing the conditional.

The first evaluation utility a world-model project needs turns an open-loop error curve into a usable horizon. The script below implements the compounding recursion \(e_{k+1} = (1+\delta)e_k + \epsilon\) in closed form, inverts it for the largest horizon whose error stays under a threshold \(\tau\), and fits \(\epsilon\) and \(\delta\) to a measured curve by regressing \(e_{k+1}\) on \(e_k\). It compares a teacher-forced model with slightly lower one-step error against a model trained on its own rollouts, then recovers the parameters of the first from a noisy synthetic curve.

"""Open-loop error growth, usable horizon, and fitting (eps, delta) to a measured error curve."""
import math
import numpy as np

def rollout_error(eps, delta, k):
    """Error after k self-fed steps of e_{j+1} = (1 + delta) e_j + eps, e_0 = 0."""
    return eps * k if delta == 0 else eps * ((1 + delta) ** k - 1) / delta

def usable_horizon(eps, delta, tau):
    """Largest k with rollout_error(k) <= tau."""
    if delta == 0:
        return math.floor(tau / eps)
    return math.floor(math.log(1 + tau * delta / eps) / math.log(1 + delta))

def fit_eps_delta(curve):
    """Least squares on e_{k+1} = (1 + delta) e_k + eps, with curve = [e_1, e_2, ...]."""
    e = np.concatenate([[0.0], curve])
    X = np.stack([e[:-1], np.ones(len(e) - 1)], axis=1)
    slope, eps = np.linalg.lstsq(X, e[1:], rcond=None)[0]
    return eps, slope - 1

if __name__ == "__main__":
    tau = 0.5
    models = {"teacher-forced": (0.010, 0.050), "self-forced": (0.012, 0.005)}
    for name, (eps, delta) in models.items():
        print(f"{name:15s} e1={rollout_error(eps, delta, 1):.3f} "
              f"e15={rollout_error(eps, delta, 15):.3f} e100={rollout_error(eps, delta, 100):.2f} "
              f"horizon={usable_horizon(eps, delta, tau)}")
    # Recover (eps, delta) from a noisy measured curve (average over many rollouts).
    rng = np.random.default_rng(0)
    k = np.arange(1, 31)
    measured = rollout_error(0.010, 0.050, k) * (1 + 0.02 * rng.standard_normal(len(k)))
    eps_hat, delta_hat = fit_eps_delta(measured)
    print(f"fitted eps={eps_hat:.4f} delta={delta_hat:.4f} "
          f"predicted horizon={usable_horizon(eps_hat, delta_hat, tau)}")
    for eps, delta in models.values():           # the floor in the horizon formula is tight
        h = usable_horizon(eps, delta, tau)
        assert rollout_error(eps, delta, h) <= tau < rollout_error(eps, delta, h + 1)

It prints error at 1, 15 and 100 steps, the usable horizon at \(\tau = 0.5\), and the fitted parameters:

teacher-forced  e1=0.010 e15=0.216 e100=26.10 horizon=25
self-forced     e1=0.012 e15=0.186 e100=1.55 horizon=37
fitted eps=0.0098 delta=0.0514 predicted horizon=25

The teacher-forced model wins at one step (0.010 against 0.012) and loses at every horizon that matters: 25 usable steps against 37, and an error at 100 steps seventeen times larger. The regression recovers \(\delta\) to within a few percent from a 30-step curve, which is enough to predict the horizon. Two cautions apply to real curves. A pixel metric saturates once a rollout has drifted into a different but plausible future, which bends the curve downward and can produce a negative fitted \(\delta\); fit only the early, pre-saturation part, or fit in a feature space whose distances keep growing. Per-rollout errors are heavy-tailed, so the curve should be averaged over a few hundred rollouts before fitting.

In practice, world-model evaluation is a budgeting problem. The tests that most directly measure usefulness (closed-loop task success, human preference, physics suites) are the most expensive, and the cheapest (teacher-forced loss) is the least informative. For a generative simulator, evaluation cost scales with the number of generated frames, and frames are produced at roughly deployment speed, so a full suite cannot run on every change. The standard design is a tiered pipeline in which cheap checks gate expensive ones.

TierTriggerContentsGate
Per changetraining-code or data changeteacher-forced loss; open-loop error at a few horizons; action-sensitivity smoke testno horizon worse than its run-to-run noise band
Nightlylatest checkpointFVD at short and long windows; loop closure; no-op drift; physics probe subsetwithin the release band
Releasecandidate checkpointclosed-loop task success; full physics suite; human preference; exploitability attacknot worse than the previous release at a stated confidence

Table. A three-tier evaluation pipeline. Gates compare against noise bands measured by rerunning one checkpoint with different seeds, not against fixed thresholds.

Monitoring. The dashboard that exposes regressions plots error against horizon, one line per checkpoint, with the seed noise band. A change that lowers the one-step point while raising the long-horizon point is the signature of the horizon gap; a change that improves FVD while lowering action sensitivity is the signature of the mechanism gap. A common cause of the first is a data-mixture change toward static scenes, which teaches the model that copying the previous frame is cheap and raises its feedback gain; noise-augmented conditioning frames are the usual corrective.

Evidence from 2025–2026 benchmarks. Large comparative studies confirm that the gaps are not hypothetical. WorldArena (Shang et al. 2026) scored 14 embodied world models both on video quality and on use as a data engine, policy evaluator and planner, and reported a perception–functionality gap: its perception score tracked human judgment closely (Pearson r = 0.825) but tracked planning success only weakly (r = 0.360). Every reported number therefore needs its protocol (extractor, window, clip count, seeds, held-out split) attached, and the release decision rests on the closed-loop tier.

FVD and Why It Is Not Enough

Unterthiner et al. (2018) proposed the Fréchet Video Distance, which embeds real and generated videos with a pretrained action-recognition network and compares the two feature distributions:

\[ \mathrm{FVD} = \|\mu_r - \mu_g\|^2 + \mathrm{Tr}\!\left(\Sigma_r + \Sigma_g - 2(\Sigma_r \Sigma_g)^{1/2}\right), \]

where \(\mu_r, \Sigma_r\) and \(\mu_g, \Sigma_g\) are the mean and covariance of the features for real and generated clips. FVD was a large step forward for video generation, but as a world-model metric it has structural blind spots:

  • It compares distributions of clips, so a model can score well while never responding to actions, as long as its clips look like typical clips.
  • It inherits the feature extractor's notion of similarity, which is tuned for recognizing human actions in short clips, not for physics or long-range consistency.
  • It is computed on short windows, so it says little about drift over minutes or about whether a revisited location still looks the same.

Suites such as VBench (Huang et al. 2024) decompose video quality into many dimensions (subject consistency, motion smoothness, temporal flicker and so on) and validate them against human preference, which is more diagnostic than one number. They still measure how video looks rather than whether a model can be controlled.

Definition. Let \(\phi\) map a clip \(v\) to features \(\phi(v)\in\mathbb R^d\) using a frozen network (an I3D action classifier in the original FVD). Real clips yield sample mean and covariance \(\mu_r,\Sigma_r\), generated clips \(\mu_g,\Sigma_g\). FVD is the Fréchet distance between the two fitted Gaussians,

\[ \mathrm{FVD} = \|\mu_r-\mu_g\|_2^2 + \mathrm{Tr}\!\left(\Sigma_r+\Sigma_g-2(\Sigma_r\Sigma_g)^{1/2}\right), \]

which equals the squared 2-Wasserstein distance between \(\mathcal N(\mu_r,\Sigma_r)\) and \(\mathcal N(\mu_g,\Sigma_g)\). In one dimension it reduces to \((\mu_r-\mu_g)^2+(\sigma_r-\sigma_g)^2\); for \(\mathcal N(0,1)\) against \(\mathcal N(0.5,0.8^2)\) it is \(0.25+0.04 = 0.29\).

Finite-sample bias. With \(N\) clips per set drawn from the same distribution with covariance \(\Sigma\), the estimated means still differ, and \(\mathbb E\|\hat\mu_r-\hat\mu_g\|^2 = 2\,\mathrm{Tr}(\Sigma)/N\); the covariance term adds a positive bias of the same \(O(1/N)\) order. FVD is biased upward, and values computed with different \(N\) are not comparable. With \(d = 400\), fewer than 400 clips make \(\hat\Sigma\) singular, one reason FVD sets hold thousands of clips.

Action blindness. A world model defines \(\hat P(v\mid c,a)\). FVD compares only the marginal \(\hat P(v) = \mathbb E_{c,a}\hat P(v\mid c,a)\) with \(P(v)\). A model that samples from the correct marginal regardless of \(a\) attains the same expected FVD as a perfect model. Conditioning restores the link:

\[ \mathrm{FD}_{\text{cond}} = \mathbb E_{a}\Big[\mathrm{FD}\big(P(\phi(v)\mid a),\,\hat P(\phi(v)\mid a)\big)\Big]. \]

If real features shift by \(\pm 2\) along one axis with action right or left (unit noise), an action-blind model has the right marginal, but conditioned on "right" its feature has mean 0 and variance \(1+4 = 5\) against mean 2 and variance 1. The one-axis conditional distance is \(4 + (1+5-2\sqrt5) \approx 5.53\).

Assumptions. The Gaussian summary ignores higher moments; the extractor defines similarity, so changing it changes the metric; conditional FD multiplies the clip budget by the number of action buckets to keep each bucket's bias small.

The script computes the Fréchet distance from feature arrays of shape (N, d), measures its bias when both sets come from one distribution, and shows on synthetic features why an action-blind model passes the unconditional score but fails a per-action one. In a real pipeline the features come from a frozen video network applied to clips; drawing them directly makes the ground truth known.

"""Frechet distance on clip features: exact value, sample-size bias, and blindness to actions."""
import numpy as np
from scipy import linalg

def frechet(mu1, s1, mu2, s2):
    covmean = linalg.sqrtm(s1 @ s2).real          # drop round-off imaginary parts
    return float(np.sum((mu1 - mu2) ** 2) + np.trace(s1 + s2 - 2 * covmean))

def fd(f_real, f_gen):
    """f_*: (N, d) clip embeddings (I3D features in FVD)."""
    return frechet(f_real.mean(0), np.cov(f_real, rowvar=False),
                   f_gen.mean(0), np.cov(f_gen, rowvar=False))

def conditional_fd(f_real, f_gen, actions):
    return float(np.mean([fd(f_real[actions == a], f_gen[actions == a])
                          for a in np.unique(actions)]))

if __name__ == "__main__":
    rng, d = np.random.default_rng(0), 16
    print(f"1-D N(0,1) vs N(0.5,0.8^2): {frechet(np.zeros(1), np.eye(1), np.full(1, .5), .64 * np.eye(1)):.4f}")
    for n in (256, 2048):                         # same distribution, still FD > 0
        v = np.mean([fd(rng.normal(size=(n, d)), rng.normal(size=(n, d))) for _ in range(5)])
        print(f"same distribution, N={n:4d}: FD={v:.3f}")
    n = 2048
    a = rng.integers(0, 2, size=n)                # commanded action: 0 = left, 1 = right
    def clips(follow):
        sign = np.where(a == 1, 1.0, -1.0) if follow else rng.choice([-1.0, 1.0], size=n)
        f = rng.normal(size=(n, d)); f[:, 0] += 2 * sign
        return f
    real, follows, ignores = clips(True), clips(True), clips(False)
    print(f"unconditional FD: follows {fd(real, follows):.3f}  ignores {fd(real, ignores):.3f}")
    print(f"per-action FD:    follows {conditional_fd(real, follows, a):.3f}  "
          f"ignores {conditional_fd(real, ignores, a):.3f}")

It prints the hand-checkable 1-D value, the same-distribution bias at two sample sizes, and both scores for the two models:

1-D N(0,1) vs N(0.5,0.8^2): 0.2900
same distribution, N= 256: FD=0.622
same distribution, N=2048: FD=0.080
unconditional FD: follows 0.096  ignores 0.096
per-action FD:    follows 0.169  ignores 5.873

The 1-D case reproduces 0.29. Two samples of the same distribution score 0.62 at 256 clips and 0.08 at 2,048, the \(1/N\) bias at work. The last two lines carry the main point: the unconditional distance gives identical scores to a model that follows actions and one that ignores them, while the per-action distance separates them by a factor of about 35. Two implementation details matter. scipy.linalg.sqrtm can return tiny imaginary parts when \(\Sigma_r\Sigma_g\) is nearly singular, so only the real part is kept. np.cov must be called with rowvar=False; transposing by mistake yields an \(N\times N\) covariance and a meaningless score.

FVD is cheap to report and easy to optimize, which makes it a tempting release gate for video world models. Used alone it rewards changes that sharpen frames or reduce motion and stays silent about controllability. A typical failure: lowering the sampling temperature of a token-based simulator lowers FVD, because the sampler favors the most common continuation (walking forward), while turns become sluggish. The marginal improves and the turn conditionals degrade.

Protocol fieldWhy it must be fixed
Extractor and weights hashdefines what "similar" means
Frames per clip, stride, frame ratelonger windows expose drift
Resolution and resize filterresizing changes features
Clip count for real and generated setsbias scales as \(1/N\)
Real reference set (held-out maps or episodes)different references give different baselines
Generation seeds and sampler settingstemperature and guidance trade realism for diversity

Table. FVD protocol card. A report that changes any row is a new metric, not a new value of the old one.

Making it trustworthy. Four numbers turn FVD into a usable nightly signal: the real-versus-real score of two disjoint halves of the reference set (the noise floor); the run-to-run spread of one checkpoint over several seed sets; the score of real clips with frames shuffled in time, which measures whether the extractor sees motion at all (Ge et al. 2024 found FVD nearly insensitive to large temporal corruption and recommended features from self-supervised video models); and conditional FVD per action bucket, used as a co-gate.

Choosing a suite. For visual quality, pinned FVD is adequate. For diagnosis, VBench or VBench-2.0 (Zheng et al. 2025), which adds controllability, physics and commonsense dimensions scored by vision-language models, localizes failures at the cost of trusting several automatic judges. For controllability, no marginal metric suffices.

Testing Physical Understanding

A wave of 2024–2025 benchmarks asks the sharper question of whether video models capture physical mechanisms, and their answer so far is "less than they appear to":

  • Physics-IQ. Motamed et al. (2025) built real-world test videos whose continuation requires understanding of fluid dynamics, optics, solid mechanics, magnetism or thermodynamics. Across the generators they tested, physical understanding was weak and unrelated to visual realism; their summary is that realism does not imply physical understanding.
  • Controlled physical laws. Kang et al. (2024) trained video models on a 2D mechanics simulator and found near-perfect in-distribution generalization, partial combinatorial generalization, and failure out of distribution that scaling did not fix. The models appeared to generalize by retrieving similar training cases, prioritizing color over size, size over velocity and velocity over shape when attributes conflicted.
  • World generation. Duan et al. (2025) introduced WorldScore, which recasts world generation as a sequence of next-scene tasks specified by a camera trajectory and text, so that 3D, 4D and video generators can be compared on controllability, quality and dynamics over 3,000 test cases.

Motion masks. For a grey-scale video \(V\in[0,1]^{T\times H\times W}\), the motion mask at step \(t\) marks pixels whose intensity changed by more than a threshold \(\eta\): \(M_t(i,j) = \mathbb 1[\,|V_{t+1}(i,j)-V_t(i,j)|>\eta\,]\). With \(\hat M\) for the prediction, \(M\) for a real take and \(\mathrm{IoU}(A,B) = |A\cap B|/|A\cup B|\), the Physics-IQ-style overlap metrics are

\[ \text{spatial} = \mathrm{IoU}\big(\textstyle\bigvee_t\hat M_t,\ \bigvee_t M_t\big),\qquad \text{spatiotemporal} = \tfrac{1}{T-1}\textstyle\sum_t \mathrm{IoU}(\hat M_t, M_t), \] \[ \text{weighted} = \frac{\sum_{ij}\min(\bar{\hat M}_{ij},\bar M_{ij})}{\sum_{ij}\max(\bar{\hat M}_{ij},\bar M_{ij})},\qquad \bar M_{ij} = \tfrac{1}{T-1}\textstyle\sum_t M_t(i,j). \]

They ask where motion occurs, where and when, and how much; a pixel MSE adds how it looks. Scores are normalized so that a second real take of the same experiment, the physical variance, equals 100%. If both masks are empty at a step the IoU is 1, so a model that predicts no motion earns credit whenever nothing should move; that floor must be measured before low scores are read.

Law fits. When the governing law is known, fitting its parameters to the model's output is sharper. For a tracked falling object with heights \(y_k\) at \(t_k = k\Delta t\), least squares on design rows \(X_k = (1,t_k,t_k^2)\) gives \(\hat\beta = (X^\top X)^{-1}X^\top y\) and \(\hat g = 2\hat\beta_3\). A rendering that moves the object at constant speed returns \(\hat g = 0\) however realistic its frames.

Generalization regimes. Following Kang et al., let each training clip have attributes \(z = (\text{color},\text{size},\text{velocity},\text{shape})\). In-distribution tests draw \(z\) from the training support; combinatorial tests use seen values in unseen combinations; out-of-distribution tests use unseen values. A model that has learned the law is invariant to the regime; one that retrieves the nearest training case degrades from the first to the third.

Small samples. Correlations across a handful of models are weak evidence. With \(n = 8\) models, \(|r|\) must exceed about 0.71 for significance at 5%, so "realism did not predict physical understanding" is the defensible reading, not proven independence.

The script re-implements simplified Physics-IQ-style mask metrics and a gravity probe on synthetic 32×32 videos of a falling disc at 10 frames per second. Two real takes differ only in a small initial velocity; the second take sets the ceiling of 100. Two flawed models are scored against them: one moves the disc down at constant speed, one leaves it frozen. The score sums the three overlap metrics and normalizes by the second take; the published benchmark also folds in an MSE term, omitted here.

"""Physics-IQ-style motion-mask scores and a fitted-gravity probe on synthetic falling-ball videos."""
import numpy as np

def masks(video, thresh=0.1):                     # (T, H, W) -> (T-1, H, W) changed pixels
    return np.abs(np.diff(video, axis=0)) > thresh

def iou(a, b):
    u = np.logical_or(a, b).sum()
    return 1.0 if u == 0 else float(np.logical_and(a, b).sum() / u)

def metrics(pred, real):
    mp, mr = masks(pred), masks(real)
    spatial = iou(mp.any(0), mr.any(0))                         # where motion happens
    st = float(np.mean([iou(p, r) for p, r in zip(mp, mr)]))    # where and when
    wp, wr = mp.mean(0), mr.mean(0)                             # how much, per pixel
    weighted = float(np.minimum(wp, wr).sum() / max(np.maximum(wp, wr).sum(), 1e-9))
    return spatial, st, weighted

def ball(ys, H=32, W=32, x=16, r=2):
    yy, xx = np.mgrid[:H, :W]
    return np.stack([((yy - y) ** 2 + (xx - x) ** 2 <= r * r).astype(float) for y in ys])

def fitted_g(ys, dt):                             # y = y0 + v t + g t^2 / 2
    return float(2 * np.polyfit(np.arange(len(ys)) * dt, ys, 2)[0])

if __name__ == "__main__":
    fps, T, g = 10, 50, 9.0
    t = np.arange(T) / fps
    fall = lambda v0: np.clip(2 + v0 * t + 0.5 * g * t ** 2, 0, 29)   # rests on floor at row 29
    real_a, real_b = ball(fall(0.0)), ball(fall(0.3))                 # two physical takes
    linear = np.clip(2 + 3 * t, 0, 29)
    ceiling = sum(metrics(real_b, real_a))
    for name, v in [("second real take", real_b), ("constant velocity", ball(linear)),
                    ("frozen", ball(np.full(T, 2.0)))]:
        s, st, w = metrics(v, real_a)
        print(f"{name:17s} spatial={s:.2f} st={st:.2f} weighted={w:.2f} "
              f"score={100 * (s + st + w) / ceiling:5.1f}")
    print(f"fitted g: real {fitted_g(fall(0.0)[:7], 1 / fps):.2f}, "
          f"constant velocity {abs(fitted_g(linear[:7], 1 / fps)):.2f}")

It prints the three overlap metrics and normalized score for each video, then the fitted acceleration over the first seven frames of free fall:

second real take  spatial=0.96 st=0.74 weighted=0.95 score=100.0
constant velocity spatial=0.54 st=0.16 weighted=0.48 score= 44.2
frozen            spatial=0.00 st=0.53 weighted=0.00 score= 20.0
fitted g: real 9.00, constant velocity 0.00

The constant-velocity model passes through the right column, so it earns about half the spatial and weighted credit, but it is rarely in the right place at the right frame (spatiotemporal 0.16). The frozen model's entire score of 20 comes from frames after the real disc has landed, when both masks are empty: this is the do-nothing floor. The law fit separates the cases cleanly, 9.00 rows/s² against 0. Practical checks: if every model scores near the ceiling, \(\eta\) is too high and masks are empty everywhere; if the second take scores poorly against the first, the takes are misaligned in time and should be aligned on a visible event such as the moment of release.

Optimizing a video world model for speed, resolution or human preference can degrade its physics without any perceptual metric noticing, because realism and physical accuracy move independently. A typical case is step distillation for real-time play: the faster student keeps FVD and rater preference while losing accuracy in collisions and fluids, where physics is concentrated in a few frames. The physics suite therefore needs to be a separate gate with its own statistics.

Unit of analysis. Physics benchmarks are small (Physics-IQ has 66 scenarios), and between-scenario variation dominates within-scenario variation, so per-clip confidence intervals are too narrow. Both checkpoints are run on the same scenarios, the per-scenario score difference is computed, and a bootstrap resamples scenarios with all their views and takes together. Pairing removes the between-scenario variance and makes a small suite usable as a gate.

SignalCadencePurpose
Real-experiment mask score, paired bootstrap over scenariosreleasegate
Per-category score (fluids, optics, solids, magnetism, heat)releaselocalize a regression
Law-fit probes on synthetic clipsnightlycheap early warning
Frozen-frame baseline scorewhen thresholds changesanity check on \(\eta\)
In-distribution minus out-of-distribution scorereleasedetect case-based generalization

Table. Physics evaluation signals. The scenario, not the clip, is the independent unit.

Choosing suites. Real-experiment suites such as Physics-IQ are faithful but small and costly to extend. Synthetic suites with known laws, in the style of Kang et al., give unlimited data and clean out-of-distribution splits and are the best detector of retrieval-like generalization, though they may not transfer to real footage. Judged suites (VBench-2.0's physics dimension, WorldScore's dynamics scores) cover more phenomena but measure plausibility as a judge sees it. Teams commonly use all three: a held-out real suite as the release gate, synthetic probes nightly and judged suites for coverage, while keeping probe scenarios out of any distillation or fine-tuning objective so that the gate is not overfitted.

Controllability, Counterfactuals and Closed-Loop Tests

The strongest evaluations put the world model inside a decision loop and measure task success, because that is the only test that cannot be passed by looking right. Zhang et al. (2025) made this the organizing principle of World-in-World, a benchmark that plugs generative world models into a shared planner and action interface across four embodied environments and scores task success. Their findings line up with the rest of this part:

  • Controllability matters more than visual quality; realistic video does not ensure an agent succeeds.
  • Post-training on action–observation data improves closed-loop results more than switching to a bigger pretrained video generator.
  • Spending more inference compute on planning substantially improves results.

Beyond full closed-loop tasks, four targeted tests catch common failures cheaply:

  • Action sensitivity. Roll out the same context under different actions and check that the futures differ in the right way (moving left goes left) and that a no-op leaves the scene still. A model that ignores actions passes FVD and fails this immediately.
  • Counterfactual consistency. Intervene on one factor (remove an obstacle, change a dose) and check that only its consequences change. In discrete domains, the compression and distinction tests of Vafa et al. (2024) formalize this.
  • Loop closure. Move away from a location and come back; the scene should match. This directly measures memory and long-horizon consistency.
  • Exploitability. Train or search a policy against the model and evaluate it in the real environment; the gap between imagined and real return measures how much of the model's error an optimizer can find.
World-model typePrimary metricsDiagnostic testsTypical failure modes
Control (Dreamer, MuZero, TD-MPC2)Real-environment return; sample efficiencyOpen-loop prediction at planning horizon; imagined vs real return gapPolicy exploits model errors; reward head overfits; drops small decision-relevant details
Video / interactive simulatorHuman preference; FVD/VBench; WorldScoreAction sensitivity; loop closure; physics probes (Physics-IQ); minutes-long rolloutsDrift; forgetting off-screen content; ignoring or misreading actions; plausible but wrong physics
Latent (JEPA, DINO-WM)Downstream probe accuracy; planning success to goalsPost-hoc decoders; collapse checks (embedding variance)Representation collapse; silently discarded details; poor coverage of action space
LLM world modelsAgent success with the simulator; state-prediction accuracyProbing and intervention; Myhill–Nerode compression/distinction; consistency across paraphrased statesInconsistent state tracking; hallucinated tool outputs; rewards that can be talked into success
Domain (health, driving)Calibration and discrimination of forecasts; scenario fidelitySubgroup and temporal-shift tests; simulated vs observed cohort statisticsLearning care patterns rather than biology; miscalibration under shift; confounded "interventions"

Table. Evaluation by world-model type. The left two columns say what to report; the right two say what to look for before believing the report.

Simulation bound. For a policy \(\pi\), horizon \(H\) and rewards in \([0,R_{\max}]\), let \(J(\pi)\) and \(\hat J(\pi)\) be the undiscounted \(H\)-step returns under \(P\) and \(\hat P\). If \(\mathrm{TV}\big(P(\cdot\mid s,a),\hat P(\cdot\mid s,a)\big)\le\epsilon\) on the states and actions \(\pi\) visits, a coupling argument shows the state distributions at step \(k\) differ by at most \(k\epsilon\) in total variation. Since \(|\mathbb E_p f - \mathbb E_q f|\le R_{\max}\mathrm{TV}(p,q)\) for \(f\in[0,R_{\max}]\),

\[ |J(\pi)-\hat J(\pi)| \;\le\; R_{\max}\,\epsilon\sum_{k=0}^{H-1}k \;=\; R_{\max}\,\epsilon\,\frac{H(H-1)}{2}. \]

The bound is quadratic in horizon: at \(H = 15\), the imagination horizon of DreamerV3, the factor is 105; at \(H = 30\) it is 435. Crucially, \(\epsilon\) is measured on the policy's own state distribution, which an optimizer pushes toward poorly modeled regions.

Exploitability. With \(\hat\pi = \arg\max_\pi\hat J(\pi)\), define \(\Delta_{\text{exploit}} = \hat J(\hat\pi) - J(\hat\pi)\). It grows with optimizer strength, so it is a property of the (model, optimizer) pair and must be reported with the optimizer and its budget.

Action sensitivity and loop closure. For context \(c\), an action set \(\mathcal A\) including a no-op \(\varnothing\), and \(K\)-step end states \(\hat s_K(c,a)\) and \(s_K(c,a)\),

\[ \rho = \frac{\max_{a,a'}\|\hat s_K(c,a)-\hat s_K(c,a')\|}{\max_{a,a'}\|s_K(c,a)-s_K(c,a')\|}, \]

which is 1 for correctly sized effects, 0 when actions are ignored and above 1 when they are exaggerated; the no-op drift is \(\|\hat s_K(c,\varnothing)-s_0\|\). Applying \(a_{1:K}\) then its inverse gives the loop-closure error \(\|\hat s_{2K}-s_0\|\), which grows as \(2Kb\) under a per-step drift \(b\).

Compression and distinction. If the true world is a deterministic finite automaton, two prefixes reach the same state exactly when they admit the same continuations (Myhill–Nerode). Vafa et al. test a sequence model for compression (prefixes reaching one true state receive the same continuation set) and distinction (prefixes reaching different states are separated by the continuations that distinguish them). A model can predict valid next tokens almost always and fail both, because next-token validity looks only one step past each prefix.

An evaluation harness for a new world model runs in a fixed order, and the code below implements its middle steps. The order is: (1) fix the use case and the horizon it requires; (2) hold out along the axes that will shift (environment, map, robot, hospital, time period) rather than random clips; (3) report open-loop error as a curve up to the deployment horizon; (4) test action sensitivity, including a do-nothing action; (5) run loop-closure and counterfactual probes; (6) close the loop and report the imagined-versus-real return gap beside the real return; (7) let an optimizer search for the highest imagined reward and treat any sequence that scores well in the model but fails in reality as a model bug; (8) for stochastic outputs (outcomes, event times), check calibration and coverage rather than only the mode.

The script applies steps 4–7 to a 1-D world \(x' = x + a\), \(a\in[-1,1]\), with reward \(-|x'-8|\) and horizon 15. Four learned models are compared: an accurate one, one that ignores actions, one with a constant drift of 0.1 per step, and one with a spurious "portal" that teleports to the goal from a region the data never covered. The attacker is a random-shooting planner over 2,000 action sequences.

"""Four probes on a toy 1-D world: action sensitivity, no-op drift, loop closure, exploitability."""
import numpy as np

GOAL, H = 8.0, 15

def true_step(x, a):
    a = np.clip(a, -1, 1)
    return x + a, -abs(x + a - GOAL)

class Model:
    """Learned dynamics x' = x + gain*a + drift, optionally with a spurious 'portal' to the goal."""
    def __init__(self, gain=1.0, drift=0.0, portal=False):
        self.gain, self.drift, self.portal = gain, drift, portal
    def step(self, x, a):
        a = np.clip(a, -1, 1)
        nx = GOAL if (self.portal and -3 <= x < -2 and a < -0.5) else x + self.gain * a + self.drift
        return nx, -abs(nx - GOAL)

def rollout(step, x0, actions):
    x, xs, ret = x0, [], 0.0
    for a in actions:
        x, r = step(x, a); xs.append(x); ret += r
    return np.array(xs), ret

def sensitivity(m, k=10):                         # spread of end states: model / truth; no-op drift
    end = lambda step, a: rollout(step, 0.0, [a] * k)[0][-1]
    em = [end(m.step, a) for a in (-1, 0, 1)]
    et = [end(true_step, a) for a in (-1, 0, 1)]
    return (max(em) - min(em)) / (max(et) - min(et)), abs(em[1])

def loop_closure(m, k=5):                         # k steps right, k steps left
    return abs(rollout(m.step, 0.0, [1.0] * k + [-1.0] * k)[0][-1])

def exploitability(m, n=2000, seed=0):            # random-shooting planner attacks the model
    cands = np.random.default_rng(seed).uniform(-1, 1, size=(n, H))
    rets = [rollout(m.step, 0.0, c)[1] for c in cands]
    best = cands[int(np.argmax(rets))]
    real = rollout(true_step, 0.0, best)[1]
    return max(rets), real, max(rets) - real

if __name__ == "__main__":
    for name, m in {"accurate": Model(), "ignores actions": Model(gain=0.0),
                    "drifts": Model(drift=0.1), "phantom portal": Model(portal=True)}.items():
        rho, noop = sensitivity(m)
        im, real, gap = exploitability(m)
        print(f"{name:15s} rho={rho:.2f} noop={noop:.2f} loop={loop_closure(m):.2f} "
              f"imagined={im:7.2f} real={real:7.2f} gap={gap:6.2f}")

It prints, per model, the action-sensitivity ratio, no-op drift, loop-closure error, and the imagined and real return of the planner's best sequence:

accurate        rho=1.00 noop=0.00 loop=0.00 imagined= -49.89 real= -49.89 gap=  0.00
ignores actions rho=0.00 noop=0.00 loop=0.00 imagined=-120.00 real=-119.39 gap= -0.61
drifts          rho=1.00 noop=1.00 loop=1.00 imagined= -37.89 real= -49.89 gap= 12.00
phantom portal  rho=0.50 noop=0.00 loop=0.00 imagined= -31.87 real=-160.32 gap=128.45

No single probe catches every failure. The action-blind model is flagged by \(\rho = 0\) and has nothing to exploit. The drifting model passes action sensitivity but fails no-op drift and loop closure, and the planner turns the drift into an imagined gain of 12. The portal model passes loop closure (the loop never visits the portal) and is only partly flagged by \(\rho\), yet the attack exposes it decisively: the planner walks away from the goal, and real return collapses to −160 while imagined return is −32. The planner is seeded because different searches find different model errors.

Closed-loop evaluation is the test that matters for planning and control, and it is the most expensive and the noisiest. Each decision needs several imagined rollouts plus a real step, so for a video simulator a closed-loop suite can cost several times a full FVD run; World-in-World's finding that more planning compute improves success has a direct price. Task success also varies across training seeds, which are the independent unit for a training change. Detecting a difference \(\Delta\) at 5% significance with 80% power needs about \(n = 2(1.96+0.84)^2\sigma^2/\Delta^2\) seeds per arm, which for a 5% regression is often dozens; release gates therefore combine a few full seeds with cheap probes that respond to the same failures.

MetricDefinitionFailure it flags
Real return or task successreal environment, across seedsthe outcome itself
Imagined–real gapcritic's imagined return minus realized return on the same episodesexploitation of model errors
Open-loop error on policy stateserror at several imagined steps on states the policy visitshorizon too long for the model
Ensemble disagreementon policy states versus replay statespolicy entering unmodeled regions
Action sensitivity \(\rho\)imagined versus true action spreadignored or exaggerated actions

Table. Closed-loop dashboard for a Dreamer-style agent. The gap rows give early warning; the return row confirms.

A characteristic failure. Lengthening a Dreamer-style agent's imagination horizon for better credit assignment can raise the critic's imagined return while real return falls. If open-loop error on replay data and reward-head error are unchanged but error and ensemble disagreement on the policy's own states jump beyond the old horizon, the actor is steering imagination into regions the model has not seen. Remedies trade off: shorten the horizon (caps the quadratic term, weakens credit assignment); penalize imagined reward by ensemble disagreement (costs compute and slows exploration); collect real data where the policy goes (fixes the model, costs environment steps); attack with a stronger optimizer before release (finds the problem earlier, fixes nothing).

Recent evidence. WorldArena found that some world models used as policy evaluators reported higher success than the reference simulator, consistent with exploitation. WorldLens (Liang et al. 2025) found for driving world models that no model excels across generation, geometry, action following and downstream use. For video simulators, post-training on action–observation data, conditional metrics as gates and loop-closure checks for memory are the corresponding levers.

A Reference Architecture

Whatever the domain, a production world model is a pipeline of six parts: data, an encoder or tokenizer, a dynamics model, prediction heads, a consumer (a planner, a policy learner or a simulator API) and an evaluation loop that decides what data to collect next. The research families differ in which parts they emphasize, but leaving any part out is how projects fail: no tokenizer discipline and the dynamics model wastes capacity, no consumer and nobody knows whether predictions are good enough, no evaluation loop and errors are found by users.

Reference architecture for a world model system: data, encoder, dynamics, heads, planner or simulator API, and an evaluation loop feeding data collection. Data video, logs, events Encoder tokens or latents Dynamics model RSSM, transformer, diffusion Heads / decoder frames, reward, value Real world env or users Planner / policy MPC, imagination RL Simulator API step · reset · fork query rollouts serve act log new experience Evaluation loop open-loop error curves · action sensitivity · loop closure · physics probes closed-loop task success · imagined vs real gap · adversarial search · calibration collect more data
Fig. A reference architecture for world-model systems. The top row is the model; the middle row is how it is consumed, either by a planner or policy that acts in the real world or by a simulator API that other systems call; the bottom row is the evaluation loop, whose findings drive targeted data collection (dashed). The same skeleton fits Dreamer, an interactive video simulator, an LLM tool simulator and a patient-timeline forecaster.

A few interface decisions in this skeleton pay off disproportionately:

  • The simulator API should support fork. Branching many futures from one state is what planners, counterfactual analyses and evaluation probes all need; a model that can only be stepped forward from the start is much less useful.
  • Separate the encoder's training from the dynamics model's where possible. A frozen, well-tested tokenizer (as in Genie, Cosmos or V-JEPA 2-AC) makes the dynamics model cheaper to iterate and easier to debug.
  • Expose uncertainty. Ensembles, sample diversity or explicit variance heads let the planner avoid regions where the model is guessing and let the evaluation loop target them for data collection.

Formally, the six parts are maps with typed inputs and outputs. Data are trajectories \(\mathcal{D} = \{(o_t, a_t, r_t)\}\) of observations \(o_t\), actions \(a_t\) and rewards or labels \(r_t\). The encoder maps an observation, and any recurrent memory \(h_{t-1}\), to a state \(z_t = f_\phi(o_t, h_{t-1})\) with parameters \(\phi\). The dynamics model is a transition distribution \(z_{t+1} \sim p_\theta(\cdot \mid z_t, a_t)\) with parameters \(\theta\). Heads read the state: a reward \(\hat r_t = g_r(z_t)\), a continuation probability \(\hat c_t = g_c(z_t)\) and, where a decoder exists, a frame \(\hat o_t = g_o(z_t)\). A patient-timeline model has no external action; its state is the token history and its dynamics are \(p_\theta(x_{n+1} \mid x_{1:n})\).

Consumers. A planner or policy learner optimizes an objective defined only through the model,

\[ J_{\text{model}}(\pi) = \mathbb{E}_{p_\theta,\,\pi}\Big[\textstyle\sum_{k=0}^{H-1} \gamma^k \hat r_{t+k} + \gamma^H v(z_{t+H})\Big], \]

where \(H\) is the imagination horizon, \(\gamma\) the discount and \(v\) a learned value that covers what lies beyond \(H\). A simulator API exposes the same distribution as functions: \(\texttt{step}(s, a) \mapsto (s', y)\), which must leave \(s\) unchanged, and \(\texttt{fork}(s, n) \mapsto (s^{(1)}, \dots, s^{(n)})\), which returns copies with independent random streams, so that rollouts from the branches are conditionally independent draws given \(s\). This is what makes Monte Carlo estimation possible: any quantity \(q\) of the future is estimated as \(\hat q = \tfrac{1}{n}\sum_i q(\text{rollout}^{(i)})\), with standard error \(\sigma_q / \sqrt{n}\).

Uncertainty. For an ensemble of \(M\) members, member \(m\) predicting mean \(\mu_m\) and variance \(\sigma_m^2\), the law of total variance splits the predictive variance in two:

\[ \operatorname{Var}[y] = \underbrace{\tfrac{1}{M}\textstyle\sum_m \sigma_m^2}_{\text{aleatoric}} + \underbrace{\tfrac{1}{M}\textstyle\sum_m (\mu_m - \bar\mu)^2}_{\text{epistemic}}, \qquad \bar\mu = \tfrac{1}{M}\textstyle\sum_m \mu_m . \]

The first term is noise that more data cannot remove; the second is disagreement that shrinks where data are dense. The planner should be penalized by the second term, and the evaluation loop should collect data where it is large.

Evaluation and staging. The loop's central quantities are the open-loop error curve \(e(H) = \mathbb{E}\,\lVert \hat o_{t+H} - o_{t+H} \rVert\), computed on the model's own rollouts, and the imagined-versus-real gap \(\Delta(\pi) = J_{\text{model}}(\pi) - J_{\text{real}}(\pi)\). Separating encoder and dynamics training is a two-stage objective: \(\phi^* = \arg\min_\phi \mathcal{L}_{\text{enc}}(\phi)\), then \(\theta^* = \arg\min_\theta \mathcal{L}_{\text{dyn}}(\theta; f_{\phi^*})\) with \(\phi^*\) fixed. It replaces a joint, non-stationary problem with a stationary one, at the price of a representation that cannot adapt to what the dynamics and heads need.

A world model inside a working system is best read through the interface it offers its consumers. The sketch below implements the skeleton's three essential operations over a toy ensemble of linear-Gaussian latent dynamics. encode turns an observation into a state. step advances a state by one action and returns the predicted reward together with the ensemble's disagreement about it. fork copies a state into branches with independent random streams. The assertions check the properties a planner relies on: forking does not move the state, branches diverge because each has its own noise, and stepping does not mutate its input.

"""World-model service skeleton: encode, step, fork, with ensemble uncertainty."""
from dataclasses import dataclass
import numpy as np

@dataclass
class State:
    z: np.ndarray                 # (d,) latent
    rng: np.random.Generator      # per-branch random stream
    t: int = 0

class EnsembleWorldModel:
    """M linear-Gaussian dynamics members; disagreement = epistemic uncertainty."""
    def __init__(self, d=4, a_dim=2, members=5, seed=0):
        g = np.random.default_rng(seed)
        A0 = 0.9 * np.eye(d)
        self.A = [A0 + 0.02 * g.normal(size=(d, d)) for _ in range(members)]
        self.B = [0.1 * g.normal(size=(d, a_dim)) for _ in range(members)]
        self.w_r = g.normal(size=d)            # reward head
        self.sigma = 0.05                      # aleatoric noise

    def encode(self, obs, seed):
        return State(np.asarray(obs, float).copy(), np.random.default_rng(seed))

    def step(self, s, a):
        """Pure: returns (next state, mean reward, ensemble std of reward)."""
        preds = np.stack([A @ s.z + B @ a for A, B in zip(self.A, self.B)])
        z_next = preds.mean(0) + s.rng.normal(scale=self.sigma, size=s.z.shape)
        r = preds @ self.w_r
        return State(z_next, s.rng, s.t + 1), float(r.mean()), float(r.std())

    def fork(self, s, n):
        seeds = s.rng.integers(0, 2**32, size=n)
        return [State(s.z.copy(), np.random.default_rng(int(k)), s.t) for k in seeds]

if __name__ == "__main__":
    wm = EnsembleWorldModel()
    s0 = wm.encode(np.ones(4), seed=1)
    a = np.array([1.0, -1.0])
    branches = wm.fork(s0, 3)
    nxt = [wm.step(b, a)[0].z for b in branches]
    assert all(np.allclose(b.z, s0.z) for b in branches)   # fork does not move the state
    assert not np.allclose(nxt[0], nxt[1])                 # branches have their own noise
    s1, r, u = wm.step(s0, a)
    assert s0.t == 0 and s1.t == 1                         # step is pure
    _, _, u_far = wm.step(wm.encode(10 * np.ones(4), 2), 10 * a)
    print(f"branch spread {np.round(np.std(nxt, 0), 3)}; reward std near data {u:.3f}, far {u_far:.3f}")

It prints branch spread [0.027 0.079 0.065 0.031]; reward std near data 0.203, far 2.034. The branch spread is the process noise acting independently in each fork, which is what lets a planner or a Monte Carlo estimator draw many futures from one present. The two reward standard deviations show uncertainty exposure: the five members roughly agree at the unit state and disagree ten times more at a state and action ten times larger. Because the toy is linear, disagreement scales exactly with the input; in a trained ensemble it grows wherever training data are sparse, and that is the signal a planner should penalize and the evaluation loop should route to data collection. A frequent bug in real systems is sharing one random generator across forked branches, which makes the branches identical or correlated; the second assertion catches it.

In deployment the six parts become separately versioned components, and most of the engineering sits in the contracts between them.

The encoder as a shipped artifact. A frozen tokenizer or encoder is versioned and tested on its own, and every dynamics checkpoint records the encoder version it was trained against. Genie, Cosmos and V-JEPA 2-AC follow this pattern; V-JEPA 2-AC trains its action-conditioned predictor on a frozen video encoder with less than 62 hours of robot video. The failure it prevents is silent: a retrained tokenizer changes the meaning of every token, and a dynamics model loaded against the wrong version produces plausible but wrong rollouts.

Serving the simulator API. An interactive transformer simulator keeps a session per user, with a bounded context window and a key-value cache. fork is then a copy of that cache, cheap when implemented copy-on-write and expensive when every branch duplicates the activations; planners that fork hundreds of branches per decision need the former. Real-time targets become token budgets: \(N\) tokens per frame at \(f\) frames per second require \(Nf\) generated tokens per second, which is why Genie 3's 720p at 24 frames per second depends on compressive tokenizers and distillation rather than on the plain recipe. Latent models such as DreamerV3 avoid the budget by never decoding frames during imagination.

Uncertainty as an output. The API returns a disagreement or variance estimate with every prediction, and both are logged. Ensembles multiply training and inference cost by the number of members; sample diversity across forks or a variance head is cheaper but less reliable outside the training distribution.

The health variant. In a patient-timeline system such as ETHOS-ARES or CoMET, the data contract is the event format (MEDS or OMOP) and the consumer contract is a declarative task specification (prompt cut point, stop tokens, horizon, outcome tokens), so one model answers many questions without new code. The estimator forks \(K\) rollouts per question and reports a probability with its standard error.

Monitoring. Each stage owns one health signal: the unknown-token or unknown-code rate at the encoder, open-loop error at fixed horizons for the dynamics, head error on fresh real data, the imagined-versus-real gap at the consumer, and, for the loop, the share of evaluation failures that became collected data. A stage without a signal is where failures are found by users.

Production Challenges and Solutions

The same handful of problems shows up whenever a world model leaves the paper and meets a real optimizer, a real user or real data drift. The table maps each to the solutions that have worked in the work surveyed above.

ChallengeSymptomSolutionsSeen in
Compounding errorRollouts drift or blur after a few seconds or stepsShort branched rollouts; noise on context; diffusion or self forcing; multi-step losses; learned terminal values beyond the trusted horizonMBPO, GameNGen, Diffusion Forcing, Self Forcing, TD-MPC2
Model exploitationPolicy scores well in imagination, badly in realityEnsembles with uncertainty penalties; higher sampling temperature; regular real-environment evaluation; executable reward checksWorld Models (2018), MBPO, Agent World Model
Objective mismatchBetter likelihood, no better decisionsValue-aware or value-equivalent training; reward and value heads; decide model capacity by downstream successMuZero, TD-MPC2, Lambert et al.
Missing action labelsPlenty of video, little controllable dataLatent action models; pretrain on unlabeled video and post-train on a small action-labeled setGenie, LAPO, Dreamer 4, V-JEPA 2-AC
Data coverageGood in common states, wrong in rare or novel onesCurate for diversity; targeted collection where uncertainty or eval failures concentrate; curricula at the edge of competenceCosmos curator, DreamGym, World-in-World scaling result
Memory and consistencyScenes change when revisited; long sessions degradeLong-context or explicit spatial memory; persistent 3D state; loop-closure evaluationGenie 2 and 3, Marble
Compute and latencyToo slow for interaction or for planning with many samplesLatent rather than pixel rollouts; distillation to few denoising steps; efficient transformers; shortcut objectivesGameNGen, Genie 2 (distilled), Dreamer 4, DINO-WM
EvaluationGood FVD or loss, failures found by usersUse-case-specific closed-loop tests; action-sensitivity, physics and counterfactual probes; red-team the model with an optimizerPhysics-IQ, WorldScore, World-in-World, Vafa et al.

Table. Production challenges for world models mapped to solutions. Most solutions trade something away (horizon, fidelity, flexibility) rather than removing the problem.

Each row of the table has a compact formal statement, and the statement shows why the listed remedies work.

Compounding error. Let the one-step prediction error be at most \(\varepsilon\) and the learned dynamics be \(L\)-Lipschitz, so that a state error \(\delta\) becomes at most \(L\delta\) after one step. After \(H\) open-loop steps,

\[ e(H) \le \varepsilon \sum_{k=0}^{H-1} L^k = \varepsilon\,\frac{L^H - 1}{L - 1} \quad (L \ne 1). \]

For \(L < 1\) the bound saturates at \(\varepsilon/(1-L)\); for \(L > 1\) it grows geometrically. The remedies act on its terms: short branched rollouts reduce \(H\); noise on context and self forcing train the model to pull perturbed inputs back toward the data, lowering the effective \(L\); multi-step losses reduce \(\varepsilon\) where it matters; a learned terminal value replaces the tail beyond \(H\).

Model exploitation. An ensemble of \(M\) members predicts rewards \(\hat r^{(1)}, \dots, \hat r^{(M)}\) for one imagined trajectory, and a pessimistic objective subtracts their spread: \(\tilde r = \bar r - \beta\,\sigma_r\), with \(\bar r\) the mean, \(\sigma_r\) the standard deviation across members and \(\beta \ge 0\) the penalty strength. Trajectories that look good to only some members are down-weighted; large \(\beta\) also suppresses novel but genuinely good behaviour.

Objective mismatch. Likelihood training minimizes \(\mathbb{E}[-\log p_\theta(o_{t+1} \mid h_t, a_t)]\), which weights every pixel or token equally. A value-equivalent model instead requires \(\mathcal{T}^\pi_{\theta} v = \mathcal{T}^\pi v\) for chosen policies \(\pi\) and value functions \(v\), where \(\mathcal{T}^\pi\) is the Bellman operator under the true environment and \(\mathcal{T}^\pi_\theta\) the same operator under the model. MuZero implements this by training only reward, value and policy predictions through unrolled latent steps.

Missing action labels. A latent action model pairs an inverse model \(q_\psi(u \mid o_t, o_{t+1})\) with a forward model \(p_\theta(o_{t+1} \mid o_t, u)\) and limits the capacity of the inferred action \(u\) (for example a small discrete codebook), so that \(u\) can only encode what changed between frames. A small labeled set then fits a map from real actions to \(u\).

Coverage, compute and evaluation. Estimates in a situation seen \(n_j\) times have error of order \(1/\sqrt{n_j}\), so a minimum count per situation is a collection target. A latent rollout of dimension \(d\) costs a fraction of a pixel rollout of \(w \times h \times 3\) values per step. For risk estimates from \(K\) sampled futures, the binomial standard error \(\sqrt{p(1-p)/K}\) bounds what any evaluation can resolve, and calibration is measured by the expected calibration error \(\text{ECE} = \sum_b \frac{n_b}{n} \lvert \bar y_b - \bar p_b \rvert\) over bins \(b\) of predicted probability, with \(\bar y_b\) the observed and \(\bar p_b\) the mean predicted rate.

Three diagnostics cover most rows of the table in code: a trusted horizon read from an open-loop error curve (compounding error), an ensemble-penalized reward (model exploitation), and calibration measurement and repair with expected calibration error and isotonic regression (evaluation of probabilistic outputs). Each takes plain arrays so it can run on logged evaluation outputs. trusted_horizon returns the largest horizon at which quality stays above a floor, interpolating between measured points. penalized_reward takes an \((M, N)\) array of rewards from \(M\) ensemble members for \(N\) trajectories. isotonic_fit implements pool-adjacent-violators: it sorts by score and merges neighbouring blocks whose observed rates decrease, giving a non-decreasing step function.

"""Production diagnostics: trusted horizon, ensemble penalty, calibration (ECE + isotonic)."""
import numpy as np

def trusted_horizon(h_s, psnr_db, floor_db):
    """Largest horizon (s) whose open-loop PSNR stays >= floor, linear interpolation
    between measured points. h_s ascending, psnr_db typically descending."""
    h_s, psnr_db = np.asarray(h_s, float), np.asarray(psnr_db, float)
    if psnr_db[0] < floor_db: return 0.0
    for i in range(1, len(h_s)):
        if psnr_db[i] < floor_db:
            f = (psnr_db[i - 1] - floor_db) / (psnr_db[i - 1] - psnr_db[i])
            return float(h_s[i - 1] + f * (h_s[i] - h_s[i - 1]))
    return float(h_s[-1])

def penalized_reward(ens_rewards, beta):
    """ens_rewards: (M members, N trajectories). Mean minus beta * disagreement."""
    r = np.asarray(ens_rewards, float)
    return r.mean(0) - beta * r.std(0)

def ece(p, y, bins=10):
    """Expected calibration error with equal-width bins. p, y: shape (N,)."""
    p, y = np.asarray(p, float), np.asarray(y, float)
    idx = np.minimum((p * bins).astype(int), bins - 1)
    return sum(abs(p[idx == b].mean() - y[idx == b].mean()) * (idx == b).mean()
               for b in range(bins) if (idx == b).any())

def isotonic_fit(p, y):
    """Pool-adjacent-violators: monotone map from score to frequency. Returns (x_knots, y_knots)."""
    o = np.argsort(p); x, v = np.asarray(p)[o], np.asarray(y, float)[o]
    blocks = [[v[i], 1.0, x[i]] for i in range(len(v))]          # [mean, weight, last x]
    out = []
    for b in blocks:
        out.append(b)
        while len(out) > 1 and out[-2][0] > out[-1][0]:            # violation: merge
            m2, w2, x2 = out.pop(); m1, w1, _ = out.pop()
            out.append([(m1 * w1 + m2 * w2) / (w1 + w2), w1 + w2, x2])
    return np.array([b[2] for b in out]), np.array([b[0] for b in out])

def isotonic_apply(knots, p):
    xk, yk = knots
    return yk[np.minimum(np.searchsorted(xk, p), len(xk) - 1)]

if __name__ == "__main__":
    # open-loop PSNR 28 dB at 1 s, 21 dB at 10 s; floor 24 dB
    h = trusted_horizon([1, 10], [28, 21], floor_db=24)
    assert abs(h - (1 + 9 * 4 / 7)) < 1e-9
    # ensemble: second trajectory scores higher on average but members disagree
    pen = penalized_reward([[1.0, 1.6], [1.1, 0.4], [0.9, 1.3]], beta=1.0)
    assert pen[0] > pen[1]
    # miscalibrated scores: true risk = score**2 (overconfident at the top)
    g = np.random.default_rng(0); s = g.uniform(size=20000); y = g.uniform(size=20000) < s**2
    tr, te = slice(0, 10000), slice(10000, None)
    knots = isotonic_fit(s[tr], y[tr])
    before, after = ece(s[te], y[te]), ece(isotonic_apply(knots, s[te]), y[te])
    assert after < before / 3
    print(f"trusted horizon {h:.2f} s; penalized {np.round(pen, 3)}; ECE {before:.3f} -> {after:.3f}")

It prints trusted horizon 6.14 s; penalized [0.918 0.59 ]; ECE 0.171 -> 0.009. An open-loop curve falling from 28 dB PSNR at 1 s to 21 dB at 10 s crosses a 24 dB floor at about 6.1 s, so rollouts beyond that point should be re-anchored on real frames or handed to a value function. The ensemble penalty reverses a ranking: the second trajectory has the higher mean reward, but its members disagree, so with \(\beta = 1\) the first wins. The calibration test simulates an overconfident model whose true risk is the square of its score; isotonic regression fitted on one half and applied to the other cuts ECE from 0.171 to 0.009. Fit calibration maps on held-out data only, and compute error curves open loop rather than teacher-forced, or both diagnostics look better than they are.

In practice each challenge is managed by a diagnostic signal that is monitored continuously and a remedy whose cost is known in advance. The table pairs them.

ChallengeSignal to monitorCost of the remedy
Compounding errorOpen-loop error at fixed horizons; trusted horizon per releaseShorter rollouts cost planning depth; self forcing costs training compute
Model exploitationImagined-versus-real gap per evaluation; ensemble disagreement on states the new policy visitsEnsembles multiply cost by the number of members; penalties slow learning of novel behaviour
Objective mismatchDownstream success against model loss across checkpointsValue-equivalent models cannot render observations and are tied to one reward
Missing action labelsAction sensitivity: output change for different actions from one stateA labeled post-training set must be collected
Data coverageCounts per action, environment and rare situation; error by bucketTargeted collection and curation pipelines
Memory and consistencyLoop-closure error when a scene is revisitedLonger context or explicit memory raises latency
Compute and latencyFrames or tokens per second; GPU-seconds per queryDistillation can lose diversity and rare dynamics
EvaluationClosed-loop success and calibration on held-out tasksReal trials and human grading are slow

Two failure patterns recur. The first is a regression that the dashboard cannot see: a change made for cost, such as switching a sampler from temperature 1 to truncated top-\(p\) sampling to generate fewer tokens, leaves discrimination unchanged while calibration drifts, because truncation removes the low-probability tail where rare outcomes live. Health event models such as ETHOS-ARES and CoMET estimate risks from sampled futures, so calibration belongs among the gate metrics, not only AUROC. The second is exploitation after an unrelated change: a new actor learning rate lets a policy reach states the reward head has never seen, imagined return rises while real return falls, and the fix is a disagreement penalty plus continued real data collection, not a bigger dynamics model. The distinguishing measurement is head error on held-out real transitions split by whether the state was visited by the new policy.

Remedies are chosen against the consumer's binding constraint (latency for an interactive simulator, the imagined-versus-real gap for a policy learner, calibration for a risk estimator), and each is validated by a metric that would move if the diagnosis were wrong.

A Step-by-Step Playbook

Building a world model is mostly a sequence of scoping decisions, made in order, each of which constrains the next. The playbook below is the order that avoids the most rework.

  1. Name the consumer and the horizon. Decide whether the model will train a policy, serve as an interactive simulator, plan toward goals or forecast outcomes, and how far ahead it must be right. This single decision picks the family from the taxonomy table.
  2. Define state, action and observation. Write down what the model sees, what it must respond to, and what it must output. If actions are not logged, plan for latent actions or a small labeled set from the start.
  3. Assemble and audit data for coverage. Count how much data exists per action, per environment and per rare situation. Coverage, not volume, usually limits world models; the DINO-WM and World-in-World results both point there.
  4. Choose and freeze the representation. Train or adopt a tokenizer or encoder (VAE, discrete tokens, DINOv2 or V-JEPA features) and test it in isolation: can a simple probe read the decision-relevant variables from it?
  5. Train the dynamics model with deployment-like context. Include multi-step or self-generated context in training (noise augmentation, scheduled sampling, self forcing) so the model sees its own errors before users do.
  6. Attach heads for what the consumer needs. Reward, value, termination, event probabilities, or a decoder. Train them jointly so the latent keeps what they need.
  7. Build the evaluation loop before the consumer. Implement open-loop error curves, action-sensitivity and loop-closure probes, and at least one closed-loop task. Gate every model change on them.
  8. Connect the consumer conservatively. Start with short horizons, uncertainty penalties and frequent real-environment checks; lengthen the horizon only as the imagined-versus-real gap stays small.
  9. Close the data loop. Route evaluation failures and high-uncertainty states into targeted data collection, retrain, and re-run the gate. Most of a world model's improvement after launch comes from this loop.

Several playbook steps are sizing decisions that can be computed before training starts.

Horizon (step 1). With discount \(\gamma\), rewards beyond about \(1/(1-\gamma)\) steps contribute little, so this effective horizon is what the consumer needs. If the model is trusted for only \(H\) steps, a learned value must cover the rest. In a Dreamer-style \(\lambda\)-return,

\[ R^\lambda_t = \hat r_t + \gamma \hat c_t\big[(1-\lambda)\,v(z_{t+1}) + \lambda R^\lambda_{t+1}\big], \qquad R^\lambda_H = v(z_H), \]

the final value enters \(R^\lambda_0\) with weight \(\gamma^H \lambda^{H-1}\) (ignoring continuation). With \(H = 15\), \(\gamma = 0.997\) and \(\lambda = 0.95\) that weight is about 0.47, so the critic matters as much as the dynamics.

Coverage (step 3). For a situation \(j\) seen \(n_j\) times, estimated quantities have error of order \(1/\sqrt{n_j}\). A tolerance therefore translates into a minimum count \(n_{\min}\), and every situation with \(n_j < n_{\min}\) is a concrete collection target for step 9.

Model size. CoMET's isoFLOP sweeps found a compute-optimal ratio of roughly \(D/N \approx 1{,}000\) training tokens \(D\) per parameter \(N\). Compute-optimal assumes abundant data. When data are the constraint, the right \(N\) is the one with lowest validation loss after training to convergence on the available \(D\), found by a small sweep.

Rollouts per query. An event probability estimated from \(K\) sampled futures has standard error \(\sqrt{p(1-p)/K}\), so a target standard error \(s\) needs

\[ K = \Big\lceil \frac{p(1-p)}{s^2} \Big\rceil \le \Big\lceil \frac{1}{4 s^2} \Big\rceil . \]

The gate (step 7). A gate metric estimated from \(n\) evaluation episodes is itself noisy. For a success rate \(\hat p\) the gate should require the lower confidence bound \(\hat p - z\sqrt{\hat p(1-\hat p)/n}\) to clear the threshold, which fixes \(n\) in advance.

Horizon lengthening (step 8). Let \(\Delta_H = J_{\text{model},H} - J_{\text{real}}\) be the imagined-versus-real gap when the consumer trusts \(H\) steps. A conservative schedule increases \(H\) to \(H'\) only if \(\Delta_{H'} \le \delta\) for a tolerance \(\delta\) and real return does not fall.

Three playbook steps reduce to small, testable functions. coverage_audit implements step 3: it counts training examples per situation (an action bin, an environment, a rare event) and returns the situations below a minimum count, which become targets for collection in step 9. k_for_se sizes Monte Carlo estimation for forecasting consumers: the number of sampled futures needed for a target standard error. run_gate implements step 7: a dictionary of metric thresholds written before any consumer is connected, and a check that a candidate model meets every one. A missing metric counts as a failure, so a model cannot pass by not being measured.

"""Playbook tooling: coverage audit, rollouts-per-query sizing, and a release gate."""
import math
from collections import Counter

def coverage_audit(labels, min_count):
    """labels: one situation key per training example (action bin, site, rare event)."""
    c = Counter(labels)
    return sorted(k for k, n in c.items() if n < min_count)

def k_for_se(p, se_target):
    """Rollouts so that the binomial standard error of an estimated risk p is <= se_target."""
    return math.ceil(p * (1 - p) / se_target**2)

GATE = {  # metric: (direction, threshold); written before any consumer is connected
    "closed_loop_success": (">=", 0.60),
    "trusted_horizon_s":   (">=", 5.0),
    "action_sensitivity":  (">=", 0.10),   # frame change caused by actions vs no-op
    "imagined_real_gap":   ("<=", 0.10),
    "ece":                 ("<=", 0.03),
}

def run_gate(results, gate=GATE):
    fails = []
    for m, (op, thr) in gate.items():
        v = results.get(m)
        ok = v is not None and (v >= thr if op == ">=" else v <= thr)
        if not ok:
            fails.append(f"{m}={v} (needs {op} {thr})")
    return not fails, fails

if __name__ == "__main__":
    actions = ["forward"] * 900 + ["turn"] * 80 + ["stop"] * 20
    print("under-covered:", coverage_audit(actions, min_count=50))
    print("K for SE 0.02 at p=0.15:", k_for_se(0.15, 0.02), "| worst case p=0.5:", k_for_se(0.5, 0.02))
    good = {"closed_loop_success": 0.71, "trusted_horizon_s": 6.1, "action_sensitivity": 0.22,
            "imagined_real_gap": 0.04, "ece": 0.02}
    bad = dict(good, action_sensitivity=0.03); del bad["ece"]
    print("candidate A:", run_gate(good))
    print("candidate B:", run_gate(bad))

It prints:

under-covered: ['stop']
K for SE 0.02 at p=0.15: 319 | worst case p=0.5: 625
candidate A: (True, [])
candidate B: (False, ['action_sensitivity=0.03 (needs >= 0.1)', 'ece=None (needs <= 0.03)'])

The audit flags the stop action, seen 20 times against a minimum of 50, although the dataset holds 1,000 examples: coverage, not volume, is the constraint. Estimating a 15% risk to within a standard error of 0.02 needs 319 futures, and the worst case at 50% needs 625. Candidate B is blocked for two reasons: its outputs barely respond to actions, and its calibration was never measured. Thresholds should be versioned with the code, and a useful check on the gate itself is that it fails at least one earlier, known-bad checkpoint.

The playbook's order is a cost control. Each step's artifact is cheap compared with the step after it: a task definition costs hours of expert time, a coverage audit a day of queries, a large dynamics training run weeks of accelerator time. Errors caught early save the expensive steps, and most rework in practice comes from steps taken out of order.

Deliberate exceptions. Step 4 says to freeze the representation, but DreamerV3 trains encoder, dynamics and heads jointly from the start, which works because the reconstruction and reward losses anchor the latent. The rule is better read as: freeze the representation unless a training signal keeps it honest, and test it with a probe either way.

Failure modes.

  • A gate fitted to the first good result. When evaluation is built after a promising run, metrics and thresholds tend to be chosen so that the run passes, and the gate certifies the model rather than testing it. Writing thresholds in step 7, before connecting the consumer, and versioning them is the remedy; a gate that passes every checkpoint ever trained is not discriminating.
  • Leakage that looks like progress. In forecasting systems, a tokenizer or extraction change can move information recorded after the prediction time into the prompt. Discrimination jumps on validation and disappears in deployment. Cutting prompts by the time data become available in the source system, and gating on the score change when leak-prone tokens are masked, catches it.
  • Horizon lengthened too early. A policy evaluator asked to score episodes longer than the trusted horizon produces rankings that disagree with real trials. Scoring only within the horizon, or re-anchoring on logged real frames, restores agreement.
  • A starved data loop. If evaluation failures are logged but never routed to collection, the model stops improving after launch. The loop's own metric is the fraction of failures that became training data within a release cycle.

Release mechanics. Each model version passes the same gate, is shadowed on live traffic (or, for clinical models, deployed silently with predictions logged but not shown) and is promoted only after the shadow metrics match the gate. For regulated clinical software, planned updates can be pre-specified under the FDA's December 2024 guidance on predetermined change control plans (Ropes & Gray 2024).

The State of the Art in 2025–2026

As of November 2026 the field has converged on a few large ideas while splitting into distinct product lines. The summary below is a snapshot; most of the systems named were released within the last eighteen months and have little independent evaluation yet.

  • Interactive simulators went real time. Genie 3 reached 720p at 24 frames per second with minutes of consistency (August 2025), Google made it available to subscribers as Project Genie (January 2026), and Genie 4 added generated audio and language steering (October 2026). Runway's GWM-1 and open models such as Matrix-Game 2.0 follow the same autoregressive, real-time recipe.
  • Persistent 3D emerged as an alternative. World Labs' Marble produces editable 3D environments that do not drift, trading away most dynamics.
  • Control world models scaled into video models. DreamerV3's fixed-hyperparameter recipe appeared in Nature (2025), and Dreamer 4 showed that an agent can learn a long-horizon task entirely offline inside a transformer world model trained mostly on unlabeled video.
  • Latent planning reached real robots. V-JEPA 2-AC and DINO-WM planned toward image goals in learned feature spaces, and the JEPA program gained a well-funded company in AMI Labs (2026).
  • Platforms for physical AI. NVIDIA Cosmos (2025) packaged curation, tokenizers, pretrained world models and post-training recipes for robots and vehicles, and Wayve's GAIA-2 brought multi-camera control to driving simulation.
  • LLMs became environments. LLM-simulated tools (Simia), experience models with curricula (DreamGym) and synthesized executable environments (Agent World Model) made "train the agent in a world model" standard practice for tool-using language agents.
  • Evaluation caught up with closed loops. Physics-IQ, WorldScore and World-in-World all point the same way: visual quality is a poor proxy, and controllability and closed-loop success are what separate useful world models from impressive videos.
  • Domain models scaled. Patient-timeline models such as Delphi-2M and CoMET showed that the same next-event objective, applied to health records at the scale of hundreds of thousands to over a hundred million patients, yields generative forecasters of disease trajectories, which the health half of this book examines.

The 2025–2026 systems can be compared on three quantitative axes: how much a simulator generates per second, how well a world model's judgments agree with reality, and how training scale relates to data.

Generation rate. A pixel simulator at width \(w\), height \(h\) and frame rate \(f\) produces \(whf\) pixels per second. Genie 3's reported 720p at 24 frames per second is \(1280 \times 720 \times 24 \approx 2.2 \times 10^{7}\) pixels per second. With a tokenizer that maps a \(P \times P\) patch to one token, the generation budget is \(whf/P^2\) tokens per second, which is why frontier simulators pair more compressive tokenizers with distillation to few sampling steps.

Agreement with reality. When a world model is used to evaluate policies, the quantity of interest is agreement between simulated scores \(s_i\) and real scores \(y_i\) for policies \(i = 1, \dots, n\). The Pearson correlation measures linear agreement. Because decisions depend on order, a rank-violation measure complements it. The mean maximum rank violation is

\[ \text{MMRV} = \frac{1}{n}\sum_{i=1}^{n} \max_{j \ne i}\; \lvert y_i - y_j \rvert \cdot \mathbb{1}\big[(s_i < s_j) \ne (y_i < y_j)\big], \]

so each policy contributes the largest real-score gap among the pairs the simulator orders wrongly, and 0 means perfect ordering. MMRV is in units of the real score. Correlations over few policies are uncertain: with the Fisher transform \(z = \operatorname{artanh} r\) and standard error \(1/\sqrt{n-3}\), a correlation of 0.95 over \(n = 8\) policies has a 95% interval of roughly 0.74 to 0.99.

Scale and data. Scaling laws write loss as a power law in parameters \(N\) and data \(D\), \(\mathcal{L}(N, D) \approx E + A N^{-\alpha} + B D^{-\beta}\), and the compute-optimal split minimizes this under a budget \(C \propto ND\). CoMET's isoFLOP sweeps on medical events found exponents close to natural language but an optimum near 1,000 tokens per parameter, far more data-hungry than language models. Whether similar laws hold for video, robotics and physiology world models is still being mapped.

Each axis is a ratio against a reference (pixels per second against real time, simulated against real scores, tokens against parameters), and reporting the reference is what makes a state-of-the-art claim checkable.

The most reusable measurement from the 2025–2026 work is whether a world model ranks policies the way reality does, the test behind using video world models such as WorldGym or Runway's robotics model as policy evaluators. Two functions implement it. pearson takes simulated and real scores per policy and returns their correlation. mmrv takes the same arrays and, for each policy, finds the largest real-score gap among the other policies whose order the simulator inverts, then averages over policies. The double loop is \(O(n^2)\), negligible for the tens of policies typical of such studies.

"""Does a world model rank policies like reality does? Pearson r and MMRV."""
import numpy as np

def pearson(x, y):
    x, y = np.asarray(x, float), np.asarray(y, float)
    return float(np.corrcoef(x, y)[0, 1])

def mmrv(sim, real):
    """Mean maximum rank violation: for each policy i, the largest real-score gap |real_i - real_j|
    over policies j whose order the simulator gets wrong; averaged over i. 0 = perfect ordering."""
    sim, real = np.asarray(sim, float), np.asarray(real, float)
    n = len(sim); worst = np.zeros(n)
    for i in range(n):
        for j in range(n):
            if i != j and (sim[i] < sim[j]) != (real[i] < real[j]):
                worst[i] = max(worst[i], abs(real[i] - real[j]))
    return float(worst.mean())

if __name__ == "__main__":
    real = [0.20, 0.35, 0.50, 0.62]          # real success rates of four policy checkpoints
    sim_good = [0.25, 0.33, 0.55, 0.70]      # same order
    sim_swap = [0.25, 0.58, 0.55, 0.70]      # policies 2 and 3 swapped
    assert mmrv(sim_good, real) == 0.0
    assert abs(mmrv(sim_swap, real) - 0.075) < 1e-9   # two policies each violate by 0.15
    print(f"r={pearson(sim_good, real):.3f} MMRV=0; swapped: r={pearson(sim_swap, real):.3f} MMRV={mmrv(sim_swap, real):.3f}")

It prints r=0.983 MMRV=0; swapped: r=0.895 MMRV=0.075. Four policy checkpoints have real success rates 0.20, 0.35, 0.50 and 0.62. A simulator that preserves their order has MMRV 0 even though its absolute values are off. Swapping the simulated scores of the middle two inverts one pair whose real gap is 0.15; both members of the pair contribute 0.15, so MMRV is \(2 \times 0.15 / 4 = 0.075\), while the correlation falls only to 0.895. Correlation can remain high while the one comparison a team cares about is wrong, which is why both are reported. Each simulated score is itself a Monte Carlo estimate, so it needs enough rollouts that its standard error is small next to the gaps between policies; otherwise rank violations measure sampling noise rather than model error.

In production the state of the art matters mainly as a build-or-adopt decision: train a world model from scratch, post-train an open or licensed one (Cosmos, Matrix-Game 2.0, the ethos-ares pipeline), or call a hosted simulator. The decision follows the playbook's first step and is settled by the same gate.

OptionWhen it fitsMain costGate test that decides
Train from scratchUnusual observations or actions; data cannot leave the siteData, compute, time to a first baselineMatches or beats a reproduced baseline
Post-train an open modelDomain close to the pretraining data; a small labeled set existsMaintaining a fork; licence termsAction sensitivity and ranking on in-domain tests
Hosted simulatorInteractive content; no strict latency or privacy constraintsPer-use cost; no access to internalsClosed-loop or ranking agreement on held-out policies

Adopting on reported numbers. Most systems in the snapshot were released within eighteen months and have little independent evaluation. A developer's benchmark may not cover the deployment's actions, scenes or populations, so the adopting team runs its own gate first: open-loop error curves on in-domain data, action-sensitivity probes, and a closed-loop or ranking test against real outcomes. A common finding is that a model with higher visual quality renders small actions (a fine wrist rotation, a slight steering change) almost like a no-op, so policies that differ in fine control become indistinguishable; post-training on a small action-labeled set, as Dreamer 4 and V-JEPA 2-AC do, is the usual repair. For patient-timeline models, the analogue is calibration: a model trained on another population can keep its discrimination while its risks are offset by a different baseline rate, and needs local recalibration and silent deployment before use.

Cost of evaluation. Ranking studies need many graded rollouts per policy. Runway reported that its robotics world model ranked eight manipulation policies with Pearson 0.95 and MMRV 0.033 against real progress scores, from 1,450 simulated rollouts graded by people (Runway 2026). WorldGym (Quevedo et al. 2026) replaces human graders with a vision-language model as reward. A model grader adds its own errors, so it is calibrated against a human-graded subset, and human effort is spent on pairs whose order is uncertain.

Whatever the source of the model, its value is set by the decisions of its consumer, and the gate is the instrument that measures it.

What a Health World Model Is

A health world model is a generative model of how a patient's state evolves over time, optionally conditioned on interventions: given everything recorded about a person so far, it assigns probabilities to what happens next and can sample whole future trajectories. In the language of the control half of this book, the patient timeline is the environment, clinical events are observations, treatments and care decisions are actions, and the model is a learned simulator of that environment. Unlike a game engine, nobody wrote the rules: the model learns them from records of care, which are sparse, biased by who gets measured, and shaped by decisions made for reasons the record rarely states.

The idea is old in medicine. Survival curves, Markov cohort models and cancer microsimulations are all hand-built health world models: a small set of states, transition rates estimated from data, and simulation to answer "what happens to this population under policy A versus B". What changed after 2022 is that a single neural network, trained only to predict the next token of a patient's record, began to work as a general simulator. Generate many plausible futures for a patient, count how often an outcome appears, and you have a risk estimate for any outcome the vocabulary can express, with no task-specific training. That is the "GPT style" of health world model, and ETHOS (Renc et al. 2024) is its clearest, fully documented example, which is why it sits at the center of this half of the book.

Notation

A patient's record is a token sequence \(x_{1:T} = (x_1, \dots, x_T)\) drawn from a vocabulary \(\mathcal{V}\). \(h_t = x_{1:t}\) is the history up to the current position (the "prompt"). \(p_\theta\) is the model with parameters \(\theta\). A sampled future is \(\tilde{x}^{(k)}\), \(k = 1..K\). An outcome is a predicate \(g\) on a future, for example "contains a death token before a discharge token", with true probability \(p = \Pr[g(\tilde{x}) = 1 \mid h_t]\) and Monte Carlo estimate \(\hat{p}\). \(a\) denotes an intervention such as starting a drug.

A patient's record is a token sequence \(x_{1:T} = (x_1, \dots, x_T)\) over a vocabulary \(\mathcal{V}\) of codes, binned measurements, demographic tokens and time-interval tokens. With \(h_t = x_{1:t}\) the history at the cut point \(t\), a health world model is a conditional distribution over continuations, factorized autoregressively:

\[ p_\theta(x_{t+1:T'} \mid h_t) = \prod_{s=t+1}^{T'} p_\theta(x_s \mid x_{<s}), \qquad \mathcal{L}(\theta) = -\sum_{n}\sum_{s} \log p_\theta\big(x^{(n)}_s \mid x^{(n)}_{<s}\big). \]

Training minimizes \(\mathcal{L}\) over all positions of all timelines \(n\); no outcome label appears. A question is an outcome predicate \(g\) mapping a future to \(\{0, 1\}\). The model's answer is \(p_\theta = \Pr_\theta[g(\tilde{x}) = 1 \mid h_t]\), estimated from \(K\) independent rollouts \(\tilde{x}^{(1)}, \dots, \tilde{x}^{(K)}\) by

\[ \hat{p} = \frac{1}{K}\sum_{k=1}^{K} g\big(\tilde{x}^{(k)}\big), \qquad \mathbb{E}[\hat{p}] = p_\theta, \qquad \operatorname{SE}(\hat{p}) = \sqrt{p_\theta(1 - p_\theta)/K}. \]

The estimator is unbiased for the model's probability \(p_\theta\), not for the true clinical probability \(p\); the total error splits into a Monte Carlo term that shrinks as \(1/\sqrt{K}\) and a modeling term \(p_\theta - p\) that sampling cannot reduce. An intervention \(a\) enters by editing the prompt, \(h_t \oplus a\).

The hand-built predecessors are special cases. A Markov cohort model has a small state set \(\mathcal{S}\), a transition matrix \(P\) estimated from the literature, and a cohort distribution that evolves as \(\pi_{n+1} = \pi_n P\); the probability of death within \(H\) cycles from state \(i\) is \([P^H]_{i,\text{dead}}\). A microsimulation estimates the same quantity by sampling individual paths and counting, which is exactly \(\hat{p}\). The neural model replaces \(\mathcal{S}\) with the whole history and \(P\) with \(p_\theta\), so the exact matrix power is no longer available and sampling becomes the only general way to answer a question.

The "simulate, then count" pattern predates neural networks. The script below builds a three-state Markov cohort model (well, sick, dead) with yearly transitions, computes the exact probability that a currently sick patient dies within five years by propagating the state distribution \(\pi_{n+1} = \pi_n P\), and then answers the same question the way a GPT-style health world model does: sample \(K\) futures, apply the outcome predicate, and average. The standard error \(\sqrt{p(1-p)/K}\) shows how many rollouts a stable estimate needs.

import numpy as np
# Hand-built health world model: a 3-state Markov cohort model (well, sick, dead), yearly cycles.
P = np.array([[0.90, 0.08, 0.02],    # rows: from-state, cols: to-state
              [0.10, 0.75, 0.15],
              [0.00, 0.00, 1.00]])
start, horizon = 1, 5                # patient is "sick" now; question: dead within 5 years?

# Exact answer: propagate the state distribution, pi_{n+1} = pi_n P
pi = np.eye(3)[start] @ np.linalg.matrix_power(P, horizon)
p = pi[2]

# GPT-style answer: sample K futures, count those that satisfy the outcome predicate g
rng = np.random.default_rng(0)
def rollout(s, n):
    for _ in range(n):
        s = rng.choice(3, p=P[s])
    return s
for K in (20, 200, 2000):
    p_hat = np.mean([rollout(start, horizon) == 2 for _ in range(K)])
    se = np.sqrt(p * (1 - p) / K)
    print(f"K={K:5d}  p_hat={p_hat:.3f}  exact={p:.3f}  SE={se:.3f}")

It prints:

K=   20  p_hat=0.600  exact=0.480  SE=0.112
K=  200  p_hat=0.510  exact=0.480  SE=0.035
K= 2000  p_hat=0.468  exact=0.480  SE=0.011

At \(K = 20\) (the default number of rollouts in ETHOS) the estimate is off by about one standard error of 0.11; at \(K = 2000\) it is within 0.012 of the exact value. A neural health world model keeps the rollout loop and replaces the fixed matrix row P[s] with a network's next-token distribution conditioned on the full history, which is why no closed-form answer exists and the Monte Carlo error must be budgeted. The exact computation remains useful as a test: any sampler should agree with a known model to within a few standard errors before it is trusted on a learned one.

A deployed health world model is three systems: a data pipeline that turns records into timelines, a training job, and a sampling service that answers questions. Training happens once per model version; sampling happens for every patient, every question and every update of the record, so it dominates cost. ETHOS reported about 15 seconds per 1,000 generated tokens on one A100 in its unoptimized implementation (Renc et al. 2024); the ETHOS-ARES reimplementation used 100 rollouts per query (Renc et al. 2025), and the Epic Cosmos study found that gains from extra simulations mostly plateau around 64 (Waxler et al. 2025). The number of rollouts is therefore a cost knob set per question, not a constant.

The central design decision is what the service returns. A frequency of simulated outcomes is a property of the model; reading it as a clinical probability requires checks that the training loss does not provide. Bedi, Fries & Shah (2026) list calibration, rare-event performance, timeline completion, shortcut audits and out-of-distribution validation. In practice this means a recalibration layer fitted on recent outcomes, a report of how many rollouts ended at a stop token rather than at the token budget, and performance stratified by site and month.

The main failure modes follow from the definition. Because the model learns from records of care, it inherits shortcuts and drifts when care changes. Because answers come from long rollouts, errors compound with horizon and cost grows with it. Because "what if" is a prompt edit, a user interface that lets clinicians append a drug and resample invites causal readings that the model cannot support without the assumptions of a separate causal analysis.

The Patient Timeline as an Environment

The useful mental model is a partially observed, irregularly sampled process whose observations are whatever the health system chose to record: a lab when someone ordered it, a code when someone billed it, a drug when someone gave it. A health world model therefore learns the joint process of physiology and care. That explains why these models predict what a hospital will do next so well, and why they need extra machinery before they can say what a treatment would do (see Prediction Is Not Intervention).

A patient's observed past and a fan of sampled futures from a health world model. OBSERVED HISTORY h(t) SAMPLED FUTURES from p(future | h(t), a) birth, sex diabetes dx HbA1c high ED visit creatinine now (t) discharged, day 3 ICU transfer, day 1 readmitted, day 19 future 1 future 2 future K
Fig. The GPT-style view of a health world model. The observed history is the prompt; the model samples many futures, each a full sequence of events with timing. Questions about the patient become questions about the distribution of sampled futures. Conditioning on an intervention \(a\) (for example, appending a drug token) changes the distribution, but whether that change is causal depends on the data (see the causality section). Events are fictional.

Write the latent physiological state at time \(\tau\) as \(s_\tau\), care actions as \(a_\tau\) and recorded events as tokens. Three mechanisms generate the record: physiology evolves under care, \(s_{\tau+1} \sim P(\cdot \mid s_\tau, a_\tau)\); clinicians act on what they see, \(a_\tau \sim \pi(\cdot \mid \text{history}_\tau)\); and a recording process decides what is measured and written, \(x \sim R(\cdot \mid s_\tau, a_\tau)\). A next-token model fitted to the tokens learns the marginal law

\[ p_\theta(x_{t+1} \mid h_t) \approx \sum_{s,\,a} P(s \mid h_t)\, \pi(a \mid h_t)\, R(x_{t+1} \mid s, a), \]

in which the care policy \(\pi\) and recording process \(R\) are mixed with physiology. Nothing in the objective separates them, so the model predicts care well and cannot, on its own, say what a different policy would produce.

The record is generated jointly by physiology, care decisions and a recording process.Physiology s(t)latent, continuousCare policyclinician decides a(t)Recording processwhat gets measuredRecorded tokens xcodes, labs, gapspθlearnsa(t) also changes s(t+1)and what is recorded
Fig. What a next-token model of a record actually fits. Latent physiology drives both the care policy and the recording process, and both shape the tokens. A model fitted to the tokens learns the joint law of physiology, care and documentation, not physiology alone, which is why its rollouts reproduce what the hospital tends to do next.

Irregular sampling has a precise form: the record is a marked point process with intensity \(\lambda(\tau, v \mid \mathcal{H}_\tau)\) for an event of type \(v\) at time \(\tau\). Discretizing gaps into interval tokens turns this into a sequence model, in which the time to the next event is itself a generated token rather than a fixed grid step.

A synthetic hospital makes the "physiology and care" point concrete. Each admission has a latent sepsis state that is never recorded. Clinicians order a lactate test far more often for septic patients, a lactate value exists in the record only when ordered, and death depends on sepsis alone. A count model of the record then learns that a high lactate, and even the presence of a normal lactate, signals risk. When the hospital changes policy and tests everyone, physiology is unchanged but the meaning of the tokens shifts.

import numpy as np
from collections import Counter
rng = np.random.default_rng(1)

def admission(policy_test_all=False):
    """Latent physiology -> care decision -> recording. Returns the recorded tokens."""
    septic = rng.random() < 0.15                       # latent state s, never recorded
    ordered = policy_test_all or rng.random() < (0.9 if septic else 0.1)   # care policy pi
    tl = ["ADMIT"]
    if ordered:                                        # recording process R: lab exists only if ordered
        high = rng.random() < (0.8 if septic else 0.1)
        tl.append("LACTATE_HIGH" if high else "LACTATE_NORMAL")
    died = rng.random() < (0.25 if septic else 0.02)  # outcome depends on s only
    return tl + ["DEATH" if died else "DISCHARGE"]

def fit(corpus):   # count model: p(outcome | last recorded token before it)
    c = Counter((tl[-2], tl[-1]) for tl in corpus)
    return {k: c[(k, "DEATH")] / max(1, c[(k, "DEATH")] + c[(k, "DISCHARGE")])
            for k in ("ADMIT", "LACTATE_HIGH", "LACTATE_NORMAL")}

old = [admission() for _ in range(50_000)]
m = fit(old)
print("p(death | last token):", {k: round(v, 3) for k, v in m.items()})
# The hospital changes policy: lactate for every admission. Physiology is unchanged.
new = [admission(policy_test_all=True) for _ in range(50_000)]
for k in ("LACTATE_NORMAL", "LACTATE_HIGH"):
    obs = fit(new)[k]
    print(f"{k:15s} model {m[k]:.3f}  observed after policy change {obs:.3f}")

It prints:

p(death | last token): {'ADMIT': 0.024, 'LACTATE_HIGH': 0.239, 'LACTATE_NORMAL': 0.077}
LACTATE_NORMAL  model 0.077  observed after policy change 0.029
LACTATE_HIGH    model 0.239  observed after policy change 0.152

Under the old policy a normal lactate carries 7.7% mortality, because being tested at all marks a suspected septic patient; an untested admission carries 2.4%. After universal testing the same token corresponds to 2.9% mortality, and the model, still answering with 7.7%, overestimates risk by a factor of about 2.7 without any change in patients. The fitted model is correct about the old hospital's records and wrong about the new one, which is the behavior expected from a model of the joint process of physiology and care.

Treating the record as the environment has three operational consequences. Shortcuts. Tokens produced by decisions that anticipate the outcome (a palliative-care consult, a code-status change) let the model predict deaths that the team already expects; headline AUROC rises while clinical value does not. The remedy is a shortcut audit: stratify performance by whether such tokens are in the prompt, re-run with them masked, and place cut points before the decision. Care-policy drift. A new sepsis bundle or lab panel changes \(\pi\) and \(R\), so rollouts describe the old hospital. Action tokens (orders, transfers) drift earlier and in larger volume than outcomes, so monitoring predicted against observed rates of high-volume action tokens by month gives the earliest signal; monthly recalibration fixes risk levels but not the shape of rollouts, which needs fine-tuning on recent data. Site transfer. Recording habits differ by hospital, so a model calibrated at home can be miscalibrated elsewhere; out-of-distribution validation without retraining is one of the checks proposed by Bedi, Fries & Shah (2026).

Why the GPT Style

Three properties make next-event generation attractive compared with training one supervised model per question.

  1. One objective, many tasks. The model is trained once, by maximum likelihood on every token of every timeline. Any question phrased as "does event \(e\) occur before stop condition \(s\)" can then be answered by simulation. ETHOS used the same weights for mortality, readmission, ICU length of stay, SOFA score and DRG class (Renc et al. 2024); the Epic Cosmos models were evaluated on 78 tasks without fine-tuning (Waxler et al. 2025).
  2. Full distributions, not point scores. Sampled futures give the timing of events, their co-occurrence and their order, so the same rollout yields a length of stay, a probability of a complication and the expected number of visits. A classifier gives one number.
  3. "What if" by conditioning. Because the input is just a sequence, one can edit it: append a medication token, change an age band, remove a diagnosis, then simulate again. This is the mechanism people mean when they say these models can "simulate treatment pathways", a claim the ETHOS authors make in their abstract. It is also the most dangerous property, because conditioning on an observed treatment is not the same as intervening, as a 2026 review of medical world models puts it (Liu et al. 2026).

The costs: \(K\) rollouts of possibly thousands of tokens per patient per question, errors that compound over long horizons, and estimates only as calibrated as the model's reproduction of care. Stanford researchers argued in January 2026 that these models are better described as simulators than as validated forecasters, and that a simulation frequency should not be read as a clinical probability without checks (Bedi, Fries & Shah 2026).

A task is a triple. A zero-shot question is defined by a cut point \(t\) that fixes the prompt \(h_t\), a stopping rule \(\sigma\) (a set of stop tokens, a horizon \(H\) measured by summing generated time tokens, or a token budget), and an outcome function \(g\) on the generated segment. The model's answer is

\[ \mathbb{E}_{\tilde{x} \sim p_\theta(\cdot \mid h_t),\ \text{stopped by } \sigma}\big[g(\tilde{x})\big]. \]

One objective therefore serves many tasks: mortality takes \(g = \mathbb{1}[\text{death before discharge}]\), length of stay takes \(g(\tilde{x}) = \sum_j \Delta(\tilde{x}_j)\), the sum of durations \(\Delta\) of time tokens before discharge, and a diagnosis class takes the most frequent generated class token. Because the same \(K\) rollouts serve every \(g\), the full joint distribution of timing, order and co-occurrence is available, not one marginal.

Conditioning is not intervening. Appending \(a\) gives \(p_\theta(g \mid h_t \oplus a) \approx \Pr[g \mid h_t, A = a]\), the outcome among patients observed to receive \(a\). A treatment decision needs \(\Pr[g \mid h_t, \mathrm{do}(A = a)]\). The two coincide only if, given \(h_t\), the choice of \(a\) carries no further information about the outcome (no unmeasured confounding) and similar patients received each option (overlap).

Costs. With \(K\) rollouts of average length \(\bar{L}\), a query costs \(K\bar{L}\) sequential forward steps. The Monte Carlo error \(\sqrt{p_\theta(1-p_\theta)/K}\) shrinks with \(K\); the modeling error \(p_\theta - p\) does not. Errors also compound: if each step's predictive distribution is within total variation \(\varepsilon\) of the true one, the distribution over an \(L\)-token rollout can be off by up to \(L\varepsilon\), so long horizons need more accurate models, not only more samples.

The smallest model with the full GPT-style interface is a count-based next-token model: count which token follows each token in the training timelines, normalize, and sample until a stop token. It sees only the last token, far less than a transformer, but it supports the three properties that motivate the approach: one fitted model answers several questions by changing the outcome predicate, each answer comes from sampled futures, and a "what if" is a prompt edit. The synthetic corpus sends 20% of admissions to the ICU, with death probability 0.30 in the ICU and 0.02 on the ward, so true mortality from admission is \(0.2 \times 0.30 + 0.8 \times 0.02 = 0.076\).

import numpy as np
from collections import defaultdict
STOP = {"DISCHARGE", "DEATH"}

class BigramWorldModel:
    """Count-based next-token model: fit by maximum likelihood, sample until a stop token."""
    def __init__(self, alpha=0.01):
        self.alpha, self.counts = alpha, defaultdict(lambda: defaultdict(float))
    def fit(self, timelines):
        self.vocab = sorted({t for tl in timelines for t in tl})
        for tl in timelines:
            for a, b in zip(tl[:-1], tl[1:]):
                self.counts[a][b] += 1
        return self
    def next_probs(self, last):                                  # -> array [V]
        c = np.array([self.counts[last][v] for v in self.vocab]) + self.alpha
        return c / c.sum()
    def sample(self, history, rng, max_new=50):
        out, last = [], history[-1]
        for _ in range(max_new):
            last = self.vocab[rng.choice(len(self.vocab), p=self.next_probs(last))]
            out.append(last)
            if last in STOP:
                break
        return out

def simulate(model, prompt, K, g, rng):
    """Zero-shot query = (prompt, stop rule, outcome predicate g) -> p_hat = M/K."""
    return np.mean([g(model.sample(prompt, rng)) for _ in range(K)])

died      = lambda f: "DEATH" in f          # question 1
went_icu  = lambda f: "ICU_ADMIT" in f      # question 2, same weights

rng = np.random.default_rng(0)
corpus = []                                  # 20% ICU; death 0.30 in ICU, 0.02 on the ward
for _ in range(5000):
    icu = rng.random() < 0.2
    tl = ["SEX_F", "ADMIT", "ICU_ADMIT" if icu else "LAB_LACTATE"]
    corpus.append(tl + ["DEATH" if rng.random() < (0.3 if icu else 0.02) else "DISCHARGE"])
wm = BigramWorldModel().fit(corpus)

K = 4000
print(f"p_hat(death)              = {simulate(wm, ['SEX_F', 'ADMIT'], K, died, rng):.3f}")
print(f"p_hat(ICU)                = {simulate(wm, ['SEX_F', 'ADMIT'], K, went_icu, rng):.3f}")
print(f"p_hat(death | ICU prompt) = {simulate(wm, ['SEX_F', 'ADMIT', 'ICU_ADMIT'], K, died, rng):.3f}")

It prints:

p_hat(death)              = 0.065
p_hat(ICU)                = 0.200
p_hat(death | ICU prompt) = 0.256

Two questions came from one set of weights. The mortality estimate (0.065) sits below the data-generating 0.076 because the model is fitted to a finite corpus and the estimate carries a Monte Carlo error of about 0.004; the two errors have different remedies (more data versus more rollouts). Placing an ICU token in the prompt raises the estimate to 0.256: a description of patients who were sent to the ICU in this corpus, not the effect of ICU care. In a transformer, next_probs becomes a softmax over the network output conditioned on the whole prompt, and sample becomes a batched loop over \(K\) rows.

Serving cost. Every question is \(K\) rollouts of up to thousands of tokens, generated sequentially. Production samplers batch the \(K\) rollouts of one patient as rows of one batch, cache the prompt's keys and values once and share them across rows, stop each row at its own stop token, and cap the horizon with a token budget. Because the same rollouts serve many outcome predicates, questions about one patient should be grouped into one simulation run rather than issued separately. Adaptive \(K\) helps: patients whose estimate is far from any decision threshold after a few rollouts need no more, and rollouts are spent near the threshold. The Epic Cosmos study's observation that gains mostly plateau around 64 simulations (Waxler et al. 2025) sets a practical upper range.

Incomplete rollouts. A rollout that hits the token budget before a stop token is censored. Counting it as "no event" biases risk downward; dropping it biases toward short, simple futures. The completion rate per task and per subgroup belongs on the monitoring dashboard, and a falling rate is an early sign that the model has drifted.

Calibration and "what if". Simulated frequencies are recalibrated on recent outcomes before display; the recalibration is refit when calibration error by month or by site rises. Prompt edits that append a treatment are best exposed only within a causal analysis protocol, such as a target-trial emulation, rather than as an interactive button, because the output is an observational association. Bedi, Fries & Shah (2026) make the same point in general form: these systems are simulators until their outputs are validated as forecasts.

Lineage: From Multi-State Models to Generative Event Models

GPT-style health world models descend from five threads: survival analysis, decision-analytic simulation, representation learning on records, generative sequence models, and treatment simulators from reinforcement learning. Each contributes a piece that the modern models either inherit or still lack.

Five lineages converging on GPT-style health world models.
Fig. Five threads behind GPT-style health world models. Within a lane, milestones run left to right in time; spacing is ordinal, not to scale. Years are first publication (preprint where earlier).
  1. Survival and multi-state models. Kaplan–Meier curves and the Cox model made "time to event, with censoring" the native question of clinical statistics; multi-state models added transitions among states and competing risks. A generative event model is a multi-state model with a huge learned state space; MOTOR keeps the survival likelihood explicit.
  2. Decision-analytic simulation. Markov cohort models (Sonnenberg & Beck 1993) and microsimulations such as CISNET's cancer natural-history models answer policy questions by rollout, with interventions modifying the natural-history module.
  3. Representation learning on records. Doctor AI (an RNN over about 260K patients' visits), BEHRT, Med-BERT and CLMBR learned patient representations from code sequences. They embed; they do not simulate.
  4. Generative event models. Foresight (2022) generated future clinical concepts; ETHOS (2024) made zero-shot prediction by simulation the method; Delphi-2M (2025) modeled more than 1,000 diseases over a lifetime; the Epic Cosmos models (2025) showed power-law scaling.
  5. Treatment simulators. The AI Clinician (2018) learned sepsis policies from ICU records, prompting guidelines on retrospective RL; the Causal Transformer and the Dreamer-style medDreamer carry this thread into deep learning.

The modern model takes its training recipe from thread 4, its outputs from thread 1, its use pattern (simulate, then count) from thread 2, and from thread 5 the hardest open question: can a simulator learned from observational care answer interventional questions?

Each thread contributes a formal object that the modern model inherits or lacks.

Survival and multi-state models. With distinct event times \(t_i\), \(d_i\) events and \(n_i\) patients still at risk, the Kaplan–Meier estimator is \(\hat{S}(t) = \prod_{t_i \le t} (1 - d_i / n_i)\); censored patients leave the risk set without counting as events. The Cox model writes the hazard as \(\lambda(t \mid z) = \lambda_0(t)\exp(\beta^\top z)\). A multi-state model assigns a transition hazard \(q_{jk}(t)\) to each pair of states, and a generative event model can be read as one whose "state" is the full history and whose next-event distribution plays the role of all \(q_{jk}\) at once. MOTOR keeps the likelihood explicit with piecewise-constant hazards, so each event \(v\) contributes \(\log \lambda_v(t) - \int_0^{t}\lambda_v(u)\,du\) and censored ones only the integral term.

Decision-analytic simulation. A Markov cohort model evolves \(\pi_{n+1} = \pi_n P\); a policy changes \(P\) to \(P_A\) or \(P_B\), and outcomes are compared by rollout. This is the "simulate, then count" estimator with a hand-specified simulator.

Representation learning. An encoder \(f_\theta(h_t) \in \mathbb{R}^d\) pretrained on next-code prediction is followed by a task head \(\sigma(w^\top f_\theta(h_t))\) fitted per task. It answers only the tasks it has heads for.

Generative event models. The same pretraining objective, \(-\sum \log p_\theta(x_s \mid x_{<s})\), with the head replaced by sampling: \(\hat{p} = K^{-1}\sum_k g(\tilde{x}^{(k)})\).

Treatment simulators. A Markov decision process with states, actions and rewards, and a policy value \(V^{\pi_e}\) estimated from data collected under clinicians' policy \(\pi_b\). Importance sampling weights each trajectory by \(\prod_\tau \pi_e(a_\tau \mid s_\tau)/\pi_b(a_\tau \mid s_\tau)\); with long horizons and little overlap these weights explode, which is the fragility that guidelines on retrospective reinforcement learning warn about.

Thread 1 supplies the correct handling of censoring, and thread 4 supplies estimation by simulation. The script below generates 2,000 event times with a constant hazard of 0.10 per year and censors them at uniform follow-up times, as happens when patients leave a health system. It compares three estimates of five-year survival: the Kaplan–Meier product over event times, a naive estimate that treats censored patients as survivors, and a generative estimate that fits the hazard as events divided by person-time and then samples 10,000 simulated futures.

import numpy as np
rng = np.random.default_rng(2)
n, lam, t_eval = 2000, 0.10, 5.0                # true hazard 0.10/year -> S(5) = exp(-0.5)
T = rng.exponential(1 / lam, n)                  # event times
C = rng.uniform(0, 10, n)                        # censoring (loss to follow-up)
time, event = np.minimum(T, C), T <= C

def kaplan_meier(time, event, t):
    """S(t) = prod over event times t_i <= t of (1 - d_i / n_i)."""
    S = 1.0
    for ti in np.unique(time[event & (time <= t)]):
        n_at_risk = np.sum(time >= ti)
        S *= 1 - np.sum((time == ti) & event) / n_at_risk
    return S

naive = 1 - np.mean(event & (time <= t_eval))   # treats censored patients as survivors
# Thread 1 meets thread 4: estimate the hazard (events / person-time), then simulate futures
lam_hat = event.sum() / time.sum()
sim = np.mean(rng.exponential(1 / lam_hat, 10_000) > t_eval)
print(f"true S(5)={np.exp(-lam * t_eval):.3f}  KM={kaplan_meier(time, event, t_eval):.3f}  "
      f"naive={naive:.3f}  simulated from fitted hazard={sim:.3f}")

It prints:

true S(5)=0.607  KM=0.618  naive=0.707  simulated from fitted hazard=0.609

The naive estimate overstates survival by about 0.10 because patients lost to follow-up before dying are counted as alive. Kaplan–Meier and the simulated futures both land within about 0.01 of the true 0.607, because both use the at-risk set correctly; the simulator does so through its fitted hazard. A generative event model trained on timelines faces the same issue in a different form: a training timeline that ends because the extract ends is not a timeline in which nothing happened, and evaluation labels built from such timelines need the same care.

Each thread leaves a production obligation. From survival analysis: evaluation labels are censored. A readmission label from a timeline that ends at the extract date is unknown rather than negative; label construction must track follow-up and exclude or weight patients without the full window. From decision-analytic simulation: validation of the simulator as a whole, not only of single predictions; a simulated population should reproduce observed event frequencies, which is how Akagi et al. (2026) judged a hospital simulator (correlation above 0.98 between simulated and real event frequencies). From representation learning: strong baselines. A pretrained encoder with a logistic head, or a gradient-boosted model on simple features, is cheap to serve; one 2026 study of an ETHOS-family outpatient model found that a gradient-boosted model on age and visit counts came close on new diagnoses and outperformed it on readmission (Ramachandran & Shah 2026). A generative model must beat that baseline by enough to justify the sampling cost. From generative event models: scale and its budget. The Epic Cosmos models showed power-law scaling with a compute-optimal ratio of roughly 1,000 tokens per parameter (Waxler et al. 2025), which ties model size to the volume of records available. From treatment simulators: skepticism about off-policy estimates. Gottesman et al. (2019) showed how confounding, small effective sample sizes and poorly specified rewards can make a bad policy look good; any treatment comparison drawn from a health world model inherits these risks.

A Taxonomy of Health World Models

"Health world model" covers at least five kinds of system that differ in what state they simulate, at what time scale, and how they are judged. Most published work fits one row of the table below; the GPT-style event models of this half are the first row.

KindState simulatedTypical dataExamplesHow it is evaluated
EHR event modelsNext coded event and its timing (diagnoses, labs, drugs, admissions)Hospital EHR, claims, OMOP or MEDS extractsETHOS, Foresight, CEHR-GPT, CoMETZero-shot AUROC/AUPRC on clinical tasks, calibration, synthetic-data fidelity and privacy
Disease-trajectory modelsOnset of many diseases across a lifetimeBiobanks, national registriesDelphi-2M, DT-TransformerAge-stratified AUC per disease, incidence reproduction, external cohorts
Physiological and wearable dynamicsContinuous signals (heart rate, glucose, vitals) minutes to weeks aheadWearables, bedside monitorsLSM (wearables), DT-GPTForecast error (MAE, scaled MAE), imputation error, downstream classification
ICU and treatment simulatorsPatient state under a sequence of treatmentsICU databases (MIMIC, eICU)AI Clinician, medDreamer, treatment-conditioned diffusionOff-policy evaluation, agreement with randomized trials, clinician review
Digital twinsAn individual's trajectory, often in one disease, for planning or trial designDisease registries, trials, mechanistic modelsTwinWeaver / Genie Digital Twin, mechanistic organ modelsForecast error and C-index on held-out patients and trials, prospective use

Table. Kinds of health world model. The boundaries blur: Delphi-2M is an event model restricted to diseases, and several "digital twins" are LLM forecasters over EHR text. Sources are linked in the sections that discuss each system.

A second axis cuts across the rows: a pure forecaster conditions on history; a policy-conditioned simulator also conditions on future actions. Only the second can, in principle, compare treatments, and only under the assumptions in Prediction Is Not Intervention.

The five kinds differ in the variable being simulated and in what is conditioned on. EHR event models simulate a discrete sequence \(x_{t+1:T'}\) over a large vocabulary; disease-trajectory models restrict the vocabulary to disease onsets \(v\) and model a waiting time, often as a rate \(\lambda_v(\text{age} \mid h_t)\); physiological models forecast a continuous vector \(y_{t+1:t+H} \in \mathbb{R}^{H \times d}\) and are scored by errors such as \(\mathrm{MAE} = \frac{1}{Hd}\sum |y - \hat{y}|\); treatment simulators model \(s_{\tau+1} \sim P(\cdot \mid s_\tau, a_\tau)\) inside a decision process; digital twins condition on one individual, often within one disease.

The cross-cutting axis is formal. A pure forecaster estimates \(p(y \mid h_t)\), which averages over whatever actions clinicians will take:

\[ p(y \mid h_t) = \sum_{a} \pi(a \mid h_t)\, p(y \mid h_t, a). \]

A policy-conditioned simulator estimates \(p(y \mid h_t, a_{t:t+H})\) for an action sequence chosen by the user. Reading it as \(p(y \mid h_t, \mathrm{do}(a))\) requires consistency (the observed outcome under the received treatment is the potential outcome), sequential exchangeability (no unmeasured confounders given the history) and positivity (\(\pi(a \mid h) > 0\) wherever the comparison is made). If a confounder \(s\) is recorded, the g-formula gives \(p(y \mid \mathrm{do}(a)) = \sum_s p(s)\, p(y \mid s, a)\); if it is not, no amount of data identifies the effect.

The difference between a forecaster and a policy-conditioned simulator is easiest to see on synthetic data with a known truth. In the script below, 30% of patients are severely ill, a fact absent from the record; clinicians treat 80% of severe and 20% of mild patients; treatment halves the death risk (0.40 severe, 0.05 mild before treatment). The script compares the forecaster's answer, the naive treatment-conditioned answer fitted from the record, the interventional truth, and the adjusted answer that becomes available if severity is recorded.

import numpy as np
rng = np.random.default_rng(3)
n = 200_000
severe = rng.random(n) < 0.3                                  # not in the record
treated = rng.random(n) < np.where(severe, 0.8, 0.2)          # clinicians treat the sicker
risk = np.where(severe, 0.40, 0.05) * np.where(treated, 0.5, 1.0)   # treatment halves risk
died = rng.random(n) < risk

# Pure forecaster p(death | h): averages over whatever the clinicians did
print(f"forecaster        p(death | h)        = {died.mean():.3f}")
# Policy-conditioned simulator fitted naively from the record: p(death | h, a)
for a in (0, 1):
    print(f"conditioned       p(death | h, a={a})   = {died[treated == a].mean():.3f}")
# Interventional truth do(a): same population, treatment set by fiat
for a in (0, 1):
    print(f"interventional    p(death | do(a={a}))  = {(0.3*0.40 + 0.7*0.05) * (0.5 if a else 1):.3f}")
# With severity recorded, adjust (g-formula): sum_s p(s) p(death | s, a)
for a in (0, 1):
    adj = sum(np.mean(severe == s) * died[(severe == s) & (treated == a)].mean() for s in (0, 1))
    print(f"adjusted for s    p(death | do(a={a}))  = {adj:.3f}")

It prints:

forecaster        p(death | h)        = 0.102
conditioned       p(death | h, a=0)   = 0.082
conditioned       p(death | h, a=1)   = 0.135
interventional    p(death | do(a=0))  = 0.155
interventional    p(death | do(a=1))  = 0.077
adjusted for s    p(death | do(a=0))  = 0.152
adjusted for s    p(death | do(a=1))  = 0.077

The forecaster is correct for what it claims (10.2% of these patients die under current care). The naive conditioned simulator says treatment raises mortality from 8.2% to 13.5%, the opposite of the truth (15.5% untreated, 7.7% treated), because treated patients are sicker. Recording severity and adjusting with the g-formula recovers the interventional values (0.152 and 0.077). A health world model that appends a treatment token and resamples behaves like the naive row unless every confounder is in the prompt.

The rows of the taxonomy differ in production as much as in method. EHR event models sit on OMOP or MEDS extracts refreshed from the hospital record, are served as samplers, and fail through care-policy drift and site transfer; their dashboards track calibration and timeline completion by month and site. Disease-trajectory models run on biobank or registry snapshots updated rarely; their risks are long-horizon, so validation relies on external cohorts, as Delphi-2M did by moving from UK Biobank to Danish registries without changing parameters. Physiological and wearable models run on streaming signals, often on device; their failures are sensor changes, missing data and firmware updates, and they are monitored with forecast error on rolling windows. Treatment simulators produce off-policy estimates that cannot be checked against outcomes the data never contain, so their outputs are reviewed by clinicians and compared with randomized trials where trials exist. Digital twins used for trial design or individual planning need prospective evaluation before their forecasts inform decisions.

The forecaster versus simulator distinction determines how a system may be used. A forecaster can support triage, monitoring and resource planning, where the question is what will happen under current care. A policy-conditioned simulator invites comparisons of treatments, and a product that offers that comparison needs a documented causal argument (confounders measured, overlap checked, sensitivity analysis) for each use, not only good predictive metrics.

ETHOS: Enhanced Transformer for Health Outcome Simulation

ETHOS turns each patient's hospital record into one long token sequence, trains a GPT-2-style decoder to predict the next token, and answers clinical questions by generating the patient's future many times and counting outcomes. Renc et al. (2024), a team from Massachusetts General Hospital, Harvard Medical School, MIT, Brigham and Women's and AGH University in Kraków, published it as "Zero shot health trajectory prediction using transformer" in npj Digital Medicine in September 2024 (doi:10.1038/s41746-024-01235-0). Details below come from the arXiv version (v1); I could not open the journal page itself.

The design has three simple parts: a Patient Health Timeline (PHT) that flattens heterogeneous records into tokens, a decoder-only transformer trained with the language-modeling loss, and zero-shot inference by simulation. Every choice is spelled out, so the pipeline can be rebuilt from first principles.

The method as three maps. ETHOS (Renc et al. 2024) can be written as a tokenizer, a sequence model and an estimator. A tokenizer \(\tau\) maps a patient record \(R\) to a sequence \(x_{1:T} = \tau(R)\) over a finite vocabulary \(\mathcal{V}\). A model \(p_\theta\) assigns a probability to every next token, \(p_\theta(x_t \mid x_{<t})\), and is fitted by maximum likelihood on the training timelines. A clinical question is then a triple \((t_0, \mathcal{S}, g)\): a cut point \(t_0\) that ends the prompt \(h = x_{\le t_0}\), a set of stop tokens \(\mathcal{S}\) (or a time budget) that ends a sampled future, and a function \(g\) that reads the outcome off a completed future \(\tilde{x}\).

\[ \text{answer}(h) = \mathbb{E}_{\tilde{x} \sim p_\theta(\cdot \mid h)}\big[g(\tilde{x})\big] \;\approx\; \frac{1}{K}\sum_{k=1}^{K} g\big(\tilde{x}^{(k)}\big). \]

For a binary outcome such as in-hospital death, \(g\) is an indicator and the answer is a probability; for ICU length of stay, \(g\) sums the durations of the generated interval tokens.

Three sources of error. The gap between the reported estimate \(\hat{p}\) and the true clinical probability \(p\) splits into a tokenization term, a modeling term and a Monte Carlo term:

\[ p - \hat{p} = \underbrace{(p - p_\tau)}_{\text{information lost by } \tau} + \underbrace{(p_\tau - p_\theta)}_{\text{model error}} + \underbrace{(p_\theta - \hat{p})}_{\text{sampling error}}, \]

where \(p_\tau\) is the best probability achievable from the tokenized history. Only the last term shrinks with more samples, at rate \(1/\sqrt{K}\). The first is fixed once the vocabulary is fixed (deciles, binned gaps, no notes), and the second is what training and data reduce.

Cost. Training costs roughly \(6ND\) floating-point operations for \(N\) parameters and \(D\) processed tokens. A query costs \(K \cdot L\) generated tokens for rollouts of mean length \(L\), and nothing beyond one forward pass when the answer is the next token itself.

The whole method on a toy hospital: a ground-truth generator with a hidden severity produces timelines (admission, a daily lab that is high or low, a daily interval token, then discharge or death); a small decoder-only transformer is trained on 20,000 of them with the next-token loss alone; and death risk is estimated by sampling 2,000 futures from three prompts. Because the generator is known, the exact risk given the labs seen so far can be computed by Bayes' rule and compared with the simulated one. TinyGPT is a standard causal transformer and rollout_risk a parallel sampler that stops each future at a discharge or death token and returns the fraction ending in death, its standard error and the fraction of unfinished futures; both are listed in full, with their own tests, in the code for the training objective and for zero-shot inference below.

import torch, torch.nn.functional as F
from c3_model import TinyGPT
from c4_rollout import rollout_risk

PAD, ADMIT, HI, LO, GAP, DISCH, DEATH = range(7)
NAMES = ["PAD", "ADMIT", "LAB_HI", "LAB_LO", "GAP_1D", "DISCHARGE", "DEATH"]

def simulate_patient(g):
    """Ground-truth generator: hidden severity, a daily lab, daily chance of leaving hospital."""
    sick = torch.rand(1, generator=g).item() < 0.3
    seq = [ADMIT]
    for day in range(8):
        seq.append(HI if torch.rand(1, generator=g).item() < (0.8 if sick else 0.2) else LO)
        if day == 7 or torch.rand(1, generator=g).item() < 0.25:
            die = torch.rand(1, generator=g).item() < (0.4 if sick else 0.05)
            return seq + [DEATH if die else DISCH]
        seq.append(GAP)

def true_risk(labs):
    """Exact P(death | labs so far) under the generator (posterior over severity)."""
    ls, lh = 0.3, 0.7
    for l in labs: ls *= 0.8 if l == HI else 0.2; lh *= 0.2 if l == HI else 0.8
    w = ls / (ls + lh); return w * 0.4 + (1 - w) * 0.05

g = torch.Generator().manual_seed(0); torch.manual_seed(0)
data = torch.zeros(20_000, 18, dtype=torch.long)                     # 1) build training timelines
for i in range(len(data)):
    s = simulate_patient(g); data[i, :len(s)] = torch.tensor(s)
model = TinyGPT(7, d=64, layers=2, heads=4, ctx=17, dropout=0.0)    # 2) next-token training
opt = torch.optim.AdamW(model.parameters(), lr=1e-3)
for step in range(3000):
    b = data[torch.randint(len(data), (128,))]
    loss = F.cross_entropy(model(b[:, :-1]).flatten(0, 1), b[:, 1:].flatten(), ignore_index=PAD)
    opt.zero_grad(); loss.backward(); opt.step()
print("final training loss %.3f nats/token" % loss.item())
model.eval()                                                          # 3) simulate and count
gap = torch.tensor([0., 0., 0., 0., 1440., 0., 0.])
for prompt in ([ADMIT, HI], [ADMIT, LO], [ADMIT, HI, GAP, HI]):
    p, se, inc = rollout_risk(model, torch.tensor(prompt), 2000, torch.tensor([DISCH, DEATH]),
                              torch.tensor([DEATH]), gap, max_new=20)
    labs = [t for t in prompt if t in (HI, LO)]
    print("%-28s simulated %.3f +- %.3f   exact %.3f   incomplete %.3f"
          % (" ".join(NAMES[t] for t in prompt), p, se, true_risk(labs), inc))

Output (about two and a half minutes on two CPU cores):

final training loss 0.607 nats/token
ADMIT LAB_HI                 simulated 0.269 +- 0.010   exact 0.271   incomplete 0.000
ADMIT LAB_LO                 simulated 0.087 +- 0.006   exact 0.084   incomplete 0.001
ADMIT LAB_HI GAP_1D LAB_HI   simulated 0.374 +- 0.011   exact 0.355   incomplete 0.002

No outcome label was used in training, yet the simulated risks track the exact ones within about two standard errors, including the update after a second high lab. The residual gaps are model error rather than sampling error: more futures would tighten the intervals around the model's probabilities, not move them onto the truth. The same three steps, at the scale of 241,015 patients and a 2,048-token context, are ETHOS.

Three components, three systems. In a deployment the three parts of ETHOS become separate pieces of infrastructure with different owners and failure modes. The timeline builder is an extract-transform-load job over the hospital's tables; the 2025 reimplementation, ETHOS-ARES, moved this step onto the MEDS data standard and published the code (ethos-ares). The model is a periodic training job. The simulator is an inference service whose cost scales with the number of questions, the number of futures per question and the length of each future.

What must be versioned together. Token identities are defined by the tokenizer: the decile edges, the code maps and the interval bins. A model is valid only with the exact tokenizer it was trained with, so the two ship as one artifact, and a change to either (a new lab assay, a new ICD-10-CM release, a revised bin) is a model change that needs revalidation.

Where it fails. The weak points sit at the boundaries between components: silent shifts in what a token means (a new assay moves values between deciles), rollouts that stop on the token budget instead of a clinical stop token, and probabilities that are discriminative but not calibrated. The original paper established discrimination on one hospital's held-out patients; calibration, subgroup performance and transfer to other sites have to be measured for each deployment, and in the United States a model that is updated after clearance is expected to follow a predetermined change control plan (FDA guidance, 2024).

Where cost goes. Training is a fixed cost of days on a few GPUs. Inference dominates over time: every question asked of every patient generates thousands of tokens, which is why production systems answer next-token questions directly and reserve sampling for outcomes that need a future.

Building the Patient Health Timeline

A Patient Health Timeline is a patient's events from MIMIC-IV placed in chronological order and rewritten as tokens, with explicit tokens for the passage of time. MIMIC-IV is a de-identified database of patients at Beth Israel Deaconess Medical Center in Boston; ETHOS drew on its patient, admission, ICU-stay, lab, prescription, procedure, diagnosis, medication-administration, outpatient-measurement, service and DRG tables, plus a derived SOFA score. Clinical notes were not used.

The construction steps, as described in the paper:

  1. Collect, harmonize, order. Each event is stamped with the patient's age (a 64-bit float) and sorted; ICD-9 diagnoses are converted to ICD-10-CM, drug codes to ATC, and labs restricted to the 200 most frequent tests (about 95% of lab events).
  2. Tokenize each event into 1 to 7 tokens (next section).
  3. Insert time-interval tokens between events: none for gaps under 5 minutes, 13 interval tokens in all, and repeated 6-month tokens for gaps over a year.
  4. Strip the timestamps. The model never sees a clock, only the order of events and the binned gaps between them.
  5. Split by patient, 90/10: 241,015 training/validation and 26,758 test patients.

Step 4 is the key move. Instead of a continuous time embedding, ETHOS makes time part of the vocabulary, so the model must generate time, which is what lets a rollout estimate length of stay or respect a 30-day horizon.

Records as marked point processes. A patient record is a finite set of events \(\{(a_i, e_i)\}_{i=1}^{n}\), where \(a_i\) is the patient's age at the event and \(e_i\) its content (a code, a lab value, an admission). The Patient Health Timeline sorts the events by age, \(a_{(1)} \le a_{(2)} \le \dots \le a_{(n)}\), with a fixed rule for ties, and replaces the absolute ages by gaps \(\delta_i = a_{(i)} - a_{(i-1)}\).

Gap binning. With bin edges \(0 < e_1 < \dots < e_B\) (in ETHOS, \(e_1\) is 5 minutes and there are 13 interval tokens in all), a gap becomes

\[ \beta(\delta) = \begin{cases} \varnothing, & \delta < e_1,\\ (\underbrace{D, \dots, D}_{\lfloor \delta / D \rfloor}, \beta(\delta \bmod D)), & \delta \ge D,\\ b \text{ such that } e_b \le \delta < e_{b+1}, & \text{otherwise,} \end{cases} \]

where \(D\) is the 6-month token used for gaps over a year. Giving each interval token a representative duration \(\Delta(v)\) turns a generated sequence back into elapsed time, \(\hat{\tau} = \sum_j \Delta(\tilde{x}_j)\). The map is lossy: a sum over \(n\) generated gaps carries up to \(n\) bin widths of rounding error, and gaps under 5 minutes contribute nothing.

Windows. With context length \(C\) and six static tokens, a timeline of length \(T\) is cut into \(\lceil (T-6)/(C-6) \rceil\) windows, each beginning with the static tokens. The model conditions on demographics plus at most \(C-6\) recent tokens; anything older is forgotten.

Why split by patient. Evaluation assumes test timelines are drawn independently of the fitted parameters. Splitting by event or by window would place earlier parts of a test patient's record in training, so the model could recall rather than predict; splitting by patient (90/10 in ETHOS) restores that independence at the level of people.

The functions below build a Patient Health Timeline from time-stamped events: sort, insert interval tokens, drop timestamps, cut windows that keep the static tokens first, and split by patient. Bin edges are illustrative; ETHOS used 13 interval tokens. The events are those of the fictional patient in the tokenization figure, deliberately passed out of order.

import numpy as np

GAP_EDGES  = [5, 15, 60, 120, 360, 720, 1440, 4320, 10080, 43200, 129600]   # minutes
GAP_TOKENS = ["5m-15m", "15m-1h", "1h-2h", "2h-6h", "6h-12h", "12h-1d",
              "1d-3d", "3d-1w", "1w-1mt", "1mt-3mt", "3mt-6mt"]
SIX_MONTHS = 259200

def gap_tokens(minutes):
    """Gap in minutes -> interval tokens. None under 5 min; repeated '=6mt' for long gaps."""
    out = []
    while minutes >= SIX_MONTHS:
        out.append("=6mt"); minutes -= SIX_MONTHS
    if minutes >= 5:
        out.append(GAP_TOKENS[np.searchsorted(GAP_EDGES, minutes, side="right") - 1])
    return out

def build_pht(static, events, encode):
    """Sort (minute, event) pairs, encode each event, insert gap tokens, drop the clock."""
    toks, last = list(static), None
    for minute, ev in sorted(events, key=lambda e: e[0]):
        if last is not None:
            toks += gap_tokens(minute - last)
        toks += encode(ev)
        last = minute
    return toks

def windows(ids, static_n=6, ctx=2048):
    """ctx+1 training windows that all start with the patient's static tokens."""
    static, body = ids[:static_n], ids[static_n:]
    step = ctx + 1 - static_n
    return [static + body[i:i + step] for i in range(0, max(1, len(body) - step + 1), step)]

def split_patients(ids, test_frac=0.1, seed=0):
    """Split by patient, never by event or window."""
    rng = np.random.default_rng(seed); ids = np.array(ids); rng.shuffle(ids)
    n = int(round(len(ids) * test_frac)); return set(ids[n:]), set(ids[:n])

static = ["SEX_F", "RACE_WHITE", "MARRIED", "BMI_Q7", "AGE_65-70", "START_2015-20"]
ev = [(1100, ["LAB_CREAT", "Q9"]), (0, ["ED_START"]), (90, ["LAB_CREAT", "Q10"]),
      (295, ["INPATIENT_ADMIT"]), (320, ["ICD_N17", "ICD_9"]),
      (350, ["ATC_C03", "ATC_CA01"]), (352, ["LAB_K", "Q2"])]
print(" ".join(build_pht(static, ev, encode=lambda e: e)[6:]))
w = windows(list(range(5000)))
print(len(w), "windows of", len(w[0]), "tokens; all start with static:", all(x[:6] == list(range(6)) for x in w))
tr, te = split_patients(range(267773))
print(len(tr), "train/val patients,", len(te), "test patients, overlap", len(tr & te))

Output:

ED_START 1h-2h LAB_CREAT Q10 2h-6h INPATIENT_ADMIT 15m-1h ICD_N17 ICD_9 15m-1h ATC_C03 ATC_CA01 LAB_K Q2 12h-1d LAB_CREAT Q9
2 windows of 2049 tokens; all start with static: True
240996 train/val patients, 26777 test patients, overlap 0

The token sequence matches the figure, including the absent interval token before the potassium result two minutes after the drug. The patient count is the ETHOS total (241,015 + 26,758); a random 10% split lands within a few dozen patients of the published sizes.

Ordering is a data-engineering decision. Sorting by age is simple until many events share a timestamp: an admission, its first labs and its diagnoses are often charted to the same minute. The tie-breaking rule must be deterministic and clinically sensible (admission before the labs drawn during it, discharge after the last medication), or the training data contain arbitrary orderings that the model learns as if they were dynamics. ETHOS stamps each event with age as a 64-bit float, which keeps minute resolution over a lifetime.

Which timestamp. A lab has a specimen time and a result time; a diagnosis code is often assigned at discharge but dated to admission. A timeline built on the earlier timestamp places information in the prompt before it was available, which inflates offline results and disappears in deployment. The prompt cut must use the time each fact became visible to the care team. DRG codes illustrate the point: ETHOS places them after discharge, where they are known.

Harmonization debt. MIMIC-IV mixes ICD-9 and ICD-10 eras, so ETHOS converts diagnoses to ICD-10-CM and drugs to ATC; one-to-many mappings make these conversions approximate. Restricting labs to the 200 most frequent tests keeps about 95% of lab events and silently drops the rest. ETHOS-ARES rebuilt the pipeline on the MEDS format to make these steps reproducible across datasets (Renc et al. 2025).

What to monitor. Tokens per patient and the fraction of timelines longer than the 2,048-token context (those lose their oldest history at inference); the share of events dropped by each filter; and the rate of identical timestamps per table. Clinical notes were not used, so any information that lives only in notes is outside the model.

The Token Vocabulary

ETHOS's vocabulary is designed so that every kind of event becomes a short, fixed pattern of tokens: categorical codes are split into hierarchical pieces, numbers become a type token plus a decile token, and time gaps become interval tokens. Six static tokens open every timeline.

Event typeTokens per eventUnique tokensHow it is encoded
Static: sex, race, marital status, BMI, age at start, years since 1970 at start1 each (positions 1–6)2, 6, 5, 1+10 quantiles, 21, 21Age and start year in 5-year bands; BMI as a quantile
Diagnoses (ICD-10-CM)1–32,936First three characters, next two, then the remaining suffix
Procedures (ICD-10-PCS)1–735One token per character
Administered medications (ATC)1–3312Hierarchical pieces of the ATC code
Lab tests2200 (+10 quantiles)Test token followed by a decile token Q1–Q10
Blood pressure31 (+10)Marker, systolic decile, diastolic decile
SOFA score21 (+10)Placed after ICU admission; score mapped to deciles
DRG1772771 classes plus unknown, placed after discharge
Stays and transfers1–6ED 2, inpatient 18, ICU 11, transfers 19Admission, discharge and transfer events (some with quantile tokens)
Time intervals1 (more if > 1 year)13Binned gap since the previous event; none under 5 minutes
Death, end of timeline11 eachTerminal tokens used as stopping conditions

Table. The ETHOS token vocabulary, from the paper's Table S2 and Methods (Renc et al. 2024). Quantile boundaries are computed from training-set histograms. The paper does not report a single total vocabulary size in the text I read.

Splitting codes shrinks the vocabulary and lets rare codes share statistics with their parent category. Quantile binning makes labs generatable with ten tokens per test, at the cost of resolution: a top-decile creatinine is one token whether mildly or extremely high. The figure applies these rules to a fictional patient.

Worked example: a fictional patient's record turned into ETHOS-style tokens.
Fig. Worked tokenization of a fictional patient, following the ETHOS rules: six static tokens, then each event as a short token pattern preceded by a time-interval token. ICD-10-CM N17.9 splits into its three-character category and the remainder; each lab becomes a test token plus a decile token. Token spellings are mine, and the exact ATC split points are illustrative. Reading the chips left to right, top to bottom gives the sequence the transformer is trained on.

Decile tokens. For lab test \(\ell\), let \(q_{\ell,1} < \dots < q_{\ell,9}\) be the 10th to 90th percentiles of that test's values among training patients. A value \(y\) becomes the token \(Q_j\) with

\[ j = 1 + \#\{m : q_{\ell,m} \le y\}. \]

By construction each decile has training frequency 0.1, so the value token has marginal entropy \(\ln 10 \approx 2.30\) nats, the maximum for ten symbols. The map discards everything inside a bin: \(\Pr(Q_{10})\) is the same for a value at the 91st percentile and one ten times higher, and the tails, where clinical meaning concentrates, are the widest bins.

Hierarchical codes. An ICD-10-CM code \(c\) becomes up to three tokens: category \(c_{1:3}\), the next two characters \(c_{4:5}\) and the suffix \(c_{6:}\). The autoregressive model then factorizes

\[ p(c \mid h) = p(c_{1:3} \mid h)\; p(c_{4:5} \mid h, c_{1:3})\; p(c_{6:} \mid h, c_{1:5}), \]

so a rare code shares its first factor with every code in its category. With \(n_1, n_2, n_3\) distinct pieces, about \(n_1 + n_2 + n_3\) tokens can represent up to \(n_1 n_2 n_3\) codes. The same holds for ATC drugs and, with one token per character, for ICD-10-PCS procedures.

Vocabulary size. Summing the unique-token column of the table, with one shared set of ten quantile tokens, gives roughly 4,400 tokens; the paper does not report a total, and ETHOS-ARES reports about 4,500 with a larger event set. At this size the output softmax is a small part of compute: a \(d = 768\) model spends about \(Vd \approx 3.4\)M parameters on it.

Sequence length. If an event uses \(m\) tokens on average and a fraction \(\rho\) of events is preceded by an interval token, a window of \(C\) tokens covers about \((C-6)/(m+\rho)\) events. Every token spent on an event's structure is history the model cannot see.

The code fits decile edges on synthetic training values, splits ICD-10-CM codes into hierarchical pieces, checks that the decile token carries \(\ln 10\) nats on held-out values, shows how wide the top bin is, and measures what a 15% assay bias does to the token distribution with the population stability index (PSI). Lab distributions are synthetic stand-ins for creatinine and potassium.

import numpy as np

def icd10_tokens(code):
    """'N17.9' -> ['ICD_N17', 'ICD_9']: 3-char category, next two chars, suffix."""
    c = code.replace(".", "")
    return ["ICD_" + p for p in (c[:3], c[3:5], c[5:]) if p]

class Deciles:
    """Per-test decile edges fitted on TRAINING values only; value -> 'Q1'..'Q10'."""
    def fit(self, values_by_test):
        self.edges = {t: np.quantile(v, np.linspace(0.1, 0.9, 9)) for t, v in values_by_test.items()}
        return self
    def index(self, test, values):
        return np.searchsorted(self.edges[test], values, side="right")          # 0..9
    def token(self, test, value):
        return f"Q{int(self.index(test, value)) + 1}"

def entropy(counts):
    p = counts / counts.sum(); p = p[p > 0]; return float(-(p * np.log(p)).sum())

def psi(ref, new, eps=1e-6):
    """Population stability index between two bin distributions."""
    a, b = np.clip(ref, eps, None), np.clip(new, eps, None)
    return float(((b - a) * np.log(b / a)).sum())

rng = np.random.default_rng(0)
train = {"CREAT": rng.lognormal(0.0, 0.65, 50_000), "K": rng.normal(4.2, 0.5, 50_000)}
test  = {"CREAT": rng.lognormal(0.0, 0.65, 20_000), "K": rng.normal(4.2, 0.5, 20_000)}
dec = Deciles().fit(train)
print(icd10_tokens("N17.9"), icd10_tokens("S72.001A"), dec.token("CREAT", 3.1), dec.token("K", 3.2))
idx = dec.index("CREAT", test["CREAT"])
print("test entropy of creatinine decile token: %.3f nats (ln 10 = %.3f)"
      % (entropy(np.bincount(idx, minlength=10)), np.log(10)))
top = test["CREAT"][idx == 9]
print("Q10 creatinine spans %.2f to %.2f mg/dL (one token)" % (top.min(), top.max()))
shifted = dec.index("CREAT", 1.15 * test["CREAT"])          # same patients, assay reads 15% higher
f0, f1 = np.bincount(idx, minlength=10) / len(idx), np.bincount(shifted, minlength=10) / len(idx)
print("after +15%% assay bias: Q10 share %.3f -> %.3f, PSI %.3f" % (f0[9], f1[9], psi(f0, f1)))

Output:

['ICD_N17', 'ICD_9'] ['ICD_S72', 'ICD_00', 'ICD_1A'] Q10 Q1
test entropy of creatinine decile token: 2.302 nats (ln 10 = 2.303)
Q10 creatinine spans 2.30 to 16.02 mg/dL (one token)
after +15% assay bias: Q10 share 0.101 -> 0.145, PSI 0.045

Two consequences are visible. A sevenfold range of creatinine collapses into one token, which is the resolution cost of decile binning. And a modest calibration change in the laboratory moves 4% of all creatinine values into the top decile without any change in the patients, which the frozen tokenizer cannot distinguish from sicker patients.

The tokenizer is a model component. Decile edges are statistics of one hospital's training years. They should be stored, versioned and shipped with the weights, and the edges of a deployed model are never refitted on new data without retraining or fine-tuning, because refitting changes what each \(Q_j\) means.

Drift in meaning. When a laboratory changes an assay, a unit or a reference method, the same physiology lands in a different decile. The standard monitor is the share of incoming values per decile for each test, which should stay near 10%, summarized daily by the population stability index; a common rule of thumb treats values above 0.1 as a shift worth investigating. Assay changes are better handled upstream by converting new values to the old scale using paired samples from the laboratory's parallel-testing period than by refitting the edges.

New codes. ICD-10-CM is revised every year, and new drugs receive new ATC codes. Hierarchical splitting softens this: a new code usually reuses its category and middle pieces and only its suffix is unseen. The unknown-token rate per source table is the monitor; a jump usually means a code-map update was missed.

Transfer between sites. Quantile edges are site-specific, so "Q10 creatinine" at one hospital is not the same value range at another. Moving a model to a second site requires either reusing the original edges (and accepting a shifted token distribution) or refitting them and fine-tuning. ETHOS-ARES grew the vocabulary to about 4,500 tokens with 19 interval tokens, HCPCS codes, vitals and emergency-department events (Renc et al. 2025), which shows the vocabulary as a design surface that changes between versions, each change requiring revalidation.

Resolution where it matters. Deciles spend equal tokens on the normal range and the tails. Where extreme values drive decisions (potassium, lactate), finer tail bins or more quantiles per test are cheap at a 4,500-token vocabulary; the cost is longer training to learn the extra tokens.

Training Objective and Model

ETHOS is trained exactly like a language model: maximize the probability of each token given all the tokens before it, over every timeline in the training set. For one timeline \(x_{1:T}\) the model factorizes the joint probability with the chain rule and minimizes the negative log-likelihood:

\[ p_\theta(x_{1:T}) = \prod_{t=1}^{T} p_\theta(x_t \mid x_{<t}), \qquad \mathcal{L}(\theta) = -\sum_{t=1}^{T} \log p_\theta(x_t \mid x_{<t}). \]

Here \(p_\theta(x_t \mid x_{<t})\) is a softmax over the vocabulary computed from the transformer's output at position \(t-1\), and the loss is averaged over tokens in a minibatch. Nothing in the loss is clinical: mortality is learned because death tokens follow certain patterns, length of stay because interval tokens precede discharge tokens in certain patterns.

The architecture is a decoder-only transformer based on Karpathy's nanoGPT, sized starting from GPT-2 and adjusted heuristically, with learned position embeddings and a context window of 2,048 tokens; the paper's embedding visualizations use 768 dimensions, and training took about 36 hours on 8 GPUs. Long records exceed the window, so the six static tokens are kept in the first positions. (The 2025 reimplementation, described below, reports a full configuration: 6 layers, 12 heads, about 45M parameters.)

Likelihood and cross-entropy. For a training set of timelines \(\mathcal{D}\), ETHOS minimizes the average negative log-likelihood per token,

\[ \mathcal{L}(\theta) = -\frac{1}{\sum_{x \in \mathcal{D}} T_x} \sum_{x \in \mathcal{D}} \sum_{t=1}^{T_x} \log p_\theta(x_t \mid x_{<t}), \qquad p_\theta(x_t \mid x_{<t}) = \operatorname{softmax}(W z_{t-1})_{x_t}, \]

where \(z_{t-1} \in \mathbb{R}^d\) is the transformer's output at position \(t-1\) and \(W \in \mathbb{R}^{|\mathcal{V}| \times d}\) the output projection (tied to the input embedding in nanoGPT). In expectation this is the cross-entropy \(H(p_{\text{data}}, p_\theta) = H(p_{\text{data}}) + \mathrm{KL}(p_{\text{data}} \,\|\, p_\theta)\), so minimizing it drives every conditional toward the empirical conditional frequencies, including those created by care policy and documentation habits. A uniform model over \(V\) tokens pays \(\ln V\) nats per token, about 8.4 for \(V = 4{,}500\); \(\exp(\mathcal{L})\) is the perplexity.

Causal attention. The decoder enforces \(p_\theta(x_t \mid x_{<t})\) by masking attention scores so that position \(i\) attends only to \(j \le i\); each layer costs \(O(C^2 d)\) for attention and \(O(C d^2)\) for the feed-forward block at context \(C\).

Model size. A pre-norm layer of width \(d\) with a \(4d\) feed-forward block has about \(12 d^2\) parameters (attention \(4d^2\), feed-forward \(8d^2\)). With \(N_L\) layers, tied embeddings, vocabulary \(V\) and learned positions for context \(C\):

\[ N \approx 12 N_L d^2 + V d + C d. \]

For the configuration reported by the 2025 reimplementation (\(N_L = 6\), \(d = 768\), \(C = 2{,}048\), \(V \approx 4{,}500\)) this gives \(42.5 + 3.5 + 1.6 \approx 47.6\)M, consistent with the reported "about 45M" given the approximate vocabulary.

Compute and data. Training costs about \(6ND\) FLOPs. That run used batch 32 and about 100K steps of 2,048-token windows, so \(D \approx 6.6 \times 10^9\) processed tokens, roughly 18 passes over its 361M-token corpus, and \(6ND \approx 1.8 \times 10^{18}\) FLOPs. Scaling fits on MIMIC-IV timelines built with the ETHOS pipeline find the loss-optimal model size growing as about \(C^{0.58}\) in compute and gains flattening beyond roughly 28M parameters, which the authors hypothesize reflects limited data (Zhang et al. 2025). At this data scale, more patients help more than more parameters.

A decoder-only transformer with learned positions and an output layer tied to the input embedding (as in nanoGPT), trained with shifted cross-entropy. The script counts parameters for the configuration reported by the 2025 reimplementation (6 layers, 12 heads, width 768, context 2,048, vocabulary taken as 4,500), fits a toy repeating sequence to confirm that the shift and mask are wired correctly, and checks causality by changing only the last input token.

import torch, torch.nn as nn, torch.nn.functional as F

class TinyGPT(nn.Module):
    """Decoder-only transformer, ids [B, T] -> logits [B, T, V]; learned positions; tied output."""
    def __init__(self, vocab, d=256, layers=6, heads=8, ctx=2048, dropout=0.1):
        super().__init__()
        self.tok, self.pos, self.ctx = nn.Embedding(vocab, d), nn.Embedding(ctx, d), ctx
        block = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=dropout,
                                           batch_first=True, norm_first=True)
        self.blocks = nn.TransformerEncoder(block, layers, enable_nested_tensor=False)
        self.norm = nn.LayerNorm(d)
        self.head = nn.Linear(d, vocab, bias=False)
        self.head.weight = self.tok.weight                      # weight tying, as in nanoGPT
        nn.init.normal_(self.tok.weight, std=0.02); nn.init.normal_(self.pos.weight, std=0.02)
    def forward(self, ids):
        T = ids.shape[1]
        mask = nn.Transformer.generate_square_subsequent_mask(T, device=ids.device)
        h = self.tok(ids) + self.pos(torch.arange(T, device=ids.device))
        return self.head(self.norm(self.blocks(h, mask=mask, is_causal=True)))

def nll(model, batch):
    """batch [B, T+1]: mean over tokens of -log p(x_t | x_<t) (shifted cross-entropy)."""
    return F.cross_entropy(model(batch[:, :-1]).flatten(0, 1), batch[:, 1:].flatten())

torch.manual_seed(0)
big = TinyGPT(4500, d=768, layers=6, heads=12, ctx=2048)
print("6 layers, 12 heads, d=768, V=4500: %.1fM parameters" % (sum(p.numel() for p in big.parameters()) / 1e6))
V, T = 8, 32
data = torch.tensor([1, 2, 3, 4] * 9)[: T + 1].repeat(64, 1)
m = TinyGPT(V, d=32, layers=2, heads=4, ctx=T, dropout=0.0)
opt = torch.optim.AdamW(m.parameters(), lr=3e-3, weight_decay=0.01)
with torch.no_grad(): l0 = nll(m, data).item()
for _ in range(150):
    loss = nll(m, data); opt.zero_grad(); loss.backward(); opt.step()
print("loss %.3f -> %.4f nats (ln V = %.3f)" % (l0, loss.item(), torch.log(torch.tensor(8.)).item()))
a = data[:1, :T].clone(); b = a.clone(); b[0, -1] = 7
m.eval()
with torch.no_grad():
    print("earlier logits unchanged:", torch.allclose(m(a)[0, :-1], m(b)[0, :-1], atol=1e-5))

Output:

6 layers, 12 heads, d=768, V=4500: 47.6M parameters
loss 2.148 -> 0.0088 nats (ln V = 2.079)
earlier logits unchanged: True

The count is close to the reported 45M; the difference comes from the assumed vocabulary, biases and normalization parameters. The toy loss starts near \(\ln 8\), as a freshly initialized model should, and falls toward zero on a deterministic sequence. A missing or inverted causal mask fails the last check immediately; on real data the symptom is a validation loss far below what the data's entropy allows.

Training cost is modest. ETHOS trained in about 36 hours on 8 GPUs; its 2025 reimplementation used about 100K steps on 8 A100s. Compared with inference over a hospital's daily census, training is a small, periodic cost. The engineering effort goes into data hygiene and evaluation rather than into the training loop.

Patient boundaries. Concatenating all timelines into one stream and cutting fixed windows wastes no compute but creates windows that span two patients, teaching the model a transition from one patient's discharge to the next patient's demographics. Zhang et al. changed this step of the ETHOS pipeline so that each patient's timeline is segmented independently (Zhang et al. 2025). Padding short patients to 2,048 tokens wastes compute; the efficient alternative packs several patients per window with an attention mask that blocks attention across boundaries and resets positions.

Memorization. Eighteen passes over the same patients, a model in the tens of millions of parameters and a corpus of a few hundred million tokens is a regime where memorization is plausible. It matters twice: overfitting degrades held-out discrimination, and a generator that memorizes can reproduce real timelines when it is used for synthetic data, as in federated timeline synthesis (Renc et al. 2025). ETHOS-ARES used dropout 0.3. Practical controls are early stopping on validation loss from held-out patients, comparing a model half the size, and testing generated timelines for near-copies of training records.

Selection and reproducibility. Checkpoints are selected on validation loss or validation tasks, never on test AUROC. A training run is reproducible only with its data snapshot, tokenizer version, seed and code commit recorded together.

Context length. A 2,048-token window with static tokens pinned at the front is a design compromise: long-stay ICU patients exceed it within days, and their earliest history leaves the context. Longer contexts cost quadratically in attention, and every token an event's encoding spends is history the window cannot hold, so context length and vocabulary design are set together.

Zero-Shot Inference by Simulation

To predict an outcome, ETHOS feeds a patient's timeline up to the prediction time as the prompt, samples a continuation token by token until a stopping condition, repeats this many times, and reports the fraction of continuations in which the outcome occurred. No labels, task heads or fine-tuning are involved; each task is defined by its prompt cut point, its stopping rule and the outcome tokens it counts.

Train, simulate and estimate: the three stages of zero-shot prediction with a generative event model. 1 · TRAIN 2 · SIMULATE 3 · ESTIMATE Tokenized PHTs training patients next-token loss over every token Decoder-only transformer p(next token | history) fit This patient's history prompt, cut at time t at inference K sampled futures discharge death ×K p̂ = M / K M futures with the outcome LOS: sum of interval tokens ± standard error count
Fig. The train → simulate → estimate pipeline. Training uses only the next-token loss. At inference the patient's history is the prompt; the model samples \(K\) continuations until a stop token (here discharge or death) or a time budget, and the estimate is a count. ETHOS used \(K=20\); its 2025 successor uses \(K=100\).

The paper defines each task by its rollout rule:

  • Inpatient and ICU mortality: start at admission, generate until a discharge or death token, repeat 20 times; the probability is the number of death-terminated runs divided by 20.
  • 30-day readmission: start at discharge, generate until an admission or death token, or until the summed interval tokens exceed 30 days; repeat 20 times.
  • ICU length of stay: sum the interval tokens generated before the discharge token (runs ending in death are excluded).
  • SOFA at ICU admission: read the model's probabilities over the ten SOFA decile tokens and take the expected value using the mean score per decile.
  • DRG: read the probabilities over the 772 DRG tokens at discharge directly; no sampling is needed.

The last two show that when the answer is the very next token, the softmax already is the predictive distribution; sampling is needed only when the outcome depends on a sequence of future tokens. The paper reports about 15 seconds per 1,000 generated tokens on one A100.

The Monte Carlo estimator. Let \(Y_k = g(\tilde{x}^{(k)}) \in \{0,1\}\) indicate whether the \(k\)-th sampled future contains the outcome before the stop condition. If the futures are drawn independently from the model, the \(Y_k\) are i.i.d. Bernoulli with mean \(p_\theta = \Pr_\theta[g(\tilde{x}) = 1 \mid h_t]\), so

\[ \hat{p} = \frac{1}{K}\sum_{k=1}^{K} Y_k = \frac{M}{K}, \qquad \mathbb{E}[\hat{p}] = p_\theta, \qquad \operatorname{SE}(\hat{p}) = \sqrt{\frac{p_\theta(1 - p_\theta)}{K}} \approx \sqrt{\frac{\hat{p}(1 - \hat{p})}{K}}. \]

Here \(M\) is the number of futures with the outcome and \(K\) the number sampled. The estimator is unbiased for the model's probability \(p_\theta\), not for the true clinical probability \(p\); the gap between \(p_\theta\) and \(p\) is a modeling error that more samples cannot fix. With \(K = 20\), \(\hat{p}\) can only take the values \(0, 0.05, \dots, 1\), and the standard error at \(p_\theta = 0.5\) is about 0.11; with \(K = 100\) it is 0.05.

Monte Carlo estimate of an outcome probability as the number of sampled timelines grows.
Fig. How a Monte Carlo risk estimate converges. Two independent runs of running estimates \(\hat{p}_K = M_K/K\) for an outcome whose model probability is \(p_\theta = 0.30\); the shaded band is \(p_\theta \pm 1.96\,\sqrt{p_\theta(1-p_\theta)/K}\). Vertical markers show \(K\) values used in practice: 20 (ETHOS), about 64 (where CoMET reported gains mostly plateauing) and 100 (ETHOS-ARES). Illustrative: simulated Bernoulli draws computed in the page with a fixed seed.

Tasks as stopped processes. Given a prompt \(h\) cut at time \(t_0\), a rollout samples \(\tilde{x}_1, \tilde{x}_2, \dots\) from \(p_\theta(\cdot \mid h, \tilde{x}_{<j})\) until the stopping time \(\sigma = \min\{j : \tilde{x}_j \in \mathcal{S} \text{ or } \sum_{i \le j} \Delta(\tilde{x}_i) > H\}\), where \(\mathcal{S}\) is the set of stop tokens, \(\Delta(v)\) the duration of an interval token and \(H\) a horizon (30 days for readmission, none for in-hospital mortality). The ETHOS tasks are functionals of the stopped path: an indicator \(g = \mathbf{1}[\tilde{x}_\sigma = \texttt{DEATH}]\) for mortality, and \(g = \sum_{j < \sigma} \Delta(\tilde{x}_j)\) for ICU length of stay, conditioned on \(\tilde{x}_\sigma = \texttt{DISCHARGE}\).

One-step readouts. When the answer is the next token, no sampling is needed. For SOFA at ICU admission, with \(\pi_j = p_\theta(Q_j \mid h)\) over the ten decile tokens and \(m_j\) the mean training score in decile \(j\), the prediction is \(\sum_j \pi_j m_j / \sum_j \pi_j\); for DRG it is \(\arg\max_v p_\theta(v \mid h)\) over the 772 DRG tokens.

The Monte Carlo estimator. With \(Y_k = g(\tilde{x}^{(k)}) \in \{0,1\}\) for \(K\) independent futures, \(\hat{p} = M/K\) is unbiased for \(p_\theta\) with \(\operatorname{SE} = \sqrt{p_\theta(1-p_\theta)/K}\). Its mean squared error as an estimate of the true probability \(p\) is

\[ \mathbb{E}\big[(\hat{p} - p)^2\big] = (p_\theta - p)^2 + \frac{p_\theta(1 - p_\theta)}{K}, \]

a bias that sampling cannot reduce plus a variance that it can. A worst-case standard error \(\varepsilon\) needs \(K \ge 0.25/\varepsilon^2\): 100 futures for 0.05, 625 for 0.02. For a per-patient interval the Wilson interval stays inside \([0,1]\) when \(M = 0\) or \(M = K\):

\[ \frac{\hat{p} + \frac{z^2}{2K} \pm z\sqrt{\frac{\hat{p}(1-\hat{p})}{K} + \frac{z^2}{4K^2}}}{1 + \frac{z^2}{K}}, \qquad z = 1.96. \]

Rare outcomes. The relative error is \(\operatorname{SE}/p = \sqrt{(1-p)/(pK)}\); at \(p = 0.01\) and \(K = 100\) it is near 100%, and \(\hat{p} = 0\) with probability \(0.99^{100} \approx 0.37\). The CoMET authors note that zero-shot generation does relatively poorly on low-prevalence incident disease (Waxler et al. 2025). Remedies are adaptive \(K\), one-step readouts when the outcome is one token away, and importance sampling from a proposal \(q\) with weights \(p_\theta/q\). A lower-variance score accumulates the per-step outcome probability along each path, \(\sum_{j \le \sigma} p_\theta(\tilde{x}_j \in \mathcal{O} \mid \tilde{x}_{<j})\), a form of Rao–Blackwellization that ETHOS did not use; with \(K = 20\) every raw score is a multiple of 0.05, so low-risk patients tie.

Censoring and sampling temperature. Futures that hit the token or context budget before \(\sigma\) are right-censored; dropping them biases \(\hat{p}\) toward outcomes that arrive quickly, so the incomplete fraction belongs in the report. The estimator is unbiased for \(p_\theta\) only at temperature 1 without truncation. Top-\(p\) sampling, used by ETHOS-ARES, removes the low-probability tail at every step and tends to understate rare outcomes, so its frequencies are scores to be recalibrated rather than probabilities.

Cost. A query costs \(K \cdot \mathbb{E}[\sigma]\) generated tokens; at the reported 15 seconds per 1,000 tokens on one A100, twenty futures of 300 tokens each take about 90 seconds unbatched.

The sampler runs \(K\) futures of one prompt in parallel, stops each at a stop token or a time horizon (summing the durations of generated interval tokens), counts outcome tokens and reports the fraction of futures that never stopped. It is tested against a stand-in model with a known next-token law in which death before discharge has probability \(0.02/0.20 = 0.10\). The Wilson interval gives per-patient uncertainty.

import math, torch, torch.nn.functional as F

@torch.no_grad()
def rollout_risk(model, prompt, K, stop_ids, outcome_ids, gap_minutes,
                 horizon_min=None, max_new=2000, temperature=1.0):
    """Sample K futures in parallel; return (p_hat, se, incomplete_fraction).
    gap_minutes[v] is the duration a token stands for (0 for non-interval tokens)."""
    ids = prompt.unsqueeze(0).repeat(K, 1)
    done = torch.zeros(K, dtype=torch.bool); hit = torch.zeros(K, dtype=torch.bool)
    elapsed = torch.zeros(K)
    for _ in range(max_new):
        logits = model(ids[:, -model.ctx:])[:, -1] / temperature
        nxt = torch.multinomial(F.softmax(logits, -1), 1).squeeze(1)
        nxt = torch.where(done, torch.zeros_like(nxt), nxt)        # finished rows emit PAD (id 0)
        ids = torch.cat([ids, nxt[:, None]], 1)
        elapsed += torch.where(done, 0.0, gap_minutes[nxt])
        over = elapsed > horizon_min if horizon_min is not None else torch.zeros_like(done)
        hit |= ~done & ~over & torch.isin(nxt, outcome_ids)
        done |= torch.isin(nxt, stop_ids) | over
        if done.all(): break
    p = hit.float().mean().item()
    return p, math.sqrt(p * (1 - p) / K), (~done).float().mean().item()

def wilson(M, K, z=1.96):
    """Wilson score interval for M outcomes in K futures."""
    p = M / K; den = 1 + z * z / K; c = (p + z * z / (2 * K)) / den
    h = z * math.sqrt(p * (1 - p) / K + z * z / (4 * K * K)) / den
    return max(0.0, c - h), min(1.0, c + h)

class FixedChain(torch.nn.Module):
    """Known next-token law. Tokens: 0 PAD, 1 OBS, 2 DISCHARGE, 3 DEATH, 4 GAP_1D."""
    ctx = 64
    def __init__(self, probs): super().__init__(); self.logp = torch.log(torch.tensor(probs))
    def forward(self, ids): return self.logp.expand(ids.shape[0], ids.shape[1], -1)

torch.manual_seed(0)
m = FixedChain([1e-9, 0.50, 0.18, 0.02, 0.30])
gap, stop, out = torch.tensor([0., 0., 0., 0., 1440.]), torch.tensor([2, 3]), torch.tensor([3])
p, se, inc = rollout_risk(m, torch.tensor([1]), 4000, stop, out, gap)
print("p_hat %.4f (p_theta 0.1000)  SE %.4f  incomplete %.3f" % (p, se, inc))
p2, _, _ = rollout_risk(m, torch.tensor([1]), 4000, stop, out, gap, horizon_min=2 * 1440)
print("within a 2-day horizon: p_hat %.4f" % p2)
_, _, inc3 = rollout_risk(m, torch.tensor([1]), 2000, stop, out, gap, max_new=3)
print("token budget 3: incomplete %.3f (theory 0.8^3 = 0.512)" % inc3)
print("K=20, M=3: p_hat 0.15, SE %.3f, Wilson (%.3f, %.3f)" % (math.sqrt(.15 * .85 / 20), *wilson(3, 20)))
print("K=20, M=0: Wilson (%.3f, %.3f)" % wilson(0, 20))

Output:

p_hat 0.0978 (p_theta 0.1000)  SE 0.0047  incomplete 0.000
within a 2-day horizon: p_hat 0.0815
token budget 3: incomplete 0.524 (theory 0.8^3 = 0.512)
K=20, M=3: p_hat 0.15, SE 0.080, Wilson (0.052, 0.360)
K=20, M=0: Wilson (0.000, 0.161)

The estimate lands within one standard error of the known 0.10. A horizon lowers the risk because deaths after day 2 no longer count, which is how a 30-day readmission window works. A tight token budget leaves half the futures unfinished; counting them as negatives would bias the estimate downward, so the incomplete fraction is returned rather than hidden. With \(K = 20\), three deaths give a Wald interval that crosses zero (\(0.15 \pm 0.156\)) while the Wilson interval stays inside \([0,1]\), and zero deaths still leave an upper bound of 0.16.

Two implementation details matter at scale: the padding id must not be a stop or outcome token, and recomputing the full prompt at every step costs \(O(T^2)\) per token, which a key-value cache removes. Fixing the random seed per patient during evaluation keeps model comparisons from being dominated by sampling noise.

Serving zero-shot risk by simulation is an inference-cost problem with a statistics problem inside it. The figure shows the serving path and the metric each stage should export.

Serving path for zero-shot risk by simulation, with the monitor attached to each stage.Prompt buildercut, tokenizeBatched samplerK rows, KV cacheStop / budgetstop tokens, horizonCounterM/K, Wilson CICalibratorscore to riskPSI, unknown codestokens/s, p95 latencyincomplete rateSE, ties at zeroECE by monthdashed boxes: per-stage metrics exported to monitoring
Fig. Production serving path for simulation-based risk. Each stage exports the metric that diagnoses its typical failure: shifted or unseen tokens at the prompt builder, throughput at the sampler, censored futures at the stop rule, Monte Carlo error at the counter and calibration drift after the calibrator.

Cost. ETHOS reported about 15 seconds per 1,000 generated tokens on one A100, an unoptimized baseline. The remedies, roughly in order of payoff: batch the \(K\) futures of many patients together with a key-value cache so that each step costs one token per row; compute the prompt's cache once and share it across the \(K\) rows; drop finished rows from the batch; answer one-step questions (SOFA, DRG) from the softmax without sampling; and use adaptive \(K\), starting small and adding futures only for patients whose interval straddles a decision threshold. Adaptive \(K\) makes per-patient precision depend on the threshold, which has to be documented. Re-scoring after every new event, as in the risk trajectories of ETHOS-ARES (Renc et al. 2025), multiplies the cost by the number of events per stay.

How many futures. ETHOS used 20 futures; ETHOS-ARES 100; CoMET reported gains mostly plateauing around 64 (Waxler et al. 2025). The right \(K\) depends on prevalence: for common outcomes 20 is adequate for ranking, while for outcomes at a few percent most patients score exactly zero at \(K = 20\).

Censoring. Futures that exhaust the token budget before a stop token are not negatives. Long post-discharge windows (30-day readmission) are where budgets run out, and a latency optimization that shortens the budget can silently lower predicted readmission risk. The incomplete rate per task should be reported and alerted on; Bedi, Fries and Shah list timeline completion among the checks a simulation-based prediction should pass (Stanford HAI 2026).

Calibration. Raw frequencies inherit model error, and top-\(p\) sampling sharpens them. A monotone recalibration (isotonic, or logistic on \(\operatorname{logit}\hat{p}\)) fitted on a recent held-out period, with expected calibration error tracked monthly, turns scores into risks.

An alternative to sampling. EveryQuery conditions a model on a query prompt and estimates the outcome directly; on MIMIC-IV it reports a 14.3% mean AUROC improvement over an autoregressive baseline with about 580 times less inference compute, with the largest advantage on rare outcomes (Chandak et al. 2026). It gives up the sampled trajectories, which are what make simulation inspectable.

Results

On the MIMIC-IV test set, a single ETHOS model, never trained on any label, matched or beat published task-specific models on most tasks it was tested on, with the clear exceptions of 30-day hospital readmission and readmission after intracerebral hemorrhage. The numbers below are from the arXiv version of the paper; comparators are results reported in other papers, often on differently curated cohorts, so the comparisons are indicative rather than head-to-head.

Task (test set)ETHOSComparator reported in the paper
Inpatient mortality (43,309 admissions, 2.0% positive)AUROC 0.921—
ICU mortality (7,483 ICU stays, 7.0% positive)AUROC 0.927XGBoost 0.918
ICU mortality in sepsis (3,324 patients)AUROC 0.8890.762
ICU readmissionAUROC 0.8070.82; LSTM 0.791
30-day hospital readmissionAUROC 0.7490.791
ICU length of stayMAE 2.26 days2.42 days
SOFA score on first ICU dayMAE 1.50none reported
DRG class (771 classes, 28,932 stays)Top-1 accuracy 84.8%DRG-LLaMA 52%

Table. Selected ETHOS results (Renc et al. 2024, arXiv v1). The paper gives 95% confidence intervals for each; for example, inpatient mortality 0.908–0.931. Comparators come from separate studies with their own cohorts and features.

  • Results are strongest where the stopping rule is short (in-hospital and ICU death, DRG at discharge).
  • Readmission is harder: the model must generate a plausible post-discharge month, and MIMIC-IV cannot see readmissions to other hospitals.
  • ETHOS was evaluated on the full test population while comparators used curated subsets, which cuts both ways.

One label-free simulator gave competitive discrimination across inpatient tasks. It did not establish calibration, subgroup performance or transfer to another hospital (see Evaluating Health World Models).

AUROC as a rank statistic. For scores \(s\) on \(n_1\) positive and \(n_0\) negative cases, the area under the ROC curve is the Mann–Whitney probability that a random positive outranks a random negative, with ties counting one half:

\[ \mathrm{AUROC} = \frac{1}{n_1 n_0} \sum_{i:\,y_i=1} \sum_{j:\,y_j=0} \Big( \mathbf{1}[s_i > s_j] + \tfrac{1}{2}\mathbf{1}[s_i = s_j] \Big). \]

It depends only on the ordering of scores, so it is blind to calibration: multiplying every risk by two leaves it unchanged. Scores that are multiples of \(1/K\) create ties, which pull AUROC toward 0.5 for patients that cannot be separated.

Where the interval width comes from. The Hanley–McNeil approximation gives

\[ \operatorname{SE}(A) = \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}, \quad Q_2 = \frac{2A^2}{1+A}. \]

For inpatient mortality, \(A = 0.921\) on 43,309 admissions with 2.0% positive (about 866 deaths) gives \(\operatorname{SE} \approx 0.0064\) and a 95% interval of about \((0.909, 0.933)\), close to the reported 0.908–0.931. The width is set by the number of positives, not the number of admissions; for a 7.0% outcome on 7,483 ICU stays (about 524 deaths) the interval is wider despite the higher prevalence.

Regression and classification metrics. ICU length of stay is scored by mean absolute error, \(\frac{1}{n}\sum_i |\hat{y}_i - y_i|\), which for a simulated estimate inherits the bin width of the interval tokens; DRG by top-1 accuracy over 771 classes.

What a comparison needs. A difference between two models on the same patients is tested with a paired method such as DeLong's test, which accounts for the correlation between the two AUROCs. Comparisons with numbers from other papers, on different cohorts and inclusion criteria, have no common sample and support no significance statement; the table's comparisons are therefore indicative.

What is missing. Calibration, measured for example by the Brier score \(\frac{1}{n}\sum_i (\hat{p}_i - y_i)^2\) or expected calibration error \(\sum_b \frac{n_b}{n}\,|\bar{p}_b - \bar{y}_b|\) over risk bins \(b\), is what a risk shown to a clinician requires and was not established in the results reported.

The script computes AUROC with tied scores (average ranks), measures how the number of sampled futures \(K\) changes AUROC and calibration for a rare outcome, and estimates the confidence-interval width for a cohort the size of the ETHOS inpatient-mortality test set, both by bootstrap and by the Hanley–McNeil formula. Risks and scores are synthetic.

import numpy as np

def auroc(score, y):
    """Mann-Whitney AUROC; ties get average ranks (count one half)."""
    _, inv, cnt = np.unique(score, return_inverse=True, return_counts=True)
    ranks = (np.cumsum(cnt) - (cnt - 1) / 2)[inv]
    n1 = y.sum(); n0 = len(y) - n1
    return (ranks[y].sum() - n1 * (n1 + 1) / 2) / (n1 * n0)

def ece(p, y, bins=10):
    b = np.minimum((p * bins).astype(int), bins - 1)
    return sum(abs(p[b == k].mean() - y[b == k].mean()) * (b == k).mean() for k in range(bins) if (b == k).any())

rng = np.random.default_rng(1)
p_theta = rng.beta(0.4, 8.0, 40_000); y = rng.random(40_000) < p_theta    # model risks, mean ~0.05
print("exact p_theta: AUROC %.3f" % auroc(p_theta, y))
for K in (20, 100, 1000):
    p_hat = rng.binomial(K, p_theta) / K                                     # M/K from K futures
    print("K=%4d: AUROC %.3f  ECE %.3f  share scoring 0: %.2f" % (K, auroc(p_hat, y), ece(p_hat, y), (p_hat == 0).mean()))
n, prev = 43_309, 0.02
yy = rng.random(n) < prev
s = rng.normal(0, 1, n) + 1.987 * yy                                         # binormal, AUROC ~0.92
boot = [auroc(s[i], yy[i]) for i in (rng.integers(0, n, n) for _ in range(300))]
print("positives %d, AUROC %.3f, bootstrap 95%% CI (%.3f, %.3f)" % (yy.sum(), auroc(s, yy), *np.percentile(boot, [2.5, 97.5])))
A, n1 = 0.921, round(0.02 * 43_309); n0 = 43_309 - n1
Q1, Q2 = A / (2 - A), 2 * A * A / (1 + A)
se = np.sqrt((A * (1 - A) + (n1 - 1) * (Q1 - A * A) + (n0 - 1) * (Q2 - A * A)) / (n1 * n0))
print("Hanley-McNeil: n1=%d, SE %.4f, 95%% CI (%.3f, %.3f)" % (n1, se, A - 1.96 * se, A + 1.96 * se))

Output:

exact p_theta: AUROC 0.854
K=  20: AUROC 0.778  ECE 0.016  share scoring 0: 0.60
K= 100: AUROC 0.841  ECE 0.002  share scoring 0: 0.35
K=1000: AUROC 0.852  ECE 0.001  share scoring 0: 0.14
positives 879, AUROC 0.931, bootstrap 95% CI (0.923, 0.938)
Hanley-McNeil: n1=866, SE 0.0064, 95% CI (0.909, 0.933)

For an outcome near 5% prevalence, twenty futures leave 60% of patients tied at zero and cost about 0.08 AUROC relative to the model's exact probabilities; a hundred futures recover most of it. The analytic interval for the reported 0.921 reproduces the published 0.908–0.931 closely, and the bootstrap on an idealized binormal cohort of the same size gives a similar width, confirming that roughly 870 deaths fix the precision at about \(\pm 0.01\).

What the results license. A single label-free model with competitive AUROC across inpatient tasks on one hospital's held-out patients is evidence that the representation and the simulator work. It is not evidence that the risks are calibrated, that performance holds in subgroups, at another hospital or in later years, or that showing the risk changes care. Each of those is a separate study in a deployment.

Validation before use. The usual sequence is a retrospective evaluation on the local site's recent data with the frozen tokenizer and model; a silent (shadow) deployment in which scores are logged but not shown, compared with outcomes as they arrive; and only then a display to clinicians, with calibration and subgroup reports refreshed on a schedule. Labels arrive late: in-hospital mortality is known at discharge, 30-day readmission only a month after it, so monitoring dashboards lag by the outcome horizon.

Where it is weak. Readmission was the clear gap (AUROC 0.749 against a reported 0.791), and MIMIC-IV cannot see readmissions to other hospitals, so the label itself is incomplete. A system that serves readmission risk inherits this blind spot at any single-center site; claims or health-information-exchange data are needed to close it.

Later evidence. The 2025 reimplementation reported higher AUROC than a MEDS-Tab XGBoost baseline on hospital mortality (0.940 against 0.887), ICU admission and prolonged stay, and on emergency-department tasks, with its authors noting that clinical usability had not been formally tested (Renc et al. 2025). Bedi, Fries and Shah propose five checks before such results are trusted: performance on rare versus common events, calibration, timeline completion, audits for shortcuts through administrative codes, and validation on different populations without retraining (Stanford HAI 2026).

Reporting. A production report for each task gives AUROC with an interval, calibration (ECE or a reliability curve), performance by sex, age band and race, the number of positives, the number of futures \(K\), the sampling settings and the incomplete-rollout rate, so that a later change in any of them can be traced.

Code Walkthrough: A Toy ETHOS

The whole method fits in about a hundred lines: a tokenizer that turns events into codes, decile tokens and time-gap tokens; a causal transformer trained with cross-entropy; and a rollout that samples \(K\) futures in parallel and counts outcome tokens. The code below is a teaching sketch written for this book, not the ETHOS implementation (which is open source as ethos-ares); bin edges and token names are illustrative.

1. Tokenizer. Codes are split hierarchically, numbers become deciles fitted on training data only, and gaps become interval tokens.

import numpy as np

# Time-gap bins in minutes (illustrative; ETHOS v1 used 13 interval tokens, ETHOS-ARES 19)
GAP_EDGES  = [5, 15, 60, 120, 360, 720, 1440, 4320, 10080, 43200, 129600]
GAP_TOKENS = ["5m-15m", "15m-1h", "1h-2h", "2h-6h", "6h-12h", "12h-1d",
              "1d-3d", "3d-1w", "1w-1mt", "1mt-3mt", "3mt-6mt"]
SIX_MONTHS = 259200  # minutes

def gap_tokens(minutes):
    """No token under 5 min; repeated 6-month tokens for very long gaps."""
    out = []
    while minutes >= SIX_MONTHS:
        out.append("=6mt"); minutes -= SIX_MONTHS
    if minutes >= 5:
        i = np.searchsorted(GAP_EDGES, minutes, side="right") - 1
        out.append(GAP_TOKENS[i])
    return out

def icd10_tokens(code):                       # "N17.9" -> ["ICD//N17", "ICD//9"]
    c = code.replace(".", "")
    parts = [c[:3], c[3:5], c[5:]]
    return ["ICD//" + p for p in parts if p]

class Deciles:
    """Fit per-test decile edges on TRAINING data only, then map values to Q1..Q10."""
    def fit(self, values_by_test):
        self.edges = {t: np.quantile(v, np.linspace(0.1, 0.9, 9))
                      for t, v in values_by_test.items()}
        return self
    def token(self, test, value):
        return f"Q{int(np.searchsorted(self.edges[test], value, side='right')) + 1}"

def tokenize_timeline(static, events, deciles):
    """static: list of tokens; events: time-sorted dicts with 'minute', 'kind', ..."""
    toks, last = list(static), None
    for e in events:
        if last is not None:
            toks += gap_tokens(e["minute"] - last)
        if e["kind"] == "dx":
            toks += icd10_tokens(e["code"])
        elif e["kind"] == "lab":
            toks += ["LAB//" + e["test"], deciles.token(e["test"], e["value"])]
        else:                                 # admission, discharge, death, drug ...
            toks.append(e["kind"].upper() if "code" not in e else e["code"])
        last = e["minute"]
    return toks

2. Next-token training. Timelines are concatenated, cut into windows of the context length, and trained with the standard shifted cross-entropy. In ETHOS the six static tokens sit at the start of every window; here that is handled by prepending them when windows are cut.

import torch, torch.nn as nn, torch.nn.functional as F

class TinyGPT(nn.Module):
    def __init__(self, vocab, d=256, layers=6, heads=8, ctx=2048):
        super().__init__()
        self.tok = nn.Embedding(vocab, d)
        self.pos = nn.Embedding(ctx, d)                # learned positions, as in ETHOS
        block = nn.TransformerEncoderLayer(d, heads, 4 * d, dropout=0.1,
                                           batch_first=True, norm_first=True)
        self.blocks = nn.TransformerEncoder(block, layers)
        self.head = nn.Linear(d, vocab, bias=False)
        self.ctx = ctx
    def forward(self, ids):                            # ids: [B, T]
        T = ids.shape[1]
        mask = nn.Transformer.generate_square_subsequent_mask(T, device=ids.device)
        h = self.tok(ids) + self.pos(torch.arange(T, device=ids.device))
        return self.head(self.blocks(h, mask=mask, is_causal=True))   # [B, T, V]

def train(model, windows, steps=100_000, lr=4e-4):     # windows: LongTensor [N, ctx+1]
    opt = torch.optim.AdamW(model.parameters(), lr=lr, weight_decay=0.01)
    for step in range(steps):
        batch = windows[torch.randint(len(windows), (32,))]
        x, y = batch[:, :-1], batch[:, 1:]             # predict token t from tokens < t
        loss = F.cross_entropy(model(x).flatten(0, 1), y.flatten())
        opt.zero_grad(); loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()

3. Rollout and counting. Sample \(K\) futures in one batch, stop each when it emits a stop token or exceeds the time horizon, and count futures that contain the outcome. The time budget uses the minutes implied by each generated interval token.

@torch.no_grad()
def rollout_risk(model, prompt, K, stop_ids, outcome_ids, gap_minutes,
                 horizon_min=None, max_new=2000, temperature=1.0):
    """prompt: LongTensor [T]; gap_minutes: FloatTensor [V], minutes per token (0 if not a gap)."""
    ids = prompt.unsqueeze(0).repeat(K, 1)             # K copies of the history
    done = torch.zeros(K, dtype=torch.bool)
    hit = torch.zeros(K, dtype=torch.bool)
    elapsed = torch.zeros(K)
    for _ in range(max_new):
        logits = model(ids[:, -model.ctx:])[:, -1] / temperature
        nxt = torch.multinomial(F.softmax(logits, -1), 1).squeeze(1)
        nxt = torch.where(done, torch.zeros_like(nxt), nxt)   # pad finished rows
        ids = torch.cat([ids, nxt[:, None]], 1)
        hit |= ~done & torch.isin(nxt, outcome_ids)
        elapsed += torch.where(done, 0.0, gap_minutes[nxt])
        done |= torch.isin(nxt, stop_ids)
        if horizon_min is not None:
            done |= elapsed > horizon_min
        if done.all():
            break
    p = hit.float().mean().item()
    se = (p * (1 - p) / K) ** 0.5
    return p, se, (~done).float().mean().item()        # also report incomplete rollouts

# 30-day readmission from a discharge point:
# p, se, incomplete = rollout_risk(model, prompt, K=100,
#     stop_ids=ids_of(["INPATIENT_ADMISSION", "DEATH"]),
#     outcome_ids=ids_of(["INPATIENT_ADMISSION"]), gap_minutes=gap_table,
#     horizon_min=30 * 24 * 60)

Three details carry over to real systems: fit the tokenizer on training patients only, or decile edges leak test information; production samplers drop finished sequences and use a key-value cache instead of padding; and monitor the fraction of incomplete rollouts alongside the risk itself.

The tokenizer as a map. A record is a time-ordered list of events \(e_i = (t_i, c_i, v_i)\): a time, a code and an optional numeric value. The tokenizer \(\tau\) maps the static facts \(s\) and the events to one token sequence \(x_{1:n} = \tau(s, e_{1:m})\). Three quantizers define it.

  • Values. For test \(a\), the edges \(q_{a,j} = \hat F_a^{-1}(j/10)\), \(j = 1, \dots, 9\), are empirical quantiles of training values, and a value maps to \(Q(v) = 1 + \#\{j : q_{a,j} \le v\}\). Each decile holds about 10% of training values, so the ten tokens are equally frequent and carry at most \(\log_2 10 \approx 3.3\) bits per measurement. Fitting the edges on all patients makes the evaluation tokens exactly uniform by construction: a small but real use of test data.
  • Gaps. Interval bins \([b_i, b_{i+1})\) have roughly geometric edges from 5 minutes to 6 months, so relative time resolution is roughly constant. A gap \(\Delta \ge S\) (six months) emits \(\lfloor \Delta / S \rfloor\) long-gap tokens followed by the bin of \(\Delta \bmod S\); gaps under 5 minutes emit nothing, so near-simultaneous events share a time.
  • Codes. An ICD-10 code with \(k\) pieces costs \(k\) tokens and is scored as \(p(\text{code} \mid h) = \prod_{i=1}^{k} p(\text{piece}_i \mid \text{piece}_{<i}, h)\). Rare full codes share statistical strength through their common category.

Objective. Over windows \(w\) of length \(C + 1\) whose first positions hold the static tokens, training minimizes the shifted cross-entropy

\[ \mathcal{L}(\theta) = -\frac{1}{|W|\,C} \sum_{w \in W} \sum_{t=1}^{C} \log p_\theta\big(x^{w}_{t+1} \mid x^{w}_{\le t}\big). \]

Its expectation per token is \(H(P) + \mathrm{KL}(P \,\|\, p_\theta)\): the entropy of the care process plus the model's excess. The loss floor is therefore the irreducible unpredictability of timelines, not zero, and \(e^{\mathcal{L}}\) reads as the effective number of equally likely next tokens.

The rollout estimator. For the \(k\)-th sampled continuation \(\tilde{x}^{(k)}\), let \(E_j = \sum_{i \le j} m(\tilde{x}_i)\) be the minutes assigned to interval tokens so far and define the stopping index

\[ \tau_k = \min\{\, j : \tilde{x}_j \in \mathcal{S} \ \text{or}\ E_j > H \ \text{or}\ j = L_{\max} \,\}, \qquad Y_k = \mathbb{1}\big[\exists\, j \le \tau_k : \tilde{x}_j \in \mathcal{O}\big], \]

with stop set \(\mathcal{S}\), outcome set \(\mathcal{O}\), horizon \(H\) and token budget \(L_{\max}\). Then \(\hat{p} = \frac{1}{K}\sum_k Y_k\) is unbiased for the model's probability (at temperature 1, without truncation) with standard error \(\sqrt{\hat{p}(1 - \hat{p})/K}\). If a fraction \(c\) of rows reach \(L_{\max}\) without stopping, the model's probability lies between \(\hat{p}\) and \(\hat{p} + c\) up to sampling error, because an unfinished row can still turn positive. That interval is why the incomplete fraction is returned with the estimate.

Time-budget bias. If \(m(\cdot)\) assigns each interval token the lower edge of its bin, \(E_j\) never exceeds the true elapsed time and horizon stopping fires late: a 30-day query can count events from beyond day 30, by up to one bin width per generated gap. Assigning each bin its mean gap in training data removes most of this bias.

Cost. Without a cache, each new token re-encodes the window: per layer a step costs \(O(K(T^2 d + T d^2))\) for context length \(T\) and width \(d\). With a key-value cache a step costs \(O(K(T d + d^2))\) per layer, and each row stores \(2 \cdot n_{\text{layers}} \cdot T \cdot d\) cached numbers. Padding finished rows keeps all \(K\) rows alive until the longest finishes, so the work scales with \(K \max_k \tau_k\) rather than \(\sum_k \tau_k\).

The script below runs the whole method end to end on a synthetic cohort whose true risks are known. It imports the four pieces of the walkthrough code, saved together as toy_ethos.py: Deciles fits decile edges on training values, tokenize_timeline turns events into tokens, TinyGPT is the causal transformer, and rollout_risk samples \(K\) futures and returns the outcome fraction, its standard error and the fraction of unfinished futures. Each synthetic patient has an admission lactate; above 2.83 mmol/L (the 90th percentile of the generating distribution) the daily death probability is 0.12, otherwise 0.02, and the daily discharge probability is 0.25. The exact probability of death before discharge is therefore \(d/(d + 0.25)\).

import numpy as np, torch
import warnings; warnings.filterwarnings("ignore")
from toy_ethos import Deciles, tokenize_timeline, TinyGPT, rollout_risk
import torch.nn.functional as F

rng = np.random.default_rng(0); torch.manual_seed(0)

# --- synthetic cohort: death hazard per day depends on the admission lactate ---
def patient(rng):
    lact = rng.lognormal(0.4, 0.5)                       # mmol/L
    d = 0.12 if lact > 2.83 else 0.02                    # 2.83 = 90th percentile: Q10 is high-risk
    ev, day = [dict(minute=0, kind="admission"),
               dict(minute=30, kind="lab", test="LACT", value=lact)], 0
    while True:
        day += 1; u = rng.random(); m = 30 + day * 1440
        if u < d:            ev.append(dict(minute=m, kind="death")); break
        if u < d + 0.25:     ev.append(dict(minute=m, kind="discharge")); break
        ev.append(dict(minute=m, kind="obs"))
    return ["SEX_F" if rng.random() < .5 else "SEX_M"], ev, lact

train_pts = [patient(rng) for _ in range(4000)]
dec = Deciles().fit({"LACT": np.array([l for _, _, l in train_pts])})   # training data only
seqs = [tokenize_timeline(s, e, dec) for s, e, _ in train_pts]
vocab = ["PAD"] + sorted({t for s in seqs for t in s}); ix = {t: i for i, t in enumerate(vocab)}
ctx = 24
data = torch.full((len(seqs), ctx + 1), 0)
for i, s in enumerate(seqs):
    s = [ix[t] for t in s][:ctx + 1]; data[i, :len(s)] = torch.tensor(s)

model = TinyGPT(len(vocab), d=48, layers=2, heads=4, ctx=ctx)
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
for step in range(3000):
    b = data[torch.randint(len(data), (32,))]
    logits = model(b[:, :-1])
    loss = F.cross_entropy(logits.flatten(0, 1), b[:, 1:].flatten(), ignore_index=0)
    opt.zero_grad(); loss.backward(); opt.step()
print(f"vocab {len(vocab)}, final train loss {loss.item():.3f}")

model.eval()
gap = torch.tensor([1440.0 if t == "1d-3d" else 0.0 for t in vocab])
stop = torch.tensor([ix["DEATH"], ix["DISCHARGE"]]); death = torch.tensor([ix["DEATH"]])
q_hi = dec.token("LACT", 5.0); q_lo = dec.token("LACT", 1.0)
for q, d in ((q_hi, 0.12), (q_lo, 0.02)):
    prompt = torch.tensor([ix[t] for t in ["SEX_F", "ADMISSION", "15m-1h", "LAB//LACT", q]])
    p, se, inc = rollout_risk(model, prompt, 1000, stop, death, gap, max_new=20)
    p3, _, _ = rollout_risk(model, prompt, 1000, stop, death, gap, horizon_min=3 * 1440, max_new=20)
    true = d / (d + 0.25); true3 = true * (1 - (1 - d - 0.25) ** 3)
    print(f"{q:>3}: p_hat {p:.3f} (true {true:.3f}, SE {se:.3f}, incomplete {inc:.3f}); "
          f"3-day {p3:.3f} (true {true3:.3f})")

It prints the vocabulary size and final loss, then one line per lactate decile. Real output (3,000 steps on two CPU cores, about six minutes):

vocab 20, final train loss 0.440
Q10: p_hat 0.248 (true 0.324, SE 0.014, incomplete 0.001); 3-day 0.186 (true 0.243)
 Q3: p_hat 0.079 (true 0.074, SE 0.009, incomplete 0.028); 3-day 0.052 (true 0.045)

Reading the output. The third-decile query matches the true risk within sampling error. The top-decile query is low by about 0.08 while its standard error is 0.014: the Monte Carlo error measures how well \(K\) futures estimate the model's probability, not how well the model matches the patient. Only about 400 training patients fall in the top decile, and a small, briefly trained model shrinks their risk toward the cohort rate. The 3-day horizon sums 1,440 minutes per 1d-3d token, which is exact here because every gap in the data is one day. The incomplete fraction (0.028 for the long-stay, low-risk group with a 20-token budget) is the share of futures that reached the budget before discharge or death; those futures are bounded, not negative.

The toy has the same three stages as a production system, and each stage changes when real records and latency targets arrive. The open-source ETHOS-ARES code (ethos-ares) is the closest public reference.

The tokenizer is a versioned artifact. Vocabulary, decile edges, interval bins and code-splitting rules are part of the model: weights trained with one set of edges are meaningless with another. Production pipelines store these artifacts with the weights, fit them on training patients only, and split data by patient rather than by admission so that a person's later stays cannot inform predictions about earlier ones. Codes unseen in training map to an unknown token or to their parent category. Two cheap drift monitors follow: the daily unknown-token rate, and the share of each lab's values falling in each decile, which is 10% per decile on training data by construction; an assay or unit change at the laboratory shows up there before it shows up in AUROC. ETHOS-ARES moved extraction to the MEDS format through the MEDS-DEV pipeline, so the tokenizer reads a standard event table instead of hand-written MIMIC-IV queries.

Training is small-scale language modelling. ETHOS-ARES used a GPT-2-style model of about 45M parameters with a 2,048-token context, trained for about 100K steps on 8 A100s. The consequential choices are the context length (how much history a prompt can carry), keeping the static tokens at the start of every window, and regularization (dropout 0.3 in ETHOS-ARES), since a few hundred thousand patients is a small corpus for a transformer.

Inference needs a real sampler. The teaching sampler re-encodes the full window at each step and pads finished rows. A serving system computes the prompt's key-value cache once, shares it across the \(K\) rows, extends each row by one token per step and removes rows as they stop. Paged key-value memory, as in vLLM (Kwon et al. 2023), lets many patients' rollouts share one GPU without reserving memory for the longest possible future. ETHOS-ARES sampled with top-\(p\) 0.9; truncated sampling sharpens the distribution and tends to understate rare outcomes, so its frequencies are scores to calibrate rather than probabilities.

Failure modes, each with a test.

  • Tokenizer leakage. Decile edges or vocabularies fit on all patients. Refit on the training split and confirm that evaluation metrics do not move.
  • Padding collisions. If the padding id is also a stop or outcome token, finished rows keep scoring. Assert the three id sets are disjoint.
  • Context overflow. The sampler keeps the last \(C\) tokens, so once a rollout outgrows the context the static tokens leave the window, unlike training, where they always sit at the start. Pin the static prefix and slide only the event part.
  • Time-budget bias. Converting interval tokens to minutes with lower bin edges lets horizon queries run long. Use the training mean gap per bin and test on a timeline with known gaps.
  • Censoring. Futures that hit the token budget are not negatives. Report the incomplete fraction per task (the "timeline completion" criterion of Bedi, Fries & Shah 2026) and raise the budget when it exceeds a few percent.
  • Irreproducible scores. Fix a seed per patient and query, so that reruns and model comparisons differ for model reasons, not sampling noise.

ETHOS After 2024

The ETHOS team followed up in 2025 with a MEDS-based reimplementation and risk-estimation system, and a federated variant; I found no later ETHOS paper as of November 2026. Both keep the core recipe and change the engineering around it.

What the follow-ups hold fixed. ETHOS has four parts: a tokenizer \(\tau\) from an event table to tokens; a next-token model \(p_\theta(x_{t+1} \mid x_{\le t})\) fit by maximum likelihood; a query \(q = (\mathcal{S}, \mathcal{O}, H)\) of stop tokens, outcome tokens and horizon; and the Monte Carlo estimator \(\hat{p} = M/N\) over \(N\) sampled futures. Each 2025 follow-up changes exactly one part.

  • The MEDS reimplementation changes the input to \(\tau\). Events become rows \((s, t, c, v)\) of subject, time, code and optional value, and \(\tau\) is a deterministic function of one subject's rows sorted by time. Two groups that share \(\tau\) and the data produce identical token streams, which makes their results comparable.
  • ARES changes where the estimator is evaluated. Instead of one prompt cut \(t\), it computes \(\hat{p}(t_j)\) at a sequence of cuts \(t_1 < t_2 < \dots\), a sampled path of the model's risk \(r_\theta(t) = \Pr_\theta[\text{outcome} \mid h_t]\).
  • Federated synthesis changes the training distribution. \(\theta\) is fit to samples from site generators \(q_s\) rather than to records, so the global model targets the mixture \(\sum_s w_s q_s\).

In every case the squared error of a reported probability still splits as \((p_\theta - p)^2 + p_\theta(1 - p_\theta)/N\). The follow-ups either move the bias term (new data pipeline, new training distribution) or pay the variance term many times over (one estimate per cut).

The MEDS format stores each event as one row of subject, time, code and optional numeric value; static facts are rows without a time. The converter below sorts a subject's rows, emits interval tokens between distinct times with gap_tokens (no token under five minutes, repeated six-month tokens for long gaps, imported from toy_ethos.py), splits ICD-10 codes into category and subcode pieces, appends a decile token to numeric values using edges fitted on training subjects only, and maps anything outside a frozen vocabulary to UNK.

import numpy as np
from datetime import datetime as dt
from toy_ethos import gap_tokens

# MEDS-style rows: (subject_id, time, code, numeric_value); static rows have time None
rows = [(7, None, "GENDER//F", None),
        (7, dt(2019, 3, 1, 8, 0), "HOSPITAL_ADMISSION", None),
        (7, dt(2019, 3, 1, 9, 30), "LAB//LACTATE", 4.1),
        (7, dt(2019, 3, 1, 9, 30), "LAB//CREATININE", 0.9),
        (7, dt(2019, 3, 1, 14, 0), "DIAGNOSIS//ICD//10//A41.9", None),
        (7, dt(2019, 3, 4, 10, 0), "HOSPITAL_DISCHARGE", None),
        (7, dt(2019, 11, 2, 7, 0), "HOSPITAL_ADMISSION", None)]

def fit_quantiles(train_rows, q=10):
    """Per-code decile edges from TRAINING subjects only."""
    vals = {}
    for _, _, code, v in train_rows:
        if v is not None: vals.setdefault(code, []).append(v)
    return {c: np.quantile(v, np.linspace(0, 1, q + 1)[1:-1]) for c, v in vals.items()}

def meds_to_tokens(rows, edges, vocab=None):
    rows = sorted(rows, key=lambda r: (r[0], r[1] is not None, r[1] or dt.min))
    toks, last = [], None
    for _, t, code, v in rows:
        if t is not None and last is not None:
            toks += gap_tokens((t - last).total_seconds() / 60)   # nothing within 5 minutes
        if code.startswith("DIAGNOSIS//ICD//10//"):
            c = code.split("//")[-1].replace(".", "")
            new = ["ICD//" + p for p in (c[:3], c[3:5], c[5:]) if p]
        else:
            new = [code]
        if v is not None:
            new.append(f"Q{int(np.searchsorted(edges[code], v, side='right')) + 1}")
        toks += [x if vocab is None or x in vocab else "UNK" for x in new]
        last = t if t is not None else last
    return toks

rng = np.random.default_rng(0)
train = [(s, dt(2018, 1, 1), "LAB//LACTATE", x) for s, x in enumerate(rng.lognormal(0.4, 0.5, 5000))]
train += [(s, dt(2018, 1, 1), "LAB//CREATININE", x) for s, x in enumerate(rng.lognormal(0.0, 0.4, 5000))]
edges = fit_quantiles(train)
print(meds_to_tokens(rows, edges))
print(meds_to_tokens(rows, edges, vocab={"GENDER//F", "HOSPITAL_ADMISSION", "HOSPITAL_DISCHARGE",
                                          "LAB//LACTATE", "LAB//CREATININE", "ICD//A41", "Q10", "Q5"})[-6:])

It prints the full token stream, then the last six tokens under a deliberately small vocabulary. Real output:

['GENDER//F', 'HOSPITAL_ADMISSION', '1h-2h', 'LAB//LACTATE', 'Q10', 'LAB//CREATININE', 'Q4', '2h-6h', 'ICD//A41', 'ICD//9', '1d-3d', 'HOSPITAL_DISCHARGE', '=6mt', '1mt-3mt', 'HOSPITAL_ADMISSION']
['UNK', '1d-3d', 'HOSPITAL_DISCHARGE', '=6mt', '1mt-3mt', 'HOSPITAL_ADMISSION']

The lactate of 4.1 mmol/L lands in the top decile and the creatinine of 0.9 mg/dL in the fourth. The 2 days 20 hours between diagnosis and discharge become 1d-3d, and the 242 days before readmission become one six-month token plus 1mt-3mt. Under the small vocabulary the subcode ICD//9 becomes UNK, which is the behaviour a deployed tokenizer needs for codes it never saw in training.

The 2025 work is mostly engineering, and the engineering is what an adopting hospital inherits. Moving to MEDS means the same extraction, tokenizer and training code run on any data set converted to that format, and it lets baselines such as MEDS-Tab XGBoost run on identical cohorts and labels. The ETHOS-ARES comparisons are therefore like-for-like, unlike the 2024 paper's comparisons with separate studies that used their own cohorts and features. Public code (ethos-ares) makes the configuration inspectable: vocabulary, interval bins, model size and sampling settings.

Three practical points follow for a team considering the recipe. First, both follow-ups were evaluated only on MIMIC-IV, from a single academic medical center; transfer to another site's coding and documentation practices is untested and is the first thing to measure on local data. Second, an open reimplementation still needs pinning: record the code commit, the MEDS schema version and the tokenizer artifacts with every trained model, because a change to any of them changes the token stream. Third, as of November 2026 no later ETHOS paper had appeared, so developments elsewhere in the field, such as much larger multi-system models (Waxler et al. 2025) and the evaluation criteria proposed by Bedi, Fries & Shah (2026), have not been folded back into ETHOS itself.

ETHOS-ARES: Adaptive Risk Estimation

Renc et al. (2025) introduced ARES, the Adaptive Risk Estimation System, on top of a reimplemented ETHOS; the code's README lists the peer-reviewed version in GigaScience (2025, giaf107) (ethos-ares). The setup, from the August 2025 arXiv version (v4):

  • Data and tokens: MIMIC-IV v2.2 plus the ED extension, extracted with the MEDS-DEV pipeline into the MEDS format: about 300K patients and 361M tokens. The vocabulary grows to about 4,500 tokens, with 19 interval tokens, HCPCS codes, vitals and ED events.
  • Model: GPT-2-style, 6 layers, 12 heads, 768 dimensions, 2,048-token context, dropout 0.3, about 45M parameters; AdamW at \(4\times10^{-4}\), batch 32, about 100K steps on 8 A100s.
  • Inference: top-\(p\) 0.9 sampling of \(N = 100\) futures, probability \(M/N\) with binomial intervals, reported as five ordinal risk levels.
  • Results (AUROC vs. the MEDS-Tab XGBoost baseline): hospital mortality 0.940 vs. 0.887, ICU admission 0.932 vs. 0.918, prolonged stay 0.853 vs. 0.815; on ED tasks, hospitalization at triage 0.946 (best baseline 0.863), critical outcome within 12 hours 0.945 (0.892), 72-hour re-presentation 0.745 (0.714).

The "adaptive" part is that simulation can start from any earlier token, which turns one patient's record into a risk trajectory: re-run the rollouts after each new event and watch the estimate move. The authors add an explanation module that attributes jumps to specific tokens, and they caution that rises right after invasive procedures (an intubation code, for example) are better read as retrospective markers of severity than as actionable alerts. Clinical usability had not been formally tested.

An ARES-style risk trajectory: estimated risk re-computed after each new event.
Fig. The idea behind ARES: re-run \(N = 100\) rollouts after each new token and plot the estimated risk with its binomial 95% interval. A high lactate raises the estimate; an intubation code raises it further, but as ETHOS-ARES notes, a jump right after a procedure mostly reflects severity already known to the team. Illustrative: the event times and risk values are invented, and the band is computed from the binomial formula.

A risk trajectory. For prompt cuts \(t_1 < t_2 < \dots\), one after each new event, ARES computes \(\hat{p}_j = M_j / N\) from \(N\) futures sampled from \(p_\theta(\cdot \mid h_{t_j})\). The sequence \(j \mapsto \hat{p}_j\) is a series of Monte Carlo estimates of the model's risk path \(r_j = \Pr_\theta[\text{outcome} \mid h_{t_j}]\). A displayed change \(\hat{p}_j - \hat{p}_{j-1}\) has two sources, a change in \(r\) and sampling noise. With independent samples at the two cuts its standard error is

\[ \operatorname{SE}(\hat{p}_j - \hat{p}_{j-1}) \approx \sqrt{\frac{r_j(1 - r_j) + r_{j-1}(1 - r_{j-1})}{N}}. \]

A jump from 0.10 to 0.30 is about 3.7 standard errors at \(N = 100\) and about 1.6 at \(N = 20\). Common random numbers (the same seed at both cuts) make the two estimates positively correlated, which subtracts \(2\operatorname{Cov}(\hat{p}_j, \hat{p}_{j-1})\) from the variance of the difference and makes small changes interpretable.

Intervals and levels. ARES reports a binomial interval with each estimate; the Wilson form

\[ \frac{\hat{p} + \frac{z^2}{2N} \pm z\sqrt{\frac{\hat{p}(1-\hat{p})}{N} + \frac{z^2}{4N^2}}}{1 + \frac{z^2}{N}}, \qquad z = 1.96, \]

stays inside \([0, 1]\) when \(M = 0\) or \(M = N\). Five ordinal risk levels are a step function \(\ell(\hat{p}) = 1 + \#\{m : c_m \le \hat{p}\}\) for cuts \(c_1 < \dots < c_4\). When the model risk \(r\) sits near a cut \(c\), sampling noise alone moves the level with probability about \(\Phi(-|c - r| / \operatorname{SE})\), where \(\Phi\) is the standard normal distribution function. At \(r = 0.14\), \(c = 0.15\) and \(N = 100\) this is about 0.39. A hysteresis rule keeps the displayed level \(\ell^\ast\) while the interval \([\text{lo}, \text{hi}]\) still satisfies \(\ell(\text{lo}) \le \ell^\ast \le \ell(\text{hi})\), trading flicker for a delay in showing real changes.

Attribution. A generic way to attribute a jump to token \(v\) is the counterfactual difference \(\hat{p}(h_t) - \hat{p}(h_t \setminus v)\), simulating with and without the token. Like any prompt edit, it is a statement about the model, not about the patient's biology; the ETHOS-ARES explanation module attributes jumps to tokens, and this formula illustrates the idea rather than reproducing the authors' method.

Sampling rule. ETHOS-ARES sampled with top-\(p\) 0.9: at each step only the smallest set of tokens with cumulative probability at least 0.9 is kept and renormalized. The estimator then targets the probability under the truncated sampler, not \(r_\theta\); outcome tokens that rarely make the nucleus are under-generated, so rare-outcome risks tend to be understated.

The code builds a risk trajectory by re-running one zero-shot query with the prompt cut after each event, attaching a Wilson interval and one of five ordinal levels to each estimate. It imports rollout_risk from toy_ethos.py: given a model, a prompt, \(K\), stop tokens, outcome tokens and a minutes-per-token table, it samples \(K\) futures in one batch and returns the outcome fraction, its standard error and the unfinished fraction. A stand-in model whose next-token probabilities depend only on the last token makes the right answer computable: after an ordinary observation the model risk of death before discharge is \(0.05/0.30 \approx 0.17\); right after a top-decile lactate it is \(0.30 + 0.60 \times 0.17 = 0.40\).

import math, numpy as np, torch, warnings; warnings.filterwarnings("ignore")
from toy_ethos import rollout_risk

def wilson(M, K, z=1.96):
    p = M / K; den = 1 + z * z / K
    c = (p + z * z / (2 * K)) / den
    h = z * math.sqrt(p * (1 - p) / K + z * z / (4 * K * K)) / den
    return max(0.0, c - h), min(1.0, c + h)

EDGES = (0.05, 0.15, 0.30, 0.50)                       # illustrative cuts for five levels
def level(p):
    return 1 + int(np.searchsorted(EDGES, p, side="right"))

def risk_trajectory(model, timeline, cuts, K, seed=0, **task):
    rows = []
    for c in cuts:
        torch.manual_seed(seed)                         # common random numbers across cuts
        p, _, inc = rollout_risk(model, timeline[:c], K, **task)
        rows.append((c, p, *wilson(round(p * K), K), level(p), inc))
    return rows

class LastTokenChain(torch.nn.Module):                  # next-token probs depend on last token
    ctx = 64
    def __init__(self, table):
        super().__init__(); self.logp = torch.log(torch.tensor(table))
    def forward(self, ids):
        return self.logp[ids]

#        PAD   OBS  DISCH DEATH LACT_Q10
base = [1e-9, .70, .25, .05, 1e-9]                      # risk 0.05/0.30 = 0.167
lact = [1e-9, .60, .10, .30, 1e-9]                      # right after LACT_Q10: 0.30 + 0.60*0.167 = 0.40
m = LastTokenChain([base, base, base, base, lact])
task = dict(stop_ids=torch.tensor([2, 3]), outcome_ids=torch.tensor([3]), gap_minutes=torch.zeros(5))
for r in risk_trajectory(m, torch.tensor([1, 1, 4, 1]), cuts=[2, 3, 4], K=100, **task):
    print("cut %d: p=%.2f  95%% CI (%.2f, %.2f)  level %d" % r[:5])

# Level flipping for a patient whose model risk stays at 0.14 (cut at 0.15)
rng = np.random.default_rng(0)
def flips(K, n=5000, hysteresis=False, p=0.14):
    shown, changes = level(p), 0
    for _ in range(n):
        M = rng.binomial(K, p); new = level(M / K)
        if hysteresis and new != shown:
            lo, hi = wilson(M, K)
            new = shown if level(lo) <= shown <= level(hi) else new
        changes += new != shown; shown = new
    return changes / n
for K in (20, 100):
    print(f"K={K}: level changes per re-score {flips(K):.2f}, with Wilson hysteresis {flips(K, hysteresis=True):.3f}")

It prints three trajectory rows, then the rate of level changes per re-score for a patient whose model risk stays at 0.14. Real output:

cut 2: p=0.15  95% CI (0.09, 0.23)  level 3
cut 3: p=0.36  95% CI (0.27, 0.46)  level 4
cut 4: p=0.15  95% CI (0.09, 0.23)  level 3
K=20: level changes per re-score 0.60, with Wilson hysteresis 0.004
K=100: level changes per re-score 0.50, with Wilson hysteresis 0.027

The lactate cut raises the estimate from 0.15 to 0.36 against a model risk of 0.40. Cuts 2 and 4 end in the same state and use the same seed, so they return identical futures: with common random numbers, any difference between two cuts comes from the prompt. The second part shows the cost of ordinal levels. With a model risk of 0.14 just under the 0.15 cut, the displayed level changes on half or more of all re-scores even though nothing about the patient changed. The hysteresis rule cuts this to a few percent; at \(K = 20\) its intervals are so wide that the level almost never moves, which would also hide a real change.

Turning a one-off zero-shot estimate into a continuously updated display adds four production problems to those of the sampler.

Cost multiplies with events. Re-scoring after every token multiplies simulation load by the number of events per stay, and each re-score costs \(N\) futures times their mean length in generated tokens; an intensive-care patient accrues many event tokens per day. Practical systems re-score on clinically relevant token classes (labs outside the middle deciles, vital signs, transfers, new diagnoses) and otherwise at a fixed interval, and they reuse the previous cut's key-value cache, because each new prompt extends the old one. Event filtering can miss slow deterioration spread across many unremarkable tokens; a minimum re-score frequency bounds that risk.

Retrospective jumps. As the ETHOS-ARES authors caution, rises right after invasive procedures mostly record severity the team already knew. A monitoring log should store, for every level change, the token class with the largest attributed contribution, and report the share of changes led by procedure or treatment-decision tokens. Such changes can be suppressed or shown as already explained, provided the lead time of alerts before escalation does not shorten.

Level flicker. Patients whose risk sits near a level boundary change level from sampling noise alone. The remedies are common random numbers across re-scores, a hysteresis rule that waits for the binomial interval to clear the boundary, and enough futures per cut (ETHOS-ARES used 100). Two numbers to track are level changes per patient-day and the share of changes reversed at the next re-score.

Unvalidated use. The authors state that clinical usability had not been formally tested, and the model was evaluated retrospectively on MIMIC-IV only. Before any bedside use, a silent (shadow-mode) deployment that logs trajectories without showing them, followed by calibration checks per level on local outcomes and an assessment of alert burden with clinicians, is the minimum. The explanation module needs its own check: attributions that point at tokens clinicians recognize as consequences rather than causes are a sign the display is describing care, not predicting deterioration.

Federated Timeline Synthesis

Renc et al. (2025b) trained local ETHOS-style generators at each site, shared only weights, and trained a global generator on synthetic timelines sampled from them. On five MIMIC-IV tasks, adding large synthetic sets to a small real set approached training on all the real data, while synthetic data alone fell short; the authors list one dataset, few tasks and no fairness analysis as limitations. A generative event model doubles as a synthetic-data engine, which makes the privacy evaluation of generated timelines a first-class concern.

Synthesis as a mixture. Let site \(s\) hold records from distribution \(P_s\), with weight \(w_s\) equal to its share of patients. Each site fits a local generator \(q_s \approx P_s\) and only its weights leave the site. Sampling \(n_s \propto w_s\) synthetic timelines from each generator and fitting a global model by maximum likelihood targets

\[ q_{\text{global}} \approx \sum_s w_s\, q_s \approx \sum_s w_s P_s = P_{\text{pooled}}. \]

The global model's error is therefore the local generators' error plus the error of fitting a finite synthetic sample. Two consequences follow. Patterns a local generator under-produces are lost globally, and rare patterns are exactly what small sites contribute. And if sampling ignores \(w_s\) (for example, equal numbers per site), the global model targets \(\frac{1}{S}\sum_s q_s\), which over-represents small sites.

Federated timeline synthesis: local generators, synthetic timelines, one global generator.Site 1 recordsnever leave the siteLocal generator 1fit on site dataSynthetic setsampled from G1Site 2 recordsnever leave the siteLocal generator 2fit on site dataSynthetic setsampled from G2Site 3 recordsnever leave the siteLocal generator 3fit on site dataSynthetic setsampled from G3Global generatorfit on all syntheticonly weights cross the site boundary
Fig. Federated timeline synthesis as described by Renc et al. (2025b): each site fits a local ETHOS-style generator, only the generator's weights leave the site, synthetic timelines are sampled from every local generator, and a global generator is trained on the pooled synthetic data. Privacy then depends on how much each local generator memorizes.

Synthetic plus real. The reported result, that a small real set plus a large synthetic set approached training on all real data, has a simple reading: the synthetic set lowers variance by supplying many samples of \(\sum_s w_s q_s\), while the real set anchors the bias \(q_s - P_s\) that synthetic data alone cannot correct. With synthetic data alone, the global model inherits every local generator's bias and cannot do better than \(\sum_s w_s q_s\).

Memorization. Weights are not anonymous: if \(q_s\) assigns high probability to a specific training timeline \(x\), sampling reproduces it. One test compares, for each synthetic timeline, the distance to its nearest real training timeline with the same distance computed for real held-out timelines; synthetic timelines systematically closer to training data than held-out ones indicates copying. Memorization risk in healthcare foundation models has been studied directly (Tonekaboni et al. 2025).

The script runs a federated synthesis with three sites of 6,000, 3,000 and 1,000 patients and intensive-care mortality of about 0.2, 0.3 and 0.4. Each local generator is a count-based next-token model (the smallest stand-in for an ETHOS model) fit inside its site; only the fitted generator is used to sample synthetic timelines, and a global generator is fit on those. The small site also holds one patient with a rare, identifying path (ECMO, then transplant). The script compares two sampling plans: equal numbers of synthetic timelines per site, and numbers proportional to site size.

import numpy as np
from collections import defaultdict

class Bigram:
    """Count-based next-token generator: the smallest stand-in for a local ETHOS model."""
    def __init__(self, alpha=0.01): self.alpha, self.c = alpha, defaultdict(lambda: defaultdict(float))
    def fit(self, tls):
        self.vocab = sorted({t for tl in tls for t in tl})
        for tl in tls:
            for a, b in zip(tl[:-1], tl[1:]): self.c[a][b] += 1
        return self
    def probs(self, last):
        p = np.array([self.c[last][v] for v in self.vocab]) + self.alpha
        return p / p.sum()
    def sample(self, prefix, rng, max_new=12):
        out = list(prefix)
        while len(out) < len(prefix) + max_new and out[-1] not in ("DEATH", "DISCHARGE"):
            out.append(self.vocab[rng.choice(len(self.vocab), p=self.probs(out[-1]))])
        return out

rng = np.random.default_rng(0)
def site(n, icu_death):
    tls = []
    for _ in range(n):
        if rng.random() < 0.2:
            tls.append(["ADMIT", "ICU_ADMIT", "DEATH" if rng.random() < icu_death else "DISCHARGE"])
        else:
            tls.append(["ADMIT", "LAB_LACTATE", "DEATH" if rng.random() < 0.02 else "DISCHARGE"])
    return tls

sizes, deaths = [6000, 3000, 1000], [0.20, 0.30, 0.40]
sites = [site(n, d) for n, d in zip(sizes, deaths)]
# a rare, identifying pattern seen once at the small site
sites[2].append(["ADMIT", "ECMO", "TRANSPLANT", "ICU_ADMIT", "DISCHARGE"])

def p_icu_death(model): return model.probs("ICU_ADMIT")[model.vocab.index("DEATH")]
pooled = Bigram().fit([t for s in sites for t in s])
for name, n_per_site in (("equal", [4000] * 3), ("proportional", [8000 * n // sum(sizes) for n in sizes])):
    synth = []
    for corpus, n in zip(sites, n_per_site):
        local = Bigram().fit(corpus)                     # trained inside the site
        synth += [local.sample(["ADMIT"], rng) for _ in range(n)]
    glob = Bigram().fit(synth)
    rare = sum(t[:3] == ["ADMIT", "ECMO", "TRANSPLANT"] for t in synth)
    print(f"{name:>12}: P(death|ICU) global {p_icu_death(glob):.3f} vs pooled real {p_icu_death(pooled):.3f};"
          f" synthetic copies of the rare prefix: {rare}")

It prints, for each plan, the global generator's probability of death after ICU admission, the same quantity fit on the pooled real records, and the number of synthetic timelines that reproduce the rare path. Real output:

       equal: P(death|ICU) global 0.283 vs pooled real 0.224; synthetic copies of the rare prefix: 1
proportional: P(death|ICU) global 0.236 vs pooled real 0.224; synthetic copies of the rare prefix: 1

The realized site mortalities were 0.17, 0.27 and 0.46, so the pooled rate is 0.224. Proportional sampling recovers it within sampling error (0.236) without any record leaving a site. Equal sampling over-weights the small, high-mortality site and lands near the unweighted mean of the three sites. In both runs the path seen once at one site reappears in the synthetic data: a generator exports what it memorized, even though only weights were shared. A real pipeline would add a nearest-neighbour check on long token n-grams before any synthetic timeline leaves the site.

Federated synthesis replaces data sharing with model sharing, so the governance question moves from "may these records leave?" to "what can these weights reveal?".

Pipeline. Each site runs the same versioned tokenizer and training code on its own records, which requires agreeing on vocabulary, decile edges and interval bins before training; decile edges fitted per site would give the same token different meanings at different hospitals. A coordinator collects weights, samples synthetic timelines in proportion to each site's patient count, and trains the global generator. Site-level validation stays local: each site scores the global model on its own held-out patients and reports only metrics.

Privacy controls. Weight sharing alone is not a privacy guarantee. The controls, in rising order of cost to fidelity, are deduplication and early stopping of local generators; collapsing rare codes into parent categories; filtering synthetic timelines whose nearest real neighbour is closer than real held-out patients are to the training set; and differentially private training of local generators, which bounds what any single patient can change in the weights but degrades exactly the rare patterns small sites contribute. Memorization testing (Tonekaboni et al. 2025) belongs in the release checklist for every local generator.

Evaluation gaps. The authors list one dataset, few tasks and no fairness analysis as limitations, and with a single dataset the sites were necessarily simulated from MIMIC-IV rather than being separate hospitals with different coding habits. A production evaluation would measure, per site and per subgroup, the gap between models trained on real-plus-synthetic data and on local real data.

The Generative Event Model Family

ETHOS belongs to a family of generative event models that share its recipe (tokenize, train autoregressively, simulate) and differ in data, time representation and use. By idea, the family splits into models that generate the next concept or visit, models of lifetime disease histories, and models that test whether scale helps.

Every member of the family factorizes a tokenized record \(x_{1:n}\) autoregressively and is trained by next-token cross-entropy:

\[ p_\theta(x_{1:n}) = \prod_{t=1}^{n} p_\theta(x_t \mid x_{Members differ in three choices: the event alphabet \(\mathcal{V}\) (codes, concepts extracted from text, visits, diseases), the treatment of time (interval tokens generated like events, a continuous age input, or a predicted waiting time), and the unit of prediction (one token or a whole visit). Inference is shared. For an outcome set \(\mathcal{O}\) and \(K\) sampled futures \(\tilde x^{(k)} \sim p_\theta(\cdot \mid x_{1:n})\),

\[ \hat p = \frac{1}{K}\sum_{k=1}^{K} \mathbb{1}\big[\tilde x^{(k)} \in \mathcal{O}\big], \qquad \mathrm{SE}(\hat p) = \sqrt{p(1-p)/K}, \]

which is unbiased for the model's own risk \(p\) when sampling follows the trained distribution. The estimator is what lets one pretrained model answer many questions; its variance is what makes that expensive.

The shared inference loop is independent of the transformer: sample \(K\) futures once, then evaluate any number of outcome predicates on the same rollouts. Below, a stand-in sampler emits death with probability 0.02 and discharge with probability 0.10 per step, so the true in-hospital mortality is \(0.02/0.12 = 0.167\); a second predicate (more than ten events before the stay ends, true probability \(0.88^{10} = 0.279\)) is answered from the same samples.

import numpy as np

def toy_sampler(prompt, rng, d=0.02, h=0.10, max_steps=200):
    """Stand-in for a trained decoder: each step emits DEATH, DISCHARGE or a filler lab token."""
    out = list(prompt)
    for _ in range(max_steps):
        u = rng.random()
        if u < d:     return out + ["DEATH"]
        if u < d + h: return out + ["DISCHARGE"]
        out.append("LAB_Q5")
    return out + ["TRUNCATED"]

def simulate(sample, prompt, K, outcomes, rng):
    """Sample K futures once; answer every outcome predicate from the same rollouts."""
    futures = [sample(prompt, rng)[len(prompt):] for _ in range(K)]
    res = {}
    for name, pred in outcomes.items():
        hits = np.array([pred(f) for f in futures], float)
        p = hits.mean()
        res[name] = (p, np.sqrt(max(p * (1 - p), 1e-12) / K))
    return res

outcomes = {"death": lambda f: f[-1] == "DEATH",
            "long_stay": lambda f: len(f) > 10}          # more than 10 events before stopping
rng = np.random.default_rng(0)
for K in (20, 256):
    r = simulate(toy_sampler, ["ADMIT"], K, outcomes, rng)
    print(K, {k: (round(float(p), 3), round(float(se), 3)) for k, (p, se) in r.items()})
print("true death risk", round(0.02 / 0.12, 3), "true P(len>10)", round(0.88 ** 10, 3))

Output: with \(K = 20\) the mortality estimate is 0.25 (standard error 0.097) and the long-stay estimate 0.20; with \(K = 256\) they are 0.195 (0.025) and 0.258 (0.027), each within about one standard error of the truth. In a real model toy_sampler is a decoder sampling token ids with a key-value cache, and the predicates read death, discharge and accumulated interval tokens.

Deployed, a generative event model is a sampling service rather than a classifier. The cost of one answer is a prefill of the patient's history plus \(K\) times the rollout length in decode steps; a decoder with \(N\) parameters spends about \(2N\) floating-point operations per token, but decode is sequential and memory-bound, so latency follows rollout length rather than FLOPs. The main levers are to compute the shared prompt once and reuse it across rollouts (prefix caching), to batch rollouts of many patients into one decode batch, to stop each rollout at the horizon of the question, and to answer every outcome from the same rollouts. Most failures are not in the transformer: a tokenizer change that moves time bins, a missing stop token that produces endless rollouts, or a change in sampling settings that shifts counts. ETHOS-ARES sampled 100 rollouts with top-p 0.9 while CoMET sampled at temperature 1, so sampling settings are part of the model and must be versioned with the weights and the tokenizer.

Generating Concepts and Visits

The first generation predicted what comes next in a timeline of concepts or visits, judged mostly by next-event accuracy and synthetic-record realism.

  • Kraljevic et al. (2024) built Foresight (Lancet Digital Health; preprint 2022), a GPT-2-style model (16 layers, 512 dimensions) over SNOMED CT concepts extracted from free text with MedCAT, on 811,336 patients from King's College Hospital, South London and Maudsley, and MIMIC-III, in one-day buckets. Precision@10 for the next new disorder was 0.68–0.88 across sites, and clinicians judged the top forecast relevant in 33 of 34 synthetic cases; the authors note it reflects historical practice and was not validated for long simulations.
  • Pang et al. (2024) built CEHR-GPT on Columbia's OMOP data (about 2.3M training patients): a demographic prompt, visit-type tokens, and day-gap tokens up to 1,080 days plus a long-term token (full paper). About 98% of generated sequences converted back to OMOP, privacy attacks fell below the framework's low-risk threshold, and coarser time tokens visibly broke time-sensitive cohorts: a CEHR-BERT-style representation produced a 100% synthetic heart-failure readmission rate against about 25% in real data.
  • Yang et al. (2023) built TransformEHR, an encoder-decoder pretrained on 6.5M Veterans Health Administration patients to generate all ICD codes of the next visit. It beat BERT-style pretraining on AUPRC for pancreatic cancer onset (78.6 vs. 76.9) and self-harm among patients with PTSD (16.7 vs. 13.3), and pretraining improved AUROC by 2.3% on external MIMIC-IV data.

Two lessons recur: time representation is not a detail (blurred intervals put synthetic readmissions at the wrong times), and predicting the next visit as a set (TransformEHR, RAVEN below) avoids long rollouts for visit-level questions.

Token-level models. Foresight and CEHR-GPT apply the autoregressive factorization to a single sequence. In Foresight the tokens are SNOMED CT concepts, and events in the same one-day bucket have no meaningful order, so the likelihood implicitly averages over arbitrary within-day orderings. It is scored by ranking: the next-step distribution \(p_\theta(\cdot \mid x_{

Time tokens and windowed outcomes. CEHR-GPT maps a gap of \(\Delta\) days to a token \(b(\Delta)\) (day-level up to 1,080 days, then a long-term token). A sampler emits tokens, and an outcome such as "readmission within \(w\) days" is evaluated on a decoded value \(g(b(\Delta))\). The outcome survives tokenization exactly when

\[ \mathbb{1}\big[g(b(\Delta)) \le w\big] = \mathbb{1}\big[\Delta \le w\big] \quad \text{for all } \Delta, \]

which holds if and only if \(w\) is a bin edge. Otherwise every gap in the bin \([e_j, e_{j+1})\) that straddles \(w\) is assigned to one side, and the misclassified probability mass is \(P(e_j \le \Delta < e_{j+1})\) on the wrong side of \(w\). Errors compound when an outcome window spans several sampled gaps. This is the mechanism behind CEHR-GPT's observation that a coarse time representation produced a 100% synthetic heart-failure readmission rate.

Visit-set models. TransformEHR and RAVEN predict the next visit \(V_{j+1} \subseteq \mathcal{V}\) as a whole. With per-code probabilities \(\pi_c\) and the conditional-independence approximation

\[ p(V_{j+1} \mid V_{1:j}) \approx \prod_{c \in \mathcal{V}} \pi_c^{\,y_c} (1-\pi_c)^{1-y_c}, \qquad y_c = \mathbb{1}[c \in V_{j+1}], \]

the loss is a sum of binary cross-entropies, and a visit-level question needs one forward pass instead of a rollout. The approximation ignores co-occurrence within a visit (a diagnosis and its usual drug), which a sequential decoder over the visit's codes, as in TransformEHR's encoder-decoder, can recover.

Two pieces of the first generation are checked below. The first round-trips real gaps through a time tokenizer and back to a decoded midpoint, as a sampler would, and recomputes a 30-day readmission rate. The fine tokenizer has an edge at 30 days; the coarse one merges 7 to 90 days into one token. The second is the visit-set objective, one binary cross-entropy per code.

import numpy as np
rng = np.random.default_rng(0)
# Real gaps (days) from discharge to next admission: a mix of early returns and late ones.
gaps = np.concatenate([rng.uniform(1, 30, 2500), rng.uniform(30, 365, 7500)])
true_rate = (gaps <= 30).mean()

def roundtrip(gaps, edges):
    """Tokenize each gap into a bin, then decode it back as the bin midpoint (what a sampler emits)."""
    k = np.clip(np.searchsorted(edges, gaps, side="right") - 1, 0, len(edges) - 2)
    return (edges[k] + edges[k + 1]) / 2

fine   = np.array([0, 1, 3, 7, 14, 30, 90, 180, 365, 1080.])  # a boundary at 30 days
coarse = np.array([0, 7, 90, 365, 1080.])                   # 7-90 days merged into one token
for name, e in [("fine", fine), ("coarse", coarse)]:
    print(f"{name:6s} 30-day readmission after round-trip: {(roundtrip(gaps, e) <= 30).mean():.3f}")
print(f"real   30-day readmission:                    {true_rate:.3f}")

# Visit-set objective: one binary cross-entropy per code instead of a token rollout.
def visit_bce(logits, next_visit):            # logits (C,), next_visit: multi-hot (C,)
    p = 1 / (1 + np.exp(-logits))
    return -np.sum(next_visit * np.log(p) + (1 - next_visit) * np.log(1 - p))
logits = np.array([2.0, -1.0, -3.0, 0.5]); y = np.array([1, 0, 0, 1])
print("visit-set BCE:", round(float(visit_bce(logits, y)), 3))

Output: the fine tokenizer reproduces the real 30-day readmission rate exactly (0.250 against 0.250); the coarse one gives 0.054, because every return between day 7 and day 30 decodes to the midpoint 48.5 days. CEHR-GPT's failure went the other way (100% against about 25%); the sign depends on where the decoded value falls, the cause is the same. The visit-set loss for logits (2.0, −1.0, −3.0, 0.5) and visit (1, 0, 0, 1) is 0.963. A unit test that asserts every outcome window in use is a bin edge catches this class of error before training.

The first-generation models expose three production concerns. The extraction pipeline is part of the model. Foresight's tokens are concepts that MedCAT extracts from free text, so a change to the extractor, its vocabulary or the note templates changes the input distribution without any change to the transformer. The extractor version has to be pinned with the weights, and the concept frequency histogram monitored for shifts after upgrades. The authors' own caveat, that the model reflects historical practice and was not validated for long simulations, limits it to short-horizon forecasting and review support.

Synthetic data release needs gates. CEHR-GPT's evaluation is a template for releasing synthetic patients: the share of generated sequences that convert back to valid OMOP records (about 98%), with the invalid remainder inspected rather than silently dropped; fidelity on time-sensitive cohorts such as 30-day readmission, which catches tokenizer errors that aggregate statistics miss; and a battery of privacy attacks (membership and attribute inference) whose results must stay below a stated risk threshold before data leave the institution.

Transfer depends on coding. TransformEHR's 2.3% AUROC gain on external MIMIC-IV data required mapping between coding systems and sites. External validation is a deployment step, not a publication detail: code mappings, visit definitions and missing code families must be checked per site, and visit-set models must be re-evaluated when the definition of a visit changes, for example when telehealth encounters are added.

Delphi-2M: The Natural History of Disease

Shmatko et al. (2025) trained Delphi-2M, a modified GPT, on about 0.4M UK Biobank participants to model the rates of more than 1,000 diseases as a function of each person's past history, and validated it without changing parameters on about 1.9M people in Danish registries (Nature, September 2025). Where ETHOS simulates a hospital stay token by token, Delphi simulates a lifetime of diagnoses, and it can sample synthetic health trajectories up to 20 years ahead.

Technical details, as summarized in coverage of the paper (I could not open the full text, so treat these as secondary):

  • About 1,270 tokens: three-character ICD-10 codes for 1,256 diseases, death, sex, lifestyle levels (BMI, smoking, alcohol), and "no-event" tokens that fill long gaps.
  • GPT-2 with positions replaced by a continuous age encoding, an output for the time to the next event, and masking so simultaneous events do not inform each other; about 2.2M parameters.
  • Average AUC around 0.76 in UK Biobank, falling toward 0.70 at 10 years and lower in Danish data; training only on synthetic trajectories cost a few AUC points; explainability exposed biases from the training data.

Predicting the waiting time directly, rather than discretizing time into tokens, makes Delphi a neural version of the multi-state models from the lineage. A May 2026 study, DT-Transformer (Zhu et al. 2026), trained a Delphi-style model on 1.7M patients at Mass General Brigham and reported stronger near-term discrimination (median age- and sex-stratified AUC 0.871 across 896 diseases) but faster decay at long horizons, with a median AUC of 0.713 in a prospective 2024 evaluation. The authors caution that UK Biobank is a highly selected population and that cross-population comparisons are loose.

Competing exponentials. A model that outputs a rate per disease and a time to the next event can be read as a competing-risks process. Given history \(h\), disease \(c\) has intensity \(\lambda_c(h)\) per year and the total is \(\Lambda(h) = \sum_c \lambda_c(h)\). The waiting time is \(T \sim \mathrm{Exp}(\Lambda)\), the next event is \(c\) with probability \(\lambda_c/\Lambda\), and

\[ P(T \le t) = 1 - e^{-\Lambda t}, \qquad P(\text{next}=c,\ T \le t) = \frac{\lambda_c}{\Lambda}\big(1 - e^{-\Lambda t}\big), \qquad \mathbb{E}[T] = 1/\Lambda. \]

With rates of 0.05 per year for hypertension, 0.02 for type 2 diabetes and 0.01 for myocardial infarction, \(\Lambda = 0.08\), the expected wait is 12.5 years, the probability of an event within a year is \(1-e^{-0.08} = 0.077\), and the first event is hypertension with probability 0.625.

Likelihood. The joint density of observing disease \(c^*\) after waiting \(\Delta t\) is \(\lambda_{c^*} e^{-\Lambda \Delta t}\), so the negative log-likelihood per event is

\[ \ell = -\log \lambda_{c^*} + \Lambda\,\Delta t = \underbrace{-\log \frac{\lambda_{c^*}}{\Lambda}}_{\text{which event}} \; \underbrace{-\log \Lambda + \Lambda \Delta t}_{\text{when}}, \]

a cross-entropy over the next disease plus an exponential likelihood for the waiting time. This is the multi-state model of classical epidemiology with intensities produced by a transformer and age entering as a continuous encoding rather than a position index. The intensities are piecewise constant between tokens, which is why "no-event" tokens matter: they let the model revise \(\lambda_c(h)\) as a person ages through long quiet periods. The decay of AUC with horizon follows from compounding: a 20-year sample is a product of many such steps, each with its own error. (Delphi-2M's exact loss is taken here from secondary coverage; the formulation above is the standard one consistent with it.)

The script implements a Delphi-style sampler with four tokens (hypertension, type 2 diabetes, myocardial infarction, death). Intensities depend on age and history: they rise 4% per year of age, diabetes doubles and hypertension multiplies by 1.5 the infarction rate, and a chronic disease cannot occur twice. Each step draws a waiting time from the total rate and a disease in proportion to its rate, until death or the 20-year horizon.

import numpy as np
D = ["HTN", "T2D", "MI", "DEATH"]
BASE = np.array([0.05, 0.02, 0.01, 0.005])          # rates per year at age 50

def rates(history, age):
    """Toy history-dependent intensities: age raises all rates; T2D and HTN raise MI risk."""
    r = BASE * np.exp(0.04 * (age - 50))
    if "T2D" in history: r[2] *= 2.0
    if "HTN" in history: r[2] *= 1.5
    r[[D.index(d) for d in history if d != "DEATH"]] = 0.0   # chronic diseases occur once
    return r

def sample_trajectory(age, history, horizon, rng):
    """Competing exponentials: wait ~ Exp(total rate), next disease ∝ its rate. Rates are frozen
    between events; Delphi's no-event tokens let a model refresh them during long gaps."""
    end, traj = age + horizon, []
    while True:
        r = rates(history, age); total = r.sum()
        age += rng.exponential(1 / total)
        if age > end: return traj
        d = D[rng.choice(len(D), p=r / total)]
        traj.append((d, round(age, 1))); history = history + [d]
        if d == "DEATH": return traj

rng = np.random.default_rng(0)
r0 = rates([], 50); L = r0.sum()
print("P(event within 1y) analytic %.4f" % (1 - np.exp(-L)), " P(first=HTN) %.3f" % (r0[0] / L))
print("one sampled 20-year trajectory:", sample_trajectory(50, [], 20, rng))
for hist in ([], ["T2D"]):
    mi = np.mean([any(d == "MI" for d, _ in sample_trajectory(50, hist, 20, rng)) for _ in range(20000)])
    print(f"20-year MI risk with history {hist or 'none'}: {mi:.3f}")

Output: at age 50 with no history, the analytic probability of some event within a year is 0.0815 and the first event is hypertension with probability 0.588. One sampled trajectory reads hypertension at 58.0, diabetes at 58.4, death at 69.6. Over 20,000 samples the 20-year infarction risk is 0.267 with no history and 0.388 when diabetes is already present, showing how a sampled trajectory turns history-dependent rates into horizon risks. Rates here are frozen between events, so ageing during a long gap is ignored; inserting a no-event token every few years and recomputing rates is the fix Delphi's vocabulary provides.

A lifetime disease model is cheap to serve (about 2.2M parameters, per secondary coverage) and expensive to validate. The dominant costs are data access and the evaluation design. Population selection. UK Biobank participants were recruited in middle age and are healthier than the general population, so rates learned there need checking before use elsewhere. Delphi-2M's validation on Danish registries without changing parameters is the right test, and its lower AUC there is the expected result. Differences in coding practice (primary versus hospital care, three-character ICD-10 truncation) appear as shifts in disease frequencies and must be mapped before scores are compared.

Horizon-stratified reporting. A single average AUC hides the pattern that matters: discrimination falls with horizon (toward 0.70 at 10 years for Delphi-2M; DT-Transformer's median 0.713 in a prospective 2024 evaluation). Reports should give AUC and calibration by horizon, age band, sex and disease group, and prospective results should be preferred to retrospective ones. DT-Transformer's stronger near-term but faster-decaying performance on Mass General Brigham data shows that an institution's own records may favour short horizons.

Uses and limits. Sampled trajectories suit population planning and synthetic cohorts better than individual decisions; training on synthetic trajectories alone cost only a few AUC points, which makes data sharing without patient records plausible. Biases that explainability exposed in the training data persist into every synthetic cohort, so a released generator needs the same bias audit as the data it replaces.

CoMET: Does Scale Help?

Waxler et al. (2025), a team from Epic, Microsoft Research and Yale, trained decoder-only models on Epic Cosmos, a de-identified dataset spanning more than 300M patient records from 310 health systems, and asked the scaling question directly. The paper is titled "Generative Medical Event Models Improve with Scale"; the abbreviation CoMET stands for Cosmos Medical Event Transformer, while the latest arXiv version (v3) calls the model family Curiosity.

  • Data and tokens: 118M adult patients, 115B events, 151B tokens (2012–2025); 7,105 a-priori tokens closely following ETHOS (ICD-10-CM and ATC in 1–3 pieces, top CPT procedures, the 1,000 most common labs as test plus one of 10 equal-frequency bins, interval tokens from minutes to 3–6 months). Notes and vitals were excluded.
  • Models and scaling: Qwen2-architecture decoders trained from scratch (62M, 119M, 1B parameters; 8,192-token context). isoFLOP sweeps gave power laws with exponents close to natural language but a compute-optimal ratio of roughly 1,000 tokens per parameter, and lower loss predictably improved downstream scores.
  • Inference and results: typically 20–80 simulations at temperature 1, with gains mostly plateauing around 64. Across 78 tasks the 1B model generally matched or beat supervised baselines (mainly XGBoost) without fine-tuning, for example 30-day readmission AUROC 0.770 vs. 0.717; hyperlipidemia outcomes and incident-disease AUROC were exceptions.
  • Stated limitations: no subgroup analysis, no temporal split or prospective validation, censoring not fully handled, truncated histories.

Scaling laws. For a decoder with \(N\) parameters trained on \(D\) tokens, training compute is about \(C \approx 6ND\) floating-point operations. An isoFLOP sweep fixes \(C\), trains several sizes \(N\) with \(D = C/6N\), and records the loss minimum \(N^*(C)\); repeating over budgets gives power laws \(N^* \propto C^{a}\), \(D^* \propto C^{b}\) with \(a + b = 1\). If the optimum keeps a fixed ratio \(D^*/N^* = r\), then \(C = 6rN^2\) and

\[ N^* = \sqrt{C/6r}, \qquad D^* = r N^*. \]

Chinchilla-style language models have \(r \approx 20\); CoMET's medical events gave \(r \approx 1{,}000\), so for the same budget the compute-optimal event model is about \(\sqrt{50} \approx 7\) times smaller and trained on about 7 times more tokens. A low-entropy vocabulary of 7,105 tokens with highly predictable repeats is a plausible reason. The second finding, that lower loss predictably improved downstream scores, is what makes loss a usable proxy for model selection.

How many rollouts. The per-patient error of a simulated risk is \(\sqrt{p(1-p)/K}\). Discrimination suffers from this noise because ranking depends on differences between patients, and it recovers as the noise falls below the spread of true risks; beyond that point extra rollouts buy little.

Monte Carlo standard error of a simulated risk as a function of the number of rollouts K, for a true risk of 0.10.0.0250.0500.0750.1000.095K = 100.067K = 200.047K = 400.038K = 640.027K = 1280.019K = 256standard errorerror halves only when the number of rollouts quadruples
Fig. Monte Carlo error of a simulated risk, \(\sqrt{p(1-p)/K}\), for a model risk of 0.10. The accent bar marks 20 rollouts, the number ETHOS used; CoMET reported gains mostly plateauing around 64. Computed values, not measurements.

The script measures how discrimination depends on the number of rollouts. Each of 20,000 patients has a fixed model risk; a simulated estimate with \(K\) rollouts is a binomial fraction; AUROC is computed with average ranks for ties. The last lines compute the compute-optimal split of a budget for two tokens-per-parameter ratios.

import numpy as np
from scipy.stats import rankdata
rng = np.random.default_rng(0)
N = 20000
risk = 1 / (1 + np.exp(-(rng.normal(-2.2, 1.2, N))))      # model's true per-patient risk
y = rng.random(N) < risk                                  # observed outcomes

def auroc(s, y):
    r = rankdata(s); n1 = y.sum()                         # tied scores get average ranks
    return (r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * (len(y) - n1))

print("exact-risk AUROC %.3f" % auroc(risk, y))
for K in (1, 5, 20, 64, 256):
    p_hat = rng.binomial(K, risk) / K                     # fraction of K rollouts with the outcome
    print(f"K={K:3d}  AUROC {auroc(p_hat, y):.3f}  mean SE {np.mean(np.sqrt(risk*(1-risk)/K)):.3f}")

# Compute-optimal split for a budget C ≈ 6·N·D with D = r·N tokens per parameter.
for C, r in [(1e21, 1000), (1e21, 20)]:
    Np = np.sqrt(C / (6 * r))
    print(f"C={C:.0e} r={r:4d}: N≈{Np/1e6:,.0f}M params, D≈{r*Np/1e9:,.0f}B tokens")

Output: AUROC with exact risks is 0.788; with simulated risks it is 0.583 at \(K=1\), 0.688 at 5, 0.753 at 20, 0.773 at 64 and 0.785 at 256, the same plateau CoMET observed around 64. For \(10^{21}\) FLOPs, a ratio of 1,000 tokens per parameter gives about 408M parameters and 408B tokens; a ratio of 20 gives about 2.9B parameters and 58B tokens.

Training where the data live. CoMET was trained inside a de-identified dataset spanning 310 health systems, which means the data do not move: compute is brought to the data, model weights are the exported artefact, and memorization tests (extracting rare sequences from the model) become part of the release process. A scaling result of about 1,000 tokens per parameter favours small models trained on very large corpora, which is convenient: a 1B-parameter model with an 8,192-token context serves on a single accelerator.

Inference budget. With 20 to 80 simulations per patient and gains plateauing around 64, the budget is set per task by measuring AUROC and calibration against \(K\) on a validation set, then fixing \(K\) in the serving configuration. Answering the 78 tasks from one set of rollouts amortizes the cost, which is the economic case for simulation over one supervised model per task.

What a deployment must add. The authors list no subgroup analysis, no temporal split or prospective validation, incomplete censoring handling and truncated histories. Each maps to a gate before clinical use: subgroup calibration reports, a temporal holdout and a silent prospective period, a censoring-aware evaluation of horizon outcomes, and checks that truncated histories do not bias older patients. The baselines matter too: the supervised comparators were mainly gradient-boosted trees, which are cheap to retrain per site, so the 30-day readmission gain (0.770 vs. 0.717) has to be re-established locally, and exceptions such as hyperlipidemia outcomes are a reminder to keep the baseline for tasks where it wins.

2026: Beyond Token-by-Token

2026 work pushed in two directions: cheaper visit-level prediction, and checking that simulations reproduce the statistics of real care.

  • Rajamohan et al. (2026) pretrained RAVEN on 1.29M NYU Langone patients to predict the full set of next-visit events, down-weighting repeated chronic codes so new onsets carry signal; they warn that repeats can inflate metrics, and found that in their data-limited regime more data helped more than more parameters.
  • Akagi et al. (2026) pretrained a decoder-only simulator on hundreds of millions of records from the University of Tokyo Hospital (2011–2023) and judged it mainly on fidelity (full text): with 256 simulations per prompt, event frequencies correlated with real data at \(r > 0.98\), lab distributions matched closely, and observed-to-expected ratios for eight tasks stayed near 1 on a later test year without recalibration.

Down-weighting repeats. In a visit-set loss, chronic codes that were already present reappear with high probability, so they dominate both the loss and the metrics. RAVEN-style reweighting uses

\[ \mathcal{L} = -\sum_{c} w_c \big[y_c \log \pi_c + (1-y_c)\log(1-\pi_c)\big], \qquad w_c = \begin{cases} \alpha < 1 & c \in V_{1:j} \\ 1 & \text{otherwise,} \end{cases} \]

and evaluation on new onsets restricts to codes with \(c \notin V_{1:j}\).

Fidelity. Akagi et al. compare simulated and real event-type frequencies \(\hat f_e, f_e\) by correlation, and calibration on a later year by the observed-to-expected ratio \(\mathrm{O/E} = \sum_i y_i / \sum_i \hat p_i\). With \(O\) observed events, \(\mathrm{SE}(\log \mathrm{O/E}) \approx 1/\sqrt{O}\), so 400 events give an interval of roughly \(\pm 10\%\). A frequency correlation is dominated by common events when frequencies span orders of magnitude, so \(r > 0.98\) is necessary but not sufficient; per-type ratios \(\hat f_e/f_e\) should be checked as well.

The script shows both 2026 lessons on synthetic data: a predictor that copies the previous visit looks strong when repeats are scored, and a high frequency correlation can coexist with sizeable per-event errors.

import numpy as np
from scipy.stats import rankdata
def auroc(s, y):
    r = rankdata(s); n1 = y.sum()
    return (r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * (len(y) - n1))

rng = np.random.default_rng(1)
P, C = 5000, 50
prev = rng.random((P, C)) < 0.08                          # codes present in the last visit
nxt = np.where(prev, rng.random((P, C)) < 0.9,            # chronic codes usually repeat
               rng.random((P, C)) < 0.02)                 # new onsets are rare
score = prev * 0.9 + rng.random((P, C)) * 0.05            # a "copy the last visit" predictor
print("AUROC, all codes        %.3f" % auroc(score.ravel(), nxt.ravel()))
print("AUROC, new onsets only  %.3f" % auroc(score[~prev], nxt[~prev]))

# Fidelity: simulated vs real event-type frequencies, and observed/expected on a later year.
real_f = rng.dirichlet(np.ones(200) * 0.3)
model_f = real_f * rng.lognormal(0, 0.2, 200); model_f /= model_f.sum()   # slightly wrong model
sim = rng.multinomial(256 * 400, model_f) / (256 * 400)   # 256 rollouts x 400 events
print("frequency correlation r = %.3f" % np.corrcoef(real_f, sim)[0, 1])
p_hat = rng.beta(2, 18, 10000)                             # predicted risks on the later year
y = rng.random(10000) < np.minimum(1, p_hat * 1.15)       # true risk drifted up 15%
print("O/E = %.2f" % (y.sum() / p_hat.sum()))

Output: the copy-the-last-visit predictor scores AUROC 0.892 over all codes and 0.497 on new onsets, so the headline number measured only repetition. Frequencies from a model whose per-type rates are off by about 20% still correlate with the real ones at \(r = 0.978\). A 15% upward drift in true risk shows up as O/E = 1.16.

The 2026 papers point to release gates more than to new architectures. Report new-onset metrics. Visit-set models should publish metrics with repeated chronic codes excluded, as RAVEN warns that repeats inflate results; a dashboard that mixes both hides regressions on the predictions that matter. Measure fidelity on a later year. The Tokyo simulator's O/E near 1 on a later test year without recalibration is the property a simulator needs before it feeds capacity planning or synthetic cohorts; it is monitored per task with intervals, and recalibration is triggered when O/E leaves its interval for two consecutive periods.

Keep simple baselines. On 2.7M outpatients, simulation reached 0.89 AUROC for new hypertension, but a gradient-boosted model on age and visit counts came close on new diagnoses and beat it on readmission (Ramachandran and Shah 2026). ReClaim, trained on insurance claims, reported a mean AUC of 0.756 over more than 1,000 disease-onset endpoints, falling to 0.679 in a prospective test (Ma et al. 2026). Simulation is justified per task, against a baseline and on prospective data. RAVEN's finding that more data helped more than more parameters in a data-limited regime argues for spending on data agreements before larger models.

Generative vs. Representation and Time-to-Event Models

Not every EHR foundation model is a world model. Representation models produce an embedding for a supervised head; time-to-event models learn hazards for many outcomes; generative models simulate. They trade sampling cost against flexibility, so the choice depends on whether you need trajectories or just scores.

  • Steinberg et al. (2021) showed with CLMBR that next-code language modeling is an effective representation learner: the model is trained like a generator but used as an encoder, with a logistic-regression head per task.
  • Steinberg et al. (2024) built MOTOR, which replaces next-token prediction with thousands of time-to-event pretraining tasks under a piecewise-exponential survival likelihood. It handles censoring by construction and needs one forward pass per prediction, but it can only answer questions about the outcomes it was pretrained on, and it cannot generate a trajectory.
  • The Event Stream GPT library (McDermott et al. 2023) formalized generative pretraining over continuous-time event sequences, modeling what happens next and when.
ModelData and scaleTokenization and timeObjectiveInferenceMain evaluations
ETHOS (2024)MIMIC-IV, ~268K patientsSplit codes, decile labs, 13 interval tokensNext token20 rollouts, count outcomesMortality, readmission, LOS, SOFA, DRG
ETHOS-ARES (2025)MIMIC-IV + ED via MEDS, ~300K patients, ~361M tokensAs ETHOS, 19 interval tokensNext token (45M params)100 rollouts, top-p 0.9, risk trajectoriesHospital mortality, ICU admission, prolonged stay, ED tasks
Foresight (2024)3 UK/US sites, 811K patientsSNOMED concepts from text, 1-day bucketsNext conceptTop-k next concept, synthetic timelinesPrecision@k, clinician review
CEHR-GPT (2024)Columbia OMOP, 2.3M training patientsVisits, day-gap tokens up to 1,080 daysNext tokenSampling synthetic patientsFidelity, utility, privacy attacks
TransformEHR (2023)VHA, 6.5M patientsVisits of ICD codesGenerate all codes of next visit (enc-dec)Fine-tuned classifiersPancreatic cancer, self-harm; MIMIC-IV transfer
Delphi-2M (2025)UK Biobank ~0.4M; Danish ~1.9M externalICD-10 diseases + lifestyle, continuous ageNext disease + time to eventRates and sampled 20-year trajectoriesPer-disease AUC, external validation
CoMET (2025)Epic Cosmos, 118M patients, 151B tokensETHOS-like, 7,105 tokensNext token, 62M–1B params20–80 rollouts78 tasks, scaling laws
MOTOR (2024)EHR and claims, up to 55M patientsCoded eventsTime-to-event over thousands of codesOne pass, hazardsTime-dependent C-statistic

Table. Generative event models compared with a time-to-event foundation model. Scales are as reported in each paper (patient counts round differently across versions); Delphi-2M details are from secondary coverage. MOTOR's 55M records (about 9B events) and 143M parameters are from its abstract.

A practical way to choose: if every question is "risk of outcome \(c\) by time \(\tau\)" for a fixed list of \(c\), a time-to-event model is cheaper and handles censoring properly. If questions are open-ended, involve sequences ("ICU then readmission"), or you need synthetic data, a generative model is the more general tool, and you pay for that generality in sampling compute and calibration work.

Let \(h\) be a history and \(c \in \{1,\dots,C\}\) an outcome from a fixed list. A time-to-event model outputs a hazard \(\lambda_c(t \mid h) \ge 0\), the instantaneous event rate at time \(t\) after the prediction time given no event before \(t\). Survival and risk by horizon \(\tau\) follow by integration:

\[ S_c(\tau \mid h) = \exp\!\Big(-\int_0^\tau \lambda_c(t \mid h)\,dt\Big), \qquad r_c(\tau \mid h) = 1 - S_c(\tau \mid h). \]

Piecewise-exponential likelihood. MOTOR holds the hazard constant within pieces with edges \(0 = e_0 < e_1 < \dots < e_P\). For patient \(i\) with follow-up \(T_i\) and event indicator \(\delta_i\) (0 if the record ended first, that is, censored), the exposure in piece \(p\) is \(E_{ip} = \max(0, \min(T_i, e_p) - e_{p-1})\) and \(d_{ip} = 1\) if the event fell in piece \(p\). The negative log-likelihood is

\[ \mathcal{L} = \sum_i \sum_p \big( \lambda_{ip} E_{ip} - d_{ip} \log \lambda_{ip} \big). \]

A censored patient contributes only the survival term, which is exactly the information censoring provides. With one shared hazard per piece, the maximum is \(\hat\lambda_p = \sum_i d_{ip} / \sum_i E_{ip}\), events per person-time. In the figure, hazards of 0.02 per year in year one and 0.03 thereafter give a five-year risk of \(1 - e^{-0.14} = 0.131\).

Piecewise-constant hazard (left) and the resulting cumulative risk curve (right) for hazards of 0.02 per year in year one and 0.03 per year in years one to five.0123450.010.020.030.04years since indexhazard λ(t) per year0123450.040.080.120.160.131 at 5 y0.020 at 1 yyears since indexcumulative risk 1 − S(t)
Fig. A piecewise-exponential hazard and its risk curve. Constant hazards inside each piece integrate to a cumulative hazard of 0.02 + 4 × 0.03 = 0.14 at five years, so the five-year risk is 1 − e−0.14 ≈ 0.131. Computed, illustrative values.

The generative counterpart. A generative model estimates the same quantity as \(\hat r_c(\tau) = \frac1K\sum_k \mathbb{1}[T^{(k)}_c \le \tau]\), where \(T^{(k)}_c\) is the first time outcome \(c\) appears in rollout \(k\). Its error is \(\sqrt{r(1-r)/K}\), 0.075 for \(r = 0.131\) and \(K = 20\), against no sampling error for a hazard head. In exchange it answers composite questions such as \(P(T_{\text{ICU}} < T_{\text{readmit}} \le 30\text{ days})\), which no head trained on single outcomes provides. Event Stream GPT makes the continuous-time version explicit by modeling \(p(\Delta t, c \mid h)\), the joint distribution of when the next event occurs and what it is. Censoring enters a generative model only implicitly: if records end with an end-of-record token, rollouts that emit it before \(\tau\) undercount events.

Representation models such as CLMBR fit \(\sigma(w_c^\top z + b_c)\) on an embedding \(z = f(h)\) for a binary label at a fixed horizon. The assumptions differ: the hazard model assumes non-informative censoring, the generative model assumes the end-of-record process is modeled or masked, and the representation head assumes the labelled subset with full follow-up is representative.

The module below implements a piecewise-exponential time-to-event head without a network, so every quantity can be checked by hand. exposure_and_events turns follow-up times and event indicators into arrays of shape \((N, P)\): years at risk in each piece and a one-hot event indicator. nll is the loss a neural head would minimize, with log-hazards as the output of a linear layer on the history embedding. mle_hazard is the closed-form optimum and risk_by integrates hazards to a risk at horizon \(\tau\).

"""Piecewise-exponential time-to-event head (MOTOR-style), numpy only; illustrative."""
import numpy as np

EDGES = np.array([0.0, 1.0, 5.0])          # pieces [0,1) and [1,5) years

def exposure_and_events(times, events, edges=EDGES):
    """times: (N,) follow-up end in years; events: (N,) 1 if outcome observed, 0 if censored.
    Returns exposure (N, P) years spent in each piece and event indicator (N, P)."""
    lo, hi = edges[:-1], edges[1:]
    t = np.minimum(times, edges[-1])[:, None]
    expo = np.clip(t - lo, 0.0, hi - lo)                       # time at risk inside each piece
    piece = np.searchsorted(edges, np.minimum(times, edges[-1] - 1e-9), side="right") - 1
    ev = np.zeros_like(expo)
    observed = (events == 1) & (times < edges[-1])
    ev[observed, piece[observed]] = 1.0
    return expo, ev

def nll(log_hazard, expo, ev):
    """Negative log-likelihood of a piecewise-constant hazard.
    log_hazard: (P,) or (N, P). Censored rows contribute only the survival term."""
    lam = np.exp(log_hazard)
    return float(np.sum(lam * expo) - np.sum(ev * log_hazard))

def mle_hazard(expo, ev):
    """Closed-form maximiser: events / exposure in each piece."""
    return ev.sum(0) / expo.sum(0)

def risk_by(tau, lam, edges=EDGES):
    """1 - S(tau) for piecewise-constant hazards lam (P,)."""
    lo, hi = edges[:-1], edges[1:]
    cum = np.sum(lam * np.clip(tau - lo, 0, hi - lo))
    return 1.0 - np.exp(-cum)

if __name__ == "__main__":
    # Worked example: hazards 0.02/yr in year 1, 0.03/yr in years 1-5.
    lam_true = np.array([0.02, 0.03])
    assert abs(risk_by(5.0, lam_true) - (1 - np.exp(-0.14))) < 1e-12        # 0.1306
    rng = np.random.default_rng(1)
    N = 200_000
    # simulate event times from the piecewise hazard
    u = rng.exponential(1.0, N)                       # cumulative-hazard draw
    t_event = np.where(u < 0.02, u / 0.02, 1.0 + (u - 0.02) / 0.03)
    t_cens = rng.uniform(0.5, 6.0, N)                 # administrative / loss to follow-up
    times = np.minimum(t_event, t_cens); events = (t_event <= t_cens).astype(int)
    expo, ev = exposure_and_events(times, events)
    lam_hat = mle_hazard(expo, ev)
    print("lam_hat", lam_hat.round(4), "risk_5y", round(risk_by(5.0, lam_hat), 4))
    assert np.allclose(lam_hat, lam_true, rtol=0.05)
    # the MLE is a minimum of the NLL
    base = nll(np.log(lam_hat), expo, ev)
    for d in (np.array([0.05, 0]), np.array([0, -0.05])):
        assert nll(np.log(lam_hat) + d, expo, ev) > base
    # naive mistake: drop censored people, count fraction with an event by 5 years
    naive = ((events == 1) & (times <= 5)).sum() / N
    print("naive event fraction (censoring ignored):", round(naive, 4))
    assert naive < risk_by(5.0, lam_true) - 0.02     # censoring makes naive counts too low
    print("all pwe tests passed")

Output: on 200,000 simulated patients with hazards 0.02 then 0.03 per year, censored uniformly between 0.5 and 6 years, the estimate is (0.0202, 0.0297) and the five-year risk 0.1296 against the true 0.1306; perturbing either log-hazard raises the likelihood, confirming the optimum; and the naive fraction of patients with an observed event by five years is 0.080, the censoring error the likelihood avoids. Attached to a pretrained backbone, the same nll trains a linear layer mapping the final hidden state to \(C \times P\) log-hazards, and its risks can be compared on the same patients with risks counted from rollouts; agreement within Monte Carlo error is a useful consistency check.

A health system that deploys a generative event model is soon asked to serve dozens of fixed risk scores daily, plus occasional open-ended queries and synthetic cohorts. Serving everything by simulation multiplies compute by roughly \(K\) times the rollout length relative to a single forward pass; serving everything with heads loses open-ended questions. The usual design is hybrid: one pretrained backbone, linear or hazard heads for the fixed scores (CLMBR-style or MOTOR-style), and simulation reserved for composite outcomes, on-demand questions and synthetic data.

RequirementRepresentation + headsTime-to-event headGenerative simulation
Fixed outcomes, fixed horizonsyes, labels per taskyes, censoring handledyes, at K-fold cost
Any horizon for listed outcomesno, one head per horizonyesyes
Composite or sequential outcomesonly with new labelsnoyes
Synthetic cohortsnonoyes
Inference per patientone passone passprefill plus K rollouts

Consistency monitoring. Two serving paths can disagree, and disagreement erodes trust. A nightly job compares, on a sample of patients, the head's risk with the simulated risk for the same outcome; the difference should be centred on zero with spread near \(\sqrt{r(1-r)/K}\). A systematic offset is resolved by calibration plots of each path against observed outcomes on a lagged cohort. A common cause is censoring: if a new data extract ends transferred patients' records with an end-of-record token, rollouts stop before the horizon and the simulated risk falls while the hazard head, which treats those patients as censored, does not. Remedies are to mask the token during sampling (cheap, but extrapolates), to retrain with censoring as a non-terminal marker (principled, costs a training run), or to answer horizon questions only from the head.

Choosing per outcome. An outcome moves from simulation to a head when, on a temporal holdout, the head's AUROC and calibration fall within the confidence interval of the simulated estimate. 2026 alternatives narrow the gap further: EveryQuery estimates outcomes directly from a question prompt without simulation (Chandak et al. 2026), which keeps some open-endedness at one-pass cost. MOTOR shows what a well-specified head costs: thousands of pretraining tasks and a survival likelihood, but a single pass at serving time.

Physiological Dynamics and Digital Twins

Physiological world models simulate continuous signals such as heart rate, glucose or vitals; digital twins aim to simulate one individual well enough to plan their care. The 2024–2026 evidence for both is mostly about forecasting accuracy, not decision support.

  • Narayanswamy et al. (2025) trained LSM, a wearable-sensor foundation model, on up to 40 million hours of minute-level data from more than 165,000 people (heart rate, heart-rate variability, accelerometry, electrodermal activity, skin temperature, altimeter). It is trained to impute, interpolate and extrapolate across time and sensors, and the authors report scaling laws across compute, data and model size. Extrapolation of masked future windows is a short-horizon physiological world model, though the paper frames it as representation learning.
  • Makarov et al. (2025) built DT-GPT, which fine-tunes an LLM to forecast clinical variables directly from EHR text (npj Digital Medicine, 2025). On lung cancer, ICU and Alzheimer's datasets it reduced scaled MAE by 1.3–3.4% against the best machine-learning baselines and preserved cross-variable correlations. Its successor framework TwinWeaver (ICML 2026) trained a "Genie Digital Twin" on 93,054 patients across 20 cancer types, reporting a median MASE of 0.87 vs. 0.97 for the best time-series baseline and an average C-index of 0.703 vs. 0.662 on survival, progression and therapy-switching tasks.

The margins over classical baselines are modest. A digital twin in the strong sense, accurate under hypothetical treatments for a specific patient, needs the causal properties discussed below, which none of these systems claims.

Forecasting as conditional generation. Let \(x_{1:T} \in \mathbb{R}^{T \times V}\) be a patient's sequence of \(V\) continuous variables (heart rate, glucose, a tumour marker), sampled on a grid or at irregular times, and let \(h\) be the remaining history (diagnoses, drugs, demographics). A physiological world model learns \(p_\theta(x_{T+1:T+H} \mid x_{1:T}, h)\). LSM learns it implicitly by reconstructing a masked final window; DT-GPT learns it by next-token prediction over the text serialization of \(x\) and \(h\), so numbers are produced digit by digit and the joint distribution over variables comes from the language model's factorization.

Error metrics. With point forecast \(\hat x\), the mean absolute error is \(\mathrm{MAE} = \frac{1}{H}\sum_{h=1}^{H} |x_{T+h} - \hat x_{T+h}|\). Variables on different scales are compared by a scaled MAE (dividing by each variable's standard deviation) or by the mean absolute scaled error of Hyndman and Koehler (2006),

\[ \mathrm{MASE} = \frac{\mathrm{MAE}}{\frac{1}{T-1}\sum_{t=2}^{T}|x_t - x_{t-1}|}, \]

which divides by the in-sample error of the one-step persistence forecast. MASE below 1 means beating that naive scale; for multi-step horizons values above 1 are common, so comparisons between models on the same data are what matter. TwinWeaver's 0.87 against 0.97 is such a comparison.

Survival tasks. Event outcomes (progression, death, therapy switch) are scored by the concordance index \(C = P(\hat r_i > \hat r_j \mid T_i < T_j, \delta_i = 1)\), where \(\hat r\) is predicted risk, \(T\) observed time and \(\delta\) the event indicator. A C-index of 0.703 orders about 70% of comparable patient pairs correctly; 0.5 is chance.

What a digital twin requires. Accurate forecasting estimates \(p(x_{T+1:T+H} \mid x_{1:T}, h, a_{T})\) for the treatment \(a\) actually recorded. A twin in the strong sense must estimate the interventional distribution \(p(x_{T+1:T+H} \mid x_{1:T}, h, \mathrm{do}(a))\) for treatments that were not given. The two coincide only if every common cause of treatment and outcome is contained in \((x_{1:T}, h)\) and every treatment of interest has positive probability for histories like this one. Neither condition is tested by forecasting error, which is why lower MASE alone does not establish a twin.

The script simulates two coupled vitals, heart rate and mean arterial pressure, as a first-order vector autoregression with correlated shocks, then forecasts 24 hours ahead from 72 hours of context for 200 held-out patients. It compares persistence (repeat the last value), the context mean, and a VAR(1) fitted by least squares, all scored by MASE. It then contrasts the deterministic mean forecast with 50 sampled futures per patient, the distinction DT-GPT's evaluation draws when it checks whether cross-variable correlations are preserved.

"""Forecasting two coupled vitals with persistence, a mean model and a fitted VAR(1); scored by MASE."""
import numpy as np
rng = np.random.default_rng(0)
A = np.array([[0.90, 0.05], [-0.10, 0.85]])        # heart rate and mean arterial pressure, as deviations
L = np.linalg.cholesky(np.array([[4.0, -2.4], [-2.4, 4.0]]))   # correlated shocks (corr -0.6)
def simulate(n, T):
    x = np.zeros((n, T, 2))
    for t in range(1, T):
        x[:, t] = x[:, t-1] @ A.T + rng.normal(size=(n, 2)) @ L.T
    return x + np.array([75.0, 85.0])
train, test = simulate(400, 96), simulate(200, 96)
ctx, H = 72, 24                                      # 72 hours of context, 24-hour horizon
# fit VAR(1) with intercept by least squares on training transitions
X = train[:, :-1].reshape(-1, 2); Y = train[:, 1:].reshape(-1, 2)
Xd = np.c_[X, np.ones(len(X))]; B, *_ = np.linalg.lstsq(Xd, Y, rcond=None)
resid = Y - Xd @ B; S = np.linalg.cholesky(np.cov(resid.T))
def roll(x0, h, sample=False):
    out, x = [], x0
    for _ in range(h):
        x = np.c_[x, np.ones(len(x))] @ B + (rng.normal(size=x.shape) @ S.T if sample else 0)
        out.append(x)
    return np.stack(out, 1)
hist, fut = test[:, :ctx], test[:, ctx:ctx+H]
naive_in = np.abs(np.diff(hist, axis=1)).mean(axis=1)            # in-sample one-step naive MAE, per series
def mase(pred): return (np.abs(pred - fut).mean(axis=1) / naive_in).mean()
pers = np.repeat(hist[:, -1:], H, 1); mean = np.repeat(hist.mean(1, keepdims=True), H, 1)
var_mean = roll(hist[:, -1], H)
print("MASE persistence %.3f  context mean %.3f  VAR(1) %.3f" % (mase(pers), mase(mean), mase(var_mean)))
samp = roll(np.repeat(hist[:, -1], 50, 0), H, sample=True)       # 50 sampled futures per patient
def stats(z):
    d = np.diff(z, axis=1).reshape(-1, 2); return d[:, 0].std(), np.corrcoef(d.T)[0, 1]
for name, z in [("real", fut), ("sampled", samp), ("mean forecast", var_mean)]:
    print("%-13s  sd of hourly HR change %.2f  corr(HR, MAP changes) %+.2f" % ((name,) + stats(z)))

Output:

MASE persistence 2.560  context mean 2.257  VAR(1) 1.940
real           sd of hourly HR change 2.10  corr(HR, MAP changes) -0.61
sampled        sd of hourly HR change 2.09  corr(HR, MAP changes) -0.59
mean forecast  sd of hourly HR change 0.21  corr(HR, MAP changes) -0.55

The fitted model reduces MASE by about 14% relative to the context mean and 24% relative to persistence, a margin of the same kind as the modest gains reported for DT-GPT and TwinWeaver over strong baselines. The second block shows why point accuracy is not simulation fidelity. Sampled futures reproduce both the spread of hourly changes (2.09 against 2.10 bpm) and their negative correlation with pressure; the mean forecast has the right correlation sign but a spread ten times too small, because averaging removes the variability that a simulator must generate. A model that will be rolled forward should be judged on samples, not only on its mean.

How these systems are built. The 2024–2026 physiological forecasters follow two recipes. Sensor models such as LSM pretrain a masked encoder on tens of millions of hours of minute-level wearable data and treat extrapolation as one masking pattern among several; they are served as encoders, with forecasting as a by-product. EHR forecasters such as DT-GPT serialize each patient's history into text and fine-tune a language model to emit future values; TwinWeaver generalizes this into a framework that trains one model across cancer types and tasks. The language-model route inherits mature serving infrastructure (batching, key-value caching, quantization) but pays for it: every number costs several tokens, so a forecast of ten variables over twenty visits is hundreds of decoding steps, and sampling many futures per patient multiplies that cost.

Evaluation in practice. Credible reports compare against strong classical baselines (persistence, last-observation-carried-forward, gradient-boosted trees, dedicated time-series models) on patient-level and temporal splits, report MASE or scaled MAE per variable rather than one pooled figure, and check calibration of predicted intervals. The reported margins of 1.3–3.4% in scaled MAE and 0.87 against 0.97 in MASE are useful but small enough that a change of split, cohort or preprocessing can erase them, so external validation matters more than the headline.

Failure modes. Forecasts that look accurate on average can fail exactly where decisions happen: around treatment changes, after admissions, and in rare subgroups. Language-model forecasters can produce unit errors or implausible values when number formatting drifts. The largest risk is interpretive: a twin interface invites what-if questions, and a model trained on observational records answers them with confounded associations. Production systems built on these models restrict counterfactual queries, validate against randomized evidence where it exists, and label outputs as forecasts under usual care.

Sleep, Wearable and Bed-Sensor Foundation Models

Sensor foundation models compress nights and days of physiology into vectors, and that makes them the natural front end for a health world model: they turn signals sampled hundreds of times per second into something a timeline model can read one night at a time. Most of them are not world models themselves. This section sorts sleep, wearable and ballistocardiography (BCG) models by how far they reach into the future, then shows how their outputs can become tokens in an ETHOS-style timeline. The companion book on health foundation models covers these models as representation learners in more depth; here the question is narrower: what do they let a simulator predict?

A sensor foundation model is an encoder \(f_\phi\) that maps a window of raw or minute-level signals \(s_{t} \in \mathbb{R}^{L \times C}\) (\(L\) samples, \(C\) channels) to an embedding \(z_t = f_\phi(s_t) \in \mathbb{R}^{d}\) with \(d \ll LC\). A night of four channels at 100 Hz has \(LC \approx 1.15 \times 10^7\) values; a 64-dimensional embedding compresses it by five orders of magnitude. A health world model then operates on the sequence \(z_{1}, z_{2}, \dots\) (one per night or day) jointly with clinical events \(e\). The question this section asks of each sensor model is which conditional it estimates: \(p(s_{\text{masked}} \mid s_{\text{visible}})\) inside a window, \(p(s_{t+1:t+k} \mid s_{\le t})\) beyond it, \(p(T_{\text{event}} \mid z_t)\) from a snapshot, or \(p(z_{t+1} \mid z_{\le t}, a_t)\) under an action \(a_t\). Only the last two say anything about time that has not been observed, and only the last one can be rolled forward.

The script cuts four training tasks from one person's 120-night series of resting heart rate and reports, for each, how far its target lies beyond the last observed night, whether it predicts a path of intermediate states, and whether it takes an action as input. These three properties distinguish an imputer, a forecaster, a snapshot risk model and a world model.

"""Four training tasks cut from one person's nightly series; each rung reaches further past observed time."""
import numpy as np
rng = np.random.default_rng(1)
T = 120                                            # 120 nights of resting heart rate
hr = 60 + np.cumsum(rng.normal(0, 0.3, T)) + rng.normal(0, 1.0, T)
behav = rng.integers(0, 2, T)                      # e.g. late exercise yes/no (observational)
event_day = 400                                    # a diagnosis 400 days after night 0
tasks = {}
m = np.zeros(T, bool); m[40:47] = True             # impute: hide a week inside the window
tasks["impute"] = dict(ctx=np.where(~m)[0], tgt=np.where(m)[0])
tasks["forecast"] = dict(ctx=np.arange(0, 100), tgt=np.arange(100, 120))
tasks["event"] = dict(ctx=np.arange(99, 100), tgt=np.array([event_day]))   # one night -> time to event
tasks["rollout"] = dict(ctx=np.arange(0, 100), tgt=np.arange(100, 120), action=behav[100:120])
print(f"one night at 100 Hz x 4 channels = {8*3600*100*4:,} samples -> 6 summaries + 64-d embedding")
for name, t in tasks.items():
    beyond = t["tgt"].max() - t["ctx"].max()       # how far the target lies past the last observed night
    inside = (t["tgt"] < t["ctx"].max()).all()
    print(f"{name:8s} context={len(t['ctx']):3d} targets={len(t['tgt']):2d} "
          f"lookahead={max(beyond, 0):4d} nights  inside_window={inside}  "
          f"path={len(t['tgt']) > 1 and not inside}  action_input={'action' in t}")

Output:

one night at 100 Hz x 4 channels = 11,520,000 samples -> 6 summaries + 64-d embedding
impute   context=113 targets= 7 lookahead=   0 nights  inside_window=True  path=False  action_input=False
forecast context=100 targets=20 lookahead=  20 nights  inside_window=False  path=True  action_input=False
event    context=  1 targets= 1 lookahead= 301 nights  inside_window=False  path=False  action_input=False
rollout  context=100 targets=20 lookahead=  20 nights  inside_window=False  path=True  action_input=True

Imputation never leaves the observed window. Snapshot event prediction reaches furthest (301 nights here, years in SleepFM) but produces one time, not a path. Only forecasting and rollout produce paths, and only rollout conditions on behavior.

In deployed systems sensor foundation models sit at the edge of a health world model as frozen feature extractors. Raw signals are reduced on the device or in the vendor's cloud to minute-level features or nightly summaries; an encoder trained on a device fleet (Apple's PPG model, LSM-2, BCG-FM) produces embeddings; a downstream model consumes them. Three engineering decisions follow from this split. The encoder must be versioned and frozen with every model that reads its outputs, because a retrained encoder shifts embeddings silently. The unit of exchange (one record per night or per day) fixes the time resolution of everything downstream. And the encoder's training population, typically device owners and research volunteers, bounds where the world model can be trusted. Evaluating a sensor model as a world-model component therefore means measuring forecasting skill and event lead time on held-out people and later time periods, not only linear-probe accuracy.

Representation Models, Mostly

Nearly every sensor foundation model released up to 2025 learns a representation of the present, not a transition model of the future. The two dominant pretraining objectives make this explicit. Contrastive learning pulls together two views that should share information (two modalities recorded in the same window, or two windows from the same person) and pushes apart everything else. Masked reconstruction hides patches of a signal and asks the model to fill them in. Neither objective asks what happens next night, next month or after a treatment.

A model starts to behave like a world model when its output is about time that has not been observed yet. Four steps lead there, each a stronger claim than the last:

  • Imputing missing streams. Filling a gap inside an observed window (the watch was charging) is interpolation, a weak form of dynamics.
  • Forecasting signals. Extrapolating the final minutes or hours of a window, or generating the next tokens of a signal, is a short-horizon transition model.
  • Predicting future events from a snapshot. Attaching survival heads to one night's embedding forecasts disease years ahead, but with no intermediate states, so nothing can be rolled out.
  • Action-conditioned rollouts. Predicting how physiology changes under a chosen behavior or intervention is the Dreamer-style world model of the control half of this book.
Ladder from sensor representation models to sensor world models, with example models at each rung. representation of the present simulation of the future Embed contrastive same person/time Impute masked patches fill the gap Forecast extrapolate or next token Predict events survival heads years ahead Roll out action-conditioned latent dynamics Apple PPG/ECGWBMPaPaGei, Pulse-PPGSleepFM (2024)BCG-FM LSMLSM-2SensorFM SOTERHypnosLSM-2 extrapolation SleepFM (2026):130 conditionsfrom one night SensorWMNormWear-2 most published sensor models sit on the two left rungs; the right rung is mostly 2026 preprints and workshop papers
Fig. A ladder from representation to simulation for sensor models. Each rung makes a stronger claim about unobserved time. Placement reflects each paper's main evaluated capability; several models span two rungs. Original diagram.
ModelModalityPretraining objectivePredicts the future?Main evaluation
SleepFM (2024)PSG: brain, ECG, respiratoryLeave-one-out contrastiveNoStaging, sleep-disordered breathing, retrieval
SleepFM (2026)PSG, varied channel setsContrastive, then survival headsYes: disease onset from one nightC-index across 1,000+ conditions; held-out cohort
Hypnos (2026)8 PSG modalitiesNext-token prediction on quantized signalsNext signal tokens; used for embeddingsStaging, atrial fibrillation
Apple PPG/ECG (2023)Watch PPG and ECGParticipant-level contrastiveNoDemographics, ~50 conditions
WBM (2025)27 hourly behavioral metricsContrastiveNo (stated by authors)57 health tasks
LSM-2 (2025), SensorFM (2026)Minute-level wearable featuresMasked reconstruction with inherited missingnessExtrapolation of a final windowImputation, classification
SOTER (2026)Multichannel wearable signalsGenerative, continuous-time decoderYes: zero-shot forecastingRMSE/MAE on six datasets
SensorWM (2026)Wearable states and behaviorsLatent action-conditioned dynamicsYes: multi-week rolloutsForecasting vs. persistence
BCG-FM (2026)Bed BCG (piezoelectric)Participant-level contrastiveNo (cross-sectional)Age, 15 self-reported conditions

Table. Sensor foundation models through a world-model lens. "Predicts the future?" refers to what the paper evaluates, not what the architecture could be extended to do. Sources are linked in the subsections below.

Contrastive objective. An encoder \(f_\phi\) maps a sensor window \(x\) to \(z = f_\phi(x)\). For a batch of \(B\) anchors \(z_i\) with positives \(z_i^+\) (another modality of the same window, or another window of the same person), the InfoNCE loss of van den Oord et al. (2018) is

\[ \mathcal{L}_{\text{NCE}} = -\frac{1}{B}\sum_{i=1}^{B} \log \frac{\exp(\mathrm{sim}(z_i, z_i^+)/\tau)}{\sum_{j=1}^{B} \exp(\mathrm{sim}(z_i, z_j^+)/\tau)}, \]

with cosine similarity \(\mathrm{sim}\) and temperature \(\tau\). Minimizing it maximizes a lower bound on the mutual information \(I(z; z^+)\), which is at most \(\log B\). The choice of positive pair decides what is kept. If positives are two windows of the same person at different times, the shared information is whatever is stable within a person (age, fitness, habitual heart rate); whatever changes between the two windows is, from the loss's point of view, noise to be discarded.

Masked reconstruction. A mask \(\mathcal{M}\) hides a set of patches and the model minimizes \(\sum_{p \in \mathcal{M}} \lVert \hat x_p - x_p \rVert^2\) given the visible patches. If \(\mathcal{M}\) covers interior patches, the target is an interpolation; if it covers the final patches, the target is an extrapolation \(p(x_{t+1:t+k} \mid x_{\le t})\), a short-horizon transition model. Most sensor models sample masks uniformly, so extrapolation is a small share of training signal.

What a transition model adds. A world model needs a state \(s_t\) and a transition \(p(s_{t+1} \mid s_t, a_t)\), trained with a term such as \(-\log p_\theta(x_{t+1} \mid x_{\le t}, a_t)\). Neither loss above contains this term. The four rungs of the ladder correspond to four estimands: \(p(x_{\mathcal{M}} \mid x_{\setminus \mathcal{M}})\) with \(\mathcal{M}\) inside the window (impute); the same with \(\mathcal{M}\) at the end (forecast); \(p(T \mid z_t)\), a time-to-event distribution from one embedding (predict events); and \(p(z_{t+1:t+H} \mid z_{\le t}, a_{t:t+H-1})\) (roll out). Each step adds either unobserved time or an action to the conditioning, and only the last supports simulation of alternative behaviors.

The script makes the representation-versus-dynamics distinction concrete. Each of 512 synthetic people has a stable 4-dimensional trait and a 4-dimensional state that evolves as an AR(1) process; a 16-dimensional sensor window mixes both with noise. A linear encoder with a 4-dimensional output is trained with InfoNCE, positives being two windows of the same person at random times, the recipe of Apple's PPG model and BCG-FM. Linear probes, fitted on half the people and scored on the other half, then ask what the embedding knows.

"""Same-person contrastive learning keeps the trait and discards the changing state; a transition model keeps it."""
import torch, torch.nn.functional as F
torch.manual_seed(0)
P, T, D = 512, 32, 16                               # people, windows per person, input dim
trait = torch.randn(P, 4)                           # stable per-person physiology
state = torch.zeros(P, T, 4)                        # slowly changing state (AR(1))
for t in range(1, T): state[:, t] = 0.8 * state[:, t-1] + 0.6 * torch.randn(P, 4)
mix = torch.randn(8, D)
x = torch.cat([trait[:, None].expand(-1, T, -1), state], -1) @ mix + 0.3 * torch.randn(P, T, D)

def info_nce(za, zb, tau=0.1):
    za, zb = F.normalize(za, dim=-1), F.normalize(zb, dim=-1)
    return F.cross_entropy(za @ zb.T / tau, torch.arange(len(za)))

enc = torch.nn.Linear(D, 4); opt = torch.optim.Adam(enc.parameters(), 1e-2)
for step in range(1500):                            # positives: two windows of the same person, different times
    i = torch.randint(0, P, (256,)); t1, t2 = torch.randint(0, T, (2, 256))
    loss = info_nce(enc(x[i, t1]), enc(x[i, t2])); opt.zero_grad(); loss.backward(); opt.step()

def probe_r2(z, y):                                # linear probe, fit on first half of people, score on second
    h = len(z) // 2; Z = torch.cat([z, torch.ones(len(z), 1)], 1)
    w = torch.linalg.lstsq(Z[:h], y[:h]).solution
    return 1 - ((Z[h:] @ w - y[h:]) ** 2).sum() / ((y[h:] - y[h:].mean(0)) ** 2).sum()
with torch.no_grad():
    z = enc(x[:, :-1]).reshape(-1, 4)
    print("contrastive embedding -> trait R2 %.2f" % probe_r2(z, trait[:, None].expand(-1, T-1, -1).reshape(-1, 4)))
    print("contrastive embedding -> next state R2 %.2f" % probe_r2(z, state[:, 1:].reshape(-1, 4)))
    print("raw window (transition model) -> next state R2 %.2f" % probe_r2(x[:, :-1].reshape(-1, D), state[:, 1:].reshape(-1, 4)))

Output:

contrastive embedding -> trait R2 0.99
contrastive embedding -> next state R2 -0.01
raw window (transition model) -> next state R2 0.61

The contrastive embedding recovers the trait almost perfectly and carries no information about the next state (R² near zero), while the raw window predicts it close to the ceiling of 0.64 set by the AR coefficient of 0.8. Same-person positives teach the encoder to ignore exactly what changes over time. A representation trained this way is a good input to a world model but cannot itself be one.

Why industry builds representation models. Contrastive and masked objectives scale on unlabeled fleet data, need no outcome labels, and produce one embedding that serves many downstream tasks through cheap linear probes. Apple's PPG/ECG model, WBM, LSM-2 and BCG-FM are all evaluated this way, on dozens of cross-sectional tasks such as age, sex, medication use and self-reported conditions. That evaluation protocol rewards stable person-level information and is silent about dynamics, so the published leaderboards say little about world-model use.

Placing a model on the ladder. A practical audit asks four questions of any sensor model before it is wired into a simulator. Does its pretraining objective include a loss on unobserved future time, and over what horizon? Is extrapolation evaluated against persistence and seasonal baselines, not only against other deep models? Does it accept actions or context variables as inputs? And does its evaluation include held-out later time periods, not only held-out people? The table's "Predicts the future?" column is the answer to the first question as evaluated, which can differ from what the architecture permits.

Failure modes. Using a same-person contrastive embedding as the state of a world model produces rollouts that are nearly constant, because the embedding was trained to be invariant to change; the model looks calibrated on population risk and useless for detecting deterioration. Masked models trained with mostly interior masks extrapolate poorly beyond a few minutes. Event heads on snapshots are often reported with C-index alone, which hides poor calibration at the horizons that matter clinically. Each of these is caught by evaluating on future time within the same people, which is cheap to add and rarely reported.

Cost. Adding an explicit extrapolation loss or an action-conditioned head to an existing encoder is cheap relative to pretraining: the same data, a different mask schedule or a small transition network on frozen embeddings. The expensive part is evaluation data, long within-person sequences with outcome labels, which most sensor datasets were not collected to provide.

SleepFM: One Night, Many Futures

SleepFM is the clearest case of a sensor representation model turned into a long-horizon risk forecaster: it encodes one night of polysomnography (PSG) and predicts which of hundreds of diseases will appear in the following years. PSG is the overnight sleep-lab recording of brain activity (EEG), eye movements, muscle tone, ECG and breathing, scored in 30-second epochs.

  • Thapa et al. (2024) introduced SleepFM at ICML 2024, pretrained on more than 100,000 hours of PSG from over 14,000 Stanford Sleep Clinic participants, with separate encoders for brain activity, ECG and respiratory channels.
    • Its leave-one-out contrastive loss aligns each modality with the average of the others, and beat pairwise contrastive learning on staging and sleep-disordered breathing detection.
    • Logistic regression on frozen embeddings beat an end-to-end CNN on staging (macro AUROC 0.906 vs. 0.842 in the paper's table) and on breathing-disorder detection.
  • Thapa et al. (2026) scaled SleepFM in Nature Medicine (vol. 32, published January 2026) to over 585,000 hours of PSG from about 65,000 participants across several cohorts, with an encoder that accepts different channel configurations.
    • From a single night, 130 conditions reached a C-index of at least 0.75, among them all-cause mortality (0.84), dementia (0.85), myocardial infarction (0.81), heart failure (0.80), chronic kidney disease (0.79), stroke (0.78) and atrial fibrillation (0.78).
    • The model transferred to the Sleep Heart Health Study, which was left out of pretraining, and stayed competitive with dedicated staging tools such as U-Sleep and YASA.
    • Press coverage reported follow-up of up to 25 years and over 1,041 disease categories screened.

In the vocabulary of this book, SleepFM 2026 is a time-to-event model on top of a representation, not a generative simulator: it outputs hazards, not trajectories. It cannot say what the next night will look like, or how risk evolves if sleep apnea is treated. The C-indices are also associations from a sleep-clinic population referred for a reason, so the confounding caveats of Prediction Is Not Intervention apply in full.

Three 2026 sleep models push in different directions:

  • Carter & Tarassenko (2026) trained Hypnos with next-token prediction: each of eight PSG modalities is quantized into discrete tokens with residual vector quantization, and an autoregressive transformer predicts the next token of all modalities at once. Trained on over 20,000 overnight recordings, it matched supervised staging baselines with 100× less labelled data and beat a dedicated ECG model on atrial fibrillation detection. It is the first sleep model trained with a world-model-shaped objective, though the paper uses it for embeddings rather than for generating nights.
  • Shuai et al. (2026) built OSF from 166,500 hours of public sleep recordings, compared four families of self-supervised objectives, and found that channel-invariant features are essential when channels are missing at inference, and that scaling data, model size and source mixture all help.
  • Xu et al. (2026) aligned PSG with text in SleepLM (over 100,000 hours from more than 10,000 people), adding a caption decoder so sleep physiology can be described in language.

Leave-one-out contrastive learning. SleepFM 2024 encodes \(M\) modality groups (brain activity, ECG, respiratory) of the same 30-second-epoch window with separate encoders, giving \(z_i^{(m)}\) for window \(i\). Instead of contrasting every pair of modalities, the positive for modality \(m\) is the mean of the others,

\[ \bar z_i^{(-m)} = \frac{1}{M-1}\sum_{m' \ne m} z_i^{(m')}, \qquad \mathcal{L} = \frac{1}{M}\sum_{m=1}^{M} \mathrm{InfoNCE}\big(z^{(m)}, \bar z^{(-m)}\big). \]

Each encoder must agree with the consensus of the others, which reduces the number of loss terms from \(M(M-1)/2\) pairs to \(M\) and penalizes a modality that drifts away from all the rest.

Survival heads. SleepFM 2026 attaches, for each condition \(c\), a proportional-hazards head on the night embedding \(z\): \(\lambda_c(t \mid z) = \lambda_{0c}(t)\exp(\beta_c^\top z)\). The head is trained by maximizing the Cox partial likelihood over patients with events,

\[ \ell(\beta_c) = \sum_{i:\,\delta_i = 1} \Big[\beta_c^\top z_i - \log \sum_{j:\,T_j \ge T_i} \exp(\beta_c^\top z_j)\Big], \]

which ranks each patient with an event against everyone still at risk at that time and does not need the baseline hazard. Its natural metric is Harrell's concordance index, \(C = P(\hat r_i > \hat r_j \mid T_i < T_j, \delta_i = 1)\). Because \(z\) comes from one night, the model estimates \(p(T_c \mid z)\) and no path \(z_{t+1}, z_{t+2}, \dots\): it is a time-to-event model, and the hazard ratio \(\exp(\beta_c^\top \Delta z)\) is an association, not the effect of changing sleep.

Next-token objective on signals. Hypnos quantizes each modality with residual vector quantization: a vector \(u\) is approximated by \(\sum_{k=1}^{K} c^{(k)}_{j_k}\), where stage \(k\) picks the codeword nearest to the residual left by stages \(1, \dots, k-1\). The resulting integer codes \(j_{1:K}\) form tokens, and an autoregressive transformer minimizes \(-\sum_t \log p_\theta(j_{t} \mid j_{

Channel-agnostic encoders. Sleep labs record different channel sets \(S\), so an encoder that requires a fixed montage cannot transfer. SleepFM 2026 and OSF treat a recording as a set of channel embeddings \(\{u_c\}_{c \in S}\) pooled by an operation invariant to order and count, for example attention pooling \(z = \sum_{c \in S} \alpha_c u_c\) with \(\alpha = \mathrm{softmax}(w^\top u_c)\). Training with random channel dropout makes \(z\) approximately invariant to which channels are present, which is the property OSF found essential when channels are missing at inference.

Evaluation of frozen embeddings. SleepFM 2024's staging comparison fits a logistic regression \(p(y = k \mid z) = \mathrm{softmax}(W z + b)_k\) on frozen embeddings and reports macro AUROC, the mean of one-versus-rest AUROCs over sleep stages; 0.906 against 0.842 for an end-to-end CNN means the pretrained representation separates stages better than a network trained only on labels. Language alignment, as in SleepLM, adds a caption decoder trained by \(-\sum_k \log p(w_k \mid w_{

The script implements the two SleepFM ingredients. First, the leave-one-out contrastive loss over three modality embeddings, evaluated on aligned embeddings (three noisy views of the same nights) and on unrelated ones. Second, a linear Cox head trained by the partial likelihood on 3,000 synthetic frozen night embeddings with exponential event times and censoring up to 25 years, then scored by Harrell's C-index on 1,000 held-out nights against the true risk score and a random one.

"""Leave-one-out contrastive loss over PSG modalities, then a Cox survival head on frozen night embeddings."""
import torch, torch.nn.functional as F
torch.manual_seed(0)

def loo_contrastive(z, tau=0.1):
    """z: (M, B, d) embeddings of M modalities for B nights; each modality vs. mean of the others."""
    z = F.normalize(z, dim=-1); M = z.shape[0]; loss = 0
    for m in range(M):
        rest = F.normalize((z.sum(0) - z[m]) / (M - 1), dim=-1)
        loss += F.cross_entropy(z[m] @ rest.T / tau, torch.arange(z.shape[1]))
    return loss / M
shared = torch.randn(256, 32)
aligned = torch.stack([shared + 0.3 * torch.randn(256, 32) for _ in range(3)])   # brain, ECG, respiratory
print("LOO loss aligned %.2f  unrelated %.2f" % (loo_contrastive(aligned), loo_contrastive(torch.randn(3, 256, 32))))

def cox_loss(risk, time, event):
    """Negative Cox partial log-likelihood (Breslow, no ties)."""
    order = torch.argsort(time, descending=True); r, e = risk[order], event[order]
    return -((r - torch.logcumsumexp(r, 0)) * e).sum() / e.sum()
def c_index(risk, time, event):
    """Harrell's C: among comparable pairs (earlier time is an event), share where earlier has higher risk."""
    i, j = torch.meshgrid(torch.arange(len(time)), torch.arange(len(time)), indexing="ij")
    comp = (time[i] < time[j]) & (event[i] == 1)
    conc = (risk[i] > risk[j]).float() + 0.5 * (risk[i] == risk[j]).float()
    return (conc[comp].sum() / comp.sum()).item()

n, d = 4000, 32                                    # frozen one-night embeddings and follow-up
z = torch.randn(n, d); beta = torch.zeros(d); beta[:4] = torch.tensor([0.8, -0.6, 0.5, 0.4])
t_event = torch.distributions.Exponential(0.05 * torch.exp(z @ beta)).sample()
t_cens = torch.rand(n) * 25                        # administrative censoring up to 25 years
time, event = torch.minimum(t_event, t_cens), (t_event <= t_cens).float()
head = torch.nn.Linear(d, 1, bias=False); opt = torch.optim.Adam(head.parameters(), 0.05)
tr, te = slice(0, 3000), slice(3000, n)
for _ in range(300):
    loss = cox_loss(head(z[tr]).squeeze(-1), time[tr], event[tr]); opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
    print("event rate %.2f  test C-index %.3f  oracle %.3f  random %.3f" % (event.mean(),
          c_index(head(z[te]).squeeze(-1), time[te], event[te]),
          c_index(z[te] @ beta, time[te], event[te]), c_index(torch.randn(n - 3000), time[te], event[te])))

Output:

LOO loss aligned 0.10  unrelated 7.21
event rate 0.46  test C-index 0.754  oracle 0.754  random 0.500

The loss separates aligned from unrelated modalities by two orders of magnitude, which is the signal that trains the encoders. The Cox head matches the oracle C-index of 0.754, close to the 0.75 threshold SleepFM 2026 uses to count a condition as well predicted. The example also shows the ceiling: once the head has recovered the true coefficients, C-index cannot improve further, because the remaining randomness is in the event times themselves. Nothing in the code produces a future night.

Deployment shape. SleepFM-style systems run once per study: a PSG recording is staged, encoded and scored, and the risk report accompanies the clinical sleep report. Compute is negligible next to the recording; the engineering problems are channel heterogeneity and data governance. Sleep labs record different montages, sampling rates and reference electrodes, which is why SleepFM 2026 uses an encoder that accepts varying channel sets and why OSF finds channel-invariant features essential when channels are missing at inference. Hospital PSG data sit behind the same governance as EHRs, so multi-site training needs data-use agreements or federated set-ups.

What the numbers support. A C-index of 0.84 for mortality or 0.85 for dementia from one night is strong discrimination in a sleep-clinic population that was referred for a reason. It does not establish calibration in the general population, absolute risk at a clinically useful horizon, or benefit from acting on the score. Before such a model informs care, a deployment would need calibration curves at fixed horizons in the target population, net-benefit or decision-curve analysis, and transport tests such as the held-out Sleep Heart Health Study evaluation, repeated on the deploying site's own patients.

Failure modes. Montage or scoring-software changes shift embeddings without any change in the patient. Referral patterns change the base rate. The 1,000+ conditions screened invite multiple-comparison optimism, so the 130 conditions above 0.75 should be read with confidence intervals. And the model cannot answer whether treating sleep apnea changes the forecast risk, because it has no transition and no action input; Hypnos-style next-token models over quantized signals are the route toward one, but as of 2026 they are evaluated only as embedders.

The 2026 variants in practice. Hypnos's label efficiency (matching supervised staging with 100× less labelled data) matters most for sites that cannot afford large scored datasets, since expert scoring of a night takes far longer than recording it. OSF's finding that scale, model size and source mixture all help argues for pooling public cohorts rather than single-site training. SleepLM-style caption decoders invite automatic report drafting, which needs the same checks as any clinical text generation: every statement should be traceable to a measured quantity, and fluent but unsupported descriptions should be counted, not tolerated.

Wearable Models That Look Forward

Wearable foundation models learn from continuous, free-living data, which gives them something sleep-lab models lack: long sequences of the same person, day after day. The early models discarded that temporal structure; the 2025–2026 ones are starting to model it.

  • Contrastive embedders. Abbaspourazad et al. (2023) at Apple pretrained PPG and ECG encoders on about 20 million PPG segments from 141,207 Apple Heart and Movement Study participants, using pairs from the same participant as positives (presented at ICLR 2024). Erturk et al. (2025) moved up a level of abstraction: their Wearable Behavior Model encodes a week of 27 hourly HealthKit metrics (steps, resting heart rate, HRV, sleep, gait) from 161,855 people, and the authors state plainly that it is not designed to forecast. Open PPG models follow the same pattern: PaPaGei (Pillai et al. 2024; 57,000 hours of public clinical PPG) and Pulse-PPG (Saha, Xu et al. 2025; about 55,000 hours of field PPG from 120 participants), which outperformed PaPaGei on 10 of 11 tasks.
  • Masked models that extrapolate. Narayanswamy et al. (2025) trained LSM (ICLR 2025, discussed in Physiological Dynamics) to impute, interpolate and extrapolate. Xu, Narayanswamy et al. (2025) made LSM-2 learn from the data's own gaps: its adaptive and inherited masking treats real missingness and artificial masks with one learnable mask token, so 40 million hours from 60,440 people need no imputation before training. Narayanswamy, Xu et al. (2026) scaled this recipe into SensorFM, pretrained on over a trillion minutes from five million participants, reporting a 39.6% improvement over the best baseline on temporal extrapolation and using infilling to fix daily step and sleep totals when data are missing.
  • Language-aligned models. Zhang et al. (2025) trained SensorLM (NeurIPS 2025) on about 59.7 million hours from over 103,000 people, with contrastive and caption-generation objectives, so a model can describe a day in words.
  • Generative forecasters. Chen et al. (2026) pretrained SOTER, a generative model with a neural controlled differential equation decoder that predicts and imputes at arbitrary timestamps, on 226 billion time points; it had the best forecasting error on most of six held-out datasets. Luo et al. (2026) built NormWear-2, which puts signals and intervention variables (for example dialysis or insulin settings) in one latent space and forecasts under them, across 8,026 subjects.
  • Action-conditioned world models. Lee & Heydari (2026) proposed SensorWM in a NeurIPS 2026 workshop: it predicts transitions of a compact health state given behaviors, rolls out over multiple weeks, beats persistence and time-series baselines, and simulates alternative behavior paths. Zhang et al. (2026) model EHR and wearable data jointly as one continuous-time latent process and report the largest gains at long horizons.

The last two bullets are where wearable models become world models in the sense of this book. The evidence is early: workshop papers and preprints, behavior "actions" that are observational rather than randomized, and forecasting metrics rather than decision outcomes. Behavior-conditioned rollouts inherit the confounding problem of treatment tokens: people who start exercising differ from those who do not.

Inherited masking. Free-living wearable data have real gaps: let \(O \subseteq \{1, \dots, T\}\) be the minutes actually observed. LSM-2 samples an artificial mask \(\mathcal{A}\), shows the model only \(O \setminus \mathcal{A}\), replaces every hidden position (whether hidden by \(\mathcal{A}\) or missing from \(O\)) with the same learnable token, and scores reconstruction only where the truth is known:

\[ \mathcal{L} = \frac{1}{|\mathcal{A} \cap O|}\sum_{t \in \mathcal{A} \cap O} \lVert \hat x_t - x_t \rVert^2 . \]

An impute-first pipeline instead fills \(O^c\) with a value \(\tilde x\) and scores all of \(\mathcal{A}\), so a fraction \(|\mathcal{A} \cap O^c|/|\mathcal{A}|\) of the training signal teaches the model to reproduce the imputer. When an extrapolation mask covers the end of the window, the same loss defines a short-horizon forecaster \(p(x_{T-k+1:T} \mid x_{1:T-k})\).

Continuous-time decoders. SOTER decodes with a neural controlled differential equation (Kidger et al., 2020): a hidden state follows \(dh(t) = g_\theta(h(t))\, dX(t)\), where \(X\) is a continuous interpolation of the observed path, so predictions can be read out at any timestamp \(t\) without resampling to a grid. Irregular sampling and forecasting at arbitrary horizons then come from the same model.

Action-conditioned transitions. SensorWM learns a compact state \(s_t\) and a transition \(p_\theta(s_{t+1} \mid s_t, a_t)\) where \(a_t\) is a behavior (exercise, sleep timing). A rollout samples \(s_{t+1:t+H}\) given a planned sequence \(a_{t:t+H-1}\). Training on observational data estimates \(p(s_{t+1} \mid s_t, a_t)\) as behaviors were chosen, not \(p(s_{t+1} \mid s_t, \mathrm{do}(a_t))\); the two agree only if \(s_t\) contains every common cause of behavior and outcome.

Skill against persistence. Forecasts are scored by \(\mathrm{SS} = 1 - \mathrm{MAE}_{\text{model}}/\mathrm{MAE}_{\text{persist}}\), where persistence predicts \(\hat x_{t+h} = x_t\). For a stationary AR(1) deviation with coefficient \(\phi\), the optimal one-step forecast has \(\mathrm{SS} = 1 - \sqrt{(1+\phi)/2}\): 0.29 for white noise and only 0.05 for \(\phi = 0.8\). Slowly varying physiology is hard to beat with persistence, which is why it is the baseline that matters.

Other objectives. SensorLM combines a contrastive term between a sensor embedding and a caption embedding with a captioning term \(-\sum_k \log p(w_k \mid w_{Zhang et al. (2026) treat both sources as observations of one continuous-time latent process. All three are conditional generators; whether their conditioning variables can be manipulated in the causal sense depends on how those variables were assigned in training data.

The script compares two ways of training a small masked autoencoder on one-hour windows of synthetic minute-level heart rate, 60% of which lose a 20-minute block to real missingness. The impute-first variant zero-fills the gaps before training and scores reconstruction on every artificially masked minute. The inherited variant, after LSM-2, hides artificial masks and real gaps behind one learnable token, passes the visibility pattern as input, and scores only minutes that were hidden but actually observed. Both are evaluated on held-out windows, on hidden minutes whose truth is known.

"""LSM-2-style inherited masking: real gaps and artificial masks share one mask token; loss only where observed."""
import torch, math
torch.manual_seed(0)
N, T = 6000, 60                                       # one-hour windows of minute-level heart rate
t = torch.arange(T).float()
level = 70 + 8 * torch.randn(N, 1); phase = 2 * math.pi * torch.rand(N, 1)
x = level + 6 * torch.sin(2 * math.pi * t / 30 + phase) + torch.randn(N, T)
real_obs = torch.ones(N, T, dtype=torch.bool)         # real missingness: 60% of windows lose a 20-minute block
for i in torch.nonzero(torch.rand(N) < 0.6).squeeze(1):
    s = torch.randint(0, T - 20, (1,)).item(); real_obs[i, s:s+20] = False
mu, sd = 70.0, 10.0; xn = (x - mu) / sd

class MAE(torch.nn.Module):
    def __init__(s):
        super().__init__(); s.tok = torch.nn.Parameter(torch.zeros(1))
        s.net = torch.nn.Sequential(torch.nn.Linear(2 * T, 256), torch.nn.GELU(), torch.nn.Linear(256, T))
    def forward(s, v, visible):
        inp = torch.where(visible, v, s.tok.expand_as(v))       # one learnable token for every hidden value
        return s.net(torch.cat([inp, visible.float()], 1))

def train(inherited):
    model = MAE(); opt = torch.optim.Adam(model.parameters(), 2e-3)
    for step in range(1500):
        i = torch.randint(0, 5000, (256,)); v, obs = xn[i], real_obs[i]
        art = torch.rand(256, T) < 0.3                           # artificial mask
        if inherited:
            visible = obs & ~art; target_pos = art & obs           # loss only on hidden-but-observed values
            v_in = v
        else:
            v_in = torch.where(obs, v, torch.zeros_like(v))        # gaps zero-filled before training (impute-first)
            visible = ~art; target_pos = art                        # zero-filled minutes count as data
        pred = model(v_in, visible); tgt = v_in
        loss = ((pred - tgt) ** 2)[target_pos].mean(); opt.zero_grad(); loss.backward(); opt.step()
    return model

torch.manual_seed(1); te = torch.arange(5000, N)
art_te = torch.rand(len(te), T) < 0.3; obs_te = real_obs[te]
for name, inh in [("impute-first (zero fill)", False), ("inherited masking", True)]:
    torch.manual_seed(2); m = train(inh)
    with torch.no_grad():
        v_in = xn[te] if inh else torch.where(obs_te, xn[te], torch.zeros_like(xn[te]))
        pred = m(v_in, (obs_te & ~art_te) if inh else ~art_te) * sd + mu
    pos = art_te & obs_te
    print(f"{name:26s} MAE on hidden observed minutes: {(pred - x[te]).abs()[pos].mean():.2f} bpm")

Output (about three minutes on two CPU cores):

impute-first (zero fill)   MAE on hidden observed minutes: 1.26 bpm
inherited masking          MAE on hidden observed minutes: 0.93 bpm

Inherited masking reduces reconstruction error by about a quarter with the same network and budget. The impute-first model spends capacity reproducing zeros that were never measurements and sees fabricated values as context. At the scale of LSM-2 (40 million hours) the same logic removes an imputation stage from the pipeline and keeps real gaps visible to the model as a pattern, which matters downstream because missingness itself is informative.

Where the computation runs. Consumer wearables reduce raw signals to minute-level features on the device (heart rate, step counts, sleep stage estimates) to save battery and bandwidth, so foundation models such as LSM-2, WBM and SensorFM are trained on those features, not on raw PPG. The feature extractor is part of the model: a firmware update that changes the heart-rate algorithm changes the input distribution. Training runs on research-consented subsets of device fleets (tens of thousands to millions of people), and inference for population studies is batch, while personal features (readiness scores, anomaly notifications) run nightly per user.

Evaluating forward-looking models. For SOTER, NormWear-2 or SensorWM the useful evaluation is forecast skill against persistence and seasonal-naive baselines at several horizons, interval calibration, and performance on held-out people and later periods. A model that does not beat "tomorrow equals today" on slowly varying signals such as resting heart rate has not learned dynamics, however low its absolute error. For action-conditioned models, the behaviors are observational: people choose to exercise, and those who do differ from those who do not. Validation therefore needs either randomized behavior data (micro-randomized trials in mobile health are one source) or negative-control checks that the model does not attribute effects to behaviors that cannot plausibly cause them.

Failure modes. Wear time is not random: devices come off during illness, travel and hospital stays, so a model that silently imputes those periods learns a healthier population than the one it serves. Population drift is large, since early adopters differ from later users. Language-aligned models such as SensorLM can produce fluent descriptions of a day that are not supported by the data. And a rollout of behavior paths presented to users as "what happens if" advice turns an observational association into an implied causal claim; the 2026 evidence (workshop papers, preprints, forecasting metrics) does not support that use.

Product uses that need less than a world model. SensorFM's use of infilling to correct daily step and sleep totals on days with missing data is a sound application of the imputation rung: the output is a better estimate of a quantity that occurred, checkable against days with complete data. It needs no claim about the future and no causal assumption, which makes it the safest first deployment of a masked wearable model.

Ballistocardiography and BCG Foundation Models

Ballistocardiography measures the tiny recoil of the body each time the heart ejects blood, so a sensor under a mattress or in a chair can track heart rate, heart-rate variability, breathing and movement every night without anything being worn. Reviews by Inan et al. (2015) and Sadek (2018) describe the signal: each beat produces a sequence of waves labelled H, I, J and K, of which the large J wave is used for beat detection, while breathing adds a slow oscillation and movement adds large bursts.

Synthetic bed-sensor signal decomposed into respiration and cardiac components, with a motion artifact.
Fig. What a bed sensor records. The raw signal (top) mixes a slow respiratory oscillation (middle) with a small cardiac recoil whose J peaks (dots, bottom) give beat-to-beat intervals. A body movement (shaded) swamps both, and those seconds are usually discarded by a quality filter. Illustrative: synthetic waveforms, not a real recording; amplitudes are not to scale.

Devices. Sensors include piezoelectric films, electromechanical film, load cells under bed legs, hydraulic tubes and air bladders (Sadek 2018). Consumer examples:

  • The Withings Sleep Analyzer is a pneumatic under-mattress pad. Edouard et al. (2021) validated it against lab PSG in adults suspected of sleep apnea and reported 88.0% sensitivity and 88.6% specificity for moderate-to-severe apnea (AHI ≥ 15).
  • Eight Sleep reports, in a company blog post, heart-rate error under 1 bpm and RMSSD mean absolute error of 5.7 ms against chest ECG over 474 nights from 163 people; this is not peer-reviewed.

Why BCG is hard. The cardiac recoil is weak and the sensor sees everything else too. Sadek (2018) lists the recurring problems: motion artifacts that drown the signal, waveform shape that changes with posture and body position, morphology that differs between and within people, cardiac, respiratory and movement components that must be separated, and labels that require synchronized ECG or PSG and must be collected again when the protocol changes. Even modern beat detectors show the gap: Yi et al. (2024) found a transformer mapping BCG to ECG did well across shuffled segments but much worse on unseen older adults, and Cai et al. (2025) combined template matching and deep learning with confidence scores so low-quality beats are dropped rather than guessed. Scarce labels, large unlabeled volumes and strong person-to-person variation are exactly the conditions where self-supervised pretraining should pay off.

What exists. Published BCG foundation-model work is thin. I found one model that calls itself a BCG foundation model, two transfer-learning systems and smaller self-supervised studies:

  • Kjaer et al. (2026) pretrained BCG-FM on 2.75 million hours of nightly recordings from 145,985 people, captured by a piezoelectric strip under the bed surface of the Eight Sleep Pod (full text).
    • The recipe mirrors Apple's PPG model: a small 1D EfficientNet over 60-second windows split into breathing and heart channels, InfoNCE with windows from the same person on different nights (up to 90 days apart) as positives, and no augmentations, which the authors found hurt.
    • Frozen embeddings estimated age with a 3.26-year mean absolute error, and 500 labelled participants with pretraining beat a fully supervised model trained on 3,372.
    • All disease results are cross-sectional and self-reported (mean AUROC 0.684 over 15 conditions vs. 0.637 for demographics alone); atrial fibrillation detection reached 0.954 AUROC in one small external cohort of 85 people. The paper does not forecast.
  • BCGNet (2025), a medRxiv preprint, pretrains on about 580,000 hours of PSG-derived heart-rate and respiration signals, then fine-tunes on 15,081 hours of under-pillow BCG with PSG labels; four-class staging reached Cohen's κ of 0.70–0.77 across three hospital cohorts. This is supervised transfer from PSG, not self-supervision on BCG.
  • Li et al. (2024) trained SleepNetZero only on heartbeat, breathing and movement components extracted from public PSG, then applied it zero-shot to 265 real BCG nights (five-class accuracy about 0.70, κ about 0.59).
  • Wu, Qiu & Shen (2024) applied self-supervised learning to BCG-based HRV monitoring in Biomedical Signal Processing and Control; I could only access the record, not the methods.

The pattern is that BCG borrows from neighbors: PSG-derived cardiorespiratory signals for labels, PPG/ECG recipes for pretraining. I found no published generative or forecasting BCG model. The closest generative work in cardiomechanics is Nikbakht et al. (2023), who generated synthetic seismocardiogram beats with a transformer for data augmentation.

Signal model. A bed sensor's output can be written as

\[ y(t) = r(t) + \alpha\, c(t) + m(t) + \varepsilon(t), \qquad c(t) = \sum_k g\big(t - t_k;\ \text{posture}\big), \]

a respiratory component \(r\) at roughly 0.1–0.5 Hz, a cardiac component built from one H-I-J-K complex \(g\) per beat at times \(t_k\) with small gain \(\alpha\), movement bursts \(m\) and sensor noise \(\varepsilon\). The template \(g\) depends on posture and on the person, which is the formal statement of BCG's morphology problem: the same heart produces different waveforms when the sleeper turns over.

Separation and beat detection. Because the components occupy different bands, a first separation uses band-pass filters (about 0.1–0.7 Hz for breathing, 1–15 Hz for the cardiac complex). Beats are located as J peaks \(t_{J,k}\) of the cardiac band, either by peak detection with a refractory period or by correlation with a personal template. Inter-beat intervals are \(\mathrm{IBI}_k = t_{J,k+1} - t_{J,k}\); heart rate is \(60/\overline{\mathrm{IBI}}\) and the short-term variability index

\[ \mathrm{RMSSD} = \sqrt{\frac{1}{K-1}\sum_{k=1}^{K-1}(\mathrm{IBI}_{k+1} - \mathrm{IBI}_k)^2}. \]

RMSSD is computed only over consecutive valid beats; differencing across a discarded segment would join intervals that were never adjacent. Respiratory rate is the dominant frequency of \(r\).

Quality. A quality mask \(q(t) \in \{0,1\}\) discards seconds in which the cardiac-band envelope exceeds a multiple of its median, the signature of movement. The night's quality score is the retained fraction \(\bar q\), and a beat-level confidence, as in Cai et al. (2025), lets a detector drop rather than guess.

Why self-supervision fits. BCG-FM's objective is InfoNCE with windows from the same person on different nights (up to 90 days apart) as positives. Its invariances are therefore to posture, night-to-night state and noise, and its embedding encodes stable traits: hence the strong age estimate (3.26-year MAE) and cross-sectional disease associations. Label efficiency follows from the same argument: if the embedding already separates people by physiology, a linear probe needs few labels, which is the observation that 500 labelled participants with pretraining beat 3,372 without.

Transfer instead of self-supervision. BCGNet and SleepNetZero solve the label problem by changing the input space rather than the objective. Both reduce PSG to the components a bed sensor can see (heart-rate, respiration and movement series \(\tilde x = \pi(\text{PSG})\)), train a staging model \(p_\theta(y \mid \tilde x)\) on large PSG archives with expert labels, and apply it to BCG-derived series \(\pi'(\text{BCG})\). The method works to the extent that \(\pi'(\text{BCG})\) and \(\pi(\text{PSG})\) have similar distributions; BCGNet narrows the remaining gap by fine-tuning on 15,081 hours of paired BCG and PSG, whereas SleepNetZero applies the PSG-trained model zero-shot.

Agreement metrics. Staging agreement is reported as Cohen's \(\kappa = (p_o - p_e)/(1 - p_e)\), where \(p_o\) is observed agreement and \(p_e\) the agreement expected from label frequencies alone; \(\kappa\) of 0.70–0.77 is substantial agreement and close to inter-scorer agreement for four-class staging. Apnea screening at AHI \(\ge 15\) is a binary decision scored by sensitivity \(P(\hat y = 1 \mid y = 1)\) and specificity \(P(\hat y = 0 \mid y = 0)\), here 88.0% and 88.6% against PSG.

The script builds five minutes of a synthetic bed-sensor signal at 100 Hz: a breathing oscillation at 15 breaths per minute, a much smaller H-I-J-K cardiac complex at about 60 beats per minute with respiratory-linked and random variability, a 12-second movement burst and noise. It separates breathing and cardiac bands with zero-phase Butterworth filters, marks movement seconds with an envelope-based quality mask, detects J peaks, and estimates heart rate, RMSSD and respiratory rate against the known truth.

"""Synthetic bed-sensor (BCG) signal: separate breathing and cardiac parts, detect J peaks, drop motion, get HR and RMSSD."""
import numpy as np
from scipy.signal import butter, sosfiltfilt, find_peaks
rng = np.random.default_rng(0); fs = 100; T = 300                 # 5 minutes at 100 Hz
t = np.arange(T * fs) / fs
ibi = 1.0 + 0.04 * np.sin(2 * np.pi * 0.25 * np.arange(400)) + rng.normal(0, 0.025, 400)  # ~60 bpm with HRV
beats = np.cumsum(ibi); beats = beats[beats < T - 1]
tmpl_t = np.arange(-0.15, 0.35, 1 / fs)                               # H-I-J-K complex as a sum of Gaussians
tmpl = sum(a * np.exp(-((tmpl_t - c) / 0.025) ** 2) for a, c in [(0.3, -0.05), (-0.5, 0.05), (1.0, 0.12), (-0.6, 0.2)])
cardiac = np.zeros_like(t)
for b in beats:
    k = int(b * fs) + np.arange(len(tmpl)) - 15
    ok = (k >= 0) & (k < len(t)); cardiac[k[ok]] += tmpl[ok]
resp = 8 * np.sin(2 * np.pi * 0.25 * t)                                # 15 breaths/min, much larger than the beat
motion = np.where((t > 140) & (t < 152), 60 * rng.normal(size=len(t)), 0)
y = resp + 0.5 * cardiac + motion + 0.05 * rng.normal(size=len(t))
bp = lambda lo, hi, s: sosfiltfilt(butter(4, [lo, hi], "band", fs=fs, output="sos"), s)
r, c = bp(0.1, 0.7, y), bp(2.0, 15.0, y)
env = np.convolve(np.abs(c), np.ones(fs) / fs, "same")                 # 1-s envelope of the cardiac band
good = env < 3 * np.median(env)                                        # quality mask: drop motion seconds
pk, _ = find_peaks(np.where(good, c, 0), distance=int(0.5 * fs), height=0.5 * np.percentile(c[good], 99))
pt = pk / fs; d = np.diff(pt); keep = good[pk[:-1]] & good[pk[1:]] & (d < 1.6)
est_ibi = d[keep]
true_d = np.diff(beats); true_ibi = true_d[(beats[:-1] < 139) | (beats[1:] > 153)]
rmssd = lambda v: 1000 * np.sqrt(np.mean(np.diff(v) ** 2))
f = np.fft.rfftfreq(len(r), 1 / fs); rr = 60 * f[np.argmax(np.abs(np.fft.rfft(r * good)))]
print(f"quality fraction {good.mean():.3f}  beats detected {len(pk)} (true {len(beats)})")
print(f"HR  est {60 / est_ibi.mean():.1f} bpm  true {60 / true_ibi.mean():.1f} bpm")
print(f"RMSSD est {rmssd(est_ibi):.0f} ms  true {rmssd(true_ibi):.0f} ms   resp rate est {rr:.1f}/min (true 15.0)")

Output:

quality fraction 0.955  beats detected 285 (true 299)
HR  est 60.0 bpm  true 60.0 bpm
RMSSD est 53 ms  true 52 ms   resp rate est 15.0/min (true 15.0)

The quality mask removes about 4.5% of the recording, almost exactly the movement burst, and the detector finds 285 of 299 beats, the missing ones lying inside the discarded seconds. On the clean remainder the estimates match the truth. Real recordings are harder in every respect the signal model names: the template changes with posture and between people, cardiac and respiratory bands leak into each other at low heart rates, and movement is frequent and partial rather than one clean burst. That gap between a synthetic check and field data is the reason BCG work relies on synchronized ECG or PSG for validation.

Devices and data paths. Commercial bed sensors (pneumatic pads such as the Withings Sleep Analyzer, piezoelectric strips such as the one in the Eight Sleep Pod, load cells and under-pillow devices) sample at tens to hundreds of hertz and upload either raw signals or derived summaries. Signal processing, quality filtering and beat detection usually run in the vendor's cloud, so the vendor controls the algorithm version that produces every number a downstream model sees. BCG-FM was trained on 2.75 million hours from one vendor's fleet; that scale exists only inside companies, which is why published BCG foundation-model work is thin and concentrated.

Validation. The validation standard is simultaneous reference recording: chest ECG for heart rate and RMSSD, lab PSG for sleep staging and apnea. Peer-reviewed validations such as Edouard et al.'s apnea study report sensitivity and specificity against PSG at a stated threshold; vendor blog posts, such as Eight Sleep's heart-rate and RMSSD figures, are useful indications but are not peer-reviewed. Generalization needs to be tested across people, not across shuffled segments, as Yi et al. showed: a BCG-to-ECG model that did well on shuffled segments did much worse on unseen older adults.

Failure modes and monitoring. The recurring problems are bed partners and pets (two hearts on one sensor), mattress and frame changes that alter coupling, posture-dependent waveforms, and firmware updates that change the quality filter. Each shows up as a shift in the share of low-quality time or in summary distributions rather than as an error message, so production pipelines track the quality fraction and summary statistics per device model and firmware version and treat abrupt changes as device events before physiological ones. Clinical claims (atrial fibrillation, apnea) need regulatory clearance for the specific device and algorithm version, which constrains how quickly a foundation-model upgrade can reach users.

Readiness for world modeling. Bed sensors offer what other modalities lack, years of nightly data with near-perfect adherence, but the published models are cross-sectional encoders and supervised stagers. Moving to a world model requires long per-person sequences linked to clinical events, which BCG-FM's authors list as future work, and validation of nightly summaries against reference measurements over months rather than single nights. A realistic sequence is to establish that summaries are stable within a person when nothing changes, then that deviations are associated with known events, and only then to train and evaluate transition models over nights.

A BCG World Model: Design Sketch

This subsection is a design sketch, not a description of published work. Bed sensors are unusually well suited to world modeling because they produce one long, regular, effortless sequence per person: every night, for years, with no adherence problem. A BCG world model would model the sequence of nights rather than the waveform within a night.

  1. Per-night state. Encode each night with a frozen BCG encoder (BCG-FM-like) into an embedding plus interpretable summaries: sleep heart rate, RMSSD, respiratory rate, time in bed, movement index and a signal-quality fraction.
  2. Personal baselines. Express summaries as deviations from the person's own trailing 28-night baseline, which absorbs much of the inter-person variability that makes raw BCG hard to compare.
  3. Transition model. Train an autoregressive model over nights, with optional context such as bed temperature settings, travel or illness flags, to predict the next night's state; uncertainty matters more than point accuracy.
  4. Event coupling. Join nights to clinical events (diagnoses, medications, admissions) so the same model predicts both, as in the next subsection.
  5. Evaluation. Forecast skill against a persistence baseline (tomorrow equals today), calibration of predicted deviations, and lead time for events such as an atrial fibrillation diagnosis or a heart-failure admission.

The obvious use is early warning: a model that knows what a person's next night should look like can flag nights that do not fit. Whether nightly BCG adds lead time over existing wearables for any clinical event is untested, and BCG-FM's authors themselves list longer per-person sequences as future work.

Personal baselines. For a nightly summary \(x_t\) (sleeping heart rate, say), the deviation from a trailing \(w\)-night mean is \(d_t = x_t - b_t\) with \(b_t = \frac{1}{w}\sum_{s=t-w}^{t-1} x_s\). If a person's nights fluctuate around a personal level \(\mu_i\) with independent noise of variance \(\sigma^2\), then \(\mathbb{E}[d_t] = 0\) and \(\mathrm{Var}(d_t) = \sigma^2(1 + 1/w)\); between-person differences in \(\mu_i\) cancel. With \(w = 28\) the baseline adds only about 3.5% to the variance.

Transition model. The simplest transition over nights is an AR(1) on deviations with Gaussian noise, \(d_{t+1} = \phi\, d_t + \eta_t\), \(\eta_t \sim \mathcal{N}(0, \sigma_\eta^2)\), fitted by least squares or by minimizing the Gaussian negative log-likelihood \(\tfrac12 \log 2\pi\sigma_\eta^2 + (d_{t+1} - \phi d_t)^2/2\sigma_\eta^2\). A richer model replaces \(\phi d_t\) with a sequence model over night embeddings and context \(c_t\) (bed temperature, travel, illness flags) and predicts a distribution, not a point. The forecast is \(\hat x_{t+1} = b_t + \phi\, d_t\) with an 80% interval \(\pm 1.28\, \sigma_\eta\).

Evaluation. Against persistence, the optimal one-step forecast of a stationary AR(1) has skill \(1 - \sqrt{(1+\phi)/2}\), so for \(\phi = 0.5\) the ceiling is about 0.13. Interval calibration is checked by coverage: the fraction of nights inside the 80% interval should be close to 0.80. For early warning, a flag is raised when a standardized deviation \(z_t = d_t/\mathrm{sd}(d)\) exceeds a threshold \(k\) on several consecutive nights; the trade-off between sensitivity and false alarms is set by \(k\) and the run length, and lead time is the number of nights between the first flag and the clinical event.

The script simulates 200 nights of sleeping heart rate for 300 people whose personal baselines differ by several beats per minute, with AR(1) night-to-night deviations. Sixty of them drift upward by up to 6 bpm over the 10 nights before an admission on night 180. It fits an AR(1) on deviations from a trailing 28-night baseline, scores next-night forecasts against persistence and checks 80% interval coverage on nights 120–164, then runs a three-nights-in-a-row deviation alarm at two thresholds.

"""Next-night forecasting over a personal baseline: skill vs. persistence, interval coverage, early-warning lead time."""
import numpy as np
rng = np.random.default_rng(0)
P, T, W = 300, 200, 28
mu = rng.normal(58, 6, (P, 1))                         # personal resting HR baselines differ a lot
dev = np.zeros((P, T))
for t in range(1, T): dev[:, t] = 0.5 * dev[:, t-1] + rng.normal(0, 1.5, P)
hr = mu + dev
sick = np.arange(P) < 60; onset = 170                 # 60 people: HR drifts up 10 nights before an admission at night 180
hr[sick, onset:180] += np.linspace(0.6, 6, 10)

def baseline(x, t): return x[:, t-W:t].mean(1)        # trailing 28-night mean, past only
tr = np.arange(W, 120)                                  # fit AR(1) on deviations from baseline, nights 28-119
d_now = np.stack([hr[:, t] - baseline(hr, t) for t in tr[:-1]], 1)
d_next = np.stack([hr[:, t+1] - baseline(hr, t) for t in tr[:-1]], 1)
phi = (d_now * d_next).sum() / (d_now ** 2).sum(); sig = (d_next - phi * d_now).std()
te = np.arange(120, 165)                                # evaluation nights before any drift
pred = np.stack([baseline(hr, t) + phi * (hr[:, t] - baseline(hr, t)) for t in te], 1)
true, pers = hr[:, te + 1], hr[:, te]
skill = 1 - np.abs(true - pred).mean() / np.abs(true - pers).mean()
cover = (np.abs(true - pred) < 1.2816 * sig).mean()
print(f"phi {phi:.2f}  sigma {sig:.2f} bpm  skill vs persistence {skill:.2f}  80% interval coverage {cover:.2f}")
sd_dev = d_now.std()                                   # spread of a night's deviation from its own baseline
z = np.stack([(hr[:, t+1] - baseline(hr, t)) / sd_dev for t in range(120, 179)], 1)
for thr in (1.5, 2.0):
    hi = z > thr; flag = hi[:, 2:] & hi[:, 1:-1] & hi[:, :-2]          # three surprising nights in a row
    first = np.where(flag.any(1), flag.argmax(1) + 123, -1)            # night of the third surprising night
    lead = 180 - first[sick & (first >= onset)]
    print(f"threshold {thr}: sensitivity {np.mean(first[sick] >= onset):.2f}  "
          f"healthy people alarmed {np.mean(first[~sick] >= 0):.2f}  median lead {np.median(lead):.0f} nights")

Output:

phi 0.53  sigma 1.52 bpm  skill vs persistence 0.12  80% interval coverage 0.80
threshold 1.5: sensitivity 0.60  healthy people alarmed 0.25  median lead 4 nights
threshold 2.0: sensitivity 0.63  healthy people alarmed 0.04  median lead 3 nights

The fitted coefficient of 0.53 is close to the true 0.5, the skill of 0.12 sits just below the analytic ceiling of 0.13 for that coefficient, and the 80% interval covers 80% of nights. The alarm shows the operating trade-off: at threshold 1.5, a quarter of healthy people are alarmed at least once in two months, and some early false alarms pre-empt the true one; at 2.0 the false-alarm share falls to 4% with similar sensitivity and three to four nights of lead time. These are properties of a synthetic drift; whether real BCG nights carry such a drift before any clinical event is the open question.

Building it. A nightly BCG world model is cheap to run: one record per person per night, a small sequence model, and a forecast and anomaly score computed after the person wakes. The cost lies in data plumbing and validation. Per-night summaries and embeddings must be versioned by firmware and encoder; baselines must use past nights only; and the event coupling step requires a linked clinical record, which bed-sensor vendors rarely hold. Partnerships with health systems or consented research cohorts are the usual route.

Evaluating it. The decisive numbers are forecast skill against persistence on held-out people and later months, interval coverage, and, for early warning, sensitivity, false alarms per person-year and median lead time at a fixed operating point. Lead time is compared with what existing wearables and routine care already provide; a model that flags heart-failure decompensation one night before admission adds little if weight gain or symptoms would have flagged it three days earlier.

Failure modes. Alert fatigue is the first: a threshold that catches most events in simulation can alarm a large share of healthy users over a few months, and users then ignore or disable alerts. Non-physiological shifts (a new mattress, a partner, a firmware change) produce runs of deviations that look like deterioration. Missing nights cluster around illness, so a model that drops them loses the signal it was built for. And any claim that the system improves outcomes requires a prospective study; as of 2026 none has tested whether nightly BCG adds lead time over existing wearables for any clinical event.

Plugging Sensors into a Health World Model

A GPT-style health world model can take sensor data in two ways: as discrete summary tokens that the model both reads and generates, or as embedding soft tokens projected into its input space. The first keeps the model a closed generative simulator; the second carries more information but cannot be rolled forward without an extra head. The diagram extends the reference architecture with a sensor branch.

Sensor branch for a GPT-style health world model: sources, frozen encoders, nightly summary, two tokenization routes, and the timeline model. Wearable minute-level HR, steps, sleep Bed sensor (BCG) every night, no wear Polysomnography occasional clinic night Frozen encoder LSM-2 / SensorFM-like Frozen encoder BCG-FM-like Frozen encoder SleepFM-like Per-night summary embedding z · HR, HRV, respiratory rate, sleep time · deviation from personal baseline · quality flag Route A: summary tokens NIGHT · HRV_Q3 · TST_Q7 readable and generatable Route B: soft token linear projection of z readable, not generatable EHR events codes, labs, time gaps ETHOS vocabulary GPT-style timeline model one interleaved sequence of nights and clinical events · roll out futures and count outcomes
Fig. A sensor branch for a GPT-style health world model. Each source passes through a frozen encoder into one record per night; Route A turns it into discrete tokens the timeline model can also generate, Route B feeds the embedding directly. EHR events enter with the usual ETHOS vocabulary. Original diagram.

Route A follows the ETHOS vocabulary exactly: a night becomes a marker token followed by decile tokens for a few summaries, preceded by a time-gap token like any other event. Because every token is in the vocabulary, a rollout generates future nights alongside future diagnoses, so the model can be asked "what do the next 30 nights look like" as well as "how likely is heart failure in a year". Embeddings can join this route if they are vector-quantized into a codebook of "night types", the same trick Hypnos uses on raw signals. Route B passes the embedding through a learned projection, like an image patch in a multimodal LLM. It keeps more information, but the model can only condition on it, so simulated futures contain no sensor data unless a separate regression head predicts the next embedding.

Three practical issues decide whether either route helps. Token budget: a year of nights at five or six tokens each is around 2,000 tokens, comparable to a long hospital stay, so many systems will pool nights into weekly summaries. Informative missingness: people stop wearing devices when they are ill or travelling, so absent nights should be explicit tokens, in the spirit of LSM-2's inherited masks. Population overlap: sensor cohorts (device owners, research volunteers) and EHR cohorts rarely coincide, and joint wearable–EHR models such as Zhang et al. (2026) are still early preprints.

As of late 2026 the pieces exist separately: large sensor encoders, one sleep model that forecasts disease from a single night, a first BCG foundation model, and workshop-stage action-conditioned wearable world models. No published system I found yet joins nightly sensor tokens and clinical events in one generative timeline, and none has shown that simulated sensor trajectories change a clinical decision.

Two factorizations. Let \(e_{1:n}\) be the token sequence of a timeline model over a vocabulary \(\mathcal{V}\). In Route A each night becomes tokens in an extended vocabulary \(\mathcal{V}' = \mathcal{V} \cup \mathcal{V}_{\text{night}}\), and the model defines one autoregressive distribution

\[ p_\theta(e_{1:n}) = \prod_{k=1}^{n} p_\theta(e_k \mid e_{so sampling a continuation produces future nights and future clinical events from the same softmax. In Route B the night embedding \(z_t \in \mathbb{R}^d\) enters as an input vector \(W z_t\) in the model's embedding space. The model then defines \(p_\theta(e_k \mid e_{

Tokenizing a night. With deviation \(d_t\) from a trailing personal baseline and decile edges \(q_1 < \dots < q_9\) fitted on training patients, the decile token is \(\mathrm{Q}k\) with \(k = 1 + \#\{j : q_j < d_t\}\). An embedding becomes a night-type token by vector quantization, \(c_t = \arg\min_{c} \lVert z_t - \mu_c \rVert\) over a codebook of \(C\) centroids. The information carried is bounded: \(\log_2 10 \approx 3.3\) bits per decile token and \(\log_2 C\) bits for the night type, about 19 bits per night for four summaries and \(C = 64\), against a full continuous vector in Route B.

Token budget. At \(m\) tokens per night, a year costs \(365\,m\) tokens; for \(m = 6\) that is 2,190, comparable to a long hospital stay and to the entire context of many timeline models. Pooling to weekly summaries reduces it to \(52\,m = 312\). Self-attention cost grows as \(O(n^2)\) in context length, so nightly tokens over several years either require long-context attention or a sliding window that drops older clinical history.

Missingness. Let \(R_t \in \{0, 1\}\) indicate a valid night. Dropping invalid nights is harmless only if missingness is ignorable, \(p(R_t \mid x, e) = p(R_t \mid \text{observed})\). Devices are removed during illness and admissions, so \(R_t\) depends on the unobserved state; encoding \(R_t = 0\) as an explicit token lets the model learn \(p(e_{k} \mid R_{\le t})\), treating absence as information rather than as a gap.

The module implements Route A: it turns per-night sensor summaries into ETHOS-style tokens and interleaves them with clinical events. Inputs per night are four summaries (sleeping heart rate, RMSSD, respiratory rate, sleep minutes), a quality fraction in \([0, 1]\) from the sensor's quality filter, and an embedding vector from a frozen encoder of the BCG-FM, LSM-2 or SleepFM kind. Output is a list of string tokens; in a real pipeline these map to integer ids appended to the timeline vocabulary. Token names and thresholds are illustrative.

personal_deviation computes each night's deviation from the mean of up to 28 previous valid nights and returns NaN until 7 exist, using only the past. fit_tokenizer fits decile edges per feature on training patients' deviations and a k-means codebook of "night types" on training embeddings. night_tokens emits a marker, one decile token per feature (or an explicit unknown token) and a night-type token; a night below the quality threshold becomes two tokens that record the absence. interleave merges nights and clinical events by time and inserts gap tokens. skill_vs_persistence scores forecasts against "tomorrow equals today".

"""Route A: nightly sensor summaries -> ETHOS-style tokens (illustrative names and thresholds)."""
import numpy as np
from sklearn.cluster import KMeans

FEATS = ["hr", "rmssd", "resp_rate", "sleep_min"]

def personal_deviation(series, window=28, min_nights=7):
    """Deviation of each night from the mean of the previous `window` valid nights (past only)."""
    out = np.full(len(series), np.nan)
    for t in range(len(series)):
        past = series[max(0, t - window):t]
        past = past[~np.isnan(past)]
        if len(past) >= min_nights:
            out[t] = series[t] - past.mean()
    return out

def fit_tokenizer(train_dev, emb_train, n_codes=64):
    """train_dev: dict feat -> 1D array of personal deviations (TRAINING patients only)."""
    edges = {f: np.nanquantile(train_dev[f], np.linspace(0.1, 0.9, 9)) for f in FEATS}
    codebook = KMeans(n_clusters=n_codes, n_init=4, random_state=0).fit(emb_train)
    return edges, codebook

def night_tokens(night, edges, codebook, quality_min=0.6):
    """night: dict with feature deviations, 'quality' in [0,1] and 'emb' vector."""
    if night["quality"] < quality_min:
        return ["NIGHT", "NIGHT_LOWQ"]                 # absence is information, not a gap
    toks = ["NIGHT"]
    for f in FEATS:
        v = night[f]
        toks.append(f"{f.upper()}_DEV_UNK" if np.isnan(v)
                    else f"{f.upper()}_DEV_Q{int(np.searchsorted(edges[f], v)) + 1}")
    toks.append(f"NIGHT_C{int(codebook.predict(night['emb'][None])[0])}")
    return toks

def interleave(ehr_events, nights, gap_token):
    """Merge (time, tokens) lists from EHR and nights; insert time-gap tokens between events."""
    stream = sorted(ehr_events + nights, key=lambda e: e[0])
    seq, last_t = [], None
    for t, toks in stream:
        gap = gap_token(t - last_t) if last_t is not None else None
        if gap:
            seq.append(gap)
        seq.extend(toks)
        last_t = t
    return seq

def skill_vs_persistence(y_true, y_pred, y_prev):
    """1 - MAE(model) / MAE(persistence). > 0 means better than 'tomorrow equals today'."""
    return 1.0 - np.mean(np.abs(y_true - y_pred)) / np.mean(np.abs(y_true - y_prev))

if __name__ == "__main__":
    rng = np.random.default_rng(0)
    # 60 nights of resting heart rate around a personal baseline of 58 bpm; nights 50-59 rise by 6 bpm
    hr = 58 + rng.normal(0, 1.5, 60); hr[50:] += 6; hr[[10, 11]] = np.nan
    dev = personal_deviation(hr)
    assert np.all(np.isnan(dev[:7]))                       # not enough history yet
    assert np.nanmean(dev[52:]) > 4                         # the rise is visible as a deviation
    # tokenizer fitted on 500 training people (synthetic deviations and 8-D embeddings)
    train = {f: rng.normal(0, 1, 5000) for f in FEATS}
    edges, cb = fit_tokenizer(train, rng.normal(size=(5000, 8)), n_codes=16)
    good = dict(hr=2.5, rmssd=-1.4, resp_rate=0.0, sleep_min=np.nan, quality=0.9, emb=rng.normal(size=8))
    toks = night_tokens(good, edges, cb)
    assert toks[0] == "NIGHT" and toks[1] == "HR_DEV_Q10" and toks[2] == "RMSSD_DEV_Q1"
    assert toks[3] == "RESP_RATE_DEV_Q6" and toks[4] == "SLEEP_MIN_DEV_UNK" and len(toks) == 6
    assert night_tokens(dict(good, quality=0.3), edges, cb) == ["NIGHT", "NIGHT_LOWQ"]
    gap = lambda d: None if d < 0.01 else ("GAP_1D" if d < 2 else "GAP_WEEK")   # d in days
    seq = interleave([(0.5, ["DX_I48"]), (9.0, ["ADMIT"])], [(0.0, ["NIGHT", "NIGHT_LOWQ"]), (1.0, toks)], gap)
    assert seq[:3] == ["NIGHT", "NIGHT_LOWQ", "GAP_1D"] and seq[-2:] == ["GAP_WEEK", "ADMIT"]
    # persistence skill: a forecaster that knows the baseline beats 'tomorrow equals today'
    y = 58 + rng.normal(0, 1.5, 365); prev = np.r_[58, y[:-1]]
    s = skill_vs_persistence(y, np.full(365, 58.0), prev)
    print("tokens:", toks, "\nskill vs persistence:", round(s, 3))
    assert s > 0.2            # for white noise around a mean, MAE ratio is about 1/sqrt(2)
    print("all night_tok tests passed")

Output:

tokens: ['NIGHT', 'HR_DEV_Q10', 'RMSSD_DEV_Q1', 'RESP_RATE_DEV_Q6', 'SLEEP_MIN_DEV_UNK', 'NIGHT_C5'] 
skill vs persistence: 0.298
all night_tok tests passed

A night with deviations +2.5, −1.4 and 0.0 and a missing sleep-minute value becomes six tokens; the same night at quality 0.3 becomes ['NIGHT', 'NIGHT_LOWQ']. The assertions check that the first seven deviations are undefined, that a 6 bpm rise over the last ten nights is visible, and that interleaving inserts a one-day gap after the first night and a week gap before an admission. A forecaster that knows the baseline beats persistence on white-noise nights with skill 0.298, matching the analytic \(1 - 1/\sqrt{2} \approx 0.29\).

Two choices matter more than the code. Deciles of personal deviation are comparable across people and devices, which addresses BCG's between-person variability; one raw-level token per week (for example a resting heart-rate decile) keeps absolute physiology from being lost. And leakage is avoided only if baselines use past nights and edges and codebook are fitted on training patients, the same patient-level and temporal split discipline as for clinical tokens. Checks worth automating: each decile token should hold close to 10% of training nights, no codebook cluster should dominate, and the share of NIGHT_LOWQ should be tracked per device and firmware.

Ingestion pipeline. Adding sensors turns a timeline model fed by periodic batches of hospital records into one that also receives a nightly stream from heterogeneous devices. A production path has five stages, each with a contract: per-night summaries computed on the device or vendor cloud, versioned by firmware; quality scoring, with the threshold stored as a tokenizer parameter; a frozen encoder, versioned and hashed; personal baselines from past nights only; and tokenization with edges and codebook fitted on training patients. Changing any stage changes the token stream that the world model reads as physiology.

MonitorWhat a change usually means
Share of low-quality nights, by device and firmwareQuality filter or sensor change, not illness
Decile token shares against training (population stability index)Unit, firmware or population shift
Share of users with undefined baselinesNew cohort or falling wear time
Forecast skill against persistenceBaseline bug or drift
Sensor tokens as a share of contextPooling disabled or duplicated nights

Table. Monitors for a sensor branch feeding a timeline model.

Evaluation design. The claim that sensors improve a health world model is tested by ablation on identical patients: the same architecture with and without sensor tokens, the same temporal split and outcomes. Three results decide it: discrimination and calibration on clinical outcomes, lead time for events such as atrial fibrillation diagnosis or heart-failure admission at a fixed false-alert rate, and forecast skill of the sensor stream against persistence. Because sensor users are a selected subset, the comparison must run within that subset, and gains cannot be extrapolated to patients without devices.

Trade-offs. Route A keeps the model a closed generative simulator whose inputs are auditable tokens, at the cost of information lost to binning. Route B carries more information but cannot roll sensor states forward without an extra head, and binds the model to an encoder version that must be frozen with it. Weekly pooling fits typical contexts at the cost of day-level resolution. A specific failure to guard against: if runs of low-quality nights preceded admissions in training, a firmware change that raises the low-quality share will raise simulated risk with no change in patients; stratifying monitors by firmware and adding firmware version as a context token are the defenses. As of late 2026 no published system joins nightly sensor tokens and clinical events in one generative timeline, so these designs remain unvalidated in practice.

ICU and Treatment Simulators

Treatment simulators take actions as input: given a state and a proposed treatment, they predict the next state, so a policy can be trained or evaluated in simulation, as in model-based RL. Intensive care is the usual testbed because data are dense and decisions frequent.

  • Komorowski et al. (2018) built the AI Clinician (Nature Medicine), which discretized ICU patients into states, estimated a transition model from MIMIC-III, and learned fluid and vasopressor policies for sepsis. It became the reference case for both the promise and pitfalls of retrospective policy learning.
  • Gottesman et al. (2019) wrote guidelines for RL in healthcare (Nature Medicine), warning that off-policy evaluation from observational data is fragile: unmeasured confounding, small effective sample sizes and poorly specified rewards can make a bad policy look good.
  • Xu et al. (2025) proposed medDreamer, which carries the Dreamer recipe from the control half of this book into EHRs: a latent world model with a module that treats missingness as signal, and policies trained on a mix of real and imagined rollouts. On sepsis (MIMIC-IV) and ventilation (eICU) it reported the lowest estimated mortality among baselines, but all results are off-policy estimates from a learned model, with no patients treated.
  • Luo et al. (2026), in a NeurIPS 2026 workshop paper titled "One Patient, Two Futures", combined a VAE, treatment-conditioned latent diffusion, a learned clinician policy for background care, and an intervention controller. Trained on MIMIC-IV, its simulated comparison of lactated Ringer's versus saline pointed in the same direction as a randomized trial, with odds ratios closer to the trial than two conventional observational analyses.

The last example has the right shape of validation, comparing interventional predictions with a randomized trial, but it is one comparison in a workshop paper.

A treatment simulator is a learned transition model inside a Markov decision process \((\mathcal S, \mathcal A, P, r, H)\): states \(s_t\) summarize the patient at decision time \(t\), actions \(a_t\) are treatments, \(P(s_{t+1} \mid s_t, a_t)\) is the patient's response and the reward encodes the outcome, typically \(r = -1\) at death and 0 otherwise. The data are trajectories logged under the clinicians' behaviour policy \(\pi_b(a \mid s)\). The AI Clinician discretized states by clustering, discretized fluid and vasopressor doses into a grid of 25 actions, estimated \(\hat P(s' \mid s, a) = N(s, a, s') / N(s, a)\) by counting, and solved for a policy by dynamic programming:

\[ Q_t(s, a) = r(s, a) + \sum_{s'} \hat P(s' \mid s, a)\, \max_{a'} Q_{t+1}(s', a') . \]

Evaluating the learned policy. The value of a new policy \(\pi_e\) is estimated off-policy. Importance sampling reweights each logged trajectory \(\tau_i\) by \(w_i = \prod_{t} \pi_e(a_t \mid s_t) / \pi_b(a_t \mid s_t)\); the weighted estimator is \(\hat V_{\mathrm{WIS}} = \sum_i w_i R_i / \sum_i w_i\). Its reliability is summarized by the effective sample size \(\mathrm{ESS} = (\sum_i w_i)^2 / \sum_i w_i^2\), which collapses as the horizon grows because \(w_i\) is a product of \(H\) ratios. A handful of trajectories that happen to follow the new policy then carry the estimate, the fragility Gottesman et al. describe. The alternative is model-based evaluation, rolling \(\pi_e\) out in \(\hat P\). With rewards bounded by \(r_{\max}\) and \(\epsilon = \max_{s,a} \lVert \hat P(\cdot \mid s,a) - P(\cdot \mid s,a) \rVert_1\), the simulation lemma bounds its error by \(|V^{\pi_e}_P - V^{\pi_e}_{\hat P}| \le H^2 \epsilon\, r_{\max}\). Both estimators assume that \(s_t\) contains every variable that drove the clinicians' choice; if it does not, \(\hat P\) estimates an observational, not an interventional, transition.

Latent and generative variants. medDreamer replaces the tabular model with a Dreamer-style latent model trained by a variational objective and trains an actor-critic on \(\lambda\)-returns from a mixture of real and imagined trajectories. "One Patient, Two Futures" factorizes a rollout into a latent encoder, a treatment-conditioned diffusion model \(p_\theta(z_{t+1} \mid z_t, a_t)\), a learned clinician policy \(\pi_c\) that supplies background care, and a controller that fixes the treatment under study. A comparison of two fluids is the contrast of two rollout distributions, summarized by an odds ratio.

The script below runs the AI Clinician pipeline end to end on a synthetic six-state ICU process whose true dynamics are known. It logs 3,000 eight-step episodes under a clinician policy that raises the dose with severity, estimates the transition model by counting, plans by backward value iteration, and evaluates a softened version of the plan three ways: by running it in the true process, by weighted importance sampling on the logs, and by rolling it out in the learned model.

"""AI-Clinician-style pipeline on a synthetic tabular ICU MDP: learn a transition model
from logged clinician data, plan in it, then estimate the new policy's value off-policy."""
import numpy as np

S, A, T, GAMMA = 6, 3, 8, 1.0           # severity states 0 (well) .. 5 (dying); actions = dose 0/1/2
rng = np.random.default_rng(0)

def true_P():
    """P[s, a, s']: dose helps in the middle states, harms the mildest (side effects)."""
    P = np.zeros((S, A, S))
    for s in range(S):
        for a in range(A):
            drift = 0.15 * (s >= 2) - 0.07 * a * (1 <= s <= 4) + 0.10 * a * (s == 0)
            up, down = np.clip(0.25 + drift, 0.02, 0.9), np.clip(0.25 - drift, 0.02, 0.9)
            P[s, a, min(s + 1, S - 1)] += up; P[s, a, max(s - 1, 0)] += down
            P[s, a, s] += 1 - up - down
    P[S - 1] = 0; P[S - 1, :, S - 1] = 1                     # death is absorbing
    return P

def clinician(s):                       # behaviour policy: dose rises with severity, never 0 prob
    logits = np.array([1.5 - 0.6 * s, 0.3, 0.6 * s - 1.5])
    return np.exp(logits) / np.exp(logits).sum()

def rollout(P, policy, n, s0=3):
    traj = []
    for _ in range(n):
        s, ep = s0, []
        for t in range(T):
            p = policy(s); a = rng.choice(A, p=p)
            s2 = rng.choice(S, p=P[s, a]); ep.append((s, a, p[a], s2)); s = s2
        traj.append(ep)
    return traj

reward = lambda s2: -1.0 * (s2 == S - 1)            # outcome: death by step T

def value_iteration(P):
    V = np.zeros(S); pi = np.zeros((T, S), int)
    for t in reversed(range(T)):
        Q = np.einsum('sat,t->sa', P, -1.0 * (np.arange(S) == S - 1) + GAMMA * V * (np.arange(S) != S - 1))
        pi[t] = Q.argmax(1); V = Q.max(1)
    return pi

P = true_P(); logs = rollout(P, clinician, 3000)
C = np.full((S, A, S), 1e-3)                        # count-based transition model
for ep in logs:
    for s, a, _, s2 in ep: C[s, a, s2] += 1
P_hat = C / C.sum(-1, keepdims=True)
pi = value_iteration(P_hat)[0]                      # stationary approximation of the plan
target = lambda s: 0.85 * np.eye(A)[pi[s]] + 0.05   # softened plan, as in practice

def mortality(eps):  return np.mean([any(s2 == S - 1 for *_, s2 in ep) for ep in eps])
true_new = mortality(rollout(P, target, 20000))
true_clin = mortality(rollout(P, clinician, 20000))
w = np.array([np.prod([target(s)[a] / pb for s, a, pb, _ in ep]) for ep in logs])
y = np.array([any(s2 == S - 1 for *_, s2 in ep) for ep in logs], float)
wis = np.sum(w * y) / np.sum(w); ess = w.sum() ** 2 / np.sum(w ** 2)
print("learned policy (dose per state):", pi)
print(f"mortality  clinician {true_clin:.3f} | learned policy, true {true_new:.3f} | WIS estimate {wis:.3f}")
print(f"logged episodes {len(logs)}, nonzero weights {(w > 0).sum()}, effective sample size {ess:.1f}")
model_based = mortality(rollout(P_hat, target, 20000))  # "imagined" evaluation in the learned model
print(f"model-based estimate (rollouts in learned model) {model_based:.3f}")

Output (python3 treat_sim.py):

learned policy (dose per state): [0 2 2 2 2 0]
mortality  clinician 0.508 | learned policy, true 0.382 | WIS estimate 0.183
logged episodes 3000, nonzero weights 3000, effective sample size 17.9
model-based estimate (rollouts in learned model) 0.381

The learned policy really is better than the clinicians' (true mortality 0.382 against 0.508), but weighted importance sampling reports 0.183, more than twice as optimistic, because 3,000 logged episodes shrink to an effective sample size of about 18. Rolling the policy out in the learned model gives 0.381, close to the truth, only because the state here is fully observed and Markov; with unrecorded severity the same rollout would inherit confounding. Printing the effective sample size next to every off-policy estimate is the cheapest safeguard against reading such a number as evidence.

How these systems are built. ICU treatment simulators share a pipeline: extract a cohort from MIMIC-III/IV or eICU, bin time into decision steps (hours to a few hours), impute and normalize vitals and labs, define a small discrete action space (fluid and vasopressor dose bins in the AI Clinician), choose a reward (usually survival at a fixed horizon), fit the transition model and then the policy. The expensive part is not training; tabular and latent models train in hours. It is the cohort and action definitions, which decide what the model can represent, and validation, which no offline metric completes.

Evaluation ladder. In practice a credible project climbs several rungs: forecast fidelity of the simulator under care as usual; off-policy estimates reported with diagnostics (effective sample size, weight distribution, and doubly robust estimators that combine a model with importance weights, Jiang & Li 2016); evaluation on more than one database and task (medDreamer reports sepsis on MIMIC-IV and ventilation on eICU), ideally with external validation at another hospital; clinician review of recommended actions in specific cases; silent prospective running; and only then a randomized evaluation. Most published systems, including medDreamer, stop at the second or third rung, and their headline mortality reductions are estimates from learned models.

Failure modes. A policy optimized inside a learned model finds the model's errors: it recommends actions that clinicians rarely took in that state, where the transition model has few counts and the importance weights are largest. Rewards defined on mortality ignore harms that do not kill within the horizon, such as fluid overload or renal injury. Action timing is noisy in charting, so a dose recorded after a deterioration can look like its cause. Hospitals differ in practice, so a policy learned on one site's data reflects that site's case mix. Common mitigations are restricting the policy to actions with adequate support, reporting results per subgroup, and testing the simulator's interventional predictions against randomized evidence, which is what made the lactated Ringer's versus saline comparison in "One Patient, Two Futures" informative.

Prediction Is Not Intervention

A health world model trained on observational records learns \(p(\text{future} \mid \text{history})\), the distribution of what happened to patients like this one under the care they actually received. Appending a treatment token and resampling gives \(p(\text{future} \mid \text{history}, a)\): what happened to patients who received \(a\). That is not the effect of giving \(a\), because in the data, who received \(a\) depended on how sick they were. This is confounding by indication (Catalogue of Bias 2018), and it is the single most important caveat for anyone who wants to use a generative EHR model for "what if" questions.

Confounding by indication: severity drives both treatment and outcome. Severity partly unrecorded Treatment a e.g. vasopressor token Outcome e.g. death token sicker → treated sicker → worse causal effect of a What the world model learns p(death | history, a recorded) effect of a mixed with the reasons clinicians chose a What a treatment decision needs p(death | history, do(a)) needs adjustment, trial emulation or randomized data
Fig. Why conditioning is not intervening. Sicker patients are more likely to receive the treatment and more likely to die, so in observational data the treatment token predicts death even if the treatment helps. A generative model faithfully reproduces that association. Original diagram.

Inserting a vasopressor token mostly asks "what usually happens to patients sick enough to get one". van Geloven et al. (2024) describe three common modeling choices that create such causal blind spots in clinical prediction: including treatment as a predictor, restricting to treated patients, and ignoring treatment altogether. Each yields risks that are easily misread as treatment-specific. Delphi's coverage notes it captures associations rather than causal relationships, and ETHOS-ARES treats post-procedure risk jumps as severity markers.

Conditioning versus intervening. Let \(H\) be the recorded history, \(U\) unrecorded severity, \(A \in \{0,1\}\) the treatment and \(Y\) the outcome. A generative model trained on observational data estimates, at best,

\[ p(Y \mid H, A{=}a) = \int p(Y \mid H, U, A{=}a)\, p(U \mid H, A{=}a)\, dU . \]

The interventional quantity instead averages over severity as it is distributed before the treatment decision:

\[ p(Y \mid H, \mathrm{do}(A{=}a)) = \int p(Y \mid H, U, A{=}a)\, p(U \mid H)\, dU . \]

The two differ exactly when \(p(U \mid H, A{=}a) \neq p(U \mid H)\), that is, when receiving the treatment carries information about unrecorded severity. In graph terms, \(A \leftarrow U \to Y\) is an open back-door path that only conditioning on \(U\) closes. If \(U\) is empty, the two expressions coincide, which is the no-unmeasured-confounding assumption.

Example

Let 20% of patients be severe, with treatment given to 80% of severe and 10% of other patients, and let treatment cut death risk by a quarter in both groups (0.40 to 0.30, and 0.04 to 0.03). By Bayes' rule \(P(\text{severe} \mid A{=}1) = 0.16/0.24 = 0.67\), so \(P(Y \mid A{=}1) = 0.21\) and \(P(Y \mid A{=}0) = 0.059\), whereas \(P(Y \mid \mathrm{do}(A{=}1)) = 0.084\) and \(P(Y \mid \mathrm{do}(A{=}0)) = 0.112\). The conditional risk ratio is 3.6; the causal one is 0.75.

The three blind spots, formally. van Geloven et al.'s three choices estimate different targets. Including treatment as a predictor estimates \(p(Y \mid H, A)\), the conditional above. Restricting to treated patients estimates \(p(Y \mid H, A{=}1)\) on a population selected by \(p(A{=}1 \mid H)\). Ignoring treatment estimates \(p(Y \mid H) = \sum_a p(Y \mid H, a)\, p(a \mid H)\), the risk under the current treatment policy, which changes whenever practice changes. None equals \(p(Y \mid H, \mathrm{do}(A{=}a))\) without further assumptions.

The script draws two million synthetic patients in which severity drives both treatment and death, and treatment lowers risk by a quarter in every patient. The "world model" is the ideal one: exact cell frequencies of the observational data, which is what an infinitely large generative model would learn. It is then queried three ways: conditioning on the treatment token, adjusting for a recorded proxy of severity (high lactate, which agrees with true severity 80–90% of the time), and the true interventional risk.

"""Conditioning vs intervening: a perfectly fitted observational model answers the wrong question."""
import numpy as np
rng = np.random.default_rng(1); n = 2_000_000

u = rng.random(n) < 0.2                                   # unrecorded severity (20% severe)
h = np.where(u, rng.random(n) < 0.8, rng.random(n) < 0.1) # recorded proxy, e.g. high lactate
a = rng.random(n) < np.where(u, 0.8, 0.1)                 # clinicians treat the sickest
risk = np.where(u, 0.40, 0.04) * np.where(a, 0.75, 1.0)   # treatment cuts risk by 25% in everyone
y = rng.random(n) < risk

def p(mask): return y[mask].mean()                         # empirical "world model" = cell frequencies

cond = {k: p(a == k) for k in (0, 1)}                                         # p(Y | A=a)
cond_h = {k: sum((h == j).mean() * p((h == j) & (a == k)) for j in (0, 1)) for k in (0, 1)}  # adjust for proxy H
truth = {k: 0.2 * 0.40 * (0.75 if k else 1) + 0.8 * 0.04 * (0.75 if k else 1) for k in (0, 1)}  # p(Y | do(A=a))
for name, d in [("p(Y|A) naive", cond), ("adjusted for proxy H", cond_h), ("p(Y|do(A)) truth", truth)]:
    print(f"{name:22s} treated {d[1]:.3f}  untreated {d[0]:.3f}  risk ratio {d[1] / d[0]:.2f}")

Output (python3 conf_sim.py):

p(Y|A) naive           treated 0.211  untreated 0.059  risk ratio 3.58
adjusted for proxy H   treated 0.155  untreated 0.070  risk ratio 2.22
p(Y|do(A)) truth       treated 0.084  untreated 0.112  risk ratio 0.75

The perfectly fitted model reports that treatment multiplies mortality by 3.6, when it actually multiplies it by 0.75. Adjusting for an imperfect proxy of severity moves the estimate toward the truth (2.22) but leaves it on the wrong side of 1. The lesson for health world models is that fitting the observational distribution better does not shrink this error: it is a property of the question, not of the estimator, and it shrinks only as the recorded history captures the reasons for treatment.

Where the problem appears. Generative EHR models expose a sampling interface: append tokens to a history and draw futures. Nothing in that interface distinguishes a diagnosis token from a treatment token, so a what-if query is one line of code, and its answer looks exactly like a validated forecast. ETHOS-style models and Delphi-2M are trained and evaluated as forecasters of care as usual, and their authors frame them that way (Delphi as associational, ETHOS-ARES reading post-procedure risk jumps as severity markers); the risk is in downstream tools that reuse the sampling interface for decisions.

Design decisions. Serving these models responsibly in research or clinical settings means handling treatment tokens explicitly. Reasonable choices include classifying tokens into covariates, outcomes and actions in the vocabulary metadata; blocking or flagging queries that append an action token to the current time and read off outcomes; labelling every output as "under care as usual" unless it came from a causal pipeline; and logging the full query (history, appended tokens, number of samples) so that audits can tell forecasts from implicit counterfactuals. At training time, predicting outcomes only from information available before the treatment decision gives forecasts that are easier to interpret, at some cost in accuracy.

Failure modes. The most damaging is silent: a dashboard that compares simulated outcomes with and without a treatment token, read as a treatment effect. A second is drift under practice change: a model that ignores treatment learns risk under the old policy, so when a guideline changes who is treated, its risks shift without any change in patients. Monitoring therefore tracks both calibration over time and the share of queries that involve treatment tokens, and any decision-facing use goes through a trial-emulation design with its own validation.

What Counterfactual Use Requires

Turning a health world model into an interventional simulator requires assumptions and machinery beyond next-token prediction. The main routes, from most to least established:

  1. Target trial emulation. Hernán & Robins (2016) framed observational causal analysis as emulating a specific randomized trial: eligibility, strategies, time zero, follow-up, analysis plan. A world model can simulate outcomes under each strategy inside this design; the emulation discipline (aligned time zero, no immortal-time bias) is what makes the answer interpretable.
  2. Adjustment for confounding. If all confounders are in the history (no unmeasured confounding), every patient could have received either option (positivity), and outcomes are well defined (consistency), the interventional distribution equals an adjusted observational one, via inverse probability weighting or g-computation. The Causal Transformer (Melnychuk et al. 2022) learns representations that predict outcomes but not treatment assignment, to reduce time-varying confounding.
  3. Separating the clinician policy. Model the patient's response separately from clinicians' decisions, then replace the learned policy with a fixed one for the treatment under study, as "One Patient, Two Futures" does. The no-unmeasured-confounding assumption still applies.
  4. Validation against trials. The direct check is agreement with randomized evidence. Keogh & van Geloven (2023) show how to evaluate "prediction under interventions" on observational data with artificial censoring and inverse probability weighting, extending calibration and discrimination to the counterfactual setting.

As of late 2026, GPT-style health world models are good forecasters of care as usual and plausible engines for causal analysis inside trial-emulation designs; they are not, by themselves, treatment simulators. The 2026 review by Liu et al. reaches the same conclusion and calls for target-trial emulation, sensitivity analyses and prospective testing before interventional use.

Target trial. A target trial is a protocol \((\mathcal E, \{g_1, g_2\}, t_0, \text{follow-up}, Y, \text{contrast})\): eligibility \(\mathcal E\) evaluated at time zero \(t_0\), treatment strategies \(g_k\) that map each history to an action, an outcome and an estimand such as the risk difference \(\mu_{g_1} - \mu_{g_2}\). Eligibility, assignment and follow-up must start together at \(t_0\), or immortal-time bias appears.

Identification. With potential outcomes \(Y^a\), the interventional mean \(\mu_a = \mathbb E[Y^a]\) is identified under exchangeability \(Y^a \perp A \mid H\), positivity \(0 < e(H) < 1\) where \(e(H) = P(A{=}1 \mid H)\), and consistency \(Y = Y^A\). Two estimators follow. g-computation standardizes the outcome model, \(\hat\mu_a = \frac1n \sum_i \hat{\mathbb E}[Y \mid H_i, A{=}a]\); inverse probability weighting reweights, \(\hat\mu_a = \sum_i w_i \mathbb 1[A_i{=}a] Y_i / \sum_i w_i \mathbb 1[A_i{=}a]\) with \(w_i = 1/e(H_i)\) for treated and \(1/(1-e(H_i))\) for untreated patients.

Time-varying treatments. Earlier treatments change later covariates \(L_t\) that also drive later treatments, so conditioning on \(L_t\) blocks part of the effect while not conditioning leaves confounding. The g-formula resolves this by simulation:

\[ \mu_g = \sum_{\bar l} \mathbb E[Y \mid \bar l_T, \bar a_T{=}g(\bar l_T)] \prod_{t=0}^{T} p(l_t \mid \bar l_{t-1}, \bar a_{t-1}{=}g(\bar l_{t-1})) . \]

Monte Carlo evaluation of this sum is a world-model rollout in which covariates are sampled from the model and every treatment is set by \(g\) instead of by the learned clinician policy \(\pi(a_t \mid \bar l_t, \bar a_{t-1})\). A generative event model is therefore a natural engine for the parametric g-formula, provided its covariate model is correct and the assumptions hold.

Positivity and diagnostics. If nobody with a given history received a treatment, \(e(H) = 0\) and the model has no data for that branch. Checking \(\hat e(H)\) along simulated trajectories and refusing where it leaves a band such as \([0.02, 0.98]\) is a simple safeguard; the effective sample size \((\sum w_i)^2 / \sum w_i^2\) summarizes how much data supports a weighted estimate. Keogh and van Geloven's validation censors each patient when observed treatment departs from \(g\) and weights the remainder by the inverse probability of remaining uncensored, so that calibration and discrimination are computed in a pseudo-population that followed \(g\). For residual confounding, the E-value \(\mathrm{RR} + \sqrt{\mathrm{RR}(\mathrm{RR}-1)}\) gives the minimum risk-ratio association an unmeasured confounder would need with both treatment and outcome to explain away an observed risk ratio \(\mathrm{RR} > 1\) (apply it to \(1/\mathrm{RR}\) for protective effects) (VanderWeele & Ding 2017).

The script below builds a two-step ICU process with treatment–confounder feedback: severity at admission \(L_0\) drives the first treatment \(A_0\); \(A_0\) improves later severity \(L_1\); \(L_1\) drives the second treatment \(A_1\); and death depends on both severities and \(A_1\). All confounders are recorded, so the effect of "always treat" versus "never treat" is identified. The g-formula fits \(p(L_1 \mid L_0, A_0)\) and \(p(Y \mid L_0, L_1, A_1)\) by counting, which is the role a generative event model plays at scale, and rolls out with both treatments fixed. A positivity check lists history cells whose treatment propensity leaves \([0.02, 0.98]\).

"""Time-varying treatment: the g-formula as a world-model rollout with the clinician policy replaced."""
import numpy as np
rng = np.random.default_rng(2); n = 1_000_000
sig = lambda x: 1 / (1 + np.exp(-x))

def world(n, policy=None):
    """Data-generating process. policy=None -> clinicians decide; else policy(t) gives a fixed action."""
    L0 = rng.random(n) < 0.3                                          # severe at admission
    A0 = rng.random(n) < (sig(-1.5 + 2.5 * L0) if policy is None else policy(0))
    L1 = rng.random(n) < sig(-1.0 + 2.0 * L0 - 1.2 * A0)               # treatment improves later state
    A1 = rng.random(n) < (sig(-1.5 + 2.5 * L1) if policy is None else policy(1))
    Y = rng.random(n) < sig(-2.5 + 2.0 * L1 + 0.8 * L0 - 0.6 * A1)     # death
    return L0, A0, L1, A1, Y

L0, A0, L1, A1, Y = world(n)                                           # observational records
always, never = (lambda t: 1.0), (lambda t: 0.0)
truth = {s: world(n, f)[-1].mean() for s, f in [("always", always), ("never", never)]}

# naive: compare patients who happened to follow each strategy
naive = {"always": Y[A0 & A1].mean(), "never": Y[~A0 & ~A1].mean()}
# conditioning on L1 (a confounder of A1 that is also caused by A0) blocks part of the effect
strat = {k: sum((L0 == i).mean() * (L1 == j).mean() * Y[(L0 == i) & (L1 == j) & (A0 == k) & (A1 == k)].mean()
                for i in (0, 1) for j in (0, 1)) for k in (0, 1)}
cond_L1 = {"always": strat[1], "never": strat[0]}

def g_formula(a, m=1_000_000):
    """Fit p(L1 | L0, A0) and p(Y | L0, L1, A1) by counts, then roll out with A fixed to a."""
    l0 = rng.choice(L0, m)                                             # empirical baseline distribution
    pL1 = {(i, k): L1[(L0 == i) & (A0 == k)].mean() for i in (0, 1) for k in (0, 1)}
    pY = {(i, j, k): Y[(L0 == i) & (L1 == j) & (A1 == k)].mean() for i in (0, 1) for j in (0, 1) for k in (0, 1)}
    l1 = rng.random(m) < np.vectorize(lambda i: pL1[(i, a)])(l0.astype(int))
    py = np.array([pY[(i, j, a)] for i, j in zip(l0.astype(int), l1.astype(int))])
    return (rng.random(m) < py).mean()
gf = {"always": g_formula(1), "never": g_formula(0)}

def positivity(lo=0.02, hi=0.98):
    """Propensity of treatment in each recorded history cell; flag cells outside [lo, hi]."""
    cells = {("t0", i): A0[L0 == i].mean() for i in (0, 1)}
    cells.update({("t1", i, j): A1[(L0 == i) & (L1 == j)].mean() for i in (0, 1) for j in (0, 1)})
    return {c: round(e, 3) for c, e in cells.items() if not lo < e < hi}, len(cells)

for name, d in [("naive", naive), ("conditioning on L1", cond_L1), ("g-formula rollout", gf), ("truth", truth)]:
    print(f"{name:19s} always {d['always']:.3f}  never {d['never']:.3f}  risk diff {d['always'] - d['never']:+.3f}")
print("positivity violations (cells outside [0.02, 0.98]):", *positivity())

Output (python3 gformula.py, about 2 s):

naive               always 0.287  never 0.128  risk diff +0.159
conditioning on L1  always 0.138  never 0.209  risk diff -0.072
g-formula rollout   always 0.116  never 0.248  risk diff -0.132
truth               always 0.117  never 0.248  risk diff -0.131
positivity violations (cells outside [0.02, 0.98]): {} 6

The naive comparison of patients who happened to follow each strategy makes treatment look harmful (+0.159). Stratifying on \(L_1\), the usual regression instinct, gets the sign right but loses almost half the effect, because \(L_1\) is on the causal path from \(A_0\) to death. The g-formula rollout recovers the true risk difference (−0.132 against −0.131). All six history cells pass the positivity check here; in real records, cells with near-zero propensity should be refused rather than simulated.

A guarded what-if pipeline. A defensible design for interventional questions wraps the health world model in a protocol rather than exposing the sampler. The steps, in order: (1) write the query as a target trial (eligibility, strategies, time zero, follow-up, outcome) and store it with the answer; (2) check positivity by estimating the propensity of each strategy along the patient's history and along simulated trajectories, and refuse where it is near 0 or 1 or where too few comparable patients exist; (3) run g-formula rollouts that override the studied treatment tokens while keeping the learned clinician policy for all other care, as "One Patient, Two Futures" does; (4) gate each query family (for example fluid choice in sepsis) on agreement with randomized evidence before enabling it; (5) report the effect with Monte Carlo and model uncertainty, the assumptions, an E-value, and the refusal rate.

Guarded what-if pipeline: target-trial specification, positivity check, rollouts with the policy replaced, trial benchmark gate, answer with uncertainty; failed checks lead to refusal. Target trial strategies, time zero Positivity propensity in band? g-formula policy replaced Trial gate matches RCT family? Answer effect, CI, E-value Refuse with stated reason (thin data or unvalidated query family) fail fail
Fig. A guarded what-if pipeline around a health world model. The world model is used only in the g-formula step; the other steps decide whether its answer can be read causally. Original diagram.

Costs and monitoring. The pipeline narrows and slows the interface: each answer needs rollouts under two or more strategies, and a share of queries is refused. Useful monitors are the share of treatment queries answered by raw conditioning (target zero), refusal rates per query family, the effective sample size of comparable historical patients, agreement of simulated effects with trial estimates, and forecast calibration under care as usual, a prerequisite because the g-formula is only as good as the covariate model.

What remains unsolved. The pipeline does not remove the no-unmeasured-confounding assumption; it makes violations visible only where randomized benchmarks exist. Benchmarks are scarce. The prospective test is to enable a query family after it passes the gate and compare its predictions with the next randomized trial or natural experiment in that area, such as a protocol change that shifted treatment rates without changing patients. Agreement supports using the model as a g-formula engine for that family; disagreement counts against it regardless of forecast AUROC.

Evaluating Health World Models

A health world model must be evaluated twice: as a predictor (accurate, calibrated risks for the people it will serve) and as a simulator (realistic timelines that do not leak training patients). Papers mostly report the first, usually as AUROC; practice is thinnest on the second.

Let \(x\) be a patient's history up to the prediction time and \(Y\in\{0,1\}\) indicate whether outcome \(c\) occurs within the horizon. A health world model \(P_\theta\) defines a distribution over future timelines \(f\), and its model risk is

\[ p_\theta(x) = \Pr_{f\sim P_\theta(\cdot\mid x)}\big[c\in f\big]. \]

Zero-shot inference estimates it from \(K\) rollouts: \(\hat p = M/K\) with \(M\sim\mathrm{Binomial}(K, p_\theta(x))\), so \(\mathbb{E}[\hat p]=p_\theta(x)\) and \(\operatorname{Var}[\hat p]=p_\theta(1-p_\theta)/K\). Predictor evaluations (discrimination, calibration, subgroups, shift, utility) test properties of \(\hat p\) against \(Y\). Simulator evaluations (fidelity, privacy) test the distribution of the sampled \(f\) themselves, against real futures and against the training set. Every predictor metric is computed on \(\hat p\), not on \(p_\theta\), and so measures the model and the sampling budget together: the estimator is unbiased, so calibration-in-the-large is unaffected by \(K\), but its noise and its \(K+1\) possible values degrade ranking.

import numpy as np
from scipy.stats import rankdata

def auroc(y, s):
    r = rankdata(s); y = y.astype(bool); n1 = y.sum()
    return (r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * (~y).sum())

rng = np.random.default_rng(0)
N = 30_000
p_model = 1 / (1 + np.exp(-rng.normal(-5.0, 1.5, N)))    # the model's risk p_theta(x)
y = rng.binomial(1, p_model)                               # outcomes drawn from it
for K in [5, 20, 100, 1000]:
    p_hat = rng.binomial(K, p_model) / K                    # M/K from K rollouts
    print(f"K={K:5d}  AUROC={auroc(y, p_hat):.3f}  O/E={y.sum()/p_hat.sum():.2f}")
print(f"exact      AUROC={auroc(y, p_model):.3f}")

Simulates a model whose risks are known exactly, estimates them from K rollouts, and prints the AUROC and observed-to-expected ratio of the simulation frequency.

K=    5  AUROC=0.634  O/E=1.03
K=   20  AUROC=0.704  O/E=1.01
K=  100  AUROC=0.797  O/E=1.02
K= 1000  AUROC=0.828  O/E=1.02
exact      AUROC=0.836

The observed-to-expected ratio stays near 1 at every \(K\) because \(M/K\) is unbiased, while AUROC rises from 0.634 at \(K=5\) toward the exact-risk value of 0.836. Part of a reported AUROC is therefore a property of the sampling budget, not of the model, and the budget must be stated with the result.

In deployment, evaluation is a release gate and a monitor rather than a table in a paper. The gate decides whether a model version may produce risks that clinicians or downstream systems see; the monitor decides when it must stop. Both depend on a fixed specification: prediction time and horizon for each task, cohort definition, sampling settings (temperature, truncation, \(K\), token budget, seed), and each metric with its pass threshold and confidence interval.

Evaluation map: predictor checks, simulator checks and decision checks, feeding a release decision.Predictor checksdiscrimination: AUROC, AUPRCcalibration: O/E, slope, ECEsubgroups with CIstemporal and site shiftshortcut auditSimulator checksrollout completion, validitymarginal fidelity: KS, TVtiming: gaps, length of staydependency: co-occurrenceprivacy: memorization testsDecision checksnet benefit (decision curve)silent prospective runrandomized evaluationinterventional validityvs. trials, IPWAll three columns must pass before simulated frequencies are used as risks
Fig. Three families of checks for a health world model. Predictor checks treat the simulation frequency as a risk score; simulator checks treat rollouts as synthetic patient timelines; decision checks ask whether acting on the output helps. A release review applies them from left to right.

Sampling dominates the cost: test patients × tasks × \(K\) × tokens per rollout. Discrimination, calibration, subgroup, shift and fidelity checks can all reuse the same stored rollouts, so they are generated once and versioned with their sampling configuration; privacy tests need separate prompts from training and held-out patients. Reporting can follow TRIPOD-LLM (Gallifant et al. (2025)). Published health world models mostly stop at AUROC; the simulator and decision checks are where an internal review has to add work.

Discrimination

Discrimination asks whether the model ranks patients who will have the outcome above those who will not. AUROC is the standard summary; AUPRC is more informative at low prevalence, which is why the CoMET paper's incident-disease results look much better on AUPRC than on AUROC. For generative models, small-\(K\) scores tie (see Zero-Shot Inference), and next-event metrics can be inflated by recurrent codes a model predicts by copying history, as the RAVEN authors note; report new onsets separately.

With \(n_1\) positives and \(n_0\) negatives, the AUROC is the Mann–Whitney probability that a random positive outranks a random negative, ties counted as one half:

\[ \mathrm{AUROC}=\frac{1}{n_1n_0}\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)=\frac{R_1-n_1(n_1+1)/2}{n_1n_0}, \]

where \(R_1\) is the sum of tie-averaged ranks of the positives. It is invariant to any strictly increasing transform of \(\hat p\), which is why it cannot detect miscalibration. Its standard error has the closed form of Hanley & McNeil (1982), dominated by the smaller class: a few hundred events give intervals of about ±0.01–0.02. With \(K\) rollouts and true risk \(q\), \(\Pr(\hat p=0)=(1-q)^K\); for \(q=0.01,K=20\) that is 0.82, so most low-risk patients tie. Average precision has chance level \(n_1/(n_0+n_1)\), the prevalence. For a new-onset analysis the same statistics are computed only over patients whose history \(x_i\) does not already contain \(c\); for censored follow-up the C-index replaces AUROC.

import numpy as np
from scipy.stats import rankdata
from sklearn.metrics import roc_auc_score, average_precision_score

def auroc(y, s):
    """P(random positive outranks random negative), ties count 1/2."""
    r = rankdata(s); y = y.astype(bool); n1 = y.sum()
    return (r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * (~y).sum())

rng = np.random.default_rng(1)
N = 20_000
had_before = rng.random(N) < 0.15                  # chronic code already in history
risk_new = 1 / (1 + np.exp(-rng.normal(-4.5, 1.2, N)))
y = np.where(had_before, rng.random(N) < 0.9,      # recurrent: recorded again
             rng.random(N) < risk_new).astype(int)
# A model that copies history scores recurrent patients ~0.9, others by risk
score = np.where(had_before, 0.9, risk_new) + rng.normal(0, 0.02, N)
assert abs(auroc(y, score) - roc_auc_score(y, score)) < 1e-12
new = ~had_before
print(f"all events   AUROC {auroc(y, score):.3f}  AUPRC {average_precision_score(y, score):.3f}  prev {y.mean():.3f}")
print(f"new onsets   AUROC {auroc(y[new], score[new]):.3f}  AUPRC {average_precision_score(y[new], score[new]):.3f}  prev {y[new].mean():.3f}")

Builds a cohort in which 15% of patients already carry a chronic code, scores them with a model that copies history, and prints AUROC and AUPRC on all events and on new onsets only.

all events   AUROC 0.962  AUPRC 0.863  prev 0.155
new onsets   AUROC 0.735  AUPRC 0.104  prev 0.020

Copying the history earns an AUROC of 0.962 on all events, but on new onsets the same scores reach 0.735, and AUPRC falls from 0.863 to 0.104 against a prevalence of 0.020. Reporting the pooled number alone would credit the model with a skill it lacks.

A credible discrimination report gives, per task, AUROC and AUPRC with confidence intervals, the prevalence next to the AUPRC, and a split into new onsets and recurrent events, as the RAVEN authors recommend. CoMET illustrates why both curves matter: against supervised baselines its largest model had the higher AUPRC on all six incident-disease tasks but the higher AUROC on only one.

Ties are an engineering choice. Rare outcomes need more rollouts, and a common policy is adaptive: a modest \(K\) for every patient, then more rollouts for patients whose score lies near a decision threshold or is zero. The prediction time must be enforced in the data pipeline so that no token recorded after it (discharge disposition, billing codes, backfilled diagnoses) reaches the prompt, and a shortcut audit reruns the evaluation with such tokens masked. Bedi, Fries & Shah (2026) also ask for performance by event frequency, because a single AUROC averaged over tasks hides rare codes.

Calibration

Calibration asks whether, among patients given a risk of 20%, about 20% have the outcome. The next-token loss is a proper scoring rule per token, but rollouts compound per-step errors and truncated sampling distorts frequencies. Bedi, Fries & Shah (2026) list calibration first among the checks a generative EHR model should pass before its frequencies are read as probabilities. The Akagi et al. (2026) simulator is a positive example: observed-to-expected ratios near 1 on a later test year without recalibration.

Reliability diagram for simulated risks before and after recalibration.
Fig. A reliability diagram for simulated risks. Points bin patients by predicted risk \(\hat{p} = M/K\) and plot the observed outcome rate in each bin. Here the raw simulation frequencies are too extreme (an S-shaped curve crossing the diagonal), and a monotone recalibration map fitted on a held-out set pulls them back toward the diagonal. Illustrative: curves are generated from a logistic distortion, not from a real model.

Perfect calibration means \(\Pr(Y=1\mid\hat p=q)=q\) for all \(q\). Summaries test it at increasing resolution (Van Calster et al. (2019)):

  • Calibration-in-the-large: \(\mathrm{O/E}=\sum_i y_i/\sum_i\hat p_i\).
  • Logistic recalibration \(\operatorname{logit}\Pr(Y=1)=a+b\operatorname{logit}\tilde p\), with \(\tilde p=(M+0.5)/(K+1)\) to avoid infinite logits; ideal \(a=0,b=1\), and \(b \lt 1\) means predictions are too extreme.
  • \(\mathrm{ECE}=\sum_b \frac{n_b}{N}\lvert\bar y_b-\bar p_b\rvert\) over bins; the Brier score \(\frac1N\sum_i(\hat p_i-y_i)^2\), which for simulation also contains the Monte Carlo term \(\frac1N\sum_i p_i(1-p_i)/K\).

Sampling settings explain most simulation-specific miscalibration. At temperature \(\tau\) each step samples from \(\pi_\tau(v)\propto\pi(v)^{1/\tau}\); for \(\tau \lt 1\), or under top-\(p\) truncation, every step overweights likely tokens, and a path through \(r\) unlikely tokens is down-weighted by a factor that shrinks geometrically in \(r\), so rare outcomes become rarer. Only \(\tau=1\) without truncation gives an unbiased estimate of \(p_\theta\). If a fraction of rollouts stops at the token budget before the horizon, discarding them estimates risk conditional on completion, which over-weights fast outcomes; treating them as right-censored is the consistent alternative.

import numpy as np
from sklearn.isotonic import IsotonicRegression

def oe(y, p): return y.sum() / p.sum()
def slope_intercept(y, p, it=30):
    """Fit logit P(y=1) = a + b logit(p) by Newton's method."""
    X = np.c_[np.ones_like(p), np.log(p / (1 - p))]; w = np.zeros(2)
    for _ in range(it):
        mu = 1 / (1 + np.exp(-X @ w))
        w += np.linalg.solve(X.T @ (X * (mu * (1 - mu))[:, None]), X.T @ (y - mu))
    return w

rng = np.random.default_rng(2)
z = rng.normal(-2.0, 1.0, 40_000); y = rng.binomial(1, 1 / (1 + np.exp(-z)))
K = 50
p_raw = (rng.binomial(K, 1 / (1 + np.exp(-1.6 * z))) + 0.5) / (K + 1)   # too-extreme rollouts
fit, test = slice(0, 20_000), slice(20_000, None)
iso = IsotonicRegression(out_of_bounds="clip", y_min=1e-4, y_max=1 - 1e-4).fit(p_raw[fit], y[fit])
p_cal = iso.predict(p_raw[test])
for name, p in [("raw", p_raw[test]), ("isotonic", p_cal)]:
    a, b = slope_intercept(y[test], p)
    print(f"{name:9s} O/E {oe(y[test], p):.2f}  intercept {a:+.2f}  slope {b:.2f}")

Generates 50 rollouts per patient from a model whose logits are 1.6 times too large, fits isotonic regression on one half of the cohort, and prints O/E, calibration intercept and slope on the other half before and after.

raw       O/E 1.63  intercept -0.06  slope 0.63
isotonic  O/E 1.02  intercept +0.01  slope 0.99

The raw frequencies have slope 0.63 (too extreme) and O/E 1.63; the isotonic map, fitted on held-out patients, restores slope 0.99 and O/E 1.02. Because the map is monotone, it leaves the ranking and hence the AUROC unchanged.

Calibration is the property most easily broken by inference settings that look harmless. ETHOS-ARES sampled with top-\(p\) truncation; a production system that wants frequencies read as probabilities samples at temperature 1 without truncation, records the configuration with every score, and treats any change of sampler, \(K\) or token budget as a new model version that needs recalibration checks. The share of rollouts that hit the budget is reported per task; CoMET treated such rollouts as right-censored.

Recalibration maps (isotonic or Platt) are fitted per task on held-out patients from the period of intended use, versioned with the model, and checked on a later period. Akagi et al. (2026) showed the strongest version of the result: trained on University of Tokyo Hospital records from 2011 to 2022 and tested on 2023 admissions, the simulator kept observed-to-expected ratios close to 1 for eight tasks without recalibration. In monitoring, a monthly O/E and calibration slope per task are cheap to compute and are usually the first metrics to move.

Simulation Fidelity

Fidelity asks whether simulated timelines reproduce real statistics: incidence, event counts, lab values, inter-event times, code co-occurrence, length of stay. It catches what AUROC hides, such as readmissions generated at the wrong times (CEHR-GPT's time-token comparison). Kuo et al. (2026) add a warning: generators can match population-level marginals while distorting subgroup distributions and dependency structure, so fidelity should be checked within strata and, where possible, on the structure between variables rather than only on marginals.

Let \(T(f)\) be a statistic of a timeline: event count, a lab value, a gap between events, length of stay, or an indicator for a code. Fidelity compares its distribution under simulated futures with that under real futures. For continuous \(T\) the Kolmogorov–Smirnov distance \(D=\sup_t\lvert F_{\text{real}}(t)-F_{\text{sim}}(t)\rvert\) is standard; for token categories the total-variation distance \(\tfrac12\sum_v\lvert P(v)-Q(v)\rvert\). Stratified fidelity takes \(\max_s D_s\) over strata \(s\) (age, sex, site), and dependency fidelity compares co-occurrence matrices \(C_{ab}=\Pr(a\in f,\,b\in f)\). Matching marginals does not imply matching joints: two distributions can share every marginal while coupling variables differently, which is the failure Kuo et al. (2026) describe. A stricter, conditional test prompts the simulator with real histories and compares the sampled continuations with each patient's actual future.

import numpy as np
from scipy.stats import ks_2samp

rng = np.random.default_rng(3)
n = 6000
old = rng.random(n) < 0.45                               # age >= 65
real_gap = np.where(old, rng.exponential(12, n), rng.exponential(40, n))
# Simulator matches the pooled gap distribution but ignores age
sim_old = rng.random(n) < 0.45
sim_gap = rng.choice(real_gap, n)                        # marginal resampled, age link lost
print(f"pooled   KS {ks_2samp(real_gap, sim_gap).statistic:.3f}")
for label, r, s in [("age<65 ", ~old, ~sim_old), ("age>=65", old, sim_old)]:
    print(f"{label}  KS {ks_2samp(real_gap[r], sim_gap[s]).statistic:.3f}")
print(f"5% critical value ~ {1.36*np.sqrt(2/n):.3f} (pooled)")

Compares real and simulated time-to-readmission gaps when the simulator reproduces the pooled distribution but ignores the dependence of gaps on age, and prints KS distances overall and per age group.

pooled   KS 0.009
age<65   KS 0.183
age>=65  KS 0.218
5% critical value ~ 0.025 (pooled)

The pooled KS distance of 0.009 sits well under the 5% critical value of about 0.025, so a marginal check passes. Within age groups the distances are 0.183 and 0.218: the simulator lost the link between age and readmission timing, and only the stratified comparison shows it.

A fidelity report is a dashboard rather than one number: incidence per code, events per timeline, lab-quantile distributions, inter-event gaps, length of stay, and co-occurrence of frequent code pairs, each computed overall and by age, sex and site. Timing deserves its own panel; CEHR-GPT found readmissions generated at the wrong times only by comparing time tokens. Synthetic-EHR benchmarks such as Yan et al. (2022) score fidelity, utility and privacy together because improving one often costs another.

With hundreds of thousands of timelines every distance is statistically significant, so thresholds should be effect sizes calibrated against a real-versus-real baseline: the same distances computed between two disjoint samples of real patients. A simulated statistic that differs from real data by more than real data differs from itself is flagged. Fidelity checks reuse the stored rollouts and add little compute; the cost is in maintaining the statistic definitions as the vocabulary changes.

Subgroups and Fairness

A model that is accurate on average can be poorly calibrated for subgroups that are rare in training data or whose care differs. Delphi-2M's explainability analysis surfaced biases learned from UK Biobank, a population skewed toward healthier volunteers; CoMET's authors list the absence of subgroup analysis as a limitation; the federated ETHOS paper did not study fairness. Minimum practice: discrimination and calibration by sex, age, race and ethnicity, deprivation proxies and care setting, with confidence intervals.

For subgroup \(g\) with observed events \(O_g\) and expected events \(E_g=\sum_{i\in g}\hat p_i\), the overall ratio is a weighted average of subgroup ratios,

\[ \frac{O}{E}=\sum_g \frac{E_g}{E}\cdot\frac{O_g}{E_g}, \]

so a group carrying a small share of expected events can be badly miscalibrated while the overall ratio stays near 1. Treating \(O_g\) as Poisson gives an approximate 95% interval \((O_g\pm1.96\sqrt{O_g})/E_g\); subgroup AUROC intervals come from a stratified bootstrap that resamples positives and negatives separately. Interval width scales roughly with \(1/\sqrt{\min(n_{1g},n_{0g})}\), so a group with 50 events has intervals about four times wider than one with 800. With many groups and tasks, some intervals exclude the target by chance; a pre-specified list of groups and a minimum event count make the analysis interpretable.

import numpy as np
from scipy.stats import rankdata

def auroc(y, s):
    r = rankdata(s); y = y.astype(bool); n1 = y.sum()
    return (r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * (~y).sum())

def report(y, p, B=500, rng=np.random.default_rng(0)):
    """AUROC with stratified bootstrap 95% CI, and O/E with Poisson CI."""
    pos, neg = np.where(y == 1)[0], np.where(y == 0)[0]
    bs = [auroc(y[i], p[i]) for i in (np.r_[rng.choice(pos, len(pos)), rng.choice(neg, len(neg))] for _ in range(B))]
    O, E = y.sum(), p.sum()
    return auroc(y, p), np.percentile(bs, [2.5, 97.5]), O / E, ((O - 1.96*O**.5) / E, (O + 1.96*O**.5) / E)

rng = np.random.default_rng(4)
N = 30_000
z = rng.normal(-3.5, 1.3, N); p_true = 1 / (1 + np.exp(-z))
grp = np.where(rng.random(N) < 0.05, "minority", "majority")
p_model = np.where(grp == "minority", p_true / 2, p_true)    # under-predicts small group
y = rng.binomial(1, p_true)
print(f"overall   O/E {y.sum()/p_model.sum():.2f}")
for g in ["majority", "minority"]:
    m = grp == g
    a, ci, r, rci = report(y[m], p_model[m])
    print(f"{g:9s} n={m.sum():5d} events={y[m].sum():4d}  AUROC {a:.3f} [{ci[0]:.3f},{ci[1]:.3f}]  O/E {r:.2f} [{rci[0]:.2f},{rci[1]:.2f}]")

Builds a cohort in which a group of 5% of patients has its risk under-predicted by half, and prints AUROC with bootstrap interval and O/E with Poisson interval per group.

overall   O/E 1.03
majority  n=28525 events=1605  AUROC 0.806 [0.795,0.816]  O/E 1.00 [0.95,1.05]
minority  n= 1475 events=  95  AUROC 0.796 [0.748,0.846]  O/E 2.30 [1.84,2.76]

The overall O/E of 1.03 and the near-identical AUROCs (0.806 and 0.796) would pass a release gate, yet the minority group has O/E 2.30 with an interval of 1.84–2.76: its patients would receive risks less than half their true value.

The minimum practice is a table of discrimination and calibration with confidence intervals by sex, age band, race and ethnicity, deprivation proxies and care setting, for every task the model is released for. Some of these variables are poorly recorded in EHR data, and the data quality of the grouping variable must be reported alongside the metrics. Small groups usually need pooled test years to reach a usable event count.

Source populations shape what a model learns. Delphi-2M (Shmatko et al. 2025) was trained on UK Biobank, whose participants are healthier than the general population, and its explainability analysis surfaced biases from that source. Group-specific recalibration can repair levels (O/E) but not ranking within a group, and it builds group membership into the score, which needs clinical and ethical review. The durable fix is more representative training data and a subgroup report that is part of the release gate, not an appendix.

Privacy and Memorization

A generative model can memorize and regurgitate a real patient's timeline, especially a rare one. Tonekaboni et al. (2025) proposed black-box tests for memorization in structured-EHR foundation models at the level of both embeddings and generated outputs, aiming to separate harmful memorization from generalization, with attention to vulnerable subgroups, and released an open-source toolkit. Synthetic-data papers such as CEHR-GPT report membership-inference and attribute-inference attacks. Practical checks: nearest-neighbor distances from synthetic to training versus held-out timelines, exact-continuation tests from real prompts, and extra scrutiny of rare-code patients. Foresight removed concepts seen fewer than 100 times partly for this reason.

A membership-inference attack is a score \(A(x)\), for example the model's negative log-likelihood of timeline \(x\), used to decide whether \(x\) was in training. Its advantage is \(\mathrm{Adv}=\mathrm{TPR}-\mathrm{FPR}\) at the chosen threshold, or the AUROC of \(A\) on training versus held-out timelines; 0 and 0.5 respectively mean no leakage. Distance to closest record compares, for each synthetic timeline \(s\), \(d_{\text{train}}(s)=\min_{t}d(s,t)\) over training records with \(d_{\text{hold}}(s)\) over an equal-size held-out set; the share with \(d_{\text{train}} \lt d_{\text{hold}}\) is about 0.5 when nothing is copied. Continuation match prompts with the first \(k\) tokens of a timeline and measures how often greedy decoding reproduces the next \(m\) exactly, for training versus held-out prompts. Rare sequences dominate risk: Carlini et al. (2019) measure memorization of a unique sequence by its exposure, the log-rank of its likelihood among all candidates of the same form, which rises with how often it was seen.

import numpy as np

def jacc(a, b): return 1 - len(a & b) / len(a | b)

def dcr_share(synth, train, hold):
    """Share of synthetic records closer to a training record than to any held-out one."""
    out = []
    for s in synth:
        dt = min(jacc(s, t) for t in train); dh = min(jacc(s, h) for h in hold)
        out.append(0.5 if dt == dh else float(dt < dh))
    return np.mean(out)

rng = np.random.default_rng(5)
common, rare = np.arange(200), np.arange(200, 2200)
def patient():
    codes = set(rng.choice(common, 12)) | set(rng.choice(rare, 2))   # two rare codes each
    return frozenset(codes)
train = [patient() for _ in range(400)]; hold = [patient() for _ in range(400)]
fresh = [patient() for _ in range(200)]                 # generalizing generator
leaky = [frozenset(set(t) | {int(rng.integers(200))}) for t in train[:200]]  # near-copies
print(f"DCR share  fresh {dcr_share(fresh, train, hold):.2f}   near-copies {dcr_share(leaky, train, hold):.2f}")

Builds patients as sets of common and rare codes, then compares a generator of fresh patients with one that emits near-copies of training patients, printing the share of synthetic records closer to training than to held-out data.

DCR share  fresh 0.49   near-copies 1.00

Fresh records sit at 0.49, the no-copying value, while near-copies sit at 1.00: each is closer to its training source than to any held-out patient. The rare codes make each patient nearly unique, which is what lets a copy be identified.

Tonekaboni et al. (2025) released an open-source toolkit for black-box memorization tests on structured-EHR foundation models, covering embeddings and generated outputs and separating harmful memorization from generalization; it is a reasonable default for the privacy panel of a release review. CEHR-GPT reports membership- and attribute-inference attacks for its synthetic data. Work on language models (Carlini et al. (2021)) shows that larger models and duplicated training records memorize more, so deduplication of timelines before training is cheap insurance.

Two controls follow from the rare-code risk. Concepts below a frequency floor can be removed or merged, as Foresight did for concepts seen fewer than 100 times; and continuation-match and nearest-neighbor tests are run separately for patients with rare codes. Differential-privacy training gives formal guarantees at a cost in accuracy on exactly those rare patients. Model weights are themselves a channel for leakage, so access to them is governed like access to the training data when synthetic timelines or the model are shared outside the institution.

Temporal and Site Shift

Coding practice, formularies and care pathways change, so a model trained on 2015–2020 data may simulate care that no longer exists. Guo et al. (2023) found that EHR foundation-model representations were more robust to temporal distribution shift than count-based features, and MOTOR reported similar robustness. Generative models still need explicit tests: a temporal split (train on earlier years, test on later ones; Akagi et al. did this), and external validation at another site, as Delphi-2M did in Danish registries and TransformEHR did on MIMIC-IV. Site transfer for generative models is hard because vocabularies differ; RAVEN could use only about a quarter of rows when transferred zero-shot to the EHRSHOT benchmark.

A temporal split trains on records up to year \(T_0\) and evaluates on later years, estimating performance under the shift the model will actually meet. Shift takes three forms: covariate shift (\(P(x)\) changes, as when coding practice changes), label shift (\(P(Y)\) changes, as when outcomes improve), and concept shift (\(P(Y\mid x)\) changes, as when new treatments alter prognosis). Ranking often survives label shift while calibration does not. The simplest repair is an intercept update: choose \(a\) so that

\[ \frac1N\sum_i \operatorname{expit}\big(\operatorname{logit}\hat p_i + a\big)=\frac1N\sum_i y_i \]

on recent data, which restores calibration-in-the-large and leaves ranking unchanged. For a new site, the first quantity is vocabulary coverage, the share of the site's event tokens that map into the model's vocabulary: rows or events that cannot be mapped are lost before the model sees them, so coverage bounds what a zero-shot transfer can achieve.

import numpy as np
from scipy.stats import rankdata

def auroc(y, s):
    r = rankdata(s); y = y.astype(bool); n1 = y.sum()
    return (r[y].sum() - n1 * (n1 + 1) / 2) / (n1 * (~y).sum())
expit = lambda x: 1 / (1 + np.exp(-x)); logit = lambda p: np.log(p / (1 - p))

rng = np.random.default_rng(6)
years = np.arange(2019, 2025)
z = {t: rng.normal(-3.5, 1.3, 20_000) for t in years}
p_model = {t: expit(z[t]) for t in years}                       # trained on 2015-2018
y = {t: rng.binomial(1, expit(z[t] - 0.08 * (t - 2019))) for t in years}   # care improves
for t in years:
    print(t, f"AUROC {auroc(y[t], p_model[t]):.3f}  O/E {y[t].sum() / p_model[t].sum():.2f}")
a = 0.0                                                          # intercept update on 2023
for _ in range(20):
    q = expit(logit(p_model[2023]) + a); a -= (q.mean() - y[2023].mean()) / np.mean(q * (1 - q))
print(f"intercept update fitted on 2023: a = {a:+.3f};  2024 O/E after = "
      f"{y[2024].sum() / expit(logit(p_model[2024]) + a).sum():.2f}")

Applies a model trained on earlier years to 2019–2024 cohorts in which outcomes slowly improve, prints AUROC and O/E per year, then fits an intercept update on 2023 and checks it on 2024.

2019 AUROC 0.807  O/E 1.00
2020 AUROC 0.805  O/E 0.96
2021 AUROC 0.815  O/E 0.85
2022 AUROC 0.820  O/E 0.83
2023 AUROC 0.802  O/E 0.79
2024 AUROC 0.811  O/E 0.72
intercept update fitted on 2023: a = -0.280;  2024 O/E after = 0.92

AUROC stays between 0.80 and 0.82 in every year while O/E drifts from 1.00 to 0.72, so a discrimination-only monitor would see nothing. An intercept update fitted on 2023 moves 2024 to 0.92, closer but not at 1 because the drift continues; recalibration needs a cadence, not a single fix.

Representation-level robustness helps but does not settle the question. Guo et al. (2023) found EHR foundation-model features more robust to temporal shift than count-based features, and MOTOR reported similar robustness; a generative model still needs explicit temporal and site tests because it simulates care pathways, not only features. External validation has a sobering record in clinical prediction: the widely deployed Epic sepsis model performed much worse at an outside hospital than its developer reported (Wong et al. (2021)), and Finlayson et al. (2021) catalogue how changes in technology, population and behaviour silently degrade models.

Operational monitoring tracks inputs and outputs: token-frequency drift, the rate of out-of-vocabulary codes after a coding update, monthly O/E and slope per task, and rollout completion. Site transfer starts with mapping to a common data model and reporting coverage; RAVEN could use only about a quarter of rows when transferred zero-shot to the EHRSHOT benchmark. Retraining or recalibration is triggered by thresholds on these monitors, with each new version re-run through the full evaluation.

Clinical Utility

Utility asks whether acting on the model improves outcomes. Decision-curve analysis is the retrospective tool, silent prospective deployment the next step, and randomized evaluation the bar for claims of benefit. As of late 2026 I found no prospective clinical evaluation of a GPT-style health world model; ETHOS-ARES describes planned pilot simulations, and CoMET lists prospective validation as future work.

EvaluationMetricFailure it catches
DiscriminationAUROC, AUPRC, C-index; new-onset vs. recurrent splitModel cannot rank risk; metrics inflated by echoing chronic codes
CalibrationReliability diagram, calibration slope and intercept, observed/expected ratio, Brier scoreSimulation frequencies too extreme or shifted; sampling-temperature distortion
Rollout qualityTimeline completion rate, invalid-sequence rateRollouts truncated before outcome or horizon; censoring bias
Distribution fidelityIncidence and event-count comparison, KS distance on labs and gaps, co-occurrence statistics, LOS distributionPlausible-looking but statistically wrong futures; wrong timing
Subgroup performanceStratified AUROC and calibration with CIsGood average hides poor performance in under-represented groups
PrivacyMembership inference, nearest-neighbor distance, continuation-match testsSynthetic timelines leak training patients, especially rare ones
Temporal and site shiftPerformance on later years and external sitesModel simulates outdated or site-specific practice
Shortcut auditPerformance with leak-prone tokens masked (discharge codes, DRGs, post-outcome events)Model "predicts" from tokens recorded after the outcome was known
Interventional validityAgreement with randomized trials, counterfactual calibration under IPWConditioning mistaken for causation
Clinical utilityNet benefit, silent prospective evaluation, trialsAccurate predictions that do not change decisions or outcomes

Table. Evaluations for health world models, the metrics that implement them, and the failure each one catches. Rollout quality and shortcut audits follow the criteria proposed by Bedi, Fries & Shah (2026); interventional validity follows Keogh & van Geloven (2023).

Decision-curve analysis (Vickers & Elkin (2006)) scores a model at a treatment threshold \(t\), the risk at which a clinician is indifferent between acting and not acting. Flagging patients with \(\hat p\ge t\) gives

\[ \mathrm{NB}(t)=\frac{\mathrm{TP}(t)}{N}-\frac{\mathrm{FP}(t)}{N}\cdot\frac{t}{1-t}, \]

where the weight \(t/(1-t)\) converts false positives into the currency of true positives. The model is compared with treat-all, \(\mathrm{NB}=\pi-(1-\pi)\,t/(1-t)\) for prevalence \(\pi\), and treat-none, \(\mathrm{NB}=0\), across the range of plausible \(t\). Because the threshold is applied to the risk itself, net benefit depends on calibration, not only ranking: a model with perfect AUROC but inflated risks flags too many patients.

When the model is used to compare treatments, observed outcomes reflect the treatment actually given. Keogh & van Geloven (2023) evaluate counterfactual predictions by reweighting: patients whose observed treatment \(A_i\) matches strategy \(a\) receive weight \(w_i=1/\Pr(A_i=a\mid x_i)\), and calibration under \(a\) is assessed with \(\sum_i w_i\mathbb 1[A_i=a]\,y_i\big/\sum_i w_i\mathbb 1[A_i=a]\,\hat p_i(a)\). This requires positivity (each strategy has some chance of being chosen for every patient) and no unmeasured confounding. Randomized trials remain the only evaluation of benefit that does not rest on these assumptions.

import numpy as np

def net_benefit(y, p, t):
    """Decision-curve net benefit: TP/N - FP/N * t/(1-t)."""
    flag = p >= t; N = len(y)
    return (flag & (y == 1)).sum() / N - (flag & (y == 0)).sum() / N * t / (1 - t)

rng = np.random.default_rng(7)
N = 30_000
p_true = 1 / (1 + np.exp(-rng.normal(-4.2, 1.4, N))); y = rng.binomial(1, p_true)
p_good = p_true
p_high = 1 / (1 + np.exp(-np.log(p_true / (1 - p_true)) - 1.5))   # same ranking, risks ~4x too high
print(f"prevalence {y.mean():.3f}")
for t in [0.05, 0.10, 0.20]:
    print(f"t={t:.2f}  calibrated {net_benefit(y, p_good, t):+.4f}  miscalibrated {net_benefit(y, p_high, t):+.4f}"
          f"  treat-all {net_benefit(y, np.ones(N), t):+.4f}  treat-none +0.0000")

Compares the net benefit of calibrated risks with that of risks roughly four times too high but identically ranked, at three treatment thresholds, against treat-all and treat-none.

prevalence 0.033
t=0.05  calibrated +0.0126  miscalibrated +0.0022  treat-all -0.0182  treat-none +0.0000
t=0.10  calibrated +0.0072  miscalibrated -0.0094  treat-all -0.0748  treat-none +0.0000
t=0.20  calibrated +0.0027  miscalibrated -0.0178  treat-all -0.2091  treat-none +0.0000

Both scores have the same AUROC, yet at \(t=0.10\) the calibrated model has positive net benefit (+0.0072) while the inflated one is below treat-none (−0.0094): acting on it would do more harm than doing nothing. At \(t=0.20\) the gap widens. Net benefit, unlike AUROC, registers the miscalibration as clinical cost.

The path to a claim of benefit has three steps. Retrospective decision curves show whether any threshold range gives positive net benefit. A silent prospective deployment runs the model on live data, logs its outputs without showing them, and later compares them with outcomes; it measures what retrospective data cannot, including latency of generating rollouts at the point of care, missing or late-arriving data, rollout completion on live histories, and drift since training. Only then does a randomized or stepped-wedge evaluation test whether showing the output changes decisions and outcomes.

No GPT-style health world model has yet completed the second or third step in the published record: ETHOS-ARES describes planned pilot simulations, and CoMET lists prospective validation as future work. For reporting, TRIPOD-LLM (Gallifant et al. (2025)) extends TRIPOD+AI to studies that use large language models in health care. The full checklist in the table is a release gate in its own right: each row has a metric, a pass threshold set before the evaluation runs, and an owner who signs off. The rows that most often go unreported, rollout quality, shortcut audits and interventional validity, are those that separate a simulator that can be trusted for decisions from one that only ranks patients well.

Reference Architecture

A production GPT-style health world model is a pipeline of seven stages, and most of the engineering effort sits outside the transformer: getting records into a standard event format, building timelines, fitting the tokenizer, and evaluating and governing the outputs. The diagram below is the architecture I would start from, assembled from the ETHOS-ARES, CoMET and MEDS designs.

Reference architecture for a GPT-style health world model. Data sources EHR, claims, registries → OMOP / MEDS events (subject, time, code, value) Timeline builder sort, harmonize codes patient-level splits temporal holdout Tokenizer code splitting, deciles time-gap tokens fit on train only Decoder-only model next-token pretraining long context checkpoints, versioned Sampler K rollouts, KV cache stop tokens, horizons temperature policy Outcome estimators task specs: prompt cut, stop rule, outcome tokens p̂ ± SE, LOS, counts Evaluation discrimination, calibration fidelity, subgroups privacy, shift Use risk dashboards synthetic data trial emulation GOVERNANCE · data use agreements · memorization tests · model cards · drift monitoring · regulatory pathway
Fig. Reference architecture. Records are standardized into an event format (OMOP or MEDS), built into patient timelines with patient-level and temporal splits, tokenized with a vocabulary fitted on training data, and used to pretrain a decoder. At inference a sampler runs \(K\) rollouts under task specifications; estimators turn rollouts into risks and quantities; evaluation gates every use. Governance spans all stages. Original diagram.

Two interfaces deserve to be stable contracts. The event format between data and timeline builder: the MEDS standard (McDermott et al., NEJM AI 2026), adopted across 21 institutions in 12 countries, is a lightweight longitudinal event representation designed to complement OMOP rather than replace it, and ETHOS-ARES runs on it. And the task specification between sampler and estimators: a declarative definition of the prompt cut point, stop rule, horizon and outcome tokens, analogous to how ACES (Xu et al., ICLR 2025) defines cohorts and labels over event streams. Keeping tasks declarative is what lets one model serve dozens of questions without new code per task.

Each stage is a typed map, and the types show where the contracts sit. An event is a tuple \(e = (s, t, c, v)\): subject, timestamp, code and optional numeric value. The timeline builder groups events by subject into \(E_s\) and assigns each subject to one split, with patient-level disjointness \(\mathcal{S}_{\text{train}} \cap \mathcal{S}_{\text{test}} = \varnothing\) and a temporal holdout \(\mathcal{S}_{\text{hold}} = \{ s : t_{s,1} \ge t^\ast \}\) that informs no modelling decision.

The tokenizer \(\tau_\psi\) maps an event to a few tokens. Its parameters \(\psi\) (vocabulary, decile edges per code-unit pair, time-gap bins) must be a function of training subjects alone. The decoder minimizes \(\mathcal{L}(\theta) = -\sum_s \sum_i \log p_\theta(x_{s,i} \mid x_{s,\lt i})\).

A task specification is \(\tau = (t_{\text{pred}}, H, \mathcal{O}, \mathcal{T})\): prediction time, horizon, outcome tokens, stop tokens. With \(a_i\) the time token \(i\) became available, the prompt is \(x_{1:c}\), \(c = \max\{ i : a_i \lt t_{\text{pred}} \}\). The sampler draws \(K\) continuations, each stopped at the first token in \(\mathcal{O} \cup \mathcal{T}\), at horizon \(H\) or at a token budget. With \(K_{\text{done}}\) resolved rollouts,

\[ \hat p_\tau = \frac{1}{K_{\text{done}}} \sum_{k=1}^{K} \mathbb{1}\big[\tilde x^{(k)} \text{ reaches } \mathcal{O} \text{ first}\big], \qquad \widehat{\mathrm{SE}} = \sqrt{\hat p_\tau (1 - \hat p_\tau) / K_{\text{done}}}. \]

This is unbiased for the model's probability only at temperature 1 without truncation and with few incomplete rollouts, since discarding them favours fast outcomes.

Cost. Training costs about \(6ND\) operations per pass for \(N\) parameters and \(D\) tokens, about \(10^{17}\) for ETHOS-ARES (\(N \approx 4.5 \times 10^7\), \(D \approx 3.6 \times 10^8\)). A question costs about \(2N(c + K\bar L)\) with a key-value cache, \(\bar L\) being the mean rollout length, so stop rules and horizons are compute decisions too. One model serves many tasks because \(\tau\) enters through the prompt cut and the indicator, never through \(\theta\).

The script below runs the whole pipeline in miniature on synthetic admissions, with the two contracts made explicit. Events are MEDS-style tuples (subject_id, time, code, value); the lab code carries its unit (LAB//lactate//mmol/L) so that decile edges are keyed on the code-unit pair. The timeline builder holds out every patient whose record starts in the final year and splits the rest by patient. The tokenizer fits its decile edges on training patients only. TaskSpec is a frozen dataclass, so a task can be hashed, versioned and logged with each prediction, and the prompt keeps only events strictly before the prediction time. A toy rule stands in for the trained decoder: its probability of a death token rises with the lactate decile. The estimator applies the task's outcome, stop and horizon rules to \(K = 64\) rollouts and returns the risk, its binomial standard error and the incomplete-rollout rate.

"""Health world-model pipeline in miniature: MEDS-style events -> splits -> tokenizer
fitted on training patients only -> declarative task spec -> Monte Carlo estimator."""
import numpy as np
from dataclasses import dataclass

rng = np.random.default_rng(0)
# 1. Events: (subject_id, time_h, code, value); value is NaN for non-numeric codes.
events = []
for sid in range(1000):
    t0 = rng.uniform(0, 5 * 365 * 24)                       # admission time over 5 years
    lac = rng.lognormal(0.3, 0.5)                           # lactate, mmol/L
    events += [(sid, t0, "ADMIT", np.nan), (sid, t0 + 2, "LAB//lactate//mmol/L", lac)]
    died = rng.uniform() < min(0.9, 0.03 * lac ** 2)
    events.append((sid, t0 + rng.uniform(30, 200), "DEATH" if died else "DISCHARGE", np.nan))

# 2. Timeline builder: patient-level split plus a temporal holdout (last year).
holdout_start = 4 * 365 * 24
first_t = {}
for s, t, _, _ in events: first_t[s] = min(first_t.get(s, t), t)
pool = np.array([s for s in first_t if first_t[s] < holdout_start])
rng.shuffle(pool)
train = set(pool[: int(0.8 * len(pool))].tolist())
holdout = {s for s in first_t if first_t[s] >= holdout_start}
assert not train & holdout

# 3. Tokenizer: decile edges per (code, unit), fitted on training patients only.
train_lac = [v for s, t, c, v in events if s in train and c.startswith("LAB//lactate")]
edges = np.quantile(train_lac, np.linspace(0.1, 0.9, 9))
def tokenize(code, value):
    if np.isnan(value): return [code]
    return [code, f"Q{int(np.searchsorted(edges, value)) + 1}"]

# 4. Task specification: a declarative contract between sampler and estimator.
@dataclass(frozen=True)
class TaskSpec:
    name: str
    cut_after_h: float          # prediction time, hours after admission
    horizon_h: float
    outcome: frozenset
    stop: frozenset

def prompt(sid, spec):
    ev = sorted((t, c, v) for s, t, c, v in events if s == sid)
    t_pred = ev[0][0] + spec.cut_after_h
    return [tok for t, c, v in ev if t < t_pred for tok in tokenize(c, v)]  # strictly before

# 5. Sampler stand-in: a toy next-token rule, then the estimator with its standard error.
def rollout(toks, rng):
    q = int(toks[-1][1:]) if toks[-1].startswith("Q") else 5
    p_death = 0.02 + 0.035 * q                               # higher decile, higher risk
    return [("DEATH" if rng.uniform() < p_death else "DISCHARGE", rng.uniform(30, 200))]

def estimate(spec, toks, K, rng):
    hits = done = 0
    for _ in range(K):
        for tok, dt in rollout(toks, rng):
            if dt > spec.horizon_h: done += 1; break
            if tok in spec.outcome: hits += 1; done += 1; break
            if tok in spec.stop: done += 1; break
    p = hits / done
    return p, np.sqrt(p * (1 - p) / done), 1 - done / K

spec = TaskSpec("hospital_mortality", 24, 24 * 30, frozenset({"DEATH"}), frozenset({"DISCHARGE"}))
sid = sorted(holdout)[0]
toks = prompt(sid, spec)
p, se, inc = estimate(spec, toks, K=64, rng=rng)
print(f"train={len(train)} holdout={len(holdout)} edges[0]={edges[0]:.2f}")
print(f"prompt={toks}  p_hat={p:.3f} SE={se:.3f} incomplete={inc:.0%}")

Running it prints train=648 holdout=190 edges[0]=0.73 and then prompt=['ADMIT', 'LAB//lactate//mmol/L', 'Q7'] p_hat=0.312 SE=0.058 incomplete=0%. The discharge or death event falls after the 24-hour cut and is excluded from the prompt, which is the property a leakage test should assert. Replacing rollout with a call to a trained model changes nothing else: the task specification, the split logic and the estimator are the stable parts. With 64 rollouts the standard error is still about 0.06, a reminder that a single patient's simulated risk is a noisy number even when the population AUROC is high.

In production the seven stages become separately owned services and the two contracts become versioned artifacts. Most incidents start where a contract was left implicit: nothing crashes, and predictions drift.

Event contract. Beyond the MEDS columns, two fields pay for themselves: the unit of every measurement, so that a laboratory switching creatinine from mg/dL to µmol/L yields an unknown code-unit pair rather than a silent jump to the top decile; and the time each record became available. Diagnosis-related groups and discharge diagnoses carry the stay's clinical time but arrive days later, so prompts must be cut on availability time.

Model bundle and sampler. Tokenizer statistics and weights ship as one artifact, and serving refuses requests whose vocabulary version differs. Task specifications live in a registry in the style of ACES, hashed and logged with every output. Rollouts dominate inference: CoMET typically ran 20 to 80 simulations per question, with gains mostly plateauing around 64 (Waxler et al. 2025). Paged key-value caches with shared prompt prefixes (Kwon et al. 2023) let \(K\) rollouts reuse one encoded prompt, and early stopping at outcome or stop tokens removes wasted tokens.

BoundaryContractMonitor
Data → timelineVersioned code maps, units, availability timesUnknown-code rate per site; new units
Timeline → tokenizerStatistics fitted on training patientsToken-type histogram against training
Model → samplerTemperature 1, stop tokens, token budgetIncomplete-rollout rate; tokens per query
Estimators → useGate passed for this task and versionMonthly observed/expected by subgroup

Table. Contracts and monitors at the boundaries of the health reference architecture. Alert thresholds are set per deployment.

Governance spans the rows: ETHOS-ARES released code but not weights, and memorization tests precede any release of synthetic timelines.

Production Challenges and Solutions

The challenges below are the ones the papers in this half report or that follow directly from their designs; each maps to a concrete mitigation.

ChallengeWhy it bitesSolutions
Data standardizationEvery site codes differently; a vocabulary fitted at one hospital does not transferConvert to OMOP or MEDS first; map to standard vocabularies (ICD-10, ATC, LOINC); keep site-specific codes behind a mapping layer
Vocabulary sizeRaw code sets reach tens of thousands of tokens with a long tailHierarchical code splitting (ETHOS, CoMET); frequency cutoffs (Foresight dropped concepts seen under 100 times); decile tokens for numbers
Long contextsLifetime records exceed 2K–8K tokens; CoMET notes truncated historiesPin static tokens at the start of every window (ETHOS); summary tokens for distant history; longer-context architectures; next-visit set prediction (RAVEN)
ComputeTraining is data-hungry (about 1,000 tokens per parameter for CoMET); inference is K rollouts per questionSize the model to the data; KV caching and early stopping; read next-token probabilities when the outcome is one step away; adaptive K
Rare eventsMonte Carlo variance is large at low prevalence; rare codes are under-trainedMore samples for borderline patients; importance sampling; report AUPRC; consider time-to-event heads (MOTOR) for fixed rare outcomes
CalibrationRollout frequencies need not be probabilities; truncated sampling distorts themSample at temperature 1 for estimation; recalibrate on held-out data (isotonic or Platt); monitor observed/expected over time
Leakage and shortcutsTokens recorded after the outcome (DRGs, discharge codes) can leak the answerCut prompts strictly before the prediction time; audit with leak-prone tokens masked
PrivacyGenerated timelines can reproduce real patients; weights may memorizeMemorization tests before release; rare-code suppression; restricted weight sharing (ETHOS-ARES did not release weights); federated or synthetic training
Causal misuseUsers read "insert drug token" as a treatment effectExpose only forecasting outputs by default; route "what if" questions through trial-emulation designs; positivity checks
Regulatory statusClinical risk outputs can be regulated device software; model updates change behaviorClassify intended use early; in the US, plan updates under a predetermined change control plan per FDA's December 2024 final guidance

Table. Production challenges for GPT-style health world models and concrete solutions. Regulatory details vary by jurisdiction; the FDA guidance on predetermined change control plans for AI-enabled devices was finalized in December 2024 (Ropes & Gray 2024).

Most rows of the challenge table reduce to a quantity that can be computed before or after training.

Vocabulary. A hierarchical code with levels of sizes \(n_1, \ldots, n_d\) has up to \(\prod_j n_j\) whole-code tokens but only \(\sum_j n_j\) tokens when each level is a separate token, at the cost of \(d\) tokens per event instead of one. Rare codes then share embeddings with their parent category. A frequency cutoff keeps codes with count \(n_c \ge n_{\min}\); Foresight used \(n_{\min} = 100\). Decile tokens replace a continuous value \(v\) with \(\min\{ j : v \le q_{c,u,j} \}\), losing resolution within each tenth of the distribution.

Context. With window \(W\) and \(S\) pinned static tokens, a prompt of length \(c > W\) keeps \(x_{1:S}\) and the most recent \(W - S\) tokens; everything in between is invisible to the model. The fraction of prompts with \(c > W\) per task is the quantity to report.

Compute. Training costs about \(6ND\) operations for \(N\) parameters and \(D\) tokens; CoMET's isoFLOP sweeps put the compute-optimal ratio near \(D/N \approx 1{,}000\). A question costs about \(2N(c + K \bar L)\) with caching. When the outcome is the next token (\(\bar L = 1\)), \(p_\theta(x_{c+1} \in \mathcal{O} \mid x_{1:c})\) is read directly and \(K\) drops to 1.

Rare events. From \(K\) independent rollouts, \(\mathrm{SE} = \sqrt{p(1-p)/K}\) and the relative error is \(\mathrm{SE}/p = \sqrt{(1-p)/(pK)}\), so holding relative error at \(r\) requires \(K \approx (1-p)/(p r^2)\): 20% relative error at \(p = 0.01\) needs about 2,475 rollouts.

Relative standard error of a Monte Carlo risk estimate against outcome probability for three rollout counts. 5% 10% 20% 50% 100% 200% 0.005 0.01 0.02 0.05 0.1 0.2 0.5 outcome probability p (log scale) relative SE = SE / p K = 20 K = 64 K = 256 20% relative error
Fig. Relative standard error \(\sqrt{(1-p)/(pK)}\) of a Monte Carlo risk estimate. At \(K = 64\) the error falls below 20% only for \(p\) above about 0.28; at \(p = 0.01\) every curve is far above it. Computed from the formula.

Calibration. A score is calibrated if \(\Pr(Y = 1 \mid \hat p = q) = q\). Expected calibration error over \(B\) bins is \(\mathrm{ECE} = \sum_b \tfrac{n_b}{n} \lvert \bar y_b - \bar p_b \rvert\). Top-\(p\) sampling replaces \(p_\theta\) at every step by its renormalized nucleus; an outcome whose per-step probability \(\varepsilon\) lies outside the nucleus has estimated risk exactly zero, whereas its true \(T\)-step risk is \(1 - (1-\varepsilon)^T\). Isotonic regression fits the monotone map \(g\) minimizing \(\sum_i (y_i - g(\hat p_i))^2\) on held-out data.

Leakage, privacy, drift. A prompt is leak-free if every token satisfies \(a_i \lt t_{\text{pred}}\) in availability time. A memorization screen compares nearest-neighbour distances from generated timelines to training timelines against distances from held-out timelines to training; systematically smaller distances indicate copying. Drift monitoring tracks \(O/E\) with \(E = \sum_i \hat p_i\), whose standard error under a Poisson approximation is about \(1/\sqrt{E}\).

Three diagnostics from the challenge table fit in one short script, each operating on plain arrays so that it can run on logged outputs of a real system. Part (a) builds about 26,000 synthetic ICD-10-style codes of the form A12.34 and compares a whole-code vocabulary with a split vocabulary of category, first-suffix and second-suffix tokens, the scheme ETHOS and CoMET use for diagnoses. Part (b) asks how top-\(p\) truncation changes a rollout-based risk: at each of 50 steps an outcome token has probability \(\varepsilon\) and the remaining mass follows a steep power law, and the exact 50-step risk is computed with and without a 0.9 nucleus. Part (c) simulates an overconfident model whose true risk is the square of its score, measures expected calibration error, fits an isotonic map with the pool-adjacent-violators algorithm on one half of the data and evaluates on the other half.

"""Three production diagnostics: vocabulary size under code splitting, rare-outcome
bias from top-p sampling, and calibration repair (ECE before and after isotonic)."""
import numpy as np
rng = np.random.default_rng(0)

# (a) Vocabulary: ICD-10-like codes "A12.3x" as one token each vs. split into pieces.
cats = [f"{chr(65 + rng.integers(26))}{rng.integers(100):02d}" for _ in range(1500)]
codes = {f"{c}.{rng.integers(10)}{rng.integers(10)}" for c in cats for _ in range(20)}
split_vocab = {c[:3] for c in codes} | {"." + c[4] for c in codes} | {"_" + c[5] for c in codes}
print(f"(a) whole-code vocab {len(codes)}, split vocab {len(split_vocab)}")

# (b) Top-p truncation: the outcome token has probability eps at each of T steps.
def step_dist(eps, n=200):
    w = 1 / np.arange(1, n) ** 2.0; w = (1 - eps) * w / w.sum()
    return np.concatenate([[eps], w])                 # index 0 = outcome token
def risk(eps, T, top_p=None):
    p = step_dist(eps)
    if top_p is not None:
        order = np.argsort(-p); keep = np.cumsum(p[order]) - p[order] < top_p
        q = np.zeros_like(p); q[order[keep]] = p[order[keep]]; p = q / q.sum()
    return 1 - (1 - p[0]) ** T
for eps in (0.05, 0.004):
    print(f"(b) eps={eps}: 50-step risk, full sampling {risk(eps, 50):.3f}, top-p 0.9 {risk(eps, 50, 0.9):.3f}")

# (c) Calibration: scores whose true risk is score**2; isotonic map fitted on half.
def ece(p, y, bins=10):
    idx = np.minimum((p * bins).astype(int), bins - 1)
    return sum(abs(p[idx == b].mean() - y[idx == b].mean()) * (idx == b).mean()
               for b in range(bins) if (idx == b).any())
def isotonic_fit(p, y):                               # pool-adjacent-violators
    o = np.argsort(p); out = []
    for x, v in zip(p[o], y[o].astype(float)):
        out.append([v, 1.0, x])
        while len(out) > 1 and out[-2][0] > out[-1][0]:
            m2, w2, x2 = out.pop(); m1, w1, _ = out.pop()
            out.append([(m1 * w1 + m2 * w2) / (w1 + w2), w1 + w2, x2])
    return np.array([b[2] for b in out]), np.array([b[0] for b in out])
s = rng.uniform(size=20000); y = rng.uniform(size=20000) < s ** 2
xk, yk = isotonic_fit(s[:10000], y[:10000])
cal = yk[np.minimum(np.searchsorted(xk, s[10000:]), len(xk) - 1)]
print(f"(c) ECE {ece(s[10000:], y[10000:]):.3f} -> {ece(cal, y[10000:]):.3f} after isotonic")

Output: (a) whole-code vocab 25815, split vocab 1148; (b) eps=0.05: 50-step risk, full sampling 0.923, top-p 0.9 0.940 and (b) eps=0.004: 50-step risk, full sampling 0.182, top-p 0.9 0.000; (c) ECE 0.165 -> 0.009 after isotonic. Splitting shrinks the vocabulary more than twentyfold. Truncation does not simply shrink every risk: an outcome inside the nucleus is renormalized upward, while one outside it vanishes, so a rare outcome with an 18% true risk is reported as impossible. That asymmetry is why estimation uses temperature 1 without truncation. The isotonic map must be fitted on validation patients and evaluated on others; fitting and scoring on the same patients makes ECE near zero by construction.

Operating a health world model means turning each row of the challenge table into a signal that is computed on every model version and every monitoring window, with a rule that blocks release or pages an owner. The signals below are cheap relative to the incidents they catch.

ChallengeDiagnostic signalTypical action when it moves
StandardizationUnknown-code and unknown-unit rate per siteExtend the mapping layer before scoring the site
Vocabulary, long contextValidation loss per token type; fraction of prompts truncated per taskAdjust splitting depth or window policy
Compute, rare eventsGenerated tokens and GPU-seconds per query; relative SE per taskAdaptive \(K\) near decision thresholds; direct next-token readout
CalibrationECE and observed/expected ratio by month and subgroupCheck sampler settings first, then refit recalibration
LeakageAUROC change when leak-prone tokens are maskedBlock release; recut prompts on availability time
PrivacyNearest-neighbour and exact-continuation tests on generated timelinesSuppress rare codes; withhold synthetic release
Causal misuse, regulationAudit of API calls that edit prompts; change log against the planRoute to trial emulation; file the change under the plan

Table. Diagnostic signals for the production challenges of health world models. Thresholds are set per deployment.

Ordering the diagnosis. When calibration drifts, the cheapest explanation is usually a serving change, not the model: a switch to top-\(p\) sampling to save tokens leaves AUROC unchanged while removing low-probability branches, so a calibration metric, not AUROC, is the one that detects it. Re-running a validation sample at temperature 1 separates a sampling cause from data drift in one job. When AUROC improves suspiciously after a pipeline change, the masked-token audit comes first; a gain that disappears with leak-prone tokens masked was never real.

Costs of the remedies. Recalibration needs held-out outcomes and must be refitted after every model or sampler update. Leakage audits need a maintained list of leak-prone codes written by people who know the source systems. Memorization testing scales with the number of generated timelines; the open toolkit from Tonekaboni et al. (2025) covers both embedding-level and generation-level probes. Federated training (Renc et al. 2025) reduces data movement but adds a synthetic-data fidelity problem. Calibration repair follows standard practice, isotonic or Platt scaling (Niculescu-Mizil and Caruana 2005), and is only as good as the validation cohort's resemblance to the deployed population.

Regulatory updates. Under FDA's December 2024 final guidance, a device that will change after clearance describes the planned modifications, their validation and their impact assessment in advance (Ropes & Gray 2024). For a world model this means that retraining on a new data year, refitting the tokenizer or changing the sampler should each be named in the plan, with the gate metrics that will validate them.

A Step-by-Step Playbook

The fastest path to a credible GPT-style health world model is to reproduce ETHOS-ARES on public data first, then move to your own data with the evaluation harness already in place. The steps below assume a team with access to MIMIC-IV and, later, an institutional EHR extract.

  1. Define the questions. Write 5–10 task specifications (prompt cut, stop rule, horizon, outcome tokens) and the decision each informs.
  2. Standardize the data. Extract to MEDS (or OMOP, then MEDS); make patient-level splits and a temporal holdout year that no model sees until the end.
  3. Reproduce a baseline. Run the open ethos-ares pipeline on MIMIC-IV and match its reported AUROCs, alongside a tabular baseline such as MEDS-Tab, to validate the infrastructure.
  4. Design the tokenizer. Time bins at the resolution your tasks need, decile edges per lab-unit pair, code-splitting depth; fit everything on training patients only.
  5. Size and train. CoMET's roughly 1,000 tokens per parameter is a starting heuristic, not a law. Track validation loss per token type.
  6. Build sampler and estimators. Batched rollouts with a KV cache, stop rules, time budgets, completion-rate logging, and \(K\) chosen from a standard-error target.
  7. Evaluate with the full table, recalibrate if needed, and re-check by subgroup.
  8. Deploy silently, then decide on clinical exposure under the applicable regulatory pathway, with drift monitoring.

Order matters: starting from task specifications and an evaluation harness catches leakage, calibration and causal problems before results look good, not after.

Several playbook steps are sizing decisions that can be computed before training. Each task specification from step 1 should carry the decision threshold \(p^\ast\) it informs and a tolerable standard error \(s\) near it; both feed the calculations below.

Holdout and reproduction (steps 2–3). An AUROC \(A\) from \(n_1\) positives and \(n_0\) negatives has approximate standard error (Hanley and McNeil 1982)

\[ \mathrm{SE}(A) \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}. \]

At \(A = 0.94\), the ETHOS-ARES hospital-mortality figure, with 2,000 negatives this is about 0.023 for 50 deaths and 0.008 for 400. A reproduction matches when it lies within about two standard errors of the published value, and the holdout year needs enough events for its own estimate to be informative.

Size (step 5). CoMET's compute-optimal ratio was near \(D/N \approx 1{,}000\). ETHOS-ARES trained about 45M parameters on about 361M tokens, \(D/N \approx 8\), deep in the data-limited regime, where \(N\) is chosen by validation loss with early stopping on the available \(D\).

Sampling (step 6). \(K = \lceil p(1-p)/s^2 \rceil\), at most \(\lceil 1/(4s^2) \rceil\): 57 rollouts for \(p = 0.10\), \(s = 0.04\); 625 for \(s = 0.02\) in the worst case. A two-stage rule spends the larger budget only near \(p^\ast\).

Silent deployment (step 8). With expected events \(E = \sum_i \hat p_i\), \(\mathrm{SE}(O/E) \approx 1/\sqrt{E}\). At \(E = 200\) it is about 0.071, so \(O/E = 1.15\) is a signal and 1.05 is noise; the monitoring window is set by expected events, not the calendar.

A pre-release checklist for a health world model is most useful when it is executable. The script below encodes it as a release gate: each check is a predicate over a release manifest, a structured record written by the pipeline that states what was done (split identifiers, the patients the tokenizer was fitted on, vocabulary versions, task specifications, sampler settings, model-card fields, the monitoring plan and the regulatory classification). The fifteen checks cover data (patient-level splits, an untouched temporal holdout, tokenizer statistics from training patients only, a pinned vocabulary), tasks (a written specification for each, prompts whose latest available record precedes the prediction time), sampling (temperature 1 without truncation, \(K\) at least the value implied by a standard-error target, incomplete-rollout rate reported), metrics (a tabular baseline on the same cohort, recalibration fitted on validation data), causal scope (outputs declared as forecasts under usual care) and governance (a complete model card, an observed/expected monitoring window with enough expected events, a recorded regulatory class). Missing evidence fails the gate rather than passing silently.

"""Playbook sizing plus the pre-release checklist as an executable release gate."""
import math

def k_for_se(p, se):                      # rollouts for a binomial SE target
    return math.ceil(p * (1 - p) / se ** 2)

def oe_se(expected_events):               # Poisson SE of observed/expected
    return 1 / math.sqrt(expected_events)

CHECKS = {   # name: predicate over a release manifest (one entry per checklist line)
  "splits_by_patient":     lambda m: not set(m["train_ids"]) & set(m["test_ids"]),
  "holdout_untouched":     lambda m: m["holdout_evals_before_release"] == 0,
  "tokenizer_fit_train":   lambda m: m["tokenizer_fit_ids"] <= set(m["train_ids"]),
  "vocab_pinned":          lambda m: m["vocab_version"] == m["serving_vocab_version"],
  "task_specs_written":    lambda m: all(t.get("spec") for t in m["tasks"]),
  "prompt_before_t_pred":  lambda m: all(t["max_prompt_avail_h"] < t["t_pred_h"] for t in m["tasks"]),
  "temp1_no_truncation":   lambda m: m["sampler"] == {"temperature": 1.0, "top_p": 1.0},
  "K_from_se_target":      lambda m: all(t["K"] >= k_for_se(t["p_ref"], t["se_target"]) for t in m["tasks"]),
  "incomplete_reported":   lambda m: all("incomplete_rate" in t for t in m["tasks"]),
  "baseline_same_cohort":  lambda m: all("baseline_auroc" in t for t in m["tasks"]),
  "recal_on_validation":   lambda m: m["recal_fit_split"] == "validation",
  "forecast_scope_stated": lambda m: "usual care" in m["model_card"].get("scope", ""),
  "model_card_complete":   lambda m: {"data_period", "population", "intended_use",
                                       "failure_modes"} <= m["model_card"].keys(),
  "oe_monitoring_plan":    lambda m: m.get("oe_window_expected_events", 0) >= 100,
  "regulatory_recorded":   lambda m: bool(m.get("regulatory_class")),
}

def gate(manifest):
    fails = []
    for name, ok in CHECKS.items():
        try:
            if not ok(manifest): fails.append(name)
        except KeyError:
            fails.append(name + " (missing)")           # absent evidence fails the gate
    return fails

task = {"spec": "mortality@24h", "max_prompt_avail_h": 23.5, "t_pred_h": 24, "K": 64,
        "p_ref": 0.10, "se_target": 0.04, "incomplete_rate": 0.003, "baseline_auroc": 0.887}
m = {"train_ids": range(0, 800), "test_ids": range(800, 1000), "holdout_evals_before_release": 0,
     "tokenizer_fit_ids": set(range(0, 800)), "vocab_version": "v3", "serving_vocab_version": "v3",
     "tasks": [task], "sampler": {"temperature": 1.0, "top_p": 1.0}, "recal_fit_split": "validation",
     "model_card": {"scope": "forecasts under usual care", "data_period": "2008-2019",
                    "population": "adult admissions", "intended_use": "research",
                    "failure_modes": "see section 4"},
     "oe_window_expected_events": 200, "regulatory_class": "non-device research use"}
print("K for SE 0.04 at p=0.10:", k_for_se(0.10, 0.04), "| O/E SE at E=200:", round(oe_se(200), 3))
print("clean manifest fails:", gate(m))
m2 = dict(m, sampler={"temperature": 1.0, "top_p": 0.9}, tasks=[dict(task, max_prompt_avail_h=30)])
del m2["regulatory_class"]
print("bad manifest fails:", gate(m2))

Output: K for SE 0.04 at p=0.10: 57 | O/E SE at E=200: 0.071, then clean manifest fails: [] and bad manifest fails: ['prompt_before_t_pred', 'temp1_no_truncation', 'regulatory_recorded']. The failing manifest has three realistic defects: a prompt that includes a record available only 30 hours after admission for a 24-hour prediction, a sampler switched to top-\(p\) 0.9, and no recorded regulatory class. In continuous integration the gate runs on every candidate checkpoint after the evaluation jobs write the manifest; the model registry promotes only on an empty failure list and stores the manifest with the decision so that a later audit can reproduce it.

In production the playbook becomes a release process in which every step leaves an artifact a reviewer can check: task specifications with thresholds, a split manifest, a reproduction report, a tokenizer bundle, per-token-type validation curves, a sampler configuration, an evaluation table and a monitoring plan. The order is a cost control: a defect caught in a specification costs hours, one caught after training costs accelerator days.

Reproduction as an infrastructure test. ETHOS-ARES reports hospital-mortality AUROC 0.940 against 0.887 for MEDS-Tab. A rerun of ethos-ares far from either number usually points to a different MIMIC-IV version, cohort definition or prompt cut, which is far cheaper to find on public data than on an institutional extract.

Gates written before results. A gate defined after a promising run tends to certify that run. Thresholds belong in step 1, and a gate should fail at least one known-bad earlier checkpoint.

Silent deployment tests what retrospective evaluation cannot: whether live availability times match those assumed in training, whether latency and incomplete-rollout rates hold at real volume, and whether observed/expected ratios stay near 1 by subgroup. As of late 2026 no prospective clinical evaluation of a GPT-style health world model had been reported.

Common failure modes. A sharp AUROC gain after a tokenizer change is more often a leak than a gain, for example discharge diagnoses moved onto the discharge timestamp; the masked-token audit exposes it. A sampler change made to save cost shifts calibration without moving AUROC. A retrain on a new year drifts in subgroups the headline metric hides. Each is caught by an artifact the playbook already requires, provided promotion is refused when an artifact is missing. After exposure, retraining, tokenizer refits and sampler changes are planned modifications, pre-specified in the United States under a predetermined change control plan, each rerunning steps 4 to 8 against the same frozen holdout and gate.

Open Problems

World models in every domain share the same unsolved problems: errors compound over long horizons, models are trusted beyond their data, and nobody agrees on how to measure "understanding the world". The list below gathers the open problems from both halves.

  • Long-horizon consistency. Autoregressive simulators drift: small errors in each frame or event compound, and memory of what is off-screen (or what happened years ago in a record) fades. Persistent 3D scenes and explicit memory help but trade away dynamics.
  • Evaluation that tracks usefulness. Next-step loss and FVD reward the wrong things. Closed-loop control, action-controllability and physics probes are better but fragmented; health models are still judged mostly by AUROC on single tasks rather than by the realism of whole simulated trajectories.
  • Planners exploit model errors. A policy or search procedure optimized inside a learned model finds the places where the model is wrong. Uncertainty-aware models, conservative planning and real-world feedback loops reduce but do not remove this.
  • Pixels or latents. Generative models are easy to inspect but spend capacity on unpredictable detail; JEPA-style latent models are efficient but hard to audit. Whether one approach wins, or both are needed, is unresolved.
  • Conditioning is not intervening. Health world models learn from observational care, so "what if we gave this drug" answers describe the patients who got it. Combining generative event models with causal identification, trial emulation and prospective validation is the central open problem for medical use.
  • Calibration, fairness and privacy at scale. Monte Carlo estimates are only as calibrated as the model; performance varies across subgroups and sites; and models that generate timelines can memorize and leak real patients.
  • Scaling laws beyond language. CoMET found language-like scaling for medical events with far more tokens per parameter; whether similar laws hold for video, robotics and physiology world models, and what data coverage they demand, is still being mapped.
About the figures

All figures in this book are original illustrations or are adapted and redrawn from the cited papers, as noted in their captions. Charts marked "illustrative" use made-up parameters to show a concept, and the patient record in the tokenization figure is fictional. No figures are copied from the papers.

Citation

Cited as:

Cheng, Kevin. (Nov 2026). World Models: From Dreamer to Patient Timelines. Kevin's Notes.
@article{cheng2026worldmodels,
  title   = "World Models: From Dreamer to Patient Timelines",
  author  = "Cheng, Kevin",
  journal = "Kevin's Notes",
  year    = "2026",
  month   = "Nov"
}

References

  1. "BCGNet: An AI Model Trained on 600K Hours of Sleep Data for a Novel Under-Pillow Contactless Monitoring Device." medRxiv 2025 (preprint; author list not retrieved). medrxiv.org/content/10.1101/2025.08.23.25334218
  2. Abbaspourazad, S., Elachqar, O., Miller, A. C., Emrani, S., Nallasamy, U., Shapiro, I. "Large-scale Training of Foundation Models for Wearable Biosignals." ICLR 2024. arxiv.org/html/2312.05409v2 · iclr.cc/virtual/2024/poster/17787
  3. Akagi, Y., Seki, T., Ito, H., Takiguchi, T., Ohe, K., Kawazoe, Y. "High-Fidelity Longitudinal Patient Simulation Using Real-World Data." arXiv 2601.17310, 2026. arxiv.org/abs/2601.17310
  4. Alonso, E., et al. "Diffusion for World Modeling: Visual Details Matter in Atari." NeurIPS 2024. arxiv.org/abs/2405.12399
  5. Assran, M., et al. "Self-Supervised Learning from Images with a Joint-Embedding Predictive Architecture." CVPR 2023. arxiv.org/abs/2301.08243
  6. Assran, M., et al. "V-JEPA 2: Self-Supervised Video Models Enable Understanding, Prediction and Planning." arXiv 2025. arxiv.org/abs/2506.09985
  7. Bardes, A., et al. "Revisiting Feature Prediction for Learning Visual Representations from Video." TMLR 2024. arxiv.org/abs/2404.08471
  8. Bedi, S., Fries, J. A., Shah, N. H. "Why 'Zero-Shot' Clinical Predictions Are Risky." Stanford HAI 2026. hai.stanford.edu/news/why-zero-shot-clinical-predictions-are-risky
  9. Bruce, J., et al. "Genie: Generative Interactive Environments." ICML 2024. arxiv.org/abs/2402.15391
  10. Cai, D., Chen, X., Chen, Y., Xian, H., Yu, B., Zhang, H. "Confidence analysis-based hybrid heartbeat detection for ballistocardiogram using template matching and deep learning." arXiv 2512.22926, 2025. arxiv.org/pdf/2512.22926
  11. Carter, J. F., Tarassenko, L. "Next-Token Prediction Learns Generalisable Representations of Sleep Physiology." arXiv 2606.09605, 2026. arxiv.org/abs/2606.09605
  12. Catalogue of Bias Collaboration (Aronson, J. K., Bankhead, C., Mahtani, K. R., Nunan, D.). "Confounding by indication." Catalogue of Bias 2018. catalogofbias.org/biases/confounding-by-indication
  13. Chen, B., et al. "Diffusion Forcing: Next-token Prediction Meets Full-Sequence Diffusion." NeurIPS 2024. arxiv.org/abs/2407.01392
  14. Chen, F., Chen, S., Chen, W., Wei, Z. "SOTER: A Generative Time-Series Foundation Model for Wearable Human Physiological Signals." arXiv 2609.16804, 2026. arxiv.org/abs/2609.16804
  15. Chen, Z., et al. "Scaling Agent Learning via Experience Synthesis." ICLR 2026. arxiv.org/abs/2511.03773
  16. Choi, E., et al. "Doctor AI: Predicting Clinical Events via Recurrent Neural Networks." MLHC 2016. arxiv.org/abs/1511.05942
  17. Duan, H., et al. "WorldScore: A Unified Evaluation Benchmark for World Generation." ICCV 2025. arxiv.org/abs/2504.00983
  18. Edouard, P., Campo, D., Bartet, P., Yang, R.-Y., Bruyneel, M., Roisman, G., Escourrou, P. "Validation of the Withings Sleep Analyzer, an under-the-mattress device for the detection of moderate-severe sleep apnea syndrome." Journal of Clinical Sleep Medicine 17(6), 2021. pmc.ncbi.nlm.nih.gov/articles/PMC8314651
  19. Eight Sleep. "The Eight Sleep Pod Heart Rate and Heart Rate Variability Accuracy." Company blog (not peer-reviewed). eightsleep.com/blog/hrv-accuracy
  20. Erturk, E., Kamran, F., Abbaspourazad, S., Jewell, S., Sharma, H., Li, Y., Williamson, S., Foti, N. J., Futoma, J. "Beyond Sensor Data: Foundation Models of Behavioral Data from Wearables Improve Health Predictions." arXiv 2507.00191, 2025. arxiv.org/html/2507.00191v1
  21. Farkas, I. "A single night's sleep could predict your risk for more than 100 diseases." ScienceAlert 2026. sciencealert.com/a-single-nights-sleep-could-predict-your-risk…
  22. Google DeepMind. "Genie 2: A large-scale foundation world model." DeepMind Blog, Dec 2024. deepmind.google/discover/blog/genie-2-a-large-scale-foundation-world-model
  23. Google DeepMind. "Genie 3: A new frontier for world models." DeepMind Blog, Aug 2025. deepmind.google/discover/blog/genie-3-a-new-frontier-for-world-models
  24. Google. "Introducing Genie 4." Google Blog, Oct 2026. blog.google/…/introducing-genie-4
  25. Google. "Project Genie: Experimenting with infinite, interactive worlds." Google Blog, Jan 2026. blog.google/…/project-genie
  26. Gottesman, O., et al. "Guidelines for reinforcement learning in healthcare." Nature Medicine 2019. clinicalml.org/publication/gottesman-2019-guidelines
  27. Grimm, C., Barreto, A., Singh, S., & Silver, D. "The Value Equivalence Principle for Model-Based Reinforcement Learning." NeurIPS 2020. arxiv.org/abs/2011.03506
  28. Gu, Y., et al. "Is Your LLM Secretly a World Model of the Internet? Model-Based Planning for Web Agents." TMLR 2025. arxiv.org/abs/2411.06559
  29. Guo, L. L., et al. "EHR foundation models improve robustness in the presence of temporal distribution shift." Scientific Reports 2023. ncbi.nlm.nih.gov/pmc/articles/PMC9992466
  30. Gurnee, W., & Tegmark, M. "Language Models Represent Space and Time." ICLR 2024. arxiv.org/abs/2310.02207
  31. Ha, D., & Schmidhuber, J. "World Models." arXiv 2018; NeurIPS 2018 version "Recurrent World Models Facilitate Policy Evolution" (arXiv:1809.01999). arxiv.org/abs/1803.10122
  32. Hafner, D., et al. "Learning Latent Dynamics for Planning from Pixels." ICML 2019. arxiv.org/abs/1811.04551
  33. Hafner, D., Lillicrap, T., Ba, J., & Norouzi, M. "Dream to Control: Learning Behaviors by Latent Imagination." ICLR 2020. arxiv.org/abs/1912.01603
  34. Hafner, D., Lillicrap, T., Norouzi, M., & Ba, J. "Mastering Atari with Discrete World Models." ICLR 2021. arxiv.org/abs/2010.02193
  35. Hafner, D., Pasukonis, J., Ba, J., & Lillicrap, T. "Mastering Diverse Control Tasks through World Models." Nature 2025 (arXiv 2301.04104; project page). nature.com/articles/s41586-025-08744-2
  36. Hafner, D., Yan, W., & Lillicrap, T. "Training Agents Inside of Scalable World Models." arXiv 2025 (project page). arxiv.org/abs/2509.24527
  37. Hansen, N., Su, H., & Wang, X. "TD-MPC2: Scalable, Robust World Models for Continuous Control." ICLR 2024. arxiv.org/abs/2310.16828
  38. Hao, S., et al. "Reasoning with Language Model is Planning with World Model." EMNLP 2023. arxiv.org/abs/2305.14992
  39. Hernán, M. A., Robins, J. M. "Using Big Data to Emulate a Target Trial When a Randomized Trial Is Not Available." American Journal of Epidemiology 2016. pmc.ncbi.nlm.nih.gov/articles/PMC4832051
  40. Hu, A., et al. "GAIA-1: A Generative World Model for Autonomous Driving." arXiv 2023. arxiv.org/abs/2309.17080
  41. Huang, X., et al. "Self Forcing: Bridging the Train-Test Gap in Autoregressive Video Diffusion." NeurIPS 2025. arxiv.org/abs/2506.08009
  42. Huang, Z., et al. "VBench: Comprehensive Benchmark Suite for Video Generative Models." CVPR 2024. arxiv.org/abs/2311.17982
  43. Inan, O. T., Migeotte, P., Park, K., Etemadi, M., Tavakolian, K., Casanella, R., et al. "Ballistocardiography and Seismocardiography: A Review of Recent Advances." IEEE Journal of Biomedical and Health Informatics 19(4), 2015. upcommons.upc.edu/…/27ff7fe3-5bd9-48d3-ad4d-4a723fbe7ace
  44. Janner, M., Fu, J., Zhang, M., & Levine, S. "When to Trust Your Model: Model-Based Policy Optimization." NeurIPS 2019. arxiv.org/abs/1906.08253
  45. Johnson, A. E. W., et al. "MIMIC-IV, a freely accessible electronic health record dataset." Scientific Data 2023; PhysioNet. physionet.org/content/mimiciv
  46. Kalman, R. E. "A New Approach to Linear Filtering and Prediction Problems." Journal of Basic Engineering 1960. cs.yale.edu/homes/yry/readings/general/Kalman1960.pdf
  47. Kang, B., et al. "How Far is Video Generation from World Model: A Physical Law Perspective." arXiv 2024. arxiv.org/abs/2411.02385
  48. Keogh, R. H., van Geloven, N. "Prediction under interventions: evaluation of counterfactual performance using longitudinal observational data." arXiv 2304.10005, 2023. arxiv.org/abs/2304.10005
  49. Kjaer, M. R., Han, H., Neupane, A., Sun, D. Q. "BCG-FM: A Foundation Model for Ambient Cardiac Health Sensing." arXiv 2606.07692, 2026. arxiv.org/abs/2606.07692 · arxiv.org/html/2606.07692v1
  50. Komorowski, M., et al. "The Artificial Intelligence Clinician learns optimal treatment strategies for sepsis in intensive care." Nature Medicine 2018. spiral.imperial.ac.uk/…/b4fa2588
  51. Kraljevic, Z., Bean, D., Shek, A., et al. "Foresight—a generative pretrained transformer for modelling of patient timelines using electronic health records: a retrospective modelling study." Lancet Digital Health 6, 2024. discovery.ucl.ac.uk/10190262 · arxiv.org/abs/2212.08072
  52. Kuo, N. I.-H., Gallego, B., Jorm, L. "Synthetic but Not Realistic: The Evaluation Challenge in Generative Modelling for Structured Electronic Medical Records." arXiv 2606.08903, 2026. arxiv.org/html/2606.08903
  53. Lambert, N., Amos, B., Yadan, O., & Calandra, R. "Objective Mismatch in Model-based Reinforcement Learning." L4DC 2020. arxiv.org/abs/2002.04523
  54. LeCun, Y. "A Path Towards Autonomous Machine Intelligence." OpenReview 2022. openreview.net/forum?id=BZ5a1r-kVsf
  55. Lee, S., Heydari, A. A. "Developing World Models from Wearable Sensors." NeurIPS 2026 Workshop on Continual World Models. neurips.cc/virtual/2026/159522
  56. Li, K., et al. "Emergent World Representations: Exploring a Sequence Model Trained on a Synthetic Task." ICLR 2023. arxiv.org/abs/2210.13382
  57. Li, S., Chen, Y., Chen, X., Gao, R., Zhang, Y., Yu, C., Li, Y., Ye, Z., Huang, W., Yi, H., Leng, Y., Wu, Y. "SleepNetZero: Zero-Burden Zero-Shot Reliable Sleep Staging With Neural Networks Based on Ballistocardiograms." arXiv 2410.22646, 2024. arxiv.org/html/2410.22646v1
  58. Li, Y., et al. "BEHRT: Transformer for Electronic Health Records." Scientific Reports 2020. alphaxiv.org/abs/1907.09538
  59. Li, Y., et al. "BEHRT: Transformer for Electronic Health Records." Scientific Reports 2020. pmc.ncbi.nlm.nih.gov/articles/PMC7189231
  60. Li, Y., et al. "Simulating Environments with Reasoning Models for Agent Training." arXiv 2025. arxiv.org/abs/2511.01824
  61. Liu, K., Li, M., Bao, Y., Zhang, T., Chu, C., Bu, J., Wang, H. "Medical world models: representing medical states, modelling clinical dynamics and guiding intervention policies." arXiv 2606.16721, 2026. arxiv.org/html/2606.16721
  62. Luo, T., Chu, R., Shi, Z., Li, X., Li, Q., Jin, W. "One Patient, Two Futures: World Models for Clinical Trial Simulation." NeurIPS 2026 Workshop. neurips.cc/virtual/2026/175522
  63. Luo, Y., Chen, X., Chen, Y., et al. "Toward World Modeling of Physiological Signals with Chaos-Theoretic Balancing and Latent Dynamics." arXiv 2605.15465, 2026. arxiv.org/pdf/2605.15465
  64. Makarov, N., Bordukova, M., Quengdaeng, P., et al. "Large language models forecast patient health trajectories enabling digital twins." npj Digital Medicine 8, 2025. ctisus.com/learning/journalclub/345440
  65. Makarov, N., Bordukova, M., von Voithenberg, L., et al. "TwinWeaver: An LLM-Based Foundation Model Framework for Pan-Cancer Digital Twins." ICML 2026. icml.cc/virtual/2026/poster/61602
  66. McDermott, M. B. A., et al. "Event Stream GPT: A Data Pre-processing and Modeling Library for Generative, Pre-trained Transformers over Continuous-time Sequences of Complex Events." NeurIPS Datasets and Benchmarks 2023. arxiv.org/abs/2306.11547
  67. McDermott, M. B. A., et al. "MEDS — An Emerging Data Standard and Ecosystem for Health AI Research." NEJM AI 2026 (as reported by News-Medical). news-medical.net/news/20260529/Researchers-develop-open-source-framework…
  68. Melnychuk, V., Frauen, D., Feuerriegel, S. "Causal Transformer for Estimating Counterfactual Outcomes." ICML 2022. arxiv.org/abs/2204.07258
  69. Meta FAIR CodeGen Team. "CWM: An Open-Weights LLM for Research on Code Generation with World Models." arXiv 2025. arxiv.org/abs/2510.02387
  70. Micheli, V., Alonso, E., & Fleuret, F. "Transformers are Sample-Efficient World Models." ICLR 2023. arxiv.org/abs/2209.00588
  71. Mitchell, M. "LLMs and World Models, Part 1." AI: A Guide for Thinking Humans, Feb 2025. aiguide.substack.com/cp/157209202
  72. Motamed, S., et al. "Do Generative Video Models Understand Physical Principles?" WACV 2026. arxiv.org/abs/2501.09038
  73. Nanda, N., Lee, A., & Wattenberg, M. "Emergent Linear Representations in World Models of Self-Supervised Sequence Models." BlackboxNLP 2023. arxiv.org/abs/2309.00941
  74. Narayanswamy, G., Liu, X., Ayush, K., et al. "Scaling Wearable Foundation Models." Google Research 2025. research.google/pubs/scaling-wearable-foundation-models
  75. Narayanswamy, G., Liu, X., Ayush, K., Yang, Y., Xu, X., et al. "Scaling Wearable Foundation Models." ICLR 2025. ubicomplab.cs.washington.edu/publications/lsm_iclr25
  76. Narayanswamy, G., Xu, M. A., et al. "Towards a General Intelligence and Interface for Wearable Health Data." arXiv 2605.22759, 2026. alphaxiv.org/abs/2605.22759
  77. National Cancer Institute. "CISNET Modeling Approach." CISNET. cisnet.cancer.gov/modeling
  78. News-Medical. "AI model maps lifetime disease risks to transform future healthcare planning." News-Medical 2025. news-medical.net/news/20250918/AI-model-maps-lifetime-disease-risks…
  79. Nikbakht, M., Gazi, A. H., Zia, J., An, S., Lin, D. J., Inan, O. T., Kamaleswaran, R. "Synthetic seismocardiogram generation using a transformer-based neural network." JAMIA 30(7), 2023. pmc.ncbi.nlm.nih.gov/articles/PMC10280352
  80. NVIDIA. "Cosmos World Foundation Model Platform for Physical AI." arXiv 2025. arxiv.org/abs/2501.03575
  81. Oh, J., Guo, X., Lee, H., Lewis, R., & Singh, S. "Action-Conditional Video Prediction using Deep Networks in Atari Games." NeurIPS 2015. arxiv.org/abs/1507.08750
  82. OpenAI. "Video generation models as world simulators." OpenAI, Feb 2024. openai.com/index/video-generation-models-as-world-simulators
  83. Pang, C., Jiang, X., Pavinkurve, N. P., et al. "CEHR-GPT: Generating Electronic Health Records with Chronological Patient Timelines." arXiv 2402.04400, 2024. arxiv.org/abs/2402.04400
  84. Pillai, A., Spathis, D., Kawsar, F., Malekzadeh, M. "PaPaGei: Open Foundation Models for Optical Physiological Signals." ICLR 2025. arxiv.org/abs/2410.20542
  85. Putter, H., Fiocco, M., Geskus, R. B. "Tutorial in biostatistics: competing risks and multi-state models." Statistics in Medicine 2007. est.ufmg.br/~enricoc/pdf/sobre/Putter2007.pdf
  86. Rajamohan, H. R., Gao, X., Zhu, W., et al. "Scaling Recurrence-aware Foundation Models for Clinical Records via Next-Visit Prediction." arXiv 2603.24562, 2026. arxiv.org/html/2603.24562
  87. Rao, R. P. N., & Ballard, D. H. "Predictive coding in the visual cortex: a functional interpretation of some extra-classical receptive-field effects." Nature Neuroscience 1999. pubmed.ncbi.nlm.nih.gov/10195184
  88. Rasmy, L., et al. "Med-BERT: pretrained contextualized embeddings on large-scale structured electronic health records for disease prediction." npj Digital Medicine 2021. arxiv.org/pdf/2005.12833
  89. Renc, P., et al. "ETHOS-ARES: Adaptive Risk Estimation System" (code repository). GitHub, 2025. github.com/ipolharvard/ethos-ares
  90. Renc, P., et al. "Zero Shot Health Trajectory Prediction Using Transformer." npj Digital Medicine 2024. arxiv.org/abs/2407.21124
  91. Renc, P., Grzeszczyk, M. K., Oufattole, N., et al. "Foundation Model of Electronic Medical Records for Adaptive Risk Estimation." arXiv 2502.06124, 2025 (GigaScience 14, giaf107). arxiv.org/abs/2502.06124
  92. Renc, P., Grzeszczyk, M. K., Qian, L., Oufattole, N., Rasley, J., Sitek, A. "Federated Timeline Synthesis: Scalable and Private Methodology For Model Training and Deployment." arXiv 2506.23358, 2025. ar5iv.labs.arxiv.org/html/2506.23358
  93. Ropes & Gray. "FDA Finalizes Guidance on Predetermined Change Control Plans for AI-Enabled Devices." Ropes & Gray Alert, December 2024. ropesgray.com/en/insights/alerts/2024/12/…
  94. Runway. "Introducing Runway GWM-1." Runway Research, Dec 2025. runway.com/research/introducing-runway-gwm-1
  95. Russell, L., et al. "GAIA-2: A Controllable Multi-View Generative World Model for Autonomous Driving." arXiv 2025. arxiv.org/abs/2503.20523
  96. Sadek, I. "Ballistocardiogram Signal Processing: A Literature Review." arXiv 1807.00951, 2018. arxiv.org/pdf/1807.00951
  97. 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." IMWUT 2025. arxiv.org/html/2502.01108v2
  98. Schmidt, D., & Jiang, M. "Learning to Act without Actions." ICLR 2024. arxiv.org/abs/2312.10812
  99. Schrittwieser, J., et al. "Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model." Nature 2020. arxiv.org/abs/1911.08265
  100. Shmatko, A., et al. "Learning the natural history of human disease with generative transformers." Nature 2025. ukbiobank.ac.uk/publications/learning-the-natural-history-of-human-disease-with-generative-transformers
  101. Shuai, Z., Xu, Z., Yang, D., Wang, W., Yang, Y. "OSF: On Pre-training and Scaling of Sleep Foundation Models." arXiv 2603.00190, 2026. arxiv.org/abs/2603.00190
  102. SiliconANGLE. "World Labs launches Marble, a commercial world model generating entire virtual environments." Nov 2025. siliconangle.com/2025/11/12/world-labs-launches-marble…
  103. SiliconANGLE. "Yann LeCun's new startup AMI Labs raises $1.03B to train world models." Mar 2026. siliconangle.com/2026/03/10/yann-lecuns-new-startup-ami-labs…
  104. Skywork AI. "Matrix-Game 2.0: An Open-Source, Real-Time, and Streaming Interactive World Model." arXiv 2025. arxiv.org/abs/2508.13009
  105. Sonnenberg, F. A., Beck, J. R. "Markov models in medical decision making: a practical guide." Medical Decision Making 1993. pubmed.ncbi.nlm.nih.gov/8246705
  106. Steinberg, E., et al. "Language models are an effective representation learning technique for electronic health record data." Journal of Biomedical Informatics 2021. arxiv.org/abs/2001.05295
  107. Steinberg, E., et al. "MOTOR: A Time-To-Event Foundation Model For Structured Medical Records." ICLR 2024. arxiv.org/abs/2301.03150
  108. Sutton, R. S. "Integrated Architectures for Learning, Planning, and Reacting Based on Approximating Dynamic Programming." ICML 1990. cs.utexas.edu/~shivaram/readings/b2hd-Sutton1990.html
  109. Thapa, R., et al. "SleepFM: Multi-modal Representation Learning for Sleep Across Brain Activity, ECG and Respiratory Signals." ICML 2024. arxiv.org/html/2405.17766v1
  110. Thapa, R., Kjaer, M. R., He, B., Covert, I., Moore IV, H., Hanif, U., Ganjoo, G., Westover, M. B., Jennum, P., Brink-Kjaer, A., Mignot, E., Zou, J. "A multimodal sleep foundation model for disease prediction." Nature Medicine 32(2), 752–762, 2026. nature.com/articles/s41591-025-04133-4 · research.regionh.dk/…/a-multimodal-sleep-foundation-model-for-disease-prediction
  111. Tom's Hardware. "AI-powered Minecraft runs without a game engine, rendered in real time at a continuous 20 FPS." 2024. tomshardware.com/video-games/ai-powered-minecraft…
  112. Tonekaboni, S., Stempfle, L., Fallahpour, A., Gerych, W., Ghassemi, M. "An Investigation of Memorization Risk in Healthcare Foundation Models." NeurIPS 2025. proceedings.nips.cc/…/0f4f18102c0dad5156e11e85414ba2d2
  113. Unterthiner, T., et al. "Towards Accurate Generative Models of Video: A New Metric & Challenges." arXiv 2018. arxiv.org/abs/1812.01717
  114. Vafa, K., Chen, J. Y., Rambachan, A., Kleinberg, J., & Mullainathan, S. "Evaluating the World Model Implicit in a Generative Model." NeurIPS 2024. arxiv.org/abs/2406.03689
  115. Valevski, D., Leviathan, Y., Arar, M., & Fruchter, S. "Diffusion Models Are Real-Time Game Engines." ICLR 2025. arxiv.org/abs/2408.14837
  116. van Geloven, N., Keogh, R. H., van Amsterdam, W., et al. "The risks of risk assessment: causal blind spots when using prediction models for treatment decisions." arXiv 2402.17366, 2024. arxiv.org/abs/2402.17366
  117. Wang, R., et al. "Can Language Models Serve as Text-Based World Simulators?" ACL 2024. arxiv.org/abs/2406.06485
  118. Wang, Z., Xu, C., et al. "Agent World Model: Infinity Synthetic Environments for Agentic Reinforcement Learning." arXiv 2026. arxiv.org/abs/2602.10090
  119. Waxler, S., et al. (Epic Systems and Microsoft Research). "Generative Medical Event Models Improve with Scale." arXiv 2025. arxiv.org/abs/2508.12104
  120. Wu, C., Qiu, J., Shen, G. "Improving ballistocardiogram-based continuous heart rate variability monitoring: A self-supervised learning approach." Biomedical Signal Processing and Control 89, 105774, 2024. catalog record (DOI 10.1016/j.bspc.2023.105774)
  121. Xu, J., et al. "ACES: Automatic Cohort Extraction System for Event-Stream Datasets." ICLR 2025. arxiv.org/abs/2406.19653
  122. Xu, M. A., Narayanswamy, G., et al. "LSM-2: Learning from Incomplete Wearable Sensor Data." arXiv 2506.05321, 2025. arxiv.org/html/2506.05321v1
  123. Xu, Q., Perera, D., Habib, G., Feng, M. "medDreamer: Model-Based Reinforcement Learning with Latent Imagination on Complex EHRs for Clinical Decision Support." arXiv 2505.19785, 2025. arxiv.org/pdf/2505.19785
  124. Xu, Z., Shuai, Z., Mozaffari, E., Aysola, R. S., Kumar, R., Yang, Y. "SleepLM: Natural-Language Intelligence for Human Sleep." arXiv 2602.23605, 2026. alphaxiv.org/abs/2602.23605
  125. Yang, Z., Mitra, A., Liu, W., Berlowitz, D., Yu, H. "TransformEHR: transformer-based encoder-decoder generative model to enhance prediction of disease outcomes using electronic health records." Nature Communications 2023. nature.com/articles/s41467-023-43715-z
  126. Yi, R., Popescu, M., Keller, J. M., Scott, G., Despins, L., Heise, D., Skubic, M. "Heartbeat Detection from Ballistocardiogram using Transformer Network." arXiv 2412.14376, 2024. arxiv.org/pdf/2412.14376
  127. Zhang, J., et al. "World-in-World: World Models in a Closed-Loop World." ICLR 2026. arxiv.org/abs/2510.18135
  128. Zhang, Y., et al. "SensorLM: Learning the Language of Wearable Sensors." NeurIPS 2025. neurips.cc/virtual/2025/poster/117808 · research.google/blog/sensorlm-learning-the-language-of-wearable-sensors
  129. Zhang, Y., Zhou, H., Feng, L., Hong, Y., Li, S. "Learning Longitudinal Health Representations from EHR and Wearable Data." arXiv 2601.12227, 2026. arxiv.org/abs/2601.12227
  130. Zhou, G., Pan, H., LeCun, Y., & Pinto, L. "DINO-WM: World Models on Pre-trained Visual Features enable Zero-shot Planning." arXiv 2024. arxiv.org/abs/2411.04983
  131. Zhu, Y., Weckstein, A. R., Lin, K. J., Yang, J. "DT-Transformer: A Foundation Model for Disease Trajectory Prediction on a Real-world Health System." arXiv 2605.14227, 2026. arxiv.org/pdf/2605.14227
  132. Richens, J., Abel, D., Bellot, A., & Everitt, T. "General agents need world models." ICML 2025. arxiv.org/abs/2506.01622
  133. Craik, K. J. W. "The Nature of Explanation." Cambridge University Press 1943 (summarised under "Mental model"). en.wikipedia.org/wiki/Mental_model
  134. "Model predictive control." Wikipedia. en.wikipedia.org/wiki/Model_predictive_control
  135. "System identification." Wikipedia. en.wikipedia.org/wiki/System_identification
  136. Ha, D., Schmidhuber, J. "World Models (interactive article)." worldmodels.github.io 2018. worldmodels.github.io
  137. Burchi, M., Timofte, R. "Learning Transformer-based World Models with Contrastive Predictive Coding (TWISTER)." ICLR 2025. arxiv.org/abs/2503.04416
  138. Morihira, N., Nahar, A., Bharadwaj, K., Kato, Y., Hayashi, A., Harada, T. "R2-Dreamer: Redundancy-Reduced World Models without Decoders or Augmentation." ICLR 2026. arxiv.org/abs/2603.18202
  139. Bredis, G., Balagansky, N., Gavrilov, D., Rakhimov, R. "Next Embedding Prediction Makes World Models Stronger (NE-Dreamer)." arXiv 2026. corl-team.github.io/nedreamer
  140. Chang, H., Zhang, H., Jiang, L., Liu, C., & Freeman, W. T. "MaskGIT: Masked Generative Image Transformer." CVPR 2022. arxiv.org/abs/2202.04200
  141. Dedieu, A., Ortiz, J., Lou, X., Wendelken, C., Lehrach, W., Guntupalli, J. S., Lazaro-Gredilla, M., & Murphy, K. P. "Improving Transformer World Models for Data-Efficient RL." ICML 2025. arxiv.org/abs/2502.01591
  142. Hansen, N. "TD-MPC2 default configuration (config.yaml)." GitHub repository nicklashansen/tdmpc2. github.com/nicklashansen/tdmpc2
  143. Hansen, N., Su, H., & Wang, X. "Learning Massively Multitask World Models for Continuous Control." arXiv 2025. arxiv.org/abs/2511.19584
  144. Hubert, T., Schrittwieser, J., Antonoglou, I., Barekatain, M., Schmitt, S., & Silver, D. "Learning and Planning in Complex Action Spaces." ICML 2021. arxiv.org/abs/2104.06303
  145. Karras, T., Aittala, M., Aila, T., & Laine, S. "Elucidating the Design Space of Diffusion-Based Generative Models." NeurIPS 2022. arxiv.org/abs/2206.00364
  146. Micheli, V., Alonso, E., & Fleuret, F. "Efficient World Models with Context-Aware Tokenization." ICML 2024. arxiv.org/abs/2406.19320
  147. Obando-Ceron, J., Li, L., Fujimoto, S., Bacon, P.-L., Courville, A., & Castro, P. S. "Representation Learning Enables Scalable Multitask Deep Reinforcement Learning." arXiv 2026. arxiv.org/abs/2606.05555
  148. Pu, Y., Niu, Y., Yang, Z., Ren, J., Li, H., & Liu, Y. "UniZero: Generalized and Efficient Planning with Scalable Latent World Models." arXiv 2024. arxiv.org/abs/2406.10667
  149. van den Oord, A., Vinyals, O., & Kavukcuoglu, K. "Neural Discrete Representation Learning." NeurIPS 2017. arxiv.org/abs/1711.00937
  150. Wang, S., Liu, S., Ye, W., You, J., & Gao, Y. "EfficientZero V2: Mastering Discrete and Continuous Control with Limited Data." ICML 2024. arxiv.org/abs/2403.00564
  151. 1X Technologies. "1X World Model." 1X, Jun 2025. 1x.tech/discover/redwood-ai-world-model
  152. Cui, J., et al. "Self-Forcing++: Towards Minute-Scale High-Quality Video Generation." arXiv 2025. arxiv.org/abs/2510.02283
  153. Li, Y., Zhu, Y., Wen, J., Shen, C., & Xu, Y. "WorldEval: World Model as Real-World Robot Policies Evaluator." arXiv 2025. arxiv.org/abs/2505.19017
  154. Liu, K., Hu, W., Xu, J., Shan, Y., & Lu, S. "Rolling Forcing: Autoregressive Long Video Diffusion in Real Time." arXiv 2025. arxiv.org/abs/2509.25161
  155. Xiao, Z., Lan, Y., Zhou, Y., Ouyang, W., Yang, S., Zeng, Y., & Pan, X. "WorldMem: Long-term Consistent World Simulation with Memory." NeurIPS 2025. arxiv.org/abs/2504.12369
  156. Balestriero, R., & LeCun, Y. "LeJEPA: Provable and Scalable Self-Supervised Learning Without the Heuristics." arXiv 2025. arxiv.org/abs/2511.08544
  157. Bardes, A., Ponce, J., & LeCun, Y. "VICReg: Variance-Invariance-Covariance Regularization for Self-Supervised Learning." ICLR 2022. arxiv.org/abs/2105.04906
  158. Chahe, A., & Zhou, L. "Policy-Guided World Model Planning for Language-Conditioned Visual Navigation." arXiv 2026. arxiv.org/abs/2603.25981
  159. Chen, D., Shukor, M., Moutakanni, T., et al. "VL-JEPA: Joint Embedding Predictive Architecture for Vision-language." arXiv 2025 (ICLR 2026). arxiv.org/abs/2512.10942
  160. Grill, J.-B., et al. "Bootstrap Your Own Latent: A New Approach to Self-Supervised Learning." NeurIPS 2020. arxiv.org/abs/2006.07733
  161. Maes, L., Le Lidec, Q., Scieur, D., LeCun, Y., & Balestriero, R. "LeWorldModel: Stable End-to-End Joint-Embedding Predictive Architecture from Pixels." arXiv 2026. arxiv.org/abs/2603.19312
  162. Terver, B., Yang, T.-Y., Ponce, J., Bardes, A., & LeCun, Y. "What Drives Success in Physical Planning with Joint-Embedding Predictive World Models?" arXiv 2025. arxiv.org/abs/2512.24497
  163. Vafa, K., Chang, P. G., Rambachan, A., Mullainathan, S. "What Has a Foundation Model Found? Using Inductive Bias to Probe for World Models." ICML 2025. arxiv.org/abs/2507.06952
  164. Hewitt, J., Liang, P. "Designing and Interpreting Probes with Control Tasks." EMNLP-IJCNLP 2019. aclanthology.org/D19-1275
  165. Chae, H., Kim, N., Ong, K. T., Gwak, M., Song, G., Kim, J., Kim, S., Lee, D., Yeo, J. "Web Agents with World Models: Learning and Leveraging Environment Dynamics in Web Navigation." ICLR 2025. arxiv.org/abs/2410.13232
  166. Wang, Y., Yin, D., Cui, Y., Zheng, R., Li, Z., Lin, Z., Wu, D., Wu, X., Ye, C., Zhou, Y., Chang, K.-W. "LLMs as Scalable, General-Purpose Simulators For Evolving Digital Agent Training" (UI-Simulator). NeurIPS 2025. arxiv.org/abs/2510.14969
  167. Li, Y., Wang, H., Qiu, J., Yin, Z., Zhang, D., Qian, C., Li, Z., Ma, P., Chen, G., Ji, H. "From Word to World: Can Large Language Models be Implicit Text-based World Models?" arXiv 2025. arxiv.org/abs/2512.18832
  168. Ge, S., Mahapatra, A., Parmar, G., Zhu, J.-Y., & Huang, J.-B. "On the Content Bias in Fréchet Video Distance." CVPR 2024. arxiv.org/abs/2404.12391
  169. Zheng, D., Huang, Z., Liu, H., et al. "VBench-2.0: Advancing Video Generation Benchmark Suite for Intrinsic Faithfulness." arXiv 2025. arxiv.org/abs/2503.21755
  170. Shang, Y., Li, Z., Ma, Y., et al. "WorldArena: A Unified Benchmark for Evaluating Perception and Functional Utility of Embodied World Models." arXiv 2026. arxiv.org/pdf/2602.08971
  171. Liang, A., Kong, L., Yan, T., et al. "WorldLens: Full-Spectrum Evaluations of Driving World Models in Real World." arXiv 2025. arxiv.org/abs/2512.10958
  172. Quevedo, J. H., Sharma, A. K., Sun, Y., Suryavanshi, V., Liang, P., Yang, S. "WorldGym: World Model as an Environment for Policy Evaluation." ICLR 2026. mlanthology.org/iclr/2026/quevedo2026iclr-worldgym
  173. Runway Robotics. "Accelerating robot policy evaluation" (GWM-Robotics policy-ranking study). Runway Research, Feb 2026. runway.com/research/accelerating-robot-policy-evaluation
  174. Ramachandran, J., Shah, T. "Simulating Patient Futures: A 2.7-Million-Patient World Model Across Health Networks." NeurIPS 2026 Workshop on World Models for High-Stakes Health. neurips.cc/virtual/2026/175518
  175. Zhang, S., Liu, Q., Usuyama, N., Wong, C., Naumann, T., Poon, H. "Exploring Scaling Laws for EHR Foundation Models." arXiv 2505.22964, 2025. arxiv.org/pdf/2505.22964
  176. Chandak, P., Kondas, G., Antwarg Friedman, L., Kohane, I., McDermott, M. "EveryQuery: A Promptable Foundation Model for Clinical Prediction Tasks over Electronic Health Records." arXiv 2603.07900, 2026. arxiv.org/html/2603.07900
  177. Kwon, W., Li, Z., Zhuang, S., Sheng, Y., Zheng, L., Yu, C. H., Gonzalez, J. E., Zhang, H., Stoica, I. "Efficient Memory Management for Large Language Model Serving with PagedAttention." SOSP 2023. arxiv.org/abs/2309.06180
  178. Ma, F., Liu, Y., Lan, X., et al. "Foundation Models to Unlock Real-World Evidence from Nationwide Medical Claims" (ReClaim). arXiv 2605.02740 (v2), 2026. arxiv.org/html/2605.02740v2
  179. Hyndman, R. J., Koehler, A. B. "Another look at measures of forecast accuracy." International Journal of Forecasting 22(4), 2006. doi.org/10.1016/j.ijforecast.2006.03.001
  180. Kidger, P., Morrill, J., Foster, J., Lyons, T. "Neural Controlled Differential Equations for Irregular Time Series." NeurIPS 2020. arxiv.org/abs/2005.08926
  181. van den Oord, A., Li, Y., Vinyals, O. "Representation Learning with Contrastive Predictive Coding." arXiv 1807.03748, 2018. arxiv.org/abs/1807.03748
  182. Jiang, N., Li, L. "Doubly Robust Off-policy Value Evaluation for Reinforcement Learning." ICML 2016; arXiv 1511.03722. arxiv.org/abs/1511.03722
  183. VanderWeele, T. J., Ding, P. "Sensitivity Analysis in Observational Research: Introducing the E-Value." Annals of Internal Medicine 167(4), 2017. dash.harvard.edu/bitstream/handle/1/36874927
  184. Carlini, N., Liu, C., Erlingsson, Ú., Kos, J., Song, D. "The Secret Sharer: Evaluating and Testing Unintended Memorization in Neural Networks." USENIX Security 2019. arxiv.org/abs/1802.08232
  185. Carlini, N., Tramèr, F., Wallace, E., et al. "Extracting Training Data from Large Language Models." USENIX Security 2021. arxiv.org/abs/2012.07805
  186. Finlayson, S. G., Subbaswamy, A., Singh, K., et al. "The Clinician and Dataset Shift in Artificial Intelligence." New England Journal of Medicine 2021. pubmed 34260843
  187. Gallifant, J., Afshar, M., Ameen, S., Aphinyanaphongs, Y., Chen, S., et al. "The TRIPOD-LLM reporting guideline for studies using large language models." Nature Medicine 31, 2025. dspace.library.uu.nl/handle/1874/460546
  188. Hanley, J. A., McNeil, B. J. "The meaning and use of the area under a receiver operating characteristic (ROC) curve." Radiology 1982. pubmed 7063747
  189. Van Calster, B., McLernon, D. J., van Smeden, M., Wynants, L., Steyerberg, E. W. "Calibration: the Achilles heel of predictive analytics." BMC Medicine 17, 2019. pmc.ncbi.nlm.nih.gov/articles/PMC6912996
  190. Vickers, A. J., Elkin, E. B. "Decision curve analysis: a novel method for evaluating prediction models." Medical Decision Making 26(6), 2006. pmc.ncbi.nlm.nih.gov/articles/PMC2577036
  191. Wong, A., Otles, E., Donnelly, J. P., et al. "External Validation of a Widely Implemented Proprietary Sepsis Prediction Model in Hospitalized Patients." JAMA Internal Medicine 2021. pmc.ncbi.nlm.nih.gov/articles/PMC8218233
  192. Yan, C., Yan, Y., Wan, Z., Zhang, Z., Omberg, L., Guinney, J., Mooney, S. D., Malin, B. A. "A Multifaceted Benchmarking of Synthetic Electronic Health Record Generation Models." Nature Communications 2022 (arXiv 2208.01230). arxiv.org/abs/2208.01230
  193. Niculescu-Mizil, A., Caruana, R. "Predicting Good Probabilities with Supervised Learning." ICML 2005. mlanthology.org/icml/2005/niculescumizil2005icml-predicting
  194. Oufattole, N., Bergamaschi, T., Kolo, A., et al. "MEDS-Tab: Automated tabularization and baseline methods for MEDS datasets." arXiv 2411.00200, 2024. arxiv.org/abs/2411.00200