A tiny world model

Learn, imagine, plan — an ensemble of five small networks and a sampling-based stochastic MPC that learn a pendulum swing-up and steer a unicycle around an obstacle in a handful of episodes.

What you'll learn
  • Build the model-based loop — collect, learn, plan, act — and say what each part is for
  • Separate the two kinds of uncertainty a probabilistic ensemble represents
  • Plan with particles, an expected cost and a scenario chance constraint
  • Measure compounding error and check whether a model's uncertainty can be trusted

A model-free agent learns what to do directly from reward, and usually needs millions of trials to do it. A model-based agent first learns how the world responds — a function that predicts the next state from the current state and an action — and then works out what to do by planning with that function. The planning happens in imagination, so it costs computation instead of real robot time.

This lesson builds the whole idea in about 400 lines of PyTorch, following PETS (Chua et al., 2018): a probabilistic ensemble as the world model and a sampling-based model predictive controller as the planner. Two loops nest inside each other:

Four boxes in a loop. Learn the world model (5 Gaussian MLPs trained with NLL on bootstrap resamples) passes the model to Plan in imagination (CEM with 200 plans times 10 particles times 20 steps). Plan sends action a_t to Act on the real robot, which executes the first action only; a dashed arrow returns the new state to Plan, re-planning every 0.1 s. Plan and Act are grouped as one episode of 70 MPC steps. After the episode, 70 new transitions go to the Dataset of transitions, which is used to refit the model once per episode. Four boxes in a loop. Learn the world model (5 Gaussian MLPs trained with NLL on bootstrap resamples) passes the model to Plan in imagination (CEM with 200 plans times 10 particles times 20 steps). Plan sends action a_t to Act on the real robot, which executes the first action only; a dashed arrow returns the new state to Plan, re-planning every 0.1 s. Plan and Act are grouped as one episode of 70 MPC steps. After the episode, 70 new transitions go to the Dataset of transitions, which is used to refit the model once per episode.
The inner loop is ordinary receding-horizon MPC, run every 0.1 s with the current model. The outer loop is Dyna (Sutton, 1991): after each real episode, the new transitions are added to the dataset and the model is refitted.

Two robots

Each robot has a true simulator that the learner never sees. The learner only receives transitions \((s_t, a_t, s_{t+1})\), and it knows the cost it is supposed to minimise.

Robot Observation, action Task What the textbook model misses
Pendulum \([\cos\theta, \sin\theta, \dot\theta]\), torque in \([-2, 2]\) swing up from hanging and balance everything: no prior, the model is learned from scratch
Unicycle \([x, y, \cos\theta, \sin\theta]\), speed \(v\) and turn rate \(\omega\) reach \((2.5, 2.5)\) without touching an obstacle in the way a sand patch that cuts speed to 45 % and adds sideways slip, and a steering bias of 0.35 rad/s, like a miscalibrated wheel

The pendulum is too weak to lift itself directly — gravity can accelerate it by up to 14.7 rad/s², the motor by only 6 — so it has to pump energy by swinging. The unicycle’s textbook model is the standard kinematic one:

\[x_{t+1} = x_t + v\cos\theta_t\,\Delta t, \qquad y_{t+1} = y_t + v\sin\theta_t\,\Delta t, \qquad \theta_{t+1} = \theta_t + \omega\,\Delta t .\]

It is right almost everywhere — and wrong in exactly the two ways that matter next to an obstacle.

The world model: an ensemble of Gaussians

The model does not predict the next state directly but the change in state, and not as a single number but as a Gaussian:

\[s_{t+1} = s_t + \Delta, \qquad \Delta \sim \mathcal{N}\big(\mu_e(s_t, a_t),\ \sigma_e^2(s_t, a_t)\big), \qquad e = 1, \dots, 5 .\]

Each of the five members \(e\) is an MLP with three hidden layers of 128 units and SiLU activations that outputs a mean and a log-variance per state dimension. All five run as one batched matrix multiply, so the ensemble costs little more than one network.

Training minimises the Gaussian negative log-likelihood — the squared error divided by the predicted variance, plus the log of that variance:

\[\mathcal{L} = \frac{1}{N}\sum_{n}\left[\frac{(\mu_e(s_n, a_n) - \Delta_n)^2}{\sigma_e^2(s_n, a_n)} + \log \sigma_e^2(s_n, a_n)\right].\]

The first term rewards accuracy where the model claims to be sure; the second stops it from claiming to be unsure everywhere. In the code it is one line:

mu, logvar = self._forward(O[idx], A[idx])
nll = ((mu - Tn[idx]) ** 2 * torch.exp(-logvar) + logvar).mean()

idx is the point: every member draws its minibatches from its own bootstrap resample of the data (rows sampled with replacement), so the members see slightly different data and start from different random weights. The log-variance is also soft-clamped between two learned bounds, so the predicted noise can neither collapse to zero nor blow up.

The result holds two different kinds of uncertainty:

  • Aleatoric — each member’s own \(\sigma_e\): noise the world itself adds. More data does not remove it.
  • Epistemic — how much the five members disagree: what the model has not seen yet. More data, in the right places, does remove it.
Five models fitted to the same data, each on its own bootstrap resample. Inside the explored region (grey) they agree; outside it they diverge, and the band of disagreement is the model's estimate of what it does not know. Each episode explores a little further. Raise the noise: the band inside the data barely changes, but the estimated noise does. (For speed, the members here are random-feature regressions, not neural networks.)

Hybrid: textbook model plus a learned residual

For the unicycle there is a third option. Rather than learning all of the dynamics, keep the textbook model and learn only what it gets wrong:

\[s_{t+1} = s_t + f_{\text{textbook}}(s_t, a_t) + \Delta_{\text{residual}} .\]

Only the training target changes:

def _target(self, O, A, O2):
    d = O2 - O
    return d - self.prior(O, A) if self.prior is not None else d

The networks now model a small correction — the sand and the bias — and the textbook model supplies everything else, including far from the data, where a pure network would only guess.

Planning in imagination

The planner is a model predictive controller. It cannot use a QP solver, because the model is a neural network, so it uses the cross-entropy method (CEM): sample 200 action sequences of 20 steps from a Gaussian, score them all with the model, keep the best 20, refit the Gaussian to them, and repeat four times. Then it executes only the first action and starts again at the next step, warm-started from the remainder of the old plan.

Scoring a sequence is where the uncertainty comes in. Each sequence is rolled out by 10 particles, and particle \(k\) is pinned to ensemble member \(k \bmod 5\) for the whole horizon (PETS calls this TS-∞). The members disagree, so the particles fan out: they are 10 scenarios of what might happen. From them the planner forms:

  • the expected cost: the average of the particles’ costs;
  • the probability of collision: the fraction of particles that touch the obstacle at any point in the horizon.

That fraction gives a scenario chance constraint, \(\Pr(\text{collision}) \le \delta\), enforced as a large penalty:

cost, p_viol = self.evaluate(obs, seqs)        # averages over the particles
cost = cost + 1e3 * (p_viol > self.delta) + 10.0 * p_viol
elite = seqs[np.argsort(cost)[: self.ne]]

Each CEM iteration rolls out 200 sequences × 10 particles × 20 steps, so one control step imagines about 160,000 transitions.

The planner running live. Orange: the 10 imagined futures of the plan it has just chosen; blue: what the real robot did. With the textbook model, every particle agrees, the plan grazes the obstacle, and the steering bias pushes the real robot into it. With a learned residual, the particles spread, the chance constraint keeps them clear, and the robot passes. Try δ = 1, which switches off the hard constraint. (In the browser the ensemble members are stand-ins, not trained networks: each is the true robot with perturbed sand and bias parameters, perturbed more with little data.)

Results

Each unicycle run starts with 3 episodes of smooth random actions and then runs 8 planned episodes of 7 s, refitting the model before each one (seed 0):

Planner’s model Episodes reaching the goal Episodes with a collision 1-step error 30-step error
textbook model, no learning 8/8 5/8 0.035 1.23
pure learned ensemble 7/8 2/8 (the 1st and 3rd) 0.0036 0.045
hybrid: textbook + learned residual 7/8 0/8 0.0039 0.035

The textbook planner plans a path around the obstacle every time and then drives through it, because it does not know about the bias. All five of its “members” are the same model, so its particles never spread: it sees a collision probability of exactly 0 or 1, and nothing in between to be careful about. The pure ensemble collides twice while its data is still thin, then stops. The hybrid never collides. It misses the goal only in the first planned episode, after three random ones.

Three panels for the textbook-model planner: an episode cost that falls and rises again; the last episode's path, which takes the low route past the sand patch and runs through the red obstacle disc while the single imagined trajectory runs straight; and a 30-step prediction error rising to about 1.2, far above the dotted noise floor.
Textbook model only. Middle: the last episode takes the low route past the sand and drives through the obstacle.
Three panels for the hybrid planner: an episode cost between 156 and 167; the last episode's path curving up and around the far side of the obstacle from the sand, with a narrow bundle of imagined particles at the start; and, on a log scale, the real prediction error and the total predicted spread rising together to about 0.03, with the member disagreement alone well below and a dotted true-noise floor.
Textbook model plus learned residual. Middle: the last episode goes around the side of the obstacle away from the sand. Right: the total predicted spread (green) tracks the real error (blue); the members' disagreement alone (orange) is far below it.

The pendulum has no textbook model at all. After three random episodes and three planned ones — 600 transitions, 30 s of experience — the fourth planned episode’s cost drops to its final level of about 365, and from the fifth on the pendulum finishes every episode upright.

Three panels for the pendulum: episode cost dropping from about 620 to 365 by iteration 3; the last episode's angle from upright, which pumps through two swings and settles at zero after about 4 s; and, on a log scale, the total predicted spread lying well above the real prediction error at every horizon.
Pendulum swing-up learned from scratch. Middle: two pumping swings, then balance at the top from about 4 s. Right: the predicted spread (green) is several times the real error.

Errors compound

A model that is wrong by a little at every step is wrong by a lot after many. Run each model open loop for \(H\) steps on fresh trajectories and compare with what really happened:

Open-loop prediction error against horizon on the unicycle. The textbook model's error grows almost linearly; the learned models' errors are 30× smaller at 30 steps.

Almost all of the textbook model’s error is heading. The bias turns the robot 0.035 rad per step without the model knowing, so after 30 steps the predicted heading is off by 1.05 rad (60°). On the unit circle that is a chord of 1.0 in \((\cos\theta, \sin\theta)\) alone, and the position error is added on top.

The learned models’ 1-step errors, 0.0036 and 0.0039, are as small as they can get. The real robot’s position noise is 0.003 per axis, which gives an expected error of \(0.003\sqrt{\pi/2} \approx 0.0038\) for a perfect model. Over the 20-step planning horizon, both learned models stay within 0.025.

Can you trust the uncertainty?

A chance constraint is only as good as the probabilities it is given. If the particles spread less than reality, \(\delta = 0.05\) is a promise the planner cannot keep. So compare the ensemble’s predicted spread with its actual error, horizon by horizon:

Spread divided by real error. Counting both kinds of uncertainty, the unicycle hybrid stays within 0.84–1.11 at every horizon. The members' disagreement alone would read as 2–7× overconfident. The noise-free pendulum's ensemble is 2–5× too cautious.

The spread has to be measured the way the planner uses it: roll out sampled particles, each following its member and drawing from that member’s (\sigma_e), and compare their spread with the real error. Two lessons come out of it:

  • Count both kinds of uncertainty. Measured as the disagreement between the members’ mean predictions alone — epistemic uncertainty only — the hybrid’s spread is 0.15–0.6 of its real error, which reads as badly overconfident. But the real error also contains the robot’s noise, which builds up like a random walk (the dotted noise floor in the figures above). With the members’ learned noise included, the ratio is 0.84–1.11 at every horizon for the hybrid and 0.88–1.33 for the pure ensemble: close to calibrated. The learned (\sigma_e) has found the true noise level.
  • The pendulum’s ensemble is too cautious. Its simulator has no noise at all, yet each member learned some, and the members also disagree more than they are wrong. Together the predicted spread is 1.9–4.9 times the real error. A cautious model makes a chance-constrained planner timid, and since the ratio changes with the horizon, no single scale factor fixes it exactly.

The rule: before a chance constraint can be trusted, measure the calibration on held-out data, and correct it if needed. One simple correction is to scale the spread by a factor \(c\), chosen so that 90 % of real errors fall inside \(c\) times the spread (split conformal prediction).

Why the uncertainty changes the plan

The stochastic MPC lesson proves an uncomfortable result. With linear dynamics, additive noise, a quadratic cost and a shared input plan, averaging over scenarios cannot change the optimal input: the spread adds a constant that no input can affect.

Here, two of those assumptions break:

  • The spread depends on the actions. Each ensemble member responds differently to different actions, most of all in regions they were not trained on, so some plans make the particles fan out and others keep them tight. A plan through well-explored states has low epistemic uncertainty, and the planner can tell.
  • There is a chance constraint. A penalty on the fraction of particles that collide depends on the whole distribution, not just its mean.

Both let the risk term change the decision. In the last episodes shown above, the hybrid goes around the side of the obstacle away from the sand, while the textbook planner, which never doubts itself, takes the low route past the sand and collides.

In stochastic MPC terms

Classical stochastic MPC This lesson
nominal model + learned residual --model hybrid: textbook unicycle + ensemble residual
covariance propagation along the horizon 10 particles, each pinned to one ensemble member
expected cost, e.g. \(\bar{x}^\top Q \bar{x} + \operatorname{tr}(Q P)\) average of the particles’ costs
chance constraint via a tightened bound (\(\gamma = 1.645\) for 95 %) fraction of colliding particles \(\le \delta\)
SQP with real-time iterations, horizon \(N\) CEM, horizon \(H = 20\)

The sampling version is slower and noisier than a well-tuned SQP. But it needs no gradients and no linearisation, it handles any cost and constraint you can evaluate, and it works with whatever model you can roll out — including the far larger learned models in the rest of this course.

The code

The project’s code is not published yet. It is four files:

File Contents
envs.py the two robots: hidden true dynamics, the cost, the obstacle constraint and the textbook unicycle
model.py ProbEnsemble: batched Gaussian MLPs, NLL training on bootstrap resamples, optional physics prior
planner.py CEMPlanner: CEM over action sequences, particle rollouts, expected cost and the chance constraint
run.py the Dyna loop, the plots and the compounding-error test

Typical runs take a few minutes on a CPU:

python run.py --env pendulum
python run.py --env unicycle --model hybrid    # also: --model pe, --model nominal

Try it yourself.

  • Mean versus samples. Plan with mean predictions only (--mean_only) and count collisions. What does ignoring the uncertainty cost?
  • Choose δ. Compare --no_cc, --delta 0.01 and --delta 0.2: how do path length and collisions trade off? The live animation above lets you try this in the browser first.
  • Ensemble size. Run --ensemble 1 --particles 10 against the default 5. What happens to the spread curve when there is no one to disagree with?
  • Calibrate. For the pendulum, find the scale \(c\) that puts 90 % of held-out errors inside \(c\) times the total spread, plan with the calibrated spread, and see whether the swing-up gets faster. Why did the members learn noise that the simulator does not have?
  • Dead time. Delay the unicycle’s actions by 3 steps (0.3 s) and watch the model fail. Then feed the last 3 actions in as extra inputs. Lesson 3, PlaNet, learns a recurrent state that handles this by itself.