Repository navigation
Add native RSL-RL SAC support - #8866
Conversation
Signed-off-by: Rafael Cathomen <[email protected]>
…plumbing Signed-off-by: Rafael Cathomen <[email protected]>
Signed-off-by: Rafael Cathomen <[email protected]>
Signed-off-by: Rafael Cathomen <[email protected]>
d769ad0 to
e3f41ec
Compare
Signed-off-by: Rafael Cathomen <[email protected]>
Signed-off-by: Rafael Cathomen <[email protected]>
|
Could you update the typed configs and G1 preset to match the current RSL-RL constructors? Pairing these PR heads currently fails first on |
|
This resume call still passes |
Follows the parameter names and defaults of leggedrobotics/rsl_rl#254 after review: replay_buffer_capacity, num_return_steps, num_warmup_transitions, critic_loss_type, exploration_type, max_noise_repeat_steps, num_schedule_updates, batch_norm_momentum and std_range. The algorithm config defaults now mirror the native SAC defaults, which are the best single configuration across the Isaac Lab benchmark tasks. The G1 preset keeps its tuned values. Continued training without optimizer state now selects checkpoint contents through the algorithm's default load configuration, since the runner no longer accepts load_optimizer.
RSL-RL now accepts network_cfg before distribution_cfg, so positional distribution configurations were passed as the network configuration.
The G1 velocity task now provides its policy observations as the proprio group, which the G1 PPO configuration already uses.
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (3), Compatibility and deprecation (4), Implementation (1), Style consistency (1). Other reviewed categories look good.
- PR description: Add CPU-capture, custom-model, and checkpoint-contract changes, name validation commands, and supply wrapper-step baseline/candidate measurements with revisions, workload, hardware, backend, environment count, warmup, latency, and memory; preserve template sections.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: keep _rsl_rl.py for shared dispatch, sac_cfg.py for public schemas, and the G1 preset module for task configuration; extend existing entrypoints and vecenv_wrapper.py, inline trivial helpers, condition extras copying, and remove repeated defaults. Essential flow remains configuration, environment creation, runner construction, and execution. Suggested PR breakdown: first wrapper semantics with mixed-ending coverage; then SAC schemas, registration, and dispatch with constructor validation; finally export and benchmark integration with checkpoint and replay validation.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: checkpoint_load_cfg disappears, non-MLP policies lose export support, final_obs changes type, and distillation selection follows config ancestry; preserve old contracts through targeted warnings, migration and removal guidance, and transition coverage.
- Implementation: Exact OffPolicyRunner string guards miss qualified runner names accepted by the factory, allowing published PPO checkpoints into SAC loading; check resolved runner identity in playback and export.
- Style consistency: The new factory replaces functional to_dict serialization with the legacy method form; retain to_dict(agent_cfg) to follow contribution guidance and existing callers.
- Test quality: Test quality looks good.
Significant concerns. Posted 9 inline findings.
Automated review; human maintainers own approval decisions.
| if args_cli.checkpoint: | ||
| return retrieve_file_path(args_cli.checkpoint) | ||
| if agent_cfg.class_name == "DistillationRunner": | ||
| if isinstance(agent_cfg, RslRlDistillationRunnerCfg): |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Recognize configured distillation runners
A custom config selecting DistillationRunner without this subclass no longer requires a checkpoint; benchmark resume and export student selection also change. Classify the selected runner consistently in all three paths.
| from ...rsl_rl import RslRlBaseRunnerCfg | ||
|
|
||
|
|
||
| def _configure_rsl_rl_env_cfg(env_cfg: Any, agent_cfg: RslRlBaseRunnerCfg) -> None: |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Inline the trivial runner helpers
_configure_rsl_rl_env_cfg only assigns one field, and _rsl_rl_load_cfg has one production caller. Inline those conditions at their owners; keep this module for shared runner construction.
| """Construct the configured runner using native RSL-RL callable resolution.""" | ||
| from rsl_rl.utils import resolve_callable | ||
|
|
||
| cfg = agent_cfg.to_dict() |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Use functional config serialization
The new factory replaces callers' to_dict(agent_cfg) with the legacy method form. Use the contribution guide's preferred to_dict(agent_cfg) operation here.
| from ...rsl_rl import RslRlBaseRunnerCfg | ||
|
|
||
|
|
||
| def checkpoint_load_cfg( |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Retain the checkpoint selection API
Removing checkpoint_load_cfg breaks existing imports and calls. Retain its signature and behavior with a targeted deprecation warning, migration guidance, and coverage for old and new paths.
| runner.load(resume_path, map_location=agent_cfg.device) | ||
| # Capture portable operators instead of device-specific fused inference kernels. | ||
| policy = runner.get_inference_policy(device="cpu") | ||
| if not isinstance(policy, MLPModel): |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Keep custom policies exportable
Export previously passed callable inference policies to capture; this check rejects every non-MLPModel policy first. Preserve the existing custom-policy path through a warned, documented transition before restricting it.
| if args_cli.checkpoint and is_wandb_checkpoint(args_cli.checkpoint): | ||
| return resolve_wandb_checkpoint(args_cli.checkpoint) | ||
| if args_cli.checkpoint == "pretrained": | ||
| if agent_cfg.class_name == "OffPolicyRunner": |
There was a problem hiding this comment.
🟡 Warning · Implementation — Guard qualified off-policy runners
The factory accepts qualified runner names, but this guard and export's equivalent recognize only OffPolicyRunner. Qualified SAC configurations can reach loading with a published PPO checkpoint; check resolved runner identity.
| actions = torch.clamp(actions, -self.clip_actions, self.clip_actions) | ||
| # record step information | ||
| obs_dict, rew, terminated, truncated, extras = self.env.step(actions) | ||
| extras = dict(extras) |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Avoid copying every step
dict(extras) allocates on every RSL-RL step, including PPO steps without final_obs. Copy only when replacing an extras value; otherwise retain the existing mapping.
| obs_dict, rew, terminated, truncated, extras = self.env.step(actions) | ||
| extras = dict(extras) | ||
| if "final_obs" in extras: | ||
| extras["final_obs"] = TensorDict(extras["final_obs"], batch_size=[self.num_envs]) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve final observation type
step() previously forwarded final_obs as the environment's mapping; it now replaces it with TensorDict. Keep the old return type functional while making SAC's conversion opt-in through a documented deprecation transition.
| obs_normalization=False, | ||
| network_cfg=RslRlResidualMLPCfg(hidden_dim=256, num_blocks=2, expansion=4, batch_norm_momentum=0.01), | ||
| ) | ||
| algorithm = RslRlSacAlgorithmCfg( |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Remove repeated SAC defaults
This preset repeats many RslRlSacAlgorithmCfg defaults and unchanged network defaults, creating duplicate values to maintain. Declare only G1-specific overrides.
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (2), Compatibility and deprecation (4), Implementation (1), Style consistency (2), Test quality (1). Other reviewed categories look good.
- PR description: The title, approximate additions, package scope, and dependency caveat match the diff; replace the learning-curves-on-request prose with concrete validation commands and results, preserving the template sections.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: keep _rsl_rl.py for shared construction, sac_cfg.py for the typed contract, and the G1 preset module for task configuration; inline environment setup into training callers, inline load selection into train_rsl_rl.py, and remove repeated preset defaults. Extend vecenv_wrapper.py and existing export owners. Suggested PR breakdown: timeout correction with wrapper validation; SAC configuration and runner integration with construction/checkpoint validation; export integration with capture/replay validation.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: checkpoint_load_cfg disappears, class_name-selected distillation loses routing, custom export policies are rejected, and step extras change ownership and final_obs type; preserve these contracts through complete deprecation bridges.
- Implementation: Published-checkpoint guards recognize only the bare OffPolicyRunner name, so qualified configurations bypass rejection; check resolved runner identity consistently in playback, export, and benchmarks.
- Style consistency: The added termination predicate lacks required input and return annotations; annotate the environment argument and tensor result.
- Test quality: The SAC unknown-field assertion repeats inherited configclass validation rather than testing SAC behavior; remove it while retaining native schema/default checks and distinct checkpoint, export, and timeout cases.
Significant concerns. Posted 10 inline findings.
Automated review; human maintainers own approval decisions.
| policy = runner.get_inference_policy(device="cpu") | ||
| if not isinstance(policy, MLPModel): | ||
| raise TypeError("LEAPP export requires an MLPModel policy, including its CNN and RNN variants.") | ||
| obs_set = "student" if isinstance(agent_cfg, RslRlDistillationRunnerCfg) else "actor" |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Preserve distillation runner routing
A config selecting DistillationRunner without inheriting RslRlDistillationRunnerCfg now exports actor instead of student observations; training and benchmark checkpoint checks likewise change. Classify the selected runner consistently.
| from ...rsl_rl import RslRlBaseRunnerCfg | ||
|
|
||
|
|
||
| def _configure_rsl_rl_env_cfg(env_cfg: Any, agent_cfg: RslRlBaseRunnerCfg) -> None: |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Inline trivial runner setup
Environment setup is one conditional assignment at two callers, and load selection has one caller. These helpers add import and navigation cost; inline them at their boundaries and retain the shared constructor.
| from ...rsl_rl import RslRlBaseRunnerCfg | ||
|
|
||
|
|
||
| def checkpoint_load_cfg( |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Retain checkpoint_load_cfg
Removing this public helper breaks existing imports and its runner_class call signature. Keep its behavior through a deprecation cycle with a targeted warning, migration guidance, and old/new-path tests.
| runner.load(resume_path, map_location=agent_cfg.device) | ||
| # Capture portable operators instead of device-specific fused inference kernels. | ||
| policy = runner.get_inference_policy(device="cpu") | ||
| if not isinstance(policy, MLPModel): |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Keep custom policies exportable
The new MLPModel gate rejects custom inference policies that previously reached capture, although capture calls the policy rather than requiring that base class. Remove the nominal gate and its Identity-only test.
| if args_cli.checkpoint and is_wandb_checkpoint(args_cli.checkpoint): | ||
| return resolve_wandb_checkpoint(args_cli.checkpoint) | ||
| if args_cli.checkpoint == "pretrained": | ||
| if agent_cfg.class_name == "OffPolicyRunner": |
There was a problem hiding this comment.
🟡 Warning · Implementation — Recognize qualified off-policy runners
The factory accepts qualified runner names, but this guard and export's guard match only OffPolicyRunner. Qualified SAC configurations reach published PPO checkpoint loading; check the resolved runner identity in both paths and benchmarks.
| actions = torch.clamp(actions, -self.clip_actions, self.clip_actions) | ||
| # record step information | ||
| obs_dict, rew, terminated, truncated, extras = self.env.step(actions) | ||
| extras = dict(extras) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve step extras ownership
step() previously updated and returned the environment's extras mapping; it now copies it and changes final_obs from a dictionary to TensorDict. Preserve the legacy result while providing SAC's representation separately.
| for name, parameter in parameters.items(): | ||
| if name not in injected and not isinstance(getattr(cfg, name), type(MISSING)): | ||
| assert getattr(cfg, name) == parameter.default, name | ||
| with pytest.raises(KeyError, match="unknown_option"): |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Remove generic configclass assertion
Rejecting unknown_option tests inherited configclass behavior, not a SAC contract. Delete this assertion; retain the native SAC field and default checks.
| if request.node.callspec.params.get("library") == "rsl_rl" and task == "Isaac-Cartpole" and not finite_horizon: | ||
| from isaaclab.managers import TerminationTermCfg | ||
|
|
||
| def simultaneous_failure(env): |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Annotate the termination predicate
The new function omits argument and return annotations required by the contribution guide. Annotate its environment input and tensor result.
| if library == "rsl_rl": | ||
| _assert_observation_buffer(env) | ||
| if compute_final_obs and bool(dones.any()): | ||
| from tensordict import TensorDict |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Remove duplicate TensorDict import
TensorDict is already imported at module scope. Delete this branch-local import and use the existing binding.
| obs_normalization=False, | ||
| network_cfg=RslRlResidualMLPCfg(hidden_dim=256, num_blocks=2, expansion=4, batch_norm_momentum=0.01), | ||
| ) | ||
| algorithm = RslRlSacAlgorithmCfg( |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Remove repeated SAC defaults
The G1 algorithm declaration repeats base defaults for critic count, replay capacity, batch size and other fields. Delete unchanged values so the preset states only its actual overrides.
|
Updated the PPO checkpoint fixture to provide the actor distribution required by current upstream RSL-RL. All eight focused runner, model configuration, and checkpoint checks now pass, along with the full formatting/lint and changelog checks. Workstation validation against upstream RSL-RL commit
We are still waiting for a published |
Make the shared runner helpers public under runner_rsl_rl, since core benchmarks import them. Serialize with to_dict(agent_cfg), reject published checkpoints by SAC config type, and derive the cosine schedule length from max_iterations so CLI overrides keep it aligned. Restore the distillation caveat for --no-resume_optimizer_state and tidy the wrapper and SAC config tests.
Use the immutable upstream revision already validated by the SAC integration while a containing release is pending. Align both dependency declarations and regenerate the lockfile so native SAC construction and optimizer-reset checkpoint loading use the APIs they require. Keep the published-release requirement explicit before merge.
Resolve the dependency lock conflict by retaining current main dependencies and the validated immutable RSL-RL source pin. Revalidate all 59 entrypoint tests and the full formatting, lint, and changelog checks.
|
run-ci |
| from ...rsl_rl import RslRlBaseRunnerCfg | ||
|
|
||
|
|
||
| def configure_rsl_rl_env_cfg(env_cfg: Any, agent_cfg: RslRlBaseRunnerCfg) -> None: |
There was a problem hiding this comment.
I think it might be better to inline this rather than wrapped under configure_rsl_rl_env_cfg
There was a problem hiding this comment.
I'd encourage to inline this file, the logic here is not that complex and are all the details worth to be reading
ooctipus
left a comment
There was a problem hiding this comment.
Approved with some minor comment
Applies the diff of isaac-sim#8866: typed SAC configurations, one RSL-RL runner factory, time-outs that exclude true terminations, and the FlashSAC preset for flat G1 velocity. RSL-RL is pinned to the main commit that the PR validated.
The pinned RSL-RL logger writes Performance/* and Training/* instead of Perf/* and Train/*, so the benchmark parsed no iterations.
|
run-ci |
G1 symmetry augmentation (`isaaclab_tasks.core.velocity.mdp.symmetry.g1:compute_symmetric_states`) fails on `Isaac-Velocity-Flat-G1` and `Isaac-Velocity-Rough-G1`, for PPO and SAC alike. This PR fixes it and gives the tasks from the PPO vs FlashSAC benchmark a tuned SAC agent next to their PPO agent. Two joints of the velocity-task G1 have symmetric limits and names without a roll, yaw or pitch token, so the mirror map cannot resolve their signs and raises: the waist yaw `torso_joint` and the Dex3 thumb rotation `*_zero_joint`. `torso_joint` is a yaw and flips under a sagittal mirror. I checked the full map with forward kinematics: one robot in a random pose, a second in the mirrored pose, and every body of the second compared with the reflection of its counterpart. Over 20 poses, all bodies outside the hands match within 3.3 mm, and flipping the waist or a hip sign moves bodies by 0.6 to 1.1 m, so the check is sensitive. The thumb links stay several centimetres off for every combination of finger signs, because the left and right Dex3 hands are not mirror images of each other. Finger mirroring is therefore approximate on this robot; `zero_joint` keeps the existing thumb convention (`hand_thumb_0_joint`, +1). The vector mirror factors were also rebuilt from Python tuples on every call. That is a host-to-device copy, which fails inside a captured CUDA graph, as used by rsl_rl SAC's updates. The factors are now built once per term, device and size. The benchmark tuned FlashSAC per task under the same rewards as PPO. Those settings now ship as `rsl_rl_sac_cfg_entry_point` agents for `Isaac-Cartpole`, `Isaac-Ant`, `Isaac-Humanoid`, `Isaac-Open-Drawer-Franka`, `Isaac-Reorient-Cube-Allegro`, and the flat and rough ANYmal-D and G1 velocity tasks. Each config matches the benchmarked run field by field, and its `max_iterations` is what that run reached in its time budget. Most tasks use the RSL-RL FlashSAC defaults with a higher discount, more updates per iteration, a cosine learning-rate schedule and a short warm-up; the two rough tasks only raise the learning rates and were tuned with 1024 environments. `Isaac-Reach-Franka` has no SAC agent: SAC reaches the target but much more slowly than PPO, and none of the settings tried closed that gap. The flat G1 SAC agent from #8866 moves to the tuned settings. It also named a `proprio` observation group, which the flat G1 environment does not have; it now reads `policy` like the PPO agent. Without mirrored samples, SAC learns left/right asymmetric gaits on G1, holding one leg in the air or spreading both legs wide, so both G1 SAC agents use the symmetry augmentation. Its settings move into `G1_SYMMETRY_CFG`, shared with the G1 PPO teacher. Per-task curves and videos: https://linkify.nvidia.com/s/rsl-rl-ppo-flashsac-supermimic/ (NVIDIA internal). To try a SAC agent: ``` uv run isaaclab train --rl_library rsl_rl --task Isaac-Velocity-Flat-G1 \ --agent rsl_rl_sac_cfg_entry_point physics=newton_mjwarp visualizer=none ``` 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <[email protected]>
# Description `Isaac-Velocity-Rough-G1-Depth-Student` could not run through the RSL-RL training benchmark: ``` ValueError: No runs present in the directory: '.../logs/rsl_rl/g1_rough_depth_student' match: '.*'. ``` The benchmark resolved a checkpoint for every `DistillationRunner` by searching the *student* experiment's runs, even with `resume=False`, and ignored `--checkpoint`. The training entrypoint already defines the contract: `--checkpoint` (file, run directory, `latest`/`best`, or W&B run) supplies a PPO teacher, and distillation without it is rejected unless `resume` is configured. The benchmark now uses that same resolver. A configured `resume` without `--checkpoint` still searches the experiment's runs. Checkpoints are loaded with `map_location` like the training entrypoint. RSL-RL's native `load` keeps the existing semantics: a PPO checkpoint initializes only the teacher; a distillation checkpoint continues the student. A `--checkpoint` run directory now resolves to its newest `model_*.pt`; previously the directory path was used as the filename pattern and the lookup failed. This fix is in the shared resolver, so the training entrypoint benefits too. The G1 student algorithm (`core/velocity/config/g1/agents/distillation.py`) is also updated for the RSL-RL pin introduced by #8866: `process_env_step` returns the per-step logging values and `update` returns `(loss_dict, stats_dict)`. Without it the student crashes in the runner right after the teacher checkpoint loads on current `main`, so the benchmark could not complete even with the checkpoint fix. ## Validation Benchmark runner (`scripts/benchmarks/training.py`) on an L40, `main` = `3e7e61370`: | case | `main` | this branch | |---|---|---| | student, no `--checkpoint` (`newton_kamino`, `isaacsim_rtx`) | `No runs present in ... g1_rough_depth_student` | `Distillation training requires --checkpoint.` | | student, missing `--checkpoint` file | — | `FileNotFoundError: Unable to find the file: ...` | | student, `--checkpoint` = 2-iteration `Isaac-Velocity-Rough-G1-29DoF` teacher (`newton_mjwarp`, `isaacsim_rtx`) | — | teacher loads, 2 iterations run, benchmark bundle written | The 2-iteration teacher is a functional fixture only, not a qualified teacher. New unit tests in `test_train_checkpoint_path.py` cover the missing teacher, explicit / missing teacher file, and configured resume. ## Notes for reviewers - The matching teacher on `main` is `Isaac-Velocity-Rough-G1-29DoF` (43 actions). An `Isaac-Velocity-Rough-G1` checkpoint (37 actions) is correctly rejected by RSL-RL with a size mismatch. - Separate from this change: on `main` the student's G1 model (with hands) cannot be built with `physics=newton_kamino` (`SolverKamino cannot simulate this model ... left_hand_palm_link: zero inverse mass and singular inverse inertia`). The historical failure never reached scene creation, so this was hidden. ## Type of change - Bug fix (non-breaking change which fixes an issue) ## Checklist - [x] I have read and understood the contribution guidelines - [x] I have run the `pre-commit` checks with `uv run isaaclab --format` (ruff 0.14.10 format/check pass on changed files) - [ ] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there ## Re-validation after merging `main` (rsl-rl-lib at the #8866 pin, L40, `newton_mjwarp`, `newton_renderer`) - Student without `--checkpoint`: `Distillation training requires --checkpoint.` - Student with a 2-iteration `Isaac-Velocity-Rough-G1-29DoF` fixture teacher: teacher loads, 2 iterations run, benchmark bundle and checkpoint written. Before the `distillation.py` change the same run failed with `AttributeError: 'NoneType' object has no attribute 'items'`, then `not enough values to unpack`. - `test_train_checkpoint_path.py` passes; ruff format and check pass on the changed files. --------- Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Description
Adds RSL-RL SAC support:
time_outsexclude true terminations. This also affects PPO bootstrapping.Requires an rsl-rl-lib release with SAC (leggedrobotics/rsl_rl#254) and a dependency pin bump before merging. The generic final-observation fix is a separate PR, #8868; SAC on the G1 preset does not need it.
Size: about 550 lines. About 360 are source, almost all in
isaaclab_rl(configs and factory) plus the G1 preset. In coreisaaclab, only the benchmark scripts change, to use the factory (+9/−25). About 150 lines are tests.Part of #8863
Type of change
Screenshots
G1 velocity learning curves and evaluation can be attached on request.
Checklist
pre-commitchecks withuv run isaaclab --formatsource/<pkg>/changelog.d/for every touched packageCONTRIBUTORS.mdor my name already exists there