Learned Models and Planning

Dive into Deep Learning · §15.6

Model-Based Deep RL: Learned World Models and Planning
dynamics regression · compounding rollout error · random shooting MPC · warm starts · policy distillation · Dyna & MBPO

Why Each Transition Teaches More Than a Scalar Value

Motivation

  • Richer Supervisory Signal: Model-free SAC extracts only a 1D scalar critic target y_t \in \mathbb{R} from each step, whereas a world model regresses onto the full 4D physics vector (s_{t+1} - s_t, r_t) \in \mathbb{R}^4.
  • From Thousands of Steps to Hundreds: Planning in a learned dynamics model \hat{f}_\phi swings up Pendulum after just 1 to 3 episodes (200–600 real steps).

Fitting a Neural Dynamics Model by Least Squares

World Model Regression

\min_{\phi} \sum_{i=1}^{N} \big\|\hat{f}_\phi(s_i, a_i) - (s'_i, r_i)\big\|^2

  • 1. Predict State Deltas (s' - s): Over \Delta t = 0.05\text{ s}, s' \approx s; predicting the residual \Delta s = s' - s with a skip connection \hat{s}' = s + \Delta\hat{s} focuses capacity on the change.
  • 2. Coordinate Standardization: Z-scoring every input and target dimension prevents the high-variance reward r \in [-16.2, 0] from dominating the L_2 loss.

DynamicsModel Architecture and Standardization

Model Implementation

DynamicsModel uses a 2-layer MLP with 64 smooth SiLU units and stores the dataset’s standardization statistics (\mu_x, \sigma_x, \mu_y, \sigma_y) directly inside the module:

class DynamicsModel(nn.Module):
    """(s', r) from (s, a): an MLP that maps standardized inputs to the
    standardized change of state and reward."""
    def __init__(self, obs_dim=3, act_dim=1, hidden=64):
        super().__init__()
        d_in, d_out = obs_dim + act_dim, obs_dim + 1
        self.net = nn.Sequential(nn.Linear(d_in, hidden), nn.SiLU(),
                                 nn.Linear(hidden, hidden), nn.SiLU(),
                                 nn.Linear(hidden, d_out))
        self.register_buffer('mu_x', torch.zeros(d_in))   # standardization
        self.register_buffer('sd_x', torch.ones(d_in))
        self.register_buffer('mu_y', torch.zeros(d_out))
        self.register_buffer('sd_y', torch.ones(d_out))

DynamicsModel Architecture and Standardization (cont.)

Model Implementation

forward maps the network output back to data units, and make_model pairs the model with its Adam optimizer:

    def forward(self, obs, act):
        x = (torch.cat([obs, act], -1) - self.mu_x) / self.sd_x
        y = self.net(x) * self.sd_y + self.mu_y   # (s' - s, r) in data units
        return obs + y[..., :-1], y[..., -1]

def make_model(seed, lr=1e-3):
    torch.manual_seed(seed)
    model = DynamicsModel()
    return model, torch.optim.Adam(model.parameters(), lr=lr)

DynamicsModel Architecture and Standardization (fitting)

Model Implementation

fit_model copies the data statistics into the module, then regresses the network on standardized inputs and targets:

def fit_model(model, opt, buffer, rng, num_steps=fit_steps, batch_size=256):
    """Least squares on all stored transitions, in standardized units."""
    x, y, stats = model_data(buffer)
    model.mu_x, model.sd_x, model.mu_y, model.sd_y = map(torch.as_tensor,
                                                         stats)
    mu_x, sd_x, mu_y, sd_y = stats
    x = torch.as_tensor((x - mu_x) / sd_x)
    y = torch.as_tensor((y - mu_y) / sd_y)
    for _ in range(num_steps):
        i = torch.as_tensor(rng.integers(len(x), size=batch_size))
        loss = ((model.net(x[i]) - y[i]) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
    return float(loss.detach())

One-Step Accuracy on a Single Random Episode

Single-Step Verification

Fitting DynamicsModel for 1{,}000 Adam steps on just one random episode (200 transitions) and inspecting transition i = 100 in physical units:

return of the random episode: -1072
final minibatch loss (standardized units): 0.0018
s        [-0.9407 -0.3394  5.6896] a = -0.0800
true s'  [-0.8154 -0.5789  5.4231] r = -11.0511
model s' [-0.8109 -0.584   5.436 ] r = -11.2768
angle error 0.386 degrees

At step 100 (\vartheta = -160.2^\circ, \dot\vartheta = 5.69\text{ rad/s}), the pendulum rotates by 15.6^\circ in 0.05\text{ s}; the learned model predicts the next angle to within 0.4^\circ (0.30^\circ–0.39^\circ) and the reward (-11.05) to within 0.25.

Autoregressive Rollouts and Compounding Model Error

The Horizon Bottleneck

To evaluate a candidate sequence of n = 25 torques, the model must roll out autoregressively (open-loop), feeding each predicted state \hat{s}_{t+1} back in as the input for step t+1:

@torch.inference_mode()
def rollout_model(model, obs, actions):
    """Open-loop rollout in the model: obs (..., 3) and actions (..., n, 1)
    give the predicted states (..., n, 3) and rewards (..., n), numpy in
    and out."""
    s, actions = torch.as_tensor(obs), torch.as_tensor(actions)
    states, rewards = [], []
    for t in range(actions.shape[-2]):
        s, r = model(s, actions[..., t, :])
        states.append(s)
        rewards.append(r)
    return torch.stack(states, -2).numpy(), torch.stack(rewards, -1).numpy()

Autoregressive Rollouts and Compounding Model Error (cont.)

The Horizon Bottleneck

seed   k=1    k=5   k=10   k=25   (degrees, held-out random episode)
   0   0.44   1.91   2.52   1.51
   1   1.83   7.08   8.67  12.29
   2   0.53   2.37   3.65   5.51
   3   0.38   1.89   4.77  11.82
   4   0.04   0.12   0.13   0.33
  • Why Errors Compound: The model was trained only on true states, never on its own slightly perturbed predictions; a small angle error alters the predicted gravitational torque, which perturbs velocity and snowballs over k = 10 \to 25 steps.

Random Shooting: Ranking Candidates in Imagination

Planning by Search

At state s, random shooting draws J candidate action sequences A^{(j)} = (a_0^{(j)}, \dots, a_{n-1}^{(j)}), rolls all J sequences out in parallel through \hat{f}_\phi, and scores each by its predicted n-step return \hat{G}^{(j)} = \sum_{t=0}^{n-1} \hat{r}_t^{(j)}:

first actions [ 0.55 -0.92 -1.84]  predicted  -174.2  true  -237.6
first actions [-0.47  1.99  1.92]  predicted  -173.8  true  -232.7
first actions [ 1.15 -1.04  1.51]  predicted  -174.3  true  -229.4
first actions [-0.3   0.48  1.98]  predicted  -170.7  true  -223.2
first actions [-0.08 -1.07  1.21]  predicted  -174.5  true  -242.4

Ranking vs. Calibration: From the resting bottom state (\vartheta = \pi, where hanging still for 25 steps loses -247), the model overestimates every sequence by 40–70 points because the random training episode swept past the bottom rapidly—yet the model still ranks the best real sequence first.

Receding-Horizon MPC with Shifted Warm Starts

Model-Predictive Control

  • Receding-Horizon Execution (MPC, §14.6): Just as in §14.6’s analytical MPC, execute only the first torque a_0^\star of the winning 25-step plan, observe the real next state s_{t+1}, and re-plan from scratch—preventing open-loop model errors from accumulating along the real trajectory.
  • Warm-Started Search: Instead of drawing 500 fresh random sequences at step t+1, shift step t’s winning plan forward by 1 step, append 0, and perturb it with Gaussian noise (\sigma = c = 2, keeping the unperturbed shifted plan as candidate 0).

Implementing Warm-Started Receding-Horizon MPC

MPC Controller

mpc maintains the previous step’s winning plan in a closure, shifts it forward by one step (plans[:, 1:] followed by a zero torque), and executes only the first torque plans[:, 0] of the newly refined plan:

def mpc(model, rng, horizon=horizon, noise=c):
    """Model-predictive control: at every step plan in the model, starting
    from the previous plan shifted by one step, and execute its first
    action."""
    plans = None
    def controller(obs):
        nonlocal plans
        if plans is None:
            plans = np.zeros((len(obs), horizon, 1), np.float32)
        shifted = np.concatenate([plans[:, 1:], np.zeros_like(plans[:, :1])],
                                 1)
        plans = plan(model, obs, shifted, rng, noise)[0]
        return plans[:, 0]
    return controller

Across 5 seeds at 600 real steps, warm-starting improves 10-start test returns from [-555, -165] (fresh random shooting at every step) to [-155, -115].

Swinging Up Pendulum in 200 to 600 Environment Steps

Few-Episode Swing-Up

Starting from 1 random episode (200 steps), mpc_run alternates refitting the model on all collected transitions, scoring the MPC planner on 10 fixed test starts, and collecting 1 new episode with MPC:

seed  episode returns: random, MPC x 3 |  test score at 200/400/600/800 steps
   0   -1072   -242   -118   -125  |    -181   -168   -168   -171
   1    -876   -264   -121   -123  |    -266   -201   -204   -180
   2    -966   -122   -125   -116  |    -337   -190   -168   -169
   3   -1501  -1287   -246     -2  |   -1464   -265   -191   -195
   4   -1703  -1576  -1323   -120  |   -1567  -1437   -171   -187
  • 10-Start Benchmark (\approx -170 ceiling): By 600 real steps (3 episodes), every seed scores between -165 and -215—and 3 of the 5 seeds already swing up after the single random episode (200 steps).

Out-of-Support Extrapolation and Self-Correction

Coverage Analysis

Why did seeds 3 and 4 score \sim -1{,}500 after the first random episode (200 steps) but succeed by 600 steps? Evaluating the 200-step model along the planner’s later swing-up trajectories exposes the cause:

seed   k=1    k=5   k=10   k=25   (degrees, the planner's episodes)
   0    0.3    1.4    3.3   42.4
   1    0.4    1.5    2.6   40.2
   2    0.2    0.9    1.7   28.3
   3    6.8   41.3   61.5  138.8
   4   14.8   71.9   89.8  128.3

Implicit Exploration via Model Optimism: On seeds 3 and 4, the initial random episode never lifted the pendulum above horizontal, so the 200-step model had 40^\circ–72^\circ errors within 5 steps in the upper half-plane. Yet even a failed MPC swing-up pushes the pendulum into those unvisited upper angles, recording the true physics there so the next refit succeeds.

Experience vs. Computation: MPC Planner vs. SAC

Systems Trade-off

  • Warm-Started MPC Planner: Solves Pendulum in 200–800 real steps, but evaluates 500 \times 25 = 12{,}500 model calls (\sim\text{ms}) at every test-time control step.
  • Model-Free SAC (UTD = 1 to 10): Needs 1{,}600–7{,}500 real steps, but executes a single actor forward pass (\sim\mu\text{s}) at test time by amortizing planning into policy weights \theta.

Search as a Policy Improvement Operator

Actor-Seeded Search

  • Monotonic improvement inside \hat{f}_\phi: Seeding Candidate 0 of plan with the actor’s own unperturbed rollout guarantees that the winning candidate achieves predicted return at least as high as the actor’s plan.
def actor_plan(model, actor, obs, horizon=horizon):
    """The actor's own deterministic plan for each state, imagined in the
    model: (B, n, 1)."""
    acts = []
    for _ in range(horizon):
        acts.append(actor.act_greedy(obs))
        obs = rollout_model(model, obs, acts[-1][:, None])[0][:, 0]
    return np.stack(acts, 1)

def improve(model, actor, obs, rng, noise=c):
    """Search seeded by the actor: the best first action for each state."""
    return plan(model, obs, actor_plan(model, actor, obs), rng, noise)[0][:, 0]

Distilling Search Labels into an Actor Network

Policy Distillation

  • Amortizing search into \pi_\theta: Regress the actor’s deterministic mean c\tanh\mu_\theta(s) onto the 500-candidate search actions improve(model, actor, obs) via L_2 loss (distill).

Distilling Search Labels into an Actor Network (Code)

Policy Distillation

def make_actor(seed, lr=1e-3):
    actor = d2l.SquashedGaussianPolicy(3, 1, scale=c, seed=seed)
    return actor, torch.optim.Adam(actor.parameters(), lr=lr)

def distill(actor, opt, obs, labels, rng, num_steps=1_000, batch_size=256):
    """Regress the actor's mean action, scale * tanh(mean), onto labels."""
    obs, labels = torch.as_tensor(obs), torch.as_tensor(labels)
    for _ in range(num_steps):
        i = torch.as_tensor(rng.integers(len(obs), size=batch_size))
        a = actor.scale * torch.tanh(actor.policy(obs[i])[0])
        loss = ((a - labels[i]) ** 2).mean()
        opt.zero_grad()
        loss.backward()
        opt.step()
    return float(loss.detach())

Iterated Search and Distillation (AlphaZero Loop)

Search & Distillation

  • Each round of search_and_distill refits \hat{f}_\phi, labels 200 buffer states with actor-seeded search improve, regresses \bar{a}_\theta(s) onto those labels (distill), and collects 1 episode acting with search.
  • Acting with search (blue): reliably swings up within 2–3 rounds (400–600 steps).
  • Actor alone (orange): improves from -1{,}400 toward -200, but lags behind live search due to covariate shift (imitation without DAgger aggregation) and noisy 500-sample shooting labels.

final score on the ten starts, acting with search: -191 -202 -222

Dyna and MBPO: Imagined Transitions vs. High UTD

Model-Generated Data

  • Short branched rollouts (Janner et al., 2019): Branch k = 3-step rollouts from real buffer states inside \hat{f}_\phi so synthetic data stay anchored near the true state distribution without long-horizon drift.
  • Matched-UTD ablation (Chen et al., 2021): At a matched UTD = 10, 100\% real replay transitions match 95\% imagined rollouts (1{,}500–2{,}500 real steps to -200) without risking model bias.

Concept Check: Horizons, Deltas, and Ensembles

Check Your Understanding

Reason through these three model-based design questions:

  1. Planning Horizon Trade-off: On Pendulum (\Delta t = 0.05\text{ s}), what goes wrong if you shorten the random-shooting horizon from n = 25 to n = 5, and what goes wrong if you lengthen it to n = 100?
  2. Why Predict State Deltas? Why do we train the MLP to predict standardized residuals (s' - s)/\sigma_{\Delta s} rather than predicting s' directly in raw coordinates?
  3. Model Ensembles: If you train an ensemble of M = 5 dynamics networks \hat{f}_{\phi_1}, \dots, \hat{f}_{\phi_5} from different random initializations on seed 4’s single random episode, where will their predictions disagree most?

Answers:

  1. At n = 5 (0.25\text{ s}), the planner is too myopic to see that pumping energy at the bottom pays off 20 steps later near upright; at n = 100 (5.0\text{ s}), compounding open-loop errors render the late predicted rewards pure noise.
  2. When \Delta t = 0.05\text{ s}, s' \approx s, so direct prediction spends most of its capacity learning the identity map s' = s, and unstandardized MSE is dominated by the reward r \in [-16, 0] (\text{var} \sim 20) over \Delta\cos\vartheta (\text{var} \sim 0.01).
  3. The 5 networks agree closely in the lower half-circle (where training data lie) and disagree strongly in the unvisited upper half-circle—making ensemble variance an effective epistemic uncertainty signal (PETS; Chua et al., 2018).

Summary: Model-Based Deep Reinforcement Learning

Key Takeaways

Method / Component Mathematical Mechanism Primary Advantage Primary Limitation
State-Delta MLP (\hat{f}_\phi) \hat{s}' = s + \sigma_{\Delta s} f_\phi((s,a-\mu_x)/\sigma_x) + \mu_{\Delta s} Learns global physics from 200 steps Compounding error over k-step rollouts
Random Shooting MPC \operatorname{argmax}_{A^{(j)}} \sum_{t=0}^{n-1} \hat{r}_t^{(j)}, execute a_0^\star only Replanning prevents error accumulation High test-time compute (J \times n model calls)
Shifted Warm Start Center candidates on A^\star_{1:n} from step t-1 Carries good multi-step plans across time Can get stuck in local trajectory modes
Search Distillation Regress actor \bar{a}_\theta(s) onto actor-seeded improve(s) Fast O(1) policy inference at test time Covariate shift unless labels are aggregated (DAgger)
Dyna / MBPO Rollouts Train critic on short k-step model rollouts Multiplies data for critic updates Matched UTD on real replay often performs equally well