Skip to content

torch_world.planning ​

INFO

本页尚未翻译。 阅读英文版

class CEM ​

torch_world.planning.CEM GitHub

python
CEM(
    horizon: int,
    action_dim: int,
    num_samples: int = 300,
    num_elites: int = 30,
    iterations: int = 10,
    std: float = 1.0,
    bounds: tuple[float, float] | None = None,
    objective: str = "final",
    keep_mean: bool = False,
)

Cross-entropy method over action sequences in the latent space of a WorldModel.

Each iteration samples num_samples sequences from a diagonal Gaussian, rolls them out with the model and refits the Gaussian to the num_elites cheapest under model.cost. The "final" objective scores the last imagined latent; "path" averages the cost of every imagined latent, which rewards getting close early. Under MPC, where only the first action runs, "path" keeps the planner from postponing its moves. With keep_mean the first sample of every iteration is the current mean, as in stable-worldmodel's CEM, so a good mean is never lost to an unlucky draw.

Costs are ranked in fp32 and the sampling distribution is kept in fp32 even when the caller runs under torch.autocast: bf16 keeps about three significant digits, too few to order close candidate costs.

Source code in torch_world/planning/cem.py
python
class CEM:
    """Cross-entropy method over action sequences in the latent space of a ``WorldModel``.

    Each iteration samples ``num_samples`` sequences from a diagonal Gaussian, rolls them out with the model and
    refits the Gaussian to the ``num_elites`` cheapest under ``model.cost``. The ``"final"`` objective scores the last
    imagined latent; ``"path"`` averages the cost of every imagined latent, which rewards getting close early. Under
    MPC, where only the first action runs, ``"path"`` keeps the planner from postponing its moves. With ``keep_mean``
    the first sample of every iteration is the current mean, as in stable-worldmodel's CEM, so a good mean is never
    lost to an unlucky draw.

    Costs are ranked in fp32 and the sampling distribution is kept in fp32 even when the caller runs under
    ``torch.autocast``: bf16 keeps about three significant digits, too few to order close candidate costs.
    """

    def __init__(
        self,
        horizon: int,
        action_dim: int,
        num_samples: int = 300,
        num_elites: int = 30,
        iterations: int = 10,
        std: float = 1.0,
        bounds: tuple[float, float] | None = None,
        objective: str = "final",
        keep_mean: bool = False,
    ):
        if objective not in ("final", "path"):
            raise ValueError(f"objective must be 'final' or 'path', not {objective!r}")
        self.horizon, self.action_dim = horizon, action_dim
        self.num_samples, self.num_elites, self.iterations = num_samples, num_elites, iterations
        self.std = std
        self.bounds = bounds
        self.objective = objective
        self.keep_mean = keep_mean

    @torch.no_grad()
    def __call__(
        self,
        model: WorldModel,
        z: Tensor,
        goal: Tensor,
        past_actions: Tensor | None = None,
        generator: torch.Generator | None = None,
        **cond,
    ) -> Tensor:
        """Plan ``(B, horizon, action_dim)`` from context latents ``z`` ``(B, T0, ...)`` toward ``goal`` ``(B, ...)``.

        ``past_actions`` ``(B, T0 - 1, action_dim)`` are the actions between context frames; ``cond`` tensors with a
        batch dim are forwarded to ``model.rollout``.
        """
        B, S, T0 = z.size(0), self.num_samples, z.size(1)
        mean = z.new_zeros(B, self.horizon, self.action_dim, dtype=torch.float32)
        std = torch.full_like(mean, self.std)
        z, goal, cond = _repeat(z, S), _repeat(goal, S), {k: _repeat(v, S) for k, v in cond.items()}
        past = _repeat(past_actions, S) if past_actions is not None else z.new_zeros(B * S, 0, self.action_dim)
        for _ in range(self.iterations):
            noise = torch.randn(B, S, self.horizon, self.action_dim, device=z.device, generator=generator)
            samples = mean[:, None] + std[:, None] * noise
            if self.keep_mean:
                samples[:, 0] = mean
            if self.bounds is not None:
                samples = samples.clamp(*self.bounds)
            rollout = model.rollout(z, torch.cat([past, samples.flatten(0, 1).to(past.dtype)], dim=1), **cond)
            if self.objective == "path":
                cost = torch.stack([fp32_cost(model, rollout[:, : t + 1], goal) for t in range(T0, rollout.size(1))])
                cost = cost.mean(0)
            else:
                cost = fp32_cost(model, rollout, goal)
            cost = cost.view(B, S)
            elites = samples[torch.arange(B)[:, None], cost.topk(self.num_elites, largest=False).indices]
            mean, std = elites.mean(1), elites.std(1)
        return mean.to(z.dtype)

class GRASP ​

torch_world.planning.GRASP GitHub

python
GRASP(
    horizon: int,
    action_dim: int,
    iterations: int = 750,
    lr_states: float = 0.1,
    lr_actions: float = 0.005,
    noise: float = 0.005,
    goal_weight: float = 1.0,
    sync_every: int = 50,
    sync_steps: int = 10,
    sync_lr: float = 0.05,
    bounds: tuple[float, float] | None = None,
    sync: str = "gd",
    sync_samples: int = 64,
    sync_elites: int = 8,
    sync_var_scale: float = 1.0,
    sync_var_min: float = 0.01,
    warm_start: int = 0,
)

Gradient RelAxed Stochastic Planner: gradient descent on actions and on free "virtual" intermediate latents.

Instead of backpropagating through a long serial rollout, the latents s_1 .. s_{H-1} between the current latent s_0 and the goal g (s_H = g) become optimization variables, initialized on the line from s_0 to g. Every step is then predicted in parallel from its own (stop-gradient) start latent:

loss = sum_t |F(sg(s_t), a_t) - s_{t+1}|^2 + goal_weight * sum_t cost(F(sg(s_t), a_t), g)

Actions get gradients through the model, latents only from the dynamics term, never through the model's state Jacobian. Both take an Adam step (lr_states, lr_actions), then Gaussian noise noise is added to the latents to explore. Every sync_every steps (0 disables it) the actions are refined against the true objective, model.cost of a full rollout from the context, which keeps the relaxed plan dynamically feasible, and the joint optimizer restarts. The first step is predicted from the full context z (and past_actions); the others from their single virtual latent.

The sync is one of the authors' two variants. sync="gd" takes sync_steps Adam steps (sync_lr) on the actions. sync="cem" runs sync_steps CEM iterations of sync_samples samples and sync_elites elites around the current actions; the first iteration's variance per step is sync_var_scale times the gap between the rollout and the virtual latents (where the relaxation broke down, it explores more) plus sync_var_min. The authors' LeWM Push-T result (46% against CEM's 22% at horizon 15) uses sync="cem" with sync_steps=5.

With warm_start=k, a call starts its actions from the previous plan shifted by k steps, the ones executed in between, padded with zeros, as stable-worldmodel's policy does when it replans before the plan runs out. Under RecedingHorizon this is its execute. Call reset between episodes.

Psenka et al., "Parallel Stochastic Gradient-Based Planning for World Models", 2026. Paper: https://arxiv.org/abs/2602.00475 Code: https://github.com/michael-psenka/grasp (LeWM adapter: https://github.com/michael-psenka/le-wm-grasp)

Source code in torch_world/planning/grasp.py
python
class GRASP:
    """Gradient RelAxed Stochastic Planner: gradient descent on actions and on free "virtual" intermediate latents.

    Instead of backpropagating through a long serial rollout, the latents ``s_1 .. s_{H-1}`` between the current
    latent ``s_0`` and the goal ``g`` (``s_H = g``) become optimization variables, initialized on the line from
    ``s_0`` to ``g``. Every step is then predicted in parallel from its own (stop-gradient) start latent:

        loss = sum_t |F(sg(s_t), a_t) - s_{t+1}|^2 + goal_weight * sum_t cost(F(sg(s_t), a_t), g)

    Actions get gradients through the model, latents only from the dynamics term, never through the model's state
    Jacobian. Both take an Adam step (``lr_states``, ``lr_actions``), then Gaussian noise ``noise`` is added to the
    latents to explore. Every ``sync_every`` steps (``0`` disables it) the actions are refined against the true
    objective, ``model.cost`` of a full rollout from the context, which keeps the relaxed plan dynamically feasible,
    and the joint optimizer restarts. The first step is predicted from the full context ``z`` (and ``past_actions``);
    the others from their single virtual latent.

    The sync is one of the authors' two variants. ``sync="gd"`` takes ``sync_steps`` Adam steps (``sync_lr``) on the
    actions. ``sync="cem"`` runs ``sync_steps`` CEM iterations of ``sync_samples`` samples and ``sync_elites`` elites
    around the current actions; the first iteration's variance per step is ``sync_var_scale`` times the gap between
    the rollout and the virtual latents (where the relaxation broke down, it explores more) plus ``sync_var_min``.
    The authors' LeWM Push-T result (46% against CEM's 22% at horizon 15) uses ``sync="cem"`` with ``sync_steps=5``.

    With ``warm_start=k``, a call starts its actions from the previous plan shifted by ``k`` steps, the ones executed
    in between, padded with zeros, as stable-worldmodel's policy does when it replans before the plan runs out. Under
    ``RecedingHorizon`` this is its ``execute``. Call ``reset`` between episodes.

    Psenka et al., "Parallel Stochastic Gradient-Based Planning for World Models", 2026.
    Paper: https://arxiv.org/abs/2602.00475
    Code: https://github.com/michael-psenka/grasp (LeWM adapter: https://github.com/michael-psenka/le-wm-grasp)
    """

    def __init__(
        self,
        horizon: int,
        action_dim: int,
        iterations: int = 750,
        lr_states: float = 0.1,
        lr_actions: float = 0.005,
        noise: float = 0.005,
        goal_weight: float = 1.0,
        sync_every: int = 50,
        sync_steps: int = 10,
        sync_lr: float = 0.05,
        bounds: tuple[float, float] | None = None,
        sync: str = "gd",
        sync_samples: int = 64,
        sync_elites: int = 8,
        sync_var_scale: float = 1.0,
        sync_var_min: float = 0.01,
        warm_start: int = 0,
    ):
        if sync not in ("gd", "cem"):
            raise ValueError(f"sync must be 'gd' or 'cem', not {sync!r}")
        if sync == "cem" and not 1 < sync_elites <= sync_samples:
            raise ValueError("sync='cem' needs 1 < sync_elites <= sync_samples")
        self.horizon, self.action_dim, self.iterations = horizon, action_dim, iterations
        self.lr_states, self.lr_actions, self.noise, self.goal_weight = lr_states, lr_actions, noise, goal_weight
        self.sync_every, self.sync_steps, self.sync_lr = sync_every, sync_steps, sync_lr
        self.sync, self.sync_samples, self.sync_elites = sync, sync_samples, sync_elites
        self.sync_var_scale, self.sync_var_min = sync_var_scale, sync_var_min
        self.bounds, self.warm_start = bounds, warm_start
        self.plan: Tensor | None = None

    def reset(self):
        self.plan = None

    def __call__(
        self,
        model: WorldModel,
        z: Tensor,
        goal: Tensor,
        past_actions: Tensor | None = None,
        generator: torch.Generator | None = None,
        **cond,
    ) -> Tensor:
        """Plan ``(B, horizon, action_dim)`` from context latents ``z`` ``(B, T0, ...)`` toward ``goal`` ``(B, ...)``.

        ``past_actions`` ``(B, T0 - 1, action_dim)`` are the actions between context frames; ``cond`` tensors with a
        batch dim are forwarded to ``model.rollout``. Runs with gradients enabled even under ``torch.no_grad``; the
        model's parameters get none.
        """
        B, H = z.size(0), self.horizon
        z, goal = z.detach(), goal.detach()
        past = z.new_zeros(B, 0, self.action_dim) if past_actions is None else past_actions
        frac = torch.arange(1, H, device=z.device, dtype=z.dtype).view(1, -1, *[1] * (goal.dim() - 1)) / H
        states = (z[:, -1:] + frac * (goal - z[:, -1])[:, None]).requires_grad_()
        actions = z.new_zeros(B, H, self.action_dim)
        if 0 < self.warm_start < H and self.plan is not None and self.plan.shape == actions.shape:
            actions[:, : H - self.warm_start] = self.plan[:, self.warm_start :]
        actions.requires_grad_()
        cond_steps = {k: _repeat(v, H - 1) for k, v in cond.items()}
        goal_steps = goal.repeat_interleave(H, dim=0)

        def joint_optimizer():
            return torch.optim.Adam(
                [{"params": [states], "lr": self.lr_states}, {"params": [actions], "lr": self.lr_actions}]
            )

        opt = joint_optimizer()
        with torch.enable_grad():
            for k in range(self.iterations):
                pred = model.rollout(z, torch.cat([past, actions[:, :1]], dim=1), **cond)[:, -1:]
                if H > 1:
                    s, a = states.detach().flatten(0, 1)[:, None], actions[:, 1:].flatten(0, 1)[:, None]
                    rest = model.rollout(s, a, **cond_steps)[:, -1].unflatten(0, (B, H - 1))
                    pred = torch.cat([pred, rest], dim=1)
                dynamics = (pred - torch.cat([states, goal[:, None]], dim=1)).square().flatten(2).mean(2).sum(1)
                to_goal = model.cost(pred.flatten(0, 1)[:, None], goal_steps).view(B, H).sum(1)
                loss = (dynamics + self.goal_weight * to_goal).sum()
                states.grad, actions.grad = torch.autograd.grad(loss, [states, actions])
                opt.step()
                with torch.no_grad():
                    states.add_(
                        self.noise * torch.randn(states.shape, device=z.device, dtype=z.dtype, generator=generator)
                    )
                    if self.bounds is not None:
                        actions.clamp_(*self.bounds)
                if self.sync_every and (k + 1) % self.sync_every == 0:
                    if self.sync == "cem":
                        self._cem_sync(model, z, goal, past, actions, states, cond, generator)
                    else:
                        self._sync(model, z, goal, past, actions, cond)
                    opt = joint_optimizer()
        self.plan = actions.detach().clone()
        return actions.detach()

    def _sync(self, model, z, goal, past, actions, cond):
        """Adam on the actions alone against the cost of a full rollout from the context."""
        opt = torch.optim.Adam([actions], lr=self.sync_lr)
        for _ in range(self.sync_steps):
            cost = model.cost(model.rollout(z, torch.cat([past, actions], dim=1), **cond), goal).sum()
            (actions.grad,) = torch.autograd.grad(cost, [actions])
            opt.step()
            if self.bounds is not None:
                with torch.no_grad():
                    actions.clamp_(*self.bounds)

    @torch.no_grad()
    def _cem_sync(self, model, z, goal, past, actions, states, cond, generator):
        """CEM around the actions, with a first variance per step from the gap between rollout and virtual latents."""
        B, H, A, N, T0 = z.size(0), self.horizon, self.action_dim, self.sync_samples, z.size(1)
        mean = actions.detach().float().clone()
        rollout = model.rollout(z, torch.cat([past, mean.to(past.dtype)], dim=1), **cond).float()
        if H > 1:
            gap = (rollout[:, T0 : T0 + H - 1] - states.float()).square().flatten(2).mean(2)
            gap = torch.cat([gap.mean(1, keepdim=True), gap], dim=1)
        else:
            gap = (rollout[:, -1] - goal.float()).square().flatten(1).mean(1, keepdim=True)
        var = (self.sync_var_scale * gap + self.sync_var_min)[..., None]
        zs, goals, pasts = _repeat(z, N), _repeat(goal, N), _repeat(past, N)
        conds = {k: _repeat(v, N) for k, v in cond.items()}
        batch = torch.arange(B, device=z.device)[:, None]
        for _ in range(self.sync_steps):
            noise = torch.randn(B, N, H, A, device=z.device, dtype=torch.float32, generator=generator)
            samples = mean[:, None] + noise * var[:, None].sqrt()
            if self.bounds is not None:
                samples = samples.clamp(*self.bounds)
            rollouts = model.rollout(zs, torch.cat([pasts, samples.flatten(0, 1).to(pasts.dtype)], dim=1), **conds)
            cost = fp32_cost(model, rollouts, goals)
            elites = samples[batch, cost.view(B, N).topk(self.sync_elites, largest=False).indices]
            mean = elites.mean(1)
            var = elites.var(1).mean(-1, keepdim=True) + self.sync_var_min
        actions.copy_(mean.to(actions.dtype))

class MPPI ​

torch_world.planning.MPPI GitHub

python
MPPI(
    horizon: int,
    action_dim: int,
    num_samples: int = 512,
    num_elites: int = 64,
    num_pi_trajs: int = 24,
    iterations: int = 6,
    min_std: float = 0.05,
    max_std: float = 2.0,
    temperature: float = 0.5,
)

TD-MPC2's planner: model predictive path integral control over returns estimated in latent space.

Each iteration scores num_samples action sequences with model.estimate_value: num_pi_trajs sampled from the model's policy prior model.pi and the rest from a diagonal Gaussian, clamped to [-1, 1]. The Gaussian is refit to the num_elites best, weighted by softmax(temperature * value), with its std clamped to [min_std, max_std]. The returned plan is one elite drawn with those weights.

Given a goal latent, MPPI plans for any WorldModel instead: the value of a sequence is minus model.cost of its rollout from the context, and no trajectories come from a policy prior. temperature then scales costs, so it depends on their range.

Consecutive calls start from the previous mean shifted by one step; call reset between episodes. Values are ranked and weighted in fp32 even under torch.autocast, where bf16 would blur close candidates.

Source code in torch_world/planning/mppi.py
python
class MPPI:
    """TD-MPC2's planner: model predictive path integral control over returns estimated in latent space.

    Each iteration scores ``num_samples`` action sequences with ``model.estimate_value``: ``num_pi_trajs`` sampled
    from the model's policy prior ``model.pi`` and the rest from a diagonal Gaussian, clamped to ``[-1, 1]``. The
    Gaussian is refit to the ``num_elites`` best, weighted by ``softmax(temperature * value)``, with its std clamped to
    ``[min_std, max_std]``. The returned plan is one elite drawn with those weights.

    Given a ``goal`` latent, MPPI plans for any ``WorldModel`` instead: the value of a sequence is minus
    ``model.cost`` of its rollout from the context, and no trajectories come from a policy prior. ``temperature`` then
    scales costs, so it depends on their range.

    Consecutive calls start from the previous mean shifted by one step; call ``reset`` between episodes. Values are
    ranked and weighted in fp32 even under ``torch.autocast``, where bf16 would blur close candidates.
    """

    def __init__(
        self,
        horizon: int,
        action_dim: int,
        num_samples: int = 512,
        num_elites: int = 64,
        num_pi_trajs: int = 24,
        iterations: int = 6,
        min_std: float = 0.05,
        max_std: float = 2.0,
        temperature: float = 0.5,
    ):
        if not num_pi_trajs < num_samples or not 0 < num_elites <= num_samples:
            raise ValueError("MPPI needs num_pi_trajs < num_samples and 0 < num_elites <= num_samples")
        self.horizon, self.action_dim = horizon, action_dim
        self.num_samples, self.num_elites, self.num_pi_trajs = num_samples, num_elites, num_pi_trajs
        self.iterations, self.min_std, self.max_std, self.temperature = iterations, min_std, max_std, temperature
        self.mean: Tensor | None = None

    def reset(self):
        self.mean = None

    @torch.no_grad()
    def __call__(
        self,
        model,
        z: Tensor,
        goal: Tensor | None = None,
        generator: torch.Generator | None = None,
        explore: bool = False,
    ) -> Tensor:
        """Plan ``(B, horizon, action_dim)`` from the context latents ``z`` ``(B, T0, ...)``.

        Without ``goal``, the plan maximizes TD-MPC2's ``model.estimate_value`` from the last latent. With a goal
        ``(B, ...)``, it minimizes ``model.cost`` of the rollout. ``explore`` adds Gaussian noise with the final std
        to the plan, as the reference does while collecting data.
        """
        B, S, H, A = z.size(0), self.num_samples, self.horizon, self.action_dim
        P = self.num_pi_trajs if goal is None else 0
        if goal is None:
            z = z[:, -1].repeat_interleave(S, dim=0)
        else:
            z, goal = z.repeat_interleave(S, dim=0), goal.repeat_interleave(S, dim=0)
        actions = z.new_empty(B, S, H, A, dtype=torch.float32)
        if P:
            zp = z.view(B, S, -1)[:, :P].flatten(0, 1)
            for t in range(H):
                actions[:, :P, t] = model.pi(zp)[0].view(B, P, A)
                if t < H - 1:
                    zp = model.predict(zp, actions[:, :P, t].flatten(0, 1).to(z.dtype))

        mean = z.new_zeros(B, H, A, dtype=torch.float32)
        if self.mean is not None and self.mean.shape == mean.shape:
            mean[:, :-1] = self.mean[:, 1:]
        std = torch.full_like(mean, self.max_std)
        batch = torch.arange(B, device=z.device)[:, None]
        for _ in range(self.iterations):
            noise = torch.randn(B, S - P, H, A, device=z.device, generator=generator)
            actions[:, P:] = (mean[:, None] + std[:, None] * noise).clamp(-1, 1)
            if goal is None:
                value = model.estimate_value(z, actions.flatten(0, 1).to(z.dtype)).float()
            else:
                value = -fp32_cost(model, model.rollout(z, actions.flatten(0, 1).to(z.dtype)), goal)
            value = value.nan_to_num(0).view(B, S)
            elite_value, idx = value.topk(self.num_elites, dim=1)
            elites = actions[batch, idx]
            score = (self.temperature * (elite_value - elite_value.max(1, keepdim=True).values)).exp()
            score = (score / score.sum(1, keepdim=True))[..., None, None]
            mean = (score * elites).sum(1)
            std = (score * (elites - mean[:, None]).square()).sum(1).sqrt().clamp(self.min_std, self.max_std)
        self.mean = mean

        choice = torch.multinomial(score[..., 0, 0], 1, generator=generator)
        plan = elites[batch, choice][:, 0]
        if explore:
            plan = plan + std * torch.randn(plan.shape, device=z.device, generator=generator)
        return plan.clamp(-1, 1).to(z.dtype)

class HierarchicalPlanner ​

torch_world.planning.HierarchicalPlanner GitHub

python
HierarchicalPlanner(
    high, low, shrink_every: int | None = None, min_horizon: int = 1
)

Two-level top-down planning: the high level picks subgoals, the low level plans actions to reach the next one.

model is a two-level world model (HWM, HJEPA): itself the low-level WorldModel, model.high the high-level one over latent macro-actions, model.lift maps low-level latents to high-level latents, and model.stride counts low-level steps per high-level step. Each call:

  1. lifts the current latent and the goal latent to the high level, and high(model.high, ...) searches macro-actions whose rollout ends at the goal;
  2. the first predicted high-level latent becomes the subgoal; when the high horizon is 1 the goal itself is, as H-JEPA anchors the last subgoal to the goal;
  3. low(...) searches primitive actions, usually model.stride of them, whose last predicted latent, lifted, matches the subgoal under model.high.cost.

high and low are planners with the CEM signature (CEM, GradientPlanner); high plans standardized macro-actions, so bounds=(-2, 2) matches the papers' clipping to training statistics. With shrink_every, the high horizon shrinks by one every shrink_every calls down to min_horizon, as the papers shorten it while the episode's budget runs out; call reset between episodes. subgoals keeps the last high-level rollout (B, H, D).

Source code in torch_world/planning/hierarchical.py
python
class HierarchicalPlanner:
    """Two-level top-down planning: the high level picks subgoals, the low level plans actions to reach the next one.

    ``model`` is a two-level world model (``HWM``, ``HJEPA``): itself the low-level ``WorldModel``, ``model.high`` the
    high-level one over latent macro-actions, ``model.lift`` maps low-level latents to high-level latents, and
    ``model.stride`` counts low-level steps per high-level step. Each call:

    1. lifts the current latent and the goal latent to the high level, and ``high(model.high, ...)`` searches
       macro-actions whose rollout ends at the goal;
    2. the first predicted high-level latent becomes the subgoal; when the high horizon is 1 the goal itself is,
       as H-JEPA anchors the last subgoal to the goal;
    3. ``low(...)`` searches primitive actions, usually ``model.stride`` of them, whose last predicted latent, lifted,
       matches the subgoal under ``model.high.cost``.

    ``high`` and ``low`` are planners with the ``CEM`` signature (``CEM``, ``GradientPlanner``); ``high`` plans
    standardized macro-actions, so ``bounds=(-2, 2)`` matches the papers' clipping to training statistics. With
    ``shrink_every``, the high horizon shrinks by one every ``shrink_every`` calls down to ``min_horizon``, as the
    papers shorten it while the episode's budget runs out; call ``reset`` between episodes. ``subgoals`` keeps the
    last high-level rollout ``(B, H, D)``.
    """

    def __init__(self, high, low, shrink_every: int | None = None, min_horizon: int = 1):
        self.high, self.low, self.shrink_every, self.min_horizon = high, low, shrink_every, min_horizon
        self.calls, self.subgoals = 0, None

    def reset(self):
        self.calls = 0

    def horizon(self) -> int:
        if self.shrink_every is None:
            return self.high.horizon
        return max(self.min_horizon, self.high.horizon - self.calls // self.shrink_every)

    @torch.no_grad()
    def __call__(self, model, z: Tensor, goal: Tensor, generator: torch.Generator | None = None) -> Tensor:
        """Plan ``(B, low.horizon, A)`` from low-level latents ``z`` ``(B, T0, D)`` toward ``goal`` ``(B, D)``."""
        H = self.horizon()
        high = self.high if H == self.high.horizon else copy.copy(self.high)
        high.horizon = H
        zh, gh = model.lift(z[:, -1:]), model.lift(goal[:, None])[:, 0]
        macro = high(model.high, zh, gh, generator=generator)
        self.subgoals = model.high.rollout(zh, macro)[:, 1:]
        subgoal = gh if H == 1 else self.subgoals[:, 0]
        self.calls += 1
        return self.low(_TowardSubgoal(model), z, subgoal, generator=generator)

class GradientPlanner ​

torch_world.planning.GradientPlanner GitHub

python
GradientPlanner(
    horizon: int,
    action_dim: int,
    num_samples: int = 32,
    iterations: int = 30,
    lr: float = 0.1,
    std: float = 1.0,
    bounds: tuple[float, float] | None = None,
)

Gradient descent on action sequences through a differentiable world-model rollout, as H-JEPA plans.

num_samples candidates per batch element start from N(0, std^2), one of them at the mean, and are optimized with Adam on model.cost for iterations steps, clipped to bounds after each step. The cheapest candidate seen is returned, ranked by an fp32 cost even under torch.autocast. Only the actions receive gradients; put the model in eval mode first.

Source code in torch_world/planning/hierarchical.py
python
class GradientPlanner:
    """Gradient descent on action sequences through a differentiable world-model rollout, as H-JEPA plans.

    ``num_samples`` candidates per batch element start from ``N(0, std^2)``, one of them at the mean, and are optimized
    with Adam on ``model.cost`` for ``iterations`` steps, clipped to ``bounds`` after each step. The cheapest candidate
    seen is returned, ranked by an fp32 cost even under ``torch.autocast``. Only the actions receive gradients; put the
    model in eval mode first.
    """

    def __init__(
        self,
        horizon: int,
        action_dim: int,
        num_samples: int = 32,
        iterations: int = 30,
        lr: float = 0.1,
        std: float = 1.0,
        bounds: tuple[float, float] | None = None,
    ):
        self.horizon, self.action_dim = horizon, action_dim
        self.num_samples, self.iterations, self.lr, self.std, self.bounds = num_samples, iterations, lr, std, bounds

    def __call__(self, model, z: Tensor, goal: Tensor, generator: torch.Generator | None = None) -> Tensor:
        """Plan ``(B, horizon, action_dim)`` from context latents ``z`` ``(B, T0, ...)`` toward ``goal`` ``(B, ...)``."""
        B, S = z.size(0), self.num_samples
        shape = (B, S, self.horizon, self.action_dim)
        init = self.std * torch.randn(shape, device=z.device, dtype=z.dtype, generator=generator)
        init[:, 0] = 0
        if self.bounds is not None:
            init = init.clamp(*self.bounds)
        actions = init.flatten(0, 1).requires_grad_(True)
        z, goal = _repeat(z.detach(), S), _repeat(goal.detach(), S)
        optimizer = torch.optim.Adam([actions], lr=self.lr)
        best, best_cost = actions.detach().clone(), torch.full((B * S,), float("inf"), device=z.device)
        with torch.enable_grad():
            for step in range(self.iterations + 1):
                cost = fp32_cost(model, model.rollout(z, actions), goal)
                with torch.no_grad():
                    better = cost < best_cost
                    best[better], best_cost[better] = actions[better], cost[better]
                if step == self.iterations:
                    break
                optimizer.zero_grad()
                actions.grad = torch.autograd.grad(cost.sum(), actions)[0]
                optimizer.step()
                if self.bounds is not None:
                    with torch.no_grad():
                        actions.clamp_(*self.bounds)
        index = best_cost.view(B, S).argmin(1)
        return best.view(shape)[torch.arange(B, device=z.device), index]

class LeWAMPlanner ​

torch_world.planning.LeWAMPlanner GitHub

python
LeWAMPlanner(
    *,
    num_samples=1,
    refinement_steps=0,
    lr=0.05,
    proximity=0.1,
    noise_scale=1.0,
    flow_steps=None,
)

Sample action chunks, optionally refine and rank them toward a latent goal.

Works with any WorldActionModel (LeWAM, DreamZero); WAMPlanner is the same class. Extra keyword conditions, such as DreamZero's past_actions and states, are repeated per sample and forwarded to sample_actions and predict_future; goal is forwarded to both too.

num_samples=1, refinement_steps=0 evaluates the direct learned policy. More samples rank proposals using future latent goal distance. Optional gradient refinement penalizes movement away from each learned proposal. Only actions receive gradients; model parameters and context are untouched. This planner uses the model's action normalization and physical bounds. The caller executes the first action and replans from a new observation. flow_steps optionally overrides the model's integration budget. noise_scale=0 starts at the Gaussian centre for deterministic diagnostics; this is not the mean of the learned action distribution. Defaults preserve the model's ordinary Gaussian sampling and integration budget.

Source code in torch_world/planning/lewam.py
python
class LeWAMPlanner:
    """Sample action chunks, optionally refine and rank them toward a latent goal.

    Works with any ``WorldActionModel`` (LeWAM, DreamZero); ``WAMPlanner`` is the same class. Extra keyword
    conditions, such as DreamZero's ``past_actions`` and ``states``, are repeated per sample and forwarded to
    ``sample_actions`` and ``predict_future``; ``goal`` is forwarded to both too.

    ``num_samples=1, refinement_steps=0`` evaluates the direct learned policy.
    More samples rank proposals using future latent goal distance. Optional
    gradient refinement penalizes movement away from each learned proposal.
    Only actions receive gradients; model parameters and context are untouched.
    This planner uses the model's action normalization and physical bounds.
    The caller executes the first action and replans from a new observation.
    ``flow_steps`` optionally overrides the model's integration budget.
    ``noise_scale=0`` starts at the Gaussian centre for deterministic diagnostics;
    this is not the mean of the learned action distribution. Defaults preserve
    the model's ordinary Gaussian sampling and integration budget.
    """

    def __init__(self, *, num_samples=1, refinement_steps=0, lr=0.05, proximity=0.1, noise_scale=1.0, flow_steps=None):
        if num_samples < 1 or refinement_steps < 0 or lr <= 0 or proximity < 0:
            raise ValueError("Invalid LeWAM planning budget")
        if not math.isfinite(noise_scale) or noise_scale < 0:
            raise ValueError("noise_scale must be finite and nonnegative")
        if flow_steps is not None and (not isinstance(flow_steps, int) or flow_steps < 1):
            raise ValueError("flow_steps must be a positive integer")
        self.num_samples, self.refinement_steps = num_samples, refinement_steps
        self.lr, self.proximity = lr, proximity
        self.noise_scale, self.flow_steps = noise_scale, flow_steps

    def __call__(self, model, z, goal, past_actions=None, generator=None, *, history_pad=None, remaining=None, **cond):
        b, n = z.size(0), self.num_samples
        if past_actions is not None:
            cond["past_actions"] = past_actions
        cond = {k: v if v is None else v.detach().repeat_interleave(n, 0) for k, v in cond.items()}
        context = z.detach().repeat_interleave(n, 0)
        targets = goal.detach().repeat_interleave(n, 0)
        padding = None if history_pad is None else history_pad.repeat_interleave(n, 0)
        horizon = None if remaining is None else remaining.detach().repeat_interleave(n, 0)
        with torch.no_grad():
            noise = None
            if self.noise_scale != 1:
                shape = (b * n, model.chunk_size, model.action_dim)
                noise = (
                    z.new_zeros(shape)
                    if self.noise_scale == 0
                    else torch.randn(shape, device=z.device, dtype=z.dtype, generator=generator) * self.noise_scale
                )
            proposals = model.sample_actions(
                context,
                targets,
                generator=generator,
                noise=noise,
                steps=self.flow_steps,
                history_pad=padding,
                remaining=horizon,
                **cond,
            )
        if n == 1 and not self.refinement_steps:
            return proposals
        anchor = model.normalize_actions(proposals).detach()
        actions = anchor.clone()

        def score(normalized):
            future = model.predict_future(
                context, model.denormalize_actions(normalized), targets, history_pad=padding, **cond
            )
            return model.cost(future, targets) + self.proximity * (normalized - anchor).square().mean((1, 2))

        with torch.no_grad():
            best, best_cost = actions.clone(), score(actions)
        for _ in range(self.refinement_steps):
            with torch.enable_grad():
                actions = actions.detach().requires_grad_(True)
                gradient = torch.autograd.grad(score(actions).sum(), actions)[0]
            with torch.no_grad():
                actions = model.normalize_actions(model.denormalize_actions(actions - self.lr * gradient, clamp=True))
                cost = score(actions)
                better = cost < best_cost
                best[better], best_cost[better] = actions[better], cost[better]
        index = best_cost.reshape(b, n).argmin(1)
        chunks = model.denormalize_actions(best, clamp=True).reshape(b, n, model.chunk_size, model.action_dim)
        return chunks[torch.arange(b, device=z.device), index].detach()

class LeWAMHorizonPlanner ​

torch_world.planning.LeWAMHorizonPlanner GitHub

python
LeWAMHorizonPlanner(
    *,
    num_samples=32,
    horizon=10,
    refinement_steps=5,
    lr=0.05,
    proximity=0.01,
    grad_clip=10.0,
    action_clip=3.0,
)

Imagine policy rollouts, optimize normalized actions with Adam, select best.

steps_to_goal counts dynamics steps, not raw controls. The history must use the same spacing as model.frameskip. Execute one frameskip block, then replan with actual observations. Model weights and gradients are never updated. Returned actions are bounded physical controls; internal imagined proposals use the upstream normalized-action convention.

Source code in torch_world/planning/lewam_horizon.py
python
class LeWAMHorizonPlanner:
    """Imagine policy rollouts, optimize normalized actions with Adam, select best.

    ``steps_to_goal`` counts dynamics steps, not raw controls. The history must
    use the same spacing as ``model.frameskip``. Execute one frameskip block,
    then replan with actual observations. Model weights and gradients are never
    updated. Returned actions are bounded physical controls; internal imagined
    proposals use the upstream normalized-action convention.
    """

    def __init__(
        self,
        *,
        num_samples=32,
        horizon=10,
        refinement_steps=5,
        lr=0.05,
        proximity=0.01,
        grad_clip=10.0,
        action_clip=3.0,
    ):
        if (
            min(num_samples, horizon) < 1
            or refinement_steps < 0
            or lr <= 0
            or min(proximity, grad_clip, action_clip) < 0
        ):
            raise ValueError("Invalid horizon planning budget")
        self.num_samples, self.horizon = num_samples, horizon
        self.refinement_steps, self.lr, self.proximity = refinement_steps, lr, proximity
        self.grad_clip, self.action_clip = grad_clip, action_clip
        self.last_diagnostics = {}

    @staticmethod
    def _next(model, history, pad, normalized):
        clean = F.pad(normalized, (0, 0, 0, model.chunk_size - model.frameskip))
        future = model.predict_future(history, model.denormalize_actions(clean), history_pad=pad)[:, :1]
        return torch.cat((history[:, 1:], future), 1), torch.cat((pad[:, 1:], torch.zeros_like(pad[:, :1])), 1)

    def __call__(self, model, z, goal, *, steps_to_goal, history_pad=None, generator=None):
        if model.training or getattr(model, "goal_type", None) != "sampled":
            raise ValueError("Horizon planning requires an eval-mode sampled-goal checkpoint")
        if model.num_states != 1 or model.state_dim:
            raise ValueError("Horizon planner supports one visual MSE state per dynamics step")
        b, n = len(z), self.num_samples
        left = torch.as_tensor(steps_to_goal, device=z.device, dtype=z.dtype)
        if left.shape != (b,) or not torch.isfinite(left).all() or (left <= 0).any():
            raise ValueError("steps_to_goal must be finite positive (B,) dynamics-step counts")
        index = left.round().clamp(1, self.horizon).long() - 1
        length = int(index.max()) + 1
        history = z.detach().repeat_interleave(n, 0)
        target = goal.detach().repeat_interleave(n, 0)
        pad = torch.zeros(z.shape[:2], dtype=torch.bool, device=z.device) if history_pad is None else history_pad
        pad = pad.repeat_interleave(n, 0)
        index, left = index.repeat_interleave(n), left.repeat_interleave(n)
        rows = torch.arange(b * n, device=z.device)

        def rollout(plan):
            h, p, states = history, pad, []
            for step in range(length):
                h, p = self._next(model, h, p, plan[:, step])
                states.append(h[:, -1])
            at_goal = torch.stack(states, 1)[rows, index]
            return (at_goal - target).square().mean(-1)

        with torch.no_grad():
            h, p, proposals = history, pad, []
            for step in range(length):
                actions = model.sample_actions(
                    h,
                    target,
                    remaining=(left - step).clamp(1, self.horizon) / self.horizon,
                    history_pad=p,
                    generator=generator,
                    clamp=False,
                )
                block = model.normalize_actions(actions[:, : model.frameskip])
                proposals.append(block)
                h, p = self._next(model, h, p, block)
            anchor = torch.stack(proposals, 1)
            best, best_cost = anchor.clone(), rollout(anchor)
            warm_cost = best_cost.view(b, n).min(1).values
        with torch.enable_grad():
            plan = anchor.clone().requires_grad_(True)
            optimizer = torch.optim.Adam([plan], lr=self.lr)
            for step in range(self.refinement_steps + 1):
                cost = rollout(plan)
                with torch.no_grad():
                    better = cost < best_cost
                    best[better], best_cost[better] = plan[better], cost[better]
                if step == self.refinement_steps:
                    break
                loss = cost.sum() + self.proximity * (plan - anchor).square().sum()
                optimizer.zero_grad(set_to_none=True)
                plan.grad = torch.autograd.grad(loss, plan)[0]
                if self.grad_clip:
                    torch.nn.utils.clip_grad_norm_([plan], self.grad_clip)
                optimizer.step()
                if self.action_clip:
                    with torch.no_grad():
                        plan.clamp_(-self.action_clip, self.action_clip)
        choices = best_cost.view(b, n).argmin(1)
        selected = best.view(b, n, length * model.frameskip, model.action_dim)[
            torch.arange(b, device=z.device), choices
        ]
        self.last_diagnostics = {
            "warm_cost": warm_cost.detach(),
            "best_cost": best_cost.view(b, n).min(1).values.detach(),
        }
        return model.denormalize_actions(selected, clamp=True).detach()

class DreamZeroPolicy ​

torch_world.planning.DreamZeroPolicy GitHub

python
DreamZeroPolicy(
    model,
    goal: Tensor | None = None,
    plan: Callable | None = None,
    generator: torch.Generator | None = None,
)

Run a DreamZero chunk by chunk, writing real observations back into its context.

Every chunk_actions // raw_frames_per_chunk environment steps the image observation (B, 3, H, W) is recorded. When the action queue is empty, the recorded frames of the last num_chunks - 1 chunks plus the frame before them are encoded with the model's autoencoder, and the next chunk is sampled from those latents and the actions executed over them. The model's predicted video is discarded, as DreamZero replaces predicted frames in its KV cache with the real ones: the model rebuilds its context key-value cache from the real latents for every chunk.

plan(model, z, goal, past_actions, generator) chooses the chunk; by default it is the learned policy, model.sample_actions. A WAMPlanner can rank and refine proposals toward goal instead. Each call returns one environment action (B, A). Call reset between episodes.

Source code in torch_world/planning/dreamzero.py
python
class DreamZeroPolicy:
    """Run a ``DreamZero`` chunk by chunk, writing real observations back into its context.

    Every ``chunk_actions // raw_frames_per_chunk`` environment steps the image observation ``(B, 3, H, W)`` is
    recorded. When the action queue is empty, the recorded frames of the last ``num_chunks - 1`` chunks plus the frame
    before them are encoded with the model's autoencoder, and the next chunk is sampled from those latents and the
    actions executed over them. The model's predicted video is discarded, as DreamZero replaces predicted frames in its
    KV cache with the real ones: the model rebuilds its context key-value cache from the real latents for every chunk.

    ``plan(model, z, goal, past_actions, generator)`` chooses the chunk; by default it is the learned policy,
    ``model.sample_actions``. A ``WAMPlanner`` can rank and refine proposals toward ``goal`` instead. Each call returns
    one environment action ``(B, A)``. Call ``reset`` between episodes.
    """

    def __init__(
        self,
        model,
        goal: Tensor | None = None,
        plan: Callable | None = None,
        generator: torch.Generator | None = None,
    ):
        if model.state_dim:
            raise ValueError("DreamZeroPolicy runs image-only models; build states into a custom loop")
        if model.chunk_size % model.raw_frames_per_chunk:
            raise ValueError("chunk_actions must be a multiple of the raw frames each chunk covers")
        self.model, self.goal, self.plan, self.generator = model, goal, plan, generator
        self.stride = model.chunk_size // model.raw_frames_per_chunk
        self.reset()

    def reset(self):
        self.frames: list[Tensor] = []
        self.actions: list[Tensor] = []
        self.queue: list[Tensor] = []
        self.steps = 0

    @torch.no_grad()
    def __call__(self, observation: Tensor) -> Tensor:
        model = self.model
        if self.steps % self.stride == 0:
            self.frames.append(observation)
        if not self.queue:
            context = model.num_chunks - 1
            frames = self.frames[-(1 + context * model.raw_frames_per_chunk) :]
            chunks = (len(frames) - 1) // model.raw_frames_per_chunk
            z = model.encode(torch.stack(frames, dim=1))
            past = self.actions[len(self.actions) - chunks * model.chunk_size :] if chunks else []
            past = torch.stack(past, dim=1) if past else z.new_zeros(z.size(0), 0, model.action_dim)
            if self.plan is None:
                chunk = model.sample_actions(z, self.goal, past_actions=past, generator=self.generator)
            else:
                chunk = self.plan(model, z, self.goal, past, self.generator)
            self.queue = list(chunk.unbind(1))
        action = self.queue.pop(0)
        self.actions.append(action)
        self.steps += 1
        return action