From 1f9c250dd91c11aba2ceac927f5ff259219174ad Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 03:11:19 +0000 Subject: [PATCH 01/24] Add Checkpoint Ghosts to debug and visualize policy checkpoints in the Newton visualizer Overlay rollouts of several checkpoints of one task in the Newton GL window. --checkpoint drives the reference robots; ghosts of other checkpoints are tinted, translucent copies that start from the same terrain, spawn pose and commands, so differences in behavior show up as the robots drift apart. - play ... --checkpoint_ghosts splits --num_envs among the checkpoints shown; the reference starts with all of them and adding a ghost resizes every slot. Plain play shows a greyed-out section that explains the flag. - The HUD section adds checkpoints from a folder browser, with per-ghost show, change, remove, opacity and tint. - The ghost sync keeps terrain, spawn state, joint targets and commands in step with the reference and recomputes relative and heading-derived commands from each robot's own state. - The controls are disabled in the RTX view, with a note to switch the Renderer to OpenGL. --- docs/source/api/lab/isaaclab.visualizers.rst | 23 + docs/source/concepts/visualization.rst | 55 ++- ...heckpoint-ghost-relative-targets.fixed.rst | 7 + .../checkpoint-ghost-replace.added.rst | 3 + .../checkpoint-ghost-sync-pool.changed.rst | 2 + .../checkpoint-ghost-sync.added.rst | 3 + .../envs/utils/checkpoint_ghost_sync.py | 215 +++++++++ .../isaaclab/visualizers/__init__.pyi | 13 + .../isaaclab/visualizers/checkpoint_ghost.py | 211 +++++++++ .../test/envs/test_checkpoint_ghost_sync.py | 271 +++++++++++ .../checkpoint-ghost-play.added.rst | 5 + .../checkpoint-ghost-review-fixes.fixed.rst | 3 + .../checkpoint-ghosts-config-fixes.fixed.rst | 2 + .../entrypoints/backends/play_rsl_rl.py | 174 ++++++- .../entrypoints/checkpoint_ghosts.py | 218 +++++++++ .../test/test_checkpoint_ghost_launch.py | 95 ++++ .../test_checkpoint_ghost_session_restart.py | 227 ++++++++++ .../checkpoint-ghost-change-remove.added.rst | 2 + .../checkpoint-ghost-hud-layout.added.rst | 2 + .../checkpoint-ghost-hud.added.rst | 5 + ...ckpoint-ghost-instancer-capacity.fixed.rst | 2 + .../checkpoint-ghost-offer.added.rst | 4 + .../newton/newton_checkpoint_ghosts.py | 385 ++++++++++++++++ .../newton/newton_visualizer.py | 118 ++++- .../test/test_newton_adapter.py | 33 ++ .../test/test_newton_checkpoint_ghosts.py | 428 ++++++++++++++++++ 26 files changed, 2481 insertions(+), 25 deletions(-) create mode 100644 source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst create mode 100644 source/isaaclab/changelog.d/checkpoint-ghost-replace.added.rst create mode 100644 source/isaaclab/changelog.d/checkpoint-ghost-sync-pool.changed.rst create mode 100644 source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst create mode 100644 source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py create mode 100644 source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py create mode 100644 source/isaaclab/test/envs/test_checkpoint_ghost_sync.py create mode 100644 source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst create mode 100644 source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst create mode 100644 source/isaaclab_rl/changelog.d/checkpoint-ghosts-config-fixes.fixed.rst create mode 100644 source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py create mode 100644 source/isaaclab_rl/test/test_checkpoint_ghost_launch.py create mode 100644 source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py create mode 100644 source/isaaclab_visualizers/changelog.d/checkpoint-ghost-change-remove.added.rst create mode 100644 source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud-layout.added.rst create mode 100644 source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud.added.rst create mode 100644 source/isaaclab_visualizers/changelog.d/checkpoint-ghost-instancer-capacity.fixed.rst create mode 100644 source/isaaclab_visualizers/changelog.d/checkpoint-ghost-offer.added.rst create mode 100644 source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py create mode 100644 source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py diff --git a/docs/source/api/lab/isaaclab.visualizers.rst b/docs/source/api/lab/isaaclab.visualizers.rst index f18253c6f9de..7cce450eef14 100644 --- a/docs/source/api/lab/isaaclab.visualizers.rst +++ b/docs/source/api/lab/isaaclab.visualizers.rst @@ -23,6 +23,10 @@ The following classes are part of the public :mod:`isaaclab.visualizers` API. BaseVisualizer KeyEventSource KeyboardSubscription + CheckpointGhostCheckpoint + CheckpointGhostController + CheckpointGhostLayout + CheckpointGhostSlot VisualizerCfg VisualizerBackendCfg WindowCfg @@ -42,6 +46,25 @@ The following classes are part of the public :mod:`isaaclab.visualizers` API. .. autofunction:: add_key_callbacks +.. autoclass:: CheckpointGhostCheckpoint + :members: + :show-inheritance: + +.. autoclass:: CheckpointGhostController + :members: + :show-inheritance: + +.. autoclass:: CheckpointGhostLayout + :members: + :show-inheritance: + +.. autoclass:: CheckpointGhostSlot + :members: + :show-inheritance: + +.. autodata:: CHECKPOINT_GHOST_COLORS + :no-value: + .. autoclass:: VisualizerCfg :show-inheritance: diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 20176ffa7117..71a5c423c67d 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -311,7 +311,7 @@ Visualizer Overview Picking, visualization markers, camera selection, pause controls, Visible Envs, and recording work in the RTX view of a windowed Newton visualizer, and picking draws the drag arrow there. Joint, contact, spring, center-of-mass, and inertia overlays are drawn in the RTX view too; the collision, visual, edge, and wireframe - overlays apply to the OpenGL view only. + overlays and the Checkpoint Ghost tint apply to the OpenGL view only. .. warning:: @@ -816,12 +816,56 @@ without screen-sharing, running with ``--viz viser``: The share URL is logged on startup. Rerun has no equivalent config field, but exposes its own share button in the native UI. +**Debugging and visualizing policies with Checkpoint Ghosts** + +Checkpoint Ghosts overlay rollouts of several policy checkpoints of one task in a single Newton viewport, to debug and +visualize how training changed the behavior. The ``--checkpoint`` +drives the reference robots; ghosts of other checkpoints are tinted, translucent copies that start +from the same terrain, spawn pose, and commands, so differences in behavior show up as the robots +drift apart: + +.. code-block:: bash + + uv run isaaclab play --rl_library rsl_rl --task Isaac-Velocity-Flat-AnymalD \ + --num_envs 32 --checkpoint latest --viz newton --checkpoint_ghosts + +Checkpoint Ghosts are opt-in. A plain ``play`` run shows a greyed-out **Checkpoint Ghosts (not enabled)** section in the +viewer's left panel that explains the feature and the flag, because the simulation must allocate the environments of +every slot up front and plain playback should not pay for them. + +``--num_envs`` is the total number of environments simulated, split evenly among the checkpoints shown. The reference +alone gets all of them; each checkpoint you add resizes every slot and restarts the environments from the same spawn +state. With ``--num_envs 32``, the reference starts with 32 environments, and adding one ghost gives 16 each, then +10 each (30 in use) with three. ``--checkpoint_ghost_slots`` (default and maximum eight, capped at ``--num_envs``) limits how +many checkpoints can be shown at once. The section shows what is drawn out of the simulated total, for example +``Showing 12/32 envs: 4 per slot x 3 ckpts``. **Visible Envs** in **Playback** follows the per-slot size as it +changes, and lowers the drawn count per slot, down to 1. + +Open **Checkpoint Ghosts** and choose **Add Checkpoint...** to browse for checkpoints. The window starts in the +experiment's log directory (``--checkpoint_ghost_root`` starts it elsewhere) and lists folders and the ``model_*.pt`` +files in the current one. Click a folder to enter it, **Up** to leave it, **Experiment Folder** to return, or type any +folder into the path box and press Enter. The window reopens in the folder you left it in, also after you pick a +checkpoint. The checkpoint must come from a run of this task and be an RSL-RL checkpoint, because the reference's +runner loads it; one that does not fit is reported instead of loaded. The reference is outlined and always shown. Each ghost has a +checkbox that shows or hides it. Under **Appearance**, each ghost has opacity and tint sliders; the tint blends the robot's native colors toward the +ghost color. Any tint above 0 drops native textures, and metal shading fades out as the tint rises. **Change...** replaces a ghost's checkpoint in place, and **Remove** frees the slot. + +* All ``--num_envs`` environments are always simulated. Ghost slots copy the reference slot's terrain, spawn poses, and + commands, and environments an uneven split leaves over receive zero actions. +* Randomization that cannot be mirrored between slots is disabled: startup and interval events, + curriculum terms, and observation noise. Reset events and commands are copied from the reference. +* Identical checkpoints do not stay exactly on top of each other; physics differences grow + to centimeters over a few seconds on rough terrain. +* Checkpoint Ghosts support RSL-RL and manager-based environments only. +* Tasks whose cameras render with OVRTX (``renderer=ovrtx``) are not supported yet. Checkpoint Ghosts are not offered for + them, and ``--checkpoint_ghosts`` exits with a message. + **Choosing how many environments are drawn** Every Newton viewer has a **Visible Envs** slider in its left panel that sets how many -environments are drawn. It changes only what is rendered, not the simulation. In the RTX view the OVRTX renderer is -shared with scene cameras, so the hidden environments also drop out of their images while the RTX view is shown; -the HUD notes this next to the slider. +environments are drawn. It changes only what is rendered, not the simulation. With Checkpoint Ghosts, it +counts environments per slot. In the RTX view the OVRTX renderer is shared with scene cameras, so the hidden +environments also drop out of their images while the RTX view is shown; the HUD notes this next to the slider. Resolution Rules ~~~~~~~~~~~~~~~~ @@ -989,7 +1033,8 @@ Limitations - ✓ In Newton's RTX view, the collision, visual, edge, and wireframe overlays are not available; joint, contact, spring, -center-of-mass, and inertia overlays are. +center-of-mass, and inertia overlays are. Checkpoint Ghost tint is +not available there, and the **Checkpoint Ghosts** controls are disabled until the Renderer is switched to OpenGL. **Lighting differences across visualizers** diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst new file mode 100644 index 000000000000..c11eb10d4f41 --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst @@ -0,0 +1,7 @@ +* Fixed Checkpoint Ghosts copying a navigation task's relative targets from the reference. Each ghost now recomputes + ``pos_command_b`` and ``heading_command_b`` from its own pose. +* Fixed Checkpoint Ghosts receiving the reference's turn command on velocity tasks that steer toward a heading. A ghost now + copies the reference's sampled velocity and heading target and derives its own yaw rate from its own heading. +* Fixed Checkpoint Ghosts holding joints the actions do not drive, such as the fingers of a reaching arm, at different + targets than the reference after a reset. A ghost now takes the reference's joint targets, so an identical + checkpoint follows the reference. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-replace.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-replace.added.rst new file mode 100644 index 000000000000..7e0049a2ddc2 --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-replace.added.rst @@ -0,0 +1,3 @@ +* Added :meth:`~isaaclab.visualizers.CheckpointGhostController.replace_ghost`, which loads a checkpoint into a given ghost + slot, and :meth:`~isaaclab.visualizers.CheckpointGhostController.apply_pending_restart`, which resets a newly added or + changed ghost while the simulation is paused. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-sync-pool.changed.rst b/source/isaaclab/changelog.d/checkpoint-ghost-sync-pool.changed.rst new file mode 100644 index 000000000000..dbf40d4752cd --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-sync-pool.changed.rst @@ -0,0 +1,2 @@ +* :class:`~isaaclab.envs.utils.checkpoint_ghost_sync.CheckpointGhostSync` now accepts an environment with more worlds than its + slices need, resets the extra worlds on their own, and restores the ghost slices' terrain placement when closed. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst new file mode 100644 index 000000000000..73d5396824c2 --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst @@ -0,0 +1,3 @@ +* Added :class:`~isaaclab.visualizers.CheckpointGhostController` and its slot and checkpoint types, and + :class:`~isaaclab.envs.utils.checkpoint_ghost_sync.CheckpointGhostSync`, which keep ghost slices of one manager-based + environment on the reference slice's terrain, spawn state, and commands. diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py new file mode 100644 index 000000000000..4daaf0d86a48 --- /dev/null +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -0,0 +1,215 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Keeps ghost slices of one environment on the reference slice's terrain, spawn state and commands.""" + +from __future__ import annotations + +import logging +from typing import TYPE_CHECKING, Any + +import numpy as np +import torch + +if TYPE_CHECKING: + from ..manager_based_rl_env import ManagerBasedRLEnv + from ..manager_based_rl_env_cfg import ManagerBasedRLEnvCfg + +logger = logging.getLogger(__name__) + +_TERRAIN_FIELDS = ("terrain_levels", "terrain_types", "env_origins") +"""Terrain placement tensors of every environment that the ghosts copy from the reference.""" + + +class CheckpointGhostSync: + """Synchronizes the slices of a single environment so that several policies can be compared. + + The environment is simulated with ``num_slices * slice_size`` worlds. Slice 0 is the reference; environment + ``i`` of every other slice mirrors environment ``i`` of the reference. Whenever a reference environment resets, + its ghost counterparts reset with it and receive the reference's spawn state. Velocity or pose commands are + copied from the reference after every command update. Ghost environments that terminate on their own wait + for the reference to reset. + + Only :class:`~isaaclab.envs.ManagerBasedRLEnv` is supported. Call :meth:`configure_env_cfg` on the env config + before creating the environment, because per-environment randomization other than the reset events cannot + be mirrored. + """ + + def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): + """Attach to an environment and place every slice on the reference slice's terrain. + + Args: + env: Environment simulated with at least ``slice_size * num_slices`` worlds. Worlds beyond the slices + are not mirrored: they reset on their own and are expected to receive zero actions. + slice_size: Number of environments per slice. + num_slices: Number of slices, including the reference. + + Raises: + TypeError: If the environment does not use managers. + ValueError: If the environment has fewer worlds than the slices need. + """ + for manager in ("command_manager", "event_manager", "scene"): + if not hasattr(env, manager): + raise TypeError("Checkpoint Ghosts only support manager-based environments.") + if slice_size < 1 or num_slices < 2 or env.num_envs < slice_size * num_slices: + raise ValueError( + f"Environment has {env.num_envs} envs, expected at least {num_slices} slices of {slice_size} envs." + ) + self._env = env + self._slice_size = slice_size + self._num_slices = num_slices + self._device = env.device + self._reference_ids = torch.arange(slice_size, device=self._device) + self._ghost_offsets = torch.arange(1, num_slices, device=self._device) * slice_size + self._saved_terrain = self._save_terrain() + self._sync_terrain() + self._reset_idx_original = env._reset_idx + self._compute_commands_original = env.command_manager.compute + env._reset_idx = self._reset_idx + env.command_manager.compute = self._compute_commands + + @staticmethod + def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: + """Remove per-environment randomization that cannot be mirrored between slices. + + Startup and interval events, curriculum terms, and observation corruption are disabled. Reset events + are kept because the reference's reset state is copied to the ghosts. + + Args: + env_cfg: Environment config to modify in place. + + Returns: + Names of the disabled terms. + """ + removed = [] + # A task may declare no events, curriculum, or observation groups at all. + events, curriculum, observations = ( + getattr(env_cfg, name, None) for name in ("events", "curriculum", "observations") + ) + for name, term in vars(events).items() if events is not None else (): + if term is not None and getattr(term, "mode", None) in ("startup", "interval"): + setattr(events, name, None) + removed.append(f"events.{name}") + for name, term in vars(curriculum).items() if curriculum is not None else (): + if term is not None: + setattr(curriculum, name, None) + removed.append(f"curriculum.{name}") + for group_name, group in vars(observations).items() if observations is not None else (): + if getattr(group, "enable_corruption", False): + group.enable_corruption = False + removed.append(f"observations.{group_name}.enable_corruption") + if removed: + logger.warning("Checkpoint Ghosts disabled per-environment randomization: %s", ", ".join(removed)) + return removed + + def env_origin_offsets(self) -> np.ndarray: + """Return per-environment offsets [m], shape ``[num_envs, 3]``, that move each ghost onto the reference.""" + origins = self._env.scene.env_origins + offsets = torch.zeros_like(origins) + for ghost_start in self._ghost_offsets.tolist(): + offsets[ghost_start : ghost_start + self._slice_size] = ( + origins[: self._slice_size] - origins[ghost_start : ghost_start + self._slice_size] + ) + return offsets.cpu().numpy().astype(np.float32) + + def close(self) -> None: + """Restore the environment's original reset, command update, and terrain placement.""" + self._env._reset_idx = self._reset_idx_original + self._env.command_manager.compute = self._compute_commands_original + terrain = self._terrain() + for name, values in self._saved_terrain.items(): + getattr(terrain, name).copy_(values) + + def _terrain(self) -> Any | None: + """Return the scene's terrain importer when it has terrain tiles, else None.""" + terrain = self._env.scene.terrain + return terrain if terrain is not None and getattr(terrain, "terrain_origins", None) is not None else None + + def _save_terrain(self) -> dict[str, torch.Tensor]: + """Copy the terrain placement of every environment, which :meth:`_sync_terrain` overwrites for the ghosts.""" + terrain = self._terrain() + return {} if terrain is None else {name: getattr(terrain, name).clone() for name in _TERRAIN_FIELDS} + + def _sync_terrain(self) -> None: + """Place every ghost environment on the terrain tile of its reference environment.""" + terrain = self._terrain() + if terrain is None: + return + for name in _TERRAIN_FIELDS: + values = getattr(terrain, name) + for ghost_start in self._ghost_offsets.tolist(): + values[ghost_start : ghost_start + self._slice_size] = values[: self._slice_size] + + def _reset_idx(self, env_ids: Any) -> None: + """Reset reference environments together with their ghosts, then copy the reference's spawn state.""" + if isinstance(env_ids, slice): + env_ids = torch.arange(self._env.num_envs, device=self._device)[env_ids] + env_ids = torch.as_tensor(env_ids, device=self._device, dtype=torch.long) + parked = env_ids[env_ids >= self._slice_size * self._num_slices] + if parked.numel(): + # worlds beyond the slices reset on their own, so their termination and episode statistics stay clean + self._reset_idx_original(parked) + reference = env_ids[env_ids < self._slice_size] + if reference.numel() == 0: + # ghost-only terminations wait for the reference to reset + return + ghosts = (reference[None, :] + self._ghost_offsets[:, None]).reshape(-1) + self._reset_idx_original(torch.cat([reference, ghosts])) + scene = self._env.scene + state = scene.get_state(is_relative=True) + source = reference.repeat(self._num_slices - 1) + scene.reset_to(_gather(state, source), env_ids=ghosts, is_relative=True) + self._copy_joint_targets(ghosts, source) + self._copy_command_state(reference) + + def _copy_joint_targets(self, ghosts: torch.Tensor, source: torch.Tensor) -> None: + """Give each ghost the reference's joint targets. + + Restoring the scene state sets a ghost's targets from its joint positions, while the reference keeps the + targets its own reset left. Joints the actions do not drive, such as the fingers of a reaching arm, would then + be held differently in the two, and the policy sees that in its observations. + """ + for asset in getattr(self._env.scene, "articulations", {}).values(): + for name in ("joint_pos_target", "joint_vel_target", "joint_effort_target"): + buffer = getattr(asset.data, name, None) + if buffer is not None: + targets = getattr(buffer, "torch", buffer) + targets[ghosts] = targets[source] + + def _compute_commands(self, *args: Any, **kwargs: Any) -> None: + """Update commands, then copy the reference's commands to the ghosts.""" + self._compute_commands_original(*args, **kwargs) + self._copy_command_state(self._reference_ids) + + def _copy_command_state(self, reference: torch.Tensor) -> None: + """Copy every per-environment tensor of each command term from the reference to its ghosts.""" + ghosts = (reference[None, :] + self._ghost_offsets[:, None]).reshape(-1) + source = reference.repeat(self._num_slices - 1) + manager = self._env.command_manager + origins = self._env.scene.env_origins + for name in manager.active_terms: + term = manager.get_term(name) + for key, value in vars(term).items(): + if key in _OWN_POSE_KEYS: + continue # relative to each robot's own pose, so a ghost computes it from its own state + if isinstance(value, torch.Tensor) and value.ndim >= 1 and value.shape[0] == self._env.num_envs: + value[ghosts] = value[source] + if key.endswith("_w") and value.ndim == 2 and value.shape[1] in (3, 7): + # A world-frame position names a place in the reference's world, so move it to the ghost's. + value[ghosts, :3] += origins[ghosts] - origins[source] + derives_from_own_pose = any(hasattr(term, key) for key in _OWN_POSE_KEYS) or getattr( + getattr(term, "cfg", None), "heading_command", False + ) # a velocity command that steers toward a heading turns each robot by its own heading error + if derives_from_own_pose and hasattr(term, "_update_command"): + term._update_command() # recompute the relative targets from each robot's own pose + + +_OWN_POSE_KEYS = ("pos_command_b", "heading_command_b") +"""Command tensors that express the target relative to the robot, such as those of ``UniformPose2dCommand``.""" + + +def _gather(state: dict[str, Any], ids: torch.Tensor) -> dict[str, Any]: + """Index every tensor of a nested scene-state dictionary by environment id.""" + return {key: _gather(value, ids) if isinstance(value, dict) else value[ids] for key, value in state.items()} diff --git a/source/isaaclab/isaaclab/visualizers/__init__.pyi b/source/isaaclab/isaaclab/visualizers/__init__.pyi index a230550c4afe..98b704074808 100644 --- a/source/isaaclab/isaaclab/visualizers/__init__.pyi +++ b/source/isaaclab/isaaclab/visualizers/__init__.pyi @@ -9,8 +9,14 @@ __all__ = [ "ImageViewCfg", "KeyEventSource", "KeyboardSubscription", + "CHECKPOINT_GHOST_COLORS", "PerspectiveCameraCfg", + "CheckpointGhostCheckpoint", + "CheckpointGhostController", + "CheckpointGhostLayout", + "CheckpointGhostSlot", "SceneCameraCfg", + "TrackingCameraCfg", "VisualizerCfg", "VisualizerBackendCfg", "WindowCfg", @@ -20,6 +26,13 @@ __all__ = [ from .base_visualizer import BaseVisualizer from .image_view import ImageView from .key_event_source import KeyboardSubscription, KeyEventSource, add_key_callbacks +from .checkpoint_ghost import ( + CHECKPOINT_GHOST_COLORS, + CheckpointGhostCheckpoint, + CheckpointGhostController, + CheckpointGhostLayout, + CheckpointGhostSlot, +) from .visualizer_cfg import ( ImageViewCfg, PerspectiveCameraCfg, diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py new file mode 100644 index 000000000000..98e8ec4ab7f2 --- /dev/null +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py @@ -0,0 +1,211 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Contract between a policy playback loop and a visualizer that shows Checkpoint Ghosts. + +Checkpoint Ghosts overlay several checkpoints of the same task in one viewer. The playback loop owns the +simulation and the policies; a visualizer only reads the controller to draw its HUD and tint the ghosts. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass, field + +import numpy as np + +CHECKPOINT_GHOST_COLORS: tuple[tuple[float, float, float], ...] = ( + (1.0, 0.1, 0.1), + (0.1, 1.0, 0.25), + (1.0, 0.85, 0.05), + (0.1, 0.9, 1.0), + (1.0, 0.2, 0.9), + (1.0, 0.5, 0.05), + (0.55, 0.3, 1.0), +) +"""Tint colors of the ghost slots in order; the reference slot keeps its native colors.""" + + +@dataclass(frozen=True) +class CheckpointGhostCheckpoint: + """A checkpoint that can be loaded into a ghost slot.""" + + path: str + """Absolute path to the checkpoint file.""" + + run: str + """Name of the training run directory that holds the checkpoint.""" + + name: str + """Checkpoint file name.""" + + modified: float + """Modification time of the checkpoint file, as seconds since the epoch.""" + + +@dataclass +class CheckpointGhostSlot: + """One simulated slice of environments driven by a single checkpoint.""" + + index: int + """Slot index. Slot 0 is the reference; the others are ghosts.""" + + checkpoint: CheckpointGhostCheckpoint | None = None + """Checkpoint driving this slot, or None when the slot is empty.""" + + opacity: float = 0.4 + """Opacity of the slot's robots in ``[0, 1]``. Ignored for the reference slot.""" + + tint: float = 0.7 + """How strongly :attr:`color` replaces the robots' native colors, in ``[0, 1]``. + + At ``1.0`` the color replaces all native colors and textures. Ignored for the reference slot. + """ + + visible: bool = True + """Whether the slot's robots are drawn. A hidden slot keeps its checkpoint and keeps running.""" + + color: tuple[float, float, float] | None = None + """Tint color of the slot's robots, or None to keep the native colors.""" + + label: str = "" + """Short label shown in the HUD: the checkpoint file name and its modification time.""" + + @property + def active(self) -> bool: + """Whether a checkpoint is loaded into the slot.""" + return self.checkpoint is not None + + @property + def shown(self) -> bool: + """Whether the slot has a checkpoint and is set to be drawn.""" + return self.checkpoint is not None and self.visible + + +@dataclass +class CheckpointGhostLayout: + """How environments map to slots. + + The simulated environments are split evenly among the slots that hold a checkpoint, in slot order: the first + loaded slot (the reference) owns the first ``slice_size`` environments, the next loaded slot the following + ``slice_size``, and so on. Loading or unloading a checkpoint therefore changes :attr:`slice_size`. Environments + beyond the last loaded slot's share, when the split leaves a remainder, belong to no slot. + """ + + num_envs: int + """Number of simulated environments.""" + + num_slots: int + """Largest number of slots, including the reference.""" + + slots: list[CheckpointGhostSlot] = field(default_factory=list) + """Slot state, indexed by slot.""" + + def __post_init__(self) -> None: + if self.num_envs < 1 or self.num_slots < 2: + raise ValueError("Checkpoint Ghosts need at least one environment and two slots.") + if not self.slots: + self.slots = [CheckpointGhostSlot(index=s) for s in range(self.num_slots)] + for slot in self.slots[1:]: + slot.color = CHECKPOINT_GHOST_COLORS[(slot.index - 1) % len(CHECKPOINT_GHOST_COLORS)] + + @property + def active_slots(self) -> list[CheckpointGhostSlot]: + """Slots that hold a checkpoint, in slot order.""" + return [slot for slot in self.slots if slot.active] + + @property + def slice_size(self) -> int: + """Environments per loaded slot: the simulated environments split evenly among them.""" + return max(1, self.num_envs // max(1, len(self.active_slots))) + + def slot_start(self, slot_index: int) -> int: + """Return the first environment of a loaded slot.""" + ranks = [slot.index for slot in self.active_slots] + return ranks.index(slot_index) * self.slice_size + + def visible_env_ids(self, per_slot: int) -> list[int]: + """Return the environments to show when each shown slot shows its first ``per_slot`` environments.""" + size = self.slice_size + per_slot = max(0, min(int(per_slot), size)) + return [self.slot_start(slot.index) + i for slot in self.slots if slot.shown for i in range(per_slot)] + + def slot_of_env(self, env_ids: np.ndarray) -> np.ndarray: + """Return the slot index of each environment id, or -1 for ids that belong to no loaded slot.""" + env_ids = np.asarray(env_ids) + active = [slot.index for slot in self.active_slots] + result = np.full(env_ids.shape, -1, dtype=np.int64) + if active: + rank = env_ids // self.slice_size + valid = (env_ids >= 0) & (rank < len(active)) + result[valid] = np.asarray(active)[rank[valid]] + return result + + +class CheckpointGhostController(ABC): + """Playback-loop side of Checkpoint Ghosts, read and driven by the visualizer HUD.""" + + layout: CheckpointGhostLayout + """Environment-to-slot layout and slot state.""" + + @property + @abstractmethod + def checkpoint_root(self) -> str: + """Directory searched for compatible checkpoints.""" + + @abstractmethod + def browse(self, directory: str) -> tuple[list[str], list[CheckpointGhostCheckpoint]]: + """List a directory for the checkpoint window. + + Args: + directory: Directory to list; it may be anywhere on the filesystem. + + Returns: + The names of its subdirectories and the checkpoint files in it that can be loaded. + + Raises: + OSError: If the directory cannot be read. + """ + + def other_task(self, directory: str) -> str | None: + """Return the task of the run saved in ``directory`` when it is not the running task, else None. + + The checkpoint window uses this to flag runs whose checkpoints cannot fit the running policy. + """ + return None + + @abstractmethod + def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: + """Load a checkpoint into the first empty ghost slot. + + Returns: + None on success, otherwise a message explaining why the checkpoint could not be loaded. + """ + + @abstractmethod + def remove_ghost(self, slot_index: int) -> None: + """Empty a ghost slot; the reference slot cannot be removed.""" + + def replace_ghost(self, slot_index: int, checkpoint: CheckpointGhostCheckpoint) -> str | None: + """Load a checkpoint into a given ghost slot, in place of the one it holds. + + Controllers that cannot target a slot remove that ghost and add the checkpoint to the first empty slot. + + Returns: + None on success, otherwise a message explaining why the checkpoint could not be loaded. + """ + self.remove_ghost(slot_index) + return self.add_ghost(checkpoint) + + def apply_pending_restart(self) -> None: + """Reset the environments now when a new ghost asked for a restart that the next step would apply. + + The viewer calls this while the simulation is paused, because no step runs then and a ghost that was just + added would otherwise stay in whatever pose its idle slot ended in. + """ + + @abstractmethod + def env_origin_offsets(self) -> np.ndarray: + """Return per-environment offsets [m], shape ``[num_envs, 3]``, that move each ghost onto the reference.""" diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py new file mode 100644 index 000000000000..ca2b5d43ff9e --- /dev/null +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -0,0 +1,271 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Checkpoint Ghosts keep every slice of one environment on the reference slice's spawn state and commands.""" + +from __future__ import annotations + +from types import SimpleNamespace + +import pytest +import torch + +from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync + +SLICE_SIZE = 3 +NUM_SLICES = 3 +NUM_ENVS = SLICE_SIZE * NUM_SLICES + + +class _Scene: + """Scene whose only state is one root position per environment.""" + + terrain = None + + def __init__(self, num_envs: int = NUM_ENVS) -> None: + self.env_origins = torch.zeros(num_envs, 3) + self.root_pos = torch.zeros(num_envs, 3) + self.articulations = { + "robot": SimpleNamespace(data=SimpleNamespace(root_pos_w=SimpleNamespace(torch=self.root_pos))) + } + + def get_state(self, is_relative: bool = False) -> dict: + return {"articulation": {"robot": {"root_pose": self.root_pos.clone()}}} + + def reset_to(self, state: dict, env_ids: torch.Tensor, is_relative: bool = False) -> None: + self.root_pos[env_ids] = state["articulation"]["robot"]["root_pose"] + + +class _CommandManager: + """Command manager with one term that draws an independent random command per environment.""" + + def __init__(self, num_envs: int = NUM_ENVS) -> None: + self.num_envs = num_envs + self.term = SimpleNamespace(command=torch.zeros(num_envs, 3), label="velocity") + self.active_terms = ["velocity"] + + def get_term(self, name: str) -> SimpleNamespace: + return self.term + + def compute(self, dt: float) -> None: + self.term.command[:] = torch.randn(self.num_envs, 3) + + +def _make_env(num_envs: int = NUM_ENVS) -> SimpleNamespace: + env = SimpleNamespace( + num_envs=num_envs, + device="cpu", + scene=_Scene(num_envs), + command_manager=_CommandManager(num_envs), + event_manager=object(), + reset_calls=[], + ) + + def reset_idx(env_ids: torch.Tensor) -> None: + # every reset environment spawns at its own random position, like a reset event would + env.reset_calls.append(env_ids.tolist()) + env.scene.root_pos[env_ids] = torch.randn(len(env_ids), 3) + + env._reset_idx = reset_idx + return env + + +def test_reference_reset_mirrors_spawn_state_to_ghost_counterparts() -> None: + env = _make_env() + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env._reset_idx(torch.tensor([1, 2])) + + assert sorted(env.reset_calls[0]) == [1, 2, 4, 5, 7, 8] + root_pos = env.scene.root_pos + assert torch.equal(root_pos[[4, 5]], root_pos[[1, 2]]) + assert torch.equal(root_pos[[7, 8]], root_pos[[1, 2]]) + + +def test_ghost_only_termination_waits_for_the_reference_reset() -> None: + env = _make_env() + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env._reset_idx(torch.tensor([4, 8])) + + assert env.reset_calls == [] + + +def test_commands_are_copied_from_the_reference_after_every_update() -> None: + env = _make_env() + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env.command_manager.compute(0.02) + + command = env.command_manager.term.command + assert torch.equal(command[SLICE_SIZE : 2 * SLICE_SIZE], command[:SLICE_SIZE]) + assert torch.equal(command[2 * SLICE_SIZE :], command[:SLICE_SIZE]) + + +def test_world_frame_command_positions_are_moved_to_the_ghost_s_own_origin() -> None: + env = _make_env() + env.scene.env_origins[:] = torch.arange(NUM_ENVS, dtype=torch.float32)[:, None] * torch.tensor([10.0, 0.0, 0.0]) + term = env.command_manager.term + term.pos_command_w = torch.zeros(NUM_ENVS, 3) + term.heading_command_w = torch.zeros(NUM_ENVS) + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + # Environment 0 is told to walk to a spot 2 m in front of its own origin. + term.pos_command_w[0] = env.scene.env_origins[0] + torch.tensor([2.0, 0.0, 0.0]) + term.heading_command_w[0] = 1.5 + env.command_manager.compute(0.02) + + ghost = SLICE_SIZE # The ghost counterpart of environment 0 in the next slice. + assert term.pos_command_w[ghost].tolist() == (env.scene.env_origins[ghost] + torch.tensor([2.0, 0.0, 0.0])).tolist() + assert term.heading_command_w[ghost] == 1.5 # A heading is the same in every world. + + +def test_relative_targets_are_recomputed_from_each_ghost_s_own_state_not_copied() -> None: + env = _make_env() + term = env.command_manager.term + term.pos_command_b = torch.zeros(NUM_ENVS, 3) + own_offsets = torch.arange(NUM_ENVS, dtype=torch.float32) + + def update_command() -> None: # the real term derives these from the target and the robot's own pose + term.pos_command_b[:, 0] = 5.0 - own_offsets + + term._update_command = update_command + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env.command_manager.compute(0.02) + + assert term.pos_command_b[SLICE_SIZE, 0] == 5.0 - SLICE_SIZE # the ghost's own distance, not the reference's + assert term.pos_command_b[0, 0] == 5.0 + + +def test_a_heading_derived_turn_command_is_recomputed_from_each_ghost_s_own_heading() -> None: + env = _make_env() + term = env.command_manager.term + term.cfg = SimpleNamespace(heading_command=True) + term.vel_command_b = torch.zeros(NUM_ENVS, 3) + term.heading_target = torch.zeros(NUM_ENVS) + own_heading = torch.arange(NUM_ENVS, dtype=torch.float32) * 0.1 + + def update_command() -> None: # like UniformVelocityCommand: yaw rate steers toward the heading target + term.vel_command_b[:, 2] = term.heading_target - own_heading + + term._update_command = update_command + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + term.vel_command_b[0, 0], term.heading_target[0] = 1.0, 2.0 + + env.command_manager.compute(0.02) + + ghost = SLICE_SIZE + assert term.vel_command_b[ghost, 0] == 1.0 # the sampled forward speed is the reference's + assert term.heading_target[ghost] == 2.0 # and so is the heading target + assert term.vel_command_b[ghost, 2] == pytest.approx(2.0 - own_heading[ghost]) # but the turn is the ghost's own + assert term.vel_command_b[0, 2] == pytest.approx(2.0) + + +def test_ghosts_hold_the_reference_s_joint_targets_after_a_reset() -> None: + env = _make_env() + targets = torch.zeros(NUM_ENVS, 2) + env.scene.articulations["robot"].data.joint_pos_target = targets + reset_idx = env._reset_idx + + def reset_with_targets(env_ids: torch.Tensor) -> None: + reset_idx(env_ids) + targets[env_ids] = 0.0 # the reset leaves the reference's targets at zero... + + def reset_to(state: dict, env_ids: torch.Tensor, is_relative: bool = False) -> None: + env.scene.root_pos[env_ids] = state["articulation"]["robot"]["root_pose"] + targets[env_ids] = 0.04 # ...while restoring a state sets the ghost's from its joint positions + + env._reset_idx = reset_with_targets + env.scene.reset_to = reset_to + sync = CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env._reset_idx(torch.arange(SLICE_SIZE)) + + assert (targets == 0.0).all(), targets # every slice ends up with the reference's targets + sync.close() + + +def test_close_restores_the_environment_hooks() -> None: + env = _make_env() + reset_idx, compute = env._reset_idx, env.command_manager.compute + sync = CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + sync.close() + + assert env._reset_idx == reset_idx + assert env.command_manager.compute == compute + + +def test_environment_size_must_match_the_slices() -> None: + with pytest.raises(ValueError, match="slices"): + CheckpointGhostSync(_make_env(), SLICE_SIZE, NUM_SLICES + 1) + + +def test_configure_env_cfg_keeps_only_randomization_the_reset_can_mirror() -> None: + def term(mode: str) -> SimpleNamespace: + return SimpleNamespace(mode=mode) + + cfg = SimpleNamespace( + events=SimpleNamespace(mass=term("startup"), push=term("interval"), reset_base=term("reset"), removed=None), + curriculum=SimpleNamespace(terrain_levels=object()), + observations=SimpleNamespace(policy=SimpleNamespace(enable_corruption=True)), + ) + + removed = CheckpointGhostSync.configure_env_cfg(cfg) + + assert sorted(removed) == [ + "curriculum.terrain_levels", + "events.mass", + "events.push", + "observations.policy.enable_corruption", + ] + assert cfg.events.reset_base.mode == "reset" + assert cfg.events.mass is None and cfg.events.push is None + assert cfg.curriculum.terrain_levels is None + assert cfg.observations.policy.enable_corruption is False + + +def test_configure_env_cfg_accepts_a_task_without_a_curriculum() -> None: + cfg = SimpleNamespace( + events=SimpleNamespace(push=SimpleNamespace(mode="interval")), + curriculum=None, + observations=SimpleNamespace(policy=SimpleNamespace(enable_corruption=False)), + ) + + assert CheckpointGhostSync.configure_env_cfg(cfg) == ["events.push"] + assert CheckpointGhostSync.configure_env_cfg(SimpleNamespace()) == [] # No events, curriculum, or observations. + + +def test_a_larger_pool_resets_the_environments_beyond_the_slices_on_their_own() -> None: + env = _make_env(NUM_ENVS + 4) + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env._reset_idx(torch.tensor([NUM_ENVS + 1])) # A parked environment resets on its own, without mirroring. + assert env.reset_calls == [[NUM_ENVS + 1]] + + env._reset_idx(torch.tensor([0])) + assert sorted(env.reset_calls[1]) == [0, 3, 6] + env.command_manager.compute(0.02) + command = env.command_manager.term.command + assert torch.equal(command[SLICE_SIZE : 2 * SLICE_SIZE], command[:SLICE_SIZE]) + + +def test_close_puts_the_ghost_environments_back_on_their_own_terrain() -> None: + env = _make_env() + env.scene.terrain = SimpleNamespace( + terrain_origins=object(), + terrain_levels=torch.arange(NUM_ENVS), + terrain_types=torch.arange(NUM_ENVS), + env_origins=torch.arange(NUM_ENVS * 3, dtype=torch.float32).reshape(NUM_ENVS, 3), + ) + original = env.scene.terrain.env_origins.clone() + sync = CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + assert torch.equal(env.scene.terrain.env_origins[SLICE_SIZE : 2 * SLICE_SIZE], original[:SLICE_SIZE]) + sync.close() + + assert torch.equal(env.scene.terrain.env_origins, original) + assert torch.equal(env.scene.terrain.terrain_levels, torch.arange(NUM_ENVS)) diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst new file mode 100644 index 000000000000..17c6054bb2df --- /dev/null +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst @@ -0,0 +1,5 @@ +* Added ``--checkpoint_ghosts`` and ``--checkpoint_ghost_slots`` to RSL-RL playback, the Newton GL viewer's checkpoint + visualization. ``--num_envs`` is the total simulated and is split evenly among the checkpoints shown: the reference + starts with all of them, and adding a ghost resizes every slot (32 environments give 16 each with two checkpoints). + ``--checkpoint_ghost_slots`` caps the checkpoints shown at once (default eight, at most ``--num_envs``). + ``--checkpoint_ghost_root`` searches another directory for checkpoints. Plain playback allocates nothing for the feature. diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst new file mode 100644 index 000000000000..450b2724a72a --- /dev/null +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -0,0 +1,3 @@ +* Fixed ``--checkpoint_ghosts`` rejecting a run with + several viewers such as ``--viz newton,viser``, and recurrent ghost policies keeping their memory across an episode + reset. Tasks whose cameras render with OVRTX are now rejected, since Checkpoint Ghosts do not support them yet. diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghosts-config-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghosts-config-fixes.fixed.rst new file mode 100644 index 000000000000..3f36b9f2b7ad --- /dev/null +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghosts-config-fixes.fixed.rst @@ -0,0 +1,2 @@ +* Fixed ``--checkpoint_ghosts`` rejecting the Newton GL visualizer after the shared visualizer settings refactor, and + crashing on tasks that declare no curriculum. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index f1ad5462ecf9..e2c62da9b4cf 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -11,18 +11,25 @@ import contextlib import logging import os +from pathlib import Path from isaaclab.app import add_launcher_args, launch_simulation -from isaaclab.envs import DirectMARLEnvCfg +from isaaclab.envs import DirectMARLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync from isaaclab.utils.assets import retrieve_file_path from isaaclab.utils.seed import configure_seed from isaaclab.utils.string import list_intersection +from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli from ...rsl_rl import RslRlBaseRunnerCfg, RslRlSacRunnerCfg, RslRlVecEnvWrapper from ...utils.wandb import is_wandb_checkpoint, resolve_wandb_checkpoint +from ..checkpoint_ghosts import ( + MAX_CHECKPOINT_GHOST_SLOTS, + CheckpointGhostSession, +) from ..common import ( CHECKPOINT_SELECTORS, add_common_play_args, @@ -61,6 +68,30 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: parser.add_argument( "--external_callback", default=None, help="Fully qualified path to an externally defined callback." ) + parser.add_argument( + "--checkpoint_ghosts", + action="store_true", + default=False, + help=( + "Enable Checkpoint Ghosts, the checkpoint visualization in the Newton GL viewer. The --checkpoint drives" + " the reference; ghosts are added from the viewer HUD. --num_envs is the total simulated and is split" + " evenly among the checkpoints shown." + ), + ) + parser.add_argument( + "--checkpoint_ghost_slots", + type=int, + default=None, + help=( + f"Most checkpoints shown at once, including the reference (2 to {MAX_CHECKPOINT_GHOST_SLOTS}). Defaults to" + f" {MAX_CHECKPOINT_GHOST_SLOTS}, capped at --num_envs." + ), + ) + parser.add_argument( + "--checkpoint_ghost_root", + default=None, + help="Directory searched for ghost checkpoints. Defaults to the experiment's log directory.", + ) cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) remaining_args_env_registration = cli_args.register_external_tasks(argv) @@ -69,6 +100,11 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: _, remaining_args_env_registration = setup_preset_cli(parser, remaining_args_env_registration) enable_cameras_for_video(args_cli) set_hydra_args(list_intersection(remaining_args, remaining_args_env_registration)) + if ( + args_cli.checkpoint_ghost_slots is not None + and not 2 <= args_cli.checkpoint_ghost_slots <= MAX_CHECKPOINT_GHOST_SLOTS + ): + raise SystemExit(f"--checkpoint_ghost_slots must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") return args_cli @@ -86,10 +122,8 @@ def _resolve_checkpoint( return resolve_checkpoint_selector( log_root_path, args_cli.checkpoint, - library="rsl_rl", task=normalize_task_name(args_cli.task), checkpoint_pattern=r"model_.*\.pt", - metadata={"agent": args_cli.agent}, ) if args_cli.checkpoint and os.path.isdir(args_cli.checkpoint): return get_checkpoint_path( @@ -100,12 +134,136 @@ def _resolve_checkpoint( return get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) +def create_checkpoint_ghost_session( + env: RslRlVecEnvWrapper, + args_cli: argparse.Namespace, + agent_cfg: RslRlBaseRunnerCfg, + reference_path: str, + log_root_path: str, + num_slots: int, +) -> CheckpointGhostSession: + """Build a Checkpoint Ghost session whose reference slot plays ``reference_path``.""" + + def policy_factory(path: str): + runner = create_rsl_rl_runner(env, agent_cfg, inference=True) + runner.load(path) + return runner.get_inference_policy(device=env.unwrapped.device) + + reference_file = Path(reference_path) + return CheckpointGhostSession( + env, + num_slots=num_slots, + task=args_cli.task, + checkpoint_root=os.path.abspath(args_cli.checkpoint_ghost_root or log_root_path), + checkpoint_pattern=r"model_.*\.pt", + policy_factory=policy_factory, + reference=CheckpointGhostCheckpoint( + reference_path, reference_file.parent.name, reference_file.name, reference_file.stat().st_mtime + ), + ) + + +def run_checkpoint_ghosts( + env: RslRlVecEnvWrapper, + args_cli: argparse.Namespace, + agent_cfg: RslRlBaseRunnerCfg, + reference_path: str, + log_root_path: str, +) -> None: + """Play the reference checkpoint with ghost slots that the Newton GL viewer HUD fills.""" + session = create_checkpoint_ghost_session( + env, args_cli, agent_cfg, reference_path, log_root_path, args_cli.checkpoint_ghost_slots + ) + attached = False + for visualizer in env.unwrapped.sim.visualizers: + if hasattr(visualizer, "attach_checkpoint_ghosts"): + visualizer.attach_checkpoint_ghosts(session) + attached = True + if not attached: + raise RuntimeError("--checkpoint_ghosts needs an initialized Newton GL visualizer.") + try: + run_playback( + session.step, + dt=env.unwrapped.step_dt, + args_cli=args_cli, + env_cfg=env.unwrapped.cfg, + ) + finally: + session.close() + + +def _offer_checkpoint_ghosts(env: RslRlVecEnvWrapper, env_cfg: object) -> None: + """Show the greyed-out Checkpoint Ghosts section in the Newton GL HUD of a run that started without the feature.""" + if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + return + if _scene_cameras_use_ovrtx(env_cfg): # not supported with OVRTX cameras yet + return + for visualizer in env.unwrapped.sim.visualizers: + if hasattr(visualizer, "offer_checkpoint_ghosts"): + visualizer.offer_checkpoint_ghosts() + + +def _resolve_ghost_slots(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg) -> None: + """Set ``args_cli.checkpoint_ghost_slots``, the most checkpoints that can be shown at once. + + ``--num_envs`` is the total simulated; the environments are split among the loaded checkpoints, so every slot + needs at least one. + """ + total = env_cfg.scene.num_envs + if total < 2: + raise SystemExit("--checkpoint_ghosts needs --num_envs of at least 2: one environment per checkpoint.") + slots = args_cli.checkpoint_ghost_slots + if slots is None: + slots = MAX_CHECKPOINT_GHOST_SLOTS + if slots > total: + if args_cli.checkpoint_ghost_slots is not None: + logger.warning(f"--checkpoint_ghost_slots {slots} exceeds --num_envs {total}; using {total} slots.") + slots = total + args_cli.checkpoint_ghost_slots = min(slots, MAX_CHECKPOINT_GHOST_SLOTS) + + +def _validate_checkpoint_ghosts(args_cli: argparse.Namespace, env_cfg: object) -> None: + """Reject configurations Checkpoint Ghosts cannot run, before any simulation starts.""" + if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + raise SystemExit("--checkpoint_ghosts only supports manager-based environments.") + visualizers = env_cfg.sim.visualizer_cfgs or [] + if not isinstance(visualizers, (list, tuple)): + visualizers = [visualizers] + # A shared visualizer configuration names its type on its backend; a deprecated combined one names it directly. + types = [] + for cfg in visualizers: + backend = getattr(cfg, "backend", None) + for chosen in backend if isinstance(backend, (list, tuple)) else [backend]: # --viz newton,viser selects both + types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) + if "newton" not in types: + raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") + if _scene_cameras_use_ovrtx(env_cfg): + raise SystemExit( + "--checkpoint_ghosts does not support tasks whose cameras use the OVRTX renderer yet." + " Use another renderer, such as renderer=newton_warp." + ) + + +def _scene_cameras_use_ovrtx(env_cfg: object) -> bool: + """Whether a scene sensor renders with OVRTX, which Checkpoint Ghosts do not support yet.""" + scene = getattr(env_cfg, "scene", None) + for value in vars(scene).values() if scene is not None else (): + if getattr(value, "render_on_demand", False) is True: + continue # the Newton viewer's own RTX camera, which launch adds and which no policy observes + renderer_cfg = getattr(value, "renderer_cfg", None) + if getattr(renderer_cfg, "renderer_type", None) == "ovrtx": + return True + return False + + def run(argv: list[str]) -> None: """Play a checkpoint of an RSL-RL agent.""" args_cli = _parse_args(argv) with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) + if args_cli.checkpoint_ghosts: + _validate_checkpoint_ghosts(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library="rsl_rl", action="play") @@ -121,6 +279,9 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(resume_path) env_cfg.log_dir = log_dir + if args_cli.checkpoint_ghosts: + _resolve_ghost_slots(args_cli, env_cfg) + CheckpointGhostSync.configure_env_cfg(env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play", checkpoint_path=resume_path) screen.stage("Creating environment") @@ -135,6 +296,12 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) logger.info(f"Loading model checkpoint from: {resume_path}") + if args_cli.checkpoint_ghosts: + if args_cli.deterministic: + configure_seed(env_cfg.seed, torch_deterministic=True) + screen.close() + run_checkpoint_ghosts(env, args_cli, agent_cfg, resume_path, log_root_path) + return runner = create_rsl_rl_runner(env, agent_cfg, inference=True) # configure_seed must run after runner construction so torch determinism does not disturb its initialization if args_cli.deterministic: @@ -155,4 +322,5 @@ def step() -> None: policy.reset(dones) screen.close() + _offer_checkpoint_ghosts(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py new file mode 100644 index 000000000000..b0d4d3f0f1c4 --- /dev/null +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py @@ -0,0 +1,218 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Playback of several checkpoints of one task side by side as Checkpoint Ghosts.""" + +from __future__ import annotations + +import json +import logging +import re +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any, Protocol + +import numpy as np +import torch + +from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync +from isaaclab.visualizers.checkpoint_ghost import ( + CheckpointGhostCheckpoint, + CheckpointGhostController, + CheckpointGhostLayout, +) + +from .common import RUN_MANIFEST_FILENAME, _natural_sort_key, normalize_task_name + +logger = logging.getLogger(__name__) + +MAX_CHECKPOINT_GHOST_SLOTS = 8 +"""Largest number of slots, including the reference.""" + + +class CheckpointGhostPolicy(Protocol): + """Inference policy driving one slot.""" + + def __call__(self, obs: Any) -> torch.Tensor: + """Return actions for the slot's observations.""" + + def reset(self, dones: torch.Tensor) -> None: + """Reset recurrent state of the slot's environments that terminated.""" + + +def _describe_load_error(error: Exception) -> str: + """Return a one-line reason a checkpoint could not be loaded, naming a size mismatch for what it usually means.""" + text = str(error) + if "size mismatch" in text: + return "it does not fit this task's policy (its observation or action sizes differ)" + return (text.splitlines() or [type(error).__name__])[0] + + +class CheckpointGhostSession(CheckpointGhostController): + """Steps one environment whose slices are driven by different checkpoints of the same task. + + Slot 0 is the reference and is loaded at start, so it owns every environment until a ghost is added. Ghost slots + start empty and are filled from the visualizer HUD. The environments are split evenly among the loaded slots, so + adding or removing a checkpoint resizes every slot and restarts the environments. Environments left over by an + uneven split are simulated with zero actions. + """ + + def __init__( + self, + env: Any, + *, + num_slots: int, + task: str, + checkpoint_root: str, + checkpoint_pattern: str, + policy_factory: Callable[[str], CheckpointGhostPolicy], + reference: CheckpointGhostCheckpoint, + ): + """Create the session and load the reference checkpoint. + + Args: + env: RL wrapper around a manager-based environment; its environments are split among the loaded slots. + num_slots: Largest number of slots, including the reference. + task: Task of the running environment, used to flag runs of other tasks in the checkpoint window. + checkpoint_root: Directory the checkpoint window starts in. + checkpoint_pattern: Regular expression matching checkpoint file names. + policy_factory: Builds the inference policy of a checkpoint file. + reference: Checkpoint driving slot 0. + """ + if not 2 <= num_slots <= MAX_CHECKPOINT_GHOST_SLOTS: + raise ValueError(f"Checkpoint Ghosts support 2 to {MAX_CHECKPOINT_GHOST_SLOTS} slots, got {num_slots}.") + self.layout = CheckpointGhostLayout(env.unwrapped.num_envs, num_slots) + self._env = env + self._root = checkpoint_root + self._task = normalize_task_name(task) + self._pattern = checkpoint_pattern + self._policy_factory = policy_factory + self._policies: list[CheckpointGhostPolicy | None] = [None] * num_slots + self._restart_pending = False + self._sync: CheckpointGhostSync | None = None + self._load(0, reference) + try: + self._obs = env.get_observations() + except BaseException: + self.close() + raise + # start the reference and the empty slots together from the same spawn state + self._restart_pending = True + + @property + def checkpoint_root(self) -> str: # noqa: D102 + return self._root + + def browse(self, directory: str) -> tuple[list[str], list[CheckpointGhostCheckpoint]]: # noqa: D102 + path = Path(directory) + folders, files = [], [] + for entry in path.iterdir(): + if entry.is_dir(): + if not entry.name.startswith("."): + folders.append(entry) + elif entry.is_file() and re.fullmatch(self._pattern, entry.name): + files.append(entry) + folders.sort(key=lambda p: p.stat().st_mtime, reverse=True) # newest run first + files.sort(key=lambda p: _natural_sort_key(p.name)) + return [p.name for p in folders], [ + CheckpointGhostCheckpoint(str(p.resolve()), path.name, p.name, p.stat().st_mtime) for p in files + ] + + def other_task(self, directory: str) -> str | None: # noqa: D102 + try: + manifest = json.loads((Path(directory) / RUN_MANIFEST_FILENAME).read_text(encoding="utf-8")) + task = manifest["task"] + except (OSError, ValueError, KeyError, TypeError): + return None # not a run directory, or one without a readable manifest + return task if isinstance(task, str) and normalize_task_name(task) != self._task else None + + def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: # noqa: D102 + empty = next((s for s in self.layout.slots[1:] if not s.active), None) + if empty is None: + return "All ghost slots are in use." + try: + self._load(empty.index, checkpoint) + empty.visible = True + self._resplit() + except Exception as error: # a corrupt or mismatched checkpoint must not end the session + self._policies[empty.index] = None + empty.checkpoint = None + empty.label = "" + self._resplit() + return f"Could not load {checkpoint.name}: {_describe_load_error(error)}" + return None + + def replace_ghost(self, slot_index: int, checkpoint: CheckpointGhostCheckpoint) -> str | None: # noqa: D102 + if not 1 <= slot_index < self.layout.num_slots: + return "Only a ghost slot can be changed." + slot = self.layout.slots[slot_index] + previous = (self._policies[slot_index], slot.checkpoint, slot.label) + try: + self._load(slot_index, checkpoint) + except Exception as error: # a corrupt or mismatched checkpoint must keep the ghost that was there + self._policies[slot_index], slot.checkpoint, slot.label = previous + return f"Could not load {checkpoint.name}: {_describe_load_error(error)}" + # the changed ghost starts together with the reference from the same spawn state + self._restart_pending = True + return None + + def remove_ghost(self, slot_index: int) -> None: # noqa: D102 + if slot_index < 1: + return + self._policies[slot_index] = None + self.layout.slots[slot_index].checkpoint = None + self.layout.slots[slot_index].label = "" + self._resplit() + + def env_origin_offsets(self) -> np.ndarray: # noqa: D102 + if self._sync is None: + return np.zeros((self._env.unwrapped.num_envs, 3), dtype=np.float32) + return self._sync.env_origin_offsets() + + def apply_pending_restart(self) -> None: # noqa: D102 + if not self._restart_pending: + return + self._restart_pending = False + self._obs, _ = self._env.reset() + for policy in self._policies: + if policy is not None: + policy.reset(torch.ones(self.layout.slice_size, dtype=torch.bool, device=self._env.unwrapped.device)) + + def step(self) -> None: + """Step the environment once, with each loaded slot acting on its own observations.""" + self.apply_pending_restart() + size = self.layout.slice_size + actions = torch.zeros(self._env.num_envs, self._env.num_actions, device=self._env.unwrapped.device) + for slot in self.layout.active_slots: + start = self.layout.slot_start(slot.index) + chunk = slice(start, start + size) + actions[chunk] = self._policies[slot.index](self._obs[chunk]) + self._obs, _, dones, _ = self._env.step(actions) + reference_dones = dones[:size] + for slot in self.layout.active_slots: + # A ghost resets with its reference, so a ghost that fell alone keeps its memory until then. + self._policies[slot.index].reset(reference_dones) + + def close(self) -> None: + """Detach the synchronization hooks from the environment.""" + if self._sync is not None: + self._sync.close() + self._sync = None + + def _resplit(self) -> None: + """Divide the environments among the loaded slots again and restart them from the same spawn state.""" + self.close() # restores the terrain the previous split overwrote + loaded = len(self.layout.active_slots) + if loaded >= 2: + self._sync = CheckpointGhostSync(self._env.unwrapped, self.layout.slice_size, loaded) + self._restart_pending = True + + def _load(self, slot_index: int, checkpoint: CheckpointGhostCheckpoint) -> None: + """Load a checkpoint's policy into a slot.""" + self._policies[slot_index] = self._policy_factory(checkpoint.path) + slot = self.layout.slots[slot_index] + slot.checkpoint = checkpoint + slot.label = f"{checkpoint.name} / {time.strftime('%Y-%m-%d %H:%M', time.localtime(checkpoint.modified))}" diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py new file mode 100644 index 000000000000..ddaa1bc03adc --- /dev/null +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -0,0 +1,95 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch checks and restart arguments of Checkpoint Ghosts.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +pytest.importorskip("rsl_rl") +from isaaclab.envs import ManagerBasedRLEnvCfg + +from isaaclab_rl.entrypoints.backends import play_rsl_rl + + +def _env_cfg(backend, scene=None): + cfg = ManagerBasedRLEnvCfg.__new__(ManagerBasedRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=backend)]) + cfg.scene = scene or SimpleNamespace() + return cfg + + +def test_newton_among_several_selected_viewers_is_accepted(): + backends = [SimpleNamespace(visualizer_type="viser"), SimpleNamespace(visualizer_type="newton")] + + play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), _env_cfg(backends)) + + +def test_without_newton_the_run_is_rejected(): + with pytest.raises(SystemExit, match="requires the Newton"): + play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="viser"))) + + +def test_cameras_that_render_with_ovrtx_are_rejected(): + camera = SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")) + cfg = _env_cfg(SimpleNamespace(visualizer_type="newton"), SimpleNamespace(camera=camera)) + + with pytest.raises(SystemExit, match="OVRTX"): + play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), cfg) + + +def test_the_viewer_s_own_rtx_camera_is_not_a_task_camera(): + renderer_cfg = SimpleNamespace(renderer_type="ovrtx") + scene = SimpleNamespace(viewer_camera_0_rtx=SimpleNamespace(renderer_cfg=renderer_cfg, render_on_demand=True)) + + assert not play_rsl_rl._scene_cameras_use_ovrtx(SimpleNamespace(scene=scene)) + scene.task_camera = SimpleNamespace(renderer_cfg=renderer_cfg, render_on_demand=False) + assert play_rsl_rl._scene_cameras_use_ovrtx(SimpleNamespace(scene=scene)) + + +def _slots(total: int, slots: int | None): + args = SimpleNamespace(checkpoint_ghost_slots=slots) + play_rsl_rl._resolve_ghost_slots(args, SimpleNamespace(scene=SimpleNamespace(num_envs=total))) + return args.checkpoint_ghost_slots + + +def test_the_slots_default_to_eight_capped_at_num_envs(): + assert _slots(64, None) == 8 + assert _slots(3, None) == 3 + + +def test_more_slots_than_environments_are_capped(): + assert _slots(4, 6) == 4 + assert _slots(32, 5) == 5 + + +def test_a_single_environment_cannot_be_split(): + with pytest.raises(SystemExit, match="at least 2"): + _slots(1, None) + + +def test_the_session_is_built_from_the_play_arguments(monkeypatch, tmp_path): + created = {} + + class _Session: + def __init__(self, env, **kwargs): + created.update(kwargs) + + monkeypatch.setattr(play_rsl_rl, "CheckpointGhostSession", _Session) + checkpoint = tmp_path / "run" / "model_5.pt" + checkpoint.parent.mkdir() + checkpoint.touch() + args = SimpleNamespace(checkpoint_ghost_root=None, task="Isaac-Reach-Franka") + + play_rsl_rl.create_checkpoint_ghost_session(Mock(), args, Mock(), str(checkpoint), str(tmp_path), 4) + + assert created["num_slots"] == 4 + assert created["task"] == "Isaac-Reach-Franka" + assert created["checkpoint_root"] == str(tmp_path) + assert created["reference"].name == "model_5.pt" diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py b/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py new file mode 100644 index 000000000000..7c42e2f02784 --- /dev/null +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py @@ -0,0 +1,227 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""A ghost that was just added or changed starts from the spawn state even when no step follows, such as when paused.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest +import torch + +from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostLayout + +from isaaclab_rl.entrypoints.checkpoint_ghosts import CheckpointGhostSession + +CHECKPOINT = CheckpointGhostCheckpoint("/runs/a/model_1.pt", "a", "model_1.pt", 0.0) + + +def _session(pending: bool) -> tuple[CheckpointGhostSession, Mock, Mock]: + session = object.__new__(CheckpointGhostSession) # the real constructor needs a running environment + env = Mock() + env.reset.return_value = ("observations", {}) + env.unwrapped = SimpleNamespace(device="cpu", num_envs=6) + policy = Mock() + session._env, session._sync = env, None + session._policies = [policy, None, None] + session.layout = CheckpointGhostLayout(6, 3) + session.layout.slots[0].checkpoint = CHECKPOINT + session._restart_pending = pending + return session, env, policy + + +def test_a_pending_restart_resets_the_environments_and_the_policies_once(): + session, env, policy = _session(pending=True) + + session.apply_pending_restart() + session.apply_pending_restart() + + env.reset.assert_called_once_with() + assert session._obs == "observations" + assert session._restart_pending is False + assert torch.equal(policy.reset.call_args.args[0], torch.ones(6, dtype=torch.bool)) + + +def test_without_a_pending_restart_nothing_is_reset(): + session, env, policy = _session(pending=False) + + session.apply_pending_restart() + + env.reset.assert_not_called() + policy.reset.assert_not_called() + + +def _checkpoint(name: str) -> CheckpointGhostCheckpoint: + return CheckpointGhostCheckpoint(f"/runs/{name}.pt", "run", f"{name}.pt", 0.0) + + +def _session_with_ghost(factory: Mock) -> CheckpointGhostSession: + session, _, _ = _session(pending=False) + session._policy_factory = factory + session._load(1, _checkpoint("old")) + return session + + +def test_replacing_a_ghost_loads_the_checkpoint_into_that_slot_and_restarts_together(): + factory = Mock(side_effect=["old policy", "new policy"]) + session = _session_with_ghost(factory) + + error = session.replace_ghost(1, _checkpoint("new")) + + assert error is None + assert session._policies[1] == "new policy" + assert session.layout.slots[1].checkpoint.name == "new.pt" + assert session._restart_pending is True + + +def test_a_checkpoint_that_fails_to_load_leaves_the_ghost_unchanged(): + factory = Mock(side_effect=["old policy", RuntimeError("size mismatch")]) + session = _session_with_ghost(factory) + + error = session.replace_ghost(1, _checkpoint("bad")) + + assert "bad.pt" in error and "does not fit this task" in error + assert session._policies[1] == "old policy" + assert session.layout.slots[1].checkpoint.name == "old.pt" + assert session._restart_pending is False + + +def test_the_reference_slot_cannot_be_replaced(): + session = _session_with_ghost(Mock(return_value="policy")) + + assert session.replace_ghost(0, _checkpoint("new")) is not None + + +@pytest.mark.parametrize( + ("dones", "expected"), + [ + ([False, False, False, True, False, False], [False, False, False]), # a ghost fell alone: keeps its memory + ([True, False, False, False, False, False], [True, False, False]), # the reference reset, so the ghost did too + ], + ids=["ghost-falls-alone", "reference-resets"], +) +def test_a_ghost_policy_resets_with_its_reference(dones, expected): + session, env, reference = _session(pending=False) + ghost = Mock() + session._policies = [reference, ghost, None] + session.layout.slots[1].checkpoint = CHECKPOINT # two loaded slots split the six envs into slices of three + session._obs = torch.zeros(6, 1) + env.num_envs, env.num_actions = 6, 1 + reference.return_value = torch.zeros(3, 1) + ghost.return_value = torch.zeros(3, 1) + env.step.return_value = (torch.zeros(6, 1), torch.zeros(6), torch.tensor(dones), {}) + + session.step() + + assert ghost.reset.call_args.args[0].tolist() == expected + + +def _start(monkeypatch, observations): + from isaaclab_rl.entrypoints import checkpoint_ghosts + + sync = Mock() + monkeypatch.setattr(checkpoint_ghosts, "CheckpointGhostSync", sync) + env = Mock(unwrapped=SimpleNamespace(device="cpu", step_dt=0.02, num_envs=6)) + env.get_observations.side_effect = observations + session = CheckpointGhostSession( + env, + num_slots=3, + task="Isaac-Reach-Franka", + checkpoint_root="/runs", + checkpoint_pattern=r"model_.*\.pt", + policy_factory=Mock(), + reference=CHECKPOINT, + ) + return session, sync + + +def test_a_failing_start_never_leaves_the_environment_patched(monkeypatch): + with pytest.raises(RuntimeError, match="observations"): + _start(monkeypatch, RuntimeError("observations")) + + +def test_adding_and_removing_a_ghost_splits_the_environments_again(monkeypatch): + session, sync = _start(monkeypatch, [None]) + sync.assert_not_called() # the reference alone owns every environment + assert session.layout.slice_size == 6 + + assert session.add_ghost(CHECKPOINT) is None + sync.assert_called_once_with(session._env.unwrapped, 3, 2) + assert session.layout.slice_size == 3 and session._restart_pending + + first = sync.return_value + session.remove_ghost(1) + + first.close.assert_called_once() # the old split's terrain is restored before the next one + assert sync.call_count == 1 and session._sync is None + assert session.layout.slice_size == 6 + + +def test_a_slot_is_labelled_with_the_file_name_then_its_timestamp(): + import time + + session, _, _ = _session(pending=False) + session._policy_factory = Mock() + modified = time.mktime((2026, 8, 12, 21, 14, 3, 0, 0, -1)) + checkpoint = CheckpointGhostCheckpoint("/runs/a/model_1200.pt", "a", "model_1200.pt", modified) + + session._load(1, checkpoint) + + assert session.layout.slots[1].label == "model_1200.pt / 2026-08-12 21:14" + + +def test_browsing_lists_folders_newest_first_and_only_loadable_checkpoint_files(tmp_path): + import os + + session, _, _ = _session(pending=False) + session._pattern = r"model_.*\.pt" + for name, age in (("old_run", 100), ("new_run", 0), (".hidden", 0)): + folder = tmp_path / name + folder.mkdir() + os.utime(folder, (1_000_000 - age, 1_000_000 - age)) + for name in ("model_10.pt", "model_9.pt", "notes.txt", "skrl_agent.pt"): + (tmp_path / name).touch() + + folders, files = session.browse(str(tmp_path)) + + assert folders == ["new_run", "old_run"] + assert [f.name for f in files] == ["model_9.pt", "model_10.pt"] + assert all(os.path.isabs(f.path) for f in files) + + +def test_browsing_an_unreadable_directory_raises_os_error(tmp_path): + session, _, _ = _session(pending=False) + + with pytest.raises(OSError): + session.browse(str(tmp_path / "missing")) + + +def test_a_run_of_another_task_is_named_and_a_matching_or_unknown_directory_is_not(tmp_path): + import json + + session, _, _ = _session(pending=False) + session._task = "Isaac-Reach-Franka" + for name, task in (("same", "isaac:Isaac-Reach-Franka"), ("osc", "Isaac-Reach-Franka-OSC")): + (tmp_path / name).mkdir() + (tmp_path / name / "run.json").write_text(json.dumps({"task": task})) + (tmp_path / "plain").mkdir() + (tmp_path / "bad").mkdir() + (tmp_path / "bad" / "run.json").write_text("not json") + + assert session.other_task(str(tmp_path / "osc")) == "Isaac-Reach-Franka-OSC" + assert session.other_task(str(tmp_path / "same")) is None # a namespace prefix does not make it another task + assert session.other_task(str(tmp_path / "plain")) is None + assert session.other_task(str(tmp_path / "bad")) is None + + +def test_a_load_failure_is_reported_in_one_line(): + from isaaclab_rl.entrypoints.checkpoint_ghosts import _describe_load_error + + mismatch = RuntimeError("Error(s) in loading state_dict:\n size mismatch for mlp.0.weight: copying a param") + + assert "does not fit this task" in _describe_load_error(mismatch) + assert _describe_load_error(RuntimeError("file is corrupt\nmore detail")) == "file is corrupt" diff --git a/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-change-remove.added.rst b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-change-remove.added.rst new file mode 100644 index 000000000000..a8fb6a81b3a2 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-change-remove.added.rst @@ -0,0 +1,2 @@ +* Added "Change..." and "Remove" buttons to every ghost in the Newton HUD's Checkpoint Ghosts section. "Change..." opens the + checkpoint window to replace that ghost's checkpoint in place, and "Remove" moved out of the Appearance fold. diff --git a/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud-layout.added.rst b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud-layout.added.rst new file mode 100644 index 000000000000..b9265c3a0f6d --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud-layout.added.rst @@ -0,0 +1,2 @@ +* Added a status badge for the active Checkpoint Ghosts to the Newton GL HUD header, tooltips on the Checkpoint Ghosts slot + controls, and disabled the Checkpoint Ghosts controls while the RTX view is active, with a note to switch the Renderer to OpenGL. diff --git a/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud.added.rst b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud.added.rst new file mode 100644 index 000000000000..2c05b0d8e8ab --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-hud.added.rst @@ -0,0 +1,5 @@ +* Added a Checkpoint Ghosts section to the Newton GL visualizer with a checkpoint browser window (folders, an Up button, a path box, and the last folder remembered), per-checkpoint show + toggles, and opacity and tint sliders; the tint blends a ghost toward its color and drops its native textures. +* Added a Visualizer docs link to the Newton GL and Newton RTX HUD. +* Added a Visible Envs slider to the Newton GL and Newton RTX viewers and + :meth:`~isaaclab_visualizers.newton.NewtonVisualizer.set_visible_env_count`. diff --git a/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-instancer-capacity.fixed.rst b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-instancer-capacity.fixed.rst new file mode 100644 index 000000000000..9c13ef27ac56 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-instancer-capacity.fixed.rst @@ -0,0 +1,2 @@ +* Fixed the Newton GL viewer failing every frame with an instance capacity error when more environments became + visible after the viewer started, which froze the Checkpoint Ghosts view after the second ghost was added. diff --git a/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-offer.added.rst b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-offer.added.rst new file mode 100644 index 000000000000..87da944bbc30 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-offer.added.rst @@ -0,0 +1,4 @@ +* Added a greyed-out Checkpoint Ghosts section to the Newton HUD of ``isaaclab play`` runs that do not pass + ``--checkpoint_ghosts``. It explains the checkpoint visualization and that the flag is needed because the simulation + allocates extra environments for it. With the flag on, the section shows how many of the simulated + environments are drawn. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py new file mode 100644 index 000000000000..920a243ff8a7 --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py @@ -0,0 +1,385 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Newton GL HUD section, checkpoint discovery window, and ghost tinting for Checkpoint Ghosts.""" + +from __future__ import annotations + +import os +import time +from typing import Any + +import numpy as np +import warp as wp + +from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostController + +SECTION_TOOLTIP = ( + "Checkpoint visualization: replays other checkpoints of this task from the same starts as translucent copies," + " to compare their behavior." +) +"""Tooltip of the Checkpoint Ghosts section header, shown whether or not the feature is enabled.""" + +MAX_GHOST_OPACITY = 1.0 +"""Highest value of the opacity slider.""" + +OPAQUE_LIMIT = 0.998 +"""Highest opacity written to the model. Newton re-batches shapes at 0.999 and above, so the slider's top stops here.""" + + +def display_opacity(slider: float) -> float: + """Return the opacity Newton draws for a slider value. + + The curve eases toward opaque, so the slider's upper half looks nearly solid instead of staying see-through, and + its top is just under the level where Newton switches a shape to its opaque path. + """ + return min(1.0 - (1.0 - float(slider)) ** 2, OPAQUE_LIMIT) + + +TEXTURE_ENABLE = 3 +"""Component of a Newton instance material, ``(roughness, metallic, checker, texture)``, that enables the texture.""" + +METALLIC = 1 +"""Component of a Newton instance material that holds the metallic factor.""" + + +class NewtonCheckpointGhostPanel: + """Draws the Checkpoint Ghosts HUD for a :class:`~isaaclab.visualizers.checkpoint_ghost.CheckpointGhostController`. + + The panel owns the checkpoint discovery window and tints each ghost slot's shapes through the Newton model's + per-shape color and opacity arrays, which the viewer re-reads every frame. A ghost at full tint also drops its + mesh textures and metallic shading, so no native material color shows through. + """ + + def __init__(self, controller: CheckpointGhostController): + """Create the panel. + + Args: + controller: Playback-loop side of Checkpoint Ghosts. + """ + self.controller = controller + self._window_open = False + self._replacing: int | None = None + """Ghost slot the checkpoint window is choosing a replacement for, or None when it fills a free slot.""" + self._directory: str | None = None + """Directory the checkpoint window shows; it keeps the last one across openings and selections.""" + self._folders: list[str] = [] + self._other_tasks: dict[str, str] = {} + """Task of each listed folder (and of the current one, under ``""``) that is a run of another task.""" + self._files: list[CheckpointGhostCheckpoint] = [] + self._browse_error = "" + self._message = "" + self._base_colors: np.ndarray | None = None + self._base_opacity: np.ndarray | None = None + self._tint_signature: tuple | None = None + self._shown_signature: tuple | None = None + self._native_materials: dict[int, tuple[Any, np.ndarray]] = {} + self._material_signature: tuple | None = None + + @property + def layout(self): + """Environment-to-slot layout of the controller.""" + return self.controller.layout + + def draw(self, imgui: Any, rtx_view: bool = False, owner: Any = None) -> None: + """Draw the Checkpoint Ghosts section and, when open, the checkpoint discovery window. + + Args: + imgui: The ImGui module. + rtx_view: Whether the window shows the RTX view, where the controls are disabled. + owner: The visualizer, used to report how many environments are drawn. + """ + imgui.set_next_item_open(False, imgui.Cond_.appearing) + ghosts_open = imgui.collapsing_header("Checkpoint Ghosts") + if imgui.is_item_hovered(): + imgui.set_tooltip(SECTION_TOOLTIP) + if ghosts_open: + imgui.separator() + layout = self.layout + if rtx_view: + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(0.55, 0.7, 0.95, 0.85)) + imgui.text_wrapped("RTX: switch the Renderer to OpenGL to use Checkpoint Ghosts.") + imgui.pop_style_color() + imgui.begin_disabled() + total = layout.num_envs + loaded = len(layout.active_slots) + if owner is not None: + per_slot = owner.visible_env_count + shown = sum(slot.shown for slot in layout.slots) + imgui.text(f"Showing {per_slot * shown}/{total} envs: {per_slot} per slot x {shown} ckpts") + else: + imgui.text(f"Simulating {total} envs: {layout.slice_size} per slot x {loaded} ckpts") + if imgui.is_item_hovered(): + imgui.set_tooltip( + f"The {total} envs are split evenly among the checkpoints you load ({layout.slice_size} each now)," + " so adding or removing one resizes every slot and restarts. Lower Visible Envs in Playback to draw" + " fewer per checkpoint." + ) + for slot in layout.slots: + if slot.active: + self._draw_slot(imgui, slot) + empty = sum(not slot.active for slot in layout.slots[1:]) + if not empty: + imgui.begin_disabled() + if imgui.button(f"Add Checkpoint... ({empty} free)"): + self._open_window() + if imgui.is_item_hovered(imgui.HoveredFlags_.allow_when_disabled): + imgui.set_tooltip("Load another checkpoint of this task into a free slot") + if not empty: + imgui.end_disabled() + if self._message: + imgui.text_wrapped(self._message) + if rtx_view: + imgui.end_disabled() + if self._window_open and not rtx_view: + self._draw_window(imgui) + + def apply_tint(self, model: Any) -> None: + """Write each slot's tint color and opacity to the shapes of its worlds when anything changed.""" + tint_signature = ( + self._layout_signature(), + *((slot.shown, slot.opacity, slot.tint, slot.color) for slot in self.layout.slots), + ) + if tint_signature == self._tint_signature or model.shape_color is None or model.shape_world is None: + return + self._tint_signature = tint_signature + if self._base_colors is None: + self._base_colors = model.shape_color.numpy().copy() + opacity = getattr(model, "shape_opacity", None) + self._base_opacity = None if opacity is None else opacity.numpy().copy() + worlds = model.shape_world.numpy() + slot_of_shape = self.layout.slot_of_env(worlds) + colors = self._base_colors.copy() + opacity = np.ones(len(worlds), dtype=np.float32) if self._base_opacity is None else self._base_opacity.copy() + for slot in self.layout.slots[1:]: + if slot.shown: + mask = slot_of_shape == slot.index + colors[mask] = self._base_colors[mask] * (1.0 - slot.tint) + np.asarray(slot.color) * slot.tint + opacity[mask] = display_opacity(slot.opacity) + model.shape_color = wp.array(colors, dtype=wp.vec3, device=model.shape_color.device) + model.shape_opacity = wp.array(opacity, dtype=wp.float32, device=model.shape_color.device) + + def apply_materials(self, viewer: Any) -> None: + """Drop the native textures of tinted ghosts and fade their metallic shading out as the tint rises. + + Textures multiply the shape color and switch on or off in Newton's shader, so keeping them for a nearly full + tint made the last step to 1.0 jump. Dropping them for any tint above 0 keeps the whole slider smooth. + + Newton rebuilds its shape batches, and with them the native materials, whenever the visible worlds change, so + the native materials are re-read from every batch the panel has not seen yet. + + Args: + viewer: Newton GL viewer whose shape batches are modified. + """ + batches = getattr(viewer, "_shape_instances", None) + if not batches: + return + flat = tuple((slot.tint if slot.shown and slot.tint > 0.0 else 0.0) for slot in self.layout.slots) + signature = (flat, self._layout_signature(), tuple(id(batch) for batch in batches.values())) + if signature == self._material_signature: + return + self._material_signature = signature + known = {id(batch) for batch in batches.values()} + self._native_materials = {k: v for k, v in self._native_materials.items() if k in known} + for batch in batches.values(): + if id(batch) not in self._native_materials: + self._native_materials[id(batch)] = (batch, batch.materials.numpy().copy()) + native = self._native_materials[id(batch)][1] + worlds = batch.worlds.numpy() + slot_of_instance = self.layout.slot_of_env(worlds) + materials = native.copy() + for slot in self.layout.slots[1:]: + if flat[slot.index]: + mask = slot_of_instance == slot.index + materials[mask, TEXTURE_ENABLE] = 0.0 + materials[mask, METALLIC] = native[mask, METALLIC] * (1.0 - flat[slot.index]) + batch.materials = wp.array(materials, dtype=wp.vec4, device=batch.materials.device) + # Newton uploads instance materials only while the model is flagged as changed + viewer.model_changed = True + + def _layout_signature(self) -> tuple: + """Identify how environments map to slots, which changes whenever a checkpoint is loaded or unloaded.""" + return (self.layout.slice_size, tuple(slot.index for slot in self.layout.active_slots)) + + def consume_slots_changed(self) -> bool: + """Return whether slots were filled, emptied, or shown/hidden since the last call.""" + signature = (self._layout_signature(), tuple(slot.shown for slot in self.layout.slots)) + changed = signature != self._shown_signature + self._shown_signature = signature + return changed + + def _draw_slot(self, imgui: Any, slot: Any) -> None: + imgui.push_id(slot.index) + if slot.index == 0: + # The reference keeps its own colors and is always shown, so it gets an outline, not a swatch or checkbox. + corner = imgui.get_cursor_screen_pos() + imgui.dummy(imgui.ImVec2(14, 14)) + imgui.get_window_draw_list().add_rect( + corner, + imgui.ImVec2(corner.x + 14, corner.y + 14), + imgui.get_color_u32(imgui.ImVec4(0.85, 0.85, 0.85, 1.0)), + 0.0, + 0, + 1.5, + ) + if imgui.is_item_hovered(): + imgui.set_tooltip("The reference: drawn in its own colors, opaque, and always shown") + else: + color = slot.color if slot.color is not None else (0.8, 0.8, 0.8) + imgui.color_button( + "##swatch", imgui.ImVec4(*color, 1.0), imgui.ColorEditFlags_.no_tooltip, imgui.ImVec2(14, 14) + ) + imgui.same_line() + role = "Reference" if slot.index == 0 else f"Ghost {slot.index}" + imgui.text(f"{role}: {slot.label}") + if slot.index > 0: + _, slot.visible = imgui.checkbox("##show", slot.visible) + if imgui.is_item_hovered(): + imgui.set_tooltip("Show or hide this checkpoint") + imgui.same_line() + if imgui.button("Change..."): + self._open_window(slot.index) + if imgui.is_item_hovered(): + imgui.set_tooltip("Replace this ghost's checkpoint with another one") + imgui.same_line() + if imgui.button("Remove"): + self.controller.remove_ghost(slot.index) + self._message = "" + if imgui.is_item_hovered(): + imgui.set_tooltip("Unload this checkpoint and free its slot") + imgui.set_next_item_open(False, imgui.Cond_.appearing) + if imgui.tree_node("Appearance"): + _, slot.opacity = imgui.slider_float("Opacity", slot.opacity, 0.1, MAX_GHOST_OPACITY) + if imgui.is_item_hovered(): + imgui.set_tooltip("How solid this ghost looks. 1.0 is nearly opaque") + _, slot.tint = imgui.slider_float("Tint", slot.tint, 0.0, 1.0) + if imgui.is_item_hovered(): + imgui.set_tooltip( + "Blends toward the ghost color. Any tint above 0 drops native textures," + " and metal shading fades out" + ) + imgui.tree_pop() + imgui.pop_id() + + def _open_window(self, replacing: int | None = None) -> None: + """Open the checkpoint window, to fill a free slot or, with ``replacing``, to change that ghost's checkpoint.""" + self._replacing = replacing + self._window_open = True + self._refresh() + + def _refresh(self) -> None: + """List the window's directory again.""" + if self._directory is None: + self._directory = self.controller.checkpoint_root + try: + self._folders, self._files = self.controller.browse(self._directory) + self._browse_error = "" + self._other_tasks = { + name: task + for name, task in ( + ("", self.controller.other_task(self._directory)), + *((f, self.controller.other_task(os.path.join(self._directory, f))) for f in self._folders), + ) + if task is not None + } + except OSError as error: + self._folders, self._files, self._other_tasks = [], [], {} + self._browse_error = f"Cannot read this folder: {error.strerror or error}" + + def _go(self, directory: str) -> None: + self._directory = os.path.abspath(directory) + self._refresh() + + def _draw_window(self, imgui: Any) -> None: + """Draw the checkpoint window: a folder browser that starts in the experiment's log directory.""" + imgui.set_next_window_pos(imgui.ImVec2(400, 60), imgui.Cond_.first_use_ever) + imgui.set_next_window_size(imgui.ImVec2(520, 420), imgui.Cond_.first_use_ever) + expanded, self._window_open = imgui.begin("Choose Checkpoint", self._window_open) + if expanded: + if self._replacing is not None: + imgui.text(f"Replacing Ghost {self._replacing}") + if imgui.button("Up"): + self._go(os.path.dirname(self._directory)) + if imgui.is_item_hovered(): + imgui.set_tooltip("Go to the parent folder") + imgui.same_line() + if imgui.button("Refresh"): + self._refresh() + if imgui.is_item_hovered(): + imgui.set_tooltip("List this folder again, such as for checkpoints training just saved") + imgui.same_line() + if imgui.button("Experiment Folder"): + self._go(self.controller.checkpoint_root) + if imgui.is_item_hovered(): + imgui.set_tooltip("Return to the folder this task's runs are saved in") + imgui.set_next_item_width(-1) + submitted, text = imgui.input_text("##path", self._directory, imgui.InputTextFlags_.enter_returns_true) + if imgui.is_item_hovered(): + imgui.set_tooltip("Type a folder anywhere on this machine and press Enter") + if submitted: + self._go(os.path.expanduser(text)) + imgui.separator() + if self._browse_error: + imgui.text_wrapped(self._browse_error) + elif not self._folders and not self._files: + imgui.text_wrapped("No folders or checkpoint files here.") + if "" in self._other_tasks: + imgui.text_colored( + imgui.ImVec4(1.0, 0.8, 0.2, 1.0), + f"This run is {self._other_tasks['']}, not this task. Its checkpoints will not fit.", + ) + for folder in self._folders: + other = self._other_tasks.get(folder) + if other is not None: + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(0.55, 0.55, 0.55, 1.0)) + clicked, _ = imgui.selectable(f"{folder}/" + (f" ({other})" if other else "") + "##folder", False) + if other is not None: + imgui.pop_style_color() + if imgui.is_item_hovered(): + imgui.set_tooltip("A run of a different task, so its checkpoints will not fit this policy") + if clicked: + self._go(os.path.join(self._directory, folder)) + break # the listing just changed + loaded = {slot.checkpoint.path for slot in self.layout.slots if slot.active} + for checkpoint in self._files: + taken = checkpoint.path in loaded + stamp = time.strftime("%Y-%m-%d %H:%M", time.localtime(checkpoint.modified)) + label = f"{checkpoint.name} {stamp}{' (loaded)' if taken else ''}##{checkpoint.path}" + clicked, _ = imgui.selectable(label, taken) + if imgui.is_item_hovered(): + imgui.set_tooltip( + "Already loaded" if taken else "Load this checkpoint as a tinted ghost over the reference" + ) + if clicked and not taken: + if self._replacing is None: + error = self.controller.add_ghost(checkpoint) + else: + error = self.controller.replace_ghost(self._replacing, checkpoint) + self._message = error or "" + if error is None: + self._window_open = False + imgui.end() + + +def draw_checkpoint_ghost_offer(imgui: Any) -> None: + """Draw the greyed-out Checkpoint Ghosts section of a play run that started without ``--checkpoint_ghosts``. + + Args: + imgui: The ``imgui`` module. + """ + imgui.set_next_item_open(False, imgui.Cond_.appearing) + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(0.6, 0.6, 0.6, 1.0)) + ghosts_open = imgui.collapsing_header("Checkpoint Ghosts (not enabled)") + imgui.pop_style_color() + if imgui.is_item_hovered(): + imgui.set_tooltip(SECTION_TOOLTIP) + if ghosts_open: + imgui.separator() + imgui.push_style_color(imgui.Col_.text, imgui.ImVec4(0.6, 0.6, 0.6, 1.0)) + imgui.text_wrapped( + "Not enabled. Add --checkpoint_ghosts to play to use it." + " It needs extra environments, so plain play skips it." + ) + imgui.pop_style_color() diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index 0dc3af6e30da..8f9d701989c4 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -51,12 +51,14 @@ from isaaclab.utils.math import quat_apply, quat_from_matrix, quat_mul from isaaclab.visualizers.base_visualizer import _VISUALIZER_MAX_TILES as MAX_TILED_ENVS from isaaclab.visualizers.base_visualizer import BaseVisualizer +from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostController from isaaclab.visualizers.visualizer_cfg import PerspectiveCameraCfg, WindowCfg from isaaclab_visualizers.desktop_entry import write_desktop_entry from isaaclab_visualizers.newton.newton_overlay_meshes import OverlayMeshPublisher from isaaclab_visualizers.newton.newton_visualization_markers import render_newton_visualization_markers +from .newton_checkpoint_ghosts import NewtonCheckpointGhostPanel, draw_checkpoint_ghost_offer from .newton_key_event_source import NewtonKeyEventSource from .newton_rtx_appearance import SKY_TEXTURES, RtxAppearance @@ -181,6 +183,8 @@ class NewtonViewerGL(ViewerGL): keyboard_frame_hook: Callable[[], object] | None = None """Called after every frame while a :class:`NewtonKeyEventSource` listens, to track ImGui keyboard ownership.""" _owner = None + _checkpoint_ghost_panel = None + _checkpoint_ghost_offered = False _show_stats = False """Whether the performance and model statistics overlay in the top-right corner is open.""" image_matches_camera = False @@ -307,12 +311,14 @@ def _patch_viewer_panel(self) -> None: Section order: 1. **Simulation** (open) — physics backend, model info, playback and environment controls. - 2. **Live Plots** (closed) — injected when :meth:`~NewtonGLVisualizer.add_live_plots` + 2. **Checkpoint Ghosts** (closed) — added by :meth:`~NewtonGLVisualizer.attach_checkpoint_ghosts`; it decides + which environments the window shows. + 3. **Live Plots** (closed) — injected when :meth:`~NewtonGLVisualizer.add_live_plots` is called. - 3. **Model Overlays** and **Visualization Markers** (closed) — debug visibility controls. - 4. **Rendering Options** (open) — VSync, the renderer and camera source, and renderer-specific options. - 5. **Controls** (closed) — camera keyboard reference. - 6. **Selection API** (closed) — Newton's selection panel. + 4. **Model Overlays** and **Visualization Markers** (closed) — debug visibility controls. + 5. **Rendering Options** (open) — VSync, the renderer and camera source, and renderer-specific options. + 6. **Controls** (closed) — camera keyboard reference. + 7. **Selection API** (closed) — Newton's selection panel. The top-level Newton ``Pause / Step`` row is suppressed; pause/resume is handled by the IsaacLab controls inside **Simulation**. @@ -368,6 +374,16 @@ def _render_left_panel(_g=gui): if viewer._has_environment_controls(): viewer._render_environment_controls(imgui) + # --- Checkpoint Ghosts ---------------------------------------------- + if viewer._checkpoint_ghost_panel is not None: + viewer._checkpoint_ghost_panel.draw( + imgui, + rtx_view=viewer._owner is not None and viewer._owner.rtx_rendering, + owner=viewer._owner, + ) + elif viewer._checkpoint_ghost_offered: + draw_checkpoint_ghost_offer(imgui) + # --- Live Plots ------------------------------------------------- live_plots_cb = viewer._live_plots_callback if live_plots_cb is not None: @@ -467,10 +483,10 @@ def _has_environment_controls(self) -> bool: def _render_environment_controls(self, imgui) -> None: """Render the visible-environment count slider.""" owner = self._owner - imgui.text("Visible Envs") + imgui.text("Visible Envs (per slot)" if owner._checkpoint_ghost_panel is not None else "Visible Envs") changed, new_count = imgui.slider_int("##VisibleEnvs", owner.visible_env_count, 1, owner.visible_env_limit) if changed: - owner.set_visible_env_count(new_count) + owner.set_visible_env_count(new_count, defer=True) if imgui.is_item_hovered(): imgui.set_tooltip("Number of environments drawn in the viewer; simulation is unaffected") if getattr(owner, "rtx_rendering", False): @@ -772,10 +788,13 @@ class NewtonVisualizerBase(BaseVisualizer): _rtx_arrows_pending = False _rtx_overlay_flags: tuple | None = None _rtx_visibility_limited = False + _visible_worlds_pending = False + """Whether the Visible Envs slider changed and the next frame must apply it before logging state.""" _rtx_switch: str | None = None """``"requested"`` once the HUD asked for RTX and showed the wait message, ``"loading"`` until its first frame.""" _borrowing_view = False """Whether an off-screen capture has swapped the displayed view, so the window controls must not act on it.""" + _checkpoint_ghost_panel = None _rtx_appearance: RtxAppearance | None = None # The OpenGL window overrides these; the standalone RTX window has no OpenGL view to switch to. @@ -932,7 +951,7 @@ def _draw_rtx_unavailable(self, imgui) -> None: hover_tooltip( imgui, "RTX adds an OVRTX camera, which costs some startup time and a little speed, so it is opt-in" ) - hud_note(imgui, "Launch with --viz newton_rtx to enable the RTX toggle.") + hud_note(imgui, "Use --viz newton_rtx to enable RTX toggle.") def _draw_streaming_view_controls(self, imgui) -> None: """Choose one declared display source without reading the other sensors.""" @@ -950,7 +969,7 @@ def _draw_streaming_view_controls(self, imgui) -> None: self.set_rtx_rendering(False) if imgui.is_item_hovered(imgui.HoveredFlags_.allow_when_disabled): imgui.set_tooltip( - "Fast rasterizer with visual overlays and markers" + "Fast rasterizer with visual overlays, markers, and Checkpoint Ghosts" if not sensor else "A scene sensor is rendered by its own renderer. This applies to the free camera" ) @@ -1638,6 +1657,10 @@ def __init__(self, cfg: VisualizerCfg): self._cfg_visible_env_ids: list[int] | None = None self._visible_env_count: int | None = None self._num_envs = 0 + self._checkpoint_ghost_panel: NewtonCheckpointGhostPanel | None = None + self._base_world_offsets: np.ndarray | None = None + """World offsets without the Checkpoint Ghost overlay, which the overlay is added to every frame it changes.""" + """Checkpoint Ghost offsets last given to the OVRTX view, to skip rewriting poses when they are unchanged.""" # ------------------------------------------------------------------ # GL lifecycle @@ -1760,6 +1783,17 @@ def _render_frame(self) -> None: try: if appearance is not None and self.rtx_rendering and appearance.available and appearance.poll(): self.current_image_view.invalidate() # a sky finished downloading, whether or not its panel is open + if self._visible_worlds_pending: + self._visible_worlds_pending = False + self._apply_visible_worlds() + if self._checkpoint_ghost_panel is not None: + self._checkpoint_ghost_panel.apply_tint(self.backend.model) + if self._checkpoint_ghost_panel.consume_slots_changed(): + self._apply_visible_worlds() + if viewer.is_training_paused(): + # No simulation step runs while paused, so a ghost added now is reset to its spawn pose here. + self._checkpoint_ghost_panel.controller.apply_pending_restart() + self._checkpoint_ghost_panel.apply_materials(viewer) viewer.begin_frame(self._sim_time) except BaseException: if self._rtx_switch == "loading": # the switch failed before the first RTX frame @@ -1945,29 +1979,65 @@ def set_rtx_rendering(self, enabled: bool) -> None: # Only a perspective view continues from the viewer's pose; a scene sensor keeps the task's own placement. self._select_camera(target, keep_pose=self._image_views[target].camera is None) + def offer_checkpoint_ghosts(self) -> None: + """Show a greyed-out Checkpoint Ghosts section that says the feature needs ``--checkpoint_ghosts``.""" + if self._viewer is not None: + self._viewer._checkpoint_ghost_offered = True + + def attach_checkpoint_ghosts( + self, + controller: CheckpointGhostController, + ) -> None: + """Show the Checkpoint Ghosts HUD section for a playback loop that drives several checkpoints. + + Only environments of slots with a checkpoint are visible, and each ghost slot is tinted and overlaid on + the reference slot. The visible-environment slider then counts environments per slot. + + Args: + controller: Playback-loop side of Checkpoint Ghosts. + """ + self._checkpoint_ghost_panel = NewtonCheckpointGhostPanel(controller) + self._visible_env_count = None # follow the per-slot limit, which changes with the loaded checkpoints + if self._viewer is not None: + self._viewer._checkpoint_ghost_panel = self._checkpoint_ghost_panel + self._apply_visible_worlds() + @property def visible_env_limit(self) -> int: - """Largest value of the visible-environment count: the environments the cfg allows, else all.""" + """Largest value of the visible-environment count: environments per slot with Checkpoint Ghosts, else all.""" + if self._checkpoint_ghost_panel is not None: + return self._checkpoint_ghost_panel.layout.slice_size return len(self._cfg_visible_env_ids) if self._cfg_visible_env_ids is not None else self._num_envs @property def visible_env_count(self) -> int: - """Number of environments currently shown.""" + """Number of environments currently shown (per slot with Checkpoint Ghosts).""" if self._visible_env_count is not None: return min(self._visible_env_count, self.visible_env_limit) return self.visible_env_limit - def set_visible_env_count(self, count: int) -> None: - """Show only the first ``count`` environments. + def set_visible_env_count(self, count: int, *, defer: bool = False) -> None: + """Show only the first ``count`` environments (per slot with Checkpoint Ghosts). Args: count: Number of environments to show, clamped to ``[1, visible_env_limit]``. + defer: Apply the change at the start of the next frame instead of now. The HUD uses this because its + widgets run after the frame's state was logged but before the scene is drawn, so shapes rebuilt + there would be drawn once without poses. """ - self._visible_env_count = max(1, min(int(count), self.visible_env_limit)) - self._apply_visible_worlds() + count = max(1, min(int(count), self.visible_env_limit)) + # Showing every environment of a slot keeps following the limit, which Checkpoint Ghosts change as slots resize. + self._visible_env_count = None if count >= self.visible_env_limit else count + if defer: + self._visible_worlds_pending = True + else: + self._apply_visible_worlds() def _select_visible_env_ids(self) -> list[int] | None: - """Resolve the environments to show from the cfg and the HUD count.""" + """Resolve the environments to show from the cfg, the HUD count, and the Checkpoint Ghost slots.""" + panel = self._checkpoint_ghost_panel + if panel is not None: + return panel.layout.visible_env_ids(self.visible_env_count) if self._visible_env_count is None: return self._cfg_visible_env_ids ids = self._cfg_visible_env_ids if self._cfg_visible_env_ids is not None else range(self._num_envs) @@ -1999,15 +2069,29 @@ def _add_viewer_camera(self, sim: SimulationContext) -> None: self._image_views.append(view) def _apply_visible_worlds(self) -> None: - """Apply the visible environments.""" + """Apply the visible environments and, with Checkpoint Ghosts, overlay each ghost on the reference.""" if self._viewer is None: return self._env_ids = self._select_visible_env_ids() self._drop_shape_instancers() self._viewer.set_visible_worlds(self._env_ids) self._viewer.set_world_offsets(self.cfg.backend.world_spacing) + world_offsets = getattr(self._viewer, "world_offsets", None) + self._base_world_offsets = None if world_offsets is None else world_offsets.numpy().copy() + self._apply_ghost_offsets() self._apply_rtx_visible_envs() + def _apply_ghost_offsets(self) -> None: + """Overlay each ghost on the reference by the offset between their environment origins.""" + panel, viewer = self._checkpoint_ghost_panel, self._viewer + if panel is None or self._base_world_offsets is None or getattr(viewer, "world_offsets", None) is None: + return + controller = panel.controller + ghost = controller.env_origin_offsets() + viewer.world_offsets = wp.array( + self._base_world_offsets + ghost, dtype=wp.vec3, device=viewer.world_offsets.device + ) + def _apply_rtx_visible_envs(self) -> None: """Hide the environments outside the visible set in the OVRTX viewer camera's scene.""" index = self.rtx_view_index diff --git a/source/isaaclab_visualizers/test/test_newton_adapter.py b/source/isaaclab_visualizers/test/test_newton_adapter.py index 39d2ec0b27d3..09db7f28a232 100644 --- a/source/isaaclab_visualizers/test/test_newton_adapter.py +++ b/source/isaaclab_visualizers/test/test_newton_adapter.py @@ -741,6 +741,7 @@ def test_newton_visualizer_hard_reset_rebinds_viewer_model(monkeypatch, picking) cfg = visualizer.newton_cfg = NewtonBackendCfg(physics_cfg=object(), device="cpu") visualizer._env_ids = visualizer._cfg_visible_env_ids = [1, 3] visualizer._visible_env_count = None + visualizer._checkpoint_ghost_panel = None visualizer._picking_enabled = picking visualizer.cfg.backend.world_spacing = (2.0, 0.0, 0.0) visualizer.cfg.backend.show_contacts = True @@ -1453,6 +1454,21 @@ def test_a_scene_sensor_view_is_not_an_opengl_or_rtx_view(): assert visualizer.sensor_view_selected is selected +def test_ghost_offsets_overlay_each_ghost_by_its_environment_origin(): + viewer = SimpleNamespace(world_offsets=wp.zeros(3, dtype=wp.vec3, device="cpu")) + visualizer = _make_newton_visualizer(viewer) + controller = SimpleNamespace( + env_origin_offsets=lambda: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]], dtype=np.float32) + ) + visualizer._checkpoint_ghost_panel = SimpleNamespace(controller=controller) + visualizer._base_world_offsets = np.tile(np.array([0, 2, 0], dtype=np.float32), (3, 1)) + + visualizer._apply_ghost_offsets() + + assert viewer.world_offsets.numpy()[:, 0].tolist() == [0.0, 1.0, 1.0] + assert viewer.world_offsets.numpy()[:, 1].tolist() == [2.0, 2.0, 2.0] + + def test_a_mesh_logged_to_the_rtx_view_refreshes_its_cached_image(): from isaaclab_visualizers.newton.newton_visualizer import NewtonGLVisualizer @@ -1521,3 +1537,20 @@ def get_or_create_backend(cfg, camera=None): assert [cfg.source for cfg in created] == ["/World/viewer_camera_1_rtx"] assert visualizer.rtx_view_index == 1 + + +def test_a_deferred_visible_env_change_waits_for_the_next_frame_and_an_immediate_one_does_not(): + visualizer = _make_newton_visualizer(SimpleNamespace()) + visualizer._num_envs, visualizer._cfg_visible_env_ids, visualizer._visible_env_count = 8, None, None + visualizer._checkpoint_ghost_panel = None + visualizer._apply_visible_worlds = Mock() + + visualizer.set_visible_env_count(3, defer=True) + + visualizer._apply_visible_worlds.assert_not_called() + assert visualizer._visible_worlds_pending and visualizer.visible_env_count == 3 + + visualizer.set_visible_env_count(8) + + visualizer._apply_visible_worlds.assert_called_once() + assert visualizer.visible_env_count == 8 diff --git a/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py new file mode 100644 index 000000000000..dfbc44b63858 --- /dev/null +++ b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py @@ -0,0 +1,428 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Checkpoint Ghosts slot layout and the tint the Newton GL panel writes to ghost shapes.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import Mock + +import numpy as np +import pytest +import warp as wp +from isaaclab_visualizers.newton.newton_checkpoint_ghosts import NewtonCheckpointGhostPanel, display_opacity + +from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostLayout + +pytestmark = [pytest.mark.unit] + +SLICE_SIZE = 2 +POOL = 6 +CHECKPOINT = CheckpointGhostCheckpoint(path="/runs/a/model_1.pt", run="a", name="model_1.pt", modified=0.0) + + +def _panel(layout: CheckpointGhostLayout) -> NewtonCheckpointGhostPanel: + return NewtonCheckpointGhostPanel(SimpleNamespace(layout=layout)) + + +def _model() -> SimpleNamespace: + """Model with one shared static shape and one visible shape per world of three slots.""" + worlds = np.array([-1] + list(range(3 * SLICE_SIZE))) + return SimpleNamespace( + shape_world=wp.array(worlds, dtype=wp.int32, device="cpu"), + shape_color=wp.array(np.full((len(worlds), 3), 0.5), dtype=wp.vec3, device="cpu"), + shape_opacity=None, + ) + + +def test_only_slots_with_a_checkpoint_are_visible_and_limited_per_slot() -> None: + layout = CheckpointGhostLayout(POOL, 3) + layout.slots[0].checkpoint = CHECKPOINT + layout.slots[2].checkpoint = CHECKPOINT + + # two loaded slots split the six envs into slices of three; the second loaded slot starts at env 3 + assert layout.visible_env_ids(1) == [0, 3] + assert layout.visible_env_ids(99) == [0, 1, 2, 3, 4, 5] + + layout.slots[2].visible = False + + assert layout.visible_env_ids(2) == [0, 1] + + +def test_the_environments_are_split_evenly_among_the_loaded_slots() -> None: + layout = CheckpointGhostLayout(32, 8) + layout.slots[0].checkpoint = CHECKPOINT + assert layout.slice_size == 32 + + layout.slots[1].checkpoint = CHECKPOINT + assert layout.slice_size == 16 + + layout.slots[5].checkpoint = CHECKPOINT + assert layout.slice_size == 10 # 32 // 3; two envs belong to no slot + assert layout.slot_of_env(np.array([-1, 0, 9, 10, 29, 30, 31])).tolist() == [-1, 0, 0, 1, 5, -1, -1] + + layout.slots[1].checkpoint = None + assert layout.slice_size == 16 + assert layout.slot_of_env(np.array([0, 15, 16, 31])).tolist() == [0, 0, 5, 5] + + +def test_tint_applies_to_active_ghost_worlds_only_and_follows_slot_changes() -> None: + layout = CheckpointGhostLayout(POOL, 3) + layout.slots[0].checkpoint = CHECKPOINT + layout.slots[1].checkpoint = CHECKPOINT + layout.slots[1].opacity = 0.4 + layout.slots[1].tint = 1.0 + panel, model = _panel(layout), _model() + + panel.apply_tint(model) + + colors, opacity = model.shape_color.numpy(), model.shape_opacity.numpy() + ghost_shapes = [4, 5, 6] # worlds 3 to 5: two loaded slots split the six envs into slices of three + assert np.allclose(colors[ghost_shapes], layout.slots[1].color) + assert np.allclose(opacity[ghost_shapes], display_opacity(0.4)) + untouched = [0, 1, 2, 3] + assert np.allclose(colors[untouched], 0.5) + assert np.allclose(opacity[untouched], 1.0) + + layout.slots[1].checkpoint = None + panel.apply_tint(model) + assert np.allclose(model.shape_color.numpy(), 0.5) + assert np.allclose(model.shape_opacity.numpy(), 1.0) + + +def test_slot_changes_are_reported_once() -> None: + layout = CheckpointGhostLayout(POOL, 3) + panel = _panel(layout) + assert panel.consume_slots_changed() + assert not panel.consume_slots_changed() + + layout.slots[1].checkpoint = CHECKPOINT + + assert panel.consume_slots_changed() + + +def test_tint_strength_blends_between_native_and_ghost_color() -> None: + layout = CheckpointGhostLayout(POOL, 3) + layout.slots[0].checkpoint = CHECKPOINT + layout.slots[1].checkpoint = CHECKPOINT + layout.slots[1].tint = 0.5 + panel, model = _panel(layout), _model() + + panel.apply_tint(model) + + ghost_shape = 4 + expected = 0.5 * 0.5 + 0.5 * np.asarray(layout.slots[1].color) + assert np.allclose(model.shape_color.numpy()[ghost_shape], expected) + + layout.slots[1].tint = 0.0 + panel.apply_tint(model) + assert np.allclose(model.shape_color.numpy()[ghost_shape], 0.5) + + +def test_a_changed_ghost_color_is_written_even_when_nothing_else_changed() -> None: + layout = CheckpointGhostLayout(POOL, 3) + layout.slots[0].checkpoint = CHECKPOINT + layout.slots[1].checkpoint = CHECKPOINT + layout.slots[1].tint = 1.0 + panel, model = _panel(layout), _model() + panel.apply_tint(model) + + layout.slots[1].color = (0.0, 0.0, 1.0) + panel.apply_tint(model) + + assert np.allclose(model.shape_color.numpy()[4], (0.0, 0.0, 1.0)) + + +def _viewer_with_batch() -> SimpleNamespace: + """Viewer with one batch holding a textured, metallic instance for each of the three slots' first worlds.""" + worlds = np.array([0, SLICE_SIZE, 2 * SLICE_SIZE]) + native = np.tile([0.5, 0.7, 0.0, 1.0], (3, 1)).astype(np.float32) + batch = SimpleNamespace( + worlds=wp.array(worlds, dtype=wp.int32, device="cpu"), + materials=wp.array(native, dtype=wp.vec4, device="cpu"), + ) + return SimpleNamespace(_shape_instances={"batch": batch}, model_changed=False) + + +def test_a_tinted_ghost_loses_its_texture_and_fades_its_metallic_shading_with_the_tint() -> None: + layout = CheckpointGhostLayout(POOL, 3) + for slot in layout.slots: + slot.checkpoint = CHECKPOINT + layout.slots[1].tint = 1.0 + layout.slots[2].tint = 0.5 + panel, viewer = _panel(layout), _viewer_with_batch() + + panel.apply_materials(viewer) + + materials = viewer._shape_instances["batch"].materials.numpy() + assert np.allclose(materials[1], [0.5, 0.0, 0.0, 0.0]) + assert np.allclose(materials[2], [0.5, 0.35, 0.0, 0.0]) + assert np.allclose(materials[0], [0.5, 0.7, 0.0, 1.0]) + assert viewer.model_changed + + layout.slots[1].tint = 0.0 + layout.slots[2].tint = 0.0 + panel.apply_materials(viewer) + assert np.allclose(viewer._shape_instances["batch"].materials.numpy(), [0.5, 0.7, 0.0, 1.0]) + + +def test_tinting_keeps_the_opacity_the_model_already_has() -> None: + layout = CheckpointGhostLayout(POOL, 3) + layout.slots[0].checkpoint = layout.slots[1].checkpoint = CHECKPOINT + model = _model() + base = np.full(len(model.shape_world.numpy()), 0.4, dtype=np.float32) + model.shape_opacity = wp.array(base, dtype=wp.float32, device="cpu") + panel = _panel(layout) + + panel.apply_tint(model) + + opacity = model.shape_opacity.numpy() + ghost = model.shape_world.numpy() >= 3 # two loaded slots split the six envs into slices of three + assert (opacity[~ghost & (model.shape_world.numpy() >= 0)] == 0.4).all() and opacity[0] == 0.4 + assert np.allclose(opacity[ghost], display_opacity(layout.slots[1].opacity)) + + +class _TextImgui: + """Imgui double that records the text, tooltips, and headers a section draws.""" + + Col_ = SimpleNamespace(text=0) + Cond_ = SimpleNamespace(appearing=0, first_use_ever=0) + HoveredFlags_ = SimpleNamespace(allow_when_disabled=0) + ColorEditFlags_ = SimpleNamespace(no_tooltip=0) + + def __init__(self, open_header: bool = True): + self.open_header = open_header + self.texts, self.tooltips, self.headers = [], [], [] + + def set_next_item_open(self, *args): + pass + + def collapsing_header(self, label): + self.headers.append(label) + return self.open_header + + def is_item_hovered(self, *args): + return True + + def set_tooltip(self, text): + self.tooltips.append(text) + + def ImVec4(self, *args): + return args + + ImVec2 = ImVec4 + + def text(self, text): + self.texts.append(text) + + text_wrapped = text + + def text_colored(self, color, text): + self.texts.append(text) + + def slider_float(self, label, value, *args): + return False, value + + def checkbox(self, label, value): + return False, value + + def tree_node(self, label): + return False + + def get_frame_height(self): + return 20 + + def get_cursor_screen_pos(self): + return SimpleNamespace(x=0, y=0) + + def get_window_draw_list(self): + return SimpleNamespace(add_rect=lambda *args: None) + + def __getattr__(self, name): + return lambda *args, **kwargs: False + + +def test_the_section_reports_the_simulated_and_drawn_environments_and_follows_the_checkpoints() -> None: + layout = CheckpointGhostLayout(32, 8) + layout.slots[0].checkpoint = layout.slots[1].checkpoint = CHECKPOINT + panel = NewtonCheckpointGhostPanel(SimpleNamespace(layout=layout, slot_metrics=lambda index: None)) + owner = SimpleNamespace(visible_env_count=3) + imgui = _TextImgui() + + panel.draw(imgui, owner=owner) + + assert "Showing 6/32 envs: 3 per slot x 2 ckpts" in imgui.texts + + layout.slots[2].checkpoint = CHECKPOINT + imgui = _TextImgui() + panel.draw(imgui, owner=owner) + + assert "Showing 9/32 envs: 3 per slot x 3 ckpts" in imgui.texts + + +def test_without_the_flag_the_section_is_greyed_out_and_explains_how_to_enable_it() -> None: + from isaaclab_visualizers.newton.newton_checkpoint_ghosts import draw_checkpoint_ghost_offer + + imgui = _TextImgui() + + draw_checkpoint_ghost_offer(imgui) + + assert imgui.headers == ["Checkpoint Ghosts (not enabled)"] + assert any("Checkpoint visualization" in tip for tip in imgui.tooltips) + assert any("--checkpoint_ghosts" in text for text in imgui.texts) + + +def test_the_opacity_slider_eases_to_just_under_the_opaque_path() -> None: + values = [display_opacity(s) for s in (0.1, 0.4, 0.8, 1.0)] + + assert values == sorted(values) + assert display_opacity(0.4) == pytest.approx(0.64) + assert display_opacity(1.0) < 0.999 # Newton re-batches shapes at 0.999 and above + assert display_opacity(0.95) > 0.99 + + +class _BrowserImgui(_TextImgui): + """Imgui double for the checkpoint window: it clicks the entries it is told to.""" + + InputTextFlags_ = SimpleNamespace(enter_returns_true=0) + + def __init__(self, clicks=()): + super().__init__() + self.clicks, self.drawn = list(clicks), [] + + def begin(self, title, opened): + return True, opened + + def button(self, label): + return label in self.clicks + + def selectable(self, label, selected): # imgui requires the selected flag, as the real binding does + self.drawn.append(label) + return label in self.clicks, False + + def input_text(self, label, text, flags): + return False, text + + +class _Browser: + """Controller whose filesystem is a dictionary of folders.""" + + def __init__(self, layout, tree): + self.layout, self.tree, self.listed = layout, tree, [] + self.checkpoint_root = "/runs/task" + self.added = [] + + other_tasks: dict = {} + + def other_task(self, directory): + return self.other_tasks.get(directory) + + def browse(self, directory): + self.listed.append(directory) + if directory not in self.tree: + raise FileNotFoundError(2, "No such file or directory") + folders, files = self.tree[directory] + return folders, [CheckpointGhostCheckpoint(f"{directory}/{n}", "r", n, 0.0) for n in files] + + def add_ghost(self, checkpoint): + self.added.append(checkpoint.path) + return + + +def test_the_checkpoint_window_navigates_folders_and_remembers_where_it_was(): + tree = {"/runs/task": (["run_a"], []), "/runs/task/run_a": ([], ["model_1.pt"]), "/runs": (["task", "skrl"], [])} + controller = _Browser(CheckpointGhostLayout(POOL, 3), tree) + panel = NewtonCheckpointGhostPanel(controller) + + panel._open_window() + panel._draw_window(_BrowserImgui(clicks=["run_a/##folder"])) + assert panel._directory == "/runs/task/run_a" + + panel._draw_window(_BrowserImgui(clicks=["Up"])) + assert panel._directory == "/runs/task" + panel._draw_window(_BrowserImgui(clicks=["Up"])) + assert panel._directory == "/runs" # it can leave the experiment folder + + panel._window_open = False # closing the window keeps the folder + panel._open_window() + assert panel._directory == "/runs" + assert controller.listed[-1] == "/runs" + + +def test_choosing_a_checkpoint_keeps_the_folder_and_an_unreadable_folder_is_reported(): + tree = {"/runs/task": ([], ["model_1.pt"])} + controller = _Browser(CheckpointGhostLayout(POOL, 3), tree) + panel = NewtonCheckpointGhostPanel(controller) + panel._open_window() + + panel._draw_window(_BrowserImgui(clicks=["model_1.pt 1970-01-01 00:00##/runs/task/model_1.pt"])) + + assert controller.added == ["/runs/task/model_1.pt"] and not panel._window_open + panel._open_window() + assert panel._directory == "/runs/task" + + panel._go("/missing") + assert "Cannot read this folder" in panel._browse_error + + +def test_runs_of_another_task_are_flagged_in_the_checkpoint_window(): + tree = {"/runs/task": (["osc", "same"], []), "/runs/task/osc": ([], ["model_1.pt"])} + controller = _Browser(CheckpointGhostLayout(POOL, 3), tree) + controller.other_tasks = {"/runs/task/osc": "Isaac-Reach-Franka-OSC"} + panel = NewtonCheckpointGhostPanel(controller) + panel._open_window() + + imgui = _BrowserImgui() + panel._draw_window(imgui) + + assert "osc/ (Isaac-Reach-Franka-OSC)##folder" in imgui.drawn and "same/##folder" in imgui.drawn + + panel._go("/runs/task/osc") + imgui = _BrowserImgui() + panel._draw_window(imgui) + + assert any("Isaac-Reach-Franka-OSC, not this task" in text for text in imgui.texts) + + +class _DisablingImgui(_TextImgui): + """Imgui double that counts how deeply disabled the controls it draws are.""" + + def __init__(self): + super().__init__() + self.depth, self.deepest, self.disabled_buttons = 0, 0, [] + + def begin_disabled(self): + self.depth += 1 + self.deepest = max(self.deepest, self.depth) + + def end_disabled(self): + self.depth -= 1 + + def button(self, label): + self.disabled_buttons.append((label, self.depth > 0)) + return False + + +def test_the_ghost_controls_are_disabled_in_the_rtx_view_with_a_note_to_switch_renderer() -> None: + layout = CheckpointGhostLayout(POOL, 3) + layout.slots[0].checkpoint = CHECKPOINT + panel = _panel(layout) + panel._window_open = True + panel._draw_window = Mock() + + imgui = _DisablingImgui() + panel.draw(imgui, rtx_view=True) + + assert any("RTX: switch the Renderer to OpenGL" in text for text in imgui.texts) + assert imgui.depth == 0 and all(disabled for _, disabled in imgui.disabled_buttons) and imgui.disabled_buttons + panel._draw_window.assert_not_called() + + imgui = _DisablingImgui() + panel.draw(imgui, rtx_view=False) + + assert not any("RTX:" in text for text in imgui.texts) + assert imgui.depth == 0 and not any(disabled for _, disabled in imgui.disabled_buttons) + panel._draw_window.assert_called_once() From 8bdd163d8f59d040294d3b849dfb574fbf84fa24 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 03:31:01 +0000 Subject: [PATCH 02/24] Shorten the Checkpoint Ghosts docs --- docs/source/concepts/visualization.rst | 62 +++++++++----------------- 1 file changed, 20 insertions(+), 42 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 71a5c423c67d..433a2d37832e 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -311,7 +311,7 @@ Visualizer Overview Picking, visualization markers, camera selection, pause controls, Visible Envs, and recording work in the RTX view of a windowed Newton visualizer, and picking draws the drag arrow there. Joint, contact, spring, center-of-mass, and inertia overlays are drawn in the RTX view too; the collision, visual, edge, and wireframe - overlays and the Checkpoint Ghost tint apply to the OpenGL view only. + overlays apply to the OpenGL view only. .. warning:: @@ -816,56 +816,35 @@ without screen-sharing, running with ``--viz viser``: The share URL is logged on startup. Rerun has no equivalent config field, but exposes its own share button in the native UI. -**Debugging and visualizing policies with Checkpoint Ghosts** +**Comparing checkpoints with Checkpoint Ghosts** -Checkpoint Ghosts overlay rollouts of several policy checkpoints of one task in a single Newton viewport, to debug and -visualize how training changed the behavior. The ``--checkpoint`` -drives the reference robots; ghosts of other checkpoints are tinted, translucent copies that start -from the same terrain, spawn pose, and commands, so differences in behavior show up as the robots -drift apart: +Checkpoint Ghosts overlay rollouts of several checkpoints of one task in the Newton window, to see how training changed +the behavior. ``--checkpoint`` drives the reference; ghosts of other checkpoints are tinted, translucent copies that +start from the same terrain, spawn pose, and commands, so the policy is the only difference: .. code-block:: bash uv run isaaclab play --rl_library rsl_rl --task Isaac-Velocity-Flat-AnymalD \ --num_envs 32 --checkpoint latest --viz newton --checkpoint_ghosts -Checkpoint Ghosts are opt-in. A plain ``play`` run shows a greyed-out **Checkpoint Ghosts (not enabled)** section in the -viewer's left panel that explains the feature and the flag, because the simulation must allocate the environments of -every slot up front and plain playback should not pay for them. - -``--num_envs`` is the total number of environments simulated, split evenly among the checkpoints shown. The reference -alone gets all of them; each checkpoint you add resizes every slot and restarts the environments from the same spawn -state. With ``--num_envs 32``, the reference starts with 32 environments, and adding one ghost gives 16 each, then -10 each (30 in use) with three. ``--checkpoint_ghost_slots`` (default and maximum eight, capped at ``--num_envs``) limits how -many checkpoints can be shown at once. The section shows what is drawn out of the simulated total, for example -``Showing 12/32 envs: 4 per slot x 3 ckpts``. **Visible Envs** in **Playback** follows the per-slot size as it -changes, and lowers the drawn count per slot, down to 1. - -Open **Checkpoint Ghosts** and choose **Add Checkpoint...** to browse for checkpoints. The window starts in the -experiment's log directory (``--checkpoint_ghost_root`` starts it elsewhere) and lists folders and the ``model_*.pt`` -files in the current one. Click a folder to enter it, **Up** to leave it, **Experiment Folder** to return, or type any -folder into the path box and press Enter. The window reopens in the folder you left it in, also after you pick a -checkpoint. The checkpoint must come from a run of this task and be an RSL-RL checkpoint, because the reference's -runner loads it; one that does not fit is reported instead of loaded. The reference is outlined and always shown. Each ghost has a -checkbox that shows or hides it. Under **Appearance**, each ghost has opacity and tint sliders; the tint blends the robot's native colors toward the -ghost color. Any tint above 0 drops native textures, and metal shading fades out as the tint rises. **Change...** replaces a ghost's checkpoint in place, and **Remove** frees the slot. - -* All ``--num_envs`` environments are always simulated. Ghost slots copy the reference slot's terrain, spawn poses, and - commands, and environments an uneven split leaves over receive zero actions. -* Randomization that cannot be mirrored between slots is disabled: startup and interval events, - curriculum terms, and observation noise. Reset events and commands are copied from the reference. -* Identical checkpoints do not stay exactly on top of each other; physics differences grow - to centimeters over a few seconds on rough terrain. -* Checkpoint Ghosts support RSL-RL and manager-based environments only. -* Tasks whose cameras render with OVRTX (``renderer=ovrtx``) are not supported yet. Checkpoint Ghosts are not offered for - them, and ``--checkpoint_ghosts`` exits with a message. +``--num_envs`` is the total simulated and is split evenly among the checkpoints shown: the reference starts with all of +them, and each checkpoint you add resizes every slot. A plain ``play`` run shows a greyed-out section that explains the +flag. ``--checkpoint_ghost_slots`` caps the checkpoints shown (default eight). + +In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for RSL-RL ``model_*.pt`` files, starting in +the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has +opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. + +* Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored + between slots. +* Only RSL-RL and manager-based environments are supported, and not tasks whose cameras use OVRTX. **Choosing how many environments are drawn** Every Newton viewer has a **Visible Envs** slider in its left panel that sets how many -environments are drawn. It changes only what is rendered, not the simulation. With Checkpoint Ghosts, it -counts environments per slot. In the RTX view the OVRTX renderer is shared with scene cameras, so the hidden -environments also drop out of their images while the RTX view is shown; the HUD notes this next to the slider. +environments are drawn. It changes only what is rendered, not the simulation. In the RTX view the OVRTX renderer is +shared with scene cameras, so the hidden environments also drop out of their images while the RTX view is shown; +the HUD notes this next to the slider. Resolution Rules ~~~~~~~~~~~~~~~~ @@ -1033,8 +1012,7 @@ Limitations - ✓ In Newton's RTX view, the collision, visual, edge, and wireframe overlays are not available; joint, contact, spring, -center-of-mass, and inertia overlays are. Checkpoint Ghost tint is -not available there, and the **Checkpoint Ghosts** controls are disabled until the Renderer is switched to OpenGL. +center-of-mass, and inertia overlays are. **Lighting differences across visualizers** From b551f50e2c19b3f1b281342f7e947fdb33c1c0c5 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 03:33:53 +0000 Subject: [PATCH 03/24] Reject Checkpoint Ghosts for tasks whose curriculum selects the reset state --- docs/source/concepts/visualization.rst | 3 ++- .../checkpoint-ghost-play.added.rst | 2 ++ .../entrypoints/backends/play_rsl_rl.py | 7 ++++++ .../test/test_checkpoint_ghost_launch.py | 23 ++++++++++++++++++- ...eckpoint-ghost-curriculum-marker.added.rst | 2 ++ .../contrib/franka_pour/mdp/reset_dataset.py | 3 +++ .../ur10_particle_push/mdp/curriculums.py | 3 +++ 7 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/checkpoint-ghost-curriculum-marker.added.rst diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 433a2d37832e..ac19d10d9e54 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -837,7 +837,8 @@ opacity and tint under **Appearance**. The controls are disabled in the RTX view * Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored between slots. -* Only RSL-RL and manager-based environments are supported, and not tasks whose cameras use OVRTX. +* Only RSL-RL and manager-based environments are supported. Tasks whose cameras use OVRTX, or whose curriculum selects + the reset state (such as Franka Pour), are rejected at launch. **Choosing how many environments are drawn** diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst index 17c6054bb2df..3da618c0cb77 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst @@ -3,3 +3,5 @@ starts with all of them, and adding a ghost resizes every slot (32 environments give 16 each with two checkpoints). ``--checkpoint_ghost_slots`` caps the checkpoints shown at once (default eight, at most ``--num_envs``). ``--checkpoint_ghost_root`` searches another directory for checkpoints. Plain playback allocates nothing for the feature. +* Rejected ``--checkpoint_ghosts`` for tasks whose curriculum term sets the reset state, since ghosts disable curriculum + terms. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index e2c62da9b4cf..a430b1d57406 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -237,6 +237,13 @@ def _validate_checkpoint_ghosts(args_cli: argparse.Namespace, env_cfg: object) - types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) if "newton" not in types: raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") + curriculum = getattr(env_cfg, "curriculum", None) + for name, term in vars(curriculum).items() if curriculum is not None else (): + # Checkpoint Ghosts disable curriculum terms, so a task whose reset events read a term's state cannot run. + if getattr(getattr(term, "func", None), "supports_checkpoint_ghosts", True) is False: + raise SystemExit( + f"--checkpoint_ghosts does not support this task: its curriculum term '{name}' sets the reset state." + ) if _scene_cameras_use_ovrtx(env_cfg): raise SystemExit( "--checkpoint_ghosts does not support tasks whose cameras use the OVRTX renderer yet." diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index ddaa1bc03adc..a9dc07862bef 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -18,10 +18,11 @@ from isaaclab_rl.entrypoints.backends import play_rsl_rl -def _env_cfg(backend, scene=None): +def _env_cfg(backend, scene=None, curriculum=None): cfg = ManagerBasedRLEnvCfg.__new__(ManagerBasedRLEnvCfg) cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=backend)]) cfg.scene = scene or SimpleNamespace() + cfg.curriculum = curriculum return cfg @@ -93,3 +94,23 @@ def __init__(self, env, **kwargs): assert created["task"] == "Isaac-Reach-Franka" assert created["checkpoint_root"] == str(tmp_path) assert created["reference"].name == "model_5.pt" + + +def test_a_task_whose_curriculum_selects_the_reset_state_is_rejected(): + class _ResetStateCurriculum: + supports_checkpoint_ghosts = False + + curriculum = SimpleNamespace(reset_dataset=SimpleNamespace(func=_ResetStateCurriculum)) + + with pytest.raises(SystemExit, match="reset_dataset"): + play_rsl_rl._validate_checkpoint_ghosts( + SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum) + ) + + +def test_an_ordinary_curriculum_term_is_accepted(): + curriculum = SimpleNamespace(terrain_levels=SimpleNamespace(func=lambda env, env_ids: None)) + + play_rsl_rl._validate_checkpoint_ghosts( + SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum) + ) diff --git a/source/isaaclab_tasks/changelog.d/checkpoint-ghost-curriculum-marker.added.rst b/source/isaaclab_tasks/changelog.d/checkpoint-ghost-curriculum-marker.added.rst new file mode 100644 index 000000000000..e0aeefe6aa15 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/checkpoint-ghost-curriculum-marker.added.rst @@ -0,0 +1,2 @@ +* Marked the Franka Pour and UR10 single-push curriculum terms as unsupported by Checkpoint Ghosts, which disable + curriculum terms, so ``--checkpoint_ghosts`` rejects those tasks at launch instead of breaking their resets. diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py index 6256d1228c2c..963baab695f8 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/franka_pour/mdp/reset_dataset.py @@ -25,6 +25,9 @@ class PourResetDatasetCurriculum(ManagerTermBase): """Sample reset rows and learn from rank-local asynchronous episode outcomes.""" + supports_checkpoint_ghosts = False + """Checkpoint Ghosts disable curriculum terms, but this one selects the reset state that reset events read.""" + def __init__(self, cfg: CurriculumTermCfg, env: FrankaPourEnv): super().__init__(cfg, env) states = env._reset_dataset_states diff --git a/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/mdp/curriculums.py b/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/mdp/curriculums.py index 53f77c75dc1d..49e8ad9ca578 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/mdp/curriculums.py +++ b/source/isaaclab_tasks/isaaclab_tasks/contrib/ur10_particle_push/mdp/curriculums.py @@ -26,6 +26,9 @@ class SinglePushCurriculum(ManagerTermBase): to the full reset distribution from the first rollout. """ + supports_checkpoint_ghosts = False + """Checkpoint Ghosts disable curriculum terms, but this one selects the reset state that reset events read.""" + def __init__(self, cfg: CurriculumTermCfg, env: UR10ParticlePushEnv) -> None: super().__init__(cfg, env) level_count = len(env.cfg.reset_randomization_scales) From 6aaa857dd40830f773f5e5be526700f480c1bd1a Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 04:09:14 +0000 Subject: [PATCH 04/24] Fix checkpoint selectors in play and disable physics-randomizing reset events for ghosts --- docs/source/concepts/visualization.rst | 4 +-- ...heckpoint-ghost-relative-targets.fixed.rst | 3 +++ .../envs/utils/checkpoint_ghost_sync.py | 15 ++++++++--- .../test/envs/test_checkpoint_ghost_sync.py | 26 +++++++++++++++++++ .../checkpoint-ghost-review-fixes.fixed.rst | 2 ++ .../entrypoints/backends/play_rsl_rl.py | 2 ++ .../test/test_checkpoint_ghost_launch.py | 12 +++++++++ 7 files changed, 59 insertions(+), 5 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index ac19d10d9e54..915fd889384b 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -835,8 +835,8 @@ In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. -* Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored - between slots. +* Startup and interval events, reset events that randomize physics (``randomize_*``), curriculum terms, and observation + noise are disabled, since they cannot be mirrored between slots. * Only RSL-RL and manager-based environments are supported. Tasks whose cameras use OVRTX, or whose curriculum selects the reset state (such as Franka Pour), are rejected at launch. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst index c11eb10d4f41..dfefd3897acd 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst @@ -5,3 +5,6 @@ * Fixed Checkpoint Ghosts holding joints the actions do not drive, such as the fingers of a reaching arm, at different targets than the reference after a reset. A ghost now takes the reference's joint targets, so an identical checkpoint follows the reference. +* Fixed Checkpoint Ghosts running with different physics than the reference when a reset event randomizes mass, + friction, or actuator gains per environment. Reset events named ``randomize_*`` are now disabled, like startup and + interval events, and pose and velocity resets are still mirrored. diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index 4daaf0d86a48..6d2c0b5bace1 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -74,8 +74,9 @@ def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: """Remove per-environment randomization that cannot be mirrored between slices. - Startup and interval events, curriculum terms, and observation corruption are disabled. Reset events - are kept because the reference's reset state is copied to the ghosts. + Startup and interval events, reset events that randomize physics parameters (``randomize_*``), curriculum terms, + and observation corruption are disabled. The other reset events are kept because the reference's reset state is + copied to the ghosts. Args: env_cfg: Environment config to modify in place. @@ -89,7 +90,15 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: getattr(env_cfg, name, None) for name in ("events", "curriculum", "observations") ) for name, term in vars(events).items() if events is not None else (): - if term is not None and getattr(term, "mode", None) in ("startup", "interval"): + if term is None: + continue + mode = getattr(term, "mode", None) + # A reset event that draws physics parameters (mass, friction, gains) per environment cannot be + # mirrored, since the scene state copied to a ghost does not carry them. Pose resets are mirrored. + randomizes = mode == "reset" and getattr(getattr(term, "func", None), "__name__", "").startswith( + "randomize_" + ) + if mode in ("startup", "interval") or randomizes: setattr(events, name, None) removed.append(f"events.{name}") for name, term in vars(curriculum).items() if curriculum is not None else (): diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index ca2b5d43ff9e..3c661cb4b9c6 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -269,3 +269,29 @@ def test_close_puts_the_ghost_environments_back_on_their_own_terrain() -> None: assert torch.equal(env.scene.terrain.env_origins, original) assert torch.equal(env.scene.terrain.terrain_levels, torch.arange(NUM_ENVS)) + + +def test_configure_env_cfg_also_disables_reset_events_that_randomize_physics() -> None: + def randomize_rigid_body_mass() -> None: + pass + + def reset_root_state_uniform() -> None: + pass + + def term(mode: str, func) -> SimpleNamespace: + return SimpleNamespace(mode=mode, func=func) + + cfg = SimpleNamespace( + events=SimpleNamespace( + mass=term("reset", randomize_rigid_body_mass), + pose=term("reset", reset_root_state_uniform), + startup_mass=term("startup", randomize_rigid_body_mass), + ), + curriculum=None, + observations=None, + ) + + removed = CheckpointGhostSync.configure_env_cfg(cfg) + + assert sorted(removed) == ["events.mass", "events.startup_mass"] + assert cfg.events.pose is not None and cfg.events.mass is None # the pose reset is mirrored, so it stays diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst index 450b2724a72a..eb5325417b49 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -1,3 +1,5 @@ * Fixed ``--checkpoint_ghosts`` rejecting a run with several viewers such as ``--viz newton,viser``, and recurrent ghost policies keeping their memory across an episode reset. Tasks whose cameras render with OVRTX are now rejected, since Checkpoint Ghosts do not support them yet. +* Fixed ``--checkpoint latest`` and ``--checkpoint best`` failing in RSL-RL playback after the Checkpoint Ghosts change + dropped the ``library`` and ``agent`` arguments of the checkpoint selector. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index a430b1d57406..a28f2641267b 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -122,8 +122,10 @@ def _resolve_checkpoint( return resolve_checkpoint_selector( log_root_path, args_cli.checkpoint, + library="rsl_rl", task=normalize_task_name(args_cli.task), checkpoint_pattern=r"model_.*\.pt", + metadata={"agent": args_cli.agent}, ) if args_cli.checkpoint and os.path.isdir(args_cli.checkpoint): return get_checkpoint_path( diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index a9dc07862bef..8dd5750b6b3a 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -114,3 +114,15 @@ def test_an_ordinary_curriculum_term_is_accepted(): play_rsl_rl._validate_checkpoint_ghosts( SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum) ) + + +def test_checkpoint_selectors_pass_the_library_and_agent_to_the_resolver(monkeypatch): + resolver = Mock(return_value="/runs/model_5.pt") + monkeypatch.setattr(play_rsl_rl, "resolve_checkpoint_selector", resolver) + args = SimpleNamespace(checkpoint="latest", task="Isaac-Reach-Franka", agent="rsl_rl_cfg_entry_point") + + path = play_rsl_rl._resolve_checkpoint(args, Mock(), Mock(), "/logs/rsl_rl/reach_franka") + + assert path == "/runs/model_5.pt" + assert resolver.call_args.kwargs["library"] == "rsl_rl" + assert resolver.call_args.kwargs["metadata"] == {"agent": "rsl_rl_cfg_entry_point"} From 17d438972a3fb7a328893db94da2afd1964a1d3a Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 04:15:43 +0000 Subject: [PATCH 05/24] Close the ghost session when attaching fails and tighten the controller contract --- .../envs/utils/checkpoint_ghost_sync.py | 14 +++++--------- .../isaaclab/visualizers/checkpoint_ghost.py | 8 +++----- .../test/envs/test_checkpoint_ghost_sync.py | 7 ++++--- .../checkpoint-ghost-review-fixes.fixed.rst | 2 ++ .../entrypoints/backends/play_rsl_rl.py | 18 +++++++++--------- .../entrypoints/checkpoint_ghosts.py | 8 +++++++- .../test/test_checkpoint_ghost_launch.py | 13 +++++++++++++ 7 files changed, 43 insertions(+), 27 deletions(-) diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index 6d2c0b5bace1..12bba70c54f1 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -85,19 +85,15 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: Names of the disabled terms. """ removed = [] - # A task may declare no events, curriculum, or observation groups at all. - events, curriculum, observations = ( - getattr(env_cfg, name, None) for name in ("events", "curriculum", "observations") - ) + # A task may leave these fields None when it has no events, curriculum, or observation groups. + events, curriculum, observations = env_cfg.events, env_cfg.curriculum, env_cfg.observations for name, term in vars(events).items() if events is not None else (): if term is None: continue - mode = getattr(term, "mode", None) + mode = term.mode # A reset event that draws physics parameters (mass, friction, gains) per environment cannot be # mirrored, since the scene state copied to a ghost does not carry them. Pose resets are mirrored. - randomizes = mode == "reset" and getattr(getattr(term, "func", None), "__name__", "").startswith( - "randomize_" - ) + randomizes = mode == "reset" and getattr(term.func, "__name__", "").startswith("randomize_") if mode in ("startup", "interval") or randomizes: setattr(events, name, None) removed.append(f"events.{name}") @@ -106,7 +102,7 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: setattr(curriculum, name, None) removed.append(f"curriculum.{name}") for group_name, group in vars(observations).items() if observations is not None else (): - if getattr(group, "enable_corruption", False): + if group.enable_corruption: group.enable_corruption = False removed.append(f"observations.{group_name}.enable_corruption") if removed: diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py index 98e8ec4ab7f2..cef661c6c764 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py @@ -169,12 +169,12 @@ def browse(self, directory: str) -> tuple[list[str], list[CheckpointGhostCheckpo OSError: If the directory cannot be read. """ + @abstractmethod def other_task(self, directory: str) -> str | None: """Return the task of the run saved in ``directory`` when it is not the running task, else None. The checkpoint window uses this to flag runs whose checkpoints cannot fit the running policy. """ - return None @abstractmethod def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: @@ -188,17 +188,15 @@ def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: def remove_ghost(self, slot_index: int) -> None: """Empty a ghost slot; the reference slot cannot be removed.""" + @abstractmethod def replace_ghost(self, slot_index: int, checkpoint: CheckpointGhostCheckpoint) -> str | None: """Load a checkpoint into a given ghost slot, in place of the one it holds. - Controllers that cannot target a slot remove that ghost and add the checkpoint to the first empty slot. - Returns: None on success, otherwise a message explaining why the checkpoint could not be loaded. """ - self.remove_ghost(slot_index) - return self.add_ghost(checkpoint) + @abstractmethod def apply_pending_restart(self) -> None: """Reset the environments now when a new ghost asked for a restart that the next step would apply. diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index 3c661cb4b9c6..1c804ec83973 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -206,7 +206,7 @@ def test_environment_size_must_match_the_slices() -> None: def test_configure_env_cfg_keeps_only_randomization_the_reset_can_mirror() -> None: def term(mode: str) -> SimpleNamespace: - return SimpleNamespace(mode=mode) + return SimpleNamespace(mode=mode, func=lambda: None) cfg = SimpleNamespace( events=SimpleNamespace(mass=term("startup"), push=term("interval"), reset_base=term("reset"), removed=None), @@ -230,13 +230,14 @@ def term(mode: str) -> SimpleNamespace: def test_configure_env_cfg_accepts_a_task_without_a_curriculum() -> None: cfg = SimpleNamespace( - events=SimpleNamespace(push=SimpleNamespace(mode="interval")), + events=SimpleNamespace(push=SimpleNamespace(mode="interval", func=lambda: None)), curriculum=None, observations=SimpleNamespace(policy=SimpleNamespace(enable_corruption=False)), ) assert CheckpointGhostSync.configure_env_cfg(cfg) == ["events.push"] - assert CheckpointGhostSync.configure_env_cfg(SimpleNamespace()) == [] # No events, curriculum, or observations. + none = SimpleNamespace(events=None, curriculum=None, observations=None) + assert CheckpointGhostSync.configure_env_cfg(none) == [] # A task with no events, curriculum, or observations. def test_a_larger_pool_resets_the_environments_beyond_the_slices_on_their_own() -> None: diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst index eb5325417b49..f12a35fc55dc 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -3,3 +3,5 @@ reset. Tasks whose cameras render with OVRTX are now rejected, since Checkpoint Ghosts do not support them yet. * Fixed ``--checkpoint latest`` and ``--checkpoint best`` failing in RSL-RL playback after the Checkpoint Ghosts change dropped the ``library`` and ``agent`` arguments of the checkpoint selector. +* Fixed Checkpoint Ghosts leaving the environment's reset and command hooks installed when no Newton viewer could + attach, and allocating a new action tensor on every playback step. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index a28f2641267b..3edfbc0fa521 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -176,14 +176,14 @@ def run_checkpoint_ghosts( session = create_checkpoint_ghost_session( env, args_cli, agent_cfg, reference_path, log_root_path, args_cli.checkpoint_ghost_slots ) - attached = False - for visualizer in env.unwrapped.sim.visualizers: - if hasattr(visualizer, "attach_checkpoint_ghosts"): - visualizer.attach_checkpoint_ghosts(session) - attached = True - if not attached: - raise RuntimeError("--checkpoint_ghosts needs an initialized Newton GL visualizer.") - try: + try: # the session patches the environment's reset and commands, which must be undone on any failure + attached = False + for visualizer in env.unwrapped.sim.visualizers: + if hasattr(visualizer, "attach_checkpoint_ghosts"): + visualizer.attach_checkpoint_ghosts(session) + attached = True + if not attached: + raise RuntimeError("--checkpoint_ghosts needs an initialized Newton GL visualizer.") run_playback( session.step, dt=env.unwrapped.step_dt, @@ -239,7 +239,7 @@ def _validate_checkpoint_ghosts(args_cli: argparse.Namespace, env_cfg: object) - types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) if "newton" not in types: raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") - curriculum = getattr(env_cfg, "curriculum", None) + curriculum = env_cfg.curriculum for name, term in vars(curriculum).items() if curriculum is not None else (): # Checkpoint Ghosts disable curriculum terms, so a task whose reset events read a term's state cannot run. if getattr(getattr(term, "func", None), "supports_checkpoint_ghosts", True) is False: diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py index b0d4d3f0f1c4..f24a7389472d 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py @@ -60,6 +60,9 @@ class CheckpointGhostSession(CheckpointGhostController): uneven split are simulated with zero actions. """ + _actions: torch.Tensor | None = None + """Actions of every environment, reused by every step.""" + def __init__( self, env: Any, @@ -185,7 +188,10 @@ def step(self) -> None: """Step the environment once, with each loaded slot acting on its own observations.""" self.apply_pending_restart() size = self.layout.slice_size - actions = torch.zeros(self._env.num_envs, self._env.num_actions, device=self._env.unwrapped.device) + if self._actions is None: + self._actions = torch.zeros(self._env.num_envs, self._env.num_actions, device=self._env.unwrapped.device) + actions = self._actions + actions.zero_() # environments of no loaded slot act with zeros for slot in self.layout.active_slots: start = self.layout.slot_start(slot.index) chunk = slice(start, start + size) diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index 8dd5750b6b3a..f792c36b5df6 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -126,3 +126,16 @@ def test_checkpoint_selectors_pass_the_library_and_agent_to_the_resolver(monkeyp assert path == "/runs/model_5.pt" assert resolver.call_args.kwargs["library"] == "rsl_rl" assert resolver.call_args.kwargs["metadata"] == {"agent": "rsl_rl_cfg_entry_point"} + + +def test_the_session_is_closed_when_no_viewer_can_attach(monkeypatch): + session = Mock() + monkeypatch.setattr(play_rsl_rl, "create_checkpoint_ghost_session", Mock(return_value=session)) + env = SimpleNamespace(unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=[object()]), step_dt=0.02)) + + with pytest.raises(RuntimeError, match="initialized Newton GL visualizer"): + play_rsl_rl.run_checkpoint_ghosts( + env, SimpleNamespace(checkpoint_ghost_slots=2), Mock(), "/runs/model_5.pt", "/logs" + ) + + session.close.assert_called_once() # its reset and command hooks must not stay installed From df25f842bcbcfc00cb879208616e7d8cee9b9f3e Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 04:22:19 +0000 Subject: [PATCH 06/24] Disable only the physics randomization reset events for ghosts --- docs/source/concepts/visualization.rst | 4 +-- ...heckpoint-ghost-relative-targets.fixed.rst | 5 ++-- .../envs/utils/checkpoint_ghost_sync.py | 27 ++++++++++++++++--- .../test/envs/test_checkpoint_ghost_sync.py | 13 +++++---- 4 files changed, 37 insertions(+), 12 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 915fd889384b..b49da04fa09a 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -835,8 +835,8 @@ In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. -* Startup and interval events, reset events that randomize physics (``randomize_*``), curriculum terms, and observation - noise are disabled, since they cannot be mirrored between slots. +* Startup and interval events, reset events that randomize physics parameters (mass, friction, gains), curriculum + terms, and observation noise are disabled, since they cannot be mirrored between slots. * Only RSL-RL and manager-based environments are supported. Tasks whose cameras use OVRTX, or whose curriculum selects the reset state (such as Franka Pour), are rejected at launch. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst index dfefd3897acd..82f6c1df41a3 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst @@ -6,5 +6,6 @@ targets than the reference after a reset. A ghost now takes the reference's joint targets, so an identical checkpoint follows the reference. * Fixed Checkpoint Ghosts running with different physics than the reference when a reset event randomizes mass, - friction, or actuator gains per environment. Reset events named ``randomize_*`` are now disabled, like startup and - interval events, and pose and velocity resets are still mirrored. + friction, or actuator gains per environment. The physics randomization reset events of ``isaaclab.envs.mdp.events`` + are now disabled, like startup and interval events. Pose and velocity resets, and a task's own reset events, are + still kept and mirrored. diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index 12bba70c54f1..899dcb69dd9f 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -19,6 +19,22 @@ logger = logging.getLogger(__name__) +_PHYSICS_RANDOMIZERS = frozenset( + { + "randomize_rigid_body_scale", + "randomize_rigid_body_material", + "randomize_rigid_body_mass", + "randomize_rigid_body_inertia", + "randomize_rigid_body_com", + "randomize_rigid_body_collider_offsets", + "randomize_physics_scene_gravity", + "randomize_actuator_gains", + "randomize_joint_parameters", + "randomize_fixed_tendon_parameters", + } +) +"""Events of :mod:`isaaclab.envs.mdp.events` that draw physics parameters per environment.""" + _TERRAIN_FIELDS = ("terrain_levels", "terrain_types", "env_origins") """Terrain placement tensors of every environment that the ghosts copy from the reference.""" @@ -74,8 +90,8 @@ def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: """Remove per-environment randomization that cannot be mirrored between slices. - Startup and interval events, reset events that randomize physics parameters (``randomize_*``), curriculum terms, - and observation corruption are disabled. The other reset events are kept because the reference's reset state is + Startup and interval events, reset events that randomize physics parameters, curriculum terms, and observation + corruption are disabled. The other reset events are kept because the reference's reset state is copied to the ghosts. Args: @@ -93,7 +109,12 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: mode = term.mode # A reset event that draws physics parameters (mass, friction, gains) per environment cannot be # mirrored, since the scene state copied to a ghost does not carry them. Pose resets are mirrored. - randomizes = mode == "reset" and getattr(term.func, "__name__", "").startswith("randomize_") + func = term.func + randomizes = ( + mode == "reset" + and getattr(func, "__module__", None) == "isaaclab.envs.mdp.events" + and getattr(func, "__name__", None) in _PHYSICS_RANDOMIZERS + ) if mode in ("startup", "interval") or randomizes: setattr(events, name, None) removed.append(f"events.{name}") diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index 1c804ec83973..fbe97a443a3f 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -272,8 +272,10 @@ def test_close_puts_the_ghost_environments_back_on_their_own_terrain() -> None: assert torch.equal(env.scene.terrain.terrain_levels, torch.arange(NUM_ENVS)) -def test_configure_env_cfg_also_disables_reset_events_that_randomize_physics() -> None: - def randomize_rigid_body_mass() -> None: +def test_configure_env_cfg_also_disables_reset_events_that_randomize_physics_but_keeps_a_task_s_own() -> None: + from isaaclab.envs.mdp import events as mdp_events + + def randomize_gear_type() -> None: # a task's own event: it creates state that its later reset events read pass def reset_root_state_uniform() -> None: @@ -284,9 +286,10 @@ def term(mode: str, func) -> SimpleNamespace: cfg = SimpleNamespace( events=SimpleNamespace( - mass=term("reset", randomize_rigid_body_mass), + mass=term("reset", mdp_events.randomize_rigid_body_mass), pose=term("reset", reset_root_state_uniform), - startup_mass=term("startup", randomize_rigid_body_mass), + gear=term("reset", randomize_gear_type), + startup_mass=term("startup", mdp_events.randomize_rigid_body_mass), ), curriculum=None, observations=None, @@ -295,4 +298,4 @@ def term(mode: str, func) -> SimpleNamespace: removed = CheckpointGhostSync.configure_env_cfg(cfg) assert sorted(removed) == ["events.mass", "events.startup_mass"] - assert cfg.events.pose is not None and cfg.events.mass is None # the pose reset is mirrored, so it stays + assert cfg.events.pose is not None and cfg.events.gear is not None # these are mirrored or the task's own From 807a8f1eab0c178e1df2cbe76db679a3663fa235 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 04:45:50 +0000 Subject: [PATCH 07/24] Reset each ghost slice from the reference's random state --- docs/source/concepts/visualization.rst | 4 +- ...heckpoint-ghost-relative-targets.fixed.rst | 7 +-- .../envs/utils/checkpoint_ghost_sync.py | 60 +++++++++---------- .../test/envs/test_checkpoint_ghost_sync.py | 46 +++++++------- 4 files changed, 55 insertions(+), 62 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index b49da04fa09a..dcde3285d740 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -835,8 +835,8 @@ In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. -* Startup and interval events, reset events that randomize physics parameters (mass, friction, gains), curriculum - terms, and observation noise are disabled, since they cannot be mirrored between slots. +* Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored + between slots. Reset randomization is mirrored: each ghost resets from the reference's random state. * Only RSL-RL and manager-based environments are supported. Tasks whose cameras use OVRTX, or whose curriculum selects the reset state (such as Franka Pour), are rejected at launch. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst index 82f6c1df41a3..d3bfbbbcde06 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst @@ -5,7 +5,6 @@ * Fixed Checkpoint Ghosts holding joints the actions do not drive, such as the fingers of a reaching arm, at different targets than the reference after a reset. A ghost now takes the reference's joint targets, so an identical checkpoint follows the reference. -* Fixed Checkpoint Ghosts running with different physics than the reference when a reset event randomizes mass, - friction, or actuator gains per environment. The physics randomization reset events of ``isaaclab.envs.mdp.events`` - are now disabled, like startup and interval events. Pose and velocity resets, and a task's own reset events, are - still kept and mirrored. +* Fixed Checkpoint Ghosts running with different reset randomization than the reference, such as per-environment mass, + friction, actuator gains, or a task's own sampled target. Each ghost slice now resets from the same random state as + the reference, so it draws the reference's values. diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index 899dcb69dd9f..6ccae6f555af 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -19,22 +19,6 @@ logger = logging.getLogger(__name__) -_PHYSICS_RANDOMIZERS = frozenset( - { - "randomize_rigid_body_scale", - "randomize_rigid_body_material", - "randomize_rigid_body_mass", - "randomize_rigid_body_inertia", - "randomize_rigid_body_com", - "randomize_rigid_body_collider_offsets", - "randomize_physics_scene_gravity", - "randomize_actuator_gains", - "randomize_joint_parameters", - "randomize_fixed_tendon_parameters", - } -) -"""Events of :mod:`isaaclab.envs.mdp.events` that draw physics parameters per environment.""" - _TERRAIN_FIELDS = ("terrain_levels", "terrain_types", "env_origins") """Terrain placement tensors of every environment that the ghosts copy from the reference.""" @@ -90,9 +74,9 @@ def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: """Remove per-environment randomization that cannot be mirrored between slices. - Startup and interval events, reset events that randomize physics parameters, curriculum terms, and observation - corruption are disabled. The other reset events are kept because the reference's reset state is - copied to the ghosts. + Startup and interval events, curriculum terms, and observation corruption are disabled. Reset events are kept: + every slice resets from the same random state as the reference, and the reference's reset state is copied to the + ghosts. Args: env_cfg: Environment config to modify in place. @@ -106,16 +90,7 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: for name, term in vars(events).items() if events is not None else (): if term is None: continue - mode = term.mode - # A reset event that draws physics parameters (mass, friction, gains) per environment cannot be - # mirrored, since the scene state copied to a ghost does not carry them. Pose resets are mirrored. - func = term.func - randomizes = ( - mode == "reset" - and getattr(func, "__module__", None) == "isaaclab.envs.mdp.events" - and getattr(func, "__name__", None) in _PHYSICS_RANDOMIZERS - ) - if mode in ("startup", "interval") or randomizes: + if term.mode in ("startup", "interval"): setattr(events, name, None) removed.append(f"events.{name}") for name, term in vars(curriculum).items() if curriculum is not None else (): @@ -181,8 +156,18 @@ def _reset_idx(self, env_ids: Any) -> None: if reference.numel() == 0: # ghost-only terminations wait for the reference to reset return - ghosts = (reference[None, :] + self._ghost_offsets[:, None]).reshape(-1) - self._reset_idx_original(torch.cat([reference, ghosts])) + ghost_slices = [reference + offset for offset in self._ghost_offsets.tolist()] + ghosts = torch.cat(ghost_slices) + # Every slice resets from the same random state as the reference, so reset events that draw per-environment + # values (physics parameters, a task's own sampled state such as a target choice) give each ghost the values + # of its reference environment. + start = _rng_state(self._device) + self._reset_idx_original(reference) + end = _rng_state(self._device) + for ids in ghost_slices: + _set_rng_state(self._device, start) + self._reset_idx_original(ids) + _set_rng_state(self._device, end) scene = self._env.scene state = scene.get_state(is_relative=True) source = reference.repeat(self._num_slices - 1) @@ -236,6 +221,19 @@ def _copy_command_state(self, reference: torch.Tensor) -> None: """Command tensors that express the target relative to the robot, such as those of ``UniformPose2dCommand``.""" +def _rng_state(device: Any) -> tuple[torch.Tensor, torch.Tensor | None]: + """Return the CPU and, for a CUDA device, the CUDA random state.""" + cuda = torch.device(device).type == "cuda" + return torch.get_rng_state(), torch.cuda.get_rng_state(device) if cuda else None + + +def _set_rng_state(device: Any, state: tuple[torch.Tensor, torch.Tensor | None]) -> None: + """Restore a random state returned by :func:`_rng_state`.""" + torch.set_rng_state(state[0]) + if state[1] is not None: + torch.cuda.set_rng_state(state[1], device) + + def _gather(state: dict[str, Any], ids: torch.Tensor) -> dict[str, Any]: """Index every tensor of a nested scene-state dictionary by environment id.""" return {key: _gather(value, ids) if isinstance(value, dict) else value[ids] for key, value in state.items()} diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index fbe97a443a3f..fa6f0e583215 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -78,7 +78,7 @@ def test_reference_reset_mirrors_spawn_state_to_ghost_counterparts() -> None: env._reset_idx(torch.tensor([1, 2])) - assert sorted(env.reset_calls[0]) == [1, 2, 4, 5, 7, 8] + assert env.reset_calls == [[1, 2], [4, 5], [7, 8]] # the reference first, then each ghost slice root_pos = env.scene.root_pos assert torch.equal(root_pos[[4, 5]], root_pos[[1, 2]]) assert torch.equal(root_pos[[7, 8]], root_pos[[1, 2]]) @@ -248,7 +248,7 @@ def test_a_larger_pool_resets_the_environments_beyond_the_slices_on_their_own() assert env.reset_calls == [[NUM_ENVS + 1]] env._reset_idx(torch.tensor([0])) - assert sorted(env.reset_calls[1]) == [0, 3, 6] + assert env.reset_calls[1:] == [[0], [3], [6]] env.command_manager.compute(0.02) command = env.command_manager.term.command assert torch.equal(command[SLICE_SIZE : 2 * SLICE_SIZE], command[:SLICE_SIZE]) @@ -272,30 +272,26 @@ def test_close_puts_the_ghost_environments_back_on_their_own_terrain() -> None: assert torch.equal(env.scene.terrain.terrain_levels, torch.arange(NUM_ENVS)) -def test_configure_env_cfg_also_disables_reset_events_that_randomize_physics_but_keeps_a_task_s_own() -> None: - from isaaclab.envs.mdp import events as mdp_events - - def randomize_gear_type() -> None: # a task's own event: it creates state that its later reset events read - pass - - def reset_root_state_uniform() -> None: - pass +def test_ghosts_draw_the_same_reset_randomization_as_their_reference() -> None: + env = _make_env() + sampled = torch.zeros(NUM_ENVS) # a per-environment value a reset event draws, such as a mass or a target choice + reset_idx = env._reset_idx - def term(mode: str, func) -> SimpleNamespace: - return SimpleNamespace(mode=mode, func=func) + def reset_with_randomization(env_ids: torch.Tensor) -> None: + reset_idx(env_ids) + sampled[env_ids] = torch.rand(len(env_ids)) - cfg = SimpleNamespace( - events=SimpleNamespace( - mass=term("reset", mdp_events.randomize_rigid_body_mass), - pose=term("reset", reset_root_state_uniform), - gear=term("reset", randomize_gear_type), - startup_mass=term("startup", mdp_events.randomize_rigid_body_mass), - ), - curriculum=None, - observations=None, - ) + env._reset_idx = reset_with_randomization + env.scene.reset_to = lambda state, env_ids, is_relative=False: None # only the random draws are under test + sync = CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) - removed = CheckpointGhostSync.configure_env_cfg(cfg) + env._reset_idx(torch.arange(SLICE_SIZE)) - assert sorted(removed) == ["events.mass", "events.startup_mass"] - assert cfg.events.pose is not None and cfg.events.gear is not None # these are mirrored or the task's own + reference = sampled[:SLICE_SIZE].clone() + assert (reference > 0).all() + for slot in range(1, NUM_SLICES): + assert torch.equal(sampled[slot * SLICE_SIZE : (slot + 1) * SLICE_SIZE], reference) + env._reset_idx(torch.arange(SLICE_SIZE)) + assert not torch.equal(sampled[:SLICE_SIZE], reference) # the next reset draws new values: the stream moves on + assert torch.equal(sampled[SLICE_SIZE : 2 * SLICE_SIZE], sampled[:SLICE_SIZE]) + sync.close() From cbedd3717e5cee116220f39255d7afc3a87f59aa Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 04:53:20 +0000 Subject: [PATCH 08/24] Handle recurrent policies and session edge cases, keep the reference reset log, and drop a stray export --- ...heckpoint-ghost-relative-targets.fixed.rst | 2 ++ .../envs/utils/checkpoint_ghost_sync.py | 5 ++- .../isaaclab/visualizers/__init__.pyi | 1 - .../test/envs/test_checkpoint_ghost_sync.py | 30 ++++++++++++++++ .../checkpoint-ghost-review-fixes.fixed.rst | 3 ++ .../entrypoints/checkpoint_ghosts.py | 21 +++++++----- .../test_checkpoint_ghost_session_restart.py | 34 ++++++++++++++++++- 7 files changed, 85 insertions(+), 11 deletions(-) diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst index d3bfbbbcde06..f74f472ce4e4 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst @@ -8,3 +8,5 @@ * Fixed Checkpoint Ghosts running with different reset randomization than the reference, such as per-environment mass, friction, actuator gains, or a task's own sampled target. Each ghost slice now resets from the same random state as the reference, so it draws the reference's values. +* Fixed the reference's episode log being overwritten by the ghost resets, and ``--checkpoint_ghosts`` failing on a task + with an observation group set to ``None``. diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index 6ccae6f555af..d47e1c94a326 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -98,7 +98,7 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: setattr(curriculum, name, None) removed.append(f"curriculum.{name}") for group_name, group in vars(observations).items() if observations is not None else (): - if group.enable_corruption: + if group is not None and group.enable_corruption: group.enable_corruption = False removed.append(f"observations.{group_name}.enable_corruption") if removed: @@ -163,11 +163,14 @@ def _reset_idx(self, env_ids: Any) -> None: # of its reference environment. start = _rng_state(self._device) self._reset_idx_original(reference) + reference_log = dict(self._env.extras.get("log", {})) # the ghost resets below would overwrite it end = _rng_state(self._device) for ids in ghost_slices: _set_rng_state(self._device, start) self._reset_idx_original(ids) _set_rng_state(self._device, end) + if "log" in self._env.extras: + self._env.extras["log"] = reference_log scene = self._env.scene state = scene.get_state(is_relative=True) source = reference.repeat(self._num_slices - 1) diff --git a/source/isaaclab/isaaclab/visualizers/__init__.pyi b/source/isaaclab/isaaclab/visualizers/__init__.pyi index 98b704074808..0b3134347015 100644 --- a/source/isaaclab/isaaclab/visualizers/__init__.pyi +++ b/source/isaaclab/isaaclab/visualizers/__init__.pyi @@ -16,7 +16,6 @@ __all__ = [ "CheckpointGhostLayout", "CheckpointGhostSlot", "SceneCameraCfg", - "TrackingCameraCfg", "VisualizerCfg", "VisualizerBackendCfg", "WindowCfg", diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index fa6f0e583215..e3cb3f43881e 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -60,6 +60,7 @@ def _make_env(num_envs: int = NUM_ENVS) -> SimpleNamespace: scene=_Scene(num_envs), command_manager=_CommandManager(num_envs), event_manager=object(), + extras={}, reset_calls=[], ) @@ -295,3 +296,32 @@ def reset_with_randomization(env_ids: torch.Tensor) -> None: assert not torch.equal(sampled[:SLICE_SIZE], reference) # the next reset draws new values: the stream moves on assert torch.equal(sampled[SLICE_SIZE : 2 * SLICE_SIZE], sampled[:SLICE_SIZE]) sync.close() + + +def test_the_reference_reset_keeps_its_own_log_after_the_ghost_resets() -> None: + env = _make_env() + reset_idx = env._reset_idx + calls = [] + + def reset_with_log(env_ids: torch.Tensor) -> None: + reset_idx(env_ids) + calls.append(env_ids.tolist()) + env.extras["log"] = {"Episode_Reward/return": float(len(calls))} # each call overwrites the log + + env._reset_idx = reset_with_log + sync = CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env._reset_idx(torch.arange(SLICE_SIZE)) + + assert len(calls) == NUM_SLICES and env.extras["log"] == {"Episode_Reward/return": 1.0} # the reference's + sync.close() + + +def test_configure_env_cfg_skips_an_observation_group_that_is_none() -> None: + cfg = SimpleNamespace( + events=None, + curriculum=None, + observations=SimpleNamespace(unused=None, policy=SimpleNamespace(enable_corruption=True)), + ) + + assert CheckpointGhostSync.configure_env_cfg(cfg) == ["observations.policy.enable_corruption"] diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst index f12a35fc55dc..2c7a9673f422 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -5,3 +5,6 @@ dropped the ``library`` and ``agent`` arguments of the checkpoint selector. * Fixed Checkpoint Ghosts leaving the environment's reset and command hooks installed when no Newton viewer could attach, and allocating a new action tensor on every playback step. +* Fixed Checkpoint Ghosts failing with recurrent policies when a ghost is added or removed, because the new slice size + no longer matched the hidden state. Adding, changing, or removing a ghost on an empty or unknown slot, and a failed + re-split, are now handled without ending the session. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py index f24a7389472d..fffff7f36e3b 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py @@ -39,8 +39,8 @@ class CheckpointGhostPolicy(Protocol): def __call__(self, obs: Any) -> torch.Tensor: """Return actions for the slot's observations.""" - def reset(self, dones: torch.Tensor) -> None: - """Reset recurrent state of the slot's environments that terminated.""" + def reset(self, dones: torch.Tensor | None = None) -> None: + """Reset recurrent state of the environments that terminated, or of all of them when ``dones`` is None.""" def _describe_load_error(error: Exception) -> str: @@ -138,20 +138,25 @@ def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: # noq return "All ghost slots are in use." try: self._load(empty.index, checkpoint) - empty.visible = True - self._resplit() except Exception as error: # a corrupt or mismatched checkpoint must not end the session + return f"Could not load {checkpoint.name}: {_describe_load_error(error)}" # nothing changed yet + empty.visible = True + try: + self._resplit() + except Exception as error: # the new split failed: go back to the previous one self._policies[empty.index] = None empty.checkpoint = None empty.label = "" self._resplit() - return f"Could not load {checkpoint.name}: {_describe_load_error(error)}" + return f"Could not add {checkpoint.name}: {error}" return None def replace_ghost(self, slot_index: int, checkpoint: CheckpointGhostCheckpoint) -> str | None: # noqa: D102 if not 1 <= slot_index < self.layout.num_slots: return "Only a ghost slot can be changed." slot = self.layout.slots[slot_index] + if not slot.active: + return "Only a loaded ghost can be changed; add a checkpoint to an empty slot instead." previous = (self._policies[slot_index], slot.checkpoint, slot.label) try: self._load(slot_index, checkpoint) @@ -163,8 +168,8 @@ def replace_ghost(self, slot_index: int, checkpoint: CheckpointGhostCheckpoint) return None def remove_ghost(self, slot_index: int) -> None: # noqa: D102 - if slot_index < 1: - return + if not 1 <= slot_index < self.layout.num_slots or not self.layout.slots[slot_index].active: + return # the reference cannot be removed, and an empty slot has nothing to free self._policies[slot_index] = None self.layout.slots[slot_index].checkpoint = None self.layout.slots[slot_index].label = "" @@ -182,7 +187,7 @@ def apply_pending_restart(self) -> None: # noqa: D102 self._obs, _ = self._env.reset() for policy in self._policies: if policy is not None: - policy.reset(torch.ones(self.layout.slice_size, dtype=torch.bool, device=self._env.unwrapped.device)) + policy.reset() # a full reset, since adding or removing a ghost changes the policies' batch size def step(self) -> None: """Step the environment once, with each loaded slot acting on its own observations.""" diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py b/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py index 7c42e2f02784..294ba9d8ba2e 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py @@ -43,7 +43,7 @@ def test_a_pending_restart_resets_the_environments_and_the_policies_once(): env.reset.assert_called_once_with() assert session._obs == "observations" assert session._restart_pending is False - assert torch.equal(policy.reset.call_args.args[0], torch.ones(6, dtype=torch.bool)) + policy.reset.assert_called_once_with() # a full reset: adding a ghost changes a recurrent policy's batch size def test_without_a_pending_restart_nothing_is_reset(): @@ -225,3 +225,35 @@ def test_a_load_failure_is_reported_in_one_line(): assert "does not fit this task" in _describe_load_error(mismatch) assert _describe_load_error(RuntimeError("file is corrupt\nmore detail")) == "file is corrupt" + + +def test_a_resplit_failure_goes_back_to_the_previous_split_and_reports_it(monkeypatch): + session, sync = _start(monkeypatch, [None]) + sync.side_effect = [ValueError("no room"), Mock()] # the new split fails, restoring the old one succeeds + + message = session.add_ghost(CHECKPOINT) + + assert "no room" in message + assert not session.layout.slots[1].active and session.layout.slice_size == 6 # the previous split is back + + +def test_a_load_failure_leaves_the_split_alone(monkeypatch): + session, sync = _start(monkeypatch, [None]) + session._policy_factory = Mock(side_effect=RuntimeError("size mismatch")) + + message = session.add_ghost(CHECKPOINT) + + assert "does not fit this task" in message + sync.assert_not_called() # nothing was split again, so nothing was torn down + + +def test_changing_an_empty_slot_and_removing_an_empty_or_unknown_slot_do_nothing(monkeypatch): + session, sync = _start(monkeypatch, [None]) + + assert "empty slot" in session.replace_ghost(2, CHECKPOINT) + session.remove_ghost(2) + session.remove_ghost(99) + session.remove_ghost(0) + + sync.assert_not_called() + assert not session._restart_pending or session.layout.slice_size == 6 From aef66fb1de089f83775518545d6f9280235f35dc Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 05:31:03 +0000 Subject: [PATCH 09/24] Allow tasks whose cameras use OVRTX and explain why only RSL-RL is supported --- docs/source/concepts/visualization.rst | 4 ++-- .../checkpoint-ghost-review-fixes.fixed.rst | 2 +- .../entrypoints/backends/play_rsl_rl.py | 19 ------------------- .../entrypoints/checkpoint_ghosts.py | 9 ++++++++- .../test/test_checkpoint_ghost_launch.py | 17 ----------------- 5 files changed, 11 insertions(+), 40 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index dcde3285d740..79fb621ff782 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -837,8 +837,8 @@ opacity and tint under **Appearance**. The controls are disabled in the RTX view * Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored between slots. Reset randomization is mirrored: each ghost resets from the reference's random state. -* Only RSL-RL and manager-based environments are supported. Tasks whose cameras use OVRTX, or whose curriculum selects - the reset state (such as Franka Pour), are rejected at launch. +* Only RSL-RL and manager-based environments are supported. Tasks whose curriculum selects the reset state (such as + Franka Pour) are rejected at launch. **Choosing how many environments are drawn** diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst index 2c7a9673f422..c92e9e628524 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -1,6 +1,6 @@ * Fixed ``--checkpoint_ghosts`` rejecting a run with several viewers such as ``--viz newton,viser``, and recurrent ghost policies keeping their memory across an episode - reset. Tasks whose cameras render with OVRTX are now rejected, since Checkpoint Ghosts do not support them yet. + reset. * Fixed ``--checkpoint latest`` and ``--checkpoint best`` failing in RSL-RL playback after the Checkpoint Ghosts change dropped the ``library`` and ``agent`` arguments of the checkpoint selector. * Fixed Checkpoint Ghosts leaving the environment's reset and command hooks installed when no Newton viewer could diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index 3edfbc0fa521..eb74646bfcfe 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -198,8 +198,6 @@ def _offer_checkpoint_ghosts(env: RslRlVecEnvWrapper, env_cfg: object) -> None: """Show the greyed-out Checkpoint Ghosts section in the Newton GL HUD of a run that started without the feature.""" if not isinstance(env_cfg, ManagerBasedRLEnvCfg): return - if _scene_cameras_use_ovrtx(env_cfg): # not supported with OVRTX cameras yet - return for visualizer in env.unwrapped.sim.visualizers: if hasattr(visualizer, "offer_checkpoint_ghosts"): visualizer.offer_checkpoint_ghosts() @@ -246,23 +244,6 @@ def _validate_checkpoint_ghosts(args_cli: argparse.Namespace, env_cfg: object) - raise SystemExit( f"--checkpoint_ghosts does not support this task: its curriculum term '{name}' sets the reset state." ) - if _scene_cameras_use_ovrtx(env_cfg): - raise SystemExit( - "--checkpoint_ghosts does not support tasks whose cameras use the OVRTX renderer yet." - " Use another renderer, such as renderer=newton_warp." - ) - - -def _scene_cameras_use_ovrtx(env_cfg: object) -> bool: - """Whether a scene sensor renders with OVRTX, which Checkpoint Ghosts do not support yet.""" - scene = getattr(env_cfg, "scene", None) - for value in vars(scene).values() if scene is not None else (): - if getattr(value, "render_on_demand", False) is True: - continue # the Newton viewer's own RTX camera, which launch adds and which no policy observes - renderer_cfg = getattr(value, "renderer_cfg", None) - if getattr(renderer_cfg, "renderer_type", None) == "ovrtx": - return True - return False def run(argv: list[str]) -> None: diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py index fffff7f36e3b..4e7eec1d92b1 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py @@ -3,7 +3,14 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Playback of several checkpoints of one task side by side as Checkpoint Ghosts.""" +"""Playback of several checkpoints of one task side by side as Checkpoint Ghosts. + +Only RSL-RL is supported for now. The session drives each slot through RSL-RL's pieces: the vectorized-environment +wrapper (``step`` returning observations, rewards, dones and extras, plus ``get_observations`` and ``num_actions``), an +inference policy obtained from a runner with ``runner.get_inference_policy``, and ``model_*.pt`` checkpoint files. Other +libraries differ in each of these (rl_games, skrl and Stable-Baselines3 wrap environments, call policies, and name or +store checkpoints differently), so each needs a small adapter before it can share this session. +""" from __future__ import annotations diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index f792c36b5df6..e328a2a4167e 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -37,23 +37,6 @@ def test_without_newton_the_run_is_rejected(): play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="viser"))) -def test_cameras_that_render_with_ovrtx_are_rejected(): - camera = SimpleNamespace(renderer_cfg=SimpleNamespace(renderer_type="ovrtx")) - cfg = _env_cfg(SimpleNamespace(visualizer_type="newton"), SimpleNamespace(camera=camera)) - - with pytest.raises(SystemExit, match="OVRTX"): - play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), cfg) - - -def test_the_viewer_s_own_rtx_camera_is_not_a_task_camera(): - renderer_cfg = SimpleNamespace(renderer_type="ovrtx") - scene = SimpleNamespace(viewer_camera_0_rtx=SimpleNamespace(renderer_cfg=renderer_cfg, render_on_demand=True)) - - assert not play_rsl_rl._scene_cameras_use_ovrtx(SimpleNamespace(scene=scene)) - scene.task_camera = SimpleNamespace(renderer_cfg=renderer_cfg, render_on_demand=False) - assert play_rsl_rl._scene_cameras_use_ovrtx(SimpleNamespace(scene=scene)) - - def _slots(total: int, slots: int | None): args = SimpleNamespace(checkpoint_ghost_slots=slots) play_rsl_rl._resolve_ghost_slots(args, SimpleNamespace(scene=SimpleNamespace(num_envs=total))) From 90dc8d077b34dfdedfa9f1a29983ab0f9376ec47 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 05:36:48 +0000 Subject: [PATCH 10/24] Move the checkpoint ghost session into the visualizer package --- .../checkpoint-ghost-session.added.rst | 7 ++++ .../visualizers/checkpoint_ghost_session.py} | 41 ++++++++++--------- .../test_checkpoint_ghost_session.py} | 40 ++++++++---------- .../checkpoint-ghost-review-fixes.fixed.rst | 9 +--- .../entrypoints/backends/play_rsl_rl.py | 24 ++++++++--- .../test/test_checkpoint_ghost_launch.py | 13 ++++++ 6 files changed, 80 insertions(+), 54 deletions(-) create mode 100644 source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst rename source/{isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py => isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py} (87%) rename source/{isaaclab_rl/test/test_checkpoint_ghost_session_restart.py => isaaclab/test/visualizers/test_checkpoint_ghost_session.py} (90%) diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst new file mode 100644 index 000000000000..4cdd6302f653 --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst @@ -0,0 +1,7 @@ +* Added :class:`~isaaclab.visualizers.checkpoint_ghost_session.CheckpointGhostSession`, which steps one environment whose + slices are driven by different checkpoints of one task. It splits the environments among the loaded checkpoints, + resets them together from the reference's state, and serves the checkpoint browser. It needs only an environment + wrapper and a policy factory, so a library's play entry point supplies the wiring. Only RSL-RL provides it for now. +* Fixed the session failing with recurrent policies when a ghost is added or removed, and handled a ghost added, + changed, or removed on an empty or unknown slot, and a failed re-split, without ending the session. It reuses one + action tensor for every step. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py similarity index 87% rename from source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py rename to source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py index 4e7eec1d92b1..d719df1cadcc 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/checkpoint_ghosts.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py @@ -5,16 +5,14 @@ """Playback of several checkpoints of one task side by side as Checkpoint Ghosts. -Only RSL-RL is supported for now. The session drives each slot through RSL-RL's pieces: the vectorized-environment -wrapper (``step`` returning observations, rewards, dones and extras, plus ``get_observations`` and ``num_actions``), an -inference policy obtained from a runner with ``runner.get_inference_policy``, and ``model_*.pt`` checkpoint files. Other -libraries differ in each of these (rl_games, skrl and Stable-Baselines3 wrap environments, call policies, and name or -store checkpoints differently), so each needs a small adapter before it can share this session. +The session does not depend on a training library. It needs an environment wrapper whose ``step`` returns +observations, rewards, dones and extras and that has ``get_observations``, ``reset`` and ``num_actions``, plus a +``policy_factory`` that turns a checkpoint file into a callable policy with a ``reset`` method. A library's play entry +point supplies those, so supporting another library means writing that wiring. Only RSL-RL provides it for now. """ from __future__ import annotations -import json import logging import re import time @@ -26,13 +24,8 @@ import torch from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync -from isaaclab.visualizers.checkpoint_ghost import ( - CheckpointGhostCheckpoint, - CheckpointGhostController, - CheckpointGhostLayout, -) -from .common import RUN_MANIFEST_FILENAME, _natural_sort_key, normalize_task_name +from .checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostController, CheckpointGhostLayout logger = logging.getLogger(__name__) @@ -50,6 +43,16 @@ def reset(self, dones: torch.Tensor | None = None) -> None: """Reset recurrent state of the environments that terminated, or of all of them when ``dones`` is None.""" +def _task_name(task: str) -> str: + """Return a task id without its namespace prefix.""" + return task.split(":")[-1] + + +def _natural_sort_key(value: str) -> list[int | str]: + """Order file names such as ``model_9.pt`` before ``model_10.pt``.""" + return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", value)] + + def _describe_load_error(error: Exception) -> str: """Return a one-line reason a checkpoint could not be loaded, naming a size mismatch for what it usually means.""" text = str(error) @@ -80,6 +83,7 @@ def __init__( checkpoint_pattern: str, policy_factory: Callable[[str], CheckpointGhostPolicy], reference: CheckpointGhostCheckpoint, + run_task: Callable[[str], str | None] | None = None, ): """Create the session and load the reference checkpoint. @@ -91,13 +95,16 @@ def __init__( checkpoint_pattern: Regular expression matching checkpoint file names. policy_factory: Builds the inference policy of a checkpoint file. reference: Checkpoint driving slot 0. + run_task: Returns the task of the training run saved in a directory, or None when it is not a run. Without + it, the checkpoint window does not flag runs of other tasks. """ if not 2 <= num_slots <= MAX_CHECKPOINT_GHOST_SLOTS: raise ValueError(f"Checkpoint Ghosts support 2 to {MAX_CHECKPOINT_GHOST_SLOTS} slots, got {num_slots}.") self.layout = CheckpointGhostLayout(env.unwrapped.num_envs, num_slots) self._env = env self._root = checkpoint_root - self._task = normalize_task_name(task) + self._task = _task_name(task) + self._run_task = run_task self._pattern = checkpoint_pattern self._policy_factory = policy_factory self._policies: list[CheckpointGhostPolicy | None] = [None] * num_slots @@ -132,12 +139,8 @@ def browse(self, directory: str) -> tuple[list[str], list[CheckpointGhostCheckpo ] def other_task(self, directory: str) -> str | None: # noqa: D102 - try: - manifest = json.loads((Path(directory) / RUN_MANIFEST_FILENAME).read_text(encoding="utf-8")) - task = manifest["task"] - except (OSError, ValueError, KeyError, TypeError): - return None # not a run directory, or one without a readable manifest - return task if isinstance(task, str) and normalize_task_name(task) != self._task else None + task = self._run_task(directory) if self._run_task is not None else None + return task if isinstance(task, str) and _task_name(task) != self._task else None def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: # noqa: D102 empty = next((s for s in self.layout.slots[1:] if not s.active), None) diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py similarity index 90% rename from source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py rename to source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py index 294ba9d8ba2e..9d38286b910d 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_session_restart.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py @@ -13,9 +13,9 @@ import pytest import torch +from isaaclab.visualizers import checkpoint_ghost_session as checkpoint_ghosts from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostLayout - -from isaaclab_rl.entrypoints.checkpoint_ghosts import CheckpointGhostSession +from isaaclab.visualizers.checkpoint_ghost_session import CheckpointGhostSession CHECKPOINT = CheckpointGhostCheckpoint("/runs/a/model_1.pt", "a", "model_1.pt", 0.0) @@ -121,8 +121,6 @@ def test_a_ghost_policy_resets_with_its_reference(dones, expected): def _start(monkeypatch, observations): - from isaaclab_rl.entrypoints import checkpoint_ghosts - sync = Mock() monkeypatch.setattr(checkpoint_ghosts, "CheckpointGhostSync", sync) env = Mock(unwrapped=SimpleNamespace(device="cpu", step_dt=0.02, num_envs=6)) @@ -200,26 +198,8 @@ def test_browsing_an_unreadable_directory_raises_os_error(tmp_path): session.browse(str(tmp_path / "missing")) -def test_a_run_of_another_task_is_named_and_a_matching_or_unknown_directory_is_not(tmp_path): - import json - - session, _, _ = _session(pending=False) - session._task = "Isaac-Reach-Franka" - for name, task in (("same", "isaac:Isaac-Reach-Franka"), ("osc", "Isaac-Reach-Franka-OSC")): - (tmp_path / name).mkdir() - (tmp_path / name / "run.json").write_text(json.dumps({"task": task})) - (tmp_path / "plain").mkdir() - (tmp_path / "bad").mkdir() - (tmp_path / "bad" / "run.json").write_text("not json") - - assert session.other_task(str(tmp_path / "osc")) == "Isaac-Reach-Franka-OSC" - assert session.other_task(str(tmp_path / "same")) is None # a namespace prefix does not make it another task - assert session.other_task(str(tmp_path / "plain")) is None - assert session.other_task(str(tmp_path / "bad")) is None - - def test_a_load_failure_is_reported_in_one_line(): - from isaaclab_rl.entrypoints.checkpoint_ghosts import _describe_load_error + from isaaclab.visualizers.checkpoint_ghost_session import _describe_load_error mismatch = RuntimeError("Error(s) in loading state_dict:\n size mismatch for mlp.0.weight: copying a param") @@ -257,3 +237,17 @@ def test_changing_an_empty_slot_and_removing_an_empty_or_unknown_slot_do_nothing sync.assert_not_called() assert not session._restart_pending or session.layout.slice_size == 6 + + +def test_a_run_of_another_task_is_named_and_a_matching_or_unknown_directory_is_not(): + session, _, _ = _session(pending=False) + session._task = "Isaac-Reach-Franka" + tasks = {"/runs/osc": "Isaac-Reach-Franka-OSC", "/runs/same": "isaac:Isaac-Reach-Franka", "/runs/plain": None} + session._run_task = tasks.get + + assert session.other_task("/runs/osc") == "Isaac-Reach-Franka-OSC" + assert session.other_task("/runs/same") is None # a namespace prefix does not make it another task + assert session.other_task("/runs/plain") is None + + session._run_task = None # without a reader, no run is flagged + assert session.other_task("/runs/osc") is None diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst index c92e9e628524..e2f47e914650 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -1,10 +1,5 @@ -* Fixed ``--checkpoint_ghosts`` rejecting a run with - several viewers such as ``--viz newton,viser``, and recurrent ghost policies keeping their memory across an episode - reset. +* Fixed ``--checkpoint_ghosts`` rejecting a run with several viewers such as ``--viz newton,viser``. * Fixed ``--checkpoint latest`` and ``--checkpoint best`` failing in RSL-RL playback after the Checkpoint Ghosts change dropped the ``library`` and ``agent`` arguments of the checkpoint selector. * Fixed Checkpoint Ghosts leaving the environment's reset and command hooks installed when no Newton viewer could - attach, and allocating a new action tensor on every playback step. -* Fixed Checkpoint Ghosts failing with recurrent policies when a ghost is added or removed, because the new slice size - no longer matched the hidden state. Adding, changing, or removing a ghost on an empty or unknown slot, and a failed - re-split, are now handled without ending the session. + attach. diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index eb74646bfcfe..f6915d6cc569 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -9,6 +9,7 @@ import argparse import contextlib +import json import logging import os from pathlib import Path @@ -20,18 +21,16 @@ from isaaclab.utils.seed import configure_seed from isaaclab.utils.string import list_intersection from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint +from isaaclab.visualizers.checkpoint_ghost_session import MAX_CHECKPOINT_GHOST_SLOTS, CheckpointGhostSession import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli from ...rsl_rl import RslRlBaseRunnerCfg, RslRlSacRunnerCfg, RslRlVecEnvWrapper from ...utils.wandb import is_wandb_checkpoint, resolve_wandb_checkpoint -from ..checkpoint_ghosts import ( - MAX_CHECKPOINT_GHOST_SLOTS, - CheckpointGhostSession, -) from ..common import ( CHECKPOINT_SELECTORS, + RUN_MANIFEST_FILENAME, add_common_play_args, apply_env_overrides, apply_video_recording, @@ -136,6 +135,14 @@ def _resolve_checkpoint( return get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) +def _run_task(directory: str) -> str | None: + """Return the task named by the run manifest in ``directory``, or None when it is not a training run.""" + try: + return json.loads((Path(directory) / RUN_MANIFEST_FILENAME).read_text(encoding="utf-8"))["task"] + except (OSError, ValueError, KeyError, TypeError): + return None + + def create_checkpoint_ghost_session( env: RslRlVecEnvWrapper, args_cli: argparse.Namespace, @@ -144,7 +151,13 @@ def create_checkpoint_ghost_session( log_root_path: str, num_slots: int, ) -> CheckpointGhostSession: - """Build a Checkpoint Ghost session whose reference slot plays ``reference_path``.""" + """Build a Checkpoint Ghost session whose reference slot plays ``reference_path``. + + Checkpoint Ghosts are available for RSL-RL only because this function is the RSL-RL wiring of an otherwise + library-independent session: the environment wrapper it drives (``RslRlVecEnvWrapper``), the policy factory below + (a runner's ``get_inference_policy``), and the ``model_*.pt`` checkpoint files. rl_games, skrl and SB3 wrap + environments, call policies, and store checkpoints differently, so each needs its own version of this wiring. + """ def policy_factory(path: str): runner = create_rsl_rl_runner(env, agent_cfg, inference=True) @@ -162,6 +175,7 @@ def policy_factory(path: str): reference=CheckpointGhostCheckpoint( reference_path, reference_file.parent.name, reference_file.name, reference_file.stat().st_mtime ), + run_task=_run_task, ) diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index e328a2a4167e..98769c3eb2d8 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -122,3 +122,16 @@ def test_the_session_is_closed_when_no_viewer_can_attach(monkeypatch): ) session.close.assert_called_once() # its reset and command hooks must not stay installed + + +def test_the_task_of_a_run_is_read_from_its_manifest(tmp_path): + import json + + (tmp_path / "run").mkdir() + (tmp_path / "run" / "run.json").write_text(json.dumps({"task": "Isaac-Reach-Franka-OSC"})) + (tmp_path / "bad").mkdir() + (tmp_path / "bad" / "run.json").write_text("not json") + + assert play_rsl_rl._run_task(str(tmp_path / "run")) == "Isaac-Reach-Franka-OSC" + assert play_rsl_rl._run_task(str(tmp_path / "bad")) is None + assert play_rsl_rl._run_task(str(tmp_path / "missing")) is None From e12da674427c078f425ebb134bfb82b8696654ab Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 05:45:09 +0000 Subject: [PATCH 11/24] Skip stale policy resets when the split changes mid-step and read run manifests once --- docs/source/concepts/visualization.rst | 4 ++- .../checkpoint-ghost-session.added.rst | 2 ++ .../visualizers/checkpoint_ghost_session.py | 9 ++++++- .../test_checkpoint_ghost_session.py | 27 +++++++++++++++++++ .../newton/newton_checkpoint_ghosts.py | 13 +++++++-- .../newton/newton_visualizer.py | 1 - .../test/test_newton_checkpoint_ghosts.py | 17 ++++++++++++ 7 files changed, 68 insertions(+), 5 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 79fb621ff782..1d1674b056b5 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -836,7 +836,9 @@ the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. * Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored - between slots. Reset randomization is mirrored: each ghost resets from the reference's random state. + between slots, so the reference plays without disturbances such as pushes and can look steadier than in training. + Reset randomization is mirrored: each ghost resets from the reference's random state. Randomness that does not come + from torch's generators (numpy, warp) is not mirrored. * Only RSL-RL and manager-based environments are supported. Tasks whose curriculum selects the reset state (such as Franka Pour) are rejected at launch. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst index 4cdd6302f653..dd636a3586b3 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst @@ -5,3 +5,5 @@ * Fixed the session failing with recurrent policies when a ghost is added or removed, and handled a ghost added, changed, or removed on an empty or unknown slot, and a failed re-split, without ending the session. It reuses one action tensor for every step. +* Fixed the session resetting policies with a stale slice size when a ghost is added or removed while the environment + steps, and a failed rollback after a failed re-split raising out of the viewer instead of returning a message. diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py index d719df1cadcc..ecd7e51a29d6 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py @@ -157,7 +157,10 @@ def add_ghost(self, checkpoint: CheckpointGhostCheckpoint) -> str | None: # noq self._policies[empty.index] = None empty.checkpoint = None empty.label = "" - self._resplit() + try: + self._resplit() + except Exception: # the previous split cannot be rebuilt either: leave the environment unsynchronized + logger.exception("Could not restore the previous Checkpoint Ghost split.") return f"Could not add {checkpoint.name}: {error}" return None @@ -212,6 +215,10 @@ def step(self) -> None: chunk = slice(start, start + size) actions[chunk] = self._policies[slot.index](self._obs[chunk]) self._obs, _, dones, _ = self._env.step(actions) + if self._restart_pending: + # The viewer can add or remove a ghost while the environment steps. The split then changed, so this step's + # dones no longer line up with the slots; the restart resets every environment and policy before the next. + return reference_dones = dones[:size] for slot in self.layout.active_slots: # A ghost resets with its reference, so a ghost that fell alone keeps its memory until then. diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py index 9d38286b910d..1125e403f7e7 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py @@ -251,3 +251,30 @@ def test_a_run_of_another_task_is_named_and_a_matching_or_unknown_directory_is_n session._run_task = None # without a reader, no run is flagged assert session.other_task("/runs/osc") is None + + +def test_a_ghost_added_while_the_environment_steps_skips_the_stale_policy_resets(): + session, env, policy = _session(pending=False) + session._obs = torch.zeros(6, 1) + env.num_envs, env.num_actions = 6, 1 + policy.return_value = torch.zeros(6, 1) + + def step(actions): + session._restart_pending = True # the viewer added a ghost during the step, changing the split + return torch.zeros(6, 1), torch.zeros(6), torch.zeros(6, dtype=torch.bool), {} + + env.step.side_effect = step + + session.step() + + policy.reset.assert_not_called() # the pending restart resets every policy before the next step + + +def test_a_failed_rollback_after_a_failed_resplit_still_returns_a_message(monkeypatch): + session, sync = _start(monkeypatch, [None]) + sync.side_effect = ValueError("no room") # both the new split and the rollback fail + + message = session.add_ghost(CHECKPOINT) + + assert "no room" in message # reported to the viewer instead of raised + assert not session.layout.slots[1].active and session._sync is None diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py index 920a243ff8a7..2c1acdcd9580 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py @@ -66,6 +66,8 @@ def __init__(self, controller: CheckpointGhostController): self._directory: str | None = None """Directory the checkpoint window shows; it keeps the last one across openings and selections.""" self._folders: list[str] = [] + self._task_cache: dict[str, str | None] = {} + """Task of each directory read so far, so reopening or navigating does not read every run manifest again.""" self._other_tasks: dict[str, str] = {} """Task of each listed folder (and of the current one, under ``""``) that is a run of another task.""" self._files: list[CheckpointGhostCheckpoint] = [] @@ -279,8 +281,8 @@ def _refresh(self) -> None: self._other_tasks = { name: task for name, task in ( - ("", self.controller.other_task(self._directory)), - *((f, self.controller.other_task(os.path.join(self._directory, f))) for f in self._folders), + ("", self._other_task(self._directory)), + *((f, self._other_task(os.path.join(self._directory, f))) for f in self._folders), ) if task is not None } @@ -288,6 +290,12 @@ def _refresh(self) -> None: self._folders, self._files, self._other_tasks = [], [], {} self._browse_error = f"Cannot read this folder: {error.strerror or error}" + def _other_task(self, directory: str) -> str | None: + """Return the other task a run directory belongs to, reading its manifest only once.""" + if directory not in self._task_cache: + self._task_cache[directory] = self.controller.other_task(directory) + return self._task_cache[directory] + def _go(self, directory: str) -> None: self._directory = os.path.abspath(directory) self._refresh() @@ -306,6 +314,7 @@ def _draw_window(self, imgui: Any) -> None: imgui.set_tooltip("Go to the parent folder") imgui.same_line() if imgui.button("Refresh"): + self._task_cache.clear() # a run may have been added or changed since it was read self._refresh() if imgui.is_item_hovered(): imgui.set_tooltip("List this folder again, such as for checkpoints training just saved") diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index 8f9d701989c4..f3dcb8fb93e4 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -1660,7 +1660,6 @@ def __init__(self, cfg: VisualizerCfg): self._checkpoint_ghost_panel: NewtonCheckpointGhostPanel | None = None self._base_world_offsets: np.ndarray | None = None """World offsets without the Checkpoint Ghost overlay, which the overlay is added to every frame it changes.""" - """Checkpoint Ghost offsets last given to the OVRTX view, to skip rewriting poses when they are unchanged.""" # ------------------------------------------------------------------ # GL lifecycle diff --git a/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py index dfbc44b63858..87dcd4263097 100644 --- a/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py +++ b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py @@ -426,3 +426,20 @@ def test_the_ghost_controls_are_disabled_in_the_rtx_view_with_a_note_to_switch_r assert not any("RTX:" in text for text in imgui.texts) assert imgui.depth == 0 and not any(disabled for _, disabled in imgui.disabled_buttons) panel._draw_window.assert_called_once() + + +def test_run_manifests_are_read_once_per_folder_until_refresh_is_clicked(): + tree = {"/runs/task": (["a", "b"], []), "/runs/task/a": ([], []), "/runs/task/b": ([], [])} + controller = _Browser(CheckpointGhostLayout(POOL, 3), tree) + reads = [] + controller.other_task = lambda directory: reads.append(directory) + panel = NewtonCheckpointGhostPanel(controller) + + panel._open_window() + panel._open_window() # reopening the window lists the folder again + + assert sorted(reads) == ["/runs/task", "/runs/task/a", "/runs/task/b"] + + panel._draw_window(_BrowserImgui(clicks=["Refresh"])) + + assert len(reads) == 6 # Refresh reads them again, since a run may have changed From fcc3f4e84b03ec2a99c7e093b0028cb7ae65452f Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:06:52 +0000 Subject: [PATCH 12/24] Move Checkpoint Ghosts play helpers out of the RSL-RL play script The play script now only calls guarded hooks in isaaclab.visualizers.checkpoint_ghost_play (flags, launch checks, slot resolving, the HUD offer and the run loop), so a plain play run is unchanged and other libraries can reuse the helpers. --- .../visualizers/checkpoint_ghost_play.py | 182 +++++++++++++++++ .../visualizers/test_checkpoint_ghost_play.py | 171 ++++++++++++++++ .../entrypoints/backends/play_rsl_rl.py | 191 ++---------------- .../test/test_checkpoint_ghost_launch.py | 110 +--------- 4 files changed, 375 insertions(+), 279 deletions(-) create mode 100644 source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py create mode 100644 source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py new file mode 100644 index 000000000000..280b2905d1ee --- /dev/null +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -0,0 +1,182 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""The library-independent parts of Checkpoint Ghosts that a ``play`` script calls. + +A play script adds the flags with :func:`add_args`, checks and prepares the run with :func:`check` and :func:`prepare`, +shows the greyed-out HUD section of a plain run with :func:`offer`, and hands its policy loading and playback loop to +``run`` when ``--checkpoint_ghosts`` is set. Every function but :func:`add_args`, :func:`offer`, and :func:`run` does +nothing without the flag, so a script that does not use the feature behaves exactly as before. +""" + +from __future__ import annotations + +import argparse +import json +import logging +import os +from collections.abc import Callable +from pathlib import Path +from typing import Any + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync +from isaaclab.utils.seed import configure_seed + +from .checkpoint_ghost import CheckpointGhostCheckpoint +from .checkpoint_ghost_session import MAX_CHECKPOINT_GHOST_SLOTS, CheckpointGhostSession + +logger = logging.getLogger(__name__) + +_RUN_MANIFEST_FILENAME = "run.json" +"""Name of the manifest that training writes into a run directory (``isaaclab_rl.entrypoints.common``).""" + + +def add_args(parser: argparse.ArgumentParser) -> None: + """Add the Checkpoint Ghosts flags to a play script's parser.""" + parser.add_argument( + "--checkpoint_ghosts", + action="store_true", + default=False, + help=( + "Enable Checkpoint Ghosts, the checkpoint visualization in the Newton GL viewer. The --checkpoint drives" + " the reference; ghosts are added from the viewer HUD. --num_envs is the total simulated and is split" + " evenly among the checkpoints shown." + ), + ) + parser.add_argument( + "--checkpoint_ghost_slots", + type=int, + default=None, + help=( + f"Most checkpoints shown at once, including the reference (2 to {MAX_CHECKPOINT_GHOST_SLOTS}). Defaults to" + f" {MAX_CHECKPOINT_GHOST_SLOTS}, capped at --num_envs." + ), + ) + parser.add_argument( + "--checkpoint_ghost_root", + default=None, + help="Directory searched for ghost checkpoints. Defaults to the experiment's log directory.", + ) + + +def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: + """Reject a configuration Checkpoint Ghosts cannot run, before any simulation starts. + + Does nothing without ``--checkpoint_ghosts``. + """ + if not args_cli.checkpoint_ghosts: + return + slots = args_cli.checkpoint_ghost_slots + if slots is not None and not 2 <= slots <= MAX_CHECKPOINT_GHOST_SLOTS: + raise SystemExit(f"--checkpoint_ghost_slots must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") + if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + raise SystemExit("--checkpoint_ghosts only supports manager-based environments.") + visualizers = env_cfg.sim.visualizer_cfgs or [] + if not isinstance(visualizers, (list, tuple)): + visualizers = [visualizers] + # A shared visualizer configuration names its type on its backend; a deprecated combined one names it directly. + types = [] + for cfg in visualizers: + backend = getattr(cfg, "backend", None) + for chosen in backend if isinstance(backend, (list, tuple)) else [backend]: # --viz newton,viser selects both + types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) + if "newton" not in types: + raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") + curriculum = env_cfg.curriculum + for name, term in vars(curriculum).items() if curriculum is not None else (): + # Checkpoint Ghosts disable curriculum terms, so a task whose reset events read a term's state cannot run. + if getattr(getattr(term, "func", None), "supports_checkpoint_ghosts", True) is False: + raise SystemExit( + f"--checkpoint_ghosts does not support this task: its curriculum term '{name}' sets the reset state." + ) + + +def prepare(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg) -> None: + """Resolve the slot count and disable randomization that cannot be mirrored, before the environment is created. + + ``--num_envs`` is the total simulated; the environments are split among the loaded checkpoints, so every slot needs + at least one. Does nothing without ``--checkpoint_ghosts``. + """ + if not args_cli.checkpoint_ghosts: + return + total = env_cfg.scene.num_envs + if total < 2: + raise SystemExit("--checkpoint_ghosts needs --num_envs of at least 2: one environment per checkpoint.") + slots = args_cli.checkpoint_ghost_slots + if slots is None: + slots = MAX_CHECKPOINT_GHOST_SLOTS + if slots > total: + if args_cli.checkpoint_ghost_slots is not None: + logger.warning(f"--checkpoint_ghost_slots {slots} exceeds --num_envs {total}; using {total} slots.") + slots = total + args_cli.checkpoint_ghost_slots = min(slots, MAX_CHECKPOINT_GHOST_SLOTS) + CheckpointGhostSync.configure_env_cfg(env_cfg) + + +def offer(env: Any, env_cfg: Any) -> None: + """Show the greyed-out Checkpoint Ghosts section in the Newton GL HUD of a run that started without the feature.""" + if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + return + for visualizer in env.unwrapped.sim.visualizers: + if hasattr(visualizer, "offer_checkpoint_ghosts"): + visualizer.offer_checkpoint_ghosts() + + +def run( + env: Any, + args_cli: argparse.Namespace, + *, + policy_factory: Callable[[str], Any], + checkpoint_pattern: str, + reference_path: str, + log_root_path: str, + run_playback: Callable[..., None], +) -> None: + """Play the reference checkpoint with ghost slots that the Newton GL viewer HUD fills. + + Args: + env: The library's environment wrapper. + args_cli: Parsed play arguments. + policy_factory: Builds the inference policy of a checkpoint file. + checkpoint_pattern: Regular expression matching the library's checkpoint file names. + reference_path: Checkpoint driving the reference slot. + log_root_path: The experiment's log directory, where the checkpoint window starts by default. + run_playback: The play script's playback loop, called with ``step``, ``dt``, ``args_cli`` and ``env_cfg``. + """ + if args_cli.deterministic: + configure_seed(env.unwrapped.cfg.seed, torch_deterministic=True) # no runner is built here, so seed up front + reference_file = Path(reference_path) + session = CheckpointGhostSession( + env, + num_slots=args_cli.checkpoint_ghost_slots, + task=args_cli.task, + checkpoint_root=os.path.abspath(args_cli.checkpoint_ghost_root or log_root_path), + checkpoint_pattern=checkpoint_pattern, + policy_factory=policy_factory, + reference=CheckpointGhostCheckpoint( + reference_path, reference_file.parent.name, reference_file.name, reference_file.stat().st_mtime + ), + run_task=_run_task, + ) + try: # the session patches the environment's reset and commands, which must be undone on any failure + attached = False + for visualizer in env.unwrapped.sim.visualizers: + if hasattr(visualizer, "attach_checkpoint_ghosts"): + visualizer.attach_checkpoint_ghosts(session) + attached = True + if not attached: + raise RuntimeError("--checkpoint_ghosts needs an initialized Newton GL visualizer.") + run_playback(session.step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env.unwrapped.cfg) + finally: + session.close() + + +def _run_task(directory: str) -> str | None: + """Return the task named by the run manifest in ``directory``, or None when it is not a training run.""" + try: + return json.loads((Path(directory) / _RUN_MANIFEST_FILENAME).read_text(encoding="utf-8"))["task"] + except (OSError, ValueError, KeyError, TypeError): + return None diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py new file mode 100644 index 000000000000..252538a5b5a7 --- /dev/null +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -0,0 +1,171 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Launch checks and session building that play scripts share for Checkpoint Ghosts.""" + +from __future__ import annotations + +import json +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from isaaclab.envs import ManagerBasedRLEnvCfg +from isaaclab.visualizers import checkpoint_ghost_play as play + + +def _env_cfg(backend, scene=None, curriculum=None): + cfg = ManagerBasedRLEnvCfg.__new__(ManagerBasedRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=backend)]) + cfg.scene = scene or SimpleNamespace() + cfg.curriculum = curriculum + return cfg + + +def _args(**kwargs): + return SimpleNamespace(checkpoint_ghosts=True, checkpoint_ghost_slots=None, **kwargs) + + +def test_nothing_is_checked_or_changed_without_the_flag(): + args = SimpleNamespace(checkpoint_ghosts=False, checkpoint_ghost_slots=99) + + play.check(args, object()) + play.prepare(args, object()) + + assert args.checkpoint_ghost_slots == 99 + + +def test_newton_among_several_selected_viewers_is_accepted(): + backends = [SimpleNamespace(visualizer_type="viser"), SimpleNamespace(visualizer_type="newton")] + + play.check(_args(), _env_cfg(backends)) + + +def test_without_newton_the_run_is_rejected(): + with pytest.raises(SystemExit, match="requires the Newton"): + play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="viser"))) + + +def test_a_slot_count_out_of_range_is_rejected(): + args = _args() + args.checkpoint_ghost_slots = 1 + + with pytest.raises(SystemExit, match="between 2 and"): + play.check(args, object()) + + +def test_a_task_whose_curriculum_selects_the_reset_state_is_rejected(): + class _ResetStateCurriculum: + supports_checkpoint_ghosts = False + + curriculum = SimpleNamespace(reset_dataset=SimpleNamespace(func=_ResetStateCurriculum)) + + with pytest.raises(SystemExit, match="reset_dataset"): + play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum)) + + +def test_an_ordinary_curriculum_term_is_accepted(): + curriculum = SimpleNamespace(terrain_levels=SimpleNamespace(func=lambda env, env_ids: None)) + + play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum)) + + +def _slots(monkeypatch, total: int, slots: int | None): + monkeypatch.setattr(play.CheckpointGhostSync, "configure_env_cfg", Mock()) + args = _args() + args.checkpoint_ghost_slots = slots + play.prepare(args, SimpleNamespace(scene=SimpleNamespace(num_envs=total))) + return args.checkpoint_ghost_slots + + +def test_the_slots_default_to_eight_capped_at_num_envs(monkeypatch): + assert _slots(monkeypatch, 64, None) == 8 + assert _slots(monkeypatch, 3, None) == 3 + + +def test_more_slots_than_environments_are_capped(monkeypatch): + assert _slots(monkeypatch, 4, 6) == 4 + assert _slots(monkeypatch, 32, 5) == 5 + + +def test_a_single_environment_cannot_be_split(monkeypatch): + with pytest.raises(SystemExit, match="at least 2"): + _slots(monkeypatch, 1, None) + + +def test_the_session_is_built_from_the_play_arguments(monkeypatch, tmp_path): + created = {} + + class _Session: + def __init__(self, env, **kwargs): + created.update(kwargs) + + def step(self): + pass + + def close(self): + pass + + monkeypatch.setattr(play, "CheckpointGhostSession", _Session) + checkpoint = tmp_path / "run" / "model_5.pt" + checkpoint.parent.mkdir() + checkpoint.touch() + viewer = Mock() + env = SimpleNamespace(unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=[viewer]), step_dt=0.02, cfg="cfg")) + args = SimpleNamespace( + checkpoint_ghost_root=None, checkpoint_ghost_slots=4, task="Isaac-Reach-Franka", deterministic=False + ) + run_playback = Mock() + + play.run( + env, + args, + policy_factory=Mock(), + checkpoint_pattern=r"model_.*\.pt", + reference_path=str(checkpoint), + log_root_path=str(tmp_path), + run_playback=run_playback, + ) + + assert created["num_slots"] == 4 + assert created["task"] == "Isaac-Reach-Franka" + assert created["checkpoint_root"] == str(tmp_path) + assert created["reference"].name == "model_5.pt" + viewer.attach_checkpoint_ghosts.assert_called_once() + run_playback.assert_called_once() + + +def test_the_session_is_closed_when_no_viewer_can_attach(monkeypatch, tmp_path): + session = Mock() + monkeypatch.setattr(play, "CheckpointGhostSession", Mock(return_value=session)) + checkpoint = tmp_path / "model_5.pt" + checkpoint.touch() + env = SimpleNamespace(unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=[object()]), step_dt=0.02)) + args = SimpleNamespace(checkpoint_ghost_root=None, checkpoint_ghost_slots=2, task="t", deterministic=False) + + with pytest.raises(RuntimeError, match="initialized Newton GL visualizer"): + play.run( + env, + args, + policy_factory=Mock(), + checkpoint_pattern="", + reference_path=str(checkpoint), + log_root_path=str(tmp_path), + run_playback=Mock(), + ) + + session.close.assert_called_once() # its reset and command hooks must not stay installed + + +def test_the_task_of_a_run_is_read_from_its_manifest(tmp_path): + (tmp_path / "run").mkdir() + (tmp_path / "run" / "run.json").write_text(json.dumps({"task": "Isaac-Reach-Franka-OSC"})) + (tmp_path / "bad").mkdir() + (tmp_path / "bad" / "run.json").write_text("not json") + + assert play._run_task(str(tmp_path / "run")) == "Isaac-Reach-Franka-OSC" + assert play._run_task(str(tmp_path / "bad")) is None + assert play._run_task(str(tmp_path / "missing")) is None diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index f6915d6cc569..c5d38312bb35 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -9,19 +9,15 @@ import argparse import contextlib -import json import logging import os -from pathlib import Path from isaaclab.app import add_launcher_args, launch_simulation -from isaaclab.envs import DirectMARLEnvCfg, ManagerBasedRLEnvCfg -from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync +from isaaclab.envs import DirectMARLEnvCfg from isaaclab.utils.assets import retrieve_file_path from isaaclab.utils.seed import configure_seed from isaaclab.utils.string import list_intersection -from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint -from isaaclab.visualizers.checkpoint_ghost_session import MAX_CHECKPOINT_GHOST_SLOTS, CheckpointGhostSession +from isaaclab.visualizers import checkpoint_ghost_play import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli @@ -30,7 +26,6 @@ from ...utils.wandb import is_wandb_checkpoint, resolve_wandb_checkpoint from ..common import ( CHECKPOINT_SELECTORS, - RUN_MANIFEST_FILENAME, add_common_play_args, apply_env_overrides, apply_video_recording, @@ -67,30 +62,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: parser.add_argument( "--external_callback", default=None, help="Fully qualified path to an externally defined callback." ) - parser.add_argument( - "--checkpoint_ghosts", - action="store_true", - default=False, - help=( - "Enable Checkpoint Ghosts, the checkpoint visualization in the Newton GL viewer. The --checkpoint drives" - " the reference; ghosts are added from the viewer HUD. --num_envs is the total simulated and is split" - " evenly among the checkpoints shown." - ), - ) - parser.add_argument( - "--checkpoint_ghost_slots", - type=int, - default=None, - help=( - f"Most checkpoints shown at once, including the reference (2 to {MAX_CHECKPOINT_GHOST_SLOTS}). Defaults to" - f" {MAX_CHECKPOINT_GHOST_SLOTS}, capped at --num_envs." - ), - ) - parser.add_argument( - "--checkpoint_ghost_root", - default=None, - help="Directory searched for ghost checkpoints. Defaults to the experiment's log directory.", - ) + checkpoint_ghost_play.add_args(parser) cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) remaining_args_env_registration = cli_args.register_external_tasks(argv) @@ -99,11 +71,6 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: _, remaining_args_env_registration = setup_preset_cli(parser, remaining_args_env_registration) enable_cameras_for_video(args_cli) set_hydra_args(list_intersection(remaining_args, remaining_args_env_registration)) - if ( - args_cli.checkpoint_ghost_slots is not None - and not 2 <= args_cli.checkpoint_ghost_slots <= MAX_CHECKPOINT_GHOST_SLOTS - ): - raise SystemExit(f"--checkpoint_ghost_slots must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") return args_cli @@ -135,139 +102,13 @@ def _resolve_checkpoint( return get_checkpoint_path(log_root_path, agent_cfg.load_run, agent_cfg.load_checkpoint) -def _run_task(directory: str) -> str | None: - """Return the task named by the run manifest in ``directory``, or None when it is not a training run.""" - try: - return json.loads((Path(directory) / RUN_MANIFEST_FILENAME).read_text(encoding="utf-8"))["task"] - except (OSError, ValueError, KeyError, TypeError): - return None - - -def create_checkpoint_ghost_session( - env: RslRlVecEnvWrapper, - args_cli: argparse.Namespace, - agent_cfg: RslRlBaseRunnerCfg, - reference_path: str, - log_root_path: str, - num_slots: int, -) -> CheckpointGhostSession: - """Build a Checkpoint Ghost session whose reference slot plays ``reference_path``. - - Checkpoint Ghosts are available for RSL-RL only because this function is the RSL-RL wiring of an otherwise - library-independent session: the environment wrapper it drives (``RslRlVecEnvWrapper``), the policy factory below - (a runner's ``get_inference_policy``), and the ``model_*.pt`` checkpoint files. rl_games, skrl and SB3 wrap - environments, call policies, and store checkpoints differently, so each needs its own version of this wiring. - """ - - def policy_factory(path: str): - runner = create_rsl_rl_runner(env, agent_cfg, inference=True) - runner.load(path) - return runner.get_inference_policy(device=env.unwrapped.device) - - reference_file = Path(reference_path) - return CheckpointGhostSession( - env, - num_slots=num_slots, - task=args_cli.task, - checkpoint_root=os.path.abspath(args_cli.checkpoint_ghost_root or log_root_path), - checkpoint_pattern=r"model_.*\.pt", - policy_factory=policy_factory, - reference=CheckpointGhostCheckpoint( - reference_path, reference_file.parent.name, reference_file.name, reference_file.stat().st_mtime - ), - run_task=_run_task, - ) - - -def run_checkpoint_ghosts( - env: RslRlVecEnvWrapper, - args_cli: argparse.Namespace, - agent_cfg: RslRlBaseRunnerCfg, - reference_path: str, - log_root_path: str, -) -> None: - """Play the reference checkpoint with ghost slots that the Newton GL viewer HUD fills.""" - session = create_checkpoint_ghost_session( - env, args_cli, agent_cfg, reference_path, log_root_path, args_cli.checkpoint_ghost_slots - ) - try: # the session patches the environment's reset and commands, which must be undone on any failure - attached = False - for visualizer in env.unwrapped.sim.visualizers: - if hasattr(visualizer, "attach_checkpoint_ghosts"): - visualizer.attach_checkpoint_ghosts(session) - attached = True - if not attached: - raise RuntimeError("--checkpoint_ghosts needs an initialized Newton GL visualizer.") - run_playback( - session.step, - dt=env.unwrapped.step_dt, - args_cli=args_cli, - env_cfg=env.unwrapped.cfg, - ) - finally: - session.close() - - -def _offer_checkpoint_ghosts(env: RslRlVecEnvWrapper, env_cfg: object) -> None: - """Show the greyed-out Checkpoint Ghosts section in the Newton GL HUD of a run that started without the feature.""" - if not isinstance(env_cfg, ManagerBasedRLEnvCfg): - return - for visualizer in env.unwrapped.sim.visualizers: - if hasattr(visualizer, "offer_checkpoint_ghosts"): - visualizer.offer_checkpoint_ghosts() - - -def _resolve_ghost_slots(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg) -> None: - """Set ``args_cli.checkpoint_ghost_slots``, the most checkpoints that can be shown at once. - - ``--num_envs`` is the total simulated; the environments are split among the loaded checkpoints, so every slot - needs at least one. - """ - total = env_cfg.scene.num_envs - if total < 2: - raise SystemExit("--checkpoint_ghosts needs --num_envs of at least 2: one environment per checkpoint.") - slots = args_cli.checkpoint_ghost_slots - if slots is None: - slots = MAX_CHECKPOINT_GHOST_SLOTS - if slots > total: - if args_cli.checkpoint_ghost_slots is not None: - logger.warning(f"--checkpoint_ghost_slots {slots} exceeds --num_envs {total}; using {total} slots.") - slots = total - args_cli.checkpoint_ghost_slots = min(slots, MAX_CHECKPOINT_GHOST_SLOTS) - - -def _validate_checkpoint_ghosts(args_cli: argparse.Namespace, env_cfg: object) -> None: - """Reject configurations Checkpoint Ghosts cannot run, before any simulation starts.""" - if not isinstance(env_cfg, ManagerBasedRLEnvCfg): - raise SystemExit("--checkpoint_ghosts only supports manager-based environments.") - visualizers = env_cfg.sim.visualizer_cfgs or [] - if not isinstance(visualizers, (list, tuple)): - visualizers = [visualizers] - # A shared visualizer configuration names its type on its backend; a deprecated combined one names it directly. - types = [] - for cfg in visualizers: - backend = getattr(cfg, "backend", None) - for chosen in backend if isinstance(backend, (list, tuple)) else [backend]: # --viz newton,viser selects both - types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) - if "newton" not in types: - raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") - curriculum = env_cfg.curriculum - for name, term in vars(curriculum).items() if curriculum is not None else (): - # Checkpoint Ghosts disable curriculum terms, so a task whose reset events read a term's state cannot run. - if getattr(getattr(term, "func", None), "supports_checkpoint_ghosts", True) is False: - raise SystemExit( - f"--checkpoint_ghosts does not support this task: its curriculum term '{name}' sets the reset state." - ) - - def run(argv: list[str]) -> None: """Play a checkpoint of an RSL-RL agent.""" args_cli = _parse_args(argv) with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) - if args_cli.checkpoint_ghosts: - _validate_checkpoint_ghosts(args_cli, env_cfg) + checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library="rsl_rl", action="play") @@ -283,9 +124,7 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(resume_path) env_cfg.log_dir = log_dir - if args_cli.checkpoint_ghosts: - _resolve_ghost_slots(args_cli, env_cfg) - CheckpointGhostSync.configure_env_cfg(env_cfg) + checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play", checkpoint_path=resume_path) screen.stage("Creating environment") @@ -301,10 +140,22 @@ def run(argv: list[str]) -> None: env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) logger.info(f"Loading model checkpoint from: {resume_path}") if args_cli.checkpoint_ghosts: - if args_cli.deterministic: - configure_seed(env_cfg.seed, torch_deterministic=True) + + def policy_factory(path: str): + runner = create_rsl_rl_runner(env, agent_cfg, inference=True) + runner.load(path) + return runner.get_inference_policy(device=env.unwrapped.device) + screen.close() - run_checkpoint_ghosts(env, args_cli, agent_cfg, resume_path, log_root_path) + checkpoint_ghost_play.run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r"model_.*\.pt", + reference_path=resume_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) return runner = create_rsl_rl_runner(env, agent_cfg, inference=True) # configure_seed must run after runner construction so torch determinism does not disturb its initialization @@ -326,5 +177,5 @@ def step() -> None: policy.reset(dones) screen.close() - _offer_checkpoint_ghosts(env, env_cfg) + checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index 98769c3eb2d8..93b79e2b3294 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -3,7 +3,7 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Launch checks and restart arguments of Checkpoint Ghosts.""" +"""Checkpoint selection of the RSL-RL play script, which Checkpoint Ghosts also use.""" from __future__ import annotations @@ -13,92 +13,10 @@ import pytest pytest.importorskip("rsl_rl") -from isaaclab.envs import ManagerBasedRLEnvCfg from isaaclab_rl.entrypoints.backends import play_rsl_rl -def _env_cfg(backend, scene=None, curriculum=None): - cfg = ManagerBasedRLEnvCfg.__new__(ManagerBasedRLEnvCfg) - cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=backend)]) - cfg.scene = scene or SimpleNamespace() - cfg.curriculum = curriculum - return cfg - - -def test_newton_among_several_selected_viewers_is_accepted(): - backends = [SimpleNamespace(visualizer_type="viser"), SimpleNamespace(visualizer_type="newton")] - - play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), _env_cfg(backends)) - - -def test_without_newton_the_run_is_rejected(): - with pytest.raises(SystemExit, match="requires the Newton"): - play_rsl_rl._validate_checkpoint_ghosts(SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="viser"))) - - -def _slots(total: int, slots: int | None): - args = SimpleNamespace(checkpoint_ghost_slots=slots) - play_rsl_rl._resolve_ghost_slots(args, SimpleNamespace(scene=SimpleNamespace(num_envs=total))) - return args.checkpoint_ghost_slots - - -def test_the_slots_default_to_eight_capped_at_num_envs(): - assert _slots(64, None) == 8 - assert _slots(3, None) == 3 - - -def test_more_slots_than_environments_are_capped(): - assert _slots(4, 6) == 4 - assert _slots(32, 5) == 5 - - -def test_a_single_environment_cannot_be_split(): - with pytest.raises(SystemExit, match="at least 2"): - _slots(1, None) - - -def test_the_session_is_built_from_the_play_arguments(monkeypatch, tmp_path): - created = {} - - class _Session: - def __init__(self, env, **kwargs): - created.update(kwargs) - - monkeypatch.setattr(play_rsl_rl, "CheckpointGhostSession", _Session) - checkpoint = tmp_path / "run" / "model_5.pt" - checkpoint.parent.mkdir() - checkpoint.touch() - args = SimpleNamespace(checkpoint_ghost_root=None, task="Isaac-Reach-Franka") - - play_rsl_rl.create_checkpoint_ghost_session(Mock(), args, Mock(), str(checkpoint), str(tmp_path), 4) - - assert created["num_slots"] == 4 - assert created["task"] == "Isaac-Reach-Franka" - assert created["checkpoint_root"] == str(tmp_path) - assert created["reference"].name == "model_5.pt" - - -def test_a_task_whose_curriculum_selects_the_reset_state_is_rejected(): - class _ResetStateCurriculum: - supports_checkpoint_ghosts = False - - curriculum = SimpleNamespace(reset_dataset=SimpleNamespace(func=_ResetStateCurriculum)) - - with pytest.raises(SystemExit, match="reset_dataset"): - play_rsl_rl._validate_checkpoint_ghosts( - SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum) - ) - - -def test_an_ordinary_curriculum_term_is_accepted(): - curriculum = SimpleNamespace(terrain_levels=SimpleNamespace(func=lambda env, env_ids: None)) - - play_rsl_rl._validate_checkpoint_ghosts( - SimpleNamespace(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum) - ) - - def test_checkpoint_selectors_pass_the_library_and_agent_to_the_resolver(monkeypatch): resolver = Mock(return_value="/runs/model_5.pt") monkeypatch.setattr(play_rsl_rl, "resolve_checkpoint_selector", resolver) @@ -109,29 +27,3 @@ def test_checkpoint_selectors_pass_the_library_and_agent_to_the_resolver(monkeyp assert path == "/runs/model_5.pt" assert resolver.call_args.kwargs["library"] == "rsl_rl" assert resolver.call_args.kwargs["metadata"] == {"agent": "rsl_rl_cfg_entry_point"} - - -def test_the_session_is_closed_when_no_viewer_can_attach(monkeypatch): - session = Mock() - monkeypatch.setattr(play_rsl_rl, "create_checkpoint_ghost_session", Mock(return_value=session)) - env = SimpleNamespace(unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=[object()]), step_dt=0.02)) - - with pytest.raises(RuntimeError, match="initialized Newton GL visualizer"): - play_rsl_rl.run_checkpoint_ghosts( - env, SimpleNamespace(checkpoint_ghost_slots=2), Mock(), "/runs/model_5.pt", "/logs" - ) - - session.close.assert_called_once() # its reset and command hooks must not stay installed - - -def test_the_task_of_a_run_is_read_from_its_manifest(tmp_path): - import json - - (tmp_path / "run").mkdir() - (tmp_path / "run" / "run.json").write_text(json.dumps({"task": "Isaac-Reach-Franka-OSC"})) - (tmp_path / "bad").mkdir() - (tmp_path / "bad" / "run.json").write_text("not json") - - assert play_rsl_rl._run_task(str(tmp_path / "run")) == "Isaac-Reach-Franka-OSC" - assert play_rsl_rl._run_task(str(tmp_path / "bad")) is None - assert play_rsl_rl._run_task(str(tmp_path / "missing")) is None From 1dd8fc91d154cc8901767d4d20fb3049362db95d Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:25:59 +0000 Subject: [PATCH 13/24] Support Checkpoint Ghosts in rl_games, skrl, SB3, and direct environments The session now steps the Isaac Lab environment itself and hands each slot its slice of the observation groups, so a play script only supplies a policy factory. The ghost sync no longer requires a command manager, and direct environments have their noise models disabled. --- docs/source/concepts/visualization.rst | 7 ++-- .../checkpoint-ghost-session.added.rst | 5 ++- .../checkpoint-ghost-sync.added.rst | 2 +- .../envs/utils/checkpoint_ghost_sync.py | 34 +++++++++------ .../visualizers/checkpoint_ghost_play.py | 41 ++++++++++++++---- .../visualizers/checkpoint_ghost_session.py | 30 ++++++------- .../test/envs/test_checkpoint_ghost_sync.py | 21 ++++++++++ .../visualizers/test_checkpoint_ghost_play.py | 33 +++++++++++++++ .../test_checkpoint_ghost_session.py | 42 +++++++++++-------- .../checkpoint-ghost-play.added.rst | 2 +- .../entrypoints/backends/play_rl_games.py | 40 ++++++++++++++++++ .../entrypoints/backends/play_rsl_rl.py | 9 +++- .../entrypoints/backends/play_sb3.py | 31 ++++++++++++++ .../entrypoints/backends/play_skrl.py | 29 +++++++++++++ 14 files changed, 267 insertions(+), 59 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 1d1674b056b5..5f2f535fe843 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -831,7 +831,7 @@ start from the same terrain, spawn pose, and commands, so the policy is the only them, and each checkpoint you add resizes every slot. A plain ``play`` run shows a greyed-out section that explains the flag. ``--checkpoint_ghost_slots`` caps the checkpoints shown (default eight). -In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for RSL-RL ``model_*.pt`` files, starting in +In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for the library's checkpoint files, starting in the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. @@ -839,8 +839,9 @@ opacity and tint under **Appearance**. The controls are disabled in the RTX view between slots, so the reference plays without disturbances such as pushes and can look steadier than in training. Reset randomization is mirrored: each ghost resets from the reference's random state. Randomness that does not come from torch's generators (numpy, warp) is not mirrored. -* Only RSL-RL and manager-based environments are supported. Tasks whose curriculum selects the reset state (such as - Franka Pour) are rejected at launch. +* RSL-RL, rl_games, skrl, and Stable-Baselines3 playback support it, for single-agent manager-based and direct + environments. A direct environment mirrors its reset state, but goals or commands it resamples during an episode are + not mirrored. Tasks whose curriculum selects the reset state (such as Franka Pour) are rejected at launch. **Choosing how many environments are drawn** diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst index dd636a3586b3..a84cbab83f96 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst @@ -1,7 +1,8 @@ * Added :class:`~isaaclab.visualizers.checkpoint_ghost_session.CheckpointGhostSession`, which steps one environment whose slices are driven by different checkpoints of one task. It splits the environments among the loaded checkpoints, - resets them together from the reference's state, and serves the checkpoint browser. It needs only an environment - wrapper and a policy factory, so a library's play entry point supplies the wiring. Only RSL-RL provides it for now. + resets them together from the reference's state, and serves the checkpoint browser. It steps the Isaac Lab + environment itself and needs only a policy factory, so a library's play script supplies only that. RSL-RL, rl_games, + skrl, and Stable-Baselines3 playback provide it. * Fixed the session failing with recurrent policies when a ghost is added or removed, and handled a ghost added, changed, or removed on an empty or unknown slot, and a failed re-split, without ending the session. It reuses one action tensor for every step. diff --git a/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst index 73d5396824c2..c805ab2b794a 100644 --- a/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst +++ b/source/isaaclab/changelog.d/checkpoint-ghost-sync.added.rst @@ -1,3 +1,3 @@ * Added :class:`~isaaclab.visualizers.CheckpointGhostController` and its slot and checkpoint types, and - :class:`~isaaclab.envs.utils.checkpoint_ghost_sync.CheckpointGhostSync`, which keep ghost slices of one manager-based + :class:`~isaaclab.envs.utils.checkpoint_ghost_sync.CheckpointGhostSync`, which keep ghost slices of one manager-based or direct environment on the reference slice's terrain, spawn state, and commands. diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index d47e1c94a326..e4424f2003cd 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -14,6 +14,8 @@ import torch if TYPE_CHECKING: + from ..direct_rl_env import DirectRLEnv + from ..direct_rl_env_cfg import DirectRLEnvCfg from ..manager_based_rl_env import ManagerBasedRLEnv from ..manager_based_rl_env_cfg import ManagerBasedRLEnvCfg @@ -37,7 +39,7 @@ class CheckpointGhostSync: be mirrored. """ - def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): + def __init__(self, env: ManagerBasedRLEnv | DirectRLEnv, slice_size: int, num_slices: int): """Attach to an environment and place every slice on the reference slice's terrain. Args: @@ -47,12 +49,11 @@ def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): num_slices: Number of slices, including the reference. Raises: - TypeError: If the environment does not use managers. + TypeError: If the environment has no scene. ValueError: If the environment has fewer worlds than the slices need. """ - for manager in ("command_manager", "event_manager", "scene"): - if not hasattr(env, manager): - raise TypeError("Checkpoint Ghosts only support manager-based environments.") + if not hasattr(env, "scene"): + raise TypeError("Checkpoint Ghosts need an environment with a scene.") if slice_size < 1 or num_slices < 2 or env.num_envs < slice_size * num_slices: raise ValueError( f"Environment has {env.num_envs} envs, expected at least {num_slices} slices of {slice_size} envs." @@ -66,12 +67,14 @@ def __init__(self, env: ManagerBasedRLEnv, slice_size: int, num_slices: int): self._saved_terrain = self._save_terrain() self._sync_terrain() self._reset_idx_original = env._reset_idx - self._compute_commands_original = env.command_manager.compute + self._commands = getattr(env, "command_manager", None) # direct environments have none env._reset_idx = self._reset_idx - env.command_manager.compute = self._compute_commands + if self._commands is not None: + self._compute_commands_original = self._commands.compute + self._commands.compute = self._compute_commands @staticmethod - def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: + def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg) -> list[str]: """Remove per-environment randomization that cannot be mirrored between slices. Startup and interval events, curriculum terms, and observation corruption are disabled. Reset events are kept: @@ -86,7 +89,12 @@ def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg) -> list[str]: """ removed = [] # A task may leave these fields None when it has no events, curriculum, or observation groups. - events, curriculum, observations = env_cfg.events, env_cfg.curriculum, env_cfg.observations + events, curriculum = getattr(env_cfg, "events", None), getattr(env_cfg, "curriculum", None) + observations = getattr(env_cfg, "observations", None) + for noise in ("action_noise_model", "observation_noise_model"): # direct environments corrupt per environment + if getattr(env_cfg, noise, None) is not None: + setattr(env_cfg, noise, None) + removed.append(noise) for name, term in vars(events).items() if events is not None else (): if term is None: continue @@ -118,7 +126,8 @@ def env_origin_offsets(self) -> np.ndarray: def close(self) -> None: """Restore the environment's original reset, command update, and terrain placement.""" self._env._reset_idx = self._reset_idx_original - self._env.command_manager.compute = self._compute_commands_original + if self._commands is not None: + self._commands.compute = self._compute_commands_original terrain = self._terrain() for name, values in self._saved_terrain.items(): getattr(terrain, name).copy_(values) @@ -176,7 +185,8 @@ def _reset_idx(self, env_ids: Any) -> None: source = reference.repeat(self._num_slices - 1) scene.reset_to(_gather(state, source), env_ids=ghosts, is_relative=True) self._copy_joint_targets(ghosts, source) - self._copy_command_state(reference) + if self._commands is not None: + self._copy_command_state(reference) def _copy_joint_targets(self, ghosts: torch.Tensor, source: torch.Tensor) -> None: """Give each ghost the reference's joint targets. @@ -201,7 +211,7 @@ def _copy_command_state(self, reference: torch.Tensor) -> None: """Copy every per-environment tensor of each command term from the reference to its ghosts.""" ghosts = (reference[None, :] + self._ghost_offsets[:, None]).reshape(-1) source = reference.repeat(self._num_slices - 1) - manager = self._env.command_manager + manager = self._commands origins = self._env.scene.env_origins for name in manager.active_terms: term = manager.get_term(name) diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index 280b2905d1ee..e515f25f0886 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -21,7 +21,9 @@ from pathlib import Path from typing import Any -from isaaclab.envs import ManagerBasedRLEnvCfg +import torch + +from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync from isaaclab.utils.seed import configure_seed @@ -72,8 +74,8 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: slots = args_cli.checkpoint_ghost_slots if slots is not None and not 2 <= slots <= MAX_CHECKPOINT_GHOST_SLOTS: raise SystemExit(f"--checkpoint_ghost_slots must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") - if not isinstance(env_cfg, ManagerBasedRLEnvCfg): - raise SystemExit("--checkpoint_ghosts only supports manager-based environments.") + if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): + raise SystemExit("--checkpoint_ghosts only supports single-agent environments.") visualizers = env_cfg.sim.visualizer_cfgs or [] if not isinstance(visualizers, (list, tuple)): visualizers = [visualizers] @@ -85,7 +87,7 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) if "newton" not in types: raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") - curriculum = env_cfg.curriculum + curriculum = getattr(env_cfg, "curriculum", None) for name, term in vars(curriculum).items() if curriculum is not None else (): # Checkpoint Ghosts disable curriculum terms, so a task whose reset events read a term's state cannot run. if getattr(getattr(term, "func", None), "supports_checkpoint_ghosts", True) is False: @@ -94,7 +96,7 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: ) -def prepare(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg) -> None: +def prepare(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg) -> None: """Resolve the slot count and disable randomization that cannot be mirrored, before the environment is created. ``--num_envs`` is the total simulated; the environments are split among the loaded checkpoints, so every slot needs @@ -114,11 +116,16 @@ def prepare(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg) -> None slots = total args_cli.checkpoint_ghost_slots = min(slots, MAX_CHECKPOINT_GHOST_SLOTS) CheckpointGhostSync.configure_env_cfg(env_cfg) + if isinstance(env_cfg, DirectRLEnvCfg): + logger.warning( + "Direct environment: reset randomization is mirrored, but goals or commands a task resamples during an" + " episode are not, so ghosts may chase different targets." + ) def offer(env: Any, env_cfg: Any) -> None: """Show the greyed-out Checkpoint Ghosts section in the Newton GL HUD of a run that started without the feature.""" - if not isinstance(env_cfg, ManagerBasedRLEnvCfg): + if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): return for visualizer in env.unwrapped.sim.visualizers: if hasattr(visualizer, "offer_checkpoint_ghosts"): @@ -150,7 +157,7 @@ def run( configure_seed(env.unwrapped.cfg.seed, torch_deterministic=True) # no runner is built here, so seed up front reference_file = Path(reference_path) session = CheckpointGhostSession( - env, + env.unwrapped, # the Isaac Lab environment: its observation groups and 5-tuple step, free of library wrappers num_slots=args_cli.checkpoint_ghost_slots, task=args_cli.task, checkpoint_root=os.path.abspath(args_cli.checkpoint_ghost_root or log_root_path), @@ -174,6 +181,26 @@ def run( session.close() +class PolicyAdapter: + """Turns a library's act function into the policy a slot needs: observation slice in, clipped actions out.""" + + def __init__( + self, + act: Callable[[Any], torch.Tensor], + reset: Callable[[torch.Tensor | None], None] | None = None, + clip: float | None = None, + ): + self._act, self._reset, self._clip = act, reset, clip + + def __call__(self, obs: Any) -> torch.Tensor: # noqa: D102 + actions = self._act(obs) + return actions if self._clip is None else torch.clamp(actions, -self._clip, self._clip) + + def reset(self, dones: torch.Tensor | None = None) -> None: # noqa: D102 + if self._reset is not None: + self._reset(dones) + + def _run_task(directory: str) -> str | None: """Return the task named by the run manifest in ``directory``, or None when it is not a training run.""" try: diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py index ecd7e51a29d6..29961014b108 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py @@ -5,10 +5,10 @@ """Playback of several checkpoints of one task side by side as Checkpoint Ghosts. -The session does not depend on a training library. It needs an environment wrapper whose ``step`` returns -observations, rewards, dones and extras and that has ``get_observations``, ``reset`` and ``num_actions``, plus a -``policy_factory`` that turns a checkpoint file into a callable policy with a ``reset`` method. A library's play entry -point supplies those, so supporting another library means writing that wiring. Only RSL-RL provides it for now. +The session does not depend on a training library. It steps the Isaac Lab environment itself, whose observations are +a dictionary of observation groups, and needs a ``policy_factory`` that turns a checkpoint file into a policy. The +policy receives one slot's slice of that dictionary and returns the slot's actions, so a library's play script only +supplies the factory, which handles the library's own observation processing and action clipping. """ from __future__ import annotations @@ -36,13 +36,18 @@ class CheckpointGhostPolicy(Protocol): """Inference policy driving one slot.""" - def __call__(self, obs: Any) -> torch.Tensor: - """Return actions for the slot's observations.""" + def __call__(self, obs: dict[str, Any]) -> torch.Tensor: + """Return actions for one slot's slice of the observation groups.""" def reset(self, dones: torch.Tensor | None = None) -> None: """Reset recurrent state of the environments that terminated, or of all of them when ``dones`` is None.""" +def _slice(obs: Any, chunk: slice) -> Any: + """Return the environments in ``chunk`` of an observation tensor, or of every tensor in nested groups.""" + return {key: _slice(value, chunk) for key, value in obs.items()} if isinstance(obs, dict) else obs[chunk] + + def _task_name(task: str) -> str: """Return a task id without its namespace prefix.""" return task.split(":")[-1] @@ -111,11 +116,7 @@ def __init__( self._restart_pending = False self._sync: CheckpointGhostSync | None = None self._load(0, reference) - try: - self._obs = env.get_observations() - except BaseException: - self.close() - raise + self._obs: dict[str, Any] = {} # filled by the restart below, which resets the environment # start the reference and the empty slots together from the same spawn state self._restart_pending = True @@ -207,14 +208,15 @@ def step(self) -> None: self.apply_pending_restart() size = self.layout.slice_size if self._actions is None: - self._actions = torch.zeros(self._env.num_envs, self._env.num_actions, device=self._env.unwrapped.device) + self._actions = torch.zeros(self._env.num_envs, self._env.action_space.shape[-1], device=self._env.device) actions = self._actions actions.zero_() # environments of no loaded slot act with zeros for slot in self.layout.active_slots: start = self.layout.slot_start(slot.index) chunk = slice(start, start + size) - actions[chunk] = self._policies[slot.index](self._obs[chunk]) - self._obs, _, dones, _ = self._env.step(actions) + actions[chunk] = self._policies[slot.index](_slice(self._obs, chunk)) + self._obs, _, terminated, truncated, _ = self._env.step(actions) + dones = terminated | truncated if self._restart_pending: # The viewer can add or remove a ghost while the environment steps. The split then changed, so this step's # dones no longer line up with the slots; the restart resets every environment and policy before the next. diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index e3cb3f43881e..75a50300af21 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -325,3 +325,24 @@ def test_configure_env_cfg_skips_an_observation_group_that_is_none() -> None: ) assert CheckpointGhostSync.configure_env_cfg(cfg) == ["observations.policy.enable_corruption"] + + +def test_a_direct_environment_without_commands_still_mirrors_the_spawn_state() -> None: + env = _make_env() + del env.command_manager, env.event_manager # direct environments have neither manager + sync = CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + env._reset_idx(torch.tensor([0, 1])) + sync.close() + + root = env.scene.root_pos + assert torch.equal(root[[3, 4]], root[[0, 1]]) and torch.equal(root[[6, 7]], root[[0, 1]]) + + +def test_direct_noise_models_are_disabled_since_they_corrupt_each_environment_alone() -> None: + cfg = SimpleNamespace(events=None, action_noise_model=object(), observation_noise_model=object()) + + removed = CheckpointGhostSync.configure_env_cfg(cfg) + + assert removed == ["action_noise_model", "observation_noise_model"] + assert cfg.action_noise_model is None and cfg.observation_noise_model is None diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index 252538a5b5a7..1bbcdaa76083 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -12,6 +12,7 @@ from unittest.mock import Mock import pytest +import torch from isaaclab.envs import ManagerBasedRLEnvCfg from isaaclab.visualizers import checkpoint_ghost_play as play @@ -169,3 +170,35 @@ def test_the_task_of_a_run_is_read_from_its_manifest(tmp_path): assert play._run_task(str(tmp_path / "run")) == "Isaac-Reach-Franka-OSC" assert play._run_task(str(tmp_path / "bad")) is None assert play._run_task(str(tmp_path / "missing")) is None + + +def test_a_direct_environment_is_accepted(): + from isaaclab.envs import DirectRLEnvCfg + + cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=SimpleNamespace(visualizer_type="newton"))]) + + play.check(_args(), cfg) + + +def test_a_policy_adapter_clips_the_actions_and_forwards_resets(): + resets = [] + policy = play.PolicyAdapter(lambda obs: obs["policy"] * 10, resets.append, clip=1.0) + + actions = policy({"policy": torch.tensor([[0.5, -0.5]])}) + policy.reset() + policy.reset(torch.tensor([True])) + + assert actions.tolist() == [[1.0, -1.0]] + assert resets[0] is None and resets[1].tolist() == [True] + play.PolicyAdapter(lambda obs: obs).reset() # a policy without recurrent state needs no reset function + + +def test_observation_groups_are_sliced_per_slot(): + from isaaclab.visualizers.checkpoint_ghost_session import _slice + + obs = {"policy": torch.arange(6).view(6, 1), "critic": {"a": torch.arange(6)}} + + sliced = _slice(obs, slice(2, 4)) + + assert sliced["policy"].tolist() == [[2], [3]] and sliced["critic"]["a"].tolist() == [2, 3] diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py index 1125e403f7e7..48ebafe7ee58 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py @@ -109,22 +109,27 @@ def test_a_ghost_policy_resets_with_its_reference(dones, expected): ghost = Mock() session._policies = [reference, ghost, None] session.layout.slots[1].checkpoint = CHECKPOINT # two loaded slots split the six envs into slices of three - session._obs = torch.zeros(6, 1) - env.num_envs, env.num_actions = 6, 1 + session._obs = {"policy": torch.zeros(6, 1)} + env.num_envs, env.device, env.action_space = 6, "cpu", SimpleNamespace(shape=(6, 1)) reference.return_value = torch.zeros(3, 1) ghost.return_value = torch.zeros(3, 1) - env.step.return_value = (torch.zeros(6, 1), torch.zeros(6), torch.tensor(dones), {}) + env.step.return_value = ( + {"policy": torch.zeros(6, 1)}, + torch.zeros(6), + torch.tensor(dones), + torch.zeros(6, dtype=torch.bool), + {}, + ) session.step() assert ghost.reset.call_args.args[0].tolist() == expected -def _start(monkeypatch, observations): +def _start(monkeypatch): sync = Mock() monkeypatch.setattr(checkpoint_ghosts, "CheckpointGhostSync", sync) env = Mock(unwrapped=SimpleNamespace(device="cpu", step_dt=0.02, num_envs=6)) - env.get_observations.side_effect = observations session = CheckpointGhostSession( env, num_slots=3, @@ -137,13 +142,8 @@ def _start(monkeypatch, observations): return session, sync -def test_a_failing_start_never_leaves_the_environment_patched(monkeypatch): - with pytest.raises(RuntimeError, match="observations"): - _start(monkeypatch, RuntimeError("observations")) - - def test_adding_and_removing_a_ghost_splits_the_environments_again(monkeypatch): - session, sync = _start(monkeypatch, [None]) + session, sync = _start(monkeypatch) sync.assert_not_called() # the reference alone owns every environment assert session.layout.slice_size == 6 @@ -208,7 +208,7 @@ def test_a_load_failure_is_reported_in_one_line(): def test_a_resplit_failure_goes_back_to_the_previous_split_and_reports_it(monkeypatch): - session, sync = _start(monkeypatch, [None]) + session, sync = _start(monkeypatch) sync.side_effect = [ValueError("no room"), Mock()] # the new split fails, restoring the old one succeeds message = session.add_ghost(CHECKPOINT) @@ -218,7 +218,7 @@ def test_a_resplit_failure_goes_back_to_the_previous_split_and_reports_it(monkey def test_a_load_failure_leaves_the_split_alone(monkeypatch): - session, sync = _start(monkeypatch, [None]) + session, sync = _start(monkeypatch) session._policy_factory = Mock(side_effect=RuntimeError("size mismatch")) message = session.add_ghost(CHECKPOINT) @@ -228,7 +228,7 @@ def test_a_load_failure_leaves_the_split_alone(monkeypatch): def test_changing_an_empty_slot_and_removing_an_empty_or_unknown_slot_do_nothing(monkeypatch): - session, sync = _start(monkeypatch, [None]) + session, sync = _start(monkeypatch) assert "empty slot" in session.replace_ghost(2, CHECKPOINT) session.remove_ghost(2) @@ -255,13 +255,19 @@ def test_a_run_of_another_task_is_named_and_a_matching_or_unknown_directory_is_n def test_a_ghost_added_while_the_environment_steps_skips_the_stale_policy_resets(): session, env, policy = _session(pending=False) - session._obs = torch.zeros(6, 1) - env.num_envs, env.num_actions = 6, 1 + session._obs = {"policy": torch.zeros(6, 1)} + env.num_envs, env.device, env.action_space = 6, "cpu", SimpleNamespace(shape=(6, 1)) policy.return_value = torch.zeros(6, 1) def step(actions): session._restart_pending = True # the viewer added a ghost during the step, changing the split - return torch.zeros(6, 1), torch.zeros(6), torch.zeros(6, dtype=torch.bool), {} + return ( + {"policy": torch.zeros(6, 1)}, + torch.zeros(6), + torch.zeros(6, dtype=torch.bool), + torch.zeros(6, dtype=torch.bool), + {}, + ) env.step.side_effect = step @@ -271,7 +277,7 @@ def step(actions): def test_a_failed_rollback_after_a_failed_resplit_still_returns_a_message(monkeypatch): - session, sync = _start(monkeypatch, [None]) + session, sync = _start(monkeypatch) sync.side_effect = ValueError("no room") # both the new split and the rollback fail message = session.add_ghost(CHECKPOINT) diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst index 3da618c0cb77..19077aeb7ff7 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst @@ -1,4 +1,4 @@ -* Added ``--checkpoint_ghosts`` and ``--checkpoint_ghost_slots`` to RSL-RL playback, the Newton GL viewer's checkpoint +* Added ``--checkpoint_ghosts`` and ``--checkpoint_ghost_slots`` to RSL-RL, rl_games, skrl, and Stable-Baselines3 playback, the Newton GL viewer's checkpoint visualization. ``--num_envs`` is the total simulated and is split evenly among the checkpoints shown: the reference starts with all of them, and adding a ghost resizes every slot (32 environments give 16 each with two checkpoints). ``--checkpoint_ghost_slots`` caps the checkpoints shown at once (default eight, at most ``--num_envs``). diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py index 5b5758217228..afa375e907d8 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py @@ -21,6 +21,7 @@ from isaaclab.utils import index_fill_ from isaaclab.utils.assets import retrieve_file_path from isaaclab.utils.seed import configure_seed +from isaaclab.visualizers import checkpoint_ghost_play import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli @@ -61,6 +62,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: agent_help="Name of the RL agent configuration entry point.", ) parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint path, latest/best, or pretrained.") + checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) enable_cameras_for_video(args_cli) @@ -109,6 +111,7 @@ def run(argv: list[str]) -> None: " --agent rl_games_cfg_entry_point, or use --rl_library rsl_rl for RSL-RL runner configurations." ) pre_launch_video_config(env_cfg, args_cli) + checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library="rl_games", action="play") @@ -124,6 +127,7 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(os.path.dirname(resume_path)) env_cfg.log_dir = log_dir + checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") screen.stage("Creating environment") @@ -147,6 +151,41 @@ def run(argv: list[str]) -> None: if args_cli.deterministic: configure_seed(env_cfg.seed, torch_deterministic=True) runner.load(agent_cfg) + if args_cli.checkpoint_ghosts: + + def policy_factory(path: str): + player = runner.create_player() + player.restore(path) + player.reset() + + def act(obs): + obs = player.obs_to_torch(env._process_obs(obs)["obs"]) + player.get_batch_size(obs, 1) + if player.is_rnn and player.states is None: + player.init_rnn() + return player.get_action(obs, is_deterministic=player.is_deterministic) + + def reset(dones): + if dones is None: # the slot was resized: its recurrent states are rebuilt on the next act + player.states = None + elif player.states is not None: + for state in player.states: + index_fill_(state, dones, 0.0, dim=1) + + clip = params.get("env", {}).get("clip_actions") + return checkpoint_ghost_play.PolicyAdapter(act, reset, clip) + + screen.close() + checkpoint_ghost_play.run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r".*\.pth", + reference_path=resume_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) + return agent: BasePlayer = runner.create_player() agent.restore(resume_path) agent.reset() @@ -169,4 +208,5 @@ def step() -> None: index_fill_(state, dones, 0.0, dim=1) screen.close() + checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index c5d38312bb35..5d42db1f4b03 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -12,6 +12,8 @@ import logging import os +from tensordict import TensorDict + from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.envs import DirectMARLEnvCfg from isaaclab.utils.assets import retrieve_file_path @@ -144,7 +146,12 @@ def run(argv: list[str]) -> None: def policy_factory(path: str): runner = create_rsl_rl_runner(env, agent_cfg, inference=True) runner.load(path) - return runner.get_inference_policy(device=env.unwrapped.device) + policy = runner.get_inference_policy(device=env.unwrapped.device) + return checkpoint_ghost_play.PolicyAdapter( + lambda obs: policy(TensorDict(obs, batch_size=[next(iter(obs.values())).shape[0]])), + policy.reset, + agent_cfg.clip_actions, + ) screen.close() checkpoint_ghost_play.run( diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index 150abc2fa724..6436c6429792 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -13,12 +13,14 @@ import os from pathlib import Path +import torch from stable_baselines3 import PPO from stable_baselines3.common.vec_env import VecNormalize from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.envs import DirectMARLEnvCfg from isaaclab.utils.seed import configure_seed +from isaaclab.visualizers import checkpoint_ghost_play import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli @@ -65,6 +67,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: default=False, help="Use a slower SB3 wrapper but keep all the extra training info.", ) + checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) enable_cameras_for_video(args_cli) @@ -101,6 +104,7 @@ def run(argv: list[str]) -> None: with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) + checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library="sb3", action="play") @@ -115,6 +119,7 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(checkpoint_path) env_cfg.log_dir = log_dir + checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") screen.stage("Creating environment") @@ -129,6 +134,31 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) + if args_cli.checkpoint_ghosts: + + def policy_factory(path: str): + model = PPO.load(path, device=agent_cfg["device"]) + stats = Path(path.replace("/model", "/model_vecnormalize").replace(".zip", ".pkl")) + norm = VecNormalize.load(stats, env) if stats.exists() else None # each checkpoint has its own + + def act(obs): + obs = env._process_obs(obs) + actions, _ = model.predict(norm.normalize_obs(obs) if norm else obs, deterministic=True) + return torch.as_tensor(actions, device=env.unwrapped.device) + + return checkpoint_ghost_play.PolicyAdapter(act) + + screen.close() + checkpoint_ghost_play.run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r"model(?:_.*)?\.zip", + reference_path=checkpoint_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) + return vec_norm_path = checkpoint_path.replace("/model", "/model_vecnormalize").replace(".zip", ".pkl") vec_norm_path = Path(vec_norm_path) if vec_norm_path.exists(): @@ -158,4 +188,5 @@ def step() -> None: obs, _, _, _ = env.step(actions) screen.close() + checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index 1effae5c46d5..0dcdc05c0e53 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -21,6 +21,7 @@ from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.envs import DirectMARLEnvCfg from isaaclab.utils.seed import configure_seed +from isaaclab.visualizers import checkpoint_ghost_play import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli @@ -70,6 +71,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: ) parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint path, latest/best, or pretrained.") cli_args.add_skrl_args(parser) + checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) enable_cameras_for_video(args_cli) @@ -121,6 +123,7 @@ def _run(args_cli: argparse.Namespace) -> None: ) algorithm = resolve_skrl_algorithm(agent_cfg, args_cli.algorithm) pre_launch_video_config(env_cfg, args_cli) + checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library=f"skrl ({args_cli.ml_framework})", action="play") @@ -144,6 +147,7 @@ def _run(args_cli: argparse.Namespace) -> None: return log_dir = os.path.dirname(os.path.dirname(resume_path)) env_cfg.log_dir = log_dir + checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") screen.stage("Creating environment") @@ -161,6 +165,30 @@ def _run(args_cli: argparse.Namespace) -> None: agent_cfg["trainer"]["close_environment_at_exit"] = False experiment_cfg["write_interval"] = 0 experiment_cfg["checkpoint_interval"] = 0 + if args_cli.checkpoint_ghosts: + + def policy_factory(path: str): + agent = runner_cls(env, agent_cfg).agent # one agent per checkpoint, since they run side by side + agent.load(path) + agent.enable_training_mode(False, apply_to_models=True) + + def act(obs): + outputs = agent.act(obs["policy"], obs.get("critic"), timestep=0, timesteps=0) + return outputs[-1].get("mean_actions", outputs[0]) + + return checkpoint_ghost_play.PolicyAdapter(act) + + screen.close() + checkpoint_ghost_play.run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r".*\.pt", + reference_path=resume_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) + return runner = runner_cls(env, agent_cfg) # configure_seed must run after Runner() so torch determinism does not disturb its initialization if args_cli.deterministic: @@ -183,4 +211,5 @@ def step() -> None: states = env.state() screen.close() + checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=dt, args_cli=args_cli, env_cfg=env_cfg) From 46a41320669b854b522e70a95b20de3b76bbdba3 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:29:40 +0000 Subject: [PATCH 14/24] Address review of the multi-library Checkpoint Ghosts support Build the SB3 normalization path from the file name only, reject skrl's jax framework at launch, take the RSL-RL batch size from a leaf of any observation group, validate the slot count at argument parsing again, and test that the run manifest name matches training's. --- .../isaaclab/visualizers/checkpoint_ghost_play.py | 13 +++++++++---- .../test/visualizers/test_checkpoint_ghost_play.py | 13 ++++++++----- .../isaaclab_rl/entrypoints/backends/play_rsl_rl.py | 3 ++- .../isaaclab_rl/entrypoints/backends/play_sb3.py | 3 ++- .../isaaclab_rl/entrypoints/backends/play_skrl.py | 2 ++ .../test/test_checkpoint_ghost_launch.py | 8 ++++++++ 6 files changed, 31 insertions(+), 11 deletions(-) diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index e515f25f0886..c04c54a5e52b 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -36,6 +36,14 @@ """Name of the manifest that training writes into a run directory (``isaaclab_rl.entrypoints.common``).""" +def _slot_count(value: str) -> int: + """Parse ``--checkpoint_ghost_slots``, so a bad count fails at argument parsing like any other flag.""" + count = int(value) + if not 2 <= count <= MAX_CHECKPOINT_GHOST_SLOTS: + raise argparse.ArgumentTypeError(f"must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") + return count + + def add_args(parser: argparse.ArgumentParser) -> None: """Add the Checkpoint Ghosts flags to a play script's parser.""" parser.add_argument( @@ -50,7 +58,7 @@ def add_args(parser: argparse.ArgumentParser) -> None: ) parser.add_argument( "--checkpoint_ghost_slots", - type=int, + type=_slot_count, default=None, help=( f"Most checkpoints shown at once, including the reference (2 to {MAX_CHECKPOINT_GHOST_SLOTS}). Defaults to" @@ -71,9 +79,6 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: """ if not args_cli.checkpoint_ghosts: return - slots = args_cli.checkpoint_ghost_slots - if slots is not None and not 2 <= slots <= MAX_CHECKPOINT_GHOST_SLOTS: - raise SystemExit(f"--checkpoint_ghost_slots must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): raise SystemExit("--checkpoint_ghosts only supports single-agent environments.") visualizers = env_cfg.sim.visualizer_cfgs or [] diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index 1bbcdaa76083..bbda036ae410 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -50,12 +50,15 @@ def test_without_newton_the_run_is_rejected(): play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="viser"))) -def test_a_slot_count_out_of_range_is_rejected(): - args = _args() - args.checkpoint_ghost_slots = 1 +def test_a_slot_count_out_of_range_fails_at_argument_parsing(): + import argparse + + parser = argparse.ArgumentParser() + play.add_args(parser) - with pytest.raises(SystemExit, match="between 2 and"): - play.check(args, object()) + assert parser.parse_args(["--checkpoint_ghost_slots", "4"]).checkpoint_ghost_slots == 4 + with pytest.raises(SystemExit): + parser.parse_args(["--checkpoint_ghost_slots", "1"]) def test_a_task_whose_curriculum_selects_the_reset_state_is_rejected(): diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index 5d42db1f4b03..9b90a8e13443 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -13,6 +13,7 @@ import os from tensordict import TensorDict +from torch.utils._pytree import tree_leaves from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.envs import DirectMARLEnvCfg @@ -148,7 +149,7 @@ def policy_factory(path: str): runner.load(path) policy = runner.get_inference_policy(device=env.unwrapped.device) return checkpoint_ghost_play.PolicyAdapter( - lambda obs: policy(TensorDict(obs, batch_size=[next(iter(obs.values())).shape[0]])), + lambda obs: policy(TensorDict(obs, batch_size=[tree_leaves(obs)[0].shape[0]])), policy.reset, agent_cfg.clip_actions, ) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index 6436c6429792..46e0f2e05f69 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -138,7 +138,8 @@ def run(argv: list[str]) -> None: def policy_factory(path: str): model = PPO.load(path, device=agent_cfg["device"]) - stats = Path(path.replace("/model", "/model_vecnormalize").replace(".zip", ".pkl")) + name = Path(path).name.replace("model", "model_vecnormalize", 1).replace(".zip", ".pkl") + stats = Path(path).with_name(name) norm = VecNormalize.load(stats, env) if stats.exists() else None # each checkpoint has its own def act(obs): diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index 0dcdc05c0e53..52e209ff7f79 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -124,6 +124,8 @@ def _run(args_cli: argparse.Namespace) -> None: algorithm = resolve_skrl_algorithm(agent_cfg, args_cli.algorithm) pre_launch_video_config(env_cfg, args_cli) checkpoint_ghost_play.check(args_cli, env_cfg) + if args_cli.checkpoint_ghosts and args_cli.ml_framework != "torch": + raise SystemExit("--checkpoint_ghosts supports only --ml_framework torch.") screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library=f"skrl ({args_cli.ml_framework})", action="play") diff --git a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py index 93b79e2b3294..5084ce89c98f 100644 --- a/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -27,3 +27,11 @@ def test_checkpoint_selectors_pass_the_library_and_agent_to_the_resolver(monkeyp assert path == "/runs/model_5.pt" assert resolver.call_args.kwargs["library"] == "rsl_rl" assert resolver.call_args.kwargs["metadata"] == {"agent": "rsl_rl_cfg_entry_point"} + + +def test_the_ghost_manifest_name_matches_the_one_training_writes(): + from isaaclab.visualizers import checkpoint_ghost_play + + from isaaclab_rl.entrypoints.common import RUN_MANIFEST_FILENAME + + assert checkpoint_ghost_play._RUN_MANIFEST_FILENAME == RUN_MANIFEST_FILENAME # core cannot import it From dcd4288d5ec4e851f84ea3d72d4084ff6de1db19 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:38:13 +0000 Subject: [PATCH 15/24] List every Checkpoint Ghosts limitation in the visualization docs --- docs/source/concepts/visualization.rst | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 5f2f535fe843..1eb6cad95b3d 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -835,13 +835,16 @@ In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. -* Startup and interval events, curriculum terms, and observation noise are disabled, since they cannot be mirrored - between slots, so the reference plays without disturbances such as pushes and can look steadier than in training. - Reset randomization is mirrored: each ghost resets from the reference's random state. Randomness that does not come - from torch's generators (numpy, warp) is not mirrored. -* RSL-RL, rl_games, skrl, and Stable-Baselines3 playback support it, for single-agent manager-based and direct - environments. A direct environment mirrors its reset state, but goals or commands it resamples during an episode are - not mirrored. Tasks whose curriculum selects the reset state (such as Franka Pour) are rejected at launch. +Limitations: + +* Startup and interval events, curriculum terms, and action and observation noise are disabled, since they cannot be + mirrored, so the reference can look steadier than in training. Reset randomization is mirrored from torch's random + state; numpy and warp randomness is not. +* Playback with RSL-RL, rl_games, skrl (``--ml_framework torch``), and Stable-Baselines3 is supported, for + single-agent manager-based and direct environments. torchrl, rlinf, and multi-agent environments are not. +* A direct environment mirrors its reset state, but not goals or commands it resamples during an episode. +* Tasks whose curriculum selects the reset state (such as Franka Pour) are rejected at launch. +* It needs the Newton viewer, and tint and opacity need the OpenGL renderer. **Choosing how many environments are drawn** From 7dd02c89c8f3a4a0fc32fdc8368d2450d29f00cd Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:40:16 +0000 Subject: [PATCH 16/24] Comment the Checkpoint Ghosts hooks in the play scripts --- .../isaaclab_rl/entrypoints/backends/play_rl_games.py | 6 ++++++ .../isaaclab_rl/entrypoints/backends/play_rsl_rl.py | 6 ++++++ .../isaaclab_rl/entrypoints/backends/play_sb3.py | 6 ++++++ .../isaaclab_rl/entrypoints/backends/play_skrl.py | 5 +++++ 4 files changed, 23 insertions(+) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py index afa375e907d8..b0f379615590 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py @@ -62,6 +62,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: agent_help="Name of the RL agent configuration entry point.", ) parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint path, latest/best, or pretrained.") + # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) @@ -111,6 +112,7 @@ def run(argv: list[str]) -> None: " --agent rl_games_cfg_entry_point, or use --rl_library rsl_rl for RSL-RL runner configurations." ) pre_launch_video_config(env_cfg, args_cli) + # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: @@ -127,6 +129,7 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(os.path.dirname(resume_path)) env_cfg.log_dir = log_dir + # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") @@ -151,9 +154,11 @@ def run(argv: list[str]) -> None: if args_cli.deterministic: configure_seed(env_cfg.seed, torch_deterministic=True) runner.load(agent_cfg) + # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: def policy_factory(path: str): + # a ghost gets its own player, so every slot keeps its own policy and recurrent state player = runner.create_player() player.restore(path) player.reset() @@ -208,5 +213,6 @@ def step() -> None: index_fill_(state, dones, 0.0, dim=1) screen.close() + # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index 9b90a8e13443..800db25a661d 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -65,6 +65,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: parser.add_argument( "--external_callback", default=None, help="Fully qualified path to an externally defined callback." ) + # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) @@ -111,6 +112,7 @@ def run(argv: list[str]) -> None: with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) + # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: @@ -127,6 +129,7 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(resume_path) env_cfg.log_dir = log_dir + # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play", checkpoint_path=resume_path) @@ -142,9 +145,11 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) logger.info(f"Loading model checkpoint from: {resume_path}") + # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: def policy_factory(path: str): + # a ghost loads a checkpoint into its own runner, so every slot keeps its own policy runner = create_rsl_rl_runner(env, agent_cfg, inference=True) runner.load(path) policy = runner.get_inference_policy(device=env.unwrapped.device) @@ -185,5 +190,6 @@ def step() -> None: policy.reset(dones) screen.close() + # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index 46e0f2e05f69..535430815e28 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -67,6 +67,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: default=False, help="Use a slower SB3 wrapper but keep all the extra training info.", ) + # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) @@ -104,6 +105,7 @@ def run(argv: list[str]) -> None: with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) + # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: @@ -119,6 +121,7 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(checkpoint_path) env_cfg.log_dir = log_dir + # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") @@ -134,9 +137,11 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) + # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: def policy_factory(path: str): + # each checkpoint has its own policy and its own normalization statistics model = PPO.load(path, device=agent_cfg["device"]) name = Path(path).name.replace("model", "model_vecnormalize", 1).replace(".zip", ".pkl") stats = Path(path).with_name(name) @@ -189,5 +194,6 @@ def step() -> None: obs, _, _, _ = env.step(actions) screen.close() + # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index 52e209ff7f79..87ddb7b7b17f 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -71,6 +71,7 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: ) parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint path, latest/best, or pretrained.") cli_args.add_skrl_args(parser) + # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) @@ -123,6 +124,7 @@ def _run(args_cli: argparse.Namespace) -> None: ) algorithm = resolve_skrl_algorithm(agent_cfg, args_cli.algorithm) pre_launch_video_config(env_cfg, args_cli) + # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) if args_cli.checkpoint_ghosts and args_cli.ml_framework != "torch": raise SystemExit("--checkpoint_ghosts supports only --ml_framework torch.") @@ -149,6 +151,7 @@ def _run(args_cli: argparse.Namespace) -> None: return log_dir = os.path.dirname(os.path.dirname(resume_path)) env_cfg.log_dir = log_dir + # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") @@ -167,6 +170,7 @@ def _run(args_cli: argparse.Namespace) -> None: agent_cfg["trainer"]["close_environment_at_exit"] = False experiment_cfg["write_interval"] = 0 experiment_cfg["checkpoint_interval"] = 0 + # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: def policy_factory(path: str): @@ -213,5 +217,6 @@ def step() -> None: states = env.state() screen.close() + # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=dt, args_cli=args_cli, env_cfg=env_cfg) From b0d41a5274de24d0727531014eecac564d53cb4a Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:49:04 +0000 Subject: [PATCH 17/24] Move the Checkpoint Ghosts slot count and folder into the Newton visualizer config Only --checkpoint_ghosts stays on the command line. checkpoint_ghost_slots and checkpoint_ghost_root are Newton backend options. --- docs/source/concepts/visualization.rst | 5 +- .../visualizers/checkpoint_ghost_play.py | 81 +++++++++---------- .../visualizers/test_checkpoint_ghost_play.py | 58 +++++++------ .../checkpoint-ghost-play.added.rst | 9 +-- .../checkpoint-ghost-options.added.rst | 3 + .../newton/newton_visualizer_cfg.py | 9 +++ 6 files changed, 89 insertions(+), 76 deletions(-) create mode 100644 source/isaaclab_visualizers/changelog.d/checkpoint-ghost-options.added.rst diff --git a/docs/source/concepts/visualization.rst b/docs/source/concepts/visualization.rst index 1eb6cad95b3d..07592d20655b 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -829,10 +829,11 @@ start from the same terrain, spawn pose, and commands, so the policy is the only ``--num_envs`` is the total simulated and is split evenly among the checkpoints shown: the reference starts with all of them, and each checkpoint you add resizes every slot. A plain ``play`` run shows a greyed-out section that explains the -flag. ``--checkpoint_ghost_slots`` caps the checkpoints shown (default eight). +flag. The Newton backend options ``checkpoint_ghost_slots`` (default eight) and ``checkpoint_ghost_root`` set how many +checkpoints are shown at most and where the browser starts. In the **Checkpoint Ghosts** section, **Add Checkpoint...** browses folders for the library's checkpoint files, starting in -the experiment's log directory or ``--checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has +the experiment's log directory or ``checkpoint_ghost_root``. Each ghost can be shown, changed, or removed, and has opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. Limitations: diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index c04c54a5e52b..0fd0f7f137c4 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -36,16 +36,8 @@ """Name of the manifest that training writes into a run directory (``isaaclab_rl.entrypoints.common``).""" -def _slot_count(value: str) -> int: - """Parse ``--checkpoint_ghost_slots``, so a bad count fails at argument parsing like any other flag.""" - count = int(value) - if not 2 <= count <= MAX_CHECKPOINT_GHOST_SLOTS: - raise argparse.ArgumentTypeError(f"must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") - return count - - def add_args(parser: argparse.ArgumentParser) -> None: - """Add the Checkpoint Ghosts flags to a play script's parser.""" + """Add the Checkpoint Ghosts flag to a play script's parser.""" parser.add_argument( "--checkpoint_ghosts", action="store_true", @@ -53,23 +45,30 @@ def add_args(parser: argparse.ArgumentParser) -> None: help=( "Enable Checkpoint Ghosts, the checkpoint visualization in the Newton GL viewer. The --checkpoint drives" " the reference; ghosts are added from the viewer HUD. --num_envs is the total simulated and is split" - " evenly among the checkpoints shown." + " evenly among the checkpoints shown. The slot count and browser folder are Newton visualizer options" + " (checkpoint_ghost_slots, checkpoint_ghost_root)." ), ) - parser.add_argument( - "--checkpoint_ghost_slots", - type=_slot_count, - default=None, - help=( - f"Most checkpoints shown at once, including the reference (2 to {MAX_CHECKPOINT_GHOST_SLOTS}). Defaults to" - f" {MAX_CHECKPOINT_GHOST_SLOTS}, capped at --num_envs." - ), - ) - parser.add_argument( - "--checkpoint_ghost_root", - default=None, - help="Directory searched for ghost checkpoints. Defaults to the experiment's log directory.", - ) + + +def _newton_cfg(env_cfg: Any) -> Any | None: + """Return the Newton viewer's options from the environment config, or None when it is not selected.""" + visualizers = env_cfg.sim.visualizer_cfgs or [] + if not isinstance(visualizers, (list, tuple)): + visualizers = [visualizers] + # A shared visualizer configuration names its type on its backend; a deprecated combined one names it directly. + for cfg in visualizers: + backend = getattr(cfg, "backend", None) + for chosen in backend if isinstance(backend, (list, tuple)) else [backend]: # --viz newton,viser selects both + if (getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) == "newton": + return chosen + return None + + +def _slot_count(env_cfg: Any, num_envs: int) -> int: + """Return how many checkpoints can be shown at once: the configured count, capped at the environments.""" + slots = getattr(_newton_cfg(env_cfg), "checkpoint_ghost_slots", None) or MAX_CHECKPOINT_GHOST_SLOTS + return min(slots, num_envs) def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: @@ -81,17 +80,12 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: return if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): raise SystemExit("--checkpoint_ghosts only supports single-agent environments.") - visualizers = env_cfg.sim.visualizer_cfgs or [] - if not isinstance(visualizers, (list, tuple)): - visualizers = [visualizers] - # A shared visualizer configuration names its type on its backend; a deprecated combined one names it directly. - types = [] - for cfg in visualizers: - backend = getattr(cfg, "backend", None) - for chosen in backend if isinstance(backend, (list, tuple)) else [backend]: # --viz newton,viser selects both - types.append(getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) - if "newton" not in types: + newton = _newton_cfg(env_cfg) + if newton is None: raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") + slots = getattr(newton, "checkpoint_ghost_slots", None) + if slots is not None and not 2 <= slots <= MAX_CHECKPOINT_GHOST_SLOTS: + raise SystemExit(f"checkpoint_ghost_slots must be between 2 and {MAX_CHECKPOINT_GHOST_SLOTS}.") curriculum = getattr(env_cfg, "curriculum", None) for name, term in vars(curriculum).items() if curriculum is not None else (): # Checkpoint Ghosts disable curriculum terms, so a task whose reset events read a term's state cannot run. @@ -112,14 +106,9 @@ def prepare(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg | Direct total = env_cfg.scene.num_envs if total < 2: raise SystemExit("--checkpoint_ghosts needs --num_envs of at least 2: one environment per checkpoint.") - slots = args_cli.checkpoint_ghost_slots - if slots is None: - slots = MAX_CHECKPOINT_GHOST_SLOTS - if slots > total: - if args_cli.checkpoint_ghost_slots is not None: - logger.warning(f"--checkpoint_ghost_slots {slots} exceeds --num_envs {total}; using {total} slots.") - slots = total - args_cli.checkpoint_ghost_slots = min(slots, MAX_CHECKPOINT_GHOST_SLOTS) + requested = getattr(_newton_cfg(env_cfg), "checkpoint_ghost_slots", None) + if requested is not None and requested > total: + logger.warning(f"checkpoint_ghost_slots {requested} exceeds --num_envs {total}; using {total} slots.") CheckpointGhostSync.configure_env_cfg(env_cfg) if isinstance(env_cfg, DirectRLEnvCfg): logger.warning( @@ -155,17 +144,19 @@ def run( policy_factory: Builds the inference policy of a checkpoint file. checkpoint_pattern: Regular expression matching the library's checkpoint file names. reference_path: Checkpoint driving the reference slot. - log_root_path: The experiment's log directory, where the checkpoint window starts by default. + log_root_path: The experiment's log directory, where the checkpoint window starts unless the Newton options name + a ``checkpoint_ghost_root``. run_playback: The play script's playback loop, called with ``step``, ``dt``, ``args_cli`` and ``env_cfg``. """ if args_cli.deterministic: configure_seed(env.unwrapped.cfg.seed, torch_deterministic=True) # no runner is built here, so seed up front reference_file = Path(reference_path) + root = getattr(_newton_cfg(env.unwrapped.cfg), "checkpoint_ghost_root", None) or log_root_path session = CheckpointGhostSession( env.unwrapped, # the Isaac Lab environment: its observation groups and 5-tuple step, free of library wrappers - num_slots=args_cli.checkpoint_ghost_slots, + num_slots=_slot_count(env.unwrapped.cfg, env.unwrapped.num_envs), task=args_cli.task, - checkpoint_root=os.path.abspath(args_cli.checkpoint_ghost_root or log_root_path), + checkpoint_root=os.path.abspath(root), checkpoint_pattern=checkpoint_pattern, policy_factory=policy_factory, reference=CheckpointGhostCheckpoint( diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index bbda036ae410..dae2f52df629 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -27,20 +27,22 @@ def _env_cfg(backend, scene=None, curriculum=None): def _args(**kwargs): - return SimpleNamespace(checkpoint_ghosts=True, checkpoint_ghost_slots=None, **kwargs) + return SimpleNamespace(checkpoint_ghosts=True, **kwargs) + + +def _newton(**options): + return SimpleNamespace(visualizer_type="newton", **options) def test_nothing_is_checked_or_changed_without_the_flag(): - args = SimpleNamespace(checkpoint_ghosts=False, checkpoint_ghost_slots=99) + args = SimpleNamespace(checkpoint_ghosts=False) play.check(args, object()) play.prepare(args, object()) - assert args.checkpoint_ghost_slots == 99 - def test_newton_among_several_selected_viewers_is_accepted(): - backends = [SimpleNamespace(visualizer_type="viser"), SimpleNamespace(visualizer_type="newton")] + backends = [SimpleNamespace(visualizer_type="viser"), _newton()] play.check(_args(), _env_cfg(backends)) @@ -50,15 +52,18 @@ def test_without_newton_the_run_is_rejected(): play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="viser"))) -def test_a_slot_count_out_of_range_fails_at_argument_parsing(): +def test_a_slot_count_out_of_range_is_rejected(): + with pytest.raises(SystemExit, match="between 2 and"): + play.check(_args(), _env_cfg(_newton(checkpoint_ghost_slots=1))) + + +def test_the_flag_is_the_only_command_line_option(): import argparse parser = argparse.ArgumentParser() play.add_args(parser) - assert parser.parse_args(["--checkpoint_ghost_slots", "4"]).checkpoint_ghost_slots == 4 - with pytest.raises(SystemExit): - parser.parse_args(["--checkpoint_ghost_slots", "1"]) + assert vars(parser.parse_args(["--checkpoint_ghosts"])) == {"checkpoint_ghosts": True} def test_a_task_whose_curriculum_selects_the_reset_state_is_rejected(): @@ -68,21 +73,20 @@ class _ResetStateCurriculum: curriculum = SimpleNamespace(reset_dataset=SimpleNamespace(func=_ResetStateCurriculum)) with pytest.raises(SystemExit, match="reset_dataset"): - play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum)) + play.check(_args(), _env_cfg(_newton(), curriculum=curriculum)) def test_an_ordinary_curriculum_term_is_accepted(): curriculum = SimpleNamespace(terrain_levels=SimpleNamespace(func=lambda env, env_ids: None)) - play.check(_args(), _env_cfg(SimpleNamespace(visualizer_type="newton"), curriculum=curriculum)) + play.check(_args(), _env_cfg(_newton(), curriculum=curriculum)) def _slots(monkeypatch, total: int, slots: int | None): monkeypatch.setattr(play.CheckpointGhostSync, "configure_env_cfg", Mock()) - args = _args() - args.checkpoint_ghost_slots = slots - play.prepare(args, SimpleNamespace(scene=SimpleNamespace(num_envs=total))) - return args.checkpoint_ghost_slots + cfg = _env_cfg(_newton(checkpoint_ghost_slots=slots), scene=SimpleNamespace(num_envs=total)) + play.prepare(_args(), cfg) + return play._slot_count(cfg, total) def test_the_slots_default_to_eight_capped_at_num_envs(monkeypatch): @@ -100,7 +104,15 @@ def test_a_single_environment_cannot_be_split(monkeypatch): _slots(monkeypatch, 1, None) -def test_the_session_is_built_from_the_play_arguments(monkeypatch, tmp_path): +def _run_env(viewers, **options): + cfg = _env_cfg(_newton(**options)) + cfg.seed = 0 + return SimpleNamespace( + unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=viewers), step_dt=0.02, num_envs=16, cfg=cfg) + ) + + +def test_the_session_is_built_from_the_play_arguments_and_newton_options(monkeypatch, tmp_path): created = {} class _Session: @@ -118,10 +130,8 @@ def close(self): checkpoint.parent.mkdir() checkpoint.touch() viewer = Mock() - env = SimpleNamespace(unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=[viewer]), step_dt=0.02, cfg="cfg")) - args = SimpleNamespace( - checkpoint_ghost_root=None, checkpoint_ghost_slots=4, task="Isaac-Reach-Franka", deterministic=False - ) + env = _run_env([viewer], checkpoint_ghost_slots=4, checkpoint_ghost_root=str(tmp_path / "ghosts")) + args = SimpleNamespace(task="Isaac-Reach-Franka", deterministic=False) run_playback = Mock() play.run( @@ -136,7 +146,7 @@ def close(self): assert created["num_slots"] == 4 assert created["task"] == "Isaac-Reach-Franka" - assert created["checkpoint_root"] == str(tmp_path) + assert created["checkpoint_root"] == str(tmp_path / "ghosts") # the configured folder, not the log directory assert created["reference"].name == "model_5.pt" viewer.attach_checkpoint_ghosts.assert_called_once() run_playback.assert_called_once() @@ -147,8 +157,8 @@ def test_the_session_is_closed_when_no_viewer_can_attach(monkeypatch, tmp_path): monkeypatch.setattr(play, "CheckpointGhostSession", Mock(return_value=session)) checkpoint = tmp_path / "model_5.pt" checkpoint.touch() - env = SimpleNamespace(unwrapped=SimpleNamespace(sim=SimpleNamespace(visualizers=[object()]), step_dt=0.02)) - args = SimpleNamespace(checkpoint_ghost_root=None, checkpoint_ghost_slots=2, task="t", deterministic=False) + env = _run_env([object()]) + args = SimpleNamespace(task="t", deterministic=False) with pytest.raises(RuntimeError, match="initialized Newton GL visualizer"): play.run( @@ -179,7 +189,7 @@ def test_a_direct_environment_is_accepted(): from isaaclab.envs import DirectRLEnvCfg cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) - cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=SimpleNamespace(visualizer_type="newton"))]) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=_newton())]) play.check(_args(), cfg) diff --git a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst index 19077aeb7ff7..8fc9833b3679 100644 --- a/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst @@ -1,7 +1,6 @@ -* Added ``--checkpoint_ghosts`` and ``--checkpoint_ghost_slots`` to RSL-RL, rl_games, skrl, and Stable-Baselines3 playback, the Newton GL viewer's checkpoint - visualization. ``--num_envs`` is the total simulated and is split evenly among the checkpoints shown: the reference - starts with all of them, and adding a ghost resizes every slot (32 environments give 16 each with two checkpoints). - ``--checkpoint_ghost_slots`` caps the checkpoints shown at once (default eight, at most ``--num_envs``). - ``--checkpoint_ghost_root`` searches another directory for checkpoints. Plain playback allocates nothing for the feature. +* Added ``--checkpoint_ghosts`` to RSL-RL, rl_games, skrl, and Stable-Baselines3 playback, the Newton GL viewer's + checkpoint visualization. ``--num_envs`` is the total simulated and is split evenly among the checkpoints shown: the + reference starts with all of them, and adding a ghost resizes every slot (32 environments give 16 each with two + checkpoints). Plain playback allocates nothing for the feature. * Rejected ``--checkpoint_ghosts`` for tasks whose curriculum term sets the reset state, since ghosts disable curriculum terms. diff --git a/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-options.added.rst b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-options.added.rst new file mode 100644 index 000000000000..d2da8541bbc7 --- /dev/null +++ b/source/isaaclab_visualizers/changelog.d/checkpoint-ghost-options.added.rst @@ -0,0 +1,3 @@ +* Added the Newton backend options ``checkpoint_ghost_slots``, the most checkpoints Checkpoint Ghosts show at once + (default eight, at most the number of environments), and ``checkpoint_ghost_root``, the folder its checkpoint browser + starts in. diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py index 21f8bf30156e..118a1df23395 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer_cfg.py @@ -26,6 +26,15 @@ class NewtonGLBackendCfg(VisualizerBackendCfg): visualizer_type: str = "newton" cloning_contexts: ClassVar[tuple[type | str, ...]] = ("isaaclab_newton.cloner:NewtonReplicateContext",) + checkpoint_ghost_slots: int | None = None + """Most checkpoints Checkpoint Ghosts show at once, including the reference (2 to 8). + + Defaults to 8, capped at the number of environments. Only used with ``--checkpoint_ghosts``. + """ + + checkpoint_ghost_root: str | None = None + """Directory the Checkpoint Ghosts browser searches for checkpoints. Defaults to the experiment's log directory.""" + world_spacing: tuple[float, float, float] = (0.0, 0.0, 0.0) """Visual spacing between simulation worlds along each axis [m]. From b59bafef0dafe4f057861bc86e1284527b402686 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:53:10 +0000 Subject: [PATCH 18/24] Reject discrete direct actions and SB3 checkpoints without normalization statistics Ghosts only handle continuous direct action spaces, since the action buffer is sized from the Box shape. An SB3 checkpoint of a task that normalizes observations now fails to load when its statistics file is missing, instead of playing unnormalized. --- .../isaaclab/visualizers/checkpoint_ghost_play.py | 3 +++ .../test/visualizers/test_checkpoint_ghost_play.py | 13 +++++++++++++ .../isaaclab_rl/entrypoints/backends/play_sb3.py | 4 ++++ 3 files changed, 20 insertions(+) diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index 0fd0f7f137c4..2cb5b54c8022 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -21,6 +21,7 @@ from pathlib import Path from typing import Any +import gymnasium as gym import torch from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg @@ -80,6 +81,8 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: return if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): raise SystemExit("--checkpoint_ghosts only supports single-agent environments.") + if isinstance(env_cfg, DirectRLEnvCfg) and not isinstance(env_cfg.action_space, (int, gym.spaces.Box)): + raise SystemExit("--checkpoint_ghosts only supports direct environments with continuous (Box) actions.") newton = _newton_cfg(env_cfg) if newton is None: raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index dae2f52df629..c935cb6f741e 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -190,6 +190,7 @@ def test_a_direct_environment_is_accepted(): cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=_newton())]) + cfg.action_space = 6 play.check(_args(), cfg) @@ -215,3 +216,15 @@ def test_observation_groups_are_sliced_per_slot(): sliced = _slice(obs, slice(2, 4)) assert sliced["policy"].tolist() == [[2], [3]] and sliced["critic"]["a"].tolist() == [2, 3] + + +@pytest.mark.parametrize("action_space", [{3}, {"a": 2}]) +def test_a_direct_environment_with_discrete_or_composite_actions_is_rejected(action_space): + from isaaclab.envs import DirectRLEnvCfg + + cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=_newton())]) + cfg.action_space = action_space + + with pytest.raises(SystemExit, match="continuous"): + play.check(_args(), cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index 535430815e28..cf759b947f7a 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -146,6 +146,10 @@ def policy_factory(path: str): name = Path(path).name.replace("model", "model_vecnormalize", 1).replace(".zip", ".pkl") stats = Path(path).with_name(name) norm = VecNormalize.load(stats, env) if stats.exists() else None # each checkpoint has its own + if norm is None and agent_cfg.get("normalize_input"): + raise FileNotFoundError( + f"{stats.name} is missing next to it, and this task normalizes observations" + ) def act(obs): obs = env._process_obs(obs) From 2fd819119b30f14b0dd677cbc44b6b2616c16078 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:56:34 +0000 Subject: [PATCH 19/24] Move the per-library Checkpoint Ghosts policy factories out of the play scripts Each play script now makes one call into checkpoint_ghost_policies instead of carrying its own factory. --- .../backends/checkpoint_ghost_policies.py | 174 ++++++++++++++++++ .../entrypoints/backends/play_rl_games.py | 35 +--- .../entrypoints/backends/play_rsl_rl.py | 26 +-- .../entrypoints/backends/play_sb3.py | 31 +--- .../entrypoints/backends/play_skrl.py | 23 +-- 5 files changed, 185 insertions(+), 104 deletions(-) create mode 100644 source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py new file mode 100644 index 000000000000..ed5e2ed85204 --- /dev/null +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py @@ -0,0 +1,174 @@ +# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). +# All rights reserved. +# +# SPDX-License-Identifier: BSD-3-Clause + +"""Checkpoint Ghosts playback for each training library. + +Each ``run_`` builds the library's policy factory, which loads a checkpoint into its own policy so that every +slot keeps its own, and hands it to :func:`isaaclab.visualizers.checkpoint_ghost_play.run`. A play script calls it in +place of its normal playback loop when ``--checkpoint_ghosts`` is set. The library imports are local so that a +library only has to be installed to play with it. +""" + +from __future__ import annotations + +import argparse +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import torch + +from isaaclab.visualizers.checkpoint_ghost_play import PolicyAdapter, run + + +def run_rsl_rl( + env: Any, + args_cli: argparse.Namespace, + agent_cfg: Any, + reference_path: str, + log_root_path: str, + run_playback: Callable[..., None], +) -> None: + """Play RSL-RL checkpoints, each loaded into its own runner.""" + from tensordict import TensorDict + from torch.utils._pytree import tree_leaves + + from .runner_rsl_rl import create_rsl_rl_runner + + def policy_factory(path: str) -> PolicyAdapter: + runner = create_rsl_rl_runner(env, agent_cfg, inference=True) + runner.load(path) + policy = runner.get_inference_policy(device=env.unwrapped.device) + return PolicyAdapter( + lambda obs: policy(TensorDict(obs, batch_size=[tree_leaves(obs)[0].shape[0]])), + policy.reset, + agent_cfg.clip_actions, + ) + + run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r"model_.*\.pt", + reference_path=reference_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) + + +def run_rl_games( + env: Any, + args_cli: argparse.Namespace, + runner: Any, + params: dict, + reference_path: str, + log_root_path: str, + run_playback: Callable[..., None], +) -> None: + """Play rl_games checkpoints, each loaded into its own player with its own recurrent state.""" + from isaaclab.utils import index_fill_ + + def policy_factory(path: str) -> PolicyAdapter: + player = runner.create_player() + player.restore(path) + player.reset() + + def act(obs): + obs = player.obs_to_torch(env._process_obs(obs)["obs"]) + player.get_batch_size(obs, 1) + if player.is_rnn and player.states is None: + player.init_rnn() + return player.get_action(obs, is_deterministic=player.is_deterministic) + + def reset(dones): + if dones is None: # the slot was resized: its recurrent states are rebuilt on the next act + player.states = None + elif player.states is not None: + for state in player.states: + index_fill_(state, dones, 0.0, dim=1) + + return PolicyAdapter(act, reset, params.get("env", {}).get("clip_actions")) + + run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r".*\.pth", + reference_path=reference_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) + + +def run_skrl( + env: Any, + args_cli: argparse.Namespace, + runner_cls: type, + agent_cfg: dict, + reference_path: str, + log_root_path: str, + run_playback: Callable[..., None], +) -> None: + """Play skrl checkpoints, each loaded into its own agent.""" + + def policy_factory(path: str) -> PolicyAdapter: + agent = runner_cls(env, agent_cfg).agent # one agent per checkpoint, since they run side by side + agent.load(path) + agent.enable_training_mode(False, apply_to_models=True) + + def act(obs): + outputs = agent.act(obs["policy"], obs.get("critic"), timestep=0, timesteps=0) + return outputs[-1].get("mean_actions", outputs[0]) + + return PolicyAdapter(act) + + run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r".*\.pt", + reference_path=reference_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) + + +def run_sb3( + env: Any, + args_cli: argparse.Namespace, + agent_cfg: dict, + reference_path: str, + log_root_path: str, + run_playback: Callable[..., None], +) -> None: + """Play SB3 checkpoints, each with the normalization statistics saved beside it.""" + from stable_baselines3 import PPO + from stable_baselines3.common.vec_env import VecNormalize + + def policy_factory(path: str) -> PolicyAdapter: + model = PPO.load(path, device=agent_cfg["device"]) + name = Path(path).name.replace("model", "model_vecnormalize", 1).replace(".zip", ".pkl") + stats = Path(path).with_name(name) + norm = VecNormalize.load(stats, env) if stats.exists() else None + if norm is None and agent_cfg.get("normalize_input"): + # plain playback would normalize with live statistics instead, which no checkpoint was trained with + raise FileNotFoundError(f"{stats.name} is missing, and this task normalizes observations") + + def act(obs): + obs = env._process_obs(obs) + actions, _ = model.predict(norm.normalize_obs(obs) if norm else obs, deterministic=True) + return torch.as_tensor(actions, device=env.unwrapped.device) + + return PolicyAdapter(act) + + run( + env, + args_cli, + policy_factory=policy_factory, + checkpoint_pattern=r"model(?:_.*)?\.zip", + reference_path=reference_path, + log_root_path=log_root_path, + run_playback=run_playback, + ) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py index b0f379615590..ee1309420cc8 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py @@ -44,6 +44,7 @@ show_run_summary, startup_screen, ) +from . import checkpoint_ghost_policies from . import cli_args_rl_games as cli_args logger = logging.getLogger(__name__) @@ -156,39 +157,9 @@ def run(argv: list[str]) -> None: runner.load(agent_cfg) # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: - - def policy_factory(path: str): - # a ghost gets its own player, so every slot keeps its own policy and recurrent state - player = runner.create_player() - player.restore(path) - player.reset() - - def act(obs): - obs = player.obs_to_torch(env._process_obs(obs)["obs"]) - player.get_batch_size(obs, 1) - if player.is_rnn and player.states is None: - player.init_rnn() - return player.get_action(obs, is_deterministic=player.is_deterministic) - - def reset(dones): - if dones is None: # the slot was resized: its recurrent states are rebuilt on the next act - player.states = None - elif player.states is not None: - for state in player.states: - index_fill_(state, dones, 0.0, dim=1) - - clip = params.get("env", {}).get("clip_actions") - return checkpoint_ghost_play.PolicyAdapter(act, reset, clip) - screen.close() - checkpoint_ghost_play.run( - env, - args_cli, - policy_factory=policy_factory, - checkpoint_pattern=r".*\.pth", - reference_path=resume_path, - log_root_path=log_root_path, - run_playback=run_playback, + checkpoint_ghost_policies.run_rl_games( + env, args_cli, runner, params, resume_path, log_root_path, run_playback ) return agent: BasePlayer = runner.create_player() diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index 800db25a661d..55eec360eefb 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -12,9 +12,6 @@ import logging import os -from tensordict import TensorDict -from torch.utils._pytree import tree_leaves - from isaaclab.app import add_launcher_args, launch_simulation from isaaclab.envs import DirectMARLEnvCfg from isaaclab.utils.assets import retrieve_file_path @@ -44,6 +41,7 @@ show_run_summary, startup_screen, ) +from . import checkpoint_ghost_policies from . import cli_args_rsl_rl as cli_args from .runner_rsl_rl import create_rsl_rl_runner @@ -147,28 +145,8 @@ def run(argv: list[str]) -> None: logger.info(f"Loading model checkpoint from: {resume_path}") # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: - - def policy_factory(path: str): - # a ghost loads a checkpoint into its own runner, so every slot keeps its own policy - runner = create_rsl_rl_runner(env, agent_cfg, inference=True) - runner.load(path) - policy = runner.get_inference_policy(device=env.unwrapped.device) - return checkpoint_ghost_play.PolicyAdapter( - lambda obs: policy(TensorDict(obs, batch_size=[tree_leaves(obs)[0].shape[0]])), - policy.reset, - agent_cfg.clip_actions, - ) - screen.close() - checkpoint_ghost_play.run( - env, - args_cli, - policy_factory=policy_factory, - checkpoint_pattern=r"model_.*\.pt", - reference_path=resume_path, - log_root_path=log_root_path, - run_playback=run_playback, - ) + checkpoint_ghost_policies.run_rsl_rl(env, args_cli, agent_cfg, resume_path, log_root_path, run_playback) return runner = create_rsl_rl_runner(env, agent_cfg, inference=True) # configure_seed must run after runner construction so torch determinism does not disturb its initialization diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index cf759b947f7a..3e553400e6aa 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -13,7 +13,6 @@ import os from pathlib import Path -import torch from stable_baselines3 import PPO from stable_baselines3.common.vec_env import VecNormalize @@ -43,6 +42,7 @@ show_run_summary, startup_screen, ) +from . import checkpoint_ghost_policies from . import cli_args_sb3 as cli_args logger = logging.getLogger(__name__) @@ -139,34 +139,9 @@ def run(argv: list[str]) -> None: env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: - - def policy_factory(path: str): - # each checkpoint has its own policy and its own normalization statistics - model = PPO.load(path, device=agent_cfg["device"]) - name = Path(path).name.replace("model", "model_vecnormalize", 1).replace(".zip", ".pkl") - stats = Path(path).with_name(name) - norm = VecNormalize.load(stats, env) if stats.exists() else None # each checkpoint has its own - if norm is None and agent_cfg.get("normalize_input"): - raise FileNotFoundError( - f"{stats.name} is missing next to it, and this task normalizes observations" - ) - - def act(obs): - obs = env._process_obs(obs) - actions, _ = model.predict(norm.normalize_obs(obs) if norm else obs, deterministic=True) - return torch.as_tensor(actions, device=env.unwrapped.device) - - return checkpoint_ghost_play.PolicyAdapter(act) - screen.close() - checkpoint_ghost_play.run( - env, - args_cli, - policy_factory=policy_factory, - checkpoint_pattern=r"model(?:_.*)?\.zip", - reference_path=checkpoint_path, - log_root_path=log_root_path, - run_playback=run_playback, + checkpoint_ghost_policies.run_sb3( + env, args_cli, agent_cfg, checkpoint_path, log_root_path, run_playback ) return vec_norm_path = checkpoint_path.replace("/model", "/model_vecnormalize").replace(".zip", ".pkl") diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index 87ddb7b7b17f..e9aa027e1612 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -52,6 +52,7 @@ show_run_summary, startup_screen, ) +from . import checkpoint_ghost_policies from . import cli_args_skrl as cli_args logger = logging.getLogger(__name__) @@ -172,27 +173,9 @@ def _run(args_cli: argparse.Namespace) -> None: experiment_cfg["checkpoint_interval"] = 0 # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. if args_cli.checkpoint_ghosts: - - def policy_factory(path: str): - agent = runner_cls(env, agent_cfg).agent # one agent per checkpoint, since they run side by side - agent.load(path) - agent.enable_training_mode(False, apply_to_models=True) - - def act(obs): - outputs = agent.act(obs["policy"], obs.get("critic"), timestep=0, timesteps=0) - return outputs[-1].get("mean_actions", outputs[0]) - - return checkpoint_ghost_play.PolicyAdapter(act) - screen.close() - checkpoint_ghost_play.run( - env, - args_cli, - policy_factory=policy_factory, - checkpoint_pattern=r".*\.pt", - reference_path=resume_path, - log_root_path=log_root_path, - run_playback=run_playback, + checkpoint_ghost_policies.run_skrl( + env, args_cli, runner_cls, agent_cfg, resume_path, log_root_path, run_playback ) return runner = runner_cls(env, agent_cfg) From 75967785c300b266908fd18a9ee410e1c5c28e2b Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 06:58:36 +0000 Subject: [PATCH 20/24] Trim the Checkpoint Ghosts comments and boilerplate in the play scripts --- .../isaaclab/visualizers/checkpoint_ghost_play.py | 2 ++ .../test/visualizers/test_checkpoint_ghost_play.py | 5 +++++ .../isaaclab_rl/entrypoints/backends/play_rl_games.py | 6 +----- .../isaaclab_rl/entrypoints/backends/play_rsl_rl.py | 6 +----- .../isaaclab_rl/entrypoints/backends/play_sb3.py | 6 +----- .../isaaclab_rl/entrypoints/backends/play_skrl.py | 8 +------- 6 files changed, 11 insertions(+), 22 deletions(-) diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index 2cb5b54c8022..18ce58e705ee 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -79,6 +79,8 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: """ if not args_cli.checkpoint_ghosts: return + if getattr(args_cli, "ml_framework", "torch") != "torch": # skrl can also run on jax or warp + raise SystemExit("--checkpoint_ghosts supports only --ml_framework torch.") if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): raise SystemExit("--checkpoint_ghosts only supports single-agent environments.") if isinstance(env_cfg, DirectRLEnvCfg) and not isinstance(env_cfg.action_space, (int, gym.spaces.Box)): diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index c935cb6f741e..5092590938e6 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -228,3 +228,8 @@ def test_a_direct_environment_with_discrete_or_composite_actions_is_rejected(act with pytest.raises(SystemExit, match="continuous"): play.check(_args(), cfg) + + +def test_a_non_torch_skrl_framework_is_rejected(): + with pytest.raises(SystemExit, match="torch"): + play.check(_args(ml_framework="jax"), object()) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py index ee1309420cc8..9f4799995cde 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py @@ -63,7 +63,6 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: agent_help="Name of the RL agent configuration entry point.", ) parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint path, latest/best, or pretrained.") - # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) @@ -113,7 +112,6 @@ def run(argv: list[str]) -> None: " --agent rl_games_cfg_entry_point, or use --rl_library rsl_rl for RSL-RL runner configurations." ) pre_launch_video_config(env_cfg, args_cli) - # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: @@ -130,7 +128,6 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(os.path.dirname(resume_path)) env_cfg.log_dir = log_dir - # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") @@ -155,7 +152,7 @@ def run(argv: list[str]) -> None: if args_cli.deterministic: configure_seed(env_cfg.seed, torch_deterministic=True) runner.load(agent_cfg) - # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. + # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_rl_games( @@ -184,6 +181,5 @@ def step() -> None: index_fill_(state, dones, 0.0, dim=1) screen.close() - # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index 55eec360eefb..e2a43c13cca5 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -63,7 +63,6 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: parser.add_argument( "--external_callback", default=None, help="Fully qualified path to an externally defined callback." ) - # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) @@ -110,7 +109,6 @@ def run(argv: list[str]) -> None: with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) - # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: @@ -127,7 +125,6 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(resume_path) env_cfg.log_dir = log_dir - # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play", checkpoint_path=resume_path) @@ -143,7 +140,7 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) logger.info(f"Loading model checkpoint from: {resume_path}") - # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. + # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_rsl_rl(env, args_cli, agent_cfg, resume_path, log_root_path, run_playback) @@ -168,6 +165,5 @@ def step() -> None: policy.reset(dones) screen.close() - # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index 3e553400e6aa..d22a753a0f09 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -67,7 +67,6 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: default=False, help="Use a slower SB3 wrapper but keep all the extra training info.", ) - # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) @@ -105,7 +104,6 @@ def run(argv: list[str]) -> None: with startup_screen(args_cli, num_stages=3) as screen: env_cfg, agent_cfg = resolve_task_config(args_cli.task, args_cli.agent, play_mode=not args_cli.train_env_cfg) pre_launch_video_config(env_cfg, args_cli) - # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: @@ -121,7 +119,6 @@ def run(argv: list[str]) -> None: return log_dir = os.path.dirname(checkpoint_path) env_cfg.log_dir = log_dir - # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") @@ -137,7 +134,7 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) - # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. + # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_sb3( @@ -173,6 +170,5 @@ def step() -> None: obs, _, _, _ = env.step(actions) screen.close() - # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=env.unwrapped.step_dt, args_cli=args_cli, env_cfg=env_cfg) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index e9aa027e1612..6d93e3827263 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -72,7 +72,6 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: ) parser.add_argument("--checkpoint", type=str, default=None, help="Checkpoint path, latest/best, or pretrained.") cli_args.add_skrl_args(parser) - # Checkpoint Ghosts: overlay several checkpoints in the Newton viewer. checkpoint_ghost_play.add_args(parser) add_launcher_args(parser) args_cli, hydra_args = setup_preset_cli(parser, argv) @@ -125,10 +124,7 @@ def _run(args_cli: argparse.Namespace) -> None: ) algorithm = resolve_skrl_algorithm(agent_cfg, args_cli.algorithm) pre_launch_video_config(env_cfg, args_cli) - # Checkpoint Ghosts: reject unsupported setups before the simulation launches. checkpoint_ghost_play.check(args_cli, env_cfg) - if args_cli.checkpoint_ghosts and args_cli.ml_framework != "torch": - raise SystemExit("--checkpoint_ghosts supports only --ml_framework torch.") screen.stage("Launching simulation") with launch_simulation(env_cfg, args_cli), contextlib.ExitStack() as cleanup: show_run_summary(screen, args_cli, env_cfg, library=f"skrl ({args_cli.ml_framework})", action="play") @@ -152,7 +148,6 @@ def _run(args_cli: argparse.Namespace) -> None: return log_dir = os.path.dirname(os.path.dirname(resume_path)) env_cfg.log_dir = log_dir - # Checkpoint Ghosts: split --num_envs among the checkpoints; drop randomization that cannot be mirrored. checkpoint_ghost_play.prepare(args_cli, env_cfg) apply_video_recording(env_cfg, log_dir, args_cli, subdir="play") @@ -171,7 +166,7 @@ def _run(args_cli: argparse.Namespace) -> None: agent_cfg["trainer"]["close_environment_at_exit"] = False experiment_cfg["write_interval"] = 0 experiment_cfg["checkpoint_interval"] = 0 - # Checkpoint Ghosts: --checkpoint is the reference; the viewer HUD adds ghosts of other checkpoints. + # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_skrl( @@ -200,6 +195,5 @@ def step() -> None: states = env.state() screen.close() - # Checkpoint Ghosts: show the greyed-out HUD section that explains the flag. checkpoint_ghost_play.offer(env, env_cfg) run_playback(step, dt=dt, args_cli=args_cli, env_cfg=env_cfg) From 9e7a5c6946463900c42c35c0dc34883356319bfb Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 07:00:42 +0000 Subject: [PATCH 21/24] Read Checkpoint Ghosts options from a deprecated combined Newton config and expand ~ in the folder --- .../isaaclab/visualizers/checkpoint_ghost_play.py | 11 ++++++----- .../test/visualizers/test_checkpoint_ghost_play.py | 11 +++++++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index 18ce58e705ee..80a3f5ee9a86 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -59,9 +59,11 @@ def _newton_cfg(env_cfg: Any) -> Any | None: visualizers = [visualizers] # A shared visualizer configuration names its type on its backend; a deprecated combined one names it directly. for cfg in visualizers: + if getattr(cfg, "visualizer_type", None) == "newton": + return cfg # a deprecated combined configuration holds the backend options itself backend = getattr(cfg, "backend", None) for chosen in backend if isinstance(backend, (list, tuple)) else [backend]: # --viz newton,viser selects both - if (getattr(chosen, "visualizer_type", None) or getattr(cfg, "visualizer_type", None)) == "newton": + if getattr(chosen, "visualizer_type", None) == "newton": return chosen return None @@ -69,6 +71,8 @@ def _newton_cfg(env_cfg: Any) -> Any | None: def _slot_count(env_cfg: Any, num_envs: int) -> int: """Return how many checkpoints can be shown at once: the configured count, capped at the environments.""" slots = getattr(_newton_cfg(env_cfg), "checkpoint_ghost_slots", None) or MAX_CHECKPOINT_GHOST_SLOTS + if slots > num_envs: + logger.warning(f"checkpoint_ghost_slots {slots} exceeds --num_envs {num_envs}; using {num_envs} slots.") return min(slots, num_envs) @@ -111,9 +115,6 @@ def prepare(args_cli: argparse.Namespace, env_cfg: ManagerBasedRLEnvCfg | Direct total = env_cfg.scene.num_envs if total < 2: raise SystemExit("--checkpoint_ghosts needs --num_envs of at least 2: one environment per checkpoint.") - requested = getattr(_newton_cfg(env_cfg), "checkpoint_ghost_slots", None) - if requested is not None and requested > total: - logger.warning(f"checkpoint_ghost_slots {requested} exceeds --num_envs {total}; using {total} slots.") CheckpointGhostSync.configure_env_cfg(env_cfg) if isinstance(env_cfg, DirectRLEnvCfg): logger.warning( @@ -161,7 +162,7 @@ def run( env.unwrapped, # the Isaac Lab environment: its observation groups and 5-tuple step, free of library wrappers num_slots=_slot_count(env.unwrapped.cfg, env.unwrapped.num_envs), task=args_cli.task, - checkpoint_root=os.path.abspath(root), + checkpoint_root=os.path.abspath(os.path.expanduser(root)), checkpoint_pattern=checkpoint_pattern, policy_factory=policy_factory, reference=CheckpointGhostCheckpoint( diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index 5092590938e6..3821873243a5 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -233,3 +233,14 @@ def test_a_direct_environment_with_discrete_or_composite_actions_is_rejected(act def test_a_non_torch_skrl_framework_is_rejected(): with pytest.raises(SystemExit, match="torch"): play.check(_args(ml_framework="jax"), object()) + + +def test_a_deprecated_combined_config_holds_its_own_newton_options(): + combined = SimpleNamespace(visualizer_type="newton", backend=_newton(), checkpoint_ghost_slots=3) + cfg = ManagerBasedRLEnvCfg.__new__(ManagerBasedRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[combined]) + cfg.curriculum = None + + play.check(_args(), cfg) + + assert play._slot_count(cfg, 16) == 3 From 4ba0236e500ec7ba9d3d0db4bde03b45bf538aac Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 07:05:47 +0000 Subject: [PATCH 22/24] Drop the Checkpoint Ghosts comment from the play scripts --- .../isaaclab_rl/entrypoints/backends/play_rl_games.py | 1 - .../isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py | 1 - source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py | 1 - source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py | 1 - 4 files changed, 4 deletions(-) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py index 9f4799995cde..1808a3e52522 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rl_games.py @@ -152,7 +152,6 @@ def run(argv: list[str]) -> None: if args_cli.deterministic: configure_seed(env_cfg.seed, torch_deterministic=True) runner.load(agent_cfg) - # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_rl_games( diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py index e2a43c13cca5..2d013656d79a 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py @@ -140,7 +140,6 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions) logger.info(f"Loading model checkpoint from: {resume_path}") - # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_rsl_rl(env, args_cli, agent_cfg, resume_path, log_root_path, run_playback) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py index d22a753a0f09..b2288b86f229 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -134,7 +134,6 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = Sb3VecEnvWrapper(env, fast_variant=not args_cli.keep_all_info) - # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_sb3( diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py index 6d93e3827263..7dcde5d3825c 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_skrl.py @@ -166,7 +166,6 @@ def _run(args_cli: argparse.Namespace) -> None: agent_cfg["trainer"]["close_environment_at_exit"] = False experiment_cfg["write_interval"] = 0 experiment_cfg["checkpoint_interval"] = 0 - # Checkpoint Ghosts: --checkpoint is the reference, and the viewer HUD adds ghosts. if args_cli.checkpoint_ghosts: screen.close() checkpoint_ghost_policies.run_skrl( From c74499987610429990799dde6857c7ae0bba23ae Mon Sep 17 00:00:00 2001 From: mtrepte Date: Tue, 24 Nov 2026 07:08:01 +0000 Subject: [PATCH 23/24] Accept list-form continuous action spaces for direct environments Convert the declared action space with spec_to_gym_space before checking it, so [N] and N both pass, and require a flat Box. --- .../visualizers/checkpoint_ghost_play.py | 12 ++++++++++-- .../visualizers/test_checkpoint_ghost_play.py | 17 ++++++++++++++--- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py index 80a3f5ee9a86..915a044c92fa 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -26,6 +26,7 @@ from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg from isaaclab.envs.utils.checkpoint_ghost_sync import CheckpointGhostSync +from isaaclab.envs.utils.spaces import spec_to_gym_space from isaaclab.utils.seed import configure_seed from .checkpoint_ghost import CheckpointGhostCheckpoint @@ -87,8 +88,15 @@ def check(args_cli: argparse.Namespace, env_cfg: Any) -> None: raise SystemExit("--checkpoint_ghosts supports only --ml_framework torch.") if not isinstance(env_cfg, (ManagerBasedRLEnvCfg, DirectRLEnvCfg)): raise SystemExit("--checkpoint_ghosts only supports single-agent environments.") - if isinstance(env_cfg, DirectRLEnvCfg) and not isinstance(env_cfg.action_space, (int, gym.spaces.Box)): - raise SystemExit("--checkpoint_ghosts only supports direct environments with continuous (Box) actions.") + if isinstance(env_cfg, DirectRLEnvCfg): + try: + space = spec_to_gym_space(env_cfg.action_space) + except ValueError: + space = None + if not (isinstance(space, gym.spaces.Box) and len(space.shape) == 1): # the action buffer is one row per env + raise SystemExit( + "--checkpoint_ghosts only supports direct environments with a flat continuous action space." + ) newton = _newton_cfg(env_cfg) if newton is None: raise SystemExit("--checkpoint_ghosts requires the Newton GL visualizer; pass --visualizer newton.") diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py index 3821873243a5..027b80618534 100644 --- a/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -218,15 +218,15 @@ def test_observation_groups_are_sliced_per_slot(): assert sliced["policy"].tolist() == [[2], [3]] and sliced["critic"]["a"].tolist() == [2, 3] -@pytest.mark.parametrize("action_space", [{3}, {"a": 2}]) -def test_a_direct_environment_with_discrete_or_composite_actions_is_rejected(action_space): +@pytest.mark.parametrize("action_space", [{3}, {"a": 2}, [2, 3], "bad"]) +def test_a_direct_environment_without_flat_continuous_actions_is_rejected(action_space): from isaaclab.envs import DirectRLEnvCfg cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=_newton())]) cfg.action_space = action_space - with pytest.raises(SystemExit, match="continuous"): + with pytest.raises(SystemExit, match="flat continuous"): play.check(_args(), cfg) @@ -244,3 +244,14 @@ def test_a_deprecated_combined_config_holds_its_own_newton_options(): play.check(_args(), cfg) assert play._slot_count(cfg, 16) == 3 + + +@pytest.mark.parametrize("action_space", [6, [6]]) +def test_a_direct_environment_declaring_its_actions_as_an_int_or_a_list_is_accepted(action_space): + from isaaclab.envs import DirectRLEnvCfg + + cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=_newton())]) + cfg.action_space = action_space + + play.check(_args(), cfg) From 0a2664d256fc39a9560cdeadbb27fb6bdf6ba6b7 Mon Sep 17 00:00:00 2001 From: mtrepte Date: Wed, 25 Nov 2026 03:29:31 +0000 Subject: [PATCH 24/24] Keep each ghost on its reference's world spacing, reject per-environment prototypes, and load RSL-RL checkpoints on the play device --- .../envs/utils/checkpoint_ghost_sync.py | 23 +++++++++++++++++++ .../isaaclab/visualizers/checkpoint_ghost.py | 4 ++++ .../visualizers/checkpoint_ghost_session.py | 5 ++++ .../test/envs/test_checkpoint_ghost_sync.py | 9 ++++++++ .../backends/checkpoint_ghost_policies.py | 2 +- .../newton/newton_visualizer.py | 7 +++--- .../test/test_newton_adapter.py | 7 +++--- .../test/test_newton_checkpoint_ghosts.py | 4 ++-- 8 files changed, 51 insertions(+), 10 deletions(-) diff --git a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py index e4424f2003cd..6f0d7c4773f8 100644 --- a/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -58,6 +58,7 @@ def __init__(self, env: ManagerBasedRLEnv | DirectRLEnv, slice_size: int, num_sl raise ValueError( f"Environment has {env.num_envs} envs, expected at least {num_slices} slices of {slice_size} envs." ) + self._reject_multi_asset_scene(env) self._env = env self._slice_size = slice_size self._num_slices = num_slices @@ -73,6 +74,21 @@ def __init__(self, env: ManagerBasedRLEnv | DirectRLEnv, slice_size: int, num_sl self._compute_commands_original = self._commands.compute self._commands.compute = self._compute_commands + @staticmethod + def _reject_multi_asset_scene(env: ManagerBasedRLEnv | DirectRLEnv) -> None: + """Raise if an asset spawns different prototypes per environment, since a ghost would act on another object.""" + from isaaclab.sim.spawners.wrappers.wrappers_cfg import MultiAssetSpawnerCfg, MultiUsdFileCfg + + scene = env.scene + assets = {**getattr(scene, "articulations", {}), **getattr(scene, "rigid_objects", {})} + for name, asset in assets.items(): + spawn = getattr(getattr(asset, "cfg", None), "spawn", None) + if isinstance(spawn, (MultiAssetSpawnerCfg, MultiUsdFileCfg)): + raise ValueError( + f"Scene asset '{name}' spawns a different prototype per environment, so a ghost would not act on" + " the same object as its reference. Checkpoint Ghosts do not support this task yet." + ) + @staticmethod def configure_env_cfg(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg) -> list[str]: """Remove per-environment randomization that cannot be mirrored between slices. @@ -123,6 +139,13 @@ def env_origin_offsets(self) -> np.ndarray: ) return offsets.cpu().numpy().astype(np.float32) + def reference_env_ids(self) -> np.ndarray: + """Return the reference environment of each environment, shape ``[num_envs]``; references map to themselves.""" + ids = np.arange(self._env.num_envs) + for ghost_start in self._ghost_offsets.tolist(): + ids[ghost_start : ghost_start + self._slice_size] = np.arange(self._slice_size) + return ids + def close(self) -> None: """Restore the environment's original reset, command update, and terrain placement.""" self._env._reset_idx = self._reset_idx_original diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py index cef661c6c764..f7dc7cf8d524 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py @@ -204,6 +204,10 @@ def apply_pending_restart(self) -> None: added would otherwise stay in whatever pose its idle slot ended in. """ + @abstractmethod + def reference_env_ids(self) -> np.ndarray: + """Return the reference environment of each environment, shape ``[num_envs]``; references map to themselves.""" + @abstractmethod def env_origin_offsets(self) -> np.ndarray: """Return per-environment offsets [m], shape ``[num_envs, 3]``, that move each ghost onto the reference.""" diff --git a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py index 29961014b108..bcbdd6268365 100644 --- a/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py @@ -189,6 +189,11 @@ def remove_ghost(self, slot_index: int) -> None: # noqa: D102 self.layout.slots[slot_index].label = "" self._resplit() + def reference_env_ids(self) -> np.ndarray: # noqa: D102 + if self._sync is None: + return np.arange(self._env.unwrapped.num_envs) + return self._sync.reference_env_ids() + def env_origin_offsets(self) -> np.ndarray: # noqa: D102 if self._sync is None: return np.zeros((self._env.unwrapped.num_envs, 3), dtype=np.float32) diff --git a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py index 75a50300af21..7c8cefcb063d 100644 --- a/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -205,6 +205,15 @@ def test_environment_size_must_match_the_slices() -> None: CheckpointGhostSync(_make_env(), SLICE_SIZE, NUM_SLICES + 1) +def test_a_scene_with_a_different_prototype_per_environment_is_rejected() -> None: + from isaaclab.sim.spawners.wrappers.wrappers_cfg import MultiAssetSpawnerCfg + + env = _make_env() + env.scene.rigid_objects = {"object": SimpleNamespace(cfg=SimpleNamespace(spawn=MultiAssetSpawnerCfg()))} + with pytest.raises(ValueError, match="different prototype"): + CheckpointGhostSync(env, SLICE_SIZE, NUM_SLICES) + + def test_configure_env_cfg_keeps_only_randomization_the_reset_can_mirror() -> None: def term(mode: str) -> SimpleNamespace: return SimpleNamespace(mode=mode, func=lambda: None) diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py index ed5e2ed85204..2f96063effc5 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py @@ -39,7 +39,7 @@ def run_rsl_rl( def policy_factory(path: str) -> PolicyAdapter: runner = create_rsl_rl_runner(env, agent_cfg, inference=True) - runner.load(path) + runner.load(path, map_location=agent_cfg.device) policy = runner.get_inference_policy(device=env.unwrapped.device) return PolicyAdapter( lambda obs: policy(TensorDict(obs, batch_size=[tree_leaves(obs)[0].shape[0]])), diff --git a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py index 5195aabe7d0b..6f04263fdfb9 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -2109,15 +2109,14 @@ def _apply_visible_worlds(self) -> None: self._apply_rtx_visible_envs() def _apply_ghost_offsets(self) -> None: - """Overlay each ghost on the reference by the offset between their environment origins.""" + """Overlay each ghost on its reference: take the reference world's spacing offset, then shift by the origins.""" panel, viewer = self._checkpoint_ghost_panel, self._viewer if panel is None or self._base_world_offsets is None or getattr(viewer, "world_offsets", None) is None: return controller = panel.controller ghost = controller.env_origin_offsets() - viewer.world_offsets = wp.array( - self._base_world_offsets + ghost, dtype=wp.vec3, device=viewer.world_offsets.device - ) + base = self._base_world_offsets[controller.reference_env_ids()] + viewer.world_offsets = wp.array(base + ghost, dtype=wp.vec3, device=viewer.world_offsets.device) def _apply_rtx_visible_envs(self) -> None: """Hide the environments outside the visible set in the OVRTX viewer camera's scene.""" diff --git a/source/isaaclab_visualizers/test/test_newton_adapter.py b/source/isaaclab_visualizers/test/test_newton_adapter.py index 09db7f28a232..b26ea61337b9 100644 --- a/source/isaaclab_visualizers/test/test_newton_adapter.py +++ b/source/isaaclab_visualizers/test/test_newton_adapter.py @@ -1458,14 +1458,15 @@ def test_ghost_offsets_overlay_each_ghost_by_its_environment_origin(): viewer = SimpleNamespace(world_offsets=wp.zeros(3, dtype=wp.vec3, device="cpu")) visualizer = _make_newton_visualizer(viewer) controller = SimpleNamespace( - env_origin_offsets=lambda: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]], dtype=np.float32) + env_origin_offsets=lambda: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0]], dtype=np.float32), + reference_env_ids=lambda: np.array([0, 0, 0]), ) visualizer._checkpoint_ghost_panel = SimpleNamespace(controller=controller) - visualizer._base_world_offsets = np.tile(np.array([0, 2, 0], dtype=np.float32), (3, 1)) + visualizer._base_world_offsets = np.array([[0, 2, 0], [4, 2, 0], [8, 2, 0]], dtype=np.float32) # world_spacing visualizer._apply_ghost_offsets() - assert viewer.world_offsets.numpy()[:, 0].tolist() == [0.0, 1.0, 1.0] + assert viewer.world_offsets.numpy()[:, 0].tolist() == [0.0, 1.0, 1.0] # a ghost keeps its reference's spacing assert viewer.world_offsets.numpy()[:, 1].tolist() == [2.0, 2.0, 2.0] diff --git a/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py index 87dcd4263097..30f6e8e3bb74 100644 --- a/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py +++ b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py @@ -301,7 +301,7 @@ def button(self, label): def selectable(self, label, selected): # imgui requires the selected flag, as the real binding does self.drawn.append(label) - return label in self.clicks, False + return any(label == c or (c.startswith("##") and label.endswith(c)) for c in self.clicks), False def input_text(self, label, text, flags): return False, text @@ -358,7 +358,7 @@ def test_choosing_a_checkpoint_keeps_the_folder_and_an_unreadable_folder_is_repo panel = NewtonCheckpointGhostPanel(controller) panel._open_window() - panel._draw_window(_BrowserImgui(clicks=["model_1.pt 1970-01-01 00:00##/runs/task/model_1.pt"])) + panel._draw_window(_BrowserImgui(clicks=["##/runs/task/model_1.pt"])) # the label also shows a local time assert controller.added == ["/runs/task/model_1.pt"] and not panel._window_open panel._open_window()