Tokenized Game and Environment Models › From frames to environment tokens

Michael BrenndoerferJuly 19, 202612 min read
World Models HandbookAll chapters
Part 9 of 12Foundation and World-Action Models
Chapter 49Tokenized Game and Environment Models › From frames to environment tokens
Reading section 3 of 11 · From frames to environment tokens · 12 minSection 3 of 11 · 12 min

Book contents

Section 3 of 11 · 12 min read

Tokenized Game and Environment Models › From frames to environment tokensOne section · Sections in this chapter3 / 11 ↓
Reading tools Definitions & inline links

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

The starting point is a trajectory: a sequence of interactions with an environment. If we write the observation, action, reward, and termination flag at time tt, the natural notation for a trajectory is

(o0,a0,r1,d1,o1,a1,r2,d2,…,oT−1,aT−1,rT,dT,oT),(o_0, a_0, r_1, d_1, o_1, a_1, r_2, d_2, \ldots, o_{T-1}, a_{T-1}, r_T, d_T, o_T),

where:

  • ot∈RH×W×Co_t \in \mathbb{R}^{H \times W \times C}: the rendered observation at time tt in the image-based setting studied here. It may be an RGB or grayscale frame, or a stack of frames, possibly with a HUD overlay. Other interfaces, such as RAM observations, require different notation.
  • at∈Aa_t \in \mathcal{A}: the discrete control chosen at time tt. In the Arcade Learning Environment, the full discrete Atari action set has 18 controls; a game's reduced action set may contain far fewer. A multi-game dataset may use a union of the included games' actions, with each game using its applicable subset.
  • rt+1∈Rr_{t+1} \in \mathbb{R}: the reward received after the transition into time t+1t+1. Depending on the game, rewards may be sparse or frequent; pickups, scores, and deaths are possible reward events.
  • dt+1∈{0,1}d_{t+1} \in \{0,1\}: the termination flag for the transition into time t+1t+1. When dt+1=1d_{t+1}=1, the episode ends; a subsequent reset begins a new episode.
  • TT: the length of the episode.

We use tt for the observation and action indices and t+1t+1 for the reward index on purpose. Reward is associated with the transition after action ata_t; in a partially observed environment it may depend on hidden state, not solely on the two rendered frames. Part II, Ch 1: Markov and Partially Observable Decision Processes used this indexing convention. A model that misaligns rewards with actions can learn the wrong decision signal even if frame reconstruction looks good.

The tuple above is a single trajectory. The index tt labels the observation, t+1t+1 labels its reward and termination, and the episode ends at TT, so a trajectory contains T+1T+1 observations and TT action-reward bundles. Any model we build will be asked to predict the next element of this sequence given the preceding ones.

It is worth pausing on how much structure the raw trajectory leaves implicit. The observation oto_t is high-dimensional and redundant. The action ata_t is a small discrete label with no meaning until we connect it to an effect. The reward rt+1r_{t+1} and termination dt+1d_{t+1} carry explicit task feedback, yet a naive "predict the next frame" objective does not train separate predictions for them. They may also be rare compared with ordinary visual changes. The rest of this section is about the first compression step, and the following section is about the second.

Why tokenize at all

A preprocessed 84×8484 \times 84 RGB frame contains 84⋅84⋅3=21,16884 \cdot 84 \cdot 3 = 21{,}168 channel values; this is not the native resolution of every game interface. A sixty-second clip at 30 frames per second has 30⋅60=1,80030 \cdot 60 = 1{,}800 frames. Feeding all pixel values directly into a sequence model is costly, while adjacent frames share much of their content. The model may devote capacity to predicting unchanged walls instead of small events that alter the game's state.

A tokenizer can map each observation (or short clip) into a shorter sequence of discrete symbols. If the token count is reduced by 100×100\times relative to a specified raw-pixel tokenization, the dynamics model sees roughly one-hundredth as many symbols per frame. Its predictions become class labels rather than continuous intensities. A softmax over those labels represents a categorical distribution over code outcomes; whether that distribution is calibrated must be tested separately.

Environment Tokenizer

An environment tokenizer EE maps an observation, or a short temporal window of observations, to a sequence of discrete codes zt=(zt,1,…,zt,L)z_t = (z_{t,1}, \ldots, z_{t,L}) with each zt,i∈{1,…,K}z_{t,i} \in \{1, \ldots, K\}. A corresponding decoder DD attempts to reconstruct an observation from the codes. The quadruple (E,D,L,K)(E, D, L, K) is the tokenization scheme. The dynamics model is trained on the sequence of ztz_t rather than on oto_t.

The token count per frame LL and vocabulary size KK are two design knobs. LL is the number of codes emitted per observation; KK is the number of entries in the shared vocabulary. At a fixed token-count context window, increasing LL shortens the frame history that fits. Increasing KK at fixed LL does not change that token count, but changes the information capacity per token and the model's embedding and output-classification costs. These are separate tradeoffs, not interchangeable ways of setting the context length.

The combinatorial space of possible code sequences grows with both knobs. An autoregressive factorization is one tractable way to model a distribution over that space; it is not the only structured alternative.

Out[4]:
Visualization
Heatmap of log10 K^L over codebook size and tokens per frame.
Log10 of the number of possible K-ary token sequences as codebook size K and tokens per frame L vary. The combinatorial space exceeds a billion sequences for some displayed settings. Only a subset may be reachable in a particular environment; autoregression is one way to model a distribution over this space.

The tokenizer can be one of several kinds:

  • Deterministic and fixed: a hand-designed encoder, such as a color histogram or a downsample plus palette quantization.
  • Deterministic and learned: a VQ-VAE or similar autoencoder whose encoder is trained to assign a specific code to each input under a nearest-neighbor rule.
  • Stochastic and learned: a variational autoencoder with a discrete or relaxed-discrete bottleneck, where the encoder outputs a distribution over codes.
  • Temporal: a video tokenizer that maps a short clip (ot,…,ot+k)(o_t, \ldots, o_{t+k}) into a sequence of codes, so the dynamics model predicts a chunk of frames at once.

Which one you pick changes what the dynamics model sees. If the tokenizer is trained separately and frozen, the dynamics model inherits its quirks. If they are trained jointly, the dynamics objective can shape the tokenizer to keep information that matters for prediction, which is sometimes good and sometimes leads to degenerate codes. We will come back to this tradeoff.

A concrete tokenizer route: vector quantization

Vector quantization is a common discrete-tokenizer design. Walking through its codebook lookup helps explain representation errors that matter later in this chapter.

Suppose an encoder fϕf_\phi maps an observation oo to a spatial feature map of shape L×DL \times D: fϕ(o)∈RL×Df_\phi(o) \in \mathbb{R}^{L \times D}. Think of it as a grid of LL vectors, each of dimension DD. We maintain a codebook of KK vectors e1,…,eK∈RDe_1, \ldots, e_K \in \mathbb{R}^D. For each spatial position ℓ\ell, we replace the feature vector with the nearest codebook entry. This is the quantize step, and it is the only place where the continuous encoder output becomes a discrete symbol:

zℓ=arg⁡min⁡k∈{1,…,K}∥fϕ(o)ℓ−ek∥22(nearest-neighbor lookup)f^ℓ=ezℓ(replace with the codebook entry)\begin{aligned} z_\ell &= \arg\min_{k \in \{1,\ldots,K\}} \|f_\phi(o)_\ell - e_k\|_2^2 && \text{(nearest-neighbor lookup)} \\ \hat{f}_\ell &= e_{z_\ell} && \text{(replace with the codebook entry)} \end{aligned}

where:

  • fϕ(o)ℓf_\phi(o)_\ell: the encoder output at spatial position ℓ\ell, a vector in RD\mathbb{R}^D that we want to quantize
  • eke_k: the kk-th entry of the learned codebook, a representative vector in the same DD-dimensional space
  • ∥fϕ(o)ℓ−ek∥22\|f_\phi(o)_\ell - e_k\|_2^2: the squared Euclidean distance between the encoder output at position ℓ\ell and codebook entry kk, which measures how close the two vectors are
  • zℓz_\ell: the index of the nearest codebook entry, an integer in {1,…,K}\{1,\ldots,K\} that becomes the token for position ℓ\ell
  • f^ℓ\hat{f}_\ell: the quantized feature at position ℓ\ell, obtained by looking up the nearest codebook vector ezℓe_{z_\ell}, so the feature map is replaced by codebook entries before decoding

The discrete codes z=(z1,…,zL)z = (z_1, \ldots, z_L) are the tokens. The decoder gψg_\psi reconstructs an observation from the quantized features: o^=gψ(f^)\hat{o} = g_\psi(\hat{f}). Training minimizes a reconstruction loss plus a commitment term that keeps the encoder close to the codebook and a codebook term that keeps the codebook close to the encoder. The two auxiliary terms, and the straight-through estimator that lets gradients pass through the non-differentiable arg⁡min⁡\arg\min, are engineering details; the important point for us is that the tokens are category labels, not numbers, and that the codebook is a jointly learned dictionary. A code is not "a little bit like" another code in the way two nearby real numbers are close; the codes are unordered categories, and the model has to learn any similarity structure between them from data.

The quantization step partitions the encoder's feature space by nearest codebook vector. The figure below shows the assignments; it does not depict codebook collapse, because every illustrated entry is used.

Out[6]:
Visualization
Scatter plot of encoder points connected to nearest codebook vectors.
Nearest-neighbor assignment of encoder outputs to four codebook entries in a two-dimensional feature space. Several encoder points share each code, illustrating quantization. All four entries are used here, so the figure does not show codebook collapse. In training, persistently unused entries would reduce the effective vocabulary.

Several knobs matter for the downstream world model:

  • Codebook size KK. A small codebook can merge visually different inputs. A very large one increases the output vocabulary and may leave some codes poorly sampled; the actual usage distribution must be measured.
  • Tokens per frame LL. A larger LL can preserve more spatial detail, but always lengthens the dynamics sequence. Whether it retains task-relevant detail depends on the encoder and its training objective. The longer sequence also uses more of the sequence model's context window.
  • Codebook collapse. During training, only a small fraction of the codebook may receive gradient, so most codes go unused. The effective vocabulary shrinks, and the tokenizer starts aliasing inputs that should have been distinct.
  • Reconstruction vs. task sufficiency. The training objective rewards reconstructing the whole frame accurately. It does not care whether the reconstructed frame preserves the small detail that decides the game.

That last point deserves an example. Consider a key that occupies a 4×44 \times 4 pixel region on an 84×8484 \times 84 screen. It covers 4⋅4=164 \cdot 4 = 16 pixels out of 84⋅84=7,05684 \cdot 84 = 7{,}056, or about 0.23%0.23\% of the pixels. A tokenizer trained to minimize mean squared reconstruction error may devote more capacity to large, frequently visible regions such as the floor and walls than to this small key. But the game cares intensely about the key: its presence can determine whether the door opens. The tokenizer can have low average reconstruction error and still lose a variable needed for this decision. The reconstruction loss and the control task measure different things.

This is why we should not equate reconstruction error with world-model quality. As we noted in Part III, Ch 2: Sufficient State and State Abstraction, a statistic sufficient for painting need not be sufficient for decisions. A tokenizer can discard a feature needed for control while still reconstructing most pixels well. That loss can propagate downstream and may escape reconstruction-only checks; targeted event probes or control tests can reveal it earlier than a failed deployment.

Token vs. state vs. object

A token ID is a symbol from a learned dictionary. It has no intrinsic causal interpretation. A Markov state makes earlier history unnecessary for predicting the future once the current state and relevant actions are given. An object is a persistent entity in the world with identity, properties, and relations. The three can be aligned, but they are not the same thing, and a tokenized model does not automatically produce either states or objects. This is a recurring source of confusion in the literature.

A tokenized frame is an encoding that may be learned and lossy. Whether it is useful depends on the downstream task; reconstruction loss alone cannot settle whether decision-relevant distinctions survived.