Skip to content

Planning ​

INFO

このページはまだ翻訳されていません。 英語版を読む

A trained WorldModel can imagine the outcome of any action sequence. Planning searches for the sequence whose imagined final latent is closest to the latent of a goal.

Rollout and cost ​

Both come with WorldModel, built on your predict:

python
z = model.encode(pixels[:, :1])        # (B, 1, D) context latents
traj = model.rollout(z, actions)       # actions (B, T, A)  ->  latents (B, T + 1, D)
cost = model.cost(traj, goal)          # goal (B, D)        ->  (B,)

rollout predicts one step at a time and feeds each prediction back in, keeping the last model.history latents. cost is the mean squared distance between the final latent and the goal; override it for another metric (RoboJEPA uses L1).

The cross-entropy method ​

CEM keeps a diagonal Gaussian over action sequences. Each iteration it samples num_samples sequences, rolls them all out in one batch, and refits the Gaussian to the num_elites cheapest.

python
from torch_world.planning import CEM

planner = CEM(horizon=5, action_dim=2, num_samples=512, num_elites=48, iterations=10, bounds=(-1, 1))
actions = planner(model, z, goal)      # (B, horizon, action_dim), the final mean
argumentmeaning
horizonlength of the planned action sequence
num_samples, num_elitespopulation size and number kept per iteration
iterationsrefits of the Gaussian
stdinitial standard deviation (the mean starts at zero)
boundsclamp samples to the action space

The batch dimension is preserved: B problems are planned in parallel, B × num_samples rollouts per iteration.

Context and conditioning ​

With more than one context frame, pass the actions taken between them as past_actions (B, T0 - 1, A). Extra keyword arguments are forwarded to model.rollout, repeated for every sample. That is how DINO-WM gets proprioception and RoboJEPA gets states and embodiment ids:

python
planner(model, z, goal, states=env.state[:, None], embodiment=ids)

Pass a torch.Generator as generator for reproducible plans.

GRASP: gradient-based planning ​

GRASP (Psenka et al., 2026) optimizes the plan by gradient descent instead of sampling. The latents between the current one and the goal become free variables, initialized on the line between them, so every step is predicted in parallel from its own start latent:

loss = Σ_t |F(sg(s_t), a_t) − s_{t+1}|² + goal_weight · Σ_t cost(F(sg(s_t), a_t), g)

The stop-gradient sg means actions get gradients through the model but latents never do through its state Jacobian. Each iteration takes an Adam step on both, then adds Gaussian noise to the latents to escape local minima. Every sync_every iterations a few Adam steps on the actions alone minimize model.cost of a full rollout, which keeps the plan feasible.

python
from torch_world.planning import GRASP

planner = GRASP(horizon=5, action_dim=2, bounds=(-1, 1))   # defaults: the authors' LeWM settings
actions = planner(model, z, goal)                          # (B, horizon, action_dim)
argumentmeaning
iterationsgradient steps on states and actions (750)
lr_states, lr_actionsAdam learning rates of the latents and the actions
noisestd of the Gaussian noise added to the latents after each step
goal_weightweight of the per-step goal term
sync_every, sync_steps, sync_lrhow often and how hard actions are refined on the full rollout (sync_every=0 disables it)
sync"gd": Adam steps on the actions; "cem": CEM around them (sync_samples, sync_elites), exploring most where the relaxed latents and the rollout disagree
warm_startstart each call from the previous plan shifted by this many executed steps (set it to execute; call planner.reset() between episodes)
boundsclamp actions to the action space

GRASP takes the same past_actions, conditioning and generator as CEM. It needs a differentiable model and runs with gradients enabled even under torch.no_grad, without accumulating any into the model's parameters. The authors' LeWM Push-T result (46% against CEM's 22% at horizon 15, plan executed in full) uses sync="cem", sync_steps=5. GRASP's advantage is at long horizons; replanning a short horizon every chunk is where CEM is strongest. See the notebook and the reproduction report for GRASP against CEM on Two-Rooms and Push-T.

MPPI: planning for reward ​

TD-MPC2 plans for the highest return instead of toward a goal. MPPI scores action sequences with model.estimate_value: predicted rewards over the horizon plus a learned value at its end. Each iteration it adds num_pi_trajs sequences from the model's policy prior to Gaussian samples, and refits the Gaussian to the num_elites best, weighted by softmax(temperature * value). The plan it returns is one elite drawn with those weights.

python
from torch_world.planning import MPPI

planner = MPPI(horizon=3, action_dim=2)                          # the paper's settings
plan = planner(model, model.encode(obs[:, None]), explore=True)  # (B, horizon, action_dim), in [-1, 1]

MPPI remembers its last mean and starts the next call from it, shifted by one step: call planner.reset() between episodes. explore=True adds noise with the final std, as when collecting data.

Mixed precision ​

Planning under torch.autocast("cuda", dtype=torch.bfloat16) is safe: the rollout runs in bf16, but CEM, MPPI, GradientPlanner (and so HierarchicalPlanner) and GRASP's CEM sync score and rank candidates in fp32 and keep their sampling distribution in fp32. bf16 keeps about three significant digits, and candidate costs often differ by less than that, mostly when a large part of the distance to the goal does not depend on the actions. Ranked in bf16, the elites become noise: PLDM on Two-Rooms fell from 94% success in fp32 to 0%.

Plans come back in the context latents' dtype. Ranking in fp32 removes the cost's rounding, not the rollout's: a model whose bf16 predictions are far from its fp32 ones can still plan differently, so compare against fp32 once before relying on bf16.

Closed loop ​

Model-predictive control: plan, execute the first action, observe, plan again. run_policy runs any policy(observation) -> action in an environment and returns the visited states.

python
from torch_world.envs import run_policy

with torch.no_grad():
    goal = model.encode(env.render(goal_states)[:, None])[:, 0]

paths = run_policy(env, lambda obs: planner(model, model.encode(obs[:, None]), goal)[:, 0], steps=20)
distance = (paths - goal_states[:, None]).norm(dim=-1)   # (B, steps + 1)

Evaluating goal reaching ​

goal_reaching runs several policies from the same starts toward the same goals and scores them with the environment's own distance and success:

python
from torch_world.evaluation import goal_reaching, random_policy

env.reset()
start, goals = env.state.clone(), env.sample_goals((0.2, 0.5))
with torch.no_grad():
    goal = model.encode(env.render(goals)[:, None])[:, 0]

result = goal_reaching(
    env,
    {"LeWM + CEM": lambda obs: planner(model, model.encode(obs[:, None]), goal)[:, 0], "random": random_policy(env)},
    start, goals, steps=20,
)
result.rates()        # success rate per policy, e.g. {"LeWM + CEM": ..., "random": ...}
result.distances      # per policy, (B, steps + 1) distance to the goal at every step

plots.distances(result.distances, radius=env.radius) and plots.trajectories draw the result; see Figures.

Long evaluations ​

Each MuJoCo environment keeps one renderer per image size, shared by its cameras; env.close(), or a with block, frees their GL contexts. Close environments you are done with, and reuse one environment across episodes rather than making a new one per episode: on a headless GPU server, contexts that pile up in one process can stall it inside EGL.

A stall in native code cannot be interrupted from Python. For a long evaluation, run_episodes runs episode(seed) for every seed in one worker process with a time limit per episode. A stalled episode is recorded as "timeout", its worker is replaced and the next seed runs; each record is appended to a JSON Lines file as it finishes, and a rerun skips the seeds already there:

python
from torch_world.evaluation import run_episodes

def episode(seed):  # at the top level of a module; the worker imports it
    ...             # load the model and environment once (e.g. with functools.cache), run one episode
    return {"success": success}

records = run_episodes(episode, range(48), timeout=600, path="episodes.jsonl")

The first episode's time limit also covers the worker's start-up, such as loading the model.