ManiSkill with a TD-MPC2 baseline
INFO
このページはまだ翻訳されていません。 英語版を読む
ManiSkill 3 simulates manipulation with SAPIEN, GPU-parallel when CUDA is available. Here the task is PushCube-v1: push a cube into a goal region with a Panda arm. Rewards are ManiSkill's normalized dense rewards, and an episode succeeds if ManiSkill's success flag is raised at any step.
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 24,000 updates, not the paper's millions.
Not executed. ManiSkill's SAPIEN simulator publishes Linux wheels only for x86_64, so this notebook was not run on the aarch64 GPU nodes that produced the others. Run it on an x86_64 machine with CUDA, or on macOS with MoltenVK, after
pip install "torch-world[maniskill]".
import importlib.util
if importlib.util.find_spec("torch_world") is None: # on Colab
%pip install -q "torch-world[examples,maniskill]"import time
import torch
from torch_world import plots
from torch_world.envs import ManiSkill
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 = "PushCube-v1", 16, 3
world = ManiSkill(TASK, batch_size=ENVS, control_mode="pd_ee_delta_pos", terminate_on_success=False, 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")The task
The arm moves its end effector by position deltas, control_mode="pd_ee_delta_pos". Episodes run to the time limit, as in TD-MPC2's own evaluations, instead of ending at success: the rewards are dense and highest near the goal, so ending the episode there would cut off the reward a return-maximizing planner is after. 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}")Online training
Each round collects 16 episodes in parallel, then takes 600 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(40):
model.train()
for _ in range(600):
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 % 4 == 0 or round == 39:
print(f"round {round:3d} return {history[-1][0]:7.1f} success {history[-1][1]:.2f} {(time.perf_counter() - tic) / 60:5.1f} min")
plots.curves(log, smooth=100)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} success {success.float().mean():.2f}")
plots.bars({"success rate": {k: v["success"] for k, v in results.items()}}, xlabel="success rate", baseline="random actions")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: ManiSkill(name) takes the suite's own task names, and list_envs(backend="maniskill") lists the registered ones.
