cyks.in
~ / blog / video games / celeste-world-model-drift.md

Learning world models via Celeste

Open the Dreamer modal on Room 0 (100 m) in Celeste RL, jump right toward the first ledge, and ask the neural world model to imagine the next 30 frames with its eyes closed. Until this week, the chasm smeared into dark blue streaks and Madeline vanished by frame +5.

I already knew a full-scale world model could master the level: the site also replays a 10.5M-parameter DreamerV3 (ratio32) policy that cleared 100 m 50 out of 50 times (and exited greedily in 192 actions). What puzzled me was why the live world model running right inside the browser — a 602K-parameter (601,709) educational Recurrent State-Space Model (RSSM) in celeste-model.js — lost Madeline almost instantly.

The turning point for understanding why came from putting Ishan Shah’s TinyDreamer write-up and code side-by-side with my own browser weights (learned.js, rl-arcade.js, and train_celeste.py). Conveniently, TinyDreamer lives at almost the exact same ~550K-parameter budget. Auditing every tensor shape, loss term, and inference call against that reference turned “world models” from a box diagram in a paper into something I could break, measure, and rebuild on one 64×64 game screen.

What a world model actually is (and why one frame is not a state)

A game engine updates pixels deterministically from hidden simulator state. When Madeline jumps toward the first ledge in 100 m, a single frozen 64×64×3 RGB frame x_t does not tell you what happens next: rising toward the ledge and falling past it look nearly identical in one still picture, and invisible counters — velocity (vx, vy), coyote-jump grace ticks, jump buffer, and dash cooldown — govern the very next physics step.

An RSSM splits that hidden state into two pieces so a neural network can simulate physics from pixels alone:

From (h_t, z_t), small decoder heads reconstruct the imagined frame x̂_t, predicted reward r̂_t, and episode-alive probability ĉ_t. Crucially, the same model runs in two distinct regimes:

h_t = GRU(h_{t-1}, z_{t-1}, a_{t-1})
Eyes open (warmup / observation):  z_t ~ q(z_t | h_t, Enc(x_t))
Eyes closed (open-loop dream):      ẑ_t ~ p(ẑ_t | h_t)
Decode from latent state:           (x̂_t, r̂_t, ĉ_t) = Dec(h_t, z_t)
During warmup, the encoder sees real pixels x_t and uses posterior q to lock (h_t, z_t) onto the true jump trajectory. Once eyes close at t = 0, pixels vanish: only actions a_t and the learned prior p drive the rollout.
EYES OPEN · 5-FRAME WARMUP (t = -4..0) EYES CLOSED · OPEN-LOOP DREAM (t = +1..+30) x_t (64×64×3) Enc(x_t) → e_t Posterior q q(z_t | h_t, e_t) GRU h_t tracks (vx, vy) actions a_{-4..0} (h_0, z_0) x_t blocked (no pixels) truth frame used only for error check GRU(h, ẑ, a) step hidden h_t Prior p p(ẑ_t | h_t) only a_t + ẑ_{t-1} feed t+1 Decode x̂_t, r̂_t, ĉ_t to +30f
Two modes of the same RSSM. Warmup feeds real frames through q(z_t | h_t, e_t) so h_0 captures motion. Once dreaming starts at t = 0, the encoder turns off and any error in p(ẑ_t | h_t) feeds directly back into the GRU.

Debugging the 602K model: half the drift was the input, half was the bottleneck

When I probed the original 601,709-parameter browser model directly in Node and Chrome, the failure split cleanly into inference bugs on the page and structural bugs inside the weights.

On the browser side, the default live observation mode passed one single frame into model.initial() (h_0 = 0) and immediately closed its eyes. Because t === 0, the code skipped the GRU update entirely and tried to predict the jump with zero velocity memory. On Scenario 0 (Rising after a jump), starting from 1 frame instead of 5 nearly tripled player-region MSE even at +1 (0.0299 vs 0.0103) and +5 (0.0705 vs 0.0264, PSNR dropping from 22.05 dB to 17.89 dB).

Two rendering mismatches compounded that cold start:

Before retraining a single weight, I wired a rolling 5-frame observation warmup (observeContext) into the live arena and modal, added a camera shake off option (stabilizeCamera), cleaned Room 0’s observations, and replaced the placeholder curve with real copy-last PSNR. On an 8-trace Room 0 benchmark across jump and dash starts, just feeding those five real frames cut +5 clean error from 17.22 px (2/8) to 11.32 px (3/8 visible). On jump starts, +5 error plummeted from 23.26 px (2/4) to 4.34 px (3/4). With decorations on, +5 error fell from 13.34 px to 7.49 px.

Yet by +15 frames, the old 602K model still collapsed to 0 of 8 traces (8.71 px). Probing its weights over 300 teacher-forced gameplay steps explained why:

  1. 76.3% of the model sat in two flat linear layers: encoder.weight (2048 → 128, 262,144 params) and decoder1.weight (192 → 1024, 196,608 params) ate three-quarters of the 601,709 budget, leaving 12.9% (77,184) for an unnormalized GRUCell, 2.4% (14,192) for all six convolutions, 1.4% (8,192) for a single-linear prior, and 2.0% (12,288) for a hardcoded Room-0 background tensor baked into the decoder.
  2. Prior-posterior collapse: Even on 1-step teacher-forced checks, the prior p(z_t | h_t) only agreed with the posterior q(z_t | h_t, x_t) 46.9% of the time (6.09 nats KL). Because flipping a single z group perturbed h_t by dH = 0.885 — nearly as much as pressing Jump (0.912) or Right (0.925) — wrong discrete guesses on step 1 drowned out the action signal and smeared the walls by +15.
FROZEN 602K: JUMP +5f POSITION ERROR 1-frame cold start (h_0 = 0) 23.26 px 5-frame observeContext warmup 4.34 px • 8-trace clean +5: 17.22 px → 11.32 px (3/8) • Dash screen shake: 24.0 → 11.2 dB PSNR • +15f still drops to 0/8 visible (8.71 px) 601,709-PARAM BUDGET AUDIT 43.6% 32.7% encoder.weight (262K · 43.6%) decoder1.weight (197K · 32.7%) GRUCell 128d (77K · 12.9%) prior 1.4% + post + heads + Room-0 bg all 6 conv layers combined (14K · 2.4%) 1-step q/p code match: 46.9% (6.09 nats KL) 1 wrong code flip shifts h_t by dH = 0.885
Left: giving the unchanged 602K weights 5 frames of motion history immediately cuts jump error from 23.26 px to 4.34 px. Right: three-quarters of its parameters sat in two flat linear projections, leaving 1.4% for the prior.

Rebuilding the RSSM (730K): the DreamerV3 pieces that actually mattered

Fixing the input only proved that the dynamics model itself had to be rebuilt. I trained a 729,557-parameter RSSM v2 for 20,000 steps (52.1 min on an RTX 3060) over 425 clean PPO episodes (350 train, 75 dev; 140,979 frames across rooms 0..4, 9 discrete actions, with clouds, snow, and camera shake stripped so every bit went toward gameplay physics).

Five architectural and objective choices from DreamerV3 and TinyDreamer turned out to do almost all the heavy lifting:

  1. Overlapping strided CNN + nearest-upsample decoder: Four stride-2 4×4 convolutions (64→32→16→8→4, channels 3→16→24→32→48 with ChannelNorm and SiLU) encode the frame to 160 dims; the decoder mirrors that with nearest-neighbor 2× upsampling plus 3×3 convolutions (4→8→16→32→64) and drops the hardcoded Room-0 background bias so one compact model spans five rooms without block seams.
  2. Normalized GRU with momentum bias (h_t ∈ ℝ¹⁶⁰): Adding LayerNorm inside the reset, update, and candidate gates plus a -1.0 bias on the update gate (u_t = σ(LN(update) − 1)) keeps h_t biased toward preserving velocity unless new evidence arrives.
  3. 16 × 8 categorical bottleneck with 1% unimix: Each state holds 16 independent 8-way categoricals (48 bits/frame). During training, posterior samples use straight-through gradients so discrete picks remain differentiable, while mixing 1% uniform mass keeps probabilities away from zero so KL never spikes to infinity on a rare dash frame:
p_i = 0.99 · softmax(logits)_i + 0.01 / 8    (16 groups × 8 classes)
z_t = one_hot(sample(p)) + p − sg(p)        (straight-through estimator)
Unimix guarantees every token keeps at least 0.00125 probability; sg(·) stops gradients through the discrete sample while passing them through softmax probabilities p.
  1. Asymmetric balanced KL with free nats: A tiny 0.008 KL weight let the old posterior encode private frame details the prior could never guess (46.9% agreement). Balanced KL fixes the asymmetry directly:
L_KL = max(1.0, KL(sg(q) ‖ p)) + 0.1 · max(1.0, KL(q ‖ sg(p)))
Trained in float32 under BF16 autocast. Weighting dynamics (1.0×) ten times stronger than representation (0.1×) forces the prior p to chase q without letting the encoder collapse jump and dash states into a blurry average, while clamping below 1.0 free nat stops wasting capacity on sub-pixel noise.
  1. ROI/motion/edge weighting + open-loop rollout curriculum: On a 64×64 screen, Madeline is roughly 3×4 pixels (<0.3% of the image). Uniform RGB MSE gets a great score by painting the stone walls accurately while erasing the player completely. Weighting pixels around Madeline 41× (w = 1 + 40·1_ROI + 6·1_moved), adding a spatial edge gradient term (0.25 · edge_L1), and unrolling open-loop dreams during training (+5 steps after step 3,000, +10 after 8,000, +15 after 14,000) forces the GRU and prior to recover from their own mistakes over long horizons:
w = 1 + 40·1_ROI + 6·1_moved   (where moved = max_c |x_t − x_{t-1}| > 8/255)
L_img = 20 · mean( w · (0.7·Δ² + 0.3·|Δ|) + 0.25 · w_edge · |∇x̂ − ∇x| )
Loss scale upweights Madeline's bounding box and moving pixels (dash hair plumes, crumbling blocks) so the tiny bottleneck cannot treat her as noise.
Strided CNN Encoder 64×64 → 32 → 16 → 8 → 4×4×48 ChannelNorm + SiLU Linear → LayerNorm embedding e_t ∈ ℝ¹⁶⁰ Normalized GRU h_t ∈ ℝ¹⁶⁰ (reset/cand LN) u = σ(LN(update) − 1) in: h_{t-1}, z_{t-1}, a_{t-1} Posterior MLP q(z_t | h_t, e_t) Prior MLP p(z_t | h_t) Balanced KL (≥1 nat) 1.0 · KL(sg(q) ‖ p) + 0.1 · KL(q ‖ sg(p)) Discrete z_t 16 × 8 categoricals 48 bits / frame 1% unimix + ST grad Upsample Decoder 4 → 8 → 16 → 32 → 64 nearest + 3×3 conv no Room-0 bg bias x̂_t (64×64×3 RGB) Heads & Rollouts reward r̂_t · alive ĉ_t 41× player ROI loss +5/+10/+15 dream loss
The rebuilt 729,557-parameter RSSM v2. Moving capacity out of flat linear bottlenecks into strided convolutions, a normalized GRU, and 1.0 / 0.1 balanced KL lifted 1-step code agreement from 46.9% to 69.6% and closed-loop tracking far past +15.

Why 1-step PSNR lies — and how I evaluated the model instead

Another lesson from comparing tiny world models: never pick a checkpoint on 1-step MSE or full-frame PSNR alone. A model that simply copies the previous frame gets great PSNR because 99% of the background walls do not move. Instead, I tracked four checks at every 2,000-step checkpoint:

  1. Multi-horizon sprite recovery (±4 px template localization) out to +30 frames.
  2. Full-frame and player-ROI MSE vs. copying the last real frame.
  3. All-wait control sensitivity (wait_roi_mae): running real actions vs. pressing nothing from the same 5-frame prefix (0.0948 MAE difference in the player box at +5, 0.1416 at +15).
  4. Counterfactual action forks: starting from the exact same 5-frame history, branching two different future action sequences, and testing whether the dreamed frames match the real branch outcome better than the wrong branch.
100% 75% 50% 25% 0% 3k: +5 roll 8k: +10 roll 14k: +15 roll 2k 6k 10k 14k 18k 20k +5 dev (89.3%) Forks (82.8%, pk 87.5%) +15 dev (70.7%) +30 dev (50.7%)
Held-out evaluation across the 20,000-step RTX 3060 run. Stepping open-loop supervision from +5 to +10 and +15 pushes long-horizon recovery upward without hurting counterfactual branch accuracy.

On 75 held-out dev windows, Madeline’s sprite recovery jumped to 97.3% (0.79 px) at +1, 89.3% (2.47 px) at +5, 70.7% (4.26 px) at +15, 54.7% (5.39 px) at +20, and 50.7% (7.18 px) at +30. Full-frame RGB MSE beat copying the last real frame at every multi-step horizon (0.00369 vs 0.00407 at +5; 0.00392 vs 0.00624 at +15; 0.00489 vs 0.00656 at +30), and player-region MSE fell well below copy-last (0.0815 vs 0.1459 at +5; 0.0984 vs 0.1670 at +15). On counterfactual forks, the 730K model picked the true future action branch 82.8% of the time (53 of 64, zero ties).

On the external 8-trace clean benchmark, +5 error dropped from 11.32 px (3/8) to 2.31 px (6/8 visible; 4/4 jumps at 1.83 px, 2/4 dashes at 2.80 px), and +15 rose from 0/8 to 3/8 (11.08 px in JS; 2/4 jumps at 6.39 px). Packing the weights as Float16 base64 shrank celeste-model.js from 6.0 MiB to 1.86 MiB, and over 30-frame open-loop rollouts JavaScript matched PyTorch within 0.0047 max pixel difference (0.00075 mean).

Continuous latents: Shortcut Diffusion vs. Diffusion Forcing

Once the discrete RSSM worked in the browser, I wanted to understand its remaining blur. Compressing 64×64×3 = 12,288 channels down to 48 discrete bits/frame under an MSE pixel loss softens sharp pixel-art stone edges whenever the model hedges its bets.

Following TinyDreamer’s Dreamer-4-style recipe, I tested whether a continuous spatial latent + Shortcut Diffusion Transformer would keep sharper bricks over 30 frames on the exact same clean rooms 0..4 dataset (after fixing an interleaved train/dev split leak):

1. Flow matching (dt = 0):        x_σ = (1 − σ) z + σ ε,  predict clean ẑ ≈ z
2. Shortcut self-consistency:   step(2d) matches two steps of d  (d_min = 1/16 → dt = 0.5 at inference)
3. 2-step detached rollout:    sample ẑ_5 in 2 shortcut steps, then predict z_6
Self-consistency lets a 2-step Euler solver (dt = 0.5) generate each frame at inference instead of 16–32 slow diffusion steps.

To isolate why diffusion rollouts break in open loop, I trained two 15,000-step arms under identical data and GPU budget:

  1. Clean History (Tier3 Clean): history context tokens stay noise-free (σ_hist = 0) during training.
  2. Diffusion Forcing (Tier3 DF): each of the 5 history frames receives an independent noise level (40% clean, 45% light [0, 0.25], 15% moderate [0.25, 0.65]) during training so the transformer learns not to trust imperfect autoregressive history blindly.
SHORTCUT DIFFUSION + DF PIPELINE Spatial CNN Codec [3,64,64] ↔ [8,8,8] 0.00416 RGB MAE · 99.21% sprite roundtrip Per-Frame DF History Noise (σ_0..σ_4) 40% clean · 45% light [0,0.25] · 15% [0.25,0.65] 4-Block Causal Transformer (16 tok/f) QK-Norm · 3D RoPE · SwiGLU · AdaLN (0.25 bias) 2-step shortcut sample (dt=0.5) → 7.54 MiB ONNX 4× browser size of 1.86 MiB Float16 RSSM +15f RECOVERY UNDER HISTORY NOISE (224 CLIPS) Clean History @ hn=0.0 (MAE 0.0189) 20.1% Clean History @ hn=0.0625 (MAE 0.1969) 1.3% (collapse) Diffusion Forcing @ hn=0.0 (MAE 0.0139) 21.0% Diffusion Forcing @ hn=0.0625 (MAE 0.0145) 23.2% (stable) Dashed tick in bars: 730K RSSM v2 @ +15f = 70.7%
Left: the 1.81M-parameter continuous Shortcut Diffusion pipeline. Right: adding 0.0625 history noise collapses a clean-trained transformer (20.1% → 1.3%), whereas Diffusion Forcing stays completely stable — though still trailing the 730K RSSM on 15-frame lock.

Evaluated across 224 dev clips, the clean-history transformer looked competitive when history stayed noiseless (hn = 0.0): 93.8% sprite recovery at +1 (1.56 px), 71.0% at +5 (4.00 px), 20.1% at +15 (11.34 px), and 58.3% counterfactual fork accuracy (111/194). Add hn = 0.0625 noise to history, however, and it collapsed: +15 dropped to 1.3%, RGB MAE exploded from 0.0189 to 0.1969, and position error hit 23.99 px.

Diffusion Forcing absorbed that noise cleanly (0.0145 RGB MAE at hn = 0.0625 vs 0.0139 at hn = 0.0), posted the best pooled diffusion position error (12.53 px) and +15 dev recovery (23.2%, 10.64 px), and jumped from 1 of 8 (7.29 px) to 5 of 8 (3.82 px; 4/4 jumps at 3.19 px) on the 8-trace clean +5 benchmark (hn = 0.0). Even exported to ONNX (encoder.onnx 1.24 MiB + step.onnx 6.30 MiB, 7.54 MiB total), though, it costs 4× the browser budget of the 1.86 MiB RSSM.

Side-by-side over 30 imagined frames

The five-row strips below run the exact same Room 0 action sequence across every model in open loop (Real game, Tier1 5f = old 602K RSSM with 5-frame warmup, Tier2 RSSM = new 730K RSSM, Tier3 Clean = Shortcut Diffusion clean history, Tier3 DF = Shortcut Diffusion + Diffusion Forcing).

Five-row comparison on Room 0 jump-0 trace at +5, +15, and +30 imagined frames
Room 0 jump sequence (jump-0). Tier1 5f smears into dark streaks while holding an outdated silhouette. Tier2 RSSM tracks Madeline across the chasm through +30. Both Tier 3 diffusion rows render sharper rock and hair early on at +5, then drift or fragment around the player by +30.
Five-row comparison on Room 0 dash-0 trace at +5, +15, and +30 imagined frames
Room 0 dash sequence (dash-0). Tier2 RSSM keeps the dash plume and post-dash climb aligned with the real frame through +30. Tier3 DF stays cleaner than Tier3 Clean through +15 before artifacts gather below the ledge at +30.
Model +1 dev +5 dev +5 8-trace +15 dev +15 8-trace Fork acc. Browser size
Live baseline (602K, 1f) — — 1/8 (13.34 px dec.) — 0/8 (17.61 px clean) — 6.0 MiB
+ 5f context (602K) — — 3/8 (11.32 px) — 0/8 (8.71 px) — 6.0 MiB
RSSM v2 (730K) 97.3% (0.79 px) 89.3% (2.47 px) 6/8 (2.31 px) 70.7% (4.26 px) 3/8 (11.08 px) 82.8% (53/64) 1.86 MiB
Diffusion Clean (hn=0.0) 93.8% (1.56 px) 71.0% (4.00 px) 1/8 (7.29 px) 20.1% (11.34 px) 1/8 (11.20 px) 58.3% (111/194) 7.54 MiB ONNX
Diffusion Forcing (hn=0.0 / 0.0625) 88.4% (2.96 px) 59.4% / 58.0% 5/8 (3.82 px @0) 21.0% / 23.2% 0/8 / 1/8 59.5% / 57.5% —

The contrast is clear: continuous spatial diffusion preserves high-frequency pixel edges early and Diffusion Forcing stops autoregressive noise collapse from blowing up a rollout, yet at under 2 MiB in the browser a compact recurrent discrete bottleneck (730K RSSM) still leads by nearly 50 percentage points on 15-frame sprite tracking (70.7% vs 23.2%) and 23 points on counterfactual action forks (82.8% vs 59.5%).

The generalization cliff: what happens on 800 m

Once the 730K RSSM went live, I clicked over to 800 m in the arena — and immediately saw the world model hallucinate a completely different room layout.

Measuring 1-step reconstruction PSNR across all 12 playable rooms explained why: the model had only trained on clean rooms 0..4 (100 m – 500 m). Inside that training slice, reconstruction PSNR sits between 24.9 dB and 27.7 dB. Outside it (600 m – Summit), PSNR drops straight off a cliff to 7.0 – 8.0 dB. Specifically, 800 m scores 8.0 dB against itself and snaps to memorized 400 m at 21.4 dB.

30 dB 20 dB 10 dB 0 dB ← TRAINED (0..4) UNSEEN OOD (5..30) → 27.7 100m 25.8 200m 26.3 300m 24.9 400m 26.4 500m 7.5 600m 7.0 700m 8.0 800m 7.3 Old 7.2 2200 7.7 3000 7.3 Summ 800 m (8.0 dB vs self) snaps to 400 m (21.4 dB) No spatial skips → 48 bits memorize seen rooms instead of tile physics.
1-step reconstruction PSNR across all 12 playable rooms. Because the 48-bit discrete bottleneck has no spatial skip connections from input tiles, unseen rooms snap to whichever seen layout in 100 m – 500 m looks closest.

Technically, that makes complete sense: without local spatial skip connections or patch-wise conditioning from the input frame, a 48-bit bottleneck maps the 64×64 image to an associative index of seen room layouts. Give it an unfamiliar level (800 m) or draw a wall across 100 m, and the decoder reconstructs the nearest memorized attractor instead of true tile-by-tile physics.

Poke the failure modes yourself

The nicest part of debugging this in the browser is that every failure mode above is now an interactive button in Celeste RL:

// things to try inside the Dreamer lab
  • Toggle ◎ Track and drag ▥ Split A|B across x̂_t to watch Madeline's real and dreamed crosshairs separate while MSE softens brick edges.
  • Click 👁 Peek (q) mid-dream to open the model's eyes for one frame and watch the posterior snap z_t right back onto Madeline.
  • Switch 🎲 mode: argmax to sample z and watch the live H(p) ent. meter rise as prior uncertainty branches across jumps.
  • Hit ⚡ Fork Test to run Wait, Jump+Right, and Dash Up side-by-side from the exact same 5-frame prefix, or click ◈ Wipe h_t = 0 to induce single-frame velocity amnesia on demand.
  • Switch from 100 m to 800 m to watch the live fit dB readout drop off the generalization cliff into memorized 400 m.

Explore the live 730K RSSM modal, diagnostics, and 12-room comparison in Celeste RL.

References

$ ~/blog/celeste-world-model-drift ended █ ↑ back to top