torch_world.envs
class PointMass
PointMass(
batch_size: int = 1,
size: int = 32,
max_step: float = 0.1,
sigma: float = 0.06,
device=None,
*,
quality="high",
render_size=None,
max_episode_steps=100,
observation="rgb",
)Batched 2D point mass in the unit square, rendered as a Gaussian blob on an size x size RGB image.
Actions are velocities in [-1, 1]^2 scaled by max_step; positions are clipped to [low, high]^2.
Members
| Member | Description |
|---|---|
sample_goals | Goal states at a uniform distance in distance from the current states, inside the bounds. |
render | Images (B, 3, size, size) in [0, 1]: a dark blob on a light color gradient. |
position | The planar position to reach: the point itself. |
distance | Distance to goal (B, state_dim) of states (B, ..., state_dim). |
collect | Random-action episodes: pixels (B, T, 3, size, size), actions (B, T, 2), states (B, T, 2). |
Source code in torch_world/envs/point_mass.py
class PointMass(LegacyEnvironment):
"""Batched 2D point mass in the unit square, rendered as a Gaussian blob on an ``size x size`` RGB image.
Actions are velocities in ``[-1, 1]^2`` scaled by ``max_step``; positions are clipped to ``[low, high]^2``.
"""
env_id = "PointMass-v0"
action_dim = 2
state_dim = 2
low, high = 0.0, 1.0
radius = 0.1
def __init__(
self,
batch_size: int = 1,
size: int = 32,
max_step: float = 0.1,
sigma: float = 0.06,
device=None,
*,
quality="high",
render_size=None,
max_episode_steps=100,
observation="rgb",
):
self.batch_size, self.size, self.max_step, self.sigma = batch_size, size, max_step, sigma
self.device = device
self.state = torch.zeros(batch_size, 2, device=device)
self._configure_benchmark(
quality=quality,
render_size=render_size,
max_episode_steps=max_episode_steps,
observation=observation,
max_step=max_step,
sigma=sigma,
)
def reset(self, state: Tensor | None = None, generator: torch.Generator | None = None) -> Tensor:
if state is None:
state = torch.rand(self.batch_size, 2, generator=generator).to(self.device)
state = self.low + (self.high - self.low) * state
self.state = state.clone()
return self.render()
def sample_goals(
self, distance: tuple[float, float] = (0.2, 0.5), generator: torch.Generator | None = None
) -> Tensor:
"""Goal states at a uniform distance in ``distance`` from the current states, inside the bounds."""
goals = self.state.clone()
todo = torch.ones(self.batch_size, dtype=torch.bool, device=self.state.device)
while todo.any():
angle = torch.rand(self.batch_size, generator=generator).to(goals) * 2 * torch.pi
radius = (torch.rand(self.batch_size, generator=generator) * (distance[1] - distance[0]) + distance[0]).to(
goals
)
candidate = self.state + radius[:, None] * torch.stack([angle.cos(), angle.sin()], -1)
inside = ((candidate >= self.low) & (candidate <= self.high)).all(-1) & todo
goals[inside], todo = candidate[inside], todo & ~inside
return goals
def step(self, action: Tensor) -> Tensor:
self.state = (self.state + self.max_step * action.clamp(-1, 1)).clamp(self.low, self.high)
return self.render()
def render(self, state: Tensor | None = None) -> Tensor:
"""Images ``(B, 3, size, size)`` in ``[0, 1]``: a dark blob on a light color gradient."""
state = self.state if state is None else state
grid = (torch.arange(self.size, device=state.device) + 0.5) / self.size
y, x = torch.meshgrid(grid, grid, indexing="ij")
d2 = (x - state[:, 0, None, None]).square() + (y - state[:, 1, None, None]).square()
blob = torch.exp(-d2 / (2 * self.sigma**2))[:, None]
background = 0.78 + 0.18 * torch.stack([x, y, 1 - x], dim=0)[None]
ink = torch.tensor([0.10, 0.16, 0.36], device=state.device)[None, :, None, None]
return background + blob * (ink - background)
@staticmethod
def position(states: Tensor) -> Tensor:
"""The planar position to reach: the point itself."""
return states[..., :2]
object_position = position # what the task moves to its goal, for path-based metrics such as SPL
def distance(self, states: Tensor, goal: Tensor) -> Tensor:
"""Distance to ``goal`` ``(B, state_dim)`` of states ``(B, ..., state_dim)``."""
goal = goal.view(len(goal), *[1] * (states.dim() - 2), -1)
return (self.position(states) - self.position(goal)).norm(dim=-1)
def success(self, states: Tensor, goal: Tensor) -> Tensor:
return self.distance(states, goal) <= self.radius
def collect(self, num_steps: int, generator: torch.Generator | None = None, keep: float = 0.0) -> dict[str, Tensor]:
"""Random-action episodes: ``pixels`` ``(B, T, 3, size, size)``, ``actions`` ``(B, T, 2)``, ``states`` ``(B, T, 2)``.
Each step keeps the previous action with probability ``keep``, so that episodes wander further. ``actions[:, t]``
is applied at ``states[:, t]``.
"""
pixels, states, actions = [self.reset(generator=generator)], [self.state], []
for _ in range(num_steps - 1):
action = (torch.rand(self.batch_size, 2, generator=generator) * 2 - 1).to(self.state.device)
if keep and actions:
kept = (torch.rand(self.batch_size, 1, generator=generator) < keep).to(self.state.device)
action = torch.where(kept, actions[-1], action)
actions.append(action)
pixels.append(self.step(action))
states.append(self.state)
actions.append(torch.zeros_like(actions[-1]))
return {"pixels": torch.stack(pixels, 1), "actions": torch.stack(actions, 1), "states": torch.stack(states, 1)}method sample_goals
sample_goals(
distance: tuple[float, float] = (0.2, 0.5),
generator: torch.Generator | None = None,
) -> TensorGoal states at a uniform distance in distance from the current states, inside the bounds.
Source code in torch_world/envs/point_mass.py
def sample_goals(
self, distance: tuple[float, float] = (0.2, 0.5), generator: torch.Generator | None = None
) -> Tensor:
"""Goal states at a uniform distance in ``distance`` from the current states, inside the bounds."""
goals = self.state.clone()
todo = torch.ones(self.batch_size, dtype=torch.bool, device=self.state.device)
while todo.any():
angle = torch.rand(self.batch_size, generator=generator).to(goals) * 2 * torch.pi
radius = (torch.rand(self.batch_size, generator=generator) * (distance[1] - distance[0]) + distance[0]).to(
goals
)
candidate = self.state + radius[:, None] * torch.stack([angle.cos(), angle.sin()], -1)
inside = ((candidate >= self.low) & (candidate <= self.high)).all(-1) & todo
goals[inside], todo = candidate[inside], todo & ~inside
return goalsmethod render
render(state: Tensor | None = None) -> TensorImages (B, 3, size, size) in [0, 1]: a dark blob on a light color gradient.
Source code in torch_world/envs/point_mass.py
def render(self, state: Tensor | None = None) -> Tensor:
"""Images ``(B, 3, size, size)`` in ``[0, 1]``: a dark blob on a light color gradient."""
state = self.state if state is None else state
grid = (torch.arange(self.size, device=state.device) + 0.5) / self.size
y, x = torch.meshgrid(grid, grid, indexing="ij")
d2 = (x - state[:, 0, None, None]).square() + (y - state[:, 1, None, None]).square()
blob = torch.exp(-d2 / (2 * self.sigma**2))[:, None]
background = 0.78 + 0.18 * torch.stack([x, y, 1 - x], dim=0)[None]
ink = torch.tensor([0.10, 0.16, 0.36], device=state.device)[None, :, None, None]
return background + blob * (ink - background)method position
position(states: Tensor) -> TensorThe planar position to reach: the point itself.
Source code in torch_world/envs/point_mass.py
@staticmethod
def position(states: Tensor) -> Tensor:
"""The planar position to reach: the point itself."""
return states[..., :2]method distance
distance(states: Tensor, goal: Tensor) -> TensorDistance to goal (B, state_dim) of states (B, ..., state_dim).
Source code in torch_world/envs/point_mass.py
def distance(self, states: Tensor, goal: Tensor) -> Tensor:
"""Distance to ``goal`` ``(B, state_dim)`` of states ``(B, ..., state_dim)``."""
goal = goal.view(len(goal), *[1] * (states.dim() - 2), -1)
return (self.position(states) - self.position(goal)).norm(dim=-1)method collect
collect(
num_steps: int, generator: torch.Generator | None = None, keep: float = 0.0
) -> dict[str, Tensor]Random-action episodes: pixels (B, T, 3, size, size), actions (B, T, 2), states (B, T, 2).
Each step keeps the previous action with probability keep, so that episodes wander further. actions[:, t] is applied at states[:, t].
Source code in torch_world/envs/point_mass.py
def collect(self, num_steps: int, generator: torch.Generator | None = None, keep: float = 0.0) -> dict[str, Tensor]:
"""Random-action episodes: ``pixels`` ``(B, T, 3, size, size)``, ``actions`` ``(B, T, 2)``, ``states`` ``(B, T, 2)``.
Each step keeps the previous action with probability ``keep``, so that episodes wander further. ``actions[:, t]``
is applied at ``states[:, t]``.
"""
pixels, states, actions = [self.reset(generator=generator)], [self.state], []
for _ in range(num_steps - 1):
action = (torch.rand(self.batch_size, 2, generator=generator) * 2 - 1).to(self.state.device)
if keep and actions:
kept = (torch.rand(self.batch_size, 1, generator=generator) < keep).to(self.state.device)
action = torch.where(kept, actions[-1], action)
actions.append(action)
pixels.append(self.step(action))
states.append(self.state)
actions.append(torch.zeros_like(actions[-1]))
return {"pixels": torch.stack(pixels, 1), "actions": torch.stack(actions, 1), "states": torch.stack(states, 1)}class Macaw
Macaw(
batch_size: int = 1,
size: int = 64,
max_step: float = 0.1,
scale: float = 1.0,
device=None,
rooms: bool = False,
door_width: float = 0.3,
*,
quality="high",
render_size=None,
max_episode_steps=100,
observation="rgb",
)A Hyacinth macaw flying over the Pantanal, on size x size RGB images: the same dynamics as PointMass.
The state is the bird's position, kept in [low, high]^2. Its wings beat a quarter cycle per step, so a single frame does not tell the phase but a short history does. render(state) without a phase draws the bird gliding, as used for goal images. Rendering is resolution-free: a Macaw(size=192) draws the same states sharper.
With rooms, a rock wall splits the sky with one gap the bird must fly through, as in PLDM's Two-Rooms (see Rooms): tasks gives goals on the other side, and collect keeps each action with probability 0.8.
Source code in torch_world/envs/macaw.py
class Macaw(Rooms, PointMass):
"""A Hyacinth macaw flying over the Pantanal, on ``size x size`` RGB images: the same dynamics as ``PointMass``.
The state is the bird's position, kept in ``[low, high]^2``. Its wings beat a quarter cycle per step, so a single
frame does not tell the phase but a short history does. ``render(state)`` without a phase draws the bird gliding,
as used for goal images. Rendering is resolution-free: a ``Macaw(size=192)`` draws the same states sharper.
With ``rooms``, a rock wall splits the sky with one gap the bird must fly through, as in PLDM's Two-Rooms (see
``Rooms``): ``tasks`` gives goals on the other side, and ``collect`` keeps each action with probability 0.8.
"""
env_id = "Macaw-v0"
low, high = 0.15, 0.85
def __init__(
self,
batch_size: int = 1,
size: int = 64,
max_step: float = 0.1,
scale: float = 1.0,
device=None,
rooms: bool = False,
door_width: float = 0.3,
*,
quality="high",
render_size=None,
max_episode_steps=100,
observation="rgb",
):
super().__init__(batch_size, size, max_step, device=device)
self.scale, self.rooms, self.door_width, self.margin = scale, rooms, door_width, 0.05
self.phase = torch.zeros(batch_size, device=device)
self.landscape = landscape(size, device)
self._configure_benchmark(
quality=quality,
render_size=render_size,
max_episode_steps=max_episode_steps,
observation=observation,
max_step=max_step,
scale=scale,
)
def reset(self, state: Tensor | None = None, generator: torch.Generator | None = None) -> Tensor:
self.phase = torch.zeros(self.batch_size, device=self.device)
return super().reset(state, generator)
def step(self, action: Tensor) -> Tensor:
self.phase = self.phase + math.pi / 2
return super().step(action)
def collect(self, num_steps: int, generator: torch.Generator | None = None, keep: float | None = None):
keep = (0.8 if self.rooms else 0.0) if keep is None else keep
return super().collect(num_steps, generator, keep)
def render(self, state: Tensor | None = None, phase: Tensor | None = None, goal: Tensor | None = None) -> Tensor:
"""Images ``(B, 3, size, size)`` in ``[0, 1]``; ``phase`` ``(B,)`` sets the wing beat.
``goal`` ``(B, 2)`` draws a translucent gliding macaw where the goal is, for videos; models see plain frames.
"""
if state is None:
state, phase = self.state, self.phase if phase is None else phase
phase = torch.zeros(len(state), device=state.device) if phase is None else phase
image = self.landscape.to(state.device).expand(len(state), -1, -1, -1)
if goal is not None:
goal = goal.to(state.device)
image = image + 0.35 * (self._bird(image, goal, torch.zeros_like(phase)) - image)
if self.rooms:
x, y = grid(self.size, state.device)
image = paint(image, self.wall_sdf(x, y), shade(1 - x.sub(0.5).abs() * 12, ROCK_EDGE, ROCK), self.size)
return self._bird(image, state, phase)
def _bird(self, image: Tensor, state: Tensor, phase: Tensor) -> Tensor:
"""``image`` with the macaw drawn at ``state`` ``(B, 2)`` with wing beat ``phase`` ``(B,)``."""
x, y = grid(self.size, state.device)
dx, dy = (x - state[:, 0, None, None]) / self.scale, (y - state[:, 1, None, None]) / self.scale
pitch = -0.1
px, py = dx * math.cos(pitch) + dy * math.sin(pitch), -dx * math.sin(pitch) + dy * math.cos(pitch)
ppu = self.size * self.scale
lift = phase.sin()[:, None, None]
def draw(sdf, color):
nonlocal image
image = paint(image, sdf, color, ppu)
draw(_wing(px, py, lift, (0.026, -0.024), 0.85), FEATHER_EDGE)
for k, tail in enumerate(TAIL[::-1]):
draw(polygon(px, py, tail), shade((py + 0.01) / 0.03, COBALT, SHADOW) if k else FLIGHT)
body = union(
ellipse(px, py, (0.0, 0.0), (0.078, 0.031)),
capsule(px, py, (0.03, -0.006), (0.068, -0.02), 0.027),
circle(px, py, (0.072, -0.022), 0.031),
)
draw(body, shade((py + 0.035) / 0.065, HIGHLIGHT, SHADOW))
draw(union(circle(px, py, (0.103, -0.02), 0.021), polygon(px, py, HOOK)), BEAK)
draw(ellipse(px, py, (0.104, -0.031), (0.01, 0.004)), BEAK_SHINE)
draw(ellipse(px, py, (0.099, 0.005), (0.016, 0.009)), BEAK)
draw(ellipse(px, py, (0.089, 0.008), (0.012, 0.0045)), YELLOW)
draw(circle(px, py, (0.079, -0.028), 0.0095), YELLOW)
draw(circle(px, py, (0.08, -0.028), 0.005), PUPIL)
wing = _wing(px, py, lift, (0.018, -0.018), 1.0, edge=0.003)
draw(wing, FEATHER_EDGE)
draw(_wing(px, py, lift, (0.018, -0.018), 1.0), shade((py + 0.1) / 0.2, FLIGHT, SHADOW))
draw(capsule(px, py, (0.018, -0.018), _wrist((0.018, -0.018), lift, 1.0), 0.022), COBALT)
return imagemethod render
render(
state: Tensor | None = None,
phase: Tensor | None = None,
goal: Tensor | None = None,
) -> TensorImages (B, 3, size, size) in [0, 1]; phase (B,) sets the wing beat.
goal (B, 2) draws a translucent gliding macaw where the goal is, for videos; models see plain frames.
Source code in torch_world/envs/macaw.py
def render(self, state: Tensor | None = None, phase: Tensor | None = None, goal: Tensor | None = None) -> Tensor:
"""Images ``(B, 3, size, size)`` in ``[0, 1]``; ``phase`` ``(B,)`` sets the wing beat.
``goal`` ``(B, 2)`` draws a translucent gliding macaw where the goal is, for videos; models see plain frames.
"""
if state is None:
state, phase = self.state, self.phase if phase is None else phase
phase = torch.zeros(len(state), device=state.device) if phase is None else phase
image = self.landscape.to(state.device).expand(len(state), -1, -1, -1)
if goal is not None:
goal = goal.to(state.device)
image = image + 0.35 * (self._bird(image, goal, torch.zeros_like(phase)) - image)
if self.rooms:
x, y = grid(self.size, state.device)
image = paint(image, self.wall_sdf(x, y), shade(1 - x.sub(0.5).abs() * 12, ROCK_EDGE, ROCK), self.size)
return self._bird(image, state, phase)class RobotCube
RobotCube(
robot: str = "ur10e",
batch_size: int = 1,
size: int = 64,
camera: str = "front",
control_dt: float = 0.1,
max_step: float | None = None,
task: str = "pick",
root: str | Path | None = None,
device=None,
*,
quality="high",
render_size=None,
max_episode_steps=100,
observation="rgb",
presentation_camera="overview",
)Single-cube pick-and-place with a real arm in MuJoCo, after OGBench cube-single, in a light studio scene.
robot is "ur10e" (Universal Robots UR10e with a Robotiq 2F-85 gripper) or "so101" (the open-source SO-101 arm), both from MuJoCo Menagerie and downloaded once into root. Actions (dx, dy, dz, grip) in [-1, 1]^4 set the gripper's target up to max_step meters from its current position, solved by damped least-squares inverse kinematics with the gripper pointing down, and open (grip > 0) or close the gripper. Each step lasts control_dt seconds of simulation. Targets are relative to the gripper rather than to the previous target, and the arm is gravity-compensated so its joint servos hold their targets: the next state depends on the state, not on a hidden command, and resetting to a recorded state replays its actions (up to the joint velocities and finger positions, which the state omits). The state is (gripper x, y, z, opening, cube x, y, z).
task sets what tasks, distance, success and position measure: "pick" carries the cube to a goal spot, "reach" moves the open gripper to a goal pose with the cube left in place.
The batch is simulated sequentially on the CPU; observations are (B, 3, size, size) renders of the "front" camera ("top" is an orthographic view of the workspace, "wrist" rides on the gripper).
Park et al., "OGBench: Benchmarking Offline Goal-Conditioned RL", ICLR 2025. Paper: https://arxiv.org/abs/2410.20092 Code: https://github.com/seohongpark/ogbench Models: https://github.com/google-deepmind/mujoco_menagerie
Members
| Member | Description |
|---|---|
reset | A random cube on the table and the open gripper hovering above the workspace, or the given state. |
tasks | Random starts, and goals the scripted expert reaches from them: the cube carried to a random spot with the gripper backed off ("pick", run until every cube is placed, up to 60 steps), or the open gripper moved to a random pose above the workspace ("reach"). |
reach_targets | Random gripper positions (B, 3) above the workspace, the aims of "reach" tasks. |
scripted | Clean expert actions (B, 4) toward goal states (B, 7) of the current task. |
position | The cube's ("pick") or the gripper's ("reach") position on the table in the unit square of the "top" camera (x right, y down), which spans top_size meters. |
object_position | Position in meters of what the task moves to its goal, for path-based metrics such as SPL: the cube on the table plane ("pick"; lifting it is not a detour) or the gripper in 3D ("reach"). |
distance | Distance in meters between the cube and its goal spot on the table ("pick"), or between the gripper and its goal position ("reach"), for states (B, ..., 7) and goals (B, 7). |
success | The cube rests on the table within radius of its goal ("pick"), or the gripper is within radius of its goal ("reach"). |
sample_targets | Goal cube positions (B, 2) inside the workspace, at least distance[0] and at most distance[1] away. |
expert | Scripted pick-and-place actions (B, 4) that carry the cube to target (B, 2) and back off. |
solve | Run the clean expert for steps; returns the final states, used as goals. |
collect | Play data from the noisy expert, retargeted after every placement, as in OGBench's play datasets. |
Source code in torch_world/envs/robot_cube.py
class RobotCube(MujocoEnv, LegacyEnvironment):
"""Single-cube pick-and-place with a real arm in MuJoCo, after OGBench ``cube-single``, in a light studio scene.
``robot`` is ``"ur10e"`` (Universal Robots UR10e with a Robotiq 2F-85 gripper) or ``"so101"`` (the open-source
SO-101 arm), both from MuJoCo Menagerie and downloaded once into ``root``. Actions ``(dx, dy, dz, grip)`` in
``[-1, 1]^4`` set the gripper's target up to ``max_step`` meters from its current position, solved by damped
least-squares inverse kinematics with the gripper pointing down, and open (``grip > 0``) or close the gripper. Each
step lasts ``control_dt`` seconds of simulation. Targets are relative to the gripper rather than to the previous
target, and the arm is gravity-compensated so its joint servos hold their targets: the next state depends on the
state, not on a hidden command, and resetting to a recorded state replays its actions (up to the joint
velocities and finger positions, which the state omits). The state is ``(gripper x, y, z, opening, cube x, y, z)``.
``task`` sets what ``tasks``, ``distance``, ``success`` and ``position`` measure: ``"pick"`` carries the cube to a
goal spot, ``"reach"`` moves the open gripper to a goal pose with the cube left in place.
The batch is simulated sequentially on the CPU; observations are ``(B, 3, size, size)`` renders of the
``"front"`` camera (``"top"`` is an orthographic view of the workspace, ``"wrist"`` rides on the gripper).
Park et al., "OGBench: Benchmarking Offline Goal-Conditioned RL", ICLR 2025.
Paper: https://arxiv.org/abs/2410.20092
Code: https://github.com/seohongpark/ogbench
Models: https://github.com/google-deepmind/mujoco_menagerie
"""
env_id = "RobotCube-v0"
action_dim = 4
state_dim = 7
def __init__(
self,
robot: str = "ur10e",
batch_size: int = 1,
size: int = 64,
camera: str = "front",
control_dt: float = 0.1,
max_step: float | None = None,
task: str = "pick",
root: str | Path | None = None,
device=None,
*,
quality="high",
render_size=None,
max_episode_steps=100,
observation="rgb",
presentation_camera="overview",
):
if task not in ("pick", "reach"):
raise ValueError(f"task must be 'pick' or 'reach', not {task!r}")
self.robot, self.config, self.task = robot, ROBOTS[robot], task
config = self.config
super().__init__(
_build(robot, Path(root or Path.home() / ".cache" / "torch_world" / "menagerie")),
batch_size,
size,
camera,
device,
)
self.max_step, self.radius, self.half = max_step or config.max_step, config.radius, config.cube
(self.x_range, self.y_range), self.hover = config.workspace, config.hover
self.top_size = max(self.x_range[1] - self.x_range[0], self.y_range[1] - self.y_range[0]) + 0.1
self.substeps = max(1, round(control_dt / self.model.opt.timestep))
self.scratch = self.mujoco.MjData(self.model)
self.site = self.model.site("grasp").id
joints = [self.model.joint(name).id for name in config.joints]
self.qpos, self.dofs = self.model.jnt_qposadr[joints], self.model.jnt_dofadr[joints]
self.limits = self.model.jnt_range[joints].T
self.arm = np.arange(len(joints))
self.cube_qpos = self.model.joint("cube").qposadr[0]
self.targets = np.zeros((batch_size, 3))
self.opening = np.ones(batch_size)
self.closed_for = np.zeros(batch_size)
self.down = None
self.state = torch.zeros(batch_size, self.state_dim, device=device)
self.env_id = "RobotCube-v0" if robot == "ur10e" else "RobotCubeSO101-v0"
self._configure_benchmark(
quality=quality,
render_size=render_size,
max_episode_steps=max_episode_steps,
observation=observation,
presentation_camera=presentation_camera,
robot=robot,
camera=camera,
control_dt=control_dt,
max_step=self.max_step,
task=task,
root=root,
)
# simulation
def reset(self, state: Tensor | None = None, generator: torch.Generator | None = None) -> Tensor:
"""A random cube on the table and the open gripper hovering above the workspace, or the given ``state``."""
if state is None:
u = torch.rand(self.batch_size, 4, generator=generator).double().numpy()
gripper = np.stack(
[_span(self.x_range, u[:, 0]), _span(self.y_range, u[:, 1]), np.full(len(u), self.hover)], 1
)
cube = np.stack([_span(self.x_range, u[:, 2]), _span(self.y_range, u[:, 3]), np.full(len(u), self.half)], 1)
opening = np.ones(len(u))
else:
s = state.double().cpu().numpy()
gripper, opening, cube = s[:, :3], s[:, 3], s[:, 4:7]
for b, d in enumerate(self.data):
self._place(d, np.concatenate([gripper[b], [opening[b]], cube[b]]))
self.targets, self.opening = gripper.copy(), opening.copy()
self.closed_for = np.zeros(self.batch_size)
self._sync()
return self.render()
def step(self, action: Tensor) -> Tensor:
a = action.clamp(-1, 1).double().cpu().numpy()
low = np.array([self.x_range[0] - 0.05, self.y_range[0] - 0.05, self.half * 0.6])
high = np.array([self.x_range[1] + 0.05, self.y_range[1] + 0.05, self.hover + 0.1])
gripper = np.stack([d.site_xpos[self.site] for d in self.data])
self.targets = np.clip(gripper + self.max_step * a[:, :3], low, high)
self.opening = np.clip(self.opening + a[:, 3], 0, 1)
self.closed_for = np.where(self.opening < 0.5, self.closed_for + 1, 0)
for b, d in enumerate(self.data):
d.ctrl[self.arm] = self._ik(d.qpos[self.qpos], self.targets[b])
d.ctrl[-1] = _span(self.config.grip, 1 - self.opening[b])
self.mujoco.mj_step(self.model, d, self.substeps)
self._sync()
return self.render()
def _place(self, d, state: np.ndarray):
mujoco = self.mujoco
gripper, opening, cube = state[:3], state[3], state[4:7]
mujoco.mj_resetData(self.model, d)
d.qpos[self.qpos] = self._ik(np.array(self.config.home), gripper, iterations=200)
d.ctrl[self.arm] = d.qpos[self.qpos]
d.ctrl[-1] = _span(self.config.grip, 1 - opening)
d.qpos[self.cube_qpos : self.cube_qpos + 7] = [*cube, 1, 0, 0, 0]
mujoco.mj_forward(self.model, d)
def _ik(self, q: np.ndarray, target: np.ndarray, iterations: int = 20, damping: float = 1e-2) -> np.ndarray:
"""Joint positions putting the gripper site at ``target`` and pointing it down."""
mujoco, m, d = self.mujoco, self.model, self.scratch
if self.down is None:
d.qpos[self.qpos] = self.config.home
mujoco.mj_kinematics(m, d)
self.down = d.site_xmat[self.site].reshape(3, 3).copy()
q = q.copy()
jacp, jacr = np.zeros((3, m.nv)), np.zeros((3, m.nv))
for _ in range(iterations):
d.qpos[self.qpos] = q
mujoco.mj_kinematics(m, d)
mujoco.mj_comPos(m, d)
rot = d.site_xmat[self.site].reshape(3, 3)
axes = range(3) if self.config.approach is None else [self.config.approach]
turn = sum(np.cross(rot[:, i], self.down[:, i]) for i in axes)
err = np.concatenate([target - d.site_xpos[self.site], 0.5 * turn])
mujoco.mj_jacSite(m, d, jacp, jacr, self.site)
jac = np.concatenate([jacp, jacr])[:, self.dofs]
q = np.clip(q + jac.T @ np.linalg.solve(jac @ jac.T + damping * np.eye(6), err), *self.limits)
return q
def _state(self, b: int, d) -> list[float]:
return [*d.site_xpos[self.site], self.opening[b], *d.qpos[self.cube_qpos : self.cube_qpos + 3]]
def _ghost(self, goal: np.ndarray):
return goal[4:7], [1, 0, 0, 0]
# tasks and scoring
def tasks(self, generator: torch.Generator | None = None) -> tuple[Tensor, Tensor]:
"""Random starts, and goals the scripted expert reaches from them: the cube carried to a random spot with the
gripper backed off (``"pick"``, run until every cube is placed, up to 60 steps), or the open gripper moved to a
random pose above the workspace (``"reach"``)."""
self.reset(generator=generator)
start = self.state.clone()
if self.task == "pick":
target = self.sample_targets(generator=generator)
for _ in range(60):
self.step(self.expert(target))
done = _placed(
self.state, torch.cat([self.state[:, :4], target, self.state[:, 6:]], -1), self.radius, self.half
)
if (done & (self.state[:, 2] > self.hover - 0.02)).all():
break
goal = self.state.clone()
else:
aim = self.reach_targets(generator)
for _ in range(12):
self.step(self.scripted(torch.cat([aim, self.state[:, 3:]], -1)))
goal = self.state.clone()
self.reset(start)
return start, goal
def reach_targets(self, generator: torch.Generator | None = None) -> Tensor:
"""Random gripper positions ``(B, 3)`` above the workspace, the aims of ``"reach"`` tasks."""
u = torch.rand(self.batch_size, 3, generator=generator)
return torch.stack(
[_span(self.x_range, u[:, 0]), _span(self.y_range, u[:, 1]), _span((3 * self.half, self.hover), u[:, 2])],
-1,
).to(self.state)
def scripted(self, goal: Tensor) -> Tensor:
"""Clean expert actions ``(B, 4)`` toward goal states ``(B, 7)`` of the current ``task``."""
if self.task == "pick":
return self.expert(goal[:, 4:6])
move = (goal[:, :3] - self.state[:, :3].to(goal)) / self.max_step
return torch.cat([move.clamp(-1, 1), torch.ones_like(goal[:, :1])], -1)
def position(self, states: Tensor) -> Tensor:
"""The cube's (``"pick"``) or the gripper's (``"reach"``) position on the table in the unit square of the
``"top"`` camera (x right, y down), which spans ``top_size`` meters."""
x = 4 if self.task == "pick" else 0
cx, cy = sum(self.x_range) / 2, sum(self.y_range) / 2
return 0.5 - torch.stack([states[..., x + 1] - cy, states[..., x] - cx], dim=-1) / self.top_size
def object_position(self, states: Tensor) -> Tensor:
"""Position in meters of what the task moves to its goal, for path-based metrics such as SPL: the cube on the
table plane (``"pick"``; lifting it is not a detour) or the gripper in 3D (``"reach"``)."""
return states[..., 4:6] if self.task == "pick" else states[..., :3]
def distance(self, states: Tensor, goal: Tensor) -> Tensor:
"""Distance in meters between the cube and its goal spot on the table (``"pick"``), or between the gripper and
its goal position (``"reach"``), for states ``(B, ..., 7)`` and goals ``(B, 7)``."""
goal = goal.view(len(goal), *[1] * (states.dim() - 2), -1)
if self.task == "reach":
return (states[..., :3] - goal[..., :3]).norm(dim=-1)
return (states[..., 4:6] - goal[..., 4:6]).norm(dim=-1)
def success(self, states: Tensor, goal: Tensor) -> Tensor:
"""The cube rests on the table within ``radius`` of its goal (``"pick"``), or the gripper is within ``radius``
of its goal (``"reach"``)."""
if self.task == "reach":
return self.distance(states, goal) <= self.radius
return _placed(states, goal, self.radius, self.half)
def sample_targets(self, distance: tuple[float, float] | None = None, generator=None) -> Tensor:
"""Goal cube positions ``(B, 2)`` inside the workspace, at least ``distance[0]`` and at most ``distance[1]`` away."""
lo, hi = distance or (2 * self.half + 0.02, 0.5 * (self.x_range[1] - self.x_range[0]) + 0.1)
cube = self.state[:, 4:6].cpu()
targets = cube.clone()
todo = torch.ones(self.batch_size, dtype=torch.bool)
while todo.any():
u = torch.rand(self.batch_size, 2, generator=generator)
angle, radius = u[:, 0] * 2 * torch.pi, lo + (hi - lo) * u[:, 1]
candidate = cube + radius[:, None] * torch.stack([angle.cos(), angle.sin()], -1)
inside = (candidate[:, 0] >= self.x_range[0]) & (candidate[:, 0] <= self.x_range[1])
inside &= (candidate[:, 1] >= self.y_range[0]) & (candidate[:, 1] <= self.y_range[1])
targets[inside & todo], todo = candidate[inside & todo], todo & ~inside
return targets.to(self.state.device)
def expert(self, target: Tensor, state: Tensor | None = None) -> Tensor:
"""Scripted pick-and-place actions ``(B, 4)`` that carry the cube to ``target`` ``(B, 2)`` and back off.
Motion is planned from the gripper position of ``state``, by default the running episode's.
"""
s = self.state if state is None else state
ee, opening, cube = s[:, :3], s[:, 3], s[:, 4:7]
settled = torch.as_tensor(self.closed_for >= self.config.settle, device=s.device) if state is None else True
grasped = (opening < 0.5) & ((ee - cube).norm(dim=-1) < 2 * self.half) & settled
placed = ~grasped & ((cube[:, :2] - target).norm(dim=-1) < self.radius) & (cube[:, 2] < self.half + 0.005)
goal_xy = torch.where((grasped | placed)[:, None], target, cube[:, :2])
above = (ee[:, :2] - goal_xy).norm(dim=-1) < 0.15 * self.radius + 0.002
low = (ee[:, 2] - self.half).abs() < 0.005
down = above & ~placed
z = torch.where(down, torch.full_like(ee[:, 2], self.half), torch.full_like(ee[:, 2], self.hover))
xy = torch.where(placed[:, None], ee[:, :2], goal_xy)
move = ((torch.cat([xy, z[:, None]], -1) - ee) / self.max_step).clamp(-1, 1)
close = torch.where(grasped, ~(down & low), down & low & ~grasped)
return torch.cat([move, torch.where(close, -1.0, 1.0)[:, None]], dim=-1)
def solve(self, target: Tensor, steps: int) -> Tensor:
"""Run the clean expert for ``steps``; returns the final states, used as goals."""
for _ in range(steps):
self.step(self.expert(target))
return self.state.clone()
def collect(
self,
num_steps: int,
noise: float = 0.04,
cameras: list[str] | None = None,
generator: torch.Generator | None = None,
every: int = 32,
) -> dict:
"""Play data from the noisy expert, retargeted after every placement, as in OGBench's ``play`` datasets.
For ``"reach"``, the noisy expert moves the open gripper to a new random pose every ``every`` steps and holds
it there, so the ``every`` steps from a multiple of ``every`` reach one pose, as a ``"reach"`` task does.
Returns ``pixels`` ``(B, T, 3, size, size)`` (or ``(B, T, V, 3, size, size)`` for a list of ``cameras``),
``actions`` ``(B, T, 4)`` and ``states`` ``(B, T, 7)``; ``actions[:, t]`` is applied at ``states[:, t]``.
``noise`` is the standard deviation added to the expert's actions.
"""
def observe():
if cameras is None:
return self.render()
return torch.stack([self.render(camera=c) for c in cameras], dim=1)
self.reset(generator=generator)
pixels, states, actions = [observe()], [self.state], []
reach = self.task == "reach"
target = self.reach_targets(generator) if reach else self.sample_targets(generator=generator)
for t in range(num_steps - 1):
n = torch.randn(self.batch_size, 4, generator=generator).to(self.state)
expert = self.scripted(torch.cat([target, self.state[:, 3:]], -1)) if reach else self.expert(target)
action = (expert + noise * n).clamp(-1, 1)
actions.append(action)
self.step(action)
pixels.append(observe())
states.append(self.state)
if reach:
target = self.reach_targets(generator) if (t + 1) % every == 0 else target
continue
done = _placed(
self.state, torch.cat([self.state[:, :4], target, self.state[:, 6:]], -1), self.radius, self.half
)
target = torch.where(done[:, None], self.sample_targets(generator=generator), target)
actions.append(torch.zeros_like(actions[-1]))
return {"pixels": torch.stack(pixels, 1), "actions": torch.stack(actions, 1), "states": torch.stack(states, 1)}method reset
reset(
state: Tensor | None = None, generator: torch.Generator | None = None
) -> TensorA random cube on the table and the open gripper hovering above the workspace, or the given state.
Source code in torch_world/envs/robot_cube.py
def reset(self, state: Tensor | None = None, generator: torch.Generator | None = None) -> Tensor:
"""A random cube on the table and the open gripper hovering above the workspace, or the given ``state``."""
if state is None:
u = torch.rand(self.batch_size, 4, generator=generator).double().numpy()
gripper = np.stack(
[_span(self.x_range, u[:, 0]), _span(self.y_range, u[:, 1]), np.full(len(u), self.hover)], 1
)
cube = np.stack([_span(self.x_range, u[:, 2]), _span(self.y_range, u[:, 3]), np.full(len(u), self.half)], 1)
opening = np.ones(len(u))
else:
s = state.double().cpu().numpy()
gripper, opening, cube = s[:, :3], s[:, 3], s[:, 4:7]
for b, d in enumerate(self.data):
self._place(d, np.concatenate([gripper[b], [opening[b]], cube[b]]))
self.targets, self.opening = gripper.copy(), opening.copy()
self.closed_for = np.zeros(self.batch_size)
self._sync()
return self.render()method tasks
tasks(generator: torch.Generator | None = None) -> tuple[Tensor, Tensor]Random starts, and goals the scripted expert reaches from them: the cube carried to a random spot with the gripper backed off ("pick", run until every cube is placed, up to 60 steps), or the open gripper moved to a random pose above the workspace ("reach").
Source code in torch_world/envs/robot_cube.py
def tasks(self, generator: torch.Generator | None = None) -> tuple[Tensor, Tensor]:
"""Random starts, and goals the scripted expert reaches from them: the cube carried to a random spot with the
gripper backed off (``"pick"``, run until every cube is placed, up to 60 steps), or the open gripper moved to a
random pose above the workspace (``"reach"``)."""
self.reset(generator=generator)
start = self.state.clone()
if self.task == "pick":
target = self.sample_targets(generator=generator)
for _ in range(60):
self.step(self.expert(target))
done = _placed(
self.state, torch.cat([self.state[:, :4], target, self.state[:, 6:]], -1), self.radius, self.half
)
if (done & (self.state[:, 2] > self.hover - 0.02)).all():
break
goal = self.state.clone()
else:
aim = self.reach_targets(generator)
for _ in range(12):
self.step(self.scripted(torch.cat([aim, self.state[:, 3:]], -1)))
goal = self.state.clone()
self.reset(start)
return start, goalmethod reach_targets
reach_targets(generator: torch.Generator | None = None) -> TensorRandom gripper positions (B, 3) above the workspace, the aims of "reach" tasks.
Source code in torch_world/envs/robot_cube.py
def reach_targets(self, generator: torch.Generator | None = None) -> Tensor:
"""Random gripper positions ``(B, 3)`` above the workspace, the aims of ``"reach"`` tasks."""
u = torch.rand(self.batch_size, 3, generator=generator)
return torch.stack(
[_span(self.x_range, u[:, 0]), _span(self.y_range, u[:, 1]), _span((3 * self.half, self.hover), u[:, 2])],
-1,
).to(self.state)method scripted
scripted(goal: Tensor) -> TensorClean expert actions (B, 4) toward goal states (B, 7) of the current task.
Source code in torch_world/envs/robot_cube.py
def scripted(self, goal: Tensor) -> Tensor:
"""Clean expert actions ``(B, 4)`` toward goal states ``(B, 7)`` of the current ``task``."""
if self.task == "pick":
return self.expert(goal[:, 4:6])
move = (goal[:, :3] - self.state[:, :3].to(goal)) / self.max_step
return torch.cat([move.clamp(-1, 1), torch.ones_like(goal[:, :1])], -1)method position
position(states: Tensor) -> TensorThe cube's ("pick") or the gripper's ("reach") position on the table in the unit square of the "top" camera (x right, y down), which spans top_size meters.
Source code in torch_world/envs/robot_cube.py
def position(self, states: Tensor) -> Tensor:
"""The cube's (``"pick"``) or the gripper's (``"reach"``) position on the table in the unit square of the
``"top"`` camera (x right, y down), which spans ``top_size`` meters."""
x = 4 if self.task == "pick" else 0
cx, cy = sum(self.x_range) / 2, sum(self.y_range) / 2
return 0.5 - torch.stack([states[..., x + 1] - cy, states[..., x] - cx], dim=-1) / self.top_sizemethod object_position
object_position(states: Tensor) -> TensorPosition in meters of what the task moves to its goal, for path-based metrics such as SPL: the cube on the table plane ("pick"; lifting it is not a detour) or the gripper in 3D ("reach").
Source code in torch_world/envs/robot_cube.py
def object_position(self, states: Tensor) -> Tensor:
"""Position in meters of what the task moves to its goal, for path-based metrics such as SPL: the cube on the
table plane (``"pick"``; lifting it is not a detour) or the gripper in 3D (``"reach"``)."""
return states[..., 4:6] if self.task == "pick" else states[..., :3]method distance
distance(states: Tensor, goal: Tensor) -> TensorDistance in meters between the cube and its goal spot on the table ("pick"), or between the gripper and its goal position ("reach"), for states (B, ..., 7) and goals (B, 7).
Source code in torch_world/envs/robot_cube.py
def distance(self, states: Tensor, goal: Tensor) -> Tensor:
"""Distance in meters between the cube and its goal spot on the table (``"pick"``), or between the gripper and
its goal position (``"reach"``), for states ``(B, ..., 7)`` and goals ``(B, 7)``."""
goal = goal.view(len(goal), *[1] * (states.dim() - 2), -1)
if self.task == "reach":
return (states[..., :3] - goal[..., :3]).norm(dim=-1)
return (states[..., 4:6] - goal[..., 4:6]).norm(dim=-1)method success
success(states: Tensor, goal: Tensor) -> TensorThe cube rests on the table within radius of its goal ("pick"), or the gripper is within radius of its goal ("reach").
Source code in torch_world/envs/robot_cube.py
def success(self, states: Tensor, goal: Tensor) -> Tensor:
"""The cube rests on the table within ``radius`` of its goal (``"pick"``), or the gripper is within ``radius``
of its goal (``"reach"``)."""
if self.task == "reach":
return self.distance(states, goal) <= self.radius
return _placed(states, goal, self.radius, self.half)method sample_targets
sample_targets(
distance: tuple[float, float] | None = None, generator=None
) -> TensorGoal cube positions (B, 2) inside the workspace, at least distance[0] and at most distance[1] away.
Source code in torch_world/envs/robot_cube.py
def sample_targets(self, distance: tuple[float, float] | None = None, generator=None) -> Tensor:
"""Goal cube positions ``(B, 2)`` inside the workspace, at least ``distance[0]`` and at most ``distance[1]`` away."""
lo, hi = distance or (2 * self.half + 0.02, 0.5 * (self.x_range[1] - self.x_range[0]) + 0.1)
cube = self.state[:, 4:6].cpu()
targets = cube.clone()
todo = torch.ones(self.batch_size, dtype=torch.bool)
while todo.any():
u = torch.rand(self.batch_size, 2, generator=generator)
angle, radius = u[:, 0] * 2 * torch.pi, lo + (hi - lo) * u[:, 1]
candidate = cube + radius[:, None] * torch.stack([angle.cos(), angle.sin()], -1)
inside = (candidate[:, 0] >= self.x_range[0]) & (candidate[:, 0] <= self.x_range[1])
inside &= (candidate[:, 1] >= self.y_range[0]) & (candidate[:, 1] <= self.y_range[1])
targets[inside & todo], todo = candidate[inside & todo], todo & ~inside
return targets.to(self.state.device)method expert
expert(target: Tensor, state: Tensor | None = None) -> TensorScripted pick-and-place actions (B, 4) that carry the cube to target (B, 2) and back off.
Motion is planned from the gripper position of state, by default the running episode's.
Source code in torch_world/envs/robot_cube.py
def expert(self, target: Tensor, state: Tensor | None = None) -> Tensor:
"""Scripted pick-and-place actions ``(B, 4)`` that carry the cube to ``target`` ``(B, 2)`` and back off.
Motion is planned from the gripper position of ``state``, by default the running episode's.
"""
s = self.state if state is None else state
ee, opening, cube = s[:, :3], s[:, 3], s[:, 4:7]
settled = torch.as_tensor(self.closed_for >= self.config.settle, device=s.device) if state is None else True
grasped = (opening < 0.5) & ((ee - cube).norm(dim=-1) < 2 * self.half) & settled
placed = ~grasped & ((cube[:, :2] - target).norm(dim=-1) < self.radius) & (cube[:, 2] < self.half + 0.005)
goal_xy = torch.where((grasped | placed)[:, None], target, cube[:, :2])
above = (ee[:, :2] - goal_xy).norm(dim=-1) < 0.15 * self.radius + 0.002
low = (ee[:, 2] - self.half).abs() < 0.005
down = above & ~placed
z = torch.where(down, torch.full_like(ee[:, 2], self.half), torch.full_like(ee[:, 2], self.hover))
xy = torch.where(placed[:, None], ee[:, :2], goal_xy)
move = ((torch.cat([xy, z[:, None]], -1) - ee) / self.max_step).clamp(-1, 1)
close = torch.where(grasped, ~(down & low), down & low & ~grasped)
return torch.cat([move, torch.where(close, -1.0, 1.0)[:, None]], dim=-1)method solve
solve(target: Tensor, steps: int) -> TensorRun the clean expert for steps; returns the final states, used as goals.
Source code in torch_world/envs/robot_cube.py
def solve(self, target: Tensor, steps: int) -> Tensor:
"""Run the clean expert for ``steps``; returns the final states, used as goals."""
for _ in range(steps):
self.step(self.expert(target))
return self.state.clone()method collect
collect(
num_steps: int,
noise: float = 0.04,
cameras: list[str] | None = None,
generator: torch.Generator | None = None,
every: int = 32,
) -> dictPlay data from the noisy expert, retargeted after every placement, as in OGBench's play datasets.
For "reach", the noisy expert moves the open gripper to a new random pose every every steps and holds it there, so the every steps from a multiple of every reach one pose, as a "reach" task does.
Returns pixels (B, T, 3, size, size) (or (B, T, V, 3, size, size) for a list of cameras), actions (B, T, 4) and states (B, T, 7); actions[:, t] is applied at states[:, t]. noise is the standard deviation added to the expert's actions.
Source code in torch_world/envs/robot_cube.py
def collect(
self,
num_steps: int,
noise: float = 0.04,
cameras: list[str] | None = None,
generator: torch.Generator | None = None,
every: int = 32,
) -> dict:
"""Play data from the noisy expert, retargeted after every placement, as in OGBench's ``play`` datasets.
For ``"reach"``, the noisy expert moves the open gripper to a new random pose every ``every`` steps and holds
it there, so the ``every`` steps from a multiple of ``every`` reach one pose, as a ``"reach"`` task does.
Returns ``pixels`` ``(B, T, 3, size, size)`` (or ``(B, T, V, 3, size, size)`` for a list of ``cameras``),
``actions`` ``(B, T, 4)`` and ``states`` ``(B, T, 7)``; ``actions[:, t]`` is applied at ``states[:, t]``.
``noise`` is the standard deviation added to the expert's actions.
"""
def observe():
if cameras is None:
return self.render()
return torch.stack([self.render(camera=c) for c in cameras], dim=1)
self.reset(generator=generator)
pixels, states, actions = [observe()], [self.state], []
reach = self.task == "reach"
target = self.reach_targets(generator) if reach else self.sample_targets(generator=generator)
for t in range(num_steps - 1):
n = torch.randn(self.batch_size, 4, generator=generator).to(self.state)
expert = self.scripted(torch.cat([target, self.state[:, 3:]], -1)) if reach else self.expert(target)
action = (expert + noise * n).clamp(-1, 1)
actions.append(action)
self.step(action)
pixels.append(observe())
states.append(self.state)
if reach:
target = self.reach_targets(generator) if (t + 1) % every == 0 else target
continue
done = _placed(
self.state, torch.cat([self.state[:, :4], target, self.state[:, 6:]], -1), self.radius, self.half
)
target = torch.where(done[:, None], self.sample_targets(generator=generator), target)
actions.append(torch.zeros_like(actions[-1]))
return {"pixels": torch.stack(pixels, 1), "actions": torch.stack(actions, 1), "states": torch.stack(states, 1)}function run_policy
run_policy(env, policy: Callable[[Tensor], Tensor], steps: int) -> TensorRun policy(observation) -> action in closed loop from the current state; returns states (B, steps + 1, ...).
Source code in torch_world/envs/utils.py
@torch.no_grad()
def run_policy(env, policy: Callable[[Tensor], Tensor], steps: int) -> Tensor:
"""Run ``policy(observation) -> action`` in closed loop from the current state; returns states ``(B, steps + 1, ...)``."""
obs, states = env.render(), [env.state]
for _ in range(steps):
obs = env.step(policy(obs))
states.append(env.state)
return torch.stack(states, dim=1)Registered benchmark tasks
class EnvSpec
EnvSpec(
id: str,
entry_point: str | Callable,
backend: str,
description: str,
tags: tuple[str, ...] = (),
kwargs: Mapping[str, Any] = dict(),
reference: str = "",
category: str = "",
)A versioned task recipe. Listing specs never imports optional simulators.
Source code in torch_world/envs/registry.py
@dataclass(frozen=True)
class EnvSpec:
"""A versioned task recipe. Listing specs never imports optional simulators."""
id: str
entry_point: str | Callable
backend: str
description: str
tags: tuple[str, ...] = ()
kwargs: Mapping[str, Any] = field(default_factory=dict)
reference: str = ""
category: str = ""
def __post_init__(self):
if not self.id or not self.backend or not self.description:
raise ValueError("id, backend and description are required")
if not callable(self.entry_point) and (not isinstance(self.entry_point, str) or ":" not in self.entry_point):
raise ValueError("entry_point must be callable or 'module:attribute'")
object.__setattr__(self, "kwargs", MappingProxyType(deepcopy(dict(self.kwargs))))
object.__setattr__(self, "tags", tuple(self.tags))function list_envs
list_envs(
*,
backend: str | None = None,
tag: str | None = None,
category: str | None = None,
) -> tuple[EnvSpec, ...]Sorted specs, optionally filtered by backend, a capability tag, and a category from CATEGORIES.
Source code in torch_world/envs/registry.py
def list_envs(
*, backend: str | None = None, tag: str | None = None, category: str | None = None
) -> tuple[EnvSpec, ...]:
"""Sorted specs, optionally filtered by backend, a capability tag, and a category from `CATEGORIES`."""
return tuple(
s
for _, s in sorted(_REGISTRY.items())
if (backend is None or s.backend == backend)
and (tag is None or tag in s.tags)
and (category is None or s.category == category)
)CATEGORIES maps each built-in category to its title, in display order: "puzzles" (Planning puzzles), "control" (Control), "navigation" (Navigation and locomotion), "manipulation" (Manipulation). Each EnvSpec.category holds one of these names; list_envs(category="control") selects that group.
function make
make(
id: str | EnvSpec | type[BenchmarkEnv | LegacyEnvironment], **overrides: Any
) -> BenchmarkEnvInstantiate only the selected backend. Constructor overrides win over defaults.
Source code in torch_world/envs/registry.py
def make(id: str | EnvSpec | type[BenchmarkEnv | LegacyEnvironment], **overrides: Any) -> BenchmarkEnv:
"""Instantiate only the selected backend. Constructor overrides win over defaults."""
spec = get_spec(id)
if isinstance(id, type) and issubclass(id, LegacyEnvironment):
return id(**overrides).as_benchmark()
factory = id if isinstance(id, type) else spec.entry_point
if isinstance(factory, str):
module, attr = factory.split(":", 1)
factory = getattr(import_module(module), attr)
settings = deepcopy({**spec.kwargs, **overrides})
env = factory(**settings)
if not hasattr(env, "settings"):
env.settings = constructor_settings(factory, settings)
env.spec = spec
return envfunction register_env
register_env(spec: EnvSpec) -> EnvSpecRegister a recipe explicitly; duplicate IDs are errors, never silent overrides.
Source code in torch_world/envs/registry.py
def register_env(spec: EnvSpec) -> EnvSpec:
"""Register a recipe explicitly; duplicate IDs are errors, never silent overrides."""
if spec.id in _REGISTRY:
raise ValueError(f"Environment {spec.id!r} is already registered")
_REGISTRY[spec.id] = spec
return specfunction register_task
register_task(
id: str, base: str, *, description: str, **overrides: Any
) -> EnvSpecCreate a task variant without copying an environment implementation.
Source code in torch_world/envs/registry.py
def register_task(id: str, base: str, *, description: str, **overrides: Any) -> EnvSpec:
"""Create a task variant without copying an environment implementation."""
spec = get_spec(base)
return register_env(replace(spec, id=id, description=description, kwargs={**spec.kwargs, **overrides}))class BenchmarkEnv
BenchmarkEnv(
batch_size=1,
size=None,
device=None,
max_episode_steps=200,
*,
quality="high",
render_size=None,
)Implement reset/step/render, state, action_dim and transition in a subclass.
Observations are batched tensors, either vectors or RGB pixels. Actions use [-1, 1]. Finished lanes are absorbing until explicit reset; no hidden autoreset. State is an observation snapshot, not necessarily a restorable simulator state.
Members
| Member | Description |
|---|---|
collect | Collect T aligned transitions, without crossing reset boundaries. |
show_env | Reset and display this world's first batch lane beside GT; leave it open. |
show_success | Display a verified successful episode GIF beside GT, optionally saving to path. |
reference_policy | Return a fresh reference controller after reset; override for custom tasks. |
render_target | GT success-condition observation, kept separate from measured episodes. |
render_frame | Presentation frame, independent of the model's observation resolution. |
render_goal_frame | GT presentation frame; never used as a surrogate model observation. |
close | Release simulator resources; subclasses may override. |
Source code in torch_world/envs/benchmark.py
class BenchmarkEnv:
"""Implement reset/step/render, state, action_dim and transition in a subclass.
Observations are batched tensors, either vectors or RGB pixels. Actions use
[-1, 1]. Finished lanes are absorbing until explicit reset; no hidden autoreset.
State is an observation snapshot, not necessarily a restorable simulator state.
"""
def __init__(
self, batch_size=1, size=None, device=None, max_episode_steps=200, *, quality="high", render_size=None
):
self.quality = quality
self.render_quality = resolve_quality(quality)
size = self.render_quality.observation_size if size is None else size
self.render_size = self.render_quality.render_size if render_size is None else render_size
if self.render_size < 1:
raise ValueError("render_size must be positive")
if batch_size < 1 or size < 1 or max_episode_steps < 1:
raise ValueError("batch_size, size and max_episode_steps must be positive")
self.batch_size, self.size = batch_size, size
self.device = torch.device(device or "cpu")
self.max_episode_steps = max_episode_steps
self._reset_episode()
def _reset_episode(self):
self.elapsed = torch.zeros(self.batch_size, dtype=torch.long, device=self.device)
zero = torch.zeros(self.batch_size, device=self.device)
self.transition = Transition(zero, zero.bool(), zero.bool())
def _action(self, action):
action = torch.as_tensor(action, dtype=torch.float32, device=self.device)
if action.shape != (self.batch_size, self.action_dim) or not torch.isfinite(action).all():
raise ValueError(f"Expected finite actions of shape {(self.batch_size, self.action_dim)}")
return action.clamp(-1, 1)
def collect(self, num_steps, generator=None):
"""Collect T aligned transitions, without crossing reset boundaries.
``observations`` and ``next_observations`` are (B,T,...); ``valid`` masks
padding after termination. ``states`` are pre-action snapshots. Unlike
legacy pixel-world collect, every action here has a next observation.
"""
if num_steps < 1:
raise ValueError("num_steps must be positive")
obs = self.reset(generator=generator)
data = {
k: []
for k in (
"observations",
"next_observations",
"states",
"actions",
"rewards",
"terminated",
"truncated",
"valid",
)
}
for _ in range(num_steps):
active = ~self.transition.done
action = (
torch.rand(
self.batch_size, self.action_dim, generator=generator, device=getattr(generator, "device", "cpu")
).to(self.device)
* 2
- 1
)
action[~active] = 0
data["observations"].append(obs.clone())
data["states"].append(self.state.clone())
obs = self.step(action)
for key, value in (
("next_observations", obs),
("actions", action),
("valid", active),
("rewards", self.transition.reward),
("terminated", self.transition.terminated),
("truncated", self.transition.truncated),
):
data[key].append(value.clone())
out = {key: torch.stack(value, 1) for key, value in data.items()}
if obs.ndim == 4:
out["pixels"] = out["observations"]
return out
def show_env(self, *, seed=7) -> None:
"""Reset and display this world's first batch lane beside GT; leave it open."""
from torch_world.benchmarks.visualization import show_env
show_env(self, seed=seed)
def show_success(self, *, policy=None, seed=7, steps=None, path=None) -> None:
"""Display a verified successful episode GIF beside GT, optionally saving to path."""
from torch_world.benchmarks.visualization import show_success
show_success(self, policy=policy, seed=seed, steps=steps, path=path)
def reference_policy(self):
"""Return a fresh reference controller after reset; override for custom tasks."""
from torch_world.envs.references import reference_policy
return reference_policy(self)
def render_target(self):
"""GT success-condition observation, kept separate from measured episodes."""
return self.render(self.goal)
def render_frame(self, state=None):
"""Presentation frame, independent of the model's observation resolution."""
renderer = getattr(self, "render", None)
return renderer(state) if renderer else (self.state if state is None else state).clone()
def render_goal_frame(self):
"""GT presentation frame; never used as a surrogate model observation."""
return self.render_target()
@property
def render_settings(self):
return {"quality": self.quality, "observation_size": self.size, "render_size": self.render_size}
def close(self):
"""Release simulator resources; subclasses may override."""
def __enter__(self):
return self
def __exit__(self, *args):
self.close()method collect
collect(num_steps, generator=None)Collect T aligned transitions, without crossing reset boundaries.
observations and next_observations are (B,T,...); valid masks padding after termination. states are pre-action snapshots. Unlike legacy pixel-world collect, every action here has a next observation.
Source code in torch_world/envs/benchmark.py
def collect(self, num_steps, generator=None):
"""Collect T aligned transitions, without crossing reset boundaries.
``observations`` and ``next_observations`` are (B,T,...); ``valid`` masks
padding after termination. ``states`` are pre-action snapshots. Unlike
legacy pixel-world collect, every action here has a next observation.
"""
if num_steps < 1:
raise ValueError("num_steps must be positive")
obs = self.reset(generator=generator)
data = {
k: []
for k in (
"observations",
"next_observations",
"states",
"actions",
"rewards",
"terminated",
"truncated",
"valid",
)
}
for _ in range(num_steps):
active = ~self.transition.done
action = (
torch.rand(
self.batch_size, self.action_dim, generator=generator, device=getattr(generator, "device", "cpu")
).to(self.device)
* 2
- 1
)
action[~active] = 0
data["observations"].append(obs.clone())
data["states"].append(self.state.clone())
obs = self.step(action)
for key, value in (
("next_observations", obs),
("actions", action),
("valid", active),
("rewards", self.transition.reward),
("terminated", self.transition.terminated),
("truncated", self.transition.truncated),
):
data[key].append(value.clone())
out = {key: torch.stack(value, 1) for key, value in data.items()}
if obs.ndim == 4:
out["pixels"] = out["observations"]
return outmethod show_env
show_env(*, seed=7) -> NoneReset and display this world's first batch lane beside GT; leave it open.
Source code in torch_world/envs/benchmark.py
def show_env(self, *, seed=7) -> None:
"""Reset and display this world's first batch lane beside GT; leave it open."""
from torch_world.benchmarks.visualization import show_env
show_env(self, seed=seed)method show_success
show_success(*, policy=None, seed=7, steps=None, path=None) -> NoneDisplay a verified successful episode GIF beside GT, optionally saving to path.
Source code in torch_world/envs/benchmark.py
def show_success(self, *, policy=None, seed=7, steps=None, path=None) -> None:
"""Display a verified successful episode GIF beside GT, optionally saving to path."""
from torch_world.benchmarks.visualization import show_success
show_success(self, policy=policy, seed=seed, steps=steps, path=path)method reference_policy
reference_policy()Return a fresh reference controller after reset; override for custom tasks.
Source code in torch_world/envs/benchmark.py
def reference_policy(self):
"""Return a fresh reference controller after reset; override for custom tasks."""
from torch_world.envs.references import reference_policy
return reference_policy(self)method render_target
render_target()GT success-condition observation, kept separate from measured episodes.
Source code in torch_world/envs/benchmark.py
def render_target(self):
"""GT success-condition observation, kept separate from measured episodes."""
return self.render(self.goal)method render_frame
render_frame(state=None)Presentation frame, independent of the model's observation resolution.
Source code in torch_world/envs/benchmark.py
def render_frame(self, state=None):
"""Presentation frame, independent of the model's observation resolution."""
renderer = getattr(self, "render", None)
return renderer(state) if renderer else (self.state if state is None else state).clone()method render_goal_frame
render_goal_frame()GT presentation frame; never used as a surrogate model observation.
Source code in torch_world/envs/benchmark.py
def render_goal_frame(self):
"""GT presentation frame; never used as a surrogate model observation."""
return self.render_target()method close
close()Release simulator resources; subclasses may override.
Source code in torch_world/envs/benchmark.py
def close(self):
"""Release simulator resources; subclasses may override."""class Transition
Transition(
reward: Tensor,
terminated: Tensor,
truncated: Tensor,
success: Tensor | None = None,
info: Any = None,
)Outcome of the last action, including separate termination and time limits.
success=None means the task has no success signal (e.g. locomotion); it must never be interpreted as failure. All tensors have shape (B,).
Source code in torch_world/envs/benchmark.py
@dataclass
class Transition:
"""Outcome of the last action, including separate termination and time limits.
``success=None`` means the task has no success signal (e.g. locomotion);
it must never be interpreted as failure. All tensors have shape ``(B,)``.
"""
reward: Tensor
terminated: Tensor
truncated: Tensor
success: Tensor | None = None
info: Any = None
@property
def done(self):
return self.terminated | self.truncatedfunction run_experiment
run_experiment(
env_id,
*,
model_factory=lewm_baseline,
planner_factory=cem_baseline,
seed=7,
updates=400,
samples=2048,
evaluation_seeds=4,
evaluation_steps=60,
device=None,
env_kwargs=None,
output_dir=None,
save_gifs=True,
model_config=None,
)Train and compare a swappable WorldModel with a random-action control.
Pass a world instance, named task class, EnvSpec, or registered string ID. Instances are reset during training/evaluation and remain open afterward. Classes/recipes are constructed and closed by the runner using env_kwargs.
model_factory(observation_shape, action_dim) returns a WorldModel with forward(observations, actions)["loss"], encode, predict, rollout and cost. This one-step validation protocol requires history=1. Model and planner factories are independent of the environment, split, and scoring code.
Puzzle data splits by starting state; other tasks split by collection seed. Goal-renderable tasks use goal MPC, scored by success(state, goal) when the task defines distance and by its success signal otherwise. Others fit a frozen-latent reward head and plan predicted rewards, reporting actual environment returns. Isaac's default policy vectors are a state-based experiment, not a pixel result.
Source code in torch_world/benchmarks/experiment.py
def run_experiment(
env_id,
*,
model_factory=lewm_baseline,
planner_factory=cem_baseline,
seed=7,
updates=400,
samples=2048,
evaluation_seeds=4,
evaluation_steps=60,
device=None,
env_kwargs=None,
output_dir=None,
save_gifs=True,
model_config=None,
):
"""Train and compare a swappable WorldModel with a random-action control.
Pass a world instance, named task class, EnvSpec, or registered string ID.
Instances are reset during training/evaluation and remain open afterward.
Classes/recipes are constructed and closed by the runner using env_kwargs.
``model_factory(observation_shape, action_dim)`` returns a WorldModel with
forward(observations, actions)["loss"], encode, predict, rollout and cost.
This one-step validation protocol requires history=1. Model and planner
factories are independent of the environment, split, and scoring code.
Puzzle data splits by starting state; other tasks split by collection seed.
Goal-renderable tasks use goal MPC, scored by ``success(state, goal)`` when the
task defines ``distance`` and by its success signal otherwise. Others fit a frozen-latent reward head
and plan predicted rewards, reporting actual environment returns. Isaac's
default policy vectors are a state-based experiment, not a pixel result.
"""
if samples < 2 or updates < 0 or evaluation_seeds < 1 or evaluation_steps < 1:
raise ValueError("Invalid experiment sample, update or evaluation budget")
environment = env_id
spec = get_spec(environment)
env_id = spec.id
torch.manual_seed(seed)
device = device or ("cuda" if torch.cuda.is_available() else "cpu")
generator = torch.Generator().manual_seed(seed)
kwargs = dict(env_kwargs or {})
if not is_environment(environment):
if spec.backend == "isaaclab":
kwargs.setdefault("device", device)
elif spec.backend == "mujoco":
kwargs.setdefault("observation", "rgb")
with environment_scope(environment, **kwargs) as env:
spec = get_spec(env)
env_id = spec.id
tic = time.perf_counter()
train, test = (
_puzzle_data(env, samples, generator) if hasattr(env, "advance") else _collected_data(env, samples, seed)
)
model = model_factory(tuple(train[0].shape[2:]), env.action_dim).to(device)
if getattr(model, "history", 1) != 1:
raise ValueError("This one-step protocol requires a model configured with history=1")
model_name = type(model).__name__
planner = planner_factory(env.action_dim)
planned_name = model_name + " + " + type(planner).__name__
experiment_config = {
"protocol": "one-step-world-model-v2",
"environment": env_id,
"backend": spec.backend,
"environment_settings": configuration(env.settings),
"render_settings": configuration(env.render_settings),
"model_factory": configuration(model_factory),
"model_config": configuration(model_config or {}),
"model_architecture": repr(model),
"planner_factory": configuration(planner_factory),
"planner_settings": configuration(vars(planner)),
"seed": seed,
"updates": updates,
"samples": samples,
"batch_size": 64,
"optimizer": {"name": "AdamW", "lr": 3e-4, "weight_decay": 0.01},
"evaluation_seeds": [seed + 1000 + i for i in range(evaluation_seeds)],
"evaluation_steps": evaluation_steps,
"device": str(device),
"data_split": "disjoint-start-states" if hasattr(env, "advance") else "disjoint-collection-seeds",
}
optimizer = torch.optim.AdamW(model.parameters(), lr=3e-4)
losses = []
model.train()
for _ in range(updates):
idx = torch.randint(len(train[0]), (64,), generator=generator)
output = model(train[0][idx].to(device), train[1][idx].to(device))
if not torch.isfinite(output["loss"]):
raise RuntimeError("Nonfinite model loss")
optimizer.zero_grad()
output["loss"].backward()
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 10)
if not torch.isfinite(norm):
raise RuntimeError("Nonfinite model gradient")
optimizer.step()
losses.append(float(output["loss"].detach()))
model.eval()
with torch.no_grad():
pixels, actions = test[0][:512].to(device), test[1][:512].to(device)
z = model.encode(pixels)
prediction = model.predict(z[:, :1], actions[:, :1])
pred_mse = float((prediction[:, 0] - z[:, 1]).square().mean())
persistence_mse = float((z[:, 0] - z[:, 1]).square().mean())
spread = float(z.flatten(0, 1).std(0).mean())
result = {
"config": experiment_config,
"env_id": env_id,
"model": model_name,
"observation": "pixels" if train[0].ndim == 5 else "state",
"planner_policy": planned_name,
"seed": seed,
"updates": updates,
"device": str(device),
"train_pairs": len(train[0]),
"test_pairs": len(test[0]),
"losses": losses,
"heldout_latent_mse": pred_mse,
"persistence_latent_mse": persistence_mse,
"latent_std": spread,
"torch_version": torch.__version__,
"evaluation": {},
}
env.reset(seed=seed)
from torch_world.benchmarks.visualization import capture_frame
result["target"] = capture_frame(env, target=True)
result["gt_label"] = getattr(env, "gt_label", "GT")
# A goal observation is planned toward; without `distance`, the simulator's success signal scores it.
goal_planning = hasattr(env, "goal")
goal_scoring = goal_planning and hasattr(env, "distance")
if goal_planning:
with torch.no_grad():
target = model.encode(env.render(env.goal).to(device)[:, None])[:, 0]
objective = model
else:
# Same reward head protocol for every user-supplied model.
reward_head = nn.Sequential(nn.Linear(z[:, 1].flatten(1).shape[-1], 64), nn.GELU(), nn.Linear(64, 1)).to(
device
)
reward_optimizer = torch.optim.AdamW(reward_head.parameters(), lr=1e-3)
for _ in range(max(updates, 1)):
idx = torch.randint(len(train[0]), (64,), generator=generator)
with torch.no_grad():
encoded = model.encode(train[0][idx, 1:2].to(device))[:, 0].flatten(1)
reward_loss = (reward_head(encoded).squeeze(-1) - train[2][idx].to(device)).square().mean()
reward_optimizer.zero_grad()
reward_loss.backward()
reward_optimizer.step()
reward_head.eval()
with torch.no_grad():
result["heldout_reward_mse"] = float(
(reward_head(z[:, 1].flatten(1)).squeeze(-1) - test[2][: len(z)].to(device)).square().mean()
)
objective = _RewardObjective(model, reward_head)
# Score every imagined step instead of postponing reward to the horizon.
if isinstance(planner, CEM):
planner.objective = "path"
target = torch.zeros(env.batch_size, device=device)
def random_policy(obs):
return torch.rand(env.batch_size, env.action_dim, device=env.device) * 2 - 1
def planned_policy(obs):
return planner(objective, model.encode(obs.to(device)[:, None]), target)[:, 0].to(env.device)
# Record the effective objective, including reward-planning adjustments.
experiment_config["planner_settings"] = configuration(vars(planner))
for name, policy in (("random", random_policy), (planned_name, planned_policy)):
scores, video = _evaluate_policy(
env,
policy,
experiment_config["evaluation_seeds"],
evaluation_steps,
goal_scoring=goal_scoring,
)
result["evaluation"][name] = scores
result[name + " frames"] = video
result["seconds"] = time.perf_counter() - tic
if output_dir is not None:
result["run_dir"] = str(save_run(result, output_dir, gifs=save_gifs))
return resultfunction save_run
save_run(result, root, *, gifs=True)Save one immutable run and return its directory; never overwrite another run.
manifest.json is written last, marking a complete run. Aggregation ignores interrupted directories. JSON contains only scalar/list metadata; episode tensors are separate .pt files loadable with weights_only=True.
Source code in torch_world/benchmarks/artifacts.py
def save_run(result, root, *, gifs=True):
"""Save one immutable run and return its directory; never overwrite another run.
``manifest.json`` is written last, marking a complete run. Aggregation ignores
interrupted directories. JSON contains only scalar/list metadata; episode
tensors are separate ``.pt`` files loadable with ``weights_only=True``.
"""
stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S%fZ")
run_id = f"{stamp}-{uuid.uuid4().hex[:8]}"
folder = Path(root) / _slug(result["env_id"]) / _slug(result["model"]) / run_id
folder.mkdir(parents=True, exist_ok=False)
config = configuration(result["config"])
config_text = json.dumps(config, indent=2, sort_keys=True, allow_nan=False) + "\n"
(folder / "config.json").write_text(config_text)
metrics = {
k: v
for k, v in result.items()
if k not in ("config", "losses", "run_dir", "target") and not k.endswith(" frames")
}
(folder / "metrics.json").write_text(json.dumps(metrics, indent=2, sort_keys=True, allow_nan=False) + "\n")
with (folder / "training.csv").open("w", newline="") as stream:
writer = csv.writer(stream)
writer.writerow(["update", "loss"])
writer.writerows(enumerate(result["losses"], 1))
episodes = {k.removesuffix(" frames"): v.cpu() for k, v in result.items() if k.endswith(" frames")}
if episodes:
torch.save(episodes, folder / "episodes.pt")
if "target" in result:
torch.save(result["target"].cpu(), folder / "target.pt")
if gifs:
from torch_world.benchmarks.visualization import episode_gif
for policy, frames in episodes.items():
if frames.ndim == 4 and frames.shape[1] == 3:
successes = result["evaluation"].get(policy, {}).get("successes")
success = None if successes is None else bool(successes[0])
episode_gif(
frames,
result["target"],
title=policy,
success=success,
fps=4,
stride=2,
target_title=result.get("gt_label", "GT"),
).save(folder / f"{_slug(policy)}.gif")
packages = {}
for name in (
"torch-world",
"torch",
"mujoco",
"gymnasium",
"gymnasium-robotics",
"newton",
"warp-lang",
"isaaclab",
):
try:
packages[name] = version(name)
except PackageNotFoundError:
pass
files = sorted(p for p in folder.iterdir() if p.is_file())
manifest = {
"schema_version": SCHEMA_VERSION,
"library_source_sha256": library_fingerprint(),
"run_id": run_id,
"created_utc": stamp,
"environment": result["env_id"],
"model": result["model"],
"seed": result["seed"],
"config_sha256": hashlib.sha256(config_text.encode()).hexdigest(),
"packages": packages,
"files": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in files},
}
(folder / "manifest.json").write_text(json.dumps(manifest, indent=2, sort_keys=True) + "\n")
return folderfunction summarize_runs
summarize_runs(root)One row per completed run/policy; do not pool incompatible environments or metrics.
Repeated seeds remain separate rows. Consumers choose aggregation by environment, model, library source hash, protocol/config hash and seed, avoiding accidental pooling across hardware or task revisions.
Source code in torch_world/benchmarks/artifacts.py
def summarize_runs(root):
"""One row per completed run/policy; do not pool incompatible environments or metrics.
Repeated seeds remain separate rows. Consumers choose aggregation by
environment, model, library source hash, protocol/config hash and seed,
avoiding accidental pooling across hardware or task revisions.
"""
rows = []
for path in sorted(Path(root).rglob("manifest.json")):
manifest = _verify_manifest(path)
metrics = json.loads((path.parent / "metrics.json").read_text())
config = json.loads((path.parent / "config.json").read_text())
render = config.get("render_settings", {})
for policy, scores in metrics["evaluation"].items():
rows.append(
{
"run_id": manifest["run_id"],
"environment": manifest["environment"],
"model": manifest["model"],
"policy": policy,
"seed": manifest["seed"],
"config_sha256": manifest["config_sha256"],
"library_source_sha256": manifest["library_source_sha256"],
"observation": metrics["observation"],
"quality": render.get("quality"),
"observation_size": render.get("observation_size"),
"render_size": render.get("render_size"),
"camera": config.get("environment_settings", {}).get("camera"),
"success_rate": scores.get("success_rate"),
"mean_return": scores.get("mean_return"),
"mean_final_distance": (
sum(scores["final_distances"]) / len(scores["final_distances"])
if "final_distances" in scores
else None
),
"heldout_latent_mse": metrics["heldout_latent_mse"],
"persistence_latent_mse": metrics["persistence_latent_mse"],
"run_dir": str(path.parent),
}
)
return rowsfunction write_summary
write_summary(root, destination)Write a tidy CSV of completed run/policy rows; return the rows as Python dicts.
Source code in torch_world/benchmarks/artifacts.py
def write_summary(root, destination):
"""Write a tidy CSV of completed run/policy rows; return the rows as Python dicts."""
rows = summarize_runs(root)
destination = Path(destination)
destination.parent.mkdir(parents=True, exist_ok=True)
with destination.open("w", newline="") as stream:
if rows:
writer = csv.DictWriter(stream, fieldnames=list(rows[0]))
writer.writeheader()
writer.writerows(rows)
return rowsclass Scene
Scene(
bodies: str,
actuators: str,
initial: tuple[float, ...],
target: tuple[float, ...],
indices: tuple[int, ...],
tolerance: tuple[float, ...],
angular: tuple[int, ...] = (),
gravity: str = "0 0 -9.81",
velocity_tolerance: float = 0.5,
follow_camera: bool = False,
directional_light: bool = False,
attachments: tuple[MjcfAttachment, ...] = (),
success_bounds: tuple[tuple[int, float, float], ...] = (),
)Complete task specification, with joint-coordinate targets and tolerances.
Source code in torch_world/envs/physics_scenes.py
@dataclass(frozen=True)
class Scene:
"""Complete task specification, with joint-coordinate targets and tolerances."""
bodies: str
actuators: str
initial: tuple[float, ...]
target: tuple[float, ...]
indices: tuple[int, ...]
tolerance: tuple[float, ...]
angular: tuple[int, ...] = ()
gravity: str = "0 0 -9.81"
velocity_tolerance: float = 0.5
follow_camera: bool = False
directional_light: bool = False
attachments: tuple[MjcfAttachment, ...] = ()
success_bounds: tuple[tuple[int, float, float], ...] = ()
def __post_init__(self):
if not self.initial or len(self.initial) != len(self.target):
raise ValueError("initial and target must have equal, nonzero coordinate counts")
if not self.indices or len(self.indices) != len(self.tolerance):
raise ValueError("Each scored coordinate needs a tolerance")
if any(i < 0 or i >= len(self.initial) for i in self.indices):
raise ValueError("Scored coordinates must index the scene configuration")
if any(t <= 0 for t in self.tolerance) or self.velocity_tolerance <= 0:
raise ValueError("Success tolerances must be positive")
if any(i < 0 or i >= len(self.initial) or lo >= hi for i, lo, hi in self.success_bounds):
raise ValueError("Success bounds need valid coordinate indices and increasing limits")
def xml(self) -> str:
xml = f'''<mujoco model="torch_world_task">
<compiler angle="radian"/><option timestep="0.002" gravity="{self.gravity}" integrator="implicitfast"/>
<default><joint damping="0.1" armature="0.01"/><geom friction="0.7 0.01 0.001" density="500" rgba="0.2 0.5 0.75 1"/>
<motor ctrllimited="true" ctrlrange="-1 1"/><position ctrllimited="true"/></default>
<asset>
<texture type="skybox" builtin="gradient" rgb1=".85 .9 .96" rgb2=".98 .99 1" width="512" height="3072"/>
<texture name="floor" type="2d" builtin="checker" rgb1=".87 .89 .91" rgb2=".94 .95 .96" width="512" height="512"/>
<material name="floor" texture="floor" texrepeat="8 8" reflectance=".08"/>
</asset>
<visual><rgba haze=".93 .95 .98 1"/><map znear=".01"/></visual>
<worldbody><light directional="{str(self.directional_light).lower()}" pos="-2 -3 5" dir=".3 .3 -1" diffuse=".6 .6 .6"/>
<light directional="{str(self.directional_light).lower()}" pos="2 1 3" dir="-.3 -.2 -1" diffuse=".2 .2 .2" castshadow="false"/>
<geom type="plane" size="5 5 .1" friction=".01 .001 .001" material="floor" rgba="1 1 1 1"/>
{self.bodies}</worldbody>
<actuator>{self.actuators}</actuator></mujoco>'''
if not self.attachments:
return xml
root = ET.fromstring(xml)
for attachment in self.attachments:
attachment.attach(root)
return ET.tostring(root, encoding="unicode")
def assets(self) -> dict[str, bytes]:
"""Binary assets for MuJoCo's virtual filesystem, including wheel installs."""
return {name: data for attachment in self.attachments for name, data in attachment.assets().items()}method assets
assets() -> dict[str, bytes]Binary assets for MuJoCo's virtual filesystem, including wheel installs.
Source code in torch_world/envs/physics_scenes.py
def assets(self) -> dict[str, bytes]:
"""Binary assets for MuJoCo's virtual filesystem, including wheel installs."""
return {name: data for attachment in self.attachments for name, data in attachment.assets().items()}class OGBench
OGBench(
name,
*,
task_id=1,
batch_size=1,
size=None,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
)An OGBench <https://github.com/seohongpark/ogbench>_ task, by its dataset name.
name is any OGBench dataset name, such as "cube-single-play-v0", "visual-antmaze-medium-navigate-v0" or "scene-play-singletask-task2-v0"; the dataset type only selects the data, not the environment.
Goal-conditioned names evaluate one of the five evaluation tasks, task_id. The goal is an observation, goal, so render(goal) returns it and planners reach its embedding; the episode ends when OGBench reports success. Single-task names have no goal and keep OGBench's rewards, from -num_subtasks up to 0.
Observations are OGBench's state vectors (B, D), or visual- RGB images (B, 3, size, size) in [0, 1], 64 x 64 by default as in the OGBench datasets. state is the observation: OGBench defines goals and success in the simulator, so states cannot be restored or scored from tensors.
OGBench also draws from NumPy's global generator, so each lane keeps its own global stream and seeded resets are reproducible. One exception is upstream: manipulation goals settle under two random actions from an unseeded action space, so the arm in the goal varies between resets; the object targets, which define success, do not. Discrete-action powderworld tasks are not supported.
Members
| Member | Description |
|---|---|
render | The current observation, or state itself: OGBench states and goals are observations. |
render_frame | Upstream camera frames (B, 3, H, W) as uint8, from the simulator's current state. |
render_goal_frame | OGBench's rendering of the goal state at reset, from the same camera as render_frame. |
Source code in torch_world/envs/ogbench.py
class OGBench(BenchmarkEnv):
"""An `OGBench <https://github.com/seohongpark/ogbench>`_ task, by its dataset name.
``name`` is any OGBench dataset name, such as ``"cube-single-play-v0"``, ``"visual-antmaze-medium-navigate-v0"``
or ``"scene-play-singletask-task2-v0"``; the dataset type only selects the data, not the environment.
Goal-conditioned names evaluate one of the five evaluation tasks, ``task_id``. The goal is an observation,
``goal``, so ``render(goal)`` returns it and planners reach its embedding; the episode ends when OGBench reports
``success``. Single-task names have no ``goal`` and keep OGBench's rewards, from ``-num_subtasks`` up to 0.
Observations are OGBench's state vectors ``(B, D)``, or ``visual-`` RGB images ``(B, 3, size, size)`` in [0, 1],
64 x 64 by default as in the OGBench datasets. ``state`` is the observation: OGBench defines goals and success in
the simulator, so states cannot be restored or scored from tensors.
OGBench also draws from NumPy's global generator, so each lane keeps its own global stream and seeded resets are
reproducible. One exception is upstream: manipulation goals settle under two random actions from an unseeded
action space, so the arm in the goal varies between resets; the object targets, which define success, do not.
Discrete-action powderworld tasks are not supported.
"""
def __init__(
self,
name,
*,
task_id=1,
batch_size=1,
size=None,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
):
try:
import ogbench
except ImportError as exc:
raise ImportError("Install OGBench with: pip install 'torch-world[ogbench]'") from exc
self.name, self.visual = name, name.startswith("visual-")
self.goal_conditioned = "-singletask" not in name
if self.goal_conditioned and task_id not in range(1, 6):
raise ValueError("task_id must be one of OGBench's evaluation tasks, 1 to 5")
if not self.goal_conditioned and task_id != 1:
raise ValueError("Single-task names fix the task; select it in the name, e.g. '-singletask-task2-v0'")
self.task_id = task_id
self.settings = {
"name": name,
"task_id": task_id,
"batch_size": batch_size,
"size": size,
"quality": quality,
"render_size": render_size,
"max_episode_steps": max_episode_steps,
**env_kwargs,
}
try:
self.spec = get_spec(f"OGBench/{name}")
except KeyError: # an OGBench task outside the catalog carries its own spec
self.spec = EnvSpec(
f"OGBench/{name}",
"torch_world.envs.ogbench:OGBench",
"ogbench",
f"OGBench {name}",
("ogbench", "goal") if self.goal_conditioned else ("ogbench",),
{"name": name},
"https://github.com/seohongpark/ogbench",
)
size = 64 if size is None and self.visual else size
# The episode limit comes from the upstream registration, read once the environments exist.
super().__init__(batch_size, size, device, max_episode_steps or 1, quality=quality, render_size=render_size)
# Visual tasks observe through the camera at `size`; state tasks only render presentation frames.
resolution = self.size if self.visual else self.render_size
env_kwargs = {"width": resolution, "height": resolution, **env_kwargs}
if max_episode_steps is not None:
env_kwargs["max_episode_steps"] = max_episode_steps
self.envs = []
try:
for _ in range(batch_size):
self.envs.append(ogbench.make_env_and_datasets(name, env_only=True, **env_kwargs))
except Exception:
self.close()
raise
space = self.envs[0].action_space
if not hasattr(space, "low"):
self.close()
raise ValueError(f"{name} has discrete actions; OGBench adapters support continuous control")
self._low, self._high = (torch.as_tensor(b, dtype=torch.float32) for b in (space.low, space.high))
self.action_dim = space.shape[0]
self.max_episode_steps = self.envs[0].spec.max_episode_steps
self.observation_shape = (3, self.size, self.size) if self.visual else self.envs[0].observation_space.shape
self.state_dim = math.prod(self.observation_shape)
self._streams = NumpyStreams(batch_size)
self._goal_frame = None
self._reset_episode()
def _observation(self, observations):
obs = torch.as_tensor(np.stack(observations), device=self.device)
return obs.permute(0, 3, 1, 2).float() / 255 if self.visual else obs.float()
@staticmethod
def _frame(images):
return torch.as_tensor(np.stack(images)).permute(0, 3, 1, 2).contiguous()
def reset(self, state=None, *, seed=None, generator=None):
if state is not None:
raise ValueError("OGBench observations are not simulator checkpoints; use reset(seed=...)")
if seed is not None and generator is not None:
raise ValueError("Pass seed or generator, not both")
seed = seed_from_generator(generator) if seed is None else seed
self._reset_episode()
options = {"render_goal": True}
if self.goal_conditioned:
options["task_id"] = self.task_id
observations, goals, frames = [], [], []
for lane, env in enumerate(self.envs):
self._streams.seed(lane, seed + lane)
obs, info = self._streams.call(lane, env.reset, seed=seed + lane, options=options)
observations.append(obs)
goals.append(info.get("goal"))
frames.append(info.get("goal_rendered"))
self._obs = self._observation(observations)
self.state = self._obs.clone()
self._success = torch.zeros(self.batch_size, dtype=torch.bool, device=self.device)
self._goal_frame = self._frame(frames) if all(f is not None for f in frames) else None
if self.goal_conditioned:
self.goal = self._observation(goals)
return self.render()
def step(self, action):
action = self._action(action)
active = ~self.transition.done
action[~active] = 0
action = (self._low + (action.cpu() + 1) / 2 * (self._high - self._low)).numpy()
obs, reward = self._obs.clone(), torch.zeros(self.batch_size, device=self.device)
terminated, truncated = torch.zeros_like(active), torch.zeros_like(active)
success = self._success.clone()
for lane in active.nonzero().flatten().tolist():
observation, r, term, trunc, info = self._streams.call(lane, self.envs[lane].step, action[lane])
obs[lane] = self._observation([observation])[0]
reward[lane], terminated[lane], truncated[lane] = float(r), bool(term), bool(trunc)
success[lane] = bool(info["success"])
self._obs, self.state, self._success = obs, obs.clone(), success
self.elapsed += active
self.transition = Transition(
reward,
self.transition.terminated | terminated,
self.transition.truncated | truncated | ((self.elapsed >= self.max_episode_steps) & active),
success.clone(),
)
return self.render()
def render(self, state=None):
"""The current observation, or ``state`` itself: OGBench states and goals are observations."""
if state is None:
return self._obs.clone()
state = torch.as_tensor(state, device=self.device)
if state.shape[1:] != self.observation_shape:
raise ValueError(f"Expected observations of shape (B, {', '.join(map(str, self.observation_shape))})")
return state.clone()
def render_frame(self, state=None):
"""Upstream camera frames ``(B, 3, H, W)`` as uint8, from the simulator's current state."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by OGBench")
return self._frame([self._streams.call(lane, env.render) for lane, env in enumerate(self.envs)])
def render_goal_frame(self):
"""OGBench's rendering of the goal state at reset, from the same camera as ``render_frame``."""
return self._goal_frame.clone() if self._goal_frame is not None else self.render_frame()
def close(self):
for env in getattr(self, "envs", ()):
env.close()
self.envs = []method render
render(state=None)The current observation, or state itself: OGBench states and goals are observations.
Source code in torch_world/envs/ogbench.py
def render(self, state=None):
"""The current observation, or ``state`` itself: OGBench states and goals are observations."""
if state is None:
return self._obs.clone()
state = torch.as_tensor(state, device=self.device)
if state.shape[1:] != self.observation_shape:
raise ValueError(f"Expected observations of shape (B, {', '.join(map(str, self.observation_shape))})")
return state.clone()method render_frame
render_frame(state=None)Upstream camera frames (B, 3, H, W) as uint8, from the simulator's current state.
Source code in torch_world/envs/ogbench.py
def render_frame(self, state=None):
"""Upstream camera frames ``(B, 3, H, W)`` as uint8, from the simulator's current state."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by OGBench")
return self._frame([self._streams.call(lane, env.render) for lane, env in enumerate(self.envs)])method render_goal_frame
render_goal_frame()OGBench's rendering of the goal state at reset, from the same camera as render_frame.
Source code in torch_world/envs/ogbench.py
def render_goal_frame(self):
"""OGBench's rendering of the goal state at reset, from the same camera as ``render_frame``."""
return self._goal_frame.clone() if self._goal_frame is not None else self.render_frame()class DMControl
DMControl(
name,
*,
batch_size=1,
observation="state",
size=None,
camera=None,
action_repeat=1,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**task_kwargs,
)A DeepMind Control Suite <https://github.com/google-deepmind/dm_control>_ task, by "domain-task" name.
name is any suite task, such as "cheetah-run", "walker-walk" or "ball_in_cup-catch". Observations are the suite's observation dictionary flattened into one vector (B, D), or with observation="rgb" images (B, 3, size, size) in [0, 1] from camera, 64 x 64 by default as in DreamerV3 and TD-MPC2. action_repeat applies each action for that many control steps and sums their rewards, which divides the 1,000-step episode limit.
Rewards are the suite's, in [0, 1] per control step. The suite has no success condition, so transition.success is None; episodes end at the time limit. **task_kwargs go to the task, such as time_limit; its random seed is set by reset(seed=...), seed + lane per lane.
Source code in torch_world/envs/dmcontrol.py
class DMControl(MujocoLanes):
"""A `DeepMind Control Suite <https://github.com/google-deepmind/dm_control>`_ task, by ``"domain-task"`` name.
``name`` is any suite task, such as ``"cheetah-run"``, ``"walker-walk"`` or ``"ball_in_cup-catch"``.
Observations are the suite's observation dictionary flattened into one vector ``(B, D)``, or with
``observation="rgb"`` images ``(B, 3, size, size)`` in [0, 1] from ``camera``, 64 x 64 by default as in DreamerV3
and TD-MPC2. ``action_repeat`` applies each action for that many control steps and sums their rewards, which
divides the 1,000-step episode limit.
Rewards are the suite's, in [0, 1] per control step. The suite has no success condition, so
``transition.success`` is ``None``; episodes end at the time limit. ``**task_kwargs`` go to the task, such as
``time_limit``; its ``random`` seed is set by ``reset(seed=...)``, ``seed + lane`` per lane.
"""
suite = "DMControl"
has_success = False
def __init__(
self,
name,
*,
batch_size=1,
observation="state",
size=None,
camera=None,
action_repeat=1,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**task_kwargs,
):
domain, _, task = name.partition("-")
if action_repeat < 1:
raise ValueError("action_repeat must be positive")
self.name, self.action_repeat = name, action_repeat
self.settings = {
"name": name,
"batch_size": batch_size,
"observation": observation,
"size": size,
"camera": camera,
"action_repeat": action_repeat,
"quality": quality,
"render_size": render_size,
"max_episode_steps": max_episode_steps,
**task_kwargs,
}
self.spec = suite_spec(
f"DMControl/{name}",
"torch_world.envs.dmcontrol:DMControl",
"dmcontrol",
("dmcontrol",),
{"name": name},
"https://github.com/google-deepmind/dm_control",
)
camera = CAMERAS.get(domain, 0) if camera is None else camera
size = 64 if size is None and observation == "rgb" else size
super().__init__(
batch_size, size, device, observation=observation, camera=camera, quality=quality, render_size=render_size
)
try:
from dm_control import suite
except ImportError as exc:
raise ImportError("Install the DeepMind Control Suite with: pip install 'torch-world[dmcontrol]'") from exc
if (domain, task) not in suite.ALL_TASKS:
raise ValueError(f"Unknown DMControl task {name!r}; names are 'domain-task', such as 'cheetah-run'")
self._build(lambda: suite.load(domain, task, task_kwargs={"random": 0, **task_kwargs}))
spec = self.envs[0].action_spec()
self._bounds(spec.minimum, spec.maximum)
steps = self.envs[0]._step_limit
self.max_episode_steps = max_episode_steps or int(np.ceil(steps / action_repeat))
self.reset(seed=0)
def _physics(self, lane):
physics = self.envs[lane].physics
return physics.model.ptr, physics.data.ptr
@staticmethod
def _vector(observation):
return np.concatenate([np.asarray(value, dtype=np.float32).ravel() for value in observation.values()])
def _reset_lane(self, lane, seed):
env = self.envs[lane]
env.task._random = np.random.RandomState(seed) # the suite draws initial states only from the task's stream
return self._vector(env.reset().observation)
def _step_lane(self, lane, action):
reward = 0.0
for _ in range(self.action_repeat):
step = self.envs[lane].step(action)
reward += step.reward or 0.0
if step.last():
break
# A terminal discount of 0 is a task's own termination; otherwise the episode reached its time limit.
terminated = step.last() and step.discount == 0
return self._vector(step.observation), reward, terminated, step.last() and not terminated, Noneclass MetaWorld
MetaWorld(
name,
*,
batch_size=1,
observation="state",
size=None,
camera="corner2",
terminate_on_success=True,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
)A Meta-World <https://github.com/Farama-Foundation/Metaworld>_ v3 task with a Sawyer arm, by name.
name is any of the 50 v3 tasks, such as "reach-v3", "pick-place-v3" or "door-open-v3". Each reset samples a new object and goal placement, as Meta-World's MT1 does, from the lane's own generator, so reset(seed=...) is reproducible. The goal position is observed: observations are Meta-World's 39-dimensional goal-observable state (B, 39), or with observation="rgb" images (B, 3, size, size) in [0, 1] from camera.
Actions are end-effector position deltas and the gripper, 4 in [-1, 1]. Rewards are Meta-World's dense v2 shaping; transition.success is its success flag, and with terminate_on_success the episode ends there, as in Meta-World's evaluation. Episodes last 500 steps. Meta-World's corner cameras render upside down; their frames are flipped upright.
Source code in torch_world/envs/metaworld.py
class MetaWorld(MujocoLanes):
"""A `Meta-World <https://github.com/Farama-Foundation/Metaworld>`_ v3 task with a Sawyer arm, by name.
``name`` is any of the 50 v3 tasks, such as ``"reach-v3"``, ``"pick-place-v3"`` or ``"door-open-v3"``. Each
reset samples a new object and goal placement, as Meta-World's MT1 does, from the lane's own generator, so
``reset(seed=...)`` is reproducible. The goal position is observed: observations are Meta-World's 39-dimensional
goal-observable state ``(B, 39)``, or with ``observation="rgb"`` images ``(B, 3, size, size)`` in [0, 1] from
``camera``.
Actions are end-effector position deltas and the gripper, 4 in [-1, 1]. Rewards are Meta-World's dense v2 shaping;
``transition.success`` is its ``success`` flag, and with ``terminate_on_success`` the episode ends there, as in
Meta-World's evaluation. Episodes last 500 steps. Meta-World's corner cameras render upside down; their frames
are flipped upright.
"""
suite = "Meta-World"
def __init__(
self,
name,
*,
batch_size=1,
observation="state",
size=None,
camera="corner2",
terminate_on_success=True,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
):
self.name, self.terminate_on_success = name, terminate_on_success
self.settings = {
"name": name,
"batch_size": batch_size,
"observation": observation,
"size": size,
"camera": camera,
"terminate_on_success": terminate_on_success,
"quality": quality,
"render_size": render_size,
"max_episode_steps": max_episode_steps,
**env_kwargs,
}
self.spec = suite_spec(
f"MetaWorld/{name}",
"torch_world.envs.metaworld:MetaWorld",
"metaworld",
("metaworld",),
{"name": name},
"https://github.com/Farama-Foundation/Metaworld",
)
flip = isinstance(camera, str) and camera.startswith("corner")
super().__init__(
batch_size,
size,
device,
observation=observation,
camera=camera,
flip=flip,
quality=quality,
render_size=render_size,
)
try:
from metaworld.env_dict import ALL_V3_ENVIRONMENTS
except ImportError as exc:
raise ImportError("Install Meta-World with: pip install 'torch-world[metaworld]'") from exc
if name not in ALL_V3_ENVIRONMENTS:
raise ValueError(f"Unknown Meta-World task {name!r}; tasks are named like 'pick-place-v3'")
def make():
env = ALL_V3_ENVIRONMENTS[name](**env_kwargs)
# The goal-observable MT1 setup: every reset samples a placement, from the environment's seeded generator.
env._partially_observable = False
# Steps clip observations to this space, cached when the goal was hidden; recompute it with the goal.
env.__dict__.pop("sawyer_observation_space", None)
env._freeze_rand_vec = False
env.seeded_rand_vec = True
env._set_task_called = True
if max_episode_steps is not None:
env.max_path_length = max_episode_steps
return env
self._build(make)
self._bounds(self.envs[0].action_space.low, self.envs[0].action_space.high)
self.max_episode_steps = self.envs[0].max_path_length
self.reset(seed=0)
def _physics(self, lane):
return self.envs[lane].model, self.envs[lane].data
def _reset_lane(self, lane, seed):
env = self.envs[lane]
env.seed(seed)
return env.reset()[0]
def _step_lane(self, lane, action):
state, reward, terminated, truncated, info = self.envs[lane].step(action)
success = bool(info["success"])
return state, reward, terminated or (success and self.terminate_on_success), truncated, successclass ManiSkill
ManiSkill(
name,
*,
batch_size=1,
observation="state",
size=None,
camera="base_camera",
control_mode=None,
terminate_on_success=True,
sim_backend="auto",
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
)A ManiSkill 3 <https://github.com/haosulab/ManiSkill>_ task, by its registered ID.
name is any ManiSkill task, such as "PickCube-v1", "StackCube-v1" or "PushT-v1". With CUDA, all lanes run in one GPU-parallel ManiSkill environment; otherwise each lane runs its own CPU environment, which is the only kind ManiSkill's CPU simulation supports. sim_backend="physx_cpu" forces the CPU lanes.
Observations are ManiSkill's flattened state (B, D), or with observation="rgb" the camera sensor's images (B, 3, size, size) in [0, 1]; state is always the flattened agent and task state. Actions follow control_mode, ManiSkill's default for the robot unless given, rescaled from [-1, 1] to its bounds.
Rewards are ManiSkill's reward_mode, normalized dense by default; transition.success is its success flag, and episodes end on success or fail, as ManiSkill terminates them, or at the task's time limit. With terminate_on_success=False only fail ends them early, and success is reported at every step. Frames come from ManiSkill's human render camera. ManiSkill needs a Vulkan driver, MoltenVK on macOS, even without frames: its scenes build render materials. render_backend="none" skips the render cameras, and frames, for faster state observations. **env_kwargs go to gymnasium.make, such as robot_uids or reward_mode.
Members
| Member | Description |
|---|---|
render | The current observation; states live in the simulator, so they cannot be rendered from tensors. |
render_frame | Frames (B, 3, render_size, render_size) as uint8 from ManiSkill's human render camera. |
render_goal_frame | The scene at reset: ManiSkill defines goals in the simulator, and draws goal markers in its frames. |
Source code in torch_world/envs/maniskill.py
class ManiSkill(BenchmarkEnv):
"""A `ManiSkill 3 <https://github.com/haosulab/ManiSkill>`_ task, by its registered ID.
``name`` is any ManiSkill task, such as ``"PickCube-v1"``, ``"StackCube-v1"`` or ``"PushT-v1"``. With CUDA, all
lanes run in one GPU-parallel ManiSkill environment; otherwise each lane runs its own CPU environment, which is
the only kind ManiSkill's CPU simulation supports. ``sim_backend="physx_cpu"`` forces the CPU lanes.
Observations are ManiSkill's flattened state ``(B, D)``, or with ``observation="rgb"`` the ``camera`` sensor's
images ``(B, 3, size, size)`` in [0, 1]; ``state`` is always the flattened agent and task state. Actions follow
``control_mode``, ManiSkill's default for the robot unless given, rescaled from [-1, 1] to its bounds.
Rewards are ManiSkill's ``reward_mode``, normalized dense by default; ``transition.success`` is its ``success``
flag, and episodes end on success or ``fail``, as ManiSkill terminates them, or at the task's time limit. With
``terminate_on_success=False`` only ``fail`` ends them early, and ``success`` is reported at every step. Frames
come from ManiSkill's human render camera. ManiSkill needs a Vulkan driver, MoltenVK on macOS, even without
frames: its scenes build render materials. ``render_backend="none"`` skips the render cameras, and frames, for
faster state observations. ``**env_kwargs`` go to ``gymnasium.make``, such as ``robot_uids`` or ``reward_mode``.
"""
def __init__(
self,
name,
*,
batch_size=1,
observation="state",
size=None,
camera="base_camera",
control_mode=None,
terminate_on_success=True,
sim_backend="auto",
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
):
if observation not in ("state", "rgb"):
raise ValueError("observation must be 'state' or 'rgb'")
self.name, self.observation, self.camera = name, observation, camera
self.terminate_on_success = terminate_on_success
self.settings = {
"name": name,
"batch_size": batch_size,
"observation": observation,
"size": size,
"camera": camera,
"control_mode": control_mode,
"terminate_on_success": terminate_on_success,
"sim_backend": sim_backend,
"quality": quality,
"render_size": render_size,
"max_episode_steps": max_episode_steps,
**env_kwargs,
}
self.spec = suite_spec(
f"ManiSkill/{name}",
"torch_world.envs.maniskill:ManiSkill",
"maniskill",
("maniskill",),
{"name": name},
"https://github.com/haosulab/ManiSkill",
)
# The episode limit comes from the upstream registration, read once the environments exist.
super().__init__(batch_size, size, device, 1, quality=quality, render_size=render_size)
try:
import gymnasium as gym
import mani_skill.envs # noqa: F401, registers the tasks
from mani_skill.utils.registration import REGISTERED_ENVS
except ImportError as exc:
raise ImportError("Install ManiSkill with: pip install 'torch-world[maniskill]'") from exc
if name not in REGISTERED_ENVS:
raise ValueError(f"Unknown ManiSkill task {name!r}; tasks are named like 'PickCube-v1'")
self.renders = env_kwargs.get("render_backend", "gpu") not in ("none", None)
if observation == "rgb" and not self.renders:
raise ValueError("Camera observations need a render backend")
gpu = sim_backend in ("auto", "gpu", "physx_cuda") and torch.cuda.is_available()
kwargs = {
"obs_mode": "rgb+state" if observation == "rgb" else "state",
"render_mode": "rgb_array" if self.renders else None,
"sensor_configs": {"width": self.size, "height": self.size},
"human_render_camera_configs": {"width": self.render_size, "height": self.render_size},
"sim_backend": "physx_cuda" if gpu else "physx_cpu",
**({} if control_mode is None else {"control_mode": control_mode}),
**({} if max_episode_steps is None else {"max_episode_steps": max_episode_steps}),
**env_kwargs,
}
# Each group is an upstream environment and the lanes it simulates.
self.groups = []
try:
if gpu:
self.groups.append((gym.make(name, num_envs=batch_size, **kwargs), list(range(batch_size))))
else:
for lane in range(batch_size):
self.groups.append((gym.make(name, num_envs=1, **kwargs), [lane]))
except Exception:
self.close()
raise
env = self.groups[0][0]
space = env.unwrapped.single_action_space
self._low, self._high = (torch.as_tensor(b, dtype=torch.float32) for b in (space.low, space.high))
self.action_dim = space.shape[0]
# ManiSkill keeps the time limit in its own registry; the spec of the made environment drops it.
self.max_episode_steps = max_episode_steps or REGISTERED_ENVS[name].max_episode_steps
self.reset(seed=0)
def _read(self, obs):
"""Observations and state vectors of one group, on ``device``."""
state = (obs["state"] if isinstance(obs, dict) else obs).float().to(self.device)
if self.observation == "state":
return state.clone(), state
images = obs["sensor_data"][self.camera]["rgb"][..., :3].permute(0, 3, 1, 2)
return images.float().to(self.device) / 255, state
def reset(self, state=None, *, seed=None, generator=None):
if state is not None:
raise ValueError("ManiSkill observations are not simulator checkpoints; use reset(seed=...)")
if seed is not None and generator is not None:
raise ValueError("Pass seed or generator, not both")
seed = seed_from_generator(generator) if seed is None else seed
self._reset_episode()
observations, states = [], []
for env, lanes in self.groups:
obs, _ = env.reset(seed=[seed + lane for lane in lanes])
lane_obs, lane_state = self._read(obs)
observations.append(lane_obs)
states.append(lane_state)
self._obs, self.state = torch.cat(observations), torch.cat(states)
self.state_dim = self.state.shape[-1]
self._success = torch.zeros(self.batch_size, dtype=torch.bool, device=self.device)
self._start_frame = self.render_frame() if self.renders else None
return self.render()
def step(self, action):
action = self._action(action)
active = ~self.transition.done
action[~active] = 0
action = self._low.to(self.device) + (action + 1) / 2 * (self._high - self._low).to(self.device)
obs, state, success = self._obs.clone(), self.state.clone(), self._success.clone()
reward = torch.zeros(self.batch_size, device=self.device)
terminated, truncated = torch.zeros_like(active), torch.zeros_like(active)
for env, lanes in self.groups:
if not active[lanes].any(): # finished lanes are not stepped again
continue
upstream = env.unwrapped.device
lane_obs, r, term, trunc, info = env.step(action[lanes].to(upstream))
lane_obs, lane_state = self._read(lane_obs)
# A GPU group steps every lane; the finished ones keep their last outcome, absorbing.
keep = active[lanes]
index = torch.tensor(lanes, device=self.device)[keep]
obs[index], state[index] = lane_obs[keep], lane_state[keep]
reward[index] = r.float().to(self.device)[keep]
if not self.terminate_on_success: # ManiSkill terminates on success or fail; keep only failures
term = info["fail"] if "fail" in info else torch.zeros_like(term)
terminated[index] = term.to(self.device)[keep]
truncated[index] = trunc.to(self.device)[keep]
if "success" in info:
success[index] = info["success"].to(self.device)[keep]
self._obs, self.state, self._success = obs, state, success
self.elapsed += active
self.transition = Transition(
reward,
self.transition.terminated | terminated,
self.transition.truncated | truncated | ((self.elapsed >= self.max_episode_steps) & active),
success.clone(),
)
return self.render()
def render(self, state=None):
"""The current observation; states live in the simulator, so they cannot be rendered from tensors."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by ManiSkill")
return self._obs.clone()
def render_frame(self, state=None):
"""Frames ``(B, 3, render_size, render_size)`` as uint8 from ManiSkill's human render camera."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by ManiSkill")
if not self.renders:
raise RuntimeError("This ManiSkill environment was made with render_backend='none'")
frames = [env.render()[..., :3].permute(0, 3, 1, 2).cpu() for env, _ in self.groups]
return torch.cat(frames).contiguous()
def render_goal_frame(self):
"""The scene at reset: ManiSkill defines goals in the simulator, and draws goal markers in its frames."""
if self._start_frame is None:
raise RuntimeError("This ManiSkill environment was made with render_backend='none'")
return self._start_frame.clone()
@property
def gt_label(self):
return "Task at reset"
def close(self):
for env, _ in getattr(self, "groups", ()):
env.close()
self.groups = []method render
render(state=None)The current observation; states live in the simulator, so they cannot be rendered from tensors.
Source code in torch_world/envs/maniskill.py
def render(self, state=None):
"""The current observation; states live in the simulator, so they cannot be rendered from tensors."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by ManiSkill")
return self._obs.clone()method render_frame
render_frame(state=None)Frames (B, 3, render_size, render_size) as uint8 from ManiSkill's human render camera.
Source code in torch_world/envs/maniskill.py
def render_frame(self, state=None):
"""Frames ``(B, 3, render_size, render_size)`` as uint8 from ManiSkill's human render camera."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by ManiSkill")
if not self.renders:
raise RuntimeError("This ManiSkill environment was made with render_backend='none'")
frames = [env.render()[..., :3].permute(0, 3, 1, 2).cpu() for env, _ in self.groups]
return torch.cat(frames).contiguous()method render_goal_frame
render_goal_frame()The scene at reset: ManiSkill defines goals in the simulator, and draws goal markers in its frames.
Source code in torch_world/envs/maniskill.py
def render_goal_frame(self):
"""The scene at reset: ManiSkill defines goals in the simulator, and draws goal markers in its frames."""
if self._start_frame is None:
raise RuntimeError("This ManiSkill environment was made with render_backend='none'")
return self._start_frame.clone()class MyoSuite
MyoSuite(
name,
*,
batch_size=1,
observation="state",
size=None,
camera=None,
terminate_on_success=None,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
)A MyoSuite <https://github.com/MyoHub/myosuite>_ musculoskeletal task, by its registered name.
name is any MyoSuite environment, such as "myoHandPoseRandom-v0", "myoHandReorient8-v0" or "myoLegWalk-v0". Actions are muscle activations, normalized by MyoSuite to [-1, 1]: one per muscle, 39 for the hand. Observations are MyoSuite's state vector (B, D), which includes each task's target, or with observation="rgb" images (B, 3, size, size) in [0, 1] from camera: by default the model's first named camera, or MuJoCo's free camera when it has none.
Rewards are MyoSuite's dense task rewards; transition.success is its solved flag, and with terminate_on_success the episode ends there. By default it does, except in the locomotion tasks, whose solved means tracking the commanded velocity at that step rather than reaching a goal. MyoSuite's own terminations, such as a fall, also end the episode. The episode limit is the task's registered one. **env_kwargs go to MyoSuite's constructor.
Source code in torch_world/envs/myosuite.py
class MyoSuite(MujocoLanes):
"""A `MyoSuite <https://github.com/MyoHub/myosuite>`_ musculoskeletal task, by its registered name.
``name`` is any MyoSuite environment, such as ``"myoHandPoseRandom-v0"``, ``"myoHandReorient8-v0"`` or
``"myoLegWalk-v0"``. Actions are muscle activations, normalized by MyoSuite to [-1, 1]: one per muscle, 39 for
the hand. Observations are MyoSuite's state vector ``(B, D)``, which includes each task's target, or with
``observation="rgb"`` images ``(B, 3, size, size)`` in [0, 1] from ``camera``: by default the model's first named
camera, or MuJoCo's free camera when it has none.
Rewards are MyoSuite's dense task rewards; ``transition.success`` is its ``solved`` flag, and with
``terminate_on_success`` the episode ends there. By default it does, except in the locomotion tasks, whose
``solved`` means tracking the commanded velocity at that step rather than reaching a goal. MyoSuite's own
terminations, such as a fall, also end the episode. The episode limit is the task's registered one.
``**env_kwargs`` go to MyoSuite's constructor.
"""
suite = "MyoSuite"
def __init__(
self,
name,
*,
batch_size=1,
observation="state",
size=None,
camera=None,
terminate_on_success=None,
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
**env_kwargs,
):
if terminate_on_success is None:
terminate_on_success = not any(part in name for part in LOCOMOTION)
self.name, self.terminate_on_success = name, terminate_on_success
self.settings = {
"name": name,
"batch_size": batch_size,
"observation": observation,
"size": size,
"camera": camera,
"terminate_on_success": terminate_on_success,
"quality": quality,
"render_size": render_size,
"max_episode_steps": max_episode_steps,
**env_kwargs,
}
self.spec = suite_spec(
f"MyoSuite/{name}",
"torch_world.envs.myosuite:MyoSuite",
"myosuite",
("myosuite",),
{"name": name},
"https://github.com/MyoHub/myosuite",
)
super().__init__(
batch_size, size, device, observation=observation, camera=camera, quality=quality, render_size=render_size
)
try:
from myosuite.utils import gym
except ImportError as exc:
raise ImportError("Install MyoSuite with: pip install 'torch-world[myosuite]'") from exc
if name not in gym.envs.registry:
raise ValueError(f"Unknown MyoSuite environment {name!r}; tasks are named like 'myoHandPoseRandom-v0'")
if max_episode_steps is not None:
env_kwargs["max_episode_steps"] = max_episode_steps
self._build(lambda: gym.make(name, **env_kwargs))
if camera is None:
model = self._physics(0)[0]
self.camera = model.camera(0).name if model.ncam else -1
self._bounds(self.envs[0].action_space.low, self.envs[0].action_space.high)
self.max_episode_steps = max_episode_steps or self.envs[0].spec.max_episode_steps
self.reset(seed=0)
def _physics(self, lane):
env = self.envs[lane].unwrapped
return env.model, env.data
def _reset_lane(self, lane, seed):
return self.envs[lane].reset(seed=seed)[0]
def _step_lane(self, lane, action):
state, reward, terminated, truncated, info = self.envs[lane].step(action)
success = bool(info["solved"])
return state, reward, terminated or (success and self.terminate_on_success), truncated, successclass RoboCasa
RoboCasa(
task,
*,
split="target",
batch_size=1,
size=128,
camera="robot0_agentview_left",
observation="rgb",
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
robot="PandaOmron",
**env_kwargs,
)A RoboCasa <https://github.com/robocasa/robocasa>_ kitchen task, by its registered name.
task is any RoboCasa task, atomic ("OpenDrawer") or composite ("PrepareCoffee"), performed by the mobile PandaOmron robot. split="target" samples RoboCasa's 10 target kitchens and held-out object instances, "pretrain" its 2,500 pretraining scenes. Tasks are specified in language, instruction per lane, so there is no goal observation: episodes end when RoboCasa's own success check passes, with reward 1, or at the task's horizon from RoboCasa's dataset registry.
Observations are camera frames (B, 3, size, size) in [0, 1], flipped upright, or with observation="state" the robot's proprioception (B, D). state is always that vector. Object poses are left out: their number depends on the sampled kitchen, so lanes would not stack. Actions are RoboCasa's 12 controls in [-1, 1]: end-effector position and rotation deltas, gripper, base motion, torso and the base/arm mode switch, in that order.
Every reset rebuilds the kitchen, which takes seconds per lane. On macOS, robosuite's GLFW contexts corrupt the images of every RoboCasa environment in a process but the last, so batched pixel observations are refused there; presentation frames of batched state observations are affected too. RoboCasa pins mujoco==3.3.1, so it runs in its own environment; see the benchmark guide.
Members
| Member | Description |
|---|---|
reset | Sample new kitchens, or with scenes start each lane from a recorded demonstration. |
render_frame | Frames (B, 3, H, W) uint8 of the kitchen from RoboCasa's centered agent view, at render_size. |
render_goal_frame | The scene at reset: RoboCasa states its goal in language, instruction, not as an observation. |
Source code in torch_world/envs/robocasa.py
class RoboCasa(BenchmarkEnv):
"""A `RoboCasa <https://github.com/robocasa/robocasa>`_ kitchen task, by its registered name.
``task`` is any RoboCasa task, atomic (``"OpenDrawer"``) or composite (``"PrepareCoffee"``), performed by the
mobile ``PandaOmron`` robot. ``split="target"`` samples RoboCasa's 10 target kitchens and held-out object
instances, ``"pretrain"`` its 2,500 pretraining scenes. Tasks are specified in language, ``instruction`` per
lane, so there is no goal observation: episodes end when RoboCasa's own success check passes, with reward 1, or
at the task's horizon from RoboCasa's dataset registry.
Observations are ``camera`` frames ``(B, 3, size, size)`` in [0, 1], flipped upright, or with
``observation="state"`` the robot's proprioception ``(B, D)``. ``state`` is always that vector. Object poses are
left out: their number depends on the sampled kitchen, so lanes would not stack. Actions are RoboCasa's 12 controls in [-1, 1]: end-effector position and rotation deltas, gripper,
base motion, torso and the base/arm mode switch, in that order.
Every reset rebuilds the kitchen, which takes seconds per lane. On macOS, robosuite's GLFW contexts corrupt the
images of every RoboCasa environment in a process but the last, so batched pixel observations are refused there;
presentation frames of batched state observations are affected too. RoboCasa pins ``mujoco==3.3.1``, so it runs in its
own environment; see the benchmark guide.
"""
def __init__(
self,
task,
*,
split="target",
batch_size=1,
size=128,
camera="robot0_agentview_left",
observation="rgb",
quality="high",
render_size=None,
device=None,
max_episode_steps=None,
robot="PandaOmron",
**env_kwargs,
):
try:
from robocasa.utils.dataset_registry_utils import get_task_horizon
from robocasa.utils.env_utils import create_env
except ImportError as exc:
raise ImportError("RoboCasa is installed from source; see docs/guides/benchmark-environments.md") from exc
if observation not in ("rgb", "state"):
raise ValueError("observation must be 'rgb' or 'state'")
if sys.platform == "darwin" and batch_size > 1 and observation == "rgb":
raise ValueError(
"On macOS, robosuite's GLFW contexts corrupt the images of all but the last RoboCasa environment in a "
"process; use batch_size=1, observation='state', or Linux with MUJOCO_GL=egl"
)
self.task, self.split, self.camera, self.observation = task, split, camera, observation
self.settings = {
"task": task,
"split": split,
"batch_size": batch_size,
"size": size,
"camera": camera,
"observation": observation,
"quality": quality,
"render_size": render_size,
"max_episode_steps": max_episode_steps,
"robot": robot,
**env_kwargs,
}
try:
self.spec = get_spec(f"RoboCasa/{task}")
except KeyError: # a RoboCasa task outside the catalog carries its own spec
self.spec = EnvSpec(
f"RoboCasa/{task}",
"torch_world.envs.robocasa:RoboCasa",
"robocasa",
f"RoboCasa {task}",
("robocasa",),
{"task": task},
"https://robocasa.ai",
)
if max_episode_steps is None:
max_episode_steps = get_task_horizon(task)
super().__init__(batch_size, size, device, max_episode_steps, quality=quality, render_size=render_size)
# Presentation frames come from the observation pipeline, rendered during each lane's own reset and step:
# rendering a lane later, after another lane rebuilt its kitchen, can return corrupted frames.
cameras = {camera: size, PRESENTATION_CAMERA: self.render_size}
self.envs = []
try:
for _ in range(batch_size):
self.envs.append(
create_env(
task,
robots=robot,
camera_names=list(cameras),
camera_widths=list(cameras.values()),
camera_heights=list(cameras.values()),
split=split,
seed=0,
**env_kwargs,
)
)
except Exception:
self.close()
raise
self._streams = NumpyStreams(batch_size)
self.instruction = [""] * batch_size
self.reset(seed=0) # robosuite builds the robot, and its action limits, at the first reset
low, high = self.envs[0].action_spec
self._low, self._high = torch.as_tensor(low, dtype=torch.float32), torch.as_tensor(high, dtype=torch.float32)
self.action_dim = len(low)
def _vector(self, obs):
return torch.as_tensor(obs["robot0_proprio-state"], dtype=torch.float32)
@staticmethod
def _pixels(obs, camera):
"""A camera image, flipped upright from robosuite's OpenGL convention, as uint8 ``(3, H, W)``."""
return torch.as_tensor(obs[f"{camera}_image"][::-1].copy()).permute(2, 0, 1)
def _read(self, observations):
state = torch.stack([self._vector(o) for o in observations]).to(self.device)
frames = torch.stack([self._pixels(o, PRESENTATION_CAMERA) for o in observations])
if self.observation == "state":
return state, state.clone(), frames
images = torch.stack([self._pixels(o, self.camera) for o in observations]).float()
if images.shape[-1] != self.size: # the observation camera is the presentation camera, at render_size
images = torch.nn.functional.interpolate(images, (self.size, self.size), mode="area")
return (images / 255).to(self.device), state, frames
def reset(self, state=None, *, seed=None, generator=None, scenes=None):
"""Sample new kitchens, or with ``scenes`` start each lane from a recorded demonstration.
``scenes`` holds one `load_robocasa_scene` per lane: the demonstration's kitchen, objects and initial
simulator state, restored as RoboCasa's playback script does, so the demonstration's frames are reachable
goals.
"""
if state is not None:
raise ValueError("RoboCasa observations are not simulator checkpoints; use reset(seed=...) or scenes")
if seed is not None and generator is not None:
raise ValueError("Pass seed or generator, not both")
if scenes is not None and len(scenes) != self.batch_size:
raise ValueError(f"Pass one scene per lane, {self.batch_size}")
import numpy as np
seed = seed_from_generator(generator) if seed is None else seed
self._reset_episode()
observations = []
for lane, env in enumerate(self.envs):
# The kitchen, objects and robot noise come from env.rng; counter colors from NumPy's global generator.
env.rng = np.random.default_rng(seed + lane)
self._streams.seed(lane, seed + lane)
if scenes is None:
observations.append(self._streams.call(lane, env.reset))
else:
observations.append(self._streams.call(lane, self._restore, env, scenes[lane]))
self.instruction[lane] = env.get_ep_meta().get("lang", "")
self._obs, self.state, self._frames = self._read(observations)
self.state_dim = self.state.shape[-1]
self._start_frame = self.render_frame()
self._success = torch.zeros(self.batch_size, dtype=torch.bool, device=self.device)
return self.render()
@staticmethod
def _restore(env, scene):
env.set_ep_meta(scene["ep_meta"])
env.reset() # a hard reset loads the scene's fixtures; reset_from_xml_string alone does not
env.reset_from_xml_string(env.edit_model_xml(scene["model"]))
env.sim.reset()
env.sim.set_state_from_flattened(scene["state"])
env.sim.forward()
env.update_state()
return env._get_observations(force_update=True)
def step(self, action):
action = self._action(action)
active = ~self.transition.done
action[~active] = 0
action = (self._low + (action.cpu() + 1) / 2 * (self._high - self._low)).numpy()
obs, state, frames, success = self._obs.clone(), self.state.clone(), self._frames.clone(), self._success.clone()
for lane in active.nonzero().flatten().tolist():
env = self.envs[lane]
observation, *_ = self._streams.call(lane, env.step, action[lane])
lane_obs, lane_state, lane_frame = self._read([observation])
obs[lane], state[lane], frames[lane] = lane_obs[0], lane_state[0], lane_frame[0]
success[lane] = bool(self._streams.call(lane, env._check_success))
self._obs, self.state, self._frames, self._success = obs, state, frames, success
self.elapsed += active
self.transition = Transition(
(success & active).float(),
self.transition.terminated | (success & active),
self.transition.truncated | (~success & active & (self.elapsed >= self.max_episode_steps)),
success.clone(),
)
return self.render()
def render(self, state=None):
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by RoboCasa")
return self._obs.clone()
def render_frame(self, state=None):
"""Frames ``(B, 3, H, W)`` uint8 of the kitchen from RoboCasa's centered agent view, at ``render_size``."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by RoboCasa")
return self._frames.clone()
def render_goal_frame(self):
"""The scene at reset: RoboCasa states its goal in language, ``instruction``, not as an observation."""
return self._start_frame.clone()
@property
def gt_label(self):
return f"Task · {self.instruction[0]}" if self.instruction[0] else "Task"
def close(self):
for env in getattr(self, "envs", ()):
env.close()
self.envs = []method reset
reset(state=None, *, seed=None, generator=None, scenes=None)Sample new kitchens, or with scenes start each lane from a recorded demonstration.
scenes holds one load_robocasa_scene per lane: the demonstration's kitchen, objects and initial simulator state, restored as RoboCasa's playback script does, so the demonstration's frames are reachable goals.
Source code in torch_world/envs/robocasa.py
def reset(self, state=None, *, seed=None, generator=None, scenes=None):
"""Sample new kitchens, or with ``scenes`` start each lane from a recorded demonstration.
``scenes`` holds one `load_robocasa_scene` per lane: the demonstration's kitchen, objects and initial
simulator state, restored as RoboCasa's playback script does, so the demonstration's frames are reachable
goals.
"""
if state is not None:
raise ValueError("RoboCasa observations are not simulator checkpoints; use reset(seed=...) or scenes")
if seed is not None and generator is not None:
raise ValueError("Pass seed or generator, not both")
if scenes is not None and len(scenes) != self.batch_size:
raise ValueError(f"Pass one scene per lane, {self.batch_size}")
import numpy as np
seed = seed_from_generator(generator) if seed is None else seed
self._reset_episode()
observations = []
for lane, env in enumerate(self.envs):
# The kitchen, objects and robot noise come from env.rng; counter colors from NumPy's global generator.
env.rng = np.random.default_rng(seed + lane)
self._streams.seed(lane, seed + lane)
if scenes is None:
observations.append(self._streams.call(lane, env.reset))
else:
observations.append(self._streams.call(lane, self._restore, env, scenes[lane]))
self.instruction[lane] = env.get_ep_meta().get("lang", "")
self._obs, self.state, self._frames = self._read(observations)
self.state_dim = self.state.shape[-1]
self._start_frame = self.render_frame()
self._success = torch.zeros(self.batch_size, dtype=torch.bool, device=self.device)
return self.render()method render_frame
render_frame(state=None)Frames (B, 3, H, W) uint8 of the kitchen from RoboCasa's centered agent view, at render_size.
Source code in torch_world/envs/robocasa.py
def render_frame(self, state=None):
"""Frames ``(B, 3, H, W)`` uint8 of the kitchen from RoboCasa's centered agent view, at ``render_size``."""
if state is not None:
raise ValueError("Arbitrary-state rendering is not supported by RoboCasa")
return self._frames.clone()method render_goal_frame
render_goal_frame()The scene at reset: RoboCasa states its goal in language, instruction, not as an observation.
Source code in torch_world/envs/robocasa.py
def render_goal_frame(self):
"""The scene at reset: RoboCasa states its goal in language, ``instruction``, not as an observation."""
return self._start_frame.clone()function show_success
show_success(
env_id, *, policy=None, seed=7, steps=None, env_kwargs=None, path=None
)Display a verified successful episode GIF beside GT; optionally save it.
Reset the world, replay its reference policy (or the supplied controller), and check the real transition success flag. Failed or unavailable demonstrations raise ValueError; a static target is never substituted for an episode. A supplied policy receives batched observations and returns normalized actions.
Source code in torch_world/benchmarks/visualization.py
@torch.no_grad()
def show_success(env_id, *, policy=None, seed=7, steps=None, env_kwargs=None, path=None):
"""Display a verified successful episode GIF beside GT; optionally save it.
Reset the world, replay its reference policy (or the supplied controller), and
check the real transition success flag. Failed or unavailable demonstrations
raise ValueError; a static target is never substituted for an episode.
A supplied policy receives batched observations and returns normalized actions.
"""
from pathlib import Path
from IPython.display import Markdown, display
if steps is not None and steps < 1:
raise ValueError("steps must be positive")
spec = get_spec(env_id)
kwargs = dict(env_kwargs or {})
if not is_environment(env_id):
kwargs["batch_size"] = 1
with environment_scope(env_id, **kwargs) as env:
spec = get_spec(env)
obs = env.reset(seed=seed)
policy = env.reference_policy() if policy is None else policy
target = capture_frame(env, target=True)
frames = [capture_frame(env, obs)]
if frames[0].ndim != 3 or target.ndim != 3:
raise ValueError("Success GIFs require RGB render_frame() and render_goal_frame() implementations")
# Demonstrations may need more time than the experiment evaluation budget.
# Restore the caller's limit even when policy execution or rendering fails.
reference_steps = getattr(policy, "max_steps", env.max_episode_steps)
budget = steps if steps is not None else reference_steps
stride = max(1, (budget + 179) // 180)
frame_steps = [0]
original_limit = env.max_episode_steps
succeeded = False
try:
env.max_episode_steps = max(original_limit, budget)
for step in range(1, budget + 1):
obs = env.step(policy(obs))
succeeded = env.transition.success is not None and bool(env.transition.success[0])
finished = succeeded or bool(env.transition.done[0]) or step == budget
if step % stride == 0 or finished:
frames.append(capture_frame(env, obs))
frame_steps.append(step)
if finished:
break
finally:
env.max_episode_steps = original_limit
if not succeeded:
raise ValueError(f"{spec.id}: the supplied policy did not produce a verified success")
visual = episode_gif(
torch.stack(frames),
target,
title="Reference",
success=True,
target_title=getattr(env, "gt_label", "GT"),
frame_steps=frame_steps,
)
if path is not None:
destination = Path(path)
destination.parent.mkdir(parents=True, exist_ok=True)
visual.save(destination)
display(
Markdown(
f"**{spec.id}** — verified reference episode · {step} simulator steps; separate from model evaluation."
)
)
display(visual)
return visualNamed environment classes
Import tasks directly, for example from torch_world.envs import KeyDoor, PegInsertion. Create world = KeyDoor(**settings), preview it with world.show_env(), and run run_experiment(world). The world remains open for world.show_success() or further experiments. Call world.close() when finished, or use a context manager.
Passing a class or recipe to run_experiment(KeyDoor, env_kwargs=settings) still creates an environment owned and closed by the runner. Use get_spec(world) or get_spec(KeyDoor) for versioned metadata.
Rendering quality
All 33 built-in recipes accept quality="low" | "medium" | "high" (default high). size overrides RGB model resolution; render_size overrides presentation resolution. render_frame() and render_goal_frame() return batched camera/presentation frames independently of the policy observation. render_settings exposes effective resolutions for saved experiments. MuJoCo and Franka accept camera="task" | "overview"; Franka also accepts observation="rgb" | "state".
class RenderQuality
RenderQuality(
observation_size: int, render_size: int, samples: int, shadows: bool
)Source code in torch_world/envs/rendering.py
@dataclass(frozen=True)
class RenderQuality:
observation_size: int
render_size: int
samples: int
shadows: boolOriginal-environment benchmark recipes
Use PointMass(), Macaw(), PushT() or RobotCube() directly with run_experiment(world, ...), world.show_env() and world.show_success(). Select the SO-101 with RobotCube(robot="so101"). Success displays are verified episode GIFs with GT.
The original constructors and frame-sequence collect() interfaces remain supported. world.as_benchmark() exposes the shared episode view, with fixed goals, seeded resets, episode limits and aligned transition collection. Experiments use this view automatically and share the original simulator state. The observation constructor option selects the benchmark observation type; original reset/step/render methods continue returning pixels. size retains each original class's default; use size=128 to match the notebooks. Presentation defaults to high quality at 512 pixels. RobotCube previews default to a full-arm overview; presentation_camera="task" selects its original camera. Registered string recipes through make() remain available.
class LegacyEnvironment
LegacyEnvironment()Connect original worlds to experiments without changing their collect API.
show_env(), show_success() and run_experiment(world, ...) share one cached benchmark view of this simulator. Use as_benchmark() when aligned transitions, seeded resets or explicit episode limits are needed.
Members
| Member | Description |
|---|---|
as_benchmark | Return the shared episode view; it operates on this world's actual state. |
show_env | Reset and display the environment beside GT at presentation resolution. |
show_success | Display a verified successful episode GIF beside GT, optionally saving it. |
close | Release renderers without constructing a benchmark view. |
Source code in torch_world/envs/legacy.py
class LegacyEnvironment:
"""Connect original worlds to experiments without changing their ``collect`` API.
``show_env()``, ``show_success()`` and ``run_experiment(world, ...)`` share
one cached benchmark view of this simulator. Use ``as_benchmark()`` when
aligned transitions, seeded resets or explicit episode limits are needed.
"""
def _configure_benchmark(
self, *, quality, render_size, max_episode_steps, observation, presentation_camera="overview", **options
):
preset = resolve_quality(quality)
if render_size is not None and render_size < 1:
raise ValueError("render_size must be positive")
if max_episode_steps < 1:
raise ValueError("max_episode_steps must be positive")
if observation not in {"rgb", "state"}:
raise ValueError("observation must be rgb or state")
if presentation_camera not in {"overview", "task"}:
raise ValueError("presentation_camera must be overview or task")
self._benchmark_settings = {
"quality": quality,
"render_size": preset.render_size if render_size is None else render_size,
"max_episode_steps": max_episode_steps,
"observation": observation,
"presentation_camera": presentation_camera,
"options": options,
}
@cached_property
def _benchmark_env(self):
from torch_world.envs.registry import get_spec
spec = get_spec(self)
env = LegacyTask(
spec.kwargs["environment"],
batch_size=self.batch_size,
size=self.size,
device=self.device,
**self._benchmark_settings,
_world=self,
)
env.spec = spec
return env
def as_benchmark(self) -> BenchmarkEnv:
"""Return the shared episode view; it operates on this world's actual state."""
return self._benchmark_env
def show_env(self, *, seed=7) -> None:
"""Reset and display the environment beside GT at presentation resolution."""
self.as_benchmark().show_env(seed=seed)
def show_success(self, *, policy=None, seed=7, steps=None, path=None) -> None:
"""Display a verified successful episode GIF beside GT, optionally saving it."""
self.as_benchmark().show_success(policy=policy, seed=seed, steps=steps, path=path)
def close(self):
"""Release renderers without constructing a benchmark view."""
close_renderers(getattr(self, "renderers", {}))
def __enter__(self):
return self
def __exit__(self, *exc):
self.close()method as_benchmark
as_benchmark() -> BenchmarkEnvReturn the shared episode view; it operates on this world's actual state.
Source code in torch_world/envs/legacy.py
def as_benchmark(self) -> BenchmarkEnv:
"""Return the shared episode view; it operates on this world's actual state."""
return self._benchmark_envmethod show_env
show_env(*, seed=7) -> NoneReset and display the environment beside GT at presentation resolution.
Source code in torch_world/envs/legacy.py
def show_env(self, *, seed=7) -> None:
"""Reset and display the environment beside GT at presentation resolution."""
self.as_benchmark().show_env(seed=seed)method show_success
show_success(*, policy=None, seed=7, steps=None, path=None) -> NoneDisplay a verified successful episode GIF beside GT, optionally saving it.
Source code in torch_world/envs/legacy.py
def show_success(self, *, policy=None, seed=7, steps=None, path=None) -> None:
"""Display a verified successful episode GIF beside GT, optionally saving it."""
self.as_benchmark().show_success(policy=policy, seed=seed, steps=steps, path=path)method close
close()Release renderers without constructing a benchmark view.
Source code in torch_world/envs/legacy.py
def close(self):
"""Release renderers without constructing a benchmark view."""
close_renderers(getattr(self, "renderers", {}))class LegacyTask
LegacyTask(
environment,
*,
batch_size=1,
size=None,
quality="high",
render_size=None,
device=None,
max_episode_steps=100,
observation="rgb",
options=None,
presentation_camera="overview",
_world=None,
)Episode protocol shared by named original worlds and registered recipes.
options forwards original constructor settings, e.g. RobotCube's robot, camera or asset-cache root. Observation and presentation sizes are separate. State vectors retain the original meaning; robot states are not full physics checkpoints. PushT uses a fixed, symmetric translation task; other recipes retain seeded random starts and use a fixed goal throughout an experiment.
Source code in torch_world/envs/legacy.py
class LegacyTask(BenchmarkEnv):
"""Episode protocol shared by named original worlds and registered recipes.
``options`` forwards original constructor settings, e.g. RobotCube's robot,
camera or asset-cache root. Observation and presentation sizes are separate.
State vectors retain the original meaning; robot states are not full physics
checkpoints. PushT uses a fixed, symmetric translation task; other recipes
retain seeded random starts and use a fixed goal throughout an experiment.
"""
def __init__(
self,
environment,
*,
batch_size=1,
size=None,
quality="high",
render_size=None,
device=None,
max_episode_steps=100,
observation="rgb",
options=None,
presentation_camera="overview",
_world=None,
):
super().__init__(batch_size, size, device, max_episode_steps, quality=quality, render_size=render_size)
self.settings = deepcopy(
{
"environment": environment,
"batch_size": batch_size,
"size": self.size,
"quality": quality,
"render_size": self.render_size,
"device": self.device,
"max_episode_steps": max_episode_steps,
"observation": observation,
"options": dict(options or {}),
"presentation_camera": presentation_camera,
}
)
if observation not in {"rgb", "state"}:
raise ValueError("observation must be rgb or state")
self.environment, self.observation = environment, observation
if presentation_camera not in {"overview", "task"}:
raise ValueError("presentation_camera must be overview or task")
self.presentation_camera = presentation_camera
self._camera = None
cls = getattr(import_module(f"torch_world.envs.{_MODULES[environment]}"), environment)
options = dict(options or {})
self.world = (
_world
if _world is not None
else cls(
batch_size=batch_size, size=self.size if observation == "rgb" else 1, device=self.device, **options
)
)
self.action_dim, self.state_dim = self.world.action_dim, self.world.state_dim
self._physics = hasattr(self.world, "model")
self._presentation = None
self.initial = None
if self._physics:
model = self.world.model
self.world.render_shadows = self.render_quality.shadows
model.vis.global_.offwidth = max(self.size, self.render_size, 512)
model.vis.global_.offheight = max(self.size, self.render_size, 512)
model.vis.quality.offsamples = self.render_quality.samples
else:
self._presentation = cls(batch_size=batch_size, size=self.render_size, device=self.device, **options)
if environment == "RobotCube":
if presentation_camera == "overview":
self._camera = self.world.mujoco.MjvCamera()
self._camera.lookat[:] = (0.4, 0, 0.3) if self.world.robot == "ur10e" else (0.18, 0, 0.13)
self._camera.distance = 1.8 if self.world.robot == "ur10e" else 0.65
self._camera.azimuth, self._camera.elevation = 135, -25
(x0, x1), (y0, y1) = self.world.config.workspace
x, y = x0 + 0.35 * (x1 - x0), y0 + 0.3 * (y1 - y0)
target = [x, y, self.world.hover, 1, x, y, self.world.half]
elif environment == "PushT":
self.initial = torch.tensor([0, 0.12, 0, 0.06, 0], device=self.device).expand(batch_size, -1)
target = [0, -0.085, 0, -0.10, 0] # the pusher rests on the bar it pushed
else:
target = [0.75, 0.25]
self.goal = torch.tensor(target, device=self.device).expand(batch_size, -1).clone()
@property
def state(self):
return self.world.state
def reset(self, state=None, *, seed=None, generator=None):
if seed is not None and generator is not None:
raise ValueError("Pass seed or generator, not both")
generator = torch.Generator().manual_seed(seed) if seed is not None else generator
self._reset_episode()
pixels = self.world.reset(self.initial if state is None else state, generator=generator)
return self.state.clone() if self.observation == "state" else pixels
def step(self, action):
action = self._action(action)
active = ~self.transition.done
pixels = None
if active.any():
# The adapter has only a shared time limit, so all lanes finish together.
pixels = self.world.step(action)
self.elapsed += active
self.transition = Transition(
(-self.distance(self.state, self.goal) - 0.001 * action.square().sum(-1)) * active,
torch.zeros_like(active),
self.elapsed >= self.max_episode_steps,
self.success(self.state, self.goal),
)
return self.render() if self.observation == "state" or pixels is None else pixels
def distance(self, states, goal):
return self.world.distance(states, goal)
def success(self, states, goal):
reached = self.world.success(states, goal)
if self.environment == "RobotCube" and self.world.task == "pick":
reached &= (states[..., 3] > 0.9) & (states[..., 2] > self.world.hover * 0.8)
return reached
def render(self, state=None):
if self.observation == "state":
return (self.state if state is None else state).clone()
return self.world.render(state)
def render_frame(self, state=None):
if self._physics:
return self.world.render(state, size=self.render_size, camera=self._camera)
if self.environment == "Macaw":
phase = self.world.phase if state is None else None
return self._presentation.render(self.state if state is None else state, phase=phase)
return self._presentation.render(self.state if state is None else state)
def render_goal_frame(self):
return self.render_frame(self.goal)
@property
def render_settings(self):
return {**super().render_settings, "presentation_camera": self.presentation_camera}
def reference_policy(self):
if self.environment == "RobotCube":
return lambda obs: self.world.scripted(self.goal)
if self.environment == "PushT":
return lambda obs: torch.stack(
(
torch.zeros(self.batch_size, device=self.device),
((self.goal[:, 3] - self.state[:, 3]) / self.world.max_step).clamp(-0.5, 0.5),
),
-1,
)
return lambda obs: ((self.goal - self.state) / self.world.max_step).clamp(-0.35, 0.35)
def close(self):
close_renderers(getattr(self.world, "renderers", {}))