Code Architecture — World Models
Overview
The notebook builds the three World Models modules from scratch in PyTorch: a convolutional VAE (V), an MDN-RNN (M) that also predicts the reward, and a linear controller (C). V and M are trained on random rollouts of a small 2D navigation task, PointMassNav. C is then trained with a simple evolution strategy entirely inside the dream generated by M, and tested in the real environment against two random baselines. A final diagnostic checks how much V’s latents say about the positions in the frame.
Section-by-Section Breakdown
1. Setup & Imports
- PyTorch, NumPy and matplotlib; nothing is installed
- Seeds
random, NumPy and PyTorch withSEED = 42; runs on the CPU with one thread andtorch.use_deterministic_algorithms(True)so reruns give the same numbers - Figures as JPEG at 80 dpi; on Kaggle an
atexithook copies the executed notebook toexecuted_solution.ipynb
2. Toy Environment: PointMassNav
- State: agent
(x, y)and target(x, y), both drawn uniformly from [−0.8, 0.8]² at reset - Action:
(dx, dy)clipped to [−1, 1]; the agent moves by0.1 · actionand stays inside [−1, 1]² - Observation: a 64×64 grayscale frame with the agent as a 3×3 bright square (1.0) and the target as a small cross (0.7)
- Reward: −distance to the target each step, +10 when the distance falls below 0.1, which also ends the episode; episodes last at most 100 steps
3. Collect Random Rollouts
collect_rollouts: 50 episodes with uniformly random actions, giving 4,749 frames with their actions and rewards
4. VAE Module (“V”)
- Encoder:
Conv2d(1→32)→Conv2d(32→64)→Conv2d(64→128), each with kernel 4, stride 2 and ReLU (64 → 32 → 16 → 8), then flatten (8,192 values) straight into two linear layers for μ and log σ² (32 each) - Decoder:
Linear(32 → 8,192), reshape to 128×8×8, then three transposed convolutions back to 1×64×64 (logits) - Loss: binary cross-entropy on the logits plus the KL term (β = 1), Adam with learning rate 1e-3, batch 128, 30 epochs
- 1,123,713 parameters; a figure compares four frames with their reconstructions
5. MDN-RNN Module (“M”)
MDNRNN:LSTM(32 + 2 → 128); a linear MDN head with K × (2 · 32 + 1) = 5 × 65 = 325 outputs (5 mixture logits, 5 × 32 means, 5 × 32 log-standard-deviations, clamped to [−5, 2]); and a linear reward head with 1 outputmdn_loss_fn: negative log-likelihood of the next latent under the diagonal Gaussian mixture, averaged over unpadded stepsencode_mu: encodes frames to the VAE mean μ, which is used as z everywhere after training Vprepare_sequences: builds padded whole-episode tensors (50 × 100) of z_t, a_t, z_{t+1}, rewards and a mask- Training: batches of 10 episodes, loss = NLL + 10 × reward MSE, Adam with learning rate 1e-3, 200 epochs
6. Controller Module (“C”)
Controller:a = tanh(W [z, h] + b)withLinear(32 + 128 → 2), 322 parameters
7. Dream Environment
DreamEnv: runs a batch of hallucinated episodes using only Mreset(start_idx): starts from the latents of real frames (all 4,749 collected frames are possible start states), with an empty LSTM statestep(action): feeds (z_t, a_t) and the carried LSTM state into M; samples a mixture component and the next z with temperature τ = 1.15 (mixture logits divided by τ, standard deviations multiplied by √τ); the reward is M’s predicted reward; episodes end after 100 steps- Uses its own seeded
torch.Generator
8. Train Controller with Evolution Strategy
batched_actions: applies 64 different controllers to their own dream episodes in one batched operationevaluate_in_dream: average predicted return of each parameter vector over the same 16 start states- ES loop: population 64, σ = 0.1, 60 generations; centered rank weights (
rank / (64 − 1) − 0.5, summing to zero) and the updatemean += 0.5 / 64 · (weights @ noise); the mean controller is scored each generation - The final mean parameters are loaded into
controller; a figure plots population mean, population best and mean-controller returns
9. Transfer to the Real Environment
run_real_episode: encodes each real frame with V, runs M on (z_t, a_t) with its carried state to get h_t, and steps the real environmentevaluate_real_env: 20 episodes with seeds 100–119; reports mean reward, final distance, start distance and how often the target was reached
10. Comparison: Baselines vs Dream-Trained Controller
- Baselines on the same 20 episodes: a randomly initialised controller and uniformly random actions
- Table of mean reward, final distance and successes, plus the differences in mean reward
- Diagnostic: a linear probe from z to the agent and target positions on 300 fresh frames, R² measured on 100 more; and the controller’s predicted dream return next to its real return
11. Visualize Trajectories
- Paths of the dream-trained controller in three real episodes (seeds 0–2)
12. Summary
### What the run above shows: the saved run’s real numbers
Key Functions/Classes
| Name | Purpose |
|---|---|
PointMassNav | 2D navigation task rendered as 64×64 frames |
collect_rollouts | Random-policy episodes for training V and M |
VAE | Convolutional VAE, 64×64 frame ↔ 32-dim z |
MDNRNN, mdn_loss_fn | LSTM with a mixture density head for z_{t+1} and a reward head |
encode_mu, prepare_sequences | Frames → z, and padded episode tensors for M |
Controller | Linear policy on [z, h] |
DreamEnv | Batched dream rollouts run by M with temperature τ |
batched_actions, evaluate_in_dream | Scores a whole ES population in the dream at once |
run_real_episode, evaluate_real_env | Tests a policy in the real environment |
Data Flow / Shapes
frame (64, 64) → V.encode → μ = z (32,)
(z_t, a_t, LSTM state) → M → mixture params (325,), predicted reward (1,), h_t (128,)
dream: sample z_{t+1} ~ mixture(τ = 1.15); reward = predicted reward
[z_t (32,), h_t (128,)] → C → a_t (2,)
ES: population (64, 322) × 16 dream episodes → batch of 1,024 dream rollouts of 100 steps
Deliberate Simplifications vs. the Paper
- Environment: a toy 2D navigation task instead of CarRacing-v0 and VizDoom: Take Cover.
- Where C trains: inside the dream, like the paper’s VizDoom experiment; the paper’s CarRacing controller was trained in the real environment.
- What M predicts: the next z and the reward; the paper’s VizDoom M predicted the next z and whether the agent dies.
- Optimizer for C: a simple rank-based evolution strategy instead of CMA-ES.
- Scale: 50 random rollouts instead of 10,000; a 32-dim latent and 128 LSTM units; 1-channel frames instead of RGB.
- Latent: the VAE mean μ is used as z after training, instead of a sampled z.