# World models and planning: from prediction to closed-loop control

> A world model predicts how actions change state. A planner compares candidate sequences and corrects its plan with observations. This tutorial explains latent dynamics and verifies replanning after a map error with a grid simulator.

- URL: https://dmxsf.com/en/wiki/multimodal/world-models/
- [DMXSF](https://dmxsf.com/en/about/)
- Intermediate
- Updated: 2026-11-23
- Tags: Multimodal, Reinforcement learning, Embeddings

## After this page you will be able to

- Distinguish observations, task-relevant state, candidate actions, and goals.
- Write down action-conditioned prediction and finite-horizon planning.
- Reproduce the difference between open-loop execution and feedback on an incorrect map.
- Measure one-step prediction, planning, and closed-loop success separately.

A world model predicts what may happen after an action. It can predict pixels, task-relevant features, or an explicit task state. A planner compares candidate actions using those predictions, then acts in the environment and observes the result. That feedback loop is where predictive accuracy has to become control performance.

*Figure: The planner compares candidate routes in its model, executes only a short segment, then updates the plan from a new observation.*

## Observations, states, and actions

A camera frame is an observation. The position of an occluded object or whether a gripper has made contact belongs to the state a controller needs. Sometimes a single frame suffices. Sometimes a sequence or an additional sensor is necessary. A slipping gripper and one that has yet to make contact may look alike in one frame and call for different actions. A history or an uncertainty estimate helps preserve that distinction.

| Quantity | Mobile robot | Robotic arm |
| --- | --- | --- |
| Observation | Camera frame and wheel odometry | Frames, gripper opening, and force |
| State representation | Position, heading, and nearby paths | Object pose and contact state |
| Action | Move, turn, or stop | Move the end effector or open the gripper |
| Goal | Reach a destination without collision | Place the object in the target area |

A representation is adequate for a particular task. Position can suffice on a clear map. A narrow turn may require heading and obstacle information, and a deformable object can make contact and shape important. Test whether the representation preserves distinctions that change the predicted result of a counterfactual action.

## From future frames to latent dynamics

An encoder maps observation $o_t$ to $z_t=f(o_t)$. An action-conditioned model takes action $a_t$ and predicts the next representation:

$$
\widehat z_{t+1}=g(z_t,a_t)
$$

A training objective can compare the prediction with the encoded future observation $f(o_{t+1})$ or decode the prediction and compare pixels. Feature prediction can focus learning on information retained in the representation. Pixel prediction offers directly inspectable videos. Either objective calls for checking task-relevant information. If all observations map to a constant vector, feature prediction can have low error while offering no way to distinguish goals from obstacles.

The [Stanford CS25 V6 lecture on joint embedding predictive architectures](https://web.stanford.edu/class/cs25/) explores feature prediction. [V-JEPA 2](https://arxiv.org/abs/2506.09985) learns to predict masked representations from videos, then uses action-labelled trajectories for its action-conditioned variant, V-JEPA 2-AC. Watching an object move in natural video does not identify the outcome of a specific control command. Check that actions and observations are aligned in the post-training data.

[World Models](https://dmxsf.com/en/blog/world-models-ha-schmidhuber/) compresses the environment into a latent state and learns control in imagination. [DreamerV3](https://dmxsf.com/en/blog/dreamerv3-mastering-diverse-domains-through-world-models/) trains its policy with imagined latent trajectories. A deployed planner can also use predictions to search for actions for the current goal. Ask how the imagined trajectory is used: to update a policy or to pick an action for the current decision?

### What the two CS25 models change

[Causal-JEPA](https://arxiv.org/abs/2602.11389) represents a scene as object slots. It masks some object states in the history so the predictor uses other objects to reconstruct them and predict the future. If the history of a ball about to move is hidden, the other ball's position and velocity can be more informative than background pixels. The paper compares object masking against an alternative using the same object representation. That ablation helps separate compact representations from a learning objective that encourages interaction modeling. Masking supplies an inductive bias for interactions. The objective alone cannot establish that the model recovered the true physics.

[LeWorldModel](https://arxiv.org/abs/2603.19312) learns features end to end from pixels. A prediction loss makes the next embedding predictable. A distribution regularizer encourages embeddings to spread toward an isotropic Gaussian and helps prevent constant representations. At inference, encode the start and goal images, roll out candidate action sequences, and rank them by terminal embedding distance. The cross-entropy method keeps the better candidates and refits the action distribution iteratively. Candidate count, search iterations, and horizon determine the main planning budget. Compare object-slot quality, predictive error, planning latency, and closed-loop success separately.

## Plan with the model and act in the environment

Choose a prediction horizon $H$. From estimated state $z_t$, apply $g$ to a candidate sequence $a_t,\dots,a_{t+H-1}$ and score the result. For a target distance $d$ and per-step cost $c$:

$$
J(a_{t:t+H-1}) = d(\widehat z_{t+H},z_{\mathrm{goal}})
+ \sum_{i=0}^{H-1} c(\widehat z_{t+i},a_{t+i})
$$

Small discrete spaces can use enumeration or breadth-first search. In continuous action spaces, one option is to sample sequences and refine the sampling distribution. A longer horizon can reveal a detour. It also gives errors more time to accumulate and costs more to search. Receding-horizon control plans a sequence, executes the first action or short chunk, observes the outcome, and plans again. On limited hardware the time to produce the next action belongs in the evaluation.

When an action fails, trace the failure to its stage. A state estimator may overlook an obstacle, the dynamics model may predict an impossible transition, the cost may omit collision penalties, and the controller may fail to track a valid command. Store observations, candidate actions, predicted transitions, and actual actions for paired comparisons.

## Experiment: a missing wall changes the plan

The example uses a synthetic two-by-four grid. The predicted map omits a wall. Open-loop execution commits to its first plan. A feedback variant updates the wall map and replans when an action predicts movement but the state stays still. Coordinates are zero-based row and column. The example ran on an Apple M2 Max with the Python 3.12.14 standard library.

```python
from __future__ import annotations

from collections import deque

Cell = tuple[int, int]
MOVES = ((0, 1), (1, 0), (0, -1), (-1, 0))

def step(cell: Cell, move: Cell) -> Cell:
    return cell[0] + move[0], cell[1] + move[1]

def plan(
    start: Cell,
    goal: Cell,
    walls: set[Cell],
    shape: Cell,
) -> tuple[Cell, ...] | None:
    """Find a shortest sequence, or None if the goal is blocked."""
    queue = deque([(start, ())])
    seen = {start}
    while queue:
        cell, actions = queue.popleft()
        if cell == goal:
            return actions
        for move in MOVES:
            row, col = target = step(cell, move)
            inside = 0 <= row < shape[0] and 0 <= col < shape[1]
            if inside and target not in walls and target not in seen:
                seen.add(target)
                queue.append((target, (*actions, move)))
    return None

def traverse(replan: bool, shape: Cell = (2, 4)) -> tuple[Cell, ...]:
    """Execute with an incorrect map and optional feedback."""
    start = (0, 0)
    goal = (0, shape[1] - 1)
    actual_walls = {(0, 2)}
    modeled_walls: set[Cell] = set()
    cell = start
    trace = [start]
    actions = plan(start, goal, modeled_walls, shape)
    while actions and cell != goal:
        move, *rest = actions
        target = step(cell, move)
        row, col = target
        inside = 0 <= row < shape[0] and 0 <= col < shape[1]
        if inside and target not in actual_walls:
            cell = target
        trace.append(cell)
        if replan and cell != target:
            modeled_walls.add(target)
            actions = plan(cell, goal, modeled_walls, shape)
        else:
            actions = tuple(rest)
    return tuple(trace)

fixed = traverse(False)
feedback = traverse(True)
assert fixed[-1] == (0, 1)
assert feedback[-1] == (0, 3) and len(feedback) == 7
print("open loop:", *fixed)
print("replanned:", *feedback)
```

```text
open loop: (0, 0) (0, 1) (0, 1) (0, 1)
replanned: (0, 0) (0, 1) (0, 1) (1, 1) (1, 2) (1, 3) (0, 3)
```

The widget below turns this execution into a step-by-step grid replay: pick a policy and walk the run with previous/next — see where the agent tries to go each step, where it actually stays, and when the model marks the wall into its own map.

The fixed plan assumes that each previous move succeeded and gets stuck repeating the same action. The replanner continues from the observed location and reaches the goal after a failed probe. In this deterministic example a single observation identifies the error. Friction, sensor noise, and actuator saturation can also stop a real robot, so one stalled move may justify gathering evidence rather than permanently updating the map.

## Evaluate prediction, planning, and execution

| Layer | Hold fixed | Record |
| --- | --- | --- |
| One-step prediction | Observation and actual action | Pose or contact error by action type |
| Multi-step prediction | Start state and given action sequence | Error by horizon and constraint violations |
| Planning comparison | Search budget, goal, and model | Feasible candidate rate, plan cost, and time |
| Closed-loop execution | Initial scenes and goals | Success, collisions, replans, and delays |

Using true transitions in place of the learned model gives an oracle comparison. Feeding true states in place of encoder outputs isolates representation errors. If planning still fails with those inputs, inspect search and cost. Evaluate a fixed action trace across competing models to isolate prediction. Also allow each deployed policy to run closed-loop, since prediction errors change the future states it visits.

Outside the training distribution a model may assign high scores to impossible outcomes. Repeated search can find these shortcuts. Constrain admissible actions and states and use shorter horizons, conservative actions, or extra observations when predictions are uncertain. The visual quality of generated video alone gives little evidence about closed-loop success.

## Summary and exercises

- Encode observations into a state that distinguishes the effects of relevant actions.
- Use predictions to compare sequences and actual observations to correct the plan.
- Measure one-step error, rollout error, and task execution separately.

### Quick self-check

**1. What suggests a representation has lost control information?**

- [x] Contact and no contact have the same representation but different action outcomes.
- [ ] Image color changes without affecting location or action outcome.

> Keep distinctions that change how actions affect the task.

**2. What follows the first action under receding-horizon planning?**

- [ ] Always execute the remainder of the original plan.
- [x] Read a new observation and plan the remaining actions again.

> Feedback lets the planner start from the actual state.

**3. What should you measure alongside low prediction error?**

- [x] Closed-loop success and constraint violations by action type.
- [ ] Training reconstruction loss alone.

> Search can visit unfamiliar states and errors can accumulate over multiple steps.

**4. How can you isolate state estimation errors?**

- [ ] Change the encoder, dynamics, and search budget together.
- [x] Hold the planner and dynamics fixed and provide true states.

> Changing one stage at a time helps locate the source of the failure.

### Move the wall next to the start

Change the actual wall from $(0,2)$ to $(0,1)$. Predict both final states and count the failed probes made by the feedback policy. Then block both exits and inspect how the planner represents an unreachable goal.

<details>
<summary>Worked answer</summary>

The fixed sequence stays at the start. The feedback version probes the wall once, takes the lower corridor, and reaches the goal. If both legal exits are blocked, after observing both failures, breadth-first search returns no path. Log unreachable goals separately from action failures and planning timeouts.

</details>

## Further reading

- [Stanford CS25 V6 schedule](https://web.stanford.edu/class/cs25/), lecture on joint embedding predictive architectures.
- [V-JEPA 2](https://arxiv.org/abs/2506.09985) on video prediction and action-conditioned planning.
- The [World Models](https://dmxsf.com/en/blog/world-models-ha-schmidhuber/) and [DreamerV3](https://dmxsf.com/en/blog/dreamerv3-mastering-diverse-domains-through-world-models/) explainers.

## Companion code

[World models: plan, observe, and replan](https://github.com/dmxsf/dmxsf/tree/main/labs/multimodal/world-models): Compare fixed execution with feedback on a grid with a hidden wall.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run multimodal/world-models`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/world-models/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/multimodal/world-models/README.en.md)
- [`world_models.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/multimodal/world_models.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#world-models)

## FAQ

### Does a world model need to generate video?

A world model can predict pixels, latent features, or explicit state. It needs to retain information that lets a planner compare actions.

### Why update the plan during execution?

Observations reveal prediction errors and state changes. Receding-horizon planning uses the latest observed state to choose the next action.

### What data does action-conditioned prediction need?

Align observed transitions with the actions actually executed. Natural video can pretrain a representation, and action-labelled trajectories help learn the effects of controls.
