all lessons/ world_models/ 09 · planning in latent worldslesson 9 / 16

Planning in latent worlds

Planning asks the model a bounded question right now: which candidate action sequence reaches the goal with acceptable risk? Search depth, rollout width, model bias, and real-time latency all collapse into one budget.

Where we are
Lesson 08 practiced in imagination until it had a fast reflex — a trained actor that maps state to action in one pass. But some decisions are too important, or too novel, for a reflex; you stop and think them through for the exact situation in front of you. That is planning, the other branch: keep the current belief, goal, and constraints online, predict the consequences of alternatives, pick a sequence, execute only what’s justified, observe, and solve again. We move from trajectory scoring to shooting, CEM, receding-horizon MPC, tree search, and MuZero’s value-equivalent dynamics.
Forced by 08An actor amortized from imagined rollouts. This stepPlan at decision time: shooting, CEM, MPC, MCTS, MuZero — width × depth × latency. Forces 10Prediction scales better when state factors by things.

1 · Planning is optimization wrapped around prediction

The model already answers a conditional question: given belief bt and a proposed action sequence at:t+H−1, what future states and outcomes follow? A planner simply wraps an optimizer around that answer — pick the sequence with the best predicted utility, subject to the action, state, and compute limits you face:

at:t+H−1* = arg minat:t+H−1 ∈ A E[Σk=0H−1 γk c(ŝt+k,at+k) + γH cterminalt+H)]

Term by term: H is the planning horizon; A is the set of allowed sequences (with bounds like steering rate or joint torque); c(s,a) is immediate cost (negative reward if you prefer to maximize); γ discounts distant cost; ŝ marks a model-predicted state; the expectation averages the uncertain futures. That last piece, cterminal, estimates cost beyond the horizon — leave it out and the planner learns to shove every crash one step past where it can see.

Innocent as it looks, that objective hides four independent choices: how to represent current state, how to predict consequences, how to score goals and risk, and how to search actions under a deadline. “Use a world model for planning” is not an algorithm until you pin down all four.

2 · MPC turns feedback into error correction

You could optimize a whole sequence once and execute all of it — but then every model error rides along to the end. Model predictive control (MPC) instead uses a receding horizon: at each step it solves an H-step problem, executes just the first action (or a short safe prefix), takes a new observation, updates belief, shifts the window, and solves again.

receding-horizon MPC repeat at control time t: bₜ ← state_estimator(history, newest_observation) Uₜ ← optimize_sequences(world_model, bₜ, objective, constraints, budget) execute first action aₜ = Uₜ[0] observe reality; update history warm-start next search with shift(Uₜ)

Throwing away all but the first action isn’t waste — the rest were conditional promises about a predicted future, and once reality weighs in, revising them is the whole point. Replanning quietly converts feedback into model-error correction: a gust shoves the drone, a camera reveals the obstacle was closer than believed, the tires grip differently than the latent thought — and the next optimization simply starts from the corrected state. MPC doesn’t make model quality irrelevant (between corrections you still need accurate local effects, some failures outrun the control rate, and the optimizer can exploit error even in a short window) — but closed-loop correction lets a merely local model solve tasks that would defeat a long open-loop rollout.

Planning is a width × depth budget
Increase horizon until the goal appears; increase candidate rollouts to find a route around the obstacle. In production the same product competes with latency.
Interactive planning search.
rollouts
horizon
goal
control loop

3 · Random shooting: the honest baseline

What’s the simplest optimizer that could work? For continuous control, just guess a lot and keep the best. Sample N full action sequences from a proposal, roll each through the model, score it, take the winner. No derivatives, and it parallelizes beautifully:

random_shooting(bₜ, horizon H, samples N): for i = 1 ... N in parallel: Uᵢ = (aᵢ,0 ... aᵢ,H−1) ~ proposal trajectoryᵢ ~ world_model(bₜ, Uᵢ) Jᵢ = risk_adjusted_cost(trajectoryᵢ, Uᵢ) return U_argmin(J)

It’s a great sanity baseline because its failure is legible. If good trajectories occupy a decent slice of proposal space, enough samples hit one. But with d-dimensional actions over horizon H, the search lives in roughly dH dimensions, and the useful fraction can shrink exponentially with horizon. Uniform motor noise also produces jittery, physically implausible controls. Smooth correlated noise, action-repeat, splines, a model-free policy proposal, or a shifted previous plan concentrate samples on realistic sequences. And a discipline that never expires: never compare optimizers without equalizing model evaluations and wall-clock latency — a method that looks better may just be running ten times more simulated transitions. Report the objective and what it cost.

4 · CEM: learn where to look, during this one decision

Shooting wastes samples in bad regions. The cross-entropy method (CEM) fixes that by adapting its proposal as it goes. Start with a Gaussian over the action sequence, sample candidates, keep the best K as “elites,” refit the mean and variance to those elites, and repeat for a few rounds. (The “cross-entropy” name is about fitting the proposal toward the elite distribution — it’s optimization, not the classification loss that shares the name.)

μj+1 = α μj + (1−α) mean(Uelite) σ²j+1 = α σ²j + (1−α) var(Uelite)

j indexes the CEM rounds; μ,σ² are the proposal parameters at every action time and dimension; the elites are the lowest-cost candidates; smoothing α ∈ [0,1) stops the distribution from collapsing too fast. Bounds are handled by truncation, clipping, or a tanh-squashed variable.

CEM(bₜ, H, N, elite_count K, iterations L): (μ, σ) ← warm_start_or_default(H) repeat L times: sample N action sequences Uᵢ ~ TruncatedNormal(μ, σ) evaluate risk-adjusted predicted cost Jᵢ from bₜ E ← K sequences with smallest J μ ← smooth(μ, mean(E)); σ ← smooth(σ, std(E)) enforce minimum σ to preserve search diversity return best evaluated sequence, or μ

CEM needs no gradients, tolerates discontinuous collision penalties, and steers later samples toward promising regions. Its failure modes are just as concrete: it can converge to one mode and miss a narrow alternative, or lock confidently onto a model hole. Too large an elite fraction barely concentrates; too small makes updates noisy. A minimum variance, multiple proposal modes, restarts, and uncertainty-aware costs are the usual guards.

5 · Watch CEM steer around an obstacle

Put a planar point robot at (x,y)=(0,0) that must reach (4,0) in four actions, each a displacement of length at most one, with a circular obstacle of radius 0.7 at (2,0). Cost:

J(U) = ‖p4−g‖² + 20 Σk=14 𝟙[‖pk−(2,0)‖ < 0.7] + 0.1 Σk=14 ‖ak‖²

Squared goal error, plus 20 per predicted step inside the obstacle, plus a small control penalty. Start with a proposal aimed straight right: μ0,k=(1,0), σ0,k=(0.5,0.5). Straight-line samples collide, because the centerline goes through the obstacle.

Say round one draws 64 sequences and keeps the best eight — four passing above, four below. With a single Gaussian, their vertical components average back toward zero: a concrete multimodality failure. Suppose the top route wins the tie and the elite vertical means become (0.55, 0.45, −0.35, −0.45) — rise, cross above, descend. Smooth with α=0.2 and the new mean is 0.8×elite + 0.2×old-zero ≈ (0.44,0.36,−0.28,−0.36); round two samples that corridor and tightens.

Say the best sequence ends at (3.8,0.1), never enters the obstacle, and uses four unit actions — cost (−0.2)² + 0.1² + 0 + 0.1×4 = 0.45. The straight sequence reaches the goal but clips the obstacle once at p2=(2,0) — cost 20 + 0.1×4 = 20.4. Crucially, CEM learned no permanent policy; it fit a temporary distribution for this one decision. MPC then executes only the first up-and-right action; if the robot moves less than predicted, the next observation changes p1, the old sequence is shifted as a warm start, and CEM re-solves from the measured spot. That combination — temporary plan plus feedback — is why CEM-MPC shrugs off moderate model mismatch that would sink an open-loop four-step solution.

6 · Gradients and learned proposals add structure

If the dynamics and cost are differentiable, you can skip sampling: initialize the action variables and descend ∂J/∂at:t+H−1 through the unrolled model. In a high-dimensional action space this can use each model evaluation far more efficiently than sampling — but it’s vulnerable to local minima, saturated action bounds, chaotic long-horizon derivatives, and simply wrong model gradients. (A model can predict values fine while having derivatives that point the optimizer at nonsense.) A learned actor adds a different kind of structure: draw proposals near π(a|s), then let CEM or gradients refine them for the current goal. This splits habit from deliberation — the actor amortizes the common case, planning spends compute where this situation is unusual. Keep some broad samples anyway, or a biased actor can quietly stop search from ever finding a different route.

7 · Put risk and constraints inside the objective

Minimizing expected cost is wrong when a rare collision matters more than average progress. With a stochastic model you have options: optimize a worst-case ensemble member, a high cost quantile, or conditional value at risk:

CVaRα(J) = E[J | J is in the worst (1−α) tail]

At α=0.9, CVaR averages the worst ten percent of predicted costs. A simpler score is E[J] + κ·Std[J], with κ setting risk aversion. And keep the two uncertainties distinct: disagreement because the model lacks data argues for caution or exploration; irreducible outcome noise may demand a robust action even with abundant data. Above all, a hard constraint should not be a mere finite penalty if violation is unacceptable — because some predicted reward can always be made large enough to outweigh a finite number. Candidate rejection, control barrier functions, reachability filters, a verified emergency brake, or a separate safety shield belong outside the learned objective. Planning strengthens a safety case; it does not create one.

8 · Tree search for discrete, branching decisions

Shooting treats an action sequence as one flat vector. But in chess, board games, or routing, actions branch discretely and many prefixes are shared — so re-sampling whole sequences wastes work. Monte Carlo tree search (MCTS) stores those shared prefixes in a tree, and each simulation selects a child, expands a new node, evaluates its future, and backs up value along the path. Selection uses a PUCT-style score:

a* = arg maxa [Q(s,a) + cpuctP(s,a) √(ΣbN(s,b)) / (1+N(s,a))]

Q(s,a) is the mean backed-up value of action a; P(s,a) is a learned policy prior; N(s,a) is the visit count; cpuct tunes exploration. The first term exploits actions that look good so far; the second is large for promising-but-rarely-tried actions, steering simulations toward uncertainty within the tree (distinct from real-environment exploration).

MCTS(root, simulation_budget B): repeat B times: node ← root; path ← [] while node is expanded: action ← argmax PUCT(node, action) append (node, action) to path node ← learned_or_known_dynamics(node, action) (policy_prior, leaf_value) ← evaluate_and_expand(node) back up rewards and leaf_value through reversed(path) return action distribution proportional to root visit counts

Unlike independent shooting, MCTS pours repeated compute into promising prefixes and returns a refined action distribution at the root. It’s less natural for wide continuous action spaces (unless you discretize or progressively widen), and its irregular, sequential memory access is harder to batch on accelerators. Depth, simulation count, branching factor, and leaf-value accuracy jointly set quality.

9 · MuZero learns a model for search, not for reconstruction

Classical thinking says learn the actual next observation. MuZero asks a sharper question: what must a model preserve so that MCTS chooses good actions? The answer is reward, value, and policy-relevant transition structure — not necessarily pixels, colors, or a faithfully reconstructed board. It splits into three learned functions:

s0 = hθ(o1:t)    representation (r̂k+1, sk+1) = gθ(sk, ak)    dynamics (p̂k, v̂k) = fθ(sk)    prediction

Representation h maps observation history to a root latent; dynamics g takes a latent and a hypothetical action and emits predicted immediate reward and next latent; prediction f emits a policy prior and a scalar value. MCTS uses g to expand hypothetical edges and f to prioritize and score nodes. Training unrolls recorded actions through g, supervising predicted reward by observed reward, predicted value by a bootstrapped or search-enhanced return target, and predicted policy by the MCTS root visit counts:

L = Σk=0K[ℓvalue(v̂k, zt+k) + ℓpolicy(p̂k, πt+k) + 𝟙k>0reward(r̂k, rt+k)] + regularization

K is the training unroll depth; z is a value target (not a stochastic latent here); π is the search policy from visit counts. So the model is trained precisely so that search over its own latent predictions improves the decision targets that then retrain it — a self-consistent loop.

10 · Value equivalence is precise — and task-relative

A model is value equivalent for a policy class and reward family if planning in it gives the same relevant values as the real environment, even when its internal state is not a faithful reconstruction. Two physical states may collapse to one latent if no allowed action and target objective ever needs to tell them apart — and MuZero exploits exactly that freedom.

But this is not the universal claim that “only value matters.” Equivalence is relative to what you ask. Picture two visually identical boxes, one fragile, one reinforced: if the training reward only measures how fast the robot touches a box, material gets discarded — change the goal to “lift without damage” and the old latent can’t recover it. A chess model needn’t render wood grain, but it must keep every board distinction that changes legal moves or future value. So derive the representation from the job, not from a catalog of model families:

  1. If the future job is unknown, preserve broadly predictive evidence. Observation prediction keeps features needed to predict sensors — improving reuse and interpretability. The naive hope that “accurate pixels ⇒ accurate decisions” fails both ways: capacity leaks into irrelevant texture, while a tiny reward-critical fact barely moves pixel error and gets dropped anyway.
  2. If the job is stable and search is the bottleneck, preserve decision consequences directly. Reward, value, and policy prediction keep exactly what the current decision needs — compact and search-efficient, because wood grain and lighting never enter the latent. The cost arrives when the question changes: a new reward may need something compression threw away.
  3. If it must decide now and transfer later, give the state several obligations. A multi-head model keeps current task signals plus selected physical or semantic facts — preserving focus while transferring better. The real cost: more objectives consume capacity, interact through gradients, and need deliberate loss balancing.

The diagnostic follows the requirement: probe the latent with counterfactual queries outside the training reward — change the goal, ask for a physical property, alter a constraint while holding observations fixed. If search fails because the needed distinction is simply absent even with a strong optimizer, the representation was sufficient for the old query and insufficient for the new one. “Minimal sufficient state” always needs you to finish the sentence: sufficient for what?

11 · What actually distinguishes the methods

The names click into place once you ask four questions in order: what object is optimized, when is it optimized, what action geometry does it assume, and what survives after this decision?

  1. Random shooting optimizes by selecting among finite sampled sequences, at every decision, for any sampleable action type; afterward the samples vanish and only the world model (plus an optional proposal) persists.
  2. CEM optimizes the proposal distribution, through several sample–elite–refit rounds per decision, best suited to bounded continuous control; the fitted Gaussian is temporary (discarded or shifted forward), and the persistent knowledge stays in the world model.
  3. Gradient planning optimizes the action variables directly through differentiable dynamics, at each decision, for smooth continuous actions; what must persist is a differentiable model whose gradients are actually useful.
  4. MPC optimizes no unique object of its own — it is the repeated plan/execute-a-prefix/observe/replan pattern, wrapping whatever inner solver you choose; the persistent system is estimator + model + objective + constraints + optimizer.
  5. MCTS optimizes a selective discrete tree and its root visit distribution, at each decision, natural for shared-prefix discrete branching; the tree is mostly temporary, while model, policy prior, and value estimator persist.
  6. MuZero trains the model that MCTS searches — learning representation, latent dynamics, reward, policy, and value across experience while MCTS runs online, usually over discrete actions; what persists is the value-equivalent latent model’s weights.

The prose above explains why each has its shape; the table is just a lookup once that’s understood:

MethodWhat is optimized?When?Natural action geometryWhat persists?
Random shootingA finite sampled set of action sequencesEvery decisionAny sampleable continuous or discrete sequenceWorld model and proposal rule
CEMA proposal distribution fitted to elite sequencesSeveral rounds inside each decisionUsually bounded continuous controlWorld model; optionally a shifted warm start
Gradient planningThe action variables themselvesEvery decisionSmooth continuous actions and costsDifferentiable world model and initialization
MPCWhatever its inner solver optimizesPlan, execute a prefix, then replanInherited from the inner solverEstimator, model, objective, constraints, solver
MCTSA selective tree and root visit distributionEvery discrete decisionShared-prefix discrete branchingModel, policy prior, and value estimator
MuZeroNetworks that make latent tree search decision-usefulNetworks train across experience; MCTS runs onlineUsually discrete actionsRepresentation, dynamics, reward, policy, and value weights
Resolve the apparent competition
The category error is “CEM versus MPC,” as if they were peers. The physical need is feedback after model error — that derives MPC. The computational need inside each MPC step is continuous trajectory optimization — that may derive CEM. Likewise MCTS is the online tree procedure, while MuZero supplies the learned latent dynamics, priors, rewards, and values that make it useful without a known simulator.

This also gives a debugging order. If the chosen sequence is poor even inside a trusted model, fix the inner optimizer. If the first action is good open-loop but failures grow after disturbances, inspect state estimation and replanning frequency. If search is systematic but reality disagrees with its rankings, inspect the world model or objective. The method name alone never tells you which link broke.

12 · Diagnostics before you trust closed-loop success

  1. Optimizer regret under a trusted simulator. On small cases where exhaustive or high-budget search is possible, compare the online optimizer’s cost with the reference — isolating search quality from model error.
  2. Open-loop prediction by horizon. Replay recorded actions and measure state, reward, constraint, and uncertainty error at every depth. The planning horizon should not exceed where task-critical predictions stay meaningful without correction.
  3. Predicted vs realized plan ranking. Execute safe candidate prefixes and check that lower predicted cost reliably means lower realized cost. Ranking usually matters more than pixel reconstruction.
  4. Width/depth/latency curves. Sweep candidates, horizon, CEM iterations, or MCTS simulations, plotting task return and tail latency. A method that misses its control deadline is not better.
  5. Warm-start ablation. Compare shifted previous plans, actor proposals, and cold starts — stale warm starts can trap an optimizer after abrupt goal changes.
  6. Uncertainty and support trace. Plot ensemble disagreement or data distance along the selected plan versus random alternatives. Selection drifting toward high uncertainty signals exploitation.
  7. Constraint stress tests. Perturb mass, friction, delay, obstacle position, and sensor noise; verify both planner behavior and the independent safety layer.
  8. Search-model consistency for MuZero. Compare root values before search, after search, and against realized returns; inspect visit entropy and reward predictions by unroll depth. Strong search targets can’t compensate forever for drifting latent dynamics.

13 · Planning is a real-time systems problem

A controller with a 50 ms deadline has a finite inference budget. Roughly, model work scales with candidate count × horizon × stochastic particles × optimization iterations (batching and tree reuse change the constants). Longer horizon reveals distant goals but compounds error; more width covers alternatives but raises latency; more uncertainty samples estimate tail risk but cut throughput. Production design uses the whole stack: cache the encoded current state, batch rollouts, drop to lower precision where calibrated, warm-start from the shifted plan, spend extra search only when uncertainty or novelty is high, keep a small verified fallback controller, and record both mean and worst-case latency. If the model is a slow diffusion generator, it may make gorgeous video and still be unusable in a high-frequency servo loop — the representation has to match the control clock.

So choose abstraction by decision timescale. A millisecond stabilizer may use linear local dynamics; a one-second route planner uses latent objects; a minute-scale task planner uses symbolic subgoals. A hierarchical system plans coarse subgoals at long horizon and lets low-level MPC enforce smooth motion — one monolithic model need not answer every timescale at the same resolution.

14 · Failure modes and concrete responses

Where this points next

Every planner here assumes its state keeps the entities and relations that make consequences predictable. A single unstructured vector can forget which object slid behind which wall, confuse camera motion with object motion, or lose identity across occlusion. Lesson 10 introduces object-centric state, spatial frames, and persistent memory so prediction and planning can factor by things, geometry, and relations.

Takeaway
Planning is online optimization over action-conditioned predictions. Shooting samples sequences; CEM repeatedly fits a temporary proposal to elites; MPC is the feedback architecture that executes a prefix and replans; MCTS allocates discrete search to shared prefixes; MuZero learns task-relative latent dynamics sufficient for reward, policy, and value search rather than observation reconstruction. Choose by action structure, risk, transfer needs, horizon, and real-time budget — and always diagnose model error separately from search error.

Interview prompts