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..07592d20655b 100644 --- a/docs/source/concepts/visualization.rst +++ b/docs/source/concepts/visualization.rst @@ -816,6 +816,37 @@ 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. +**Comparing checkpoints with Checkpoint Ghosts** + +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 + +``--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. 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 +opacity and tint under **Appearance**. The controls are disabled in the RTX view; switch the Renderer to OpenGL. + +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** Every Newton viewer has a **Visible Envs** slider in its left panel that sets how many 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..f74f472ce4e4 --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-relative-targets.fixed.rst @@ -0,0 +1,12 @@ +* 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. +* 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/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-session.added.rst b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst new file mode 100644 index 000000000000..a84cbab83f96 --- /dev/null +++ b/source/isaaclab/changelog.d/checkpoint-ghost-session.added.rst @@ -0,0 +1,10 @@ +* 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 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. +* 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/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..c805ab2b794a --- /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 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 new file mode 100644 index 000000000000..6f0d7c4773f8 --- /dev/null +++ b/source/isaaclab/isaaclab/envs/utils/checkpoint_ghost_sync.py @@ -0,0 +1,275 @@ +# 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 ..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 + +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 | DirectRLEnv, 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 has no scene. + ValueError: If the environment has fewer worlds than the slices need. + """ + 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." + ) + self._reject_multi_asset_scene(env) + 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._commands = getattr(env, "command_manager", None) # direct environments have none + env._reset_idx = self._reset_idx + if self._commands is not None: + 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. + + 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. + + Returns: + Names of the disabled terms. + """ + removed = [] + # A task may leave these fields None when it has no events, curriculum, or observation groups. + 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 + 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 (): + 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 group is not None and group.enable_corruption: + 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 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 + 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) + + 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 + 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) + 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) + scene.reset_to(_gather(state, source), env_ids=ghosts, is_relative=True) + self._copy_joint_targets(ghosts, source) + 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. + + 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._commands + 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 _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/isaaclab/visualizers/__init__.pyi b/source/isaaclab/isaaclab/visualizers/__init__.pyi index a230550c4afe..0b3134347015 100644 --- a/source/isaaclab/isaaclab/visualizers/__init__.pyi +++ b/source/isaaclab/isaaclab/visualizers/__init__.pyi @@ -9,7 +9,12 @@ __all__ = [ "ImageViewCfg", "KeyEventSource", "KeyboardSubscription", + "CHECKPOINT_GHOST_COLORS", "PerspectiveCameraCfg", + "CheckpointGhostCheckpoint", + "CheckpointGhostController", + "CheckpointGhostLayout", + "CheckpointGhostSlot", "SceneCameraCfg", "VisualizerCfg", "VisualizerBackendCfg", @@ -20,6 +25,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..f7dc7cf8d524 --- /dev/null +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost.py @@ -0,0 +1,213 @@ +# 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. + """ + + @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. + """ + + @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.""" + + @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. + + Returns: + None on success, otherwise a message explaining why the checkpoint could not be loaded. + """ + + @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. + + 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 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_play.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py new file mode 100644 index 000000000000..915a044c92fa --- /dev/null +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_play.py @@ -0,0 +1,219 @@ +# 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 + +import gymnasium as gym +import torch + +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 +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 flag 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. The slot count and browser folder are Newton visualizer options" + " (checkpoint_ghost_slots, checkpoint_ghost_root)." + ), + ) + + +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: + 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) == "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 + 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) + + +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 + 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): + 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.") + 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. + 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 | 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 + 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.") + 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, DirectRLEnvCfg)): + 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 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=_slot_count(env.unwrapped.cfg, env.unwrapped.num_envs), + task=args_cli.task, + checkpoint_root=os.path.abspath(os.path.expanduser(root)), + 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() + + +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: + 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/isaaclab/visualizers/checkpoint_ghost_session.py b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py new file mode 100644 index 000000000000..bcbdd6268365 --- /dev/null +++ b/source/isaaclab/isaaclab/visualizers/checkpoint_ghost_session.py @@ -0,0 +1,253 @@ +# 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. + +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 + +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 .checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostController, CheckpointGhostLayout + +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: 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] + + +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) + 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. + """ + + _actions: torch.Tensor | None = None + """Actions of every environment, reused by every step.""" + + def __init__( + self, + env: Any, + *, + num_slots: int, + task: str, + checkpoint_root: str, + 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. + + 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. + 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 = _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 + self._restart_pending = False + self._sync: CheckpointGhostSync | None = None + self._load(0, reference) + 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 + + @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 + 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) + if empty is None: + return "All ghost slots are in use." + try: + self._load(empty.index, checkpoint) + 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 = "" + 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 + + 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) + 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 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 = "" + 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) + 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() # 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.""" + self.apply_pending_restart() + size = self.layout.slice_size + if self._actions is None: + 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](_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. + 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. + 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/test/envs/test_checkpoint_ghost_sync.py b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py new file mode 100644 index 000000000000..7c8cefcb063d --- /dev/null +++ b/source/isaaclab/test/envs/test_checkpoint_ghost_sync.py @@ -0,0 +1,357 @@ +# 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(), + extras={}, + 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 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]]) + + +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_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) + + 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", func=lambda: None)), + curriculum=None, + observations=SimpleNamespace(policy=SimpleNamespace(enable_corruption=False)), + ) + + assert CheckpointGhostSync.configure_env_cfg(cfg) == ["events.push"] + 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: + 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 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)) + + +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 reset_with_randomization(env_ids: torch.Tensor) -> None: + reset_idx(env_ids) + sampled[env_ids] = torch.rand(len(env_ids)) + + 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) + + env._reset_idx(torch.arange(SLICE_SIZE)) + + 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() + + +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"] + + +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 new file mode 100644 index 000000000000..027b80618534 --- /dev/null +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_play.py @@ -0,0 +1,257 @@ +# 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 +import torch + +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, **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) + + play.check(args, object()) + play.prepare(args, object()) + + +def test_newton_among_several_selected_viewers_is_accepted(): + backends = [SimpleNamespace(visualizer_type="viser"), _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(): + 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 vars(parser.parse_args(["--checkpoint_ghosts"])) == {"checkpoint_ghosts": True} + + +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(_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(_newton(), curriculum=curriculum)) + + +def _slots(monkeypatch, total: int, slots: int | None): + monkeypatch.setattr(play.CheckpointGhostSync, "configure_env_cfg", Mock()) + 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): + 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 _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: + 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 = _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( + 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 / "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() + + +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 = _run_env([object()]) + args = SimpleNamespace(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 + + +def test_a_direct_environment_is_accepted(): + from isaaclab.envs import DirectRLEnvCfg + + cfg = DirectRLEnvCfg.__new__(DirectRLEnvCfg) + cfg.sim = SimpleNamespace(visualizer_cfgs=[SimpleNamespace(backend=_newton())]) + cfg.action_space = 6 + + 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] + + +@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="flat 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()) + + +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 + + +@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) diff --git a/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py new file mode 100644 index 000000000000..48ebafe7ee58 --- /dev/null +++ b/source/isaaclab/test/visualizers/test_checkpoint_ghost_session.py @@ -0,0 +1,286 @@ +# 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 import checkpoint_ghost_session as checkpoint_ghosts +from isaaclab.visualizers.checkpoint_ghost import CheckpointGhostCheckpoint, CheckpointGhostLayout +from isaaclab.visualizers.checkpoint_ghost_session 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 + 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(): + 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 = {"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 = ( + {"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): + sync = Mock() + monkeypatch.setattr(checkpoint_ghosts, "CheckpointGhostSync", sync) + env = Mock(unwrapped=SimpleNamespace(device="cpu", step_dt=0.02, num_envs=6)) + 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_adding_and_removing_a_ghost_splits_the_environments_again(monkeypatch): + session, sync = _start(monkeypatch) + 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_load_failure_is_reported_in_one_line(): + 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") + + 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) + 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) + 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) + + 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 + + +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 + + +def test_a_ghost_added_while_the_environment_steps_skips_the_stale_policy_resets(): + session, env, policy = _session(pending=False) + 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 ( + {"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 + + 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) + 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_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..8fc9833b3679 --- /dev/null +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-play.added.rst @@ -0,0 +1,6 @@ +* 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_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..e2f47e914650 --- /dev/null +++ b/source/isaaclab_rl/changelog.d/checkpoint-ghost-review-fixes.fixed.rst @@ -0,0 +1,5 @@ +* 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. 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/checkpoint_ghost_policies.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/checkpoint_ghost_policies.py new file mode 100644 index 000000000000..2f96063effc5 --- /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, 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]])), + 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 5b5758217228..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 @@ -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 @@ -43,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__) @@ -61,6 +63,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 +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_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 +128,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 +152,12 @@ 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: + screen.close() + checkpoint_ghost_policies.run_rl_games( + env, args_cli, runner, params, resume_path, log_root_path, run_playback + ) + return agent: BasePlayer = runner.create_player() agent.restore(resume_path) agent.reset() @@ -169,4 +180,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 c59a592e596f..1928f9aba0c7 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 @@ -21,6 +21,7 @@ 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 import checkpoint_ghost_play import isaaclab_tasks # noqa: F401 from isaaclab_tasks.utils import get_checkpoint_path, resolve_task_config, setup_preset_cli @@ -44,6 +45,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 configure_rsl_rl_env_cfg, create_rsl_rl_runner, wrap_rsl_rl_env @@ -65,6 +67,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_ghost_play.add_args(parser) parser.add_argument( "--evaluate", action="store_true", help="Score the first episode of each manager-based environment and exit." ) @@ -158,6 +161,7 @@ def run(argv: list[str]) -> None: if args_cli.evaluate and not isinstance(env_cfg, ManagerBasedRLEnvCfg): raise ValueError("--evaluate requires a manager-based RL environment for termination reporting") 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="rsl_rl", action="play") @@ -173,6 +177,7 @@ def run(argv: list[str]) -> None: return log_dir = 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", checkpoint_path=resume_path) configure_rsl_rl_env_cfg(env_cfg, agent_cfg, inference=not args_cli.train_env_cfg) @@ -188,6 +193,10 @@ def run(argv: list[str]) -> None: screen.stage("Loading policy") env = wrap_rsl_rl_env(env, agent_cfg) logger.info(f"Loading model checkpoint from: {resume_path}") + 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) + 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: @@ -208,6 +217,7 @@ def run(argv: list[str]) -> None: runner.export_policy_to_onnx(path=export_model_dir, filename="policy.onnx") screen.close() + checkpoint_ghost_play.offer(env, env_cfg) play_policy(env, policy, args_cli, 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 150abc2fa724..b2288b86f229 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_sb3.py @@ -19,6 +19,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 @@ -41,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__) @@ -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,12 @@ 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: + screen.close() + 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") vec_norm_path = Path(vec_norm_path) if vec_norm_path.exists(): @@ -158,4 +169,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..7dcde5d3825c 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 @@ -51,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__) @@ -70,6 +72,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 +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_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 +148,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 +166,12 @@ 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: + screen.close() + 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) # configure_seed must run after Runner() so torch determinism does not disturb its initialization if args_cli.deterministic: @@ -183,4 +194,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) 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..5084ce89c98f --- /dev/null +++ b/source/isaaclab_rl/test/test_checkpoint_ghost_launch.py @@ -0,0 +1,37 @@ +# 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 selection of the RSL-RL play script, which Checkpoint Ghosts also use.""" + +from __future__ import annotations + +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +pytest.importorskip("rsl_rl") + +from isaaclab_rl.entrypoints.backends import play_rsl_rl + + +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"} + + +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 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) 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/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_checkpoint_ghosts.py b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py new file mode 100644 index 000000000000..2c1acdcd9580 --- /dev/null +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_checkpoint_ghosts.py @@ -0,0 +1,394 @@ +# 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._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] = [] + 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._other_task(self._directory)), + *((f, self._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 _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() + + 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._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") + 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 cb81c5dbd7ba..aef289baa868 100644 --- a/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py +++ b/source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py @@ -51,6 +51,7 @@ 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 @@ -58,6 +59,7 @@ 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 @@ -185,6 +187,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 @@ -311,12 +315,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**. @@ -372,6 +378,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: @@ -471,10 +487,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): @@ -785,10 +801,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. @@ -948,7 +967,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.""" @@ -966,7 +985,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" ) @@ -1679,6 +1698,9 @@ 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.""" self._logged_lidar_names: list[str] = [] # ------------------------------------------------------------------ @@ -1810,6 +1832,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 @@ -1996,29 +2029,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) @@ -2050,15 +2119,28 @@ 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 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() + 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.""" index = self.rtx_view_index 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 30d539292409..d623fde7a91a 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]. diff --git a/source/isaaclab_visualizers/test/test_newton_adapter.py b/source/isaaclab_visualizers/test/test_newton_adapter.py index c7dc28cf1e83..369e9e2d095d 100644 --- a/source/isaaclab_visualizers/test/test_newton_adapter.py +++ b/source/isaaclab_visualizers/test/test_newton_adapter.py @@ -742,6 +742,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 @@ -1454,6 +1455,22 @@ 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), + reference_env_ids=lambda: np.array([0, 0, 0]), + ) + visualizer._checkpoint_ghost_panel = SimpleNamespace(controller=controller) + 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] # a ghost keeps its reference's spacing + 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 @@ -1522,3 +1539,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..30f6e8e3bb74 --- /dev/null +++ b/source/isaaclab_visualizers/test/test_newton_checkpoint_ghosts.py @@ -0,0 +1,445 @@ +# 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 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 + + +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=["##/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() + 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() + + +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