Repository navigation
Add Checkpoint Ghosts to debug and visualize policy checkpoints in the Newton visualizer - #9096
matthewtrepte wants to merge 28 commits into
Conversation
[Medium impact] The PR appears safe to merge; no new blocking issue remains. SummaryAdds Checkpoint Ghosts to compare policy checkpoints in the Newton viewer.
Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
Browser[Checkpoint browser] --> Session[Ghost session]
Session --> Policies[One policy per loaded slot]
Policies --> Actions[Combined actions]
Actions --> Env[Shared environment]
Env --> Sync[Mirror reference resets and commands]
Sync --> Session
Session --> Viewer[Newton OpenGL overlays]
Reviews (21) · Last reviewed commit: "Accept list-form continuous action space..." · Reviewed by Greptile |
| for name in manager.active_terms: | ||
| for key, value in vars(manager.get_term(name)).items(): | ||
| if isinstance(value, torch.Tensor) and value.ndim >= 1 and value.shape[0] == self._env.num_envs: | ||
| value[ghosts] = value[source] |
There was a problem hiding this comment.
Ghosts chase the wrong target. For navigation checkpoints using
UniformPose2dCommand, this copies pos_command_b and heading_command_b after each ghost has calculated them from its own pose. Once the robots drift apart, the ghost receives the reference’s distance and direction to the target, not its own. Navigation rewards also read these copied values, so the comparison becomes misleading. Copy the sampled targets and timing, then recompute each ghost’s relative commands from its own state.
There was a problem hiding this comment.
Fixed. The relative targets (pos_command_b, heading_command_b) are recomputed from each ghost's own pose after the copy, with a test for it.
| for slot in self.layout.slots: | ||
| policy = self._policies[slot.index] | ||
| if policy is not None: | ||
| policy.reset(dones[slot.index * size : (slot.index + 1) * size]) |
There was a problem hiding this comment.
Ghost memory survives episode resets. When a reference environment terminates but its ghost does not,
PolicyGhostSync resets both robots. The returned dones still marks only the reference, so this call leaves the ghost’s recurrent memory unchanged. Recurrent checkpoints such as AnymalDFlatPPORunnerRecurrentCfg then start a fresh episode with memory from the previous one. Include reference-triggered resets in each ghost policy’s reset mask.
There was a problem hiding this comment.
Fixed. A ghost policy resets with the reference's reset mask, so recurrent memory clears when the reference resets. Tests cover a ghost falling alone and the reference resetting.
| types = [ | ||
| getattr(getattr(cfg, "backend", None), "visualizer_type", None) or getattr(cfg, "visualizer_type", None) | ||
| for cfg in visualizers | ||
| ] | ||
| if "newton" not in types: | ||
| raise SystemExit("--policy_ghosts requires the Newton GL visualizer; pass --visualizer newton_gl.") |
There was a problem hiding this comment.
Multiple viewers block ghost playback. With
--viz newton,viser --policy_ghosts, configuration selection puts both backends in cfg.backend as a list. This check reads visualizer_type from the list itself, misses the Newton viewer, and exits before launch. Flatten backend lists when checking for newton, as well as accepting a single backend.
There was a problem hiding this comment.
Fixed. The backend list is flattened, so --viz newton,viser is accepted. Test added.
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Design and architecture (1), Scope and over-engineering (7), Compatibility and deprecation (9), Implementation (6), Style consistency (4), Test quality (5). Other reviewed categories look good.
- PR description: Retarget the stacked 222-file diff; state RSL-RL/manager-based limits and validation commands; substantiate the changelog’s 10–20% slowdown with baseline/candidate revisions, workload, hardware, backend, environment/slot counts, warmup, and throughput, or remove it.
- Design and architecture: Viewer appearance controls rewrite shared scene lights, changing every OVRTX camera; keep viewer lighting isolated from sensor rendering.
- Scope and over-engineering: Minimal implementation: extend play_rsl_rl and NewtonGLVisualizer; keep policy_ghost_sync.py, policy_ghost.py, policy_ghosts.py, and newton_policy_ghosts.py for hooks, contract, session, and HUD; merge policy_ghost_metrics.py into the session and batch transfers; fuse OVRTX transform passes. Keep camera_follower.py, newton_recording.py, newton_rtx_appearance.py, and newton_overlay_meshes.py only in independent lifecycle work. Suggested PR breakdown: (1) Newton compatibility, validated through old contracts; (2) tracking, validated through poses; (3) recording/appearance/overlays, validated through resource lifetimes; (4) ghosts, validated through synchronization and rendering isolation.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: RTX exports, preset constructors, dual-window selection, recording/preset rendering, AppLauncher fallback, channel discovery, and window sizing lack functional transition bridges; preserve old behavior with targeted warnings, migration guidance, and transition coverage.
- Implementation: Environment visibility and ghost offsets modify transforms shared by every OVRTX camera, changing sensor images; restrict these presentation adjustments to the viewer product.
- Style consistency: Ghost changelog fragments contradict the implemented slot-option and RTX behavior; describe both slot defaults and limit the OpenGL-only qualification to tint and opacity.
- Test quality: Added recomposition, pool-size, and camera-label cases repeat stronger coverage, while restart fixtures and the stats probe assert private state; consolidate duplicates and exercise observable session and HUD behavior.
Needs rework. Posted 32 inline findings.
The full PR diff was reviewed; some supplemental surrounding file context was omitted.
Automated review; human maintainers own approval decisions.
| # update the caller's namespace in place, as scripts read resolved values such as ``headless`` from it | ||
| args = vars(launcher_args) if isinstance(launcher_args, argparse.Namespace) else dict(launcher_args or {}) | ||
| args.update(kwargs, require_kit=True) | ||
| # Kit cannot share the process with the OVRTX visualizer; drop it as Kit did when it failed to load it |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Keep AppLauncher’s Kit fallback
AppLauncher previously skipped newton_rtx when starting Kit; removing that guard makes the deprecated alias request incompatible RTX and fail launch. Preserve the fallback with migration guidance.
There was a problem hiding this comment.
Not part of this PR anymore. It is now a single commit on main that doesn't touch this file.
| warn_deprecated_visualizer(name, stacklevel=3) | ||
| alias_options = {} | ||
| for name in selection: | ||
| alias_options.update(VISUALIZER_ALIAS_OPTIONS.get(name, {})) |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Preserve two Newton selections
Deduplicating newton_gl,newton_rtx collapses two selected windows into one. Keep both viewer selections functional throughout the deprecation transition.
There was a problem hiding this comment.
Not part of this PR anymore. It is now a single commit on main that doesn't touch this file.
| if term is not None and getattr(term, "mode", None) in ("startup", "interval"): | ||
| setattr(events, name, None) | ||
| removed.append(f"events.{name}") | ||
| for name, term in vars(curriculum).items() if curriculum is not None else (): |
There was a problem hiding this comment.
🔴 Critical · Implementation — Keep required curriculum state
Franka Pour’s reset event uses a row selected by its curriculum term. Disabling every curriculum term removes that selection; preserve dependent terms or reject the task before launch.
There was a problem hiding this comment.
Fixed. Tasks whose curriculum term selects the reset state (Franka Pour, UR10 single push) are now rejected at launch with a clear message, via a supports_checkpoint_ghosts = False marker on those terms. Other curriculum terms are still disabled, as documented.
| data.warp_buffers[str(RenderBufferKind.RGBA)], | ||
| ) | ||
|
|
||
| def set_environment_visibility(self, visible: Sequence[bool]) -> None: |
There was a problem hiding this comment.
🔴 Critical · Implementation — Isolate viewer transforms from sensors
Viewer visibility and ghost offsets alter transforms in the OVRTX scene shared by camera products. Scene-sensor images can hide or move bodies; apply these adjustments only to the viewer product.
There was a problem hiding this comment.
The ghost offsets in the OVRTX renderer were removed from this PR, so ghosts no longer change the shared scene. The viewer visibility part was in #9051, which has already merged.
| self._obs, rewards, dones, _ = self._env.step(actions) | ||
| self._metrics.update(rewards, dones) | ||
| for slot in self.layout.slots: | ||
| policy = self._policies[slot.index] |
There was a problem hiding this comment.
🔴 Critical · Implementation — Reset counterpart recurrent states
Reference termination resets ghost counterparts, but their dones may remain false. Include the reference reset mask in each ghost policy’s recurrent-state reset.
There was a problem hiding this comment.
Fixed. Same as the Greptile thread: ghost policies reset with the reference's mask.
| return shutil.which("ffmpeg") | ||
|
|
||
|
|
||
| class NewtonRecordingPanel: |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Separate the recording lifecycle
Checkpoint comparison needs no second encoder, temporary-video lifecycle, or screenshot controls. Move this module, its configuration, documentation, and tests to a recording change.
| return lights | ||
|
|
||
|
|
||
| class RtxAppearance: |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Separate unrelated RTX controls
Ghost placement needs neither editable lights and sky downloads nor newton_overlay_meshes.py’s drag-arrow publishing. Move both modules and their resource tests to independent presentation work.
| self._write(paths, "visibility", states, semantic=Semantic.TOKEN_STRING) | ||
| and self._write(paths, "inputs:intensity", np.array(intensities, np.float32)) | ||
| and self._write(paths, "inputs:color", np.array(colors, np.float32)) | ||
| ) |
There was a problem hiding this comment.
🟡 Warning · Design Architecture — Keep viewer lighting viewer-local
Appearance controls rewrite scene lights used by every OVRTX camera, and close removes only added lights. Isolate viewer lighting instead of changing the shared scene.
| def test_the_rtx_view_keeps_following_the_tracking_camera_and_returns_to_it(): | ||
| from isaaclab.visualizers import PerspectiveCameraCfg | ||
|
|
||
| def view(source, camera=None): |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Test the visible stats control
Reading an unconstructed viewer’s private _show_stats flag does not establish what the HUD displays. Assert the rendered control or remove the probe.
There was a problem hiding this comment.
No longer applies. That stats-overlay test was removed with the HUD rework.
| return viz | ||
|
|
||
|
|
||
| def test_a_lone_free_view_is_called_perspective_and_a_task_view_the_tracking_camera(): |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Consolidate camera-label tests
The free/tracking and numbered labels repeat test_newton_tracking_cameras coverage with another viewer fixture. Keep one label owner.
|
run-ci |
|
@greptileai review |
| original, current = list(sys.orig_argv), list(sys.argv) | ||
| if original[len(original) - len(current) + 1 :] == current[1:]: | ||
| return original | ||
| return [sys.executable, "-c", "from isaaclab.cli import cli; cli()", *current[1:]] |
There was a problem hiding this comment.
Restart loses playback arguments.
_parse_args replaces sys.argv with only Hydra overrides before this runs. A normal command using --viz newton leaves visualizer=newton there, which is not a suffix of the original command. This fallback then restarts with the overrides but drops play, --task, and --checkpoint. Choosing Enable or Disable Rollout Ghosts with a restart closes playback and launches an invalid command instead. Save the complete launch arguments before parsing and use that saved list here.
There was a problem hiding this comment.
This no longer applies. The HUD restart and relaunch code is gone: Checkpoint Ghosts are turned on only with --checkpoint_ghosts at launch.
| renderer = self._sim.get_or_create_backend(self._image_views[index].camera.cfg.renderer_cfg) | ||
| renderer.set_environment_offsets(offsets) |
There was a problem hiding this comment.
Ghosts change policy camera images. This shifts bodies in the shared OVRTX renderer, even while the window shows OpenGL. For a flat-grid camera task such as
Isaac-Cartpole-Camera using renderer=ovrtx, the task cameras and viewer use equal default renderer settings and share that renderer. Ghost bodies move onto the reference, but the task cameras stay at their original positions. Ghost policies then receive images of the wrong scene rather than their own rollout. Keep the overlay shifts out of the renderer used for policy observations, or reject this combination until it is isolated.
There was a problem hiding this comment.
This no longer applies. I removed the OVRTX ghost overlay, so ghosts never move bodies in the shared renderer. The controls are disabled in the RTX view, and tasks whose cameras use OVRTX are rejected at launch.
|
run-ci |
|
run-ci |
|
@greptileai review |
| name = Path(path).name.replace("model", "model_vecnormalize", 1).replace(".zip", ".pkl") | ||
| stats = Path(path).with_name(name) | ||
| norm = VecNormalize.load(stats, env) if stats.exists() else None # each checkpoint has its own | ||
|
|
||
| def act(obs): | ||
| obs = env._process_obs(obs) | ||
| actions, _ = model.predict(norm.normalize_obs(obs) if norm else obs, deterministic=True) |
There was a problem hiding this comment.
When a checkpoint has no matching statistics file, this factory sets norm to None and passes raw observations to model.predict. Franka lift trains with normalize_input: True, but periodic checkpoints have no matching statistics file. Unlike plain playback, this path also drops the configured normalization fallback. An earlier checkpoint can therefore look broken because its observations are scaled differently, not because its policy is worse.
Save and load statistics for each checkpoint, or reject normalized checkpoints whose statistics are missing.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| 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) |
There was a problem hiding this comment.
Discrete actions get wrong dimensions
action_space.shape[-1] is not the action count for every newly accepted direct environment. IsaacContrib-Cartpole-Showcase-Direct with presets=box_discrete uses Discrete(3). Its batched action space describes the environments, so this allocates num_envs columns per action row instead of one. The task then receives the wrong action shape and cannot apply it to its single cart joint.
Build the buffer from single_action_space, or reject unsupported spaces before launch.
…alizer config Only --checkpoint_ghosts stays on the command line. checkpoint_ghost_slots and checkpoint_ghost_root are Newton backend options.
…ion statistics Ghosts only handle continuous direct action spaces, since the action buffer is sized from the Box shape. An SB3 checkpoint of a task that normalizes observations now fails to load when its statistics file is missing, instead of playing unnormalized.
…ay scripts Each play script now makes one call into checkpoint_ghost_policies instead of carrying its own factory.
…ig and expand ~ in the folder
|
run-ci |
|
@greptileai review |
| if isinstance(env_cfg, DirectRLEnvCfg) and not isinstance(env_cfg.action_space, (int, gym.spaces.Box)): | ||
| raise SystemExit("--checkpoint_ghosts only supports direct environments with continuous (Box) actions.") |
There was a problem hiding this comment.
Continuous action lists block playback
check() rejects a direct environment with action_space = [1], even though spec_to_gym_space() converts that documented form to the same continuous Box as action_space = 1. The new check stops otherwise supported ghost playback before launch. Convert the specification with spec_to_gym_space() before checking the resulting space.
Convert the declared action space with spec_to_gym_space before checking it, so [N] and N both pass, and require a flat Box.
|
run-ci |
|
@greptileai review |
maxkra15
left a comment
There was a problem hiding this comment.
A few things still need fixing before merge: matching the spawned assets between slots, checkpoint device mapping, overlay spacing, and a timezone-dependent test. Details inline.
| 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() |
There was a problem hiding this comment.
Can we check that each reference/ghost pair uses the same asset prototypes here? Isaac-Lift-KukaAllegro defaults to heterogeneous objects: with 6 envs and one ghost, env 0 grasps a cuboid while its ghost env 3 grasps a capsule. Copying scene state doesn't change collision geometry or inertia, so even identical checkpoints are being compared on different objects. Please reject unmatched compositions for now, or pair worlds with matching prototypes.
There was a problem hiding this comment.
Good catch. Checkpoint Ghosts now rejects a scene whose assets use a multi-asset spawner (MultiAssetSpawnerCfg / MultiUsdFileCfg) with a clear error, so Kuka Allegro with mixed objects wont launch in ghost mode for now. Pairing worlds by prototype can come later. Fixed in 0a2664d, test added.
|
|
||
| def policy_factory(path: str) -> PolicyAdapter: | ||
| runner = create_rsl_rl_runner(env, agent_cfg, inference=True) | ||
| runner.load(path) |
There was a problem hiding this comment.
Can we keep map_location=agent_cfg.device here, like the regular play path? A checkpoint saved on another CUDA device fails to load in ghost mode when that device is absent, before get_inference_policy() can move the model. The same checkpoint works in plain play with the selected local device.
There was a problem hiding this comment.
Done, the RSL-RL ghost loader passes map_location=agent_cfg.device now like the regular play path. rl_games, skrl and SB3 already pass a device. Fixed in 0a2664d.
| viewer.world_offsets = wp.array( | ||
| self._base_world_offsets + ghost, dtype=wp.vec3, device=viewer.world_offsets.device | ||
| ) |
There was a problem hiding this comment.
This keeps each ghost's own world_spacing offset, so it no longer overlays its reference when that option is nonzero. With four envs, two checkpoints and world_spacing=(2, 0, 0), identical poses end up 4 m apart. Could we reuse the matching reference world's base offset for each ghost before applying the origin shift? That would keep the reference envs spaced while each comparison stays overlaid.
There was a problem hiding this comment.
Done. Each ghost takes its reference world base offset (the world_spacing one) first and then the origin shift, so it overlays its reference with a nonzero spacing. The offsets test uses different spacing per world now. Fixed in 0a2664d.
| panel = NewtonCheckpointGhostPanel(controller) | ||
| panel._open_window() | ||
|
|
||
| panel._draw_window(_BrowserImgui(clicks=["model_1.pt 1970-01-01 00:00##/runs/task/model_1.pt"])) |
There was a problem hiding this comment.
This assumes the machine runs in UTC, but the browser formats this timestamp with time.localtime(). With TZ=Europe/Zurich the row says 01:00, the fake click never matches, and this test fails. I get 16 passing in UTC and 1 failing / 15 passing in Zurich. Can we match the checkpoint's stable ID here, or control the timezone in the fixture?
There was a problem hiding this comment.
Fixed, the fake click matches the checkpoint stable ##path id now so the local time in the label doesnt matter. Fixed in 0a2664d.
…ent prototypes, and load RSL-RL checkpoints on the play device
|
run-ci |
# Conflicts: # source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py
# Conflicts: # source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rsl_rl.py
|
run-ci |
kellyguo11
left a comment
There was a problem hiding this comment.
Nice feature! I think we can try designing this to be more generic so that the ghost visualization function can be used across different workflows, in addition to just checkpoint visualization. The checkpoints can then be one additional layer on top of that, which makes it one way of accessing the ghost visualizations rather than coupling them together.
| """Terrain placement tensors of every environment that the ghosts copy from the reference.""" | ||
|
|
||
|
|
||
| class CheckpointGhostSync: |
There was a problem hiding this comment.
I can see other workflows like visualizing reference motions or goal poses also benefiting from ghost visualizations. perhaps we can design ghost visualizations as a feature, then the checkpoints can wrap around that implementation to provide configurations for checkpoint visualization, but we can also reuse the ghost logic for other workflows.
| 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 |
There was a problem hiding this comment.
would this interfere with action buffers required in the task?
| to the full reset distribution from the first rollout. | ||
| """ | ||
|
|
||
| supports_checkpoint_ghosts = False |
There was a problem hiding this comment.
this seems like an odd configuration. is the behavior always enabled by default? might be more intuitive if a task needs to explicitly enable the feature?
| 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 |
There was a problem hiding this comment.
what is the challenge in allowing direct environments?
| @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))) |
There was a problem hiding this comment.
how does this work when the number of ghosts are modified? if I choose to visualize 4 vs. 8 ghosts without changing num_envs, do I end up seeing different number of environments than what num_envs was specified to be?
| from isaaclab.visualizers.checkpoint_ghost_play import PolicyAdapter, run | ||
|
|
||
|
|
||
| def run_rsl_rl( |
There was a problem hiding this comment.
I'm not sure I like the idea of having a separate run function here for each RL library. is there any way we can incorporate this within the existing play scripts?
| """Name of the manifest that training writes into a run directory (``isaaclab_rl.entrypoints.common``).""" | ||
|
|
||
|
|
||
| def add_args(parser: argparse.ArgumentParser) -> None: |
There was a problem hiding this comment.
this is dealing with entrypoint arguments, not sure that it belongs under visualizers?
# Conflicts: # source/isaaclab_visualizers/isaaclab_visualizers/newton/newton_visualizer.py
Description
Adds Checkpoint Ghosts to the Newton visualizer: overlay rollouts of several checkpoints of one task in the same window. A ghost resets with the reference, and a ghost that finishes first waits for it.
play ... --checkpoint_ghostssplits--num_envsamong the checkpoints shown. The reference starts with all of them, and adding a ghost resizes every slot. The Newton visualizer optionscheckpoint_ghost_slotsandcheckpoint_ghost_rootcap the checkpoints shown and set where the browser starts.playshows a greyed-out Checkpoint Ghosts section that explains the flag, so the feature is visible without costing anything.isaaclab,isaaclab_rlandisaaclab_visualizers.Screenshots
Demo clip: Kuka Allegro lift with the official checkpoint as the reference and two ghosts (
model_0,model_19).checkpoint_ghosts_kuka_allegro_demo.mp4
Validation
isaaclab_rllaunch test), visualizer 80. Ruff check and format are clean.Possible follow-ups
Type of change
Checklist
CONTRIBUTORS.md.