DeepMind Control Suite with a TD-MPC2 baseline
The DeepMind Control Suite is the standard benchmark for continuous control. Here the task is cartpole-swingup: swing a pole up from hanging and balance it on a moving cart, from the cart and pole's positions and velocities. Rewards are dense, in [0, 1] per step, and the suite has no success condition, so the score is the episode return.
The baseline is TD-MPC2, the model these suites were benchmarked with: an encoder, latent dynamics, a reward head, an ensemble of Q-functions and a policy prior, learned online from what the agent collects, with no decoder. MPPI searches action sequences in its latent space. This is a deliberately small run: a 128-dimensional latent, state observations and 60,000 updates, not the paper's millions.
import importlib.util
if importlib.util.find_spec("torch_world") is None: # on Colab
%pip install -q "torch-world[examples,dmcontrol]"import time
import torch
from torch_world import plots
from torch_world.envs import DMControl
from torch_world.models import TDMPC2
from torch_world.models.tdmpc import state_encoder
from torch_world.planning import MPPI
torch.manual_seed(0)
device = "cuda" if torch.cuda.is_available() else "cpu"
TASK, ENVS, HORIZON = "cartpole-swingup", 16, 3
world = DMControl(TASK, batch_size=ENVS, action_repeat=2, render_size=128)
EPISODE, A, D = world.max_episode_steps, world.action_dim, world.state.shape[-1]
print(f"{EPISODE}-step episodes, {D} state dimensions, {A} actions")500-step episodes, 5 state dimensions, 1 actionsThe task
Each action repeats for two control steps, as in TD-MPC2, so an episode is 500 steps. 16 episodes run in parallel, one per batch lane; each lane is seeded separately. The first frames of four lanes:
world.reset(seed=0)
plots.images(world.render_frame()[:4], [f"lane {i}" for i in range(4)], ncols=4, size=2.2)
Model and planner
A small TD-MPC2: 128-dimensional SimNorm latents, 256-unit MLPs and the paper's five Q-functions, with the reference's discount for this episode length. MPPI plans 3 steps ahead with 256 sequences, 12 of them proposed by the policy prior, and starts each call from the previous plan shifted by one step.
model = TDMPC2(
state_encoder(D, latent_dim=128, hidden_dim=256), action_dim=A, latent_dim=128, mlp_dim=256,
discount=TDMPC2.episode_discount(EPISODE), episodic=False,
).to(device)
opt = torch.optim.Adam(model.param_groups(3e-4))
planner = MPPI(horizon=HORIZON, action_dim=A, num_samples=256, num_elites=32, num_pi_trajs=12, iterations=4)
print(f"{sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6:.2f}M parameters, discount {model.discount:.3f}")1.03M parameters, discount 0.990Online training
Each round collects 16 episodes in parallel, then takes 1000 gradient steps on windows of HORIZON + 1 steps from all episodes so far. Windows never cross the end of an episode: a lane that finished is padding, valid=False, until the next reset. The first round acts at random; after that, MPPI acts, with exploration noise from its own final std.
buffer = {k: [] for k in ("obs", "actions", "rewards", "terminated", "valid")}
def collect(policy, seed, frames=0):
"""Run one episode per lane; store it, and return its return, success and the first lanes' frames."""
obs = world.reset(seed=seed)
planner.reset()
data = {k: [] for k in buffer}
data["obs"].append(obs)
returns, success = torch.zeros(ENVS), torch.zeros(ENVS, dtype=torch.bool)
video = [world.render_frame()[:frames]] if frames else []
while not world.transition.done.all():
active = ~world.transition.done
action = policy(obs)
obs = world.step(action)
t = world.transition
for key, value in zip(data, (obs, action, t.reward, t.terminated & active, active)):
data[key].append(value)
returns += t.reward * active
if t.success is not None:
success |= t.success
if frames:
video.append(world.render_frame()[:frames])
for key in buffer: # pad to a full episode, invalid, when every lane ended early
x = torch.stack(data[key], 1)
pad = torch.zeros_like(x[:, :1]).expand(-1, EPISODE + (key == "obs") - x.size(1), *x.shape[2:])
buffer[key].append(torch.cat([x, pad], 1))
return returns, success, torch.stack(video, 1) if frames else None
def sample(n):
"""Windows of HORIZON + 1 observations whose HORIZON steps are all valid."""
obs, actions, rewards, terminated, valid = (torch.cat(buffer[k]) for k in buffer)
starts = valid[:, HORIZON - 1 :].nonzero() # valid through t + HORIZON - 1, so valid from t
pick = starts[torch.randint(len(starts), (n,))]
episode, t = pick[:, :1], pick[:, 1:] + torch.arange(HORIZON + 1)
steps = t[:, :-1]
batch = obs[episode, t], actions[episode, steps], rewards[episode, steps], terminated[episode, steps]
return [x.to(device) for x in batch]
def act(obs, explore=True):
return planner(model, model.encode(obs.to(device)[:, None]), explore=explore)[:, 0].cpu()
def random_policy(obs):
return torch.rand(ENVS, A) * 2 - 1
log = {k: [] for k in ("consistency_loss", "reward_loss", "value_loss", "pi_loss")}
history, tic = [], time.perf_counter()
returns, success, _ = collect(random_policy, seed=0)
history.append((returns.mean().item(), success.float().mean().item()))
for round in range(60):
model.train()
for _ in range(1000):
out = model(*sample(256))
opt.zero_grad()
out["loss"].backward()
model.clip_grad_norm(20.0)
opt.step()
model.update_target(0.99)
for key in log:
log[key].append(out[key].item())
model.eval()
with torch.no_grad():
returns, success, _ = collect(act, seed=(round + 1) * ENVS)
history.append((returns.mean().item(), success.float().mean().item()))
if round % 6 == 0 or round == 59:
print(f"round {round:3d} return {history[-1][0]:7.1f} {(time.perf_counter() - tic) / 60:5.1f} min")
plots.curves(log, smooth=100)round 0 return 205.4 1.4 minround 6 return 380.1 10.3 minround 12 return 801.2 23.4 minround 18 return 809.9 40.5 minround 24 return 845.9 55.0 minround 30 return 839.8 67.1 minround 36 return 840.2 76.9 minround 42 return 860.9 86.6 minround 48 return 833.8 103.2 minround 54 return 879.9 117.1 minround 59 return 879.4 125.3 min
rounds = list(range(len(history)))
plots.curves({"episode return": (rounds, [h[0] for h in history])}, smooth=3, logy=False, ylabel="return per round")
Evaluation
16 new seeded episodes for each of three policies: MPPI over the world model without exploration noise, the policy prior alone (its mean action, no search) and random actions.
def prior(obs):
return model.pi(model.encode(obs.to(device)[:, None])[:, 0])[1]["mean"].cpu()
results, video = {}, None
with torch.no_grad():
for name, policy in (
("TD-MPC2 + MPPI", lambda obs: act(obs, explore=False)),
("policy prior", prior),
("random actions", random_policy),
):
frames = 4 if name == "TD-MPC2 + MPPI" else 0
returns, success, clip = collect(policy, seed=10_000, frames=frames)
video = clip if frames else video
results[name] = {"return": returns.mean().item(), "success": success.float().mean().item()}
print(f"{name:15s} return {returns.mean():7.1f} ± {returns.std():5.1f}")
plots.bars({"episode return": {k: v["return"] for k, v in results.items()}}, xlabel="return", baseline="random actions")TD-MPC2 + MPPI return 880.8 ± 0.3policy prior return 773.4 ± 1.0random actions return 43.3 ± 30.4
Four of the planned evaluation episodes.
step = max(video.size(1) // 60, 1)
plots.episodes(video[:, ::step], titles=[f"lane {i}" for i in range(4)], fps=8)
This is a small baseline. TD-MPC2's reference runs use a 512-dimensional latent, one update per environment step and up to millions of steps; observation="rgb" with pixel_encoder trains from images. Any other task works the same way: DMControl(name) takes the suite's own task names, and list_envs(backend="dmcontrol") lists the registered ones.
