Part of World Models Handbook
Explains how causal transformers predict world dynamics from tokenized observations and actions.
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
Autoregressive Token World Models
Imagine supplying a game model with an initial agent position shifted by seven cells modulo sixteen. Does the model return to the observed trajectory, follow a different but valid trajectory, or make further mistakes? We will test those possibilities in a small deterministic world. The preceding chapters introduced recurrent state and transformer memory; here we focus on a particular interface for dynamics: discrete observation and action tokens predicted by a causal transformer.
A world model predicts environment-relevant futures from available observations and actions. A recurrent model carries a learned summary; a token model can retain an explicit recent token record and compute predictions from it. Both use conditional sequence factorizations, but lossy tokenization changes the predicted outcome space: a distribution over token grids is not identical to a distribution over raw images. Causal-transformer optimization and attention machinery are reusable, while modality alignment, tokenization, loss masks, and evaluation still need design. Whether scaling behavior transfers is an empirical question.
IRIS demonstrates categorical next-token world modeling for Atari control. Related interactive generators use different decoders: Genie generates discrete video frames with iterative masked-token prediction, while Oasis generates frames autoregressively using latent diffusion. Temporal autoregression, discrete representation, and within-frame next-token decoding are separate choices. We will use IRIS's general categorical sequence pattern for the miniature and distinguish the alternatives when they arise.
The pipeline has three stages, and each gets its own treatment in this chapter:
- Tokenization: observations and actions are mapped to symbols. A fully unified design combines disjoint modality vocabularies; hybrid systems may retain continuous inputs or separate prediction heads.
- Next-token dynamics: a causal transformer learns the conditional distribution over future world tokens given the past token stream, including action tokens that we inject along the way.
- Rollout and use: the model generates hypothetical futures by feeding its own predictions back as inputs, and an agent (in Part VII) queries those futures to make decisions.
The apparent simplicity hides design decisions. A tokenizer can discard distinctions needed by a task, although history or other modalities may retain information absent from one frame. Serialization and masks determine which inputs a prediction may read; chronological ordering alone does not establish causal identification. Under teacher forcing, training uses recorded histories. Imperfect autoregressive models may generate different histories at deployment, and their errors can influence later predictions. We will measure rollout errors and corrective fine-tuning without treating every mismatch or declining exact-match curve as proof of exposure bias.
The runnable miniature keeps the original three-entity environment, two training budgets, self-generated-context fine-tuning, and a one-token intervention. Matched teacher-forced metrics, an additional-training control, and an exact environment predictor help separate what these experiments do and do not establish.
From Latent States to Token Sequences
Before diving into tokenizers, it is worth being explicit about what changes relative to the recurrent state-space models of Part V: World-Model Architectures.
A recurrent world model carries a fixed-width state . At fixed numerical precision its storage capacity is finite, but the state can still be a sufficient statistic for a task. A strict window-conditioned token model instead recomputes predictions from the most recent token IDs and their positions. Those IDs are retained exactly, not the pre-tokenization observations. Rolling multilayer KV caches are a different implementation: retained contextual representations can encode information from tokens whose original entries have since been evicted.
Both designs allocate finite resources to an unbounded past. The recurrent summary may preserve selected information from arbitrarily long ago; the explicit token buffer preserves a bounded record. Neither guarantees successful prediction: representation loss, available context, learned attention, and optimization all matter. Direct availability of a token is not the same as retrieving its useful content.
This difference has consequences worth internalizing early:
- Memory quality: a strict token buffer preserves its stored symbols exactly. A recurrent state can preserve selected old facts or an adequate filtering statistic without preserving the full record. A relevant event outside a recomputed buffer is unavailable only if no retained evidence represents it. Tasks needing recent fine detail and tasks needing distant events therefore suggest different tests, not an automatic architecture ranking.
- Per-step compute: at fixed dimensions, a recurrent update has work in elapsed history. A cached new-token attention query has mixing work; recomputing dense attention over the entire prefix costs per generation step. KV caching reuses earlier projections because a causal model's earlier states do not depend on future tokens, provided positions and other state conventions remain consistent. The cache uses storage. Dense full-sequence training has quadratic pairwise attention work, distinct from the linear cached-query cost.
The next cell plots illustrative asymptotic growth, with each curve separately normalized to one at the smallest window. It is not a timing benchmark or a claim that the methods have equal costs at that window. It also computes cache storage for one sequence with full-width keys and values, width 1,024, 12 layers, and two-byte entries; other head layouts, batch sizes, or precisions change that accounting.
import numpy as np
window_lengths = np.array([256, 512, 1024, 2048, 4096, 8192, 16384, 32768])
## Relative per-step cost, normalized so the recurrent update at the smallest
## window costs 1. A recurrent state update is O(1) in history length.
recurrent_step = np.ones_like(window_lengths, dtype=float)
## With a KV cache, each new token attends over all W cached tokens: O(W).
cached_step = window_lengths / window_lengths[0]
## Without a cache, every step recomputes attention over the full window: O(W^2).
uncached_step = (window_lengths.astype(float) ** 2) / (window_lengths[0] ** 2)
## KV-cache memory: d_model=1024, 12 layers, K and V tensors, 2 bytes (fp16) each.
D_MODEL, N_LAYERS, BYTES = 1024, 12, 2
kv_mb = window_lengths * D_MODEL * 2 * N_LAYERS * BYTES / 1e6
print(f"KV-cache memory at 32768 tokens: {kv_mb[-1]:.2f} MB per sequence")KV-cache memory at 32768 tokens: 1610.61 MB per sequence

- Training signal: next-token prediction provides a loss term at each supervised token position. A image grid has 1,024 such terms per frame. Recurrent image models can also supervise many pixels, rewards, and latent quantities; naming their sum one loss does not reduce its information content. Token supervision is a convenient objective, not a proof of more useful gradients or superior sample efficiency. Auxiliary objectives may still help retain task-relevant information.
- Discreteness: categorical probabilities define an explicit predictive distribution, but need not be calibrated or separate epistemic from environmental uncertainty. Sampling draws symbols rather than averaging their decoded values. Learned visual quantizers can lose information; tokenization of already discrete variables can be exact. Continuous encoders also have architectural and learned bottlenecks. No downstream predictor can recover an absent distinction from unchanged inputs alone, though other retained evidence may make it inferable.
A token is an element of a finite discrete vocabulary. In the fully unified design, observations, actions, rewards, and commands can all be serialized as tokens. Other token world models use continuous components or separate heads. Vocabulary size depends on the modality and tokenizer rather than one universal range.
Tokenizing the World
A token world model is only as good as its tokenizer. This section covers three common tokenization design problems: turning images into tokens, turning actions into tokens, and fusing many modalities into one vocabulary.
Tokenization is not necessarily learned or lossy: our toy uses an exact hand-designed mapping. The visual tokenizers below do compress observations. If two complete retained token histories are identical but require different correct predictions or decisions, no downstream model can always distinguish them. A variable missing from one encoded frame may still be inferable from other frames or actions. Temporal stride sets the latent grid rate, not by itself the finest event timing the codes can preserve or the decoder can reconstruct.
Visual Tokenizers: From Pixels to Symbols
A RGB image contains 196,608 scalar channel values. iGPT applied autoregression to small images represented by clustered pixel colors, with VQ-VAE compression for larger inputs. At one color token per pixel, a frame requires 4,096 ordinary sequential decoding steps. Each step evaluates a decoder, although KV caching avoids recomputing the full prefix. Learned visual compression reduces the number of positions by encoding an image or clip as a smaller code grid.
The workhorse is the vector-quantized variational autoencoder (VQ-VAE), introduced by van den Oord, Vinyals, and Kavukcuoglu (2017). It works in three stages:
- An encoder maps an image to a downsampled feature map . A frame with 8× downsampling becomes a grid of feature vectors, one per spatial cell.
- Each feature vector is quantized: we replace it with the nearest entry in a learned codebook :
where:
- : the feature vector at spatial cell of the encoder output
- : the -th entry of the learned codebook, one of entries in total
- : the Euclidean norm, so is the index of the codebook entry closest to
- : the quantized replacement for , namely the selected codebook entry
The assignment geometry is easiest to see in two dimensions. The next cell simulates a small feature space: five clusters of encoder outputs (the analogue of one spatial cell's feature vector across many images), a codebook of 12 entries, and the nearest-neighbor rule from the equation above. Everything is deterministic given the seed.
import numpy as np
rng = np.random.default_rng(11)
## Five clusters of encoder outputs in 2-D, standing in for the feature map of
## one spatial cell across many images.
cluster_centers = np.array(
[[0.0, 0.0], [2.4, 1.1], [-1.6, 2.1], [1.7, -1.7], [-2.1, -1.0]]
)
enc_outputs = np.vstack(
[c + 0.35 * rng.standard_normal((60, 2)) for c in cluster_centers]
)
## A codebook of 12 entries.
VQ_K = 12
vq_codes = rng.uniform(-3.0, 3.0, (VQ_K, 2))
## Nearest-code assignment: argmin over squared Euclidean distance.
vq_assign = (
((enc_outputs[:, None, :] - vq_codes[None, :, :]) ** 2).sum(-1).argmin(1)
)
vq_error = np.linalg.norm(enc_outputs - vq_codes[vq_assign], axis=1)
print(f"mean quantization error per assignment: {vq_error.mean():.3f}")
## Dense grid for the Voronoi (nearest-code) partition background.
gx, gy = np.meshgrid(np.linspace(-3.6, 3.6, 220), np.linspace(-3.2, 3.6, 220))
grid_pts = np.stack([gx.ravel(), gy.ravel()], axis=1)
grid_assign = (
((grid_pts[:, None, :] - vq_codes[None, :, :]) ** 2).sum(-1).argmin(1)
)
grid_assign = grid_assign.reshape(gx.shape)mean quantization error per assignment: 0.755

- A decoder reconstructs the image from the quantized grid: .
Tokenization emits code indices, one per grid cell. With 8,192 entries, each index needs 13 bits in fixed-width storage and carries at most 13 bits of entropy. For one grid , bits. This bounds information about that image in that grid, not all information available across history. Arbitrary 8-bit RGB values for the original frame require 1,572,864 bits uncompressed. Whether the smaller representation retains task-relevant distinctions depends on the data, architecture, objective, and learned parameters.
The nearest index is locally constant away from assignment boundaries, so ordinary differentiation through the index does not give a useful encoder gradient. This does not block the derivative of a decoder loss with respect to the selected code vector itself. Standard VQ-VAE deliberately separates these paths: a straight-through estimator routes reconstruction gradients to the encoder, while a codebook loss or EMA update trains dictionary entries.
In the backward pass, pretend the quantizer was the identity function. The gradient of the loss with respect to the encoder output is approximated by the gradient with respect to the quantized value :
where:
- : the training loss being differentiated, here the reconstruction loss
- : the encoder output at spatial cell
- : its quantized replacement from the codebook
The codebook entries themselves are updated by a separate loss (or by exponential moving averages of the encoder outputs assigned to them).
The straight-through estimator is biased: it differentiates as if a small change of the encoder output changed the quantized value continuously, although hard assignments are piecewise constant. Encouraging encoder outputs to stay near their assigned codes can help training, but closeness alone does not prove that the surrogate is a useful descent direction. The estimator does not guarantee convergence to the optimum of the discrete reconstruction problem.
A VQ-VAE-style objective can combine a chosen reconstruction loss with codebook and commitment terms:
where:
- : the total VQ-VAE training objective
- : the input image
- : the encoder's continuous feature grid
- : the quantized version of that grid
- : the decoder that reconstructs the image from
- and : the L1 and Euclidean norms
- : "stop-gradient", which treats its argument as a constant during backpropagation
- : the coefficient weighting commitment relative to the other loss terms
The displayed reconstruction term is L1. The original VQ-VAE image experiments used squared error within a more general reconstruction-likelihood formulation; the VQGAN implementation uses L1. Squared error selects a conditional mean; L1 selects coordinatewise conditional medians. Neither universally guarantees sharp or semantically faithful reconstruction. In the standard gradient routing, the codebook term moves assigned entries toward encoder outputs and the commitment term moves encoder outputs toward fixed entries. Without commitment, encoder scale can drift; without a codebook loss or a replacement such as EMA, that dictionary-update path is absent. These are alignment mechanisms, not the posterior-to-prior matching performed by a VAE KL term.
Reconstruction-only point decoders can blur when an encoded representation leaves incompatible images plausible. Squared error returns their conditional mean; coordinatewise L1 medians may or may not form a coherent joint image. The mean need not lie between modes for every multimodal distribution. The asymmetric mixture below is a specific example where the squared-error optimum does lie in a low-density region.
The next cell constructs a continuous scalar Gaussian mixture, not a categorical token distribution. Its three components have equal mixture weights. The plotted mean is the squared-error-optimal point prediction; a manually chosen component center provides a visual contrast, not a learned or sampled adversarial output.
import numpy as np
## Next-value distribution for a continuous scalar when three futures are
## equally plausible: a trimodal Gaussian mixture with the modes placed
## asymmetrically, so the mixture mean lands in a low-density region
## between them rather than on the middle future.
xs_blend = np.linspace(-4.0, 4.0, 800)
BLEND_MODES = np.array([-3.0, -1.5, 3.0])
BLEND_SIGMA = 0.45
def mixture_pdf(x):
comp = np.exp(
-0.5 * ((x[:, None] - BLEND_MODES[None, :]) / BLEND_SIGMA) ** 2
)
return comp.sum(axis=1) / (
len(BLEND_MODES) * BLEND_SIGMA * np.sqrt(2 * np.pi)
)
blend_density = mixture_pdf(xs_blend)
## The L2-optimal single prediction is the mixture mean, which sits in a
## low-density region between the modes and matches none of them.
blend_prediction = float(BLEND_MODES.mean())
chosen_mode_center = float(BLEND_MODES[0])
Averaging incompatible fine-detail arrangements can blur a reconstruction. VQGAN adds perceptual and adversarial objectives and reports improved perceptual quality; these losses encourage realism without guaranteeing the correct conditional mode or turning a deterministic decoder into a sampler. Learned codebooks can also become persistently underused. An entry with no assignments receives no new assignment contribution in that batch, but momentum, weight decay, EMA statistics, smoothing, or resets may still change it. One finite batch's zero counts do not establish permanent collapse.
We can inspect initial utilization in the same two-dimensional setting. The next cell assigns points from five clusters to 48 randomly initialized entries. It measures which entries are unused in this sample before any training; persistent collapse would require following utilization during training.
import numpy as np
rng = np.random.default_rng(5)
## Synthetic encoder outputs concentrated near five chosen centers.
## This illustrative sample makes no claim about tokenized datasets generally.
collapse_centers = rng.uniform(-2.0, 2.0, (5, 2))
collapse_data = np.vstack(
[c + 0.3 * rng.standard_normal((80, 2)) for c in collapse_centers]
)
## A codebook of 48 entries initialized uniformly over the box.
CB_K = 48
cb_codes = rng.uniform(-3.0, 3.0, (CB_K, 2))
## One round of nearest-neighbor assignment, before any training.
cb_assign = (
((collapse_data[:, None, :] - cb_codes[None, :, :]) ** 2).sum(-1).argmin(1)
)
cb_counts = np.bincount(cb_assign, minlength=CB_K)
usage_sorted = np.sort(cb_counts)[::-1]
n_dead = int((cb_counts == 0).sum())
print(f"unused codes after one assignment round: {n_dead} of {CB_K}")
print(
f"mean quantization error on live codes: "
f"{np.linalg.norm(collapse_data - cb_codes[cb_assign], axis=1).mean():.3f}"
)unused codes after one assignment round: 25 of 48 mean quantization error on live codes: 0.461

EMA is an alternative centroid update, not a guarantee of reviving unused entries; dead-code resets are another possible intervention. Finite Scalar Quantization uses fixed per-coordinate levels, and MAGVIT-v2 uses lookup-free quantization. Without learned centroids, there are no dead learned code vectors, but an encoder can still underuse the implicit code space. The fixed grid constrains quantizer coordinates while learned surrounding networks shape the effective representation. These are alternatives to learned vector codebooks, not evidence of their universal displacement. Residual VQ instead approximates a feature, subtracts that approximation, and quantizes the residual. With stages of entries there are index tuples at a cost of tokens per cell; collisions or unreachable tuples can yield fewer distinct reconstructions. Additional well-trained stages can improve precision, but stage count alone does not guarantee smaller error.
The next plot compares the number of possible index tuples with token count for 512 entries per residual stage. It does not measure distinct reconstructed vectors or achieved reconstruction quality.
import numpy as np
RV_K = 512 # entries per codebook
rv_stages = np.arange(
1, 7, dtype=np.int64
) # stacked codebooks per spatial cell
## R stacked codebooks each with K entries can represent K^R combinations.
rv_combinations = RV_K**rv_stages
## while costing only R tokens per cell.
rv_tokens = rv_stages.astype(float)
print(f"combinations at R=6: {float(rv_combinations[-1]):.3e}")combinations at R=6: 1.801e+16

Video tokenizers can encode time as well as space. MAGVIT uses 3D operations; a compressed code can summarize multiple frames, for example a spatiotemporal block. Temporal stride spaces latent positions farther apart, but a code may retain within-block timing and a decoder may output every frame. Two-frame encoding is therefore not equivalent to dropping every other frame. Loss of timing depends on capacity and the learned representation. A noncausal encoder that waits for a second unseen frame adds latency; causal or overlapping schemes can have different online interfaces. Actual downsampling aliases unresolved temporal frequencies unless filtering or prior constraints make them recoverable. These distinctions connect token design to the observation-design questions in Part III.
Continuous-token designs omit codebook rounding but may retain other projection or compression losses. A continuous head can be deterministic, Gaussian, or an iterative generative module. MAR is an autoregressive image model with continuous tokens and a diffusion loss. Iterative sampling adds work, but continuous outputs are not inherently more expensive than categorical decoding across many positions. The relevant comparison includes evaluations per output, width, parallelism, representation quality, and the task.
Action Tokenizers
Actions enter the token stream too. Many environments have naturally discrete actions; many do not.
- Natively discrete actions need an agreed symbol mapping and timing convention, but no continuous-value quantization. Atari's action space has fewer than 20 actions; this makes token mapping straightforward. IRIS evaluates on Atari 100k, but this convenience alone does not explain its historical benchmark choice.
- Continuous actions must be quantized only for a fully categorical interface. RT-1 uses 256 bins per scalar action variable; its arm variables describe position, orientation, and gripper opening rather than seven joint angles. Any seven-scalar command takes seven tokens under one-token-per-variable encoding. Gato bins scalar observations and actions into 1,024 levels, while images use continuous patch embeddings. Hybrid observation-token models can instead accept or emit continuous actions.
Binning creates several distinct costs. Boundary jitter occurs when a varying command crosses a quantizer threshold repeatedly: small smooth changes become switches between adjacent output levels. This can add higher-frequency components to the command. It is not necessarily bang-bang control, and whether the physical trajectory oscillates depends on the plant and controller.
The next cell illustrates command quantization without a learned policy or a physical plant. A sinusoid crosses an interior bin edge in an eight-bin partition of ; the figure shows command discontinuities, not a simulated trajectory.
import numpy as np
## A smooth controller output regulating a setpoint that lands exactly on a
## bin edge, with a small illustrative sinusoidal variation. The
## slow crossings of that edge make the binned action flip back and forth
## between the two adjacent bins: boundary jitter.
t_cmd = np.linspace(0.0, 6.0, 600)
smooth_command = 0.25 + 0.03 * np.sin(3.0 * t_cmd) # in [-0.5, 0.5]
N_BINS = 8
bin_edges = np.linspace(-0.5, 0.5, N_BINS + 1)
bin_index = np.clip(np.digitize(smooth_command, bin_edges) - 1, 0, N_BINS - 1)
bin_midpoints = 0.5 * (bin_edges[:-1] + bin_edges[1:])
binned_action = bin_midpoints[bin_index]
## How often consecutive samples flip between two adjacent bins.
n_flips = int((np.abs(np.diff(bin_index)) == 1).sum())
Precision depends on dynamics as well as bin width. With midpoint decoding of an in-range scalar command, quantization error is bounded by half a bin width. That is not a bound on position error or a proof of unreachable targets: target alignment, feedback, integration, and execution horizon matter. Latency arises when action variables are decoded sequentially. Seven categorical variables require seven ordinary decoding steps in that design, but parallel heads or externally supplied candidate actions need not. Candidate rollouts also cost computation, although batching can share hardware throughput; Oasis's video-generation speed is not evidence about seven-token action decoding.
Continuous action heads can share an observation-token backbone. Coarse-to-fine tokens add precision with additional codes, but task-adaptive allocation requires an extra mechanism. Genie's latent action model instead uses prior frames and the next frame to learn compact transition codes without labeled actions. Such a code can provide a useful controllable interface, as evaluated in Genie, but observational frame changes can also reflect camera motion or exogenous events. Compactness alone does not identify a causal intervention. We return to this distinction in Part VI.
Multimodal Tokenizers and Unified Vocabularies
A fully unified categorical design can represent observations, actions, rewards, and termination flags in one stream. Decision Transformer instead conditions a policy on embedded return-to-go scalars; this is not the same as predicting categorical reward symbols. An integrated reward predictor can support planning if it predicts the task's relevant reward accurately. Termination is supervised only when included as a target, and an integrated head does not remove the need to evaluate planning decisions.
A fully discrete implementation can use disjoint token ranges and optional modality-boundary markers. Chameleon demonstrates early-fusion text and image modeling. Gato uses a shared policy transformer over a mix of discrete symbols and continuous image-patch embeddings, without predicting image observations. Modality-specific processing can also be fused later at an intermediate or output representation. These designs share some sequence machinery without being identical categorical world models.
Why go through the trouble? Three reasons:
- One objective, shared processing. Supervised discrete output positions can share cross-entropy. Tokenizers may require reconstruction or other objectives, and input-only modalities need no output loss. Adding a sensor can also require synchronization, missing-data conventions, masks, positional encodings, loss balancing, and evaluation. A common optimization loop is reusable, but equal loss forms do not imply equal scaling curves.
- One context. Shared attention provides a path for cross-modal conditioning without a dedicated pairwise fusion module. A past command can affect a frame prediction when it remains accessible under the context and mask. Learning that dependency still requires suitable data and optimization. Controlled tasks and modality ablations help distinguish genuine conditioning from shortcuts.
- Reusable infrastructure. Causal-transformer optimization, data parallelism, and cache techniques are reusable. Context-parallel kernels must support the chosen masks; quantization needs calibration and accuracy checks; speculative decoding needs compatible draft probabilities and action-conditioning semantics. Reuse is a practical advantage, not a promise that every component transfers unchanged.
Modality token counts can differ substantially: a 1,024-token image may sit beside one scalar token. Equal logits would give the image keys 1,024 times the scalar's total attention mass, but learned logits can overcome this count difference. Comparable information density is not required. Modality embeddings identify type and positions identify order; whether either helps an imbalance-related learning problem needs measurement. Token budgets, masks, and training mixtures are design choices rather than an intrinsic one-dimensional bottleneck.
Next-Token Dynamics
We now formalize what the model learns. Let a rollout be serialized as a single token stream interleaving observations and actions:
where:
- : the token stream for one rollout
- : the observation tokens emitted at step
- : the action tokens at step , ordered before observation block
Each and may itself expand into several tokens. A causal transformer with parameters defines an autoregressive factorization over any such stream:
where:
- : the tokens of the stream , listed in sequence order
- : all tokens preceding position , that is,
- : the categorical distribution over the vocabulary that the transformer, with parameters , assigns to the next token
- : the total number of tokens in the stream
The chain rule permits any ordering of a joint distribution. A causal next-token implementation additionally needs shifted targets: the input at the prediction position must not already contain the target. The usual mask allows self-attention and only excludes later input positions. Finite context restricts the represented conditionals, whereas the unrestricted chain rule itself makes no independence assumption. Expected negative log-likelihood is minimized by the true conditional distribution when it is representable and optimized in expectation; the optimum can be sharp or diffuse.
For prediction under externally specified actions, define the causally conditioned rollout law below. This is not generally the observational conditional obtained by selecting trajectories with an entire future action sequence: under an adaptive logging policy, future actions can reveal earlier observations. The causal rollout construction instead supplies actions without that retrospective selection. Calling its factors true intervention dynamics additionally requires adequate conditioning information, action support, and no relevant hidden confounding.
where:
- : the predicted observation blocks at steps 1 through , with
- : causal conditioning on supplied actions, not selection on future logged actions
- : the rollout horizon
- : the initial observation tokens, given as context rather than predicted
- : the externally specified actions for steps 0 through
- : the number of tokens per observation block
- : the -th token of the observation block at step
- : all observation tokens from steps before
- : actions before , including ; future actions are excluded by the causal rollout construction, not by an identity for arbitrary observational conditioning
- : the first tokens of observation block itself
Read this carefully, because it encodes several design decisions:
- Actions are conditions in this objective. We mask action targets and learn observation-token factors. Joint models can also learn behavior-policy probabilities without mathematically invalidating the same observation conditionals. Either objective needs support and causal assumptions before its predictions are trusted under intervention. In our toy, controls are randomized independently of initial states and the transition mechanism is known; a planner in another dataset cannot assume that masking actions removes confounding or provides evidence for unseen actions.
- Within-frame dependence is a decoding choice. In raster next-token decoding, a token can read earlier tokens in its frame and accessible earlier frames. Independent simultaneous outputs cannot represent residual correlations unless those are resolved by conditioning or other latent structure. Iterative masked decoding permits a different within-frame information graph. Neither access pattern guarantees coherent generated frames.
- Available context determines usable evidence. For strict recomputation, state includes the last token IDs and positional metadata. Rolling caches can carry additional contextual information. A short window suffices only when the tokenized observation-action record preserves a sufficient predictive state. In partial observability, a Bayesian posterior would summarize history under a specified model; learned transformer activations need not equal that posterior or be calibrated. Windowed prediction can approximate belief-based prediction using accessible evidence without explicitly representing the full belief.
Training is by maximum likelihood under teacher forcing:
Pure teacher forcing supplies recorded previous tokens and supervises the recorded next token. It does not feed the model's generated outputs back as training inputs. Williams and Zipser (1989) used the term in recurrent-network training; it is also standard in many sequence-to-sequence applications.
Under teacher forcing, the model is trained to maximize the likelihood of the true world tokens given their true contexts:
where:
- : the expected negative log-likelihood of the world tokens under parameters , to be minimized
- : a token stream drawn from the training data, so the expectation is taken under the data distribution rather than the model's own
- : the target token at position , with the true context fed to the model as input
- the sum ranges only over positions whose target is a world (observation) token; action tokens are masked out of the loss
Teacher forcing gives one loss term per supervised world token, uses recorded rather than self-generated histories, and permits layerwise-parallel evaluation across sequence positions. It avoids error feedback in the training inputs, but does not guarantee numerical stability or sufficient representations. Dense attention still has quadratic pairwise work. When learned conditionals reproduce the data process under matched actions, generated and recorded histories can have the same distribution; mismatch is a risk of imperfect models and changed deployment conditions, not an unavoidable consequence of teacher forcing.
Prediction Versus Use
It is worth pausing on a distinction this book keeps returning to, because token world models blur it more than most. The model above predicts observations: given a history and a candidate action sequence, it rolls out a distribution over future observation tokens. That is an open-loop forecasting capability, and everything in this chapter is about its quality.
Using predictions is a separate task from producing them. Model-predictive control searches candidate actions, executes an initial action, then replans from new evidence. Fresh observations can correct visible drift, but robustness still depends on model accuracy, sensing, constraints, and controller design. Differentiable planning through discrete choices needs an expectation, relaxation, or gradient estimator; an agent can also learn from imagined experience or distill a planner's actions. Search need not find a global optimum and may exploit overestimated rewards. Conversely, a model can retain enough task-relevant structure despite poor texture reconstruction. Predictive fidelity and decision usefulness therefore require separate tests, without assuming a general correlation.
Spatiotemporal Token Layouts
A video has spatial and temporal axes, while a token transformer consumes a linear ordering. The ordering and mask determine available inputs; chronology is particularly convenient for online generation. Any order can factor an offline clip joint in principle. For a finite model, ordering affects sequence distances and inductive bias, but accuracy differences require evidence rather than an appeal to physical causality.
For a clip of frames with tokens per frame, consider two instructive orders.
Frame-major (raster) order concatenates complete frames: all tokens of frame 0 in raster order (left-to-right, top-to-bottom), then all tokens of frame 1, and so on. Consequences:
- Frame-major order places all preceding-frame tokens earlier in the sequence. They are eligible context when retained and allowed by the attention mask. Within-frame raster order remains a modeling choice rather than a physical law.
- Within a frame, earlier raster positions include all previous rows and earlier columns of the current row. Prior-frame information can help complete the current frame, but access alone does not establish that motion coherence is learned before appearance coherence or that one task is easier.
- Actions and rewards can be inserted at frame boundaries. This exposes preceding actions to the next-frame predictor; causal interpretation and control usefulness still require correct timing, masks, support, and dynamics.
Position-major order puts all times for one spatial position before the next position. It is a valid offline clip factorization. It is not automatically a valid online forecasting protocol: supplying observed future frames would leak information unavailable at prediction time. Same-frame positions are separated by the clip length, and simple once-per-frame action insertion is inconvenient. Actions can still be supplied through a separate interface or repeated conditioning. The ordering changes sequence distances and decoding schedule, not the existence of temporal structure.
The figure below makes the difference concrete on a toy clip: three frames, each flattened to four tokens. Numbers show each token's position in the sequence.


Beyond the flattening order, several attention structure variants are used to manage cost and inductive bias. The unifying theme is that full attention over long token streams is quadratic, and every variant below is a different guess about which attention edges can be sacrificed without losing the interactions that matter:
- Full causal attention has quadratic pairwise work. Twenty seconds at 30 frames per second and 32 tokens per frame gives 19,200 tokens. In an illustrative dense block with width and a MLP, attention mixing takes about multiply-accumulates versus for projections and the MLP, giving a crossover near . Triangular evaluation, other expansion ratios, and kernels change that estimate. Cache storage also depends on width, head layout, depth, batch, and precision.
- Sliding-window attention removes direct attention edges beyond a per-layer span. Stacked layers and contextual cached states may transmit older information indirectly, so a local mask is not equivalent to deleting all history outside that span. Test whether a needed variable survives in any accessible representation rather than treating its original token's eviction as proof of forgetting.
- Factorized spatiotemporal attention alternates within-frame spatial communication with causal same-location temporal communication. For frames and spatial tokens, dense mixing work is at fixed width, rather than for full attention. Composed spatial and temporal paths can convey cross-location motion, but do not guarantee coherence. Genie's ST-transformer uses this structure with iterative MaskGIT next-frame decoding; its bidirectional spatial layer is not the raster within-frame factorization above.
- Temporal token context lets independently encoded frames contribute cross-frame evidence. IRIS uses 16 visual tokens per frame and a 20-step context. A single instantaneous frame need not identify velocity, although blur or other cues may help; previous frames supply displacement information. DQN similarly stacked four preprocessed frames. Additional historical frames increase stored context tokens, not newly emitted tokens per step. Relative cost versus a temporal encoder depends on both implementations.
Re-grounding supplies new real observations during deployment; it can correct visible prediction errors but not necessarily hidden-state errors or consequences of past bad actions. Pure generative environments lack such a reference stream. GameNGen is a separate example of robustness training: it conditions a Stable Diffusion-based generator on prior actions and frames and adds Gaussian noise to encoded context frames during training. This is not deployment-time re-grounding. Short-horizon use may need less rollout accuracy, but even one-step errors can make a controller choose harmful actions.
Exposure Bias and Long-Horizon Generation
Pure teacher forcing uses recorded histories; autonomous rollout uses generated world tokens after its supplied initial context. The question is whether those histories differ in distribution and how the model behaves on them.
The Mechanism
During rollout, world-token contexts are generated conditionally on the initial observation and supplied actions; those supplied inputs are not themselves sampled from the model. Model errors can shift later contexts and provoke further errors, but may also leave them in distribution or self-correct. Flawless-path probability is a different quantity. Let denote success at step and . Then the chain rule gives
where:
- : the probability of exact success at step conditional on all earlier successes
- : the rollout horizon
- : a constant conditional success probability along surviving prefixes; independent equal-accuracy steps are one sufficient special case
At and , that is about 37%. At , under 1%.
The next cell plots the illustrative constant-success law across 400 steps. Later we estimate empirical flawless survival directly; we do not assume the measured errors are independent.
import numpy as np
horizon_axis = np.arange(1, 401)
P_VALUES = [0.999, 0.99, 0.95, 0.90]
survival_curves = {p: p**horizon_axis for p in P_VALUES}
Recovery can improve current-step accuracy but cannot restore a rollout's flawless-so-far status after a failure. Dependence can raise or lower survival relative to a product of marginal accuracies. For example, perfectly shared success events give survival at every horizon, whereas independent successes give . Pairwise correlation alone does not determine higher-order intersections. A uniform conditional failure probability at least on every surviving prefix implies survival at most ; merely nonzero marginal errors do not establish that bound.
Here exposure bias means a mismatch between recorded-history and generated-history distributions. Such mismatch can worsen future predictions, but neither mismatch nor monotonically increasing error is inevitable. Flawless survival measures accumulated exact-match failures, not exposure bias by itself.
Visual artifacts require diagnosis. Biased transitions can drift, depending on propagation gains; inconsistent patch predictions can impair coherence. Blur may arise from tokenizer reconstruction or an averaging decoder, but categorical sampling selects token IDs rather than averaging their decoded values. A token-only rollout feeds those IDs back, not necessarily a blurred decoded image. An object may disappear through representation or prediction errors even while its evidence remains in context; eviction matters only when no retained information preserves the needed distinction.
It is important to separate two error sources that produce similar-looking drift, because they have different cures:
- Model error and feedback: clean one-step tests can reveal prediction errors, while rollout tests additionally expose their composition under feedback. Properly labeled generated-context training may help, but improvement and its cause require controls.
- Environmental uncertainty: a correct stochastic model reproduces a conditional distribution, not the particular realization in a recorded trajectory. Independent valid draws can disagree even with no distribution mismatch. Compare generated samples with repeated environment outcomes or a validated conditional reference; dispersion of model samples alone cannot distinguish correct uncertainty from a diverse wrong model.
Mitigations
The mitigation toolbox connects sequence modeling and control. Each intervention has its own target, information requirements, and possible side effects; no general ranking follows from the list.
- Scheduled sampling (Bengio et al., 2015) replaces some recorded prior inputs with model outputs during training. It helped particular reported tasks, but changes ordinary data likelihood. Huszár's analysis shows that its perturbed objective can be statistically inconsistent. Treat its schedule and outcomes as empirical choices rather than a universally principled repair.
- DAgger and generated-context training. DAgger aggregates expert-labeled states visited by a learner and reduces imitation learning to no-regret online learning. Its guarantees concern a suitable policy iterate under that reduction's assumptions, not monotone improvement of arbitrary neural rollouts. It needs an appropriate labeling oracle, not necessarily a simulator. Our later procedure is only inspired by this idea: it performs online corrective fine-tuning without dataset aggregation and uses reference-trajectory targets, so the DAgger theorem does not transfer.
- Input perturbations and output regularization target different mechanisms. Context perturbation trains on altered inputs; label smoothing regularizes output probabilities. Numerical token-ID distance has no inherent semantic meaning. Robustness to perturbations in a defined observation or representation metric need not extend to large changes or unstable multi-step propagation.
- Multi-step losses supervise predictions farther into a rollout. Continuous intermediates can support pathwise gradients; hard categorical choices require a specified estimator, relaxation, or surrogate. Shorter horizons may ease gradient estimation, while longer horizons cost more and can expose different errors. Neither horizon guarantees useful gradients or a valid likelihood interpretation; the exact objective matters.
- Decoding choices such as temperature, top-, or nucleus truncation change diversity and mode preference. Low model probability does not mean an event is wrong, and a confident argmax can be wrong. Conservative decoding may suppress errors or valid rare outcomes; repetition can occur in some regimes. Measure these effects on the intended distribution rather than assuming coherence improves.
- Fresh observations can reduce purely open-loop drift when the environment remains available. Re-reading generated history can preserve earlier information but supplies no independent truth correction. Replanning with observations does not eliminate model bias or confer robustness without sensing, estimation, and control assumptions.
Evaluate interventions against the properties they target. Paired image distances, distributional video metrics, exact-match rates, and controller returns answer different questions. A single prespecified metric can be useful evidence about one property, but is not a complete assessment of a world model.
Worked Example: A Tiny Multimodal Token World Model
We now build a deterministic one-dimensional world and compare prediction under recorded and generated contexts. It has three entities:
- An agent at a fine position that moves left, right, or holds, and is clipped at the walls.
- Ball 1, which moves one cell to the right each step, wrapping around.
- Ball 2 moves three cells per step with wraparound. Both balls' discrete position sequences repeat after 16 steps because 1 and 3 are coprime to 16; ball 2 has three times the displacement per step, not a shorter sampled repetition period.
The miniature uses the interleaved-token pattern of some categorical world models, without a learned visual tokenizer. An initial observation has three tokens; each transition adds an action followed by agent and ball positions. The disjoint ranges serve as exact encodings of these variables.
Action-before-observation order makes the control available at every next-frame prediction, and action targets will be masked from the loss. The two independent balls demonstrate multiple temporal processes sharing a stream; they do not simulate occlusion, visual rendering, or interacting-object physics.
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
torch.manual_seed(0)
torch.set_num_threads(2)
torch.use_deterministic_algorithms(True)
L = 16 # 1-D world size
N_ACTIONS = 3 # 0 = left, 1 = right, 2 = stay
AGENT_BASE, BALL1_BASE, BALL2_BASE = 3, 3 + L, 3 + 2 * L
VOCAB = 3 * L + 3 # 3 action tokens + 48 observation tokens
def agent_token(ap):
return AGENT_BASE + ap
def ball1_token(b):
return BALL1_BASE + b
def ball2_token(b):
return BALL2_BASE + b
def obs_tokens(ap, b1, b2):
return agent_token(ap), ball1_token(b1), ball2_token(b2)
def env_step(ap, b1, b2, a):
"""One environment transition. Works on scalars or numpy arrays."""
delta = np.where(a == 1, 1, np.where(a == 0, -1, 0))
ap2 = np.clip(ap + delta, 0, L - 1)
return ap2, (b1 + 1) % L, (b2 + 3) % L
def make_episode(rng, n_steps):
"""Serialize one episode into an interleaved action/observation stream."""
ap, b1, b2 = rng.integers(0, L, size=3)
toks = [int(t) for t in obs_tokens(ap, b1, b2)]
for _ in range(n_steps):
a = int(rng.integers(0, N_ACTIONS))
toks.append(a)
ap, b1, b2 = env_step(ap, b1, b2, a)
toks.extend(int(t) for t in obs_tokens(ap, b1, b2))
return toksThe vocabulary is 51 symbols: tokens 0–2 are actions, 3–18 are agent positions, 19–34 are ball-1 positions, and 35–50 are ball-2 positions. Next we generate a dataset of episodes and split it into training and validation sets. We also keep one short demo episode whose token stream we will visualize.
rng = np.random.default_rng(7)
## Episodes of 31 steps (127 tokens) cover every sequence position the
## open-loop rollouts below will visit, so rollout degradation cannot be
## blamed on position embeddings the model never trained on.
N_TRAIN, N_VAL, EP_STEPS = 4000, 500, 31
train_eps = [make_episode(rng, EP_STEPS) for _ in range(N_TRAIN)]
val_eps = [make_episode(rng, EP_STEPS) for _ in range(N_VAL)]
demo_tokens = make_episode(np.random.default_rng(3), 4)
def to_xy(episodes):
"""Inputs are all tokens but the last; targets are all but the first."""
x = torch.tensor([e[:-1] for e in episodes], dtype=torch.long)
y = torch.tensor([e[1:] for e in episodes], dtype=torch.long)
return x, y
X_tr, Y_tr = to_xy(train_eps)
X_val, Y_val = to_xy(val_eps)Here is what one episode looks like as a token stream, colored by modality. The stream opens with one initial observation frame (agent position, then the two ball positions), and after that the alternation is strict: action, then the three observation tokens it caused. This layout means each observation token is conditioned on the most recent action, and each observation token within a frame is conditioned on its earlier siblings, exactly the factorization from the dynamics section above.

The small GPT uses learned token and position embeddings, two pre-norm blocks, and a full-vocabulary output head. Upper-triangular masking excludes later inputs; shifting targets ensures the current input does not already reveal the target. Both are needed for valid next-token supervision.
Token ranges identify modalities directly. Position embeddings and the fixed predecessor-type pattern provide additional slot and timing cues. The shared embedding and categorical head illustrate production components, while the toy omits visual tokenization, modality constraints, caching, and large-data concerns.
class Block(nn.Module):
def __init__(self, d, n_heads):
super().__init__()
self.ln1 = nn.LayerNorm(d)
self.attn = nn.MultiheadAttention(d, n_heads, batch_first=True)
self.ln2 = nn.LayerNorm(d)
self.mlp = nn.Sequential(
nn.Linear(d, 4 * d), nn.GELU(), nn.Linear(4 * d, d)
)
def forward(self, x, mask):
h = self.ln1(x)
a, _ = self.attn(h, h, h, attn_mask=mask, need_weights=False)
x = x + a
x = x + self.mlp(self.ln2(x))
return x
class TinyGPT(nn.Module):
def __init__(self, vocab, d=64, n_layers=2, n_heads=2, max_len=128):
super().__init__()
self.tok = nn.Embedding(vocab, d)
self.pos = nn.Embedding(max_len, d)
self.blocks = nn.ModuleList(
[Block(d, n_heads) for _ in range(n_layers)]
)
self.ln_f = nn.LayerNorm(d)
self.head = nn.Linear(d, vocab)
def forward(self, idx):
if (
idx.ndim != 2
or idx.shape[0] < 1
or not 1 <= idx.shape[1] <= self.pos.num_embeddings
):
raise ValueError(
"Expected a nonempty batch within the position table"
)
T = idx.shape[1]
pos = torch.arange(T, device=idx.device)
x = self.tok(idx) + self.pos(pos)[None]
mask = torch.triu(
torch.full((T, T), float("-inf"), device=idx.device), diagonal=1
)
for blk in self.blocks:
x = blk(x, mask)
return self.head(self.ln_f(x))We train only on observation-token targets. Action prediction is unnecessary for this dynamics-only objective, although an auxiliary policy objective can serve other designs. The two independent initial ball positions are unpredictable from their earlier prefix; the reporting metric excludes these positions to evaluate transitions.
The 40-step and 200-step models begin from identical parameters and use the same seeded minibatch stream for their shared first 40 updates. This compares two points along the same teacher-forced training trajectory rather than conflating budget with initialization. It remains one seed and one task, not an architecture or scaling study.
Residual prediction error and feedback can interact, but two training budgets alone do not identify exposure bias. We therefore compare both models on paired initial states and actions, report the same per-frame exact-match event under teacher forcing and open-loop prediction, and distinguish per-step match from flawless survival.
def train_teacher_forced(model, X, Y, steps, batch=128, lr=1e-3, seed=101):
model.train()
batch_rng = torch.Generator().manual_seed(seed)
opt = torch.optim.Adam(model.parameters(), lr=lr)
n = X.shape[0]
losses = []
for _ in range(steps):
idx = torch.randint(0, n, (batch,), generator=batch_rng)
logits = model(X[idx])
loss_all = F.cross_entropy(
logits.reshape(-1, VOCAB), Y[idx].reshape(-1), reduction="none"
)
world = (Y[idx] >= 3).reshape(-1).float() # mask out action targets
loss = (loss_all * world).sum() / world.sum()
opt.zero_grad()
loss.backward()
opt.step()
losses.append(loss.item())
return losses
import copy
model_tf = TinyGPT(VOCAB)
model_short = copy.deepcopy(model_tf) # identical initialization
losses_tf = train_teacher_forced(model_tf, X_tr, Y_tr, steps=200)
losses_short = train_teacher_forced(model_short, X_tr, Y_tr, steps=40)teacher-forced loss (200 steps): 4.1260 -> 0.5646 teacher-forced loss (40 steps): 4.1260 -> 2.7346
Training losses describe fit to the supervised token objective, not calibrated uncertainty or decision usefulness. The printed first and final losses make any decrease a measured result. Held-out accuracy is broken down by modality so that different prediction difficulties remain visible.
@torch.no_grad()
def teacher_forced_accuracy(model, X, Y):
model.eval()
pred = model(X).argmax(-1)
ranges = {
"agent": (AGENT_BASE, BALL1_BASE),
"ball 1": (BALL1_BASE, BALL2_BASE),
"ball 2": (BALL2_BASE, VOCAB),
}
# The first two observation targets of an episode are the initial ball
# positions, drawn uniformly and unpredictable from any context; exclude
# them so this report measures transitions, not unpredictable initial states.
# This pooled token metric differs from per-frame exact match below.
predictable = torch.arange(Y.shape[1]) >= 2
acc = {}
for name, (lo, hi) in ranges.items():
m = predictable & (Y >= lo) & (Y < hi)
acc[name] = (((pred == Y) & m).sum() / m.sum()).item()
m = predictable & (Y >= 3)
acc["all obs"] = (((pred == Y) & m).sum() / m.sum()).item()
return acc
tf_acc = teacher_forced_accuracy(model_tf, X_val, Y_val)
short_acc = teacher_forced_accuracy(model_short, X_val, Y_val)Teacher-forced next-token accuracy on held-out episodes: modality 200 steps 40 steps agent 97.07% 23.92% ball 1 87.26% 6.75% ball 2 82.70% 6.77% all obs 89.01% 12.48%
For evaluation, each model receives the same sampled initial states and actions. The deterministic environment removes ambiguity from the reference trajectory: a mismatch is a prediction error. It does not identify whether that error arose from ordinary one-step error, altered context, finite capacity, or optimization. Matched teacher-forced predictions on these very trajectories provide a cleaner comparison than pooled token accuracy against frame-level rollout success.
Greedy decoding makes the evaluation deterministic conditional on parameters and inputs. It selects the highest model probability, which maximizes one-step accuracy only when the conditional ranking is correct. Calibration alone is insufficient, and trajectory-level behavior need not improve over sampling. We report greedy results without interpreting them as a bound on sampling damage.
def rollout_reference(rng, n_episodes, horizon, offset=0):
"""Paired true/shifted reference paths under the same exogenous controls."""
if n_episodes < 1 or horizon < 1 or 3 + 4 * horizon > 128:
raise ValueError(
"Positive batch/horizon required within the position table"
)
initial = rng.integers(0, L, (3, n_episodes))
actions = rng.integers(0, N_ACTIONS, (n_episodes, horizon))
shown = initial.copy()
shown[0] = (shown[0] + offset) % L
true_states, shown_states = initial.copy(), shown.copy()
truths = np.empty((horizon, 3, n_episodes), dtype=np.int64)
alternatives = np.empty_like(truths)
bases = np.array([AGENT_BASE, BALL1_BASE, BALL2_BASE])[:, None]
for t in range(horizon):
true_states = np.asarray(env_step(*true_states, actions[:, t]))
shown_states = np.asarray(env_step(*shown_states, actions[:, t]))
truths[t] = true_states + bases
alternatives[t] = shown_states + bases
return shown + bases, actions, truths, alternatives
@torch.no_grad()
def batched_rollout(
model,
rng,
n_episodes,
horizon,
corrupt_agent_offset=None,
mode="model",
score_alternative=False,
):
"""Return Boolean (horizon, modality, episode) correctness on paired cases.
mode='teacher' feeds reference tokens after each prediction.
mode='oracle' follows exact dynamics from the supplied initial state.
"""
if mode not in {"model", "teacher", "oracle"}:
raise ValueError("Unknown rollout mode")
if model is not None:
model.eval()
initial, actions, truths, alternatives = rollout_reference(
rng, n_episodes, horizon, offset=corrupt_agent_offset or 0
)
targets = alternatives if score_alternative else truths
seq = torch.zeros(n_episodes, 3 + 4 * horizon, dtype=torch.long)
seq[:, :3] = torch.from_numpy(initial.T.copy())
ok = np.zeros((horizon, 3, n_episodes), dtype=bool)
cur = 3
for t in range(horizon):
seq[:, cur] = torch.from_numpy(actions[:, t].copy())
cur += 1
for k in range(3):
if mode == "oracle":
pred = torch.from_numpy(alternatives[t, k].copy())
else:
pred = model(seq[:, :cur])[:, -1].argmax(-1)
ok[t, k] = pred.numpy() == targets[t, k]
seq[:, cur] = (
torch.from_numpy(truths[t, k].copy())
if mode == "teacher"
else pred
)
cur += 1
return ok
def summarize(ok):
if ok.ndim != 3 or ok.shape[0] == 0 or ok.shape[1] != 3 or ok.shape[2] == 0:
raise ValueError("Expected nonempty (horizon, 3, episodes) correctness")
exact = ok.all(axis=1)
step_acc = exact.mean(axis=1)
survival = np.logical_and.accumulate(exact, axis=0).mean(axis=1)
return step_acc, survival
HORIZON = 24
N_EVAL = 256
ok_tf = batched_rollout(model_tf, np.random.default_rng(21), N_EVAL, HORIZON)
ok_short = batched_rollout(
model_short, np.random.default_rng(21), N_EVAL, HORIZON
)
step_tf, surv_tf = summarize(ok_tf)
step_short, surv_short = summarize(ok_short)
teacher_tf = batched_rollout(
model_tf, np.random.default_rng(21), N_EVAL, HORIZON, mode="teacher"
)
teacher_short = batched_rollout(
model_short, np.random.default_rng(21), N_EVAL, HORIZON, mode="teacher"
)
matched_tf, _ = summarize(teacher_tf)
matched_short, _ = summarize(teacher_short)
oracle_clean = batched_rollout(
None, np.random.default_rng(21), N_EVAL, HORIZON, mode="oracle"
)
assert oracle_clean.all()
assert np.allclose(losses_tf[:40], losses_short, rtol=0, atol=0)Open-loop rollouts (256 episodes, horizon 24): quantity 200 steps 40 steps per-step exact match, step 1 85.9% 0.0% per-step exact match, final step 5.1% 0.0% flawless rollouts through horizon 0.0% 0.0% matched teacher-forced frame accuracy, mean 75.7% 0.1%
The matched teacher-forced curve requires all three transition tokens to be correct at a given horizon, with each target evaluated from its true preceding prefix. Open-loop exact match requires the same three targets while feeding predictions back. Both use the same initial states, actions, and positions. The gap therefore avoids the old token-versus-frame aggregation mismatch, although it remains a comparison of conditioning regimes rather than a universal measure of exposure bias.
Per-step exact match can recover after earlier failures. Flawless survival cannot: it is the fraction with every step correct so far and is nonincreasing by definition. Survival is at most current-step match at each horizon, but need not have a uniformly steeper slope. We estimate survival by intersecting events within each rollout, not by multiplying marginal accuracies. The printed values and curves determine this run's behavior without imposing a decay shape.

Fine-Tuning on the Model's Own Rollouts
We next compare self-generated-context corrective fine-tuning with continued teacher forcing. Both start from the same 200-step weights and use the same newly sampled states and action sequences, 60 optimizer updates, batch size, learning rate, and 16-step supervision horizon. Both evaluate every prefix separately, so their forward/backward call counts and token lengths are matched. Wall-clock timing can still differ. Evaluation extends to 24 steps, beyond the fine-tuning horizon.
The generated-context branch predicts along its own token history but receives targets from the original reference trajectory. These labels ask it to return to that trajectory, not to obey the environment transition starting from each hallucinated state. The original initial state and known actions make reference labels available; fixed recordings could supply the same labels without an interactive oracle. Some generated contexts can be ambiguous or inconsistent, so useful correction is not guaranteed. No dataset is aggregated, and no DAgger theorem is claimed.
def corrective_finetune(
model, rng, rounds=60, batch=64, horizon=16, lr=5e-4, self_context=True
):
"""Matched update budget; choose generated or true preceding context."""
if rounds < 1 or batch < 1 or horizon < 1 or 3 + 4 * horizon > 128:
raise ValueError("Invalid training budget or context length")
opt = torch.optim.Adam(model.parameters(), lr=lr)
model.train()
for _ in range(rounds):
opt.zero_grad()
ap = rng.integers(0, L, batch)
b1 = rng.integers(0, L, batch)
b2 = rng.integers(0, L, batch)
actions = rng.integers(0, N_ACTIONS, (batch, horizon))
seq = torch.zeros(batch, 3 + 4 * horizon, dtype=torch.long)
seq[:, 0] = torch.from_numpy(np.ascontiguousarray(AGENT_BASE + ap))
seq[:, 1] = torch.from_numpy(np.ascontiguousarray(BALL1_BASE + b1))
seq[:, 2] = torch.from_numpy(np.ascontiguousarray(BALL2_BASE + b2))
cur = 3
for t in range(horizon):
seq[:, cur] = torch.from_numpy(np.ascontiguousarray(actions[:, t]))
cur += 1
ap, b1, b2 = env_step(ap, b1, b2, actions[:, t])
for truth in (AGENT_BASE + ap, BALL1_BASE + b1, BALL2_BASE + b2):
logits = model(seq[:, :cur])
loss = F.cross_entropy(
logits[:, -1], torch.from_numpy(np.ascontiguousarray(truth))
)
(loss / (3 * horizon)).backward()
with torch.no_grad():
seq[:, cur] = (
logits[:, -1].argmax(-1)
if self_context
else torch.from_numpy(np.ascontiguousarray(truth))
)
cur += 1
opt.step()
return model
model_corrective = copy.deepcopy(model_tf)
model_extra = copy.deepcopy(model_tf)
corrective_finetune(model_corrective, np.random.default_rng(13))
corrective_finetune(model_extra, np.random.default_rng(13), self_context=False)
ok_corrective = batched_rollout(
model_corrective, np.random.default_rng(21), N_EVAL, HORIZON
)
ok_extra = batched_rollout(
model_extra, np.random.default_rng(21), N_EVAL, HORIZON
)
step_corrective, surv_corrective = summarize(ok_corrective)
step_extra, surv_extra = summarize(ok_extra)
corrective_acc = teacher_forced_accuracy(model_corrective, X_val, Y_val)
extra_acc = teacher_forced_accuracy(model_extra, X_val, Y_val)Matched 60-update continuation from the same 200-step weights: base: pooled teacher-forced token accuracy=0.8901; frame match mean steps 1-16=0.3032, 17-24=0.0698, final=0.0508; flawless through 24=0.0000 generated context: pooled teacher-forced token accuracy=0.8519; frame match mean steps 1-16=0.7190, 17-24=0.0137, final=0.0039; flawless through 24=0.0000 true context: pooled teacher-forced token accuracy=0.7940; frame match mean steps 1-16=0.9761, 17-24=0.0005, final=0.0000; flawless through 24=0.0000

In the seeded CPU run (PyTorch 2.13.0, NumPy 2.4.2), mean frame match over steps 1–16 was 30.3% for the base model, 71.9% after generated-context correction, and 97.6% after continued teacher forcing. Over steps 17–24, the same figures were 7.0%, 1.4%, and 0.05%. All three had zero flawless survival through step 24. The extra teacher-forced updates explain a stronger in-horizon gain than corrective contexts in this run; neither continuation improves final-step accuracy or 24-step flawless survival.
The comparison is intentionally allowed to fail. Additional teacher forcing can improve ordinary fitting, while corrective training may help within its supervision horizon and harm later predictions. Use the printed results for each branch rather than attributing every gain to generated-context training. A rule-based predictor can exactly simulate this finite deterministic system, but that does not prove this neural architecture will learn it perfectly. In stochastic worlds, imperfect exact-path matching can persist even for the true conditional distribution and is not itself exposure bias.
Corrupted Context: Testing Sensitivity to Initial Evidence
Finally, shift the supplied initial agent position by seven modulo sixteen while keeping the reference trajectory and actions unchanged. Because a modulo shift permutes a uniform initial distribution, the shown starting states remain in distribution. They are wrong relative to the paired reference, not intrinsically invalid inputs.
The oracle control follows the exact dynamics from the shifted initial state. If even this exact predictor disagrees with the original reference, that discrepancy is a consequence of changed evidence rather than exposure bias. A second learned-model score against the shifted oracle trajectory distinguishes fidelity to the supplied alternative state from agreement with the original trajectory. The intervention does not remove ordinary neural prediction errors.
Clean and shifted runs use paired actions and initial states. We measure agent and ball accuracy and count re-synchronization explicitly. Generated and observed tokens share the input interface without provenance labels, but this does not force equal reliance on every token. The test concerns sensitivity to initial evidence, a phenomenon that also occurs in recurrent predictors.
ok_corrupt = batched_rollout(
model_tf, np.random.default_rng(21), 256, HORIZON, corrupt_agent_offset=7
)
agent_clean = ok_tf[:, 0, :].mean(axis=1)
agent_corrupt = ok_corrupt[:, 0, :].mean(axis=1)
balls_clean = ok_tf[:, 1:, :].mean(axis=(1, 2))
balls_corrupt = ok_corrupt[:, 1:, :].mean(axis=(1, 2))
oracle_shifted = batched_rollout(
None,
np.random.default_rng(21),
N_EVAL,
HORIZON,
corrupt_agent_offset=7,
mode="oracle",
)
ok_alternative = batched_rollout(
model_tf,
np.random.default_rng(21),
N_EVAL,
HORIZON,
corrupt_agent_offset=7,
score_alternative=True,
)
agent_oracle = oracle_shifted[:, 0, :].mean(axis=1)
agent_alternative = ok_alternative[:, 0, :].mean(axis=1)
oracle_resynced = oracle_shifted[:, 0, :].any(axis=0).sum()Exact shifted oracle re-synchronized at least once: 5/256 Shifted neural agent accuracy against shifted oracle: 0.9150 Effect of one shifted agent token in the initial context: agent-token accuracy, clean start : 90.4% agent-token accuracy, corrupted start: 0.6% ball-token accuracy, clean start : 45.8% ball-token accuracy, corrupted start: 45.9%

In the same 256 paired episodes, the exact shifted oracle re-synchronized with the original agent trajectory at least once in 5 episodes. The learned agent averaged 0.6% accuracy against the original trajectory after the shift, but 91.5% against the alternative trajectory implied by its supplied initial state. Clean and shifted ball-token means were 45.8% and 45.9%. Those near-equal ball means do not establish attention independence.
Agent clipping under common actions can merge distinct positions; wraparound motion preserves circular displacement instead. The exact shifted-state oracle makes this distinction visible without attributing recovery to learned attention. Clipping itself is nonexpansive in Euclidean position and strictly contracts only when it shortens a difference; a larger surrounding transition can still expand differences. Learned-model accuracy changes do not establish whether attention routes information between independent variables. In video, spatial and temporal paths may spread errors, but raster order does not imply neighboring patches are affected first. These are hypotheses for intervention tests, not diagnoses from appearance alone.
Applications and Results
Categorical sequence world models and related interactive generators illustrate three distinct possibilities: sample-efficient control, generative interaction, and shared multimodal processing. Their results should be compared on their actual architectures and evaluations.
IRIS combines a learned visual autoencoder, a GPT-style dynamics predictor, and an actor-critic. It reports strong Atari 100k aggregate results among approaches without lookahead search; search-based comparisons differ. This demonstrates a useful categorical world-model recipe, not a proof that token loss counts cause sample efficiency. Recurrent decoders also supervise many quantities, so such a causal comparison would need matched information, objectives, and compute.
Genie combines a temporally aware ST-transformer VQ-VAE tokenizer with a learned 1,024-entry codebook, a latent action model, and masked next-frame dynamics. It uses iterative MaskGIT decoding within frames, not ordinary raster next-token generation, and evaluates fidelity, controllability, and policy learning rather than experience alone. Action-unlabeled video broadens possible training data, subject to selection, licensing, quality, and domain constraints; earlier observation-only predictive models already existed. Oasis instead uses a spatial autoencoder and latent diffusion to generate successive frames, reporting 20 frames per second on its specified hardware. Neither result validates a single shared discrete next-token mechanism or guarantees long-term object permanence.
Shared sequence processing is one route toward larger multimodal systems. Chameleon demonstrates discrete text/image early fusion; Gato combines continuous image embeddings with scalar tokens for policy outputs. Shared processing still permits modality-specific tokenizers, masks, and heads. It does not imply one scaling curve across modalities or general superiority over specialized components. Part IX develops these comparisons.
Limitations
The limitations are the mirror image of the strengths, and they deserve plain speaking.
Training and rollout contexts can differ. Teacher forcing avoids generated inputs during training but does not guarantee stable optimization. Rollout interventions trade data, compute, statistical bias, and gradient quality; they can help or harm. Our controlled fine-tuning comparison reports both branches rather than assuming improvement. Fresh observations can reduce visible drift when available, while pure generative environments must be evaluated without that correction stream.
Finite token budgets constrain representation. For a frame encoded as tokens from a -symbol vocabulary, . A -token record has entropy at most under the same vocabulary, before adding any other state or continuous inputs. Neither is a one-frame bound on everything the model can learn about the world. More residual stages lengthen the sequence; larger codebooks raise per-symbol capacity but also affect embedding and output-head costs. Spatial and temporal strides set token grids, not necessarily decoded resolution. Test retention of task-relevant distinctions rather than relying only on generic reconstruction quality.
Memory has implementation-dependent costs. A recomputed finite buffer stores token IDs exactly; rolling caches can carry older contextual information. A needed variable is absent only if no accessible representation preserves it. At fixed dimensions cached attention work per new token is linear in retained context, while full-prefix recomputation is quadratic. Longer context can help or hinder predictions and increases storage and computation. A fixed-width recurrent state offers different resource use and can be sufficient for some tasks.
Action interfaces trade precision and latency. Many robotic systems use continuous multivariate controls. A fully categorical design quantizes them, while continuous or parallel heads remain possible. Command jitter and action-bin error are not themselves bounds on physical trajectory accuracy. Sequential action decoding costs additional evaluations; batching, parallel heads, and external action proposals change the accounting. The interface should be tested against controller requirements, not chosen solely for objective uniformity.
Metrics have limited scope. Framewise LPIPS compares paired images and needs an explicit temporal aggregation for videos. FVD compares distributional feature moments, so correct population distributions match those moments; finite samples or probability calibration alone do not guarantee zero distance. Pooled metrics can also miss whether predictions use the supplied context. Exact-path comparisons can penalize valid stochastic alternatives. None guarantees controller performance or excludes model exploitation. Part XI develops more complete evaluations.
Summary
- A fully categorical world model can serialize observations, actions, and optional rewards, then predict world tokens with a causal next-token objective. Tokenization, target shifting, masks, and action semantics still require explicit design.
- Visual tokenizers impose finite representation budgets. VQ-VAE-style, residual, scalar, and lookup-free quantizers differ in geometry and training; no fixed choice guarantees task-relevant sufficiency or full code utilization.
- Actions can use discrete symbols, binned scalars, continuous heads, or latent interfaces. Latent transition codes require controllability evidence; action quantization error and sequential decoding cost have task-dependent control consequences.
- Frame-major layouts support simple online action interleaving. Position-major layouts remain valid offline factorizations but need care for online conditioning. Genie's masked next-frame decoder and Oasis's latent diffusion are distinct from raster categorical next-token decoding.
- An explicit token buffer retains a bounded record, while recurrent states and contextual caches can carry selected older information. Exact stored IDs do not guarantee useful retrieval, and per-step costs depend on the cache and attention implementation.
- Exposure bias concerns a history-distribution mismatch, not every rollout error. Constant conditional success probabilities yield flawless survival, but recovery can only improve current-step match, not restore survival. The miniature compares matched conditioning regimes, two training budgets, corrective fine-tuning against continued teacher forcing, and changed initial evidence against an exact oracle. It does not establish a universal repair or a controller benefit.
The next chapter studies diffusion denoising and flow-based transport as alternatives to categorical prediction. Continuous variants avoid discrete codebook rounding but can retain other compression and numerical losses. Both categorical and continuous models can represent multimodal futures. Total generation cost depends on the number and size of evaluations and available parallelism, not simply whether the output is discrete or continuous.
Quiz
Ready to test your understanding? Take this quick quiz to reinforce what you've learned about autoregressive token world models, tokenization, and rollout behavior.
Autoregressive Token World Models
Reference
Citation details
Cite or share this article.
Continue with the full handbook
This chapter is part of World Models Handbook. Use the handbook page to browse the complete table of contents and continue reading in sequence.
Explore World Models HandbookStay up to date
Get articles, book updates, and news delivered to your inbox.
No spam, unsubscribe anytime.
Join the community
Sign in to remove popups, track your reading progress, and join the discussion.

Comments
No comments yet. Be the first to share your thoughts!