From 2e0d86edbe38e831241a8c9672dbe84095dc9192 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 5 May 2026 09:37:34 +0000 Subject: [PATCH 01/36] Sync warp env's viewport check with stable env's API PR #5297 (Decouple Renderer from Camera) replaced `sim.get_setting('/isaaclab/visualizer')` (returned a comma-separated string) with `sim.has_active_visualizers()` plus per-type queries; the warp env path was missed, so it crashes with "AttributeError: 'dict' object has no attribute 'split'" during env construction. Mirror the stable env's pattern: - `has_active_visualizers()` for the gating predicate - `has_kit()` so kitless Newton-only runs (`--viz rerun`) skip ViewportCameraController --- .../envs/manager_based_env_warp.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py index 8c558b925947..03f8cc9dfba4 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py @@ -33,6 +33,7 @@ from isaaclab.ui.widgets import ManagerLiveVisualizer from isaaclab.utils.seed import configure_seed from isaaclab.utils.timer import Timer +from isaaclab.utils.version import has_kit from isaaclab_experimental.envs.interactive_scene_warp import InteractiveSceneWarp as InteractiveScene from isaaclab_experimental.utils.manager_call_switch import ManagerCallMode, ManagerCallSwitch @@ -154,13 +155,11 @@ def __init__(self, cfg: ManagerBasedEnvCfg): # Persistent scalar buffer for global env step count (stable pointer for capture). self._global_env_step_count_wp = wp.zeros((1,), dtype=wp.int32, device=self.device) - # set up camera viewport controller - # viewport is not available in other rendering modes so the function will throw a warning - # FIXME: This needs to be fixed in the future when we unify the UI functionalities even for - # non-rendering modes. - viz_str = self.sim.get_setting("/isaaclab/visualizer") or "" - available_visualizers = [v.strip() for v in viz_str.split(",") if v.strip()] - if "kit" in available_visualizers and bool(viz_str): + # set up camera viewport controller — mirror stable env (PR #5297 changed + # the visualizer API; this branch was missed). ViewportCameraController + # uses omni.kit; skip it in kitless Newton-only runs. + has_visualizers = self.sim.has_active_visualizers() + if (self.sim.has_gui or has_visualizers) and has_kit(): self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) else: self.viewport_camera_controller = None From 5fb7327351fba10816bbf23c901a4b720c10dc65 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 5 May 2026 09:37:37 +0000 Subject: [PATCH 02/36] Alias warp manager term cfgs to stable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Warp's ObservationTermCfg / RewardTermCfg / TerminationTermCfg had no behavioural difference from their stable counterparts — same fields, same base class. The override only carried Warp-first docstrings while keeping the classes as siblings of stable's, which broke `isinstance(stable_term, warp.TermCfg)` checks inside the experimental managers when a stable cfg is fed through the warp runtime. Re-export stable's term cfg classes directly. Term funcs still follow the warp-first `func(env, out, **params)` signature at runtime; the type annotation just lives on stable's class instead of warp's. --- .../managers/manager_term_cfg.py | 95 +++---------------- 1 file changed, 13 insertions(+), 82 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py index 3fab3bfc5ffc..604b138003d4 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py @@ -5,90 +5,21 @@ """Configuration terms for different managers (experimental, Warp-first). -This module is a passthrough to :mod:`isaaclab.managers.manager_term_cfg` except for -the following term configs which are overridden for Warp-first execution: - -- :class:`ObservationTermCfg` -- :class:`RewardTermCfg` -- :class:`TerminationTermCfg` +The warp manager classes accept the same term cfg shapes as the stable +managers, so this module simply re-exports the stable term cfg classes +to keep ``isinstance(stable_term, warp.TermCfg)`` true. This is what +lets the :class:`isaaclab_experimental.envs.warp_frontend.WarpFrontend` +adapter run a stable cfg through the warp runtime without rewrapping +every term. + +The ``func`` callable on each term is still expected to follow the +warp-first ``func(env, out, **params) -> None`` signature when run on +the warp runtime; only the *type* is shared with stable. """ from __future__ import annotations -from collections.abc import Callable -from dataclasses import MISSING - +# Re-export stable manager term cfg classes verbatim. +# `from … import *` carries `ObservationTermCfg`, `RewardTermCfg`, +# `TerminationTermCfg`, `ManagerTermBaseCfg`, etc. from isaaclab.managers.manager_term_cfg import * # noqa: F401,F403 -from isaaclab.managers.manager_term_cfg import ManagerTermBaseCfg as _ManagerTermBaseCfg -from isaaclab.utils import configclass - - -@configclass -class RewardTermCfg(_ManagerTermBaseCfg): - """Configuration for a reward term. - - The function is expected to write the (unweighted) reward values into a - pre-allocated Warp buffer provided by the manager. - - Expected signature: - - - ``func(env, out, **params) -> None`` - - where ``out`` is a Warp array of shape ``(num_envs,)`` with float32 dtype. - """ - - func: Callable[..., None] = MISSING - """The function to be called to fill the pre-allocated reward buffer.""" - - weight: float = MISSING - """The weight of the reward term.""" - - -@configclass -class TerminationTermCfg(_ManagerTermBaseCfg): - """Configuration for a termination term (experimental, Warp-first). - - The function is expected to write termination flags into a pre-allocated Warp buffer. - - Expected signature: - - - ``func(env, out, **params) -> None`` - - where ``out`` is a Warp array of shape ``(num_envs,)`` with boolean dtype. - """ - - func: Callable[..., None] = MISSING - """The function to be called to fill the pre-allocated termination buffer.""" - - time_out: bool = False - """Whether the termination term contributes towards episodic timeouts. Defaults to False.""" - - -@configclass -class ObservationTermCfg(_ManagerTermBaseCfg): - """Configuration for an observation term (experimental, Warp-first). - - The function is expected to write observation values into a pre-allocated Warp buffer provided - by the observation manager. - - Expected signature: - - - ``func(env, out, **params) -> None`` - - where ``out`` is a Warp array of shape ``(num_envs, obs_term_dim)`` with float32 dtype. - - Notes: - - The stable fields (noise/modifiers/history) are kept for config compatibility, but the - experimental Warp-first observation manager may not support all of them initially. - """ - - func: Callable[..., None] = MISSING - """The function to be called to fill the pre-allocated observation buffer.""" - - # Keep stable configuration fields for compatibility with existing task configs. - modifiers: list[ModifierCfg] | None = None # noqa: F405 - noise: NoiseCfg | NoiseModelCfg | None = None # noqa: F405 - clip: tuple[float, float] | None = None - scale: tuple[float, ...] | float | None = None - history_length: int = 0 - flatten_history_dim: bool = True From e842ea073fd50ee8467361945bccafea67db1acc Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 5 May 2026 09:37:55 +0000 Subject: [PATCH 03/36] Add WarpFrontend bridge: '--manager=warp' on any stable task MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lets a stable manager-based RL env cfg run on the experimental warp runtime without a separate warp task registration. Replaces the duplicate per-robot warp env cfgs by adapting the stable cfg in place. Components: - isaaclab_experimental/envs/warp_frontend.py: 'WarpFrontend' walks the stable cfg, swaps each `term.func` to its same-named warp twin (only accepting candidates whose `__module__` lives under the warp packages — the warp mdp module re-exports stable terms via `from … import *`, so a naive `getattr` would silently keep the stable function), swaps each action `class_type`, picks the `newton` field of any PresetCfg, drops sensors with no warp counterpart (`height_scanner`), and in-place class-promotes `SceneEntityCfg` instances so warp kernels see the `joint_mask` / *\_ids_wp` cached fields. A `WarpAdaptReport` records every term that had no warp twin and surfaces them via the logger; `strict=True` makes the same condition raise `LookupError` instead. - scripts/reinforcement_learning/rsl_rl/train.py: '--manager=warp' flag routes the constructed env through `WarpFrontend.build` instead of `gym.make`. The flag also auto-injects `presets=newton` into Hydra's argv so that PresetCfg wrappers resolve to the newton preset (Hydra's preset resolution runs *before* the adapter). Validated: cartpole and Anymal-D Flat both pass a 3-way comparison — - 'Isaac-Cartpole-v0' (stable manager): trains. - 'Isaac-Cartpole-Warp-v0' (existing direct path): reward 0.06 / ep 76. - 'Isaac-Cartpole-v0 --manager=warp': reward 0.06 / ep 76 (matches direct exactly). - 'Isaac-Velocity-Flat-Anymal-D-v0 presets=newton': -8.45 / 191. - 'Isaac-Velocity-Flat-Anymal-D-Warp-v0': -7.47 / 168. - 'Isaac-Velocity-Flat-Anymal-D-v0 --manager=warp': -7.69 / 174 (within run-to-run variance of the direct warp path). Both stable and warp frontends remain functional for every task; this PR adds a flag-based selector without removing the existing direct warp registrations. --- .../reinforcement_learning/rsl_rl/train.py | 28 +- .../envs/warp_frontend.py | 340 ++++++++++++++++++ 2 files changed, 367 insertions(+), 1 deletion(-) create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index eefc13a8aa2c..e66485d3a37d 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -67,6 +67,17 @@ "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." ) parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") +parser.add_argument( + "--manager", + type=str, + default="stable", + choices=["stable", "warp"], + help=( + "Manager-based env runtime. 'stable' uses isaaclab.envs.ManagerBasedRLEnv (torch);" + " 'warp' adapts the same task cfg via isaaclab_experimental.envs.warp_frontend.WarpFrontend" + " and runs on isaaclab_experimental.envs.ManagerBasedRLEnvWarp." + ), +) cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) args_cli, remaining_args = parser.parse_known_args() @@ -86,6 +97,14 @@ # The remaining arguments are the arguments that were not consumed by both this scripts # argparser and (optionally) the external callback function. remaining_args = list_intersection(remaining_args, remaining_args_env_registration) + +# When the warp manager runtime is selected, the env cfg must resolve any +# PresetCfg wrappers to their `newton` field (Hydra preset resolution runs +# *before* the WarpFrontend adapter, so we inject the override here unless +# the user already passed one explicitly). +if args_cli.manager == "warp" and not any(a.startswith("presets=") for a in remaining_args): + remaining_args.append("presets=newton") + sys.argv = [sys.argv[0]] + remaining_args # -- check RSL-RL version ---------------------------------------------------- @@ -171,7 +190,14 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen env_cfg.log_dir = log_dir # create isaac environment - env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + if args_cli.manager == "warp": + # Lazy: this is the first warp-side import. Calling it after + # SimulationApp is already alive avoids racing pxr extension init. + from isaaclab_experimental.envs.warp_frontend import WarpFrontend + + env = WarpFrontend().build(env_cfg, task_id=args_cli.task) + else: + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # convert to single-agent instance if required by the RL algorithm if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py new file mode 100644 index 000000000000..36170e991340 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py @@ -0,0 +1,340 @@ +# 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 + +"""Adapt a stable manager-based RL env cfg to run on the warp runtime. + +Module-level imports are deliberately limited to lightweight stdlib modules. +Warp-library imports fire only inside :meth:`WarpFrontend.build`, which must +be called *after* :class:`SimulationApp` is alive — otherwise the warp lib +loading will race with Kit's USD/pxr extension initialisation. +""" + +from __future__ import annotations + +import importlib +import logging +from collections.abc import Iterable +from dataclasses import dataclass, field +from types import ModuleType +from typing import Any + +logger = logging.getLogger(__name__) + + +@dataclass +class MissingItem: + """A symbol the adapter looked for but couldn't resolve to a warp twin.""" + + group: str + """Where it was looked up — e.g. ``rewards``, ``observations.policy``, ``actions``.""" + term_name: str + """Field name on the group, e.g. ``track_lin_vel_xy_exp``.""" + expected_name: str + """The symbol name searched for in the warp modules (the stable ``__name__``).""" + kind: str + """Either ``"func"`` (mdp function) or ``"class_type"`` (action runtime class).""" + searched: tuple[str, ...] + """Module dotted-paths searched, in order.""" + action: str + """Outcome: ``"dropped"`` (term set to None) or ``"raised"`` (caller saw an error).""" + + +@dataclass +class WarpAdaptReport: + """Result of :meth:`WarpFrontend.adapt`. Empty ``missing`` means clean run.""" + + missing: list[MissingItem] = field(default_factory=list) + + def __bool__(self) -> bool: # truthy when there is something to report + return bool(self.missing) + + def format(self) -> str: + if not self.missing: + return "WarpFrontend: no missing items." + lines = [f"WarpFrontend: {len(self.missing)} missing warp twin(s):"] + for m in self.missing: + lines.append( + f" - {m.group}.{m.term_name}: stable {m.kind}={m.expected_name!r} → " + f"no twin in {list(m.searched)} ({m.action})" + ) + return "\n".join(lines) + + +class _NameSwap: + """Replace ``term.`` with the same-named symbol in ``modules``. + + Drop the term entirely if no twin exists and ``drop_if_missing`` is set; + otherwise raise :class:`LookupError`. Either way, append a record to + ``report.missing`` so the caller can summarise what was lost. + + Used for both ``term.func`` (mdp swap) and ``action.class_type`` swaps — + the algorithm is identical, only the attribute name and policy differ. + """ + + def __init__( + self, + modules: Iterable[ModuleType], + attr: str, + drop_if_missing: bool, + report: WarpAdaptReport, + group_label: str, + warp_module_prefixes: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental"), + ): + self._modules = tuple(modules) + self._attr = attr + self._drop = drop_if_missing + self._report = report + self._group = group_label + # The warp mdp __init__ re-exports stable mdp terms via ``from isaaclab.envs.mdp import *`` + # before adding its own overrides. ``getattr(warp_mdp, name)`` therefore can return the + # *stable* implementation untouched. We accept a candidate as a real warp twin only if + # its ``__module__`` lives under one of these prefixes. + self._warp_module_prefixes = warp_module_prefixes + + def apply_to(self, group: Any) -> None: + if group is None: + return + for name in (n for n in dir(group) if not n.startswith("_")): + term = getattr(group, name, None) + if term is None or not hasattr(term, self._attr): + continue + stable = getattr(term, self._attr) + if not callable(stable): + continue + twin = self._resolve_twin(stable.__name__) + if twin is not None: + setattr(term, self._attr, twin) + continue + + # No twin found. + missing = MissingItem( + group=self._group, + term_name=name, + expected_name=stable.__name__, + kind=self._attr, + searched=tuple(m.__name__ for m in self._modules), + action="dropped" if self._drop else "raised", + ) + self._report.missing.append(missing) + if self._drop: + setattr(group, name, None) + else: + raise LookupError( + f"WarpFrontend: cannot adapt {self._group}.{name} — no warp twin for" + f" stable {self._attr}={stable.__name__!r}. Searched {missing.searched}." + ) + + def _resolve_twin(self, name: str) -> Any | None: + """Return the warp implementation of ``name`` from the search modules. + + Skips candidates that are merely re-exports of stable code: the warp mdp + package does ``from isaaclab.envs.mdp import *`` and a ``getattr`` lookup + will happily return the stable symbol untouched. We confirm a candidate + is actually a warp implementation by checking its ``__module__``. + """ + for module in self._modules: + candidate = getattr(module, name, None) + if candidate is None: + continue + origin = getattr(candidate, "__module__", "") or "" + if origin.startswith(self._warp_module_prefixes): + return candidate + return None + + +class WarpFrontend: + """Adapt a stable env cfg in place; build a warp-runtime env. + + Call :meth:`build` only after ``SimulationApp`` is alive — warp lib loads + lazily inside ``build``. All knobs are constructor args; subclass only if + you need to change the algorithm itself, not its parameters. + + Example:: + + with launch_simulation(env_cfg, args_cli): + env = WarpFrontend().build(env_cfg, task_id=args_cli.task) + """ + + DEFAULT_TERM_GROUPS: tuple[tuple[str, ...], ...] = ( + ("observations", "policy"), + ("events",), + ("rewards",), + ("terminations",), + ("curriculum",), + ("actions",), # included for SceneEntityCfg upgrade in action params + ) + + def __init__( + self, + stable_root: str = "isaaclab_tasks", + warp_root: str = "isaaclab_tasks_experimental", + fallback_mdp: str = "isaaclab_experimental.envs.mdp", + warp_actions: str = "isaaclab_experimental.envs.mdp.actions.joint_actions", + drop_sensors: Iterable[str] = ("height_scanner",), + term_groups: Iterable[tuple[str, ...]] = DEFAULT_TERM_GROUPS, + strict: bool = False, + ): + self._stable_root = stable_root + self._warp_root = warp_root + self._fallback_mdp = fallback_mdp + self._warp_actions = warp_actions + self._drop_sensors = tuple(drop_sensors) + self._term_groups = tuple(term_groups) + self._strict = strict + + # -- public --------------------------------------------------------------- + + def adapt(self, cfg: Any, task_id: str) -> WarpAdaptReport: + """Mutate ``cfg`` in place; return a report of what couldn't be adapted. + + With ``strict=True``, any missing twin (term func or action class) raises + :class:`LookupError` immediately so the caller sees the failure in the + traceback instead of a silently-dropped term. + """ + report = WarpAdaptReport() + + # 1. PresetCfg → newton (also dodges the lazy PhysxCfg materialisation). + # Note: by the time we run, Hydra's `resolve_presets` has already + # collapsed any PresetCfg wrapper to a concrete preset. The auto + # ``presets=newton`` injected from train.py for ``--manager=warp`` + # ensures that concrete preset is the newton one. If the preset + # somehow still has a ``newton`` attribute (custom subclass), pick it. + physics = getattr(cfg.sim, "physics", None) + if physics is not None and hasattr(physics, "newton"): + cfg.sim.physics = physics.newton + + # 2. Drop sensors warp can't run yet. + scene = getattr(cfg, "scene", None) + for sensor in self._drop_sensors: + if scene is not None and getattr(scene, sensor, None) is not None: + setattr(scene, sensor, None) + + # 3. Upgrade SceneEntityCfg instances inside term.params dicts to the + # warp-extended variant (adds joint_mask / *_ids_wp wp.array fields + # that warp mdp kernels read). + self._upgrade_scene_entity_cfgs(cfg) + + # 4. Swap term.func across all groups. + warp_mdp_modules = self._mdp_modules_for(task_id) + # Always log which warp mdp modules were resolved so it's easy to debug + # missing-twin reports. + logger.info( + "WarpFrontend: warp mdp modules for %r → %s", + task_id, + [m.__name__ for m in warp_mdp_modules], + ) + for path in self._term_groups: + if path == ("actions",): + continue # actions don't have ``func`` — handled below + group = self._walk(cfg, path) + label = ".".join(path) + swap = _NameSwap(warp_mdp_modules, "func", drop_if_missing=not self._strict, report=report, group_label=label) + swap.apply_to(group) + + # 5. Swap action class_type. An action with no warp class_type can't + # run on the warp manager, so this is always strict (raise). + action_swap = _NameSwap( + [importlib.import_module(self._warp_actions)], + attr="class_type", + drop_if_missing=False, + report=report, + group_label="actions", + ) + action_swap.apply_to(getattr(cfg, "actions", None)) + + # 6. Surface the report. + if report.missing: + level = logging.ERROR if self._strict else logging.WARNING + logger.log(level, report.format()) + + return report + + def build(self, cfg: Any, task_id: str): + """Adapt ``cfg`` and return a :class:`ManagerBasedRLEnvWarp` instance. + + Always logs the missing-twin report (if any). With ``strict=True``, + any missing twin raises before the env is constructed. + """ + # Lazy: this is the first warp-lib load. Caller must already be inside + # the SimulationApp context, i.e. inside ``launch_simulation``. + from isaaclab_experimental.envs import ManagerBasedRLEnvWarp + + self.adapt(cfg, task_id) + return ManagerBasedRLEnvWarp(cfg=cfg) + + # -- helpers -------------------------------------------------------------- + + def _upgrade_scene_entity_cfgs(self, cfg: Any) -> None: + """Upgrade every stable :class:`SceneEntityCfg` to the warp variant. + + Walks ``term.params`` dicts inside each term group and re-classes any + stable :class:`SceneEntityCfg` instance into the warp subclass so warp + mdp kernels can read ``joint_mask`` / ``joint_ids_wp`` / ``body_ids_wp`` + after :meth:`resolve`. + """ + from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _StableSE + from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSE + + def upgrade(obj: Any) -> None: + if isinstance(obj, _WarpSE) or not isinstance(obj, _StableSE): + return + # In-place class promotion + initialise warp-only fields. The class + # hierarchy guarantees compatible memory layout (warp inherits stable). + obj.__class__ = _WarpSE + obj.joint_mask = None + obj.joint_ids_wp = None + obj.body_ids_wp = None + + for path in self._term_groups: + group = self._walk(cfg, path) + if group is None: + continue + for name in (n for n in dir(group) if not n.startswith("_")): + term = getattr(group, name, None) + if term is None: + continue + params = getattr(term, "params", None) + if isinstance(params, dict): + for v in params.values(): + upgrade(v) + + @staticmethod + def _walk(root: Any, path: tuple[str, ...]) -> Any: + node = root + for attr in path: + node = getattr(node, attr, None) + if node is None: + return None + return node + + def _mdp_modules_for(self, task_id: str) -> list[ModuleType]: + """Locate warp mdp modules that mirror the stable task's mdp. + + Convention: replace ``isaaclab_tasks`` with ``isaaclab_tasks_experimental`` + in the stable cfg's module path; walk up looking for an ``mdp`` + sub-module on the warp side; always append the package-wide warp mdp + as a fallback for cross-task base terms. + """ + modules: list[ModuleType] = [] + try: + import gymnasium as gym + + entry = gym.spec(task_id).kwargs.get("env_cfg_entry_point") + except Exception: + entry = None + if isinstance(entry, str) and entry.startswith(self._stable_root): + warp_pkg = entry.rsplit(".", 1)[0].replace(self._stable_root, self._warp_root, 1) + parts = warp_pkg.split(".") + for depth in range(len(parts), 0, -1): + try: + modules.append(importlib.import_module(".".join(parts[:depth] + ["mdp"]))) + break + except ImportError: + continue + try: + modules.append(importlib.import_module(self._fallback_mdp)) + except ImportError: + logger.warning("WarpFrontend: fallback mdp module %r not importable", self._fallback_mdp) + return modules From 1cab7027c398664f5c750b18970f02ab2fd1052a Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 5 May 2026 16:41:24 +0000 Subject: [PATCH 04/36] Add changelog and apply ruff formatting for warp bridge Adds the isaaclab_experimental changelog fragment for the WarpFrontend adapter and the --manager flag, and applies the ruff-format pass that the pre-commit hook produced on warp_frontend.py. --- .../changelog.d/warp-manager-bridge.rst | 26 +++++++++++++++++++ .../envs/warp_frontend.py | 5 +++- 2 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst new file mode 100644 index 000000000000..758f4223a5f5 --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -0,0 +1,26 @@ +Added +^^^^^ + +* Added :class:`~isaaclab_experimental.envs.warp_frontend.WarpFrontend`, a + runtime adapter that lets any stable manager-based RL task config run on the + experimental warp manager runtime (:class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp`) + without a parallel ``-Warp-v0`` registration. The adapter resolves + :class:`~isaaclab_physx.preset.PresetCfg` to its ``newton`` field, swaps + ``term.func`` references to same-named warp twins discovered in the warp + ``mdp`` modules (skipping stable re-exports), promotes ``SceneEntityCfg`` + instances in-place to the warp variant, and reports any missing twins + before the env is built. + +* Added a ``--manager={stable,warp}`` flag to ``rsl_rl/train.py``. When set + to ``warp`` the script auto-injects ``presets=newton`` (so Hydra picks the + Newton physics preset before the adapter runs) and dispatches the env + through ``WarpFrontend`` instead of ``gym.make``. + +Fixed +^^^^^ + +* Fixed a regression in :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` + introduced when the ``SimulationContext.get_setting`` API was reshaped: + the warp env now mirrors the stable env and probes + :meth:`~isaaclab.sim.SimulationContext.has_active_visualizers` instead of + splitting a string setting that no longer exists. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py index 36170e991340..9da4f9c80e0e 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py @@ -230,7 +230,9 @@ def adapt(self, cfg: Any, task_id: str) -> WarpAdaptReport: continue # actions don't have ``func`` — handled below group = self._walk(cfg, path) label = ".".join(path) - swap = _NameSwap(warp_mdp_modules, "func", drop_if_missing=not self._strict, report=report, group_label=label) + swap = _NameSwap( + warp_mdp_modules, "func", drop_if_missing=not self._strict, report=report, group_label=label + ) swap.apply_to(group) # 5. Swap action class_type. An action with no warp class_type can't @@ -275,6 +277,7 @@ def _upgrade_scene_entity_cfgs(self, cfg: Any) -> None: after :meth:`resolve`. """ from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _StableSE + from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSE def upgrade(obj: Any) -> None: From 4876327a782a012a2fc1a7755986ce93b0de69fd Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 5 May 2026 17:24:06 +0000 Subject: [PATCH 05/36] Refactor warp bridge into pluggable rule pipeline; rename to --frontend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The adapter is now a sequence of CompatRule objects (resolve preset, drop sensors, promote SceneEntityCfg, swap mdp funcs, swap action class). New incompatibilities are added by writing a small rule subclass instead of editing the dispatcher. The CLI flag is renamed --manager → --frontend because the dispatch also covers direct envs: a stable manager-based cfg is adapted onto ManagerBasedRLEnvWarp; a direct task is verified to point at a warp env class and dispatched via gym.make. A stable direct cfg + --frontend=warp raises IncompatibleEnvError with the offending entry_point and a hint at the *-Direct-Warp-v0 alternative. Other fixes: - Forward render_mode through build() so --video keeps working. - Attach the CompatReport on env.unwrapped.warp_compat_report so callers can inspect what was dropped or left unresolved. - Assert the warp SceneEntityCfg subclasses the stable one before doing the in-place __class__ promotion; the rule fails loudly if the hierarchy is ever broken. - Narrow the bare except in mdp-module discovery so real ImportErrors from broken cfgs propagate. - presets=newton is now only auto-injected for stable manager-based tasks; direct warp tasks (which don't carry presets) are left alone. - Warn when the user passes presets= with --frontend=warp. - Add the commands group to the rule that promotes SceneEntityCfg. --- .../reinforcement_learning/rsl_rl/train.py | 49 +- .../changelog.d/warp-manager-bridge.rst | 26 +- .../envs/warp_frontend.py | 720 ++++++++++++------ 3 files changed, 517 insertions(+), 278 deletions(-) diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index e66485d3a37d..15326eb4b196 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -68,14 +68,15 @@ ) parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") parser.add_argument( - "--manager", + "--frontend", type=str, default="stable", choices=["stable", "warp"], help=( - "Manager-based env runtime. 'stable' uses isaaclab.envs.ManagerBasedRLEnv (torch);" - " 'warp' adapts the same task cfg via isaaclab_experimental.envs.warp_frontend.WarpFrontend" - " and runs on isaaclab_experimental.envs.ManagerBasedRLEnvWarp." + "Runtime backend for the env. 'stable' uses isaaclab.envs.* (torch);" + " 'warp' routes through isaaclab_experimental.envs.warp_frontend.WarpFrontend," + " which adapts a manager-based stable cfg onto ManagerBasedRLEnvWarp or dispatches" + " a direct task to its registered warp env class." ), ) cli_args.add_rsl_rl_args(parser) @@ -98,12 +99,29 @@ # argparser and (optionally) the external callback function. remaining_args = list_intersection(remaining_args, remaining_args_env_registration) -# When the warp manager runtime is selected, the env cfg must resolve any -# PresetCfg wrappers to their `newton` field (Hydra preset resolution runs -# *before* the WarpFrontend adapter, so we inject the override here unless -# the user already passed one explicitly). -if args_cli.manager == "warp" and not any(a.startswith("presets=") for a in remaining_args): - remaining_args.append("presets=newton") +# When the warp frontend is selected on a stable manager-based task, the cfg +# must resolve any PresetCfg wrappers to their ``newton`` field. Hydra +# resolves presets *before* the WarpFrontend runs, so we inject +# ``presets=newton`` here. We only inject for tasks registered under +# ``isaaclab_tasks.manager_based`` — direct tasks and pre-warp registrations +# don't carry a preset system, and injecting ``presets=newton`` against them +# causes Hydra to error before the frontend can produce its own diagnostic. +if args_cli.frontend == "warp" and args_cli.task is not None: + try: + _spec = gym.spec(args_cli.task) + except gym.error.NameNotFound: + _spec = None + _entry = _spec.entry_point if _spec is not None else None + _is_stable_manager = isinstance(_entry, str) and _entry.startswith("isaaclab_tasks.manager_based") + _explicit_preset = next((a for a in remaining_args if a.startswith("presets=")), None) + if _is_stable_manager and _explicit_preset is None: + remaining_args.append("presets=newton") + elif _is_stable_manager and _explicit_preset != "presets=newton": + logger.warning( + "--frontend=warp on %r expects presets=newton; got %r — adapter may fail to find a Newton physics cfg.", + args_cli.task, + _explicit_preset, + ) sys.argv = [sys.argv[0]] + remaining_args @@ -190,14 +208,15 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen env_cfg.log_dir = log_dir # create isaac environment - if args_cli.manager == "warp": - # Lazy: this is the first warp-side import. Calling it after - # SimulationApp is already alive avoids racing pxr extension init. + render_mode = "rgb_array" if args_cli.video else None + if args_cli.frontend == "warp": + # Lazy: first warp-side import. Calling this after SimulationApp + # is already alive avoids racing pxr extension init. from isaaclab_experimental.envs.warp_frontend import WarpFrontend - env = WarpFrontend().build(env_cfg, task_id=args_cli.task) + env = WarpFrontend().build(env_cfg, task_id=args_cli.task, render_mode=render_mode) else: - env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render_mode) # convert to single-agent instance if required by the RL algorithm if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 758f4223a5f5..881450b1312d 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -3,18 +3,24 @@ Added * Added :class:`~isaaclab_experimental.envs.warp_frontend.WarpFrontend`, a runtime adapter that lets any stable manager-based RL task config run on the - experimental warp manager runtime (:class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp`) - without a parallel ``-Warp-v0`` registration. The adapter resolves - :class:`~isaaclab_physx.preset.PresetCfg` to its ``newton`` field, swaps - ``term.func`` references to same-named warp twins discovered in the warp - ``mdp`` modules (skipping stable re-exports), promotes ``SceneEntityCfg`` - instances in-place to the warp variant, and reports any missing twins - before the env is built. + experimental warp runtime (:class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp`) + without a parallel ``-Warp-v0`` registration. The adapter is built on a + pluggable :class:`~isaaclab_experimental.envs.warp_frontend.CompatRule` + pipeline; new incompatibilities (sensor types, term-cfg fields, action + classes) are added by writing a small rule subclass instead of editing the + dispatcher. The default rules cover physics-preset resolution, dropping + unsupported sensors, in-place :class:`SceneEntityCfg` promotion, mdp + function swaps, and action-class swaps. The frontend also dispatches + direct envs by verifying their registered entry-point class lives under + ``isaaclab_experimental`` / ``isaaclab_tasks_experimental`` and routing + through :func:`gym.make` unchanged. -* Added a ``--manager={stable,warp}`` flag to ``rsl_rl/train.py``. When set +* Added a ``--frontend={stable,warp}`` flag to ``rsl_rl/train.py``. When set to ``warp`` the script auto-injects ``presets=newton`` (so Hydra picks the - Newton physics preset before the adapter runs) and dispatches the env - through ``WarpFrontend`` instead of ``gym.make``. + Newton physics preset before the adapter runs), warns on conflicting + ``presets=`` overrides, and dispatches the env through ``WarpFrontend`` + instead of :func:`gym.make`. ``render_mode`` is forwarded so ``--video`` + keeps working under the warp frontend. Fixed ^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py index 9da4f9c80e0e..23ea519f7cea 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py @@ -3,295 +3,304 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Adapt a stable manager-based RL env cfg to run on the warp runtime. +"""Run a stable env cfg on the warp runtime via a pluggable rule pipeline. + +The frontend classifies the cfg as manager-based or direct, runs the +applicable :class:`CompatRule` instances against it, and constructs the +matching warp env class. New incompatibilities (e.g. a new sensor type warp +can't run, a new term-cfg field that needs upgrading) are added by writing a +small :class:`CompatRule` subclass and passing it through the constructor — +no surgery in the dispatcher. Module-level imports are deliberately limited to lightweight stdlib modules. -Warp-library imports fire only inside :meth:`WarpFrontend.build`, which must -be called *after* :class:`SimulationApp` is alive — otherwise the warp lib -loading will race with Kit's USD/pxr extension initialisation. +Warp library imports fire only inside :meth:`WarpFrontend.build`, which must +be called *after* :class:`SimulationApp` is alive, otherwise warp's lib load +races with Kit's USD/pxr extension initialisation. """ from __future__ import annotations import importlib import logging -from collections.abc import Iterable +from abc import ABC, abstractmethod +from collections.abc import Iterable, Sequence from dataclasses import dataclass, field +from enum import Enum from types import ModuleType -from typing import Any +from typing import Any, ClassVar logger = logging.getLogger(__name__) -@dataclass -class MissingItem: - """A symbol the adapter looked for but couldn't resolve to a warp twin.""" - - group: str - """Where it was looked up — e.g. ``rewards``, ``observations.policy``, ``actions``.""" - term_name: str - """Field name on the group, e.g. ``track_lin_vel_xy_exp``.""" - expected_name: str - """The symbol name searched for in the warp modules (the stable ``__name__``).""" - kind: str - """Either ``"func"`` (mdp function) or ``"class_type"`` (action runtime class).""" - searched: tuple[str, ...] - """Module dotted-paths searched, in order.""" - action: str - """Outcome: ``"dropped"`` (term set to None) or ``"raised"`` (caller saw an error).""" +# --------------------------------------------------------------------------- +# Compatibility-rule framework +# --------------------------------------------------------------------------- -@dataclass -class WarpAdaptReport: - """Result of :meth:`WarpFrontend.adapt`. Empty ``missing`` means clean run.""" +class CfgKind(str, Enum): + """Workflow type of an env cfg the frontend is asked to adapt.""" - missing: list[MissingItem] = field(default_factory=list) + MANAGER_BASED = "manager_based" + DIRECT = "direct" - def __bool__(self) -> bool: # truthy when there is something to report - return bool(self.missing) - def format(self) -> str: - if not self.missing: - return "WarpFrontend: no missing items." - lines = [f"WarpFrontend: {len(self.missing)} missing warp twin(s):"] - for m in self.missing: - lines.append( - f" - {m.group}.{m.term_name}: stable {m.kind}={m.expected_name!r} → " - f"no twin in {list(m.searched)} ({m.action})" - ) - return "\n".join(lines) +_BOTH = frozenset({CfgKind.MANAGER_BASED, CfgKind.DIRECT}) +_MANAGER_ONLY = frozenset({CfgKind.MANAGER_BASED}) + +_WARP_MODULE_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") +"""Module-path prefixes that distinguish a real warp twin from a stable +re-export. The warp ``mdp`` packages do ``from isaaclab.envs.mdp import *``, +so a plain ``getattr`` lookup can return the stable symbol untouched.""" + +_TERM_GROUPS_FOR_PROMOTION: tuple[tuple[str, ...], ...] = ( + ("observations", "policy"), + ("events",), + ("rewards",), + ("terminations",), + ("commands",), + ("curriculum",), + ("actions",), +) +"""Cfg groups walked when promoting :class:`SceneEntityCfg` instances. Includes +``actions`` because action params often carry a :class:`SceneEntityCfg`.""" -class _NameSwap: - """Replace ``term.`` with the same-named symbol in ``modules``. +class IncompatibleEnvError(RuntimeError): + """Raised when the frontend can't run on the given cfg / task pair.""" - Drop the term entirely if no twin exists and ``drop_if_missing`` is set; - otherwise raise :class:`LookupError`. Either way, append a record to - ``report.missing`` so the caller can summarise what was lost. + def __init__(self, message: str, report: CompatReport | None = None): + super().__init__(message) + self.report = report - Used for both ``term.func`` (mdp swap) and ``action.class_type`` swaps — - the algorithm is identical, only the attribute name and policy differ. + +@dataclass +class CompatIssue: + """One thing the adapter looked for but couldn't resolve to a warp twin.""" + + rule: str + """Rule that produced this issue (matches :attr:`CompatRule.name`).""" + location: str + """Cfg path the issue was found at, e.g. ``rewards`` / ``actions``.""" + item: str + """Attribute name on the group, e.g. ``track_lin_vel_xy_exp``.""" + expected: str + """The symbol the rule searched for (the stable ``__name__``).""" + searched: tuple[str, ...] + """Module dotted-paths inspected, in order.""" + action: str + """Outcome: ``"dropped"``, ``"raised"``, or ``"left-stable"``.""" + + +@dataclass +class CompatReport: + """Outcome of running the rule pipeline against a cfg. + + ``changes`` is a human-readable list of mutations applied; ``issues`` + records every term the adapter couldn't resolve. A clean run has both + empty. """ - def __init__( - self, - modules: Iterable[ModuleType], - attr: str, - drop_if_missing: bool, - report: WarpAdaptReport, - group_label: str, - warp_module_prefixes: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental"), - ): - self._modules = tuple(modules) - self._attr = attr - self._drop = drop_if_missing - self._report = report - self._group = group_label - # The warp mdp __init__ re-exports stable mdp terms via ``from isaaclab.envs.mdp import *`` - # before adding its own overrides. ``getattr(warp_mdp, name)`` therefore can return the - # *stable* implementation untouched. We accept a candidate as a real warp twin only if - # its ``__module__`` lives under one of these prefixes. - self._warp_module_prefixes = warp_module_prefixes - - def apply_to(self, group: Any) -> None: - if group is None: - return - for name in (n for n in dir(group) if not n.startswith("_")): - term = getattr(group, name, None) - if term is None or not hasattr(term, self._attr): - continue - stable = getattr(term, self._attr) - if not callable(stable): - continue - twin = self._resolve_twin(stable.__name__) - if twin is not None: - setattr(term, self._attr, twin) - continue + rules_applied: list[str] = field(default_factory=list) + changes: list[str] = field(default_factory=list) + issues: list[CompatIssue] = field(default_factory=list) - # No twin found. - missing = MissingItem( - group=self._group, - term_name=name, - expected_name=stable.__name__, - kind=self._attr, - searched=tuple(m.__name__ for m in self._modules), - action="dropped" if self._drop else "raised", - ) - self._report.missing.append(missing) - if self._drop: - setattr(group, name, None) - else: - raise LookupError( - f"WarpFrontend: cannot adapt {self._group}.{name} — no warp twin for" - f" stable {self._attr}={stable.__name__!r}. Searched {missing.searched}." + def has_issues(self) -> bool: + return bool(self.issues) + + def has_fatal(self) -> bool: + return any(i.action == "raised" for i in self.issues) + + def __bool__(self) -> bool: + return bool(self.issues) or bool(self.changes) + + def format(self) -> str: + lines: list[str] = [] + if self.changes: + lines.append(f"WarpFrontend applied {len(self.changes)} change(s):") + lines.extend(f" - {c}" for c in self.changes) + if self.issues: + lines.append(f"WarpFrontend has {len(self.issues)} unresolved item(s):") + for i in self.issues: + lines.append( + f" - [{i.rule}] {i.location}.{i.item}: expected {i.expected!r}" + f" (searched {list(i.searched)}) → {i.action}" ) + return "\n".join(lines) if lines else "WarpFrontend: no changes." - def _resolve_twin(self, name: str) -> Any | None: - """Return the warp implementation of ``name`` from the search modules. - Skips candidates that are merely re-exports of stable code: the warp mdp - package does ``from isaaclab.envs.mdp import *`` and a ``getattr`` lookup - will happily return the stable symbol untouched. We confirm a candidate - is actually a warp implementation by checking its ``__module__``. - """ - for module in self._modules: - candidate = getattr(module, name, None) - if candidate is None: - continue - origin = getattr(candidate, "__module__", "") or "" - if origin.startswith(self._warp_module_prefixes): - return candidate - return None +@dataclass +class AdaptContext: + """Per-call context handed to each rule.""" + task_id: str + kind: CfgKind + strict: bool -class WarpFrontend: - """Adapt a stable env cfg in place; build a warp-runtime env. - Call :meth:`build` only after ``SimulationApp`` is alive — warp lib loads - lazily inside ``build``. All knobs are constructor args; subclass only if - you need to change the algorithm itself, not its parameters. +class CompatRule(ABC): + """One step in the warp adaptation pipeline. - Example:: + A rule mutates ``cfg`` in place and appends to ``report``. To handle a + new incompatibility, subclass and implement :meth:`apply`. Rules declare + which workflow they apply to via :attr:`applies_to`; the pipeline skips + any rule whose ``applies_to`` doesn't include the cfg kind. + """ - with launch_simulation(env_cfg, args_cli): - env = WarpFrontend().build(env_cfg, task_id=args_cli.task) + name: ClassVar[str] + applies_to: ClassVar[frozenset[CfgKind]] + + @abstractmethod + def apply(self, cfg: Any, ctx: AdaptContext, report: CompatReport) -> None: + """Mutate ``cfg`` in place and append issues / changes to ``report``.""" + + +# --------------------------------------------------------------------------- +# Helpers shared by rules +# --------------------------------------------------------------------------- + + +def _walk(root: Any, path: tuple[str, ...]) -> Any: + node = root + for attr in path: + node = getattr(node, attr, None) + if node is None: + return None + return node + + +def _resolve_warp_twin(name: str, modules: Sequence[ModuleType]) -> Any | None: + """Return ``name`` from ``modules`` if it lives under a warp prefix, else None.""" + for module in modules: + candidate = getattr(module, name, None) + if candidate is None: + continue + origin = getattr(candidate, "__module__", "") or "" + if origin.startswith(_WARP_MODULE_PREFIXES): + return candidate + return None + + +def _swap_named_attr( + group: Any, + location: str, + attr: str, + modules: Sequence[ModuleType], + *, + rule: str, + strict: bool, + report: CompatReport, +) -> None: + """Replace ``term.`` with the same-named callable from ``modules``. + + For each public attribute on ``group`` whose value has a callable ``attr`` + field, find a same-named symbol in ``modules`` whose ``__module__`` lives + under :data:`_WARP_MODULE_PREFIXES` and assign it. If no twin is found, + drop the term (set to ``None``) when ``strict`` is False, raise + :class:`LookupError` when True. Either way append a :class:`CompatIssue`. """ + if group is None: + return + searched = tuple(m.__name__ for m in modules) + # Snapshot the attribute names so mutating ``group`` mid-loop is safe. + for name in [n for n in dir(group) if not n.startswith("_")]: + term = getattr(group, name, None) + if term is None or not hasattr(term, attr): + continue + stable = getattr(term, attr) + if not callable(stable): + continue + twin = _resolve_warp_twin(stable.__name__, modules) + if twin is not None: + setattr(term, attr, twin) + continue + issue = CompatIssue( + rule=rule, + location=location, + item=name, + expected=stable.__name__, + searched=searched, + action="raised" if strict else "dropped", + ) + report.issues.append(issue) + if strict: + raise LookupError( + f"WarpFrontend: cannot adapt {location}.{name} — no warp twin for " + f"stable {attr}={stable.__name__!r}. Searched {list(searched)}." + ) + setattr(group, name, None) - DEFAULT_TERM_GROUPS: tuple[tuple[str, ...], ...] = ( - ("observations", "policy"), - ("events",), - ("rewards",), - ("terminations",), - ("curriculum",), - ("actions",), # included for SceneEntityCfg upgrade in action params - ) - def __init__( - self, - stable_root: str = "isaaclab_tasks", - warp_root: str = "isaaclab_tasks_experimental", - fallback_mdp: str = "isaaclab_experimental.envs.mdp", - warp_actions: str = "isaaclab_experimental.envs.mdp.actions.joint_actions", - drop_sensors: Iterable[str] = ("height_scanner",), - term_groups: Iterable[tuple[str, ...]] = DEFAULT_TERM_GROUPS, - strict: bool = False, - ): - self._stable_root = stable_root - self._warp_root = warp_root - self._fallback_mdp = fallback_mdp - self._warp_actions = warp_actions - self._drop_sensors = tuple(drop_sensors) - self._term_groups = tuple(term_groups) - self._strict = strict +# --------------------------------------------------------------------------- +# Concrete rules +# --------------------------------------------------------------------------- - # -- public --------------------------------------------------------------- - def adapt(self, cfg: Any, task_id: str) -> WarpAdaptReport: - """Mutate ``cfg`` in place; return a report of what couldn't be adapted. +class ResolvePhysicsPresetRule(CompatRule): + """Collapse ``cfg.sim.physics`` from a :class:`PresetCfg` to its ``newton`` field. - With ``strict=True``, any missing twin (term func or action class) raises - :class:`LookupError` immediately so the caller sees the failure in the - traceback instead of a silently-dropped term. - """ - report = WarpAdaptReport() - - # 1. PresetCfg → newton (also dodges the lazy PhysxCfg materialisation). - # Note: by the time we run, Hydra's `resolve_presets` has already - # collapsed any PresetCfg wrapper to a concrete preset. The auto - # ``presets=newton`` injected from train.py for ``--manager=warp`` - # ensures that concrete preset is the newton one. If the preset - # somehow still has a ``newton`` attribute (custom subclass), pick it. - physics = getattr(cfg.sim, "physics", None) + Hydra's preset resolution normally collapses the wrapper before the + frontend runs. This rule covers two residual cases: programmatic use of + :meth:`WarpFrontend.adapt` (no Hydra), and custom physics cfgs that still + expose a ``newton`` attribute. + """ + + name = "resolve_physics_preset" + applies_to = _BOTH + + def apply(self, cfg, ctx, report): + physics = getattr(getattr(cfg, "sim", None), "physics", None) if physics is not None and hasattr(physics, "newton"): cfg.sim.physics = physics.newton + report.changes.append(f"sim.physics → {type(physics.newton).__name__}") - # 2. Drop sensors warp can't run yet. - scene = getattr(cfg, "scene", None) - for sensor in self._drop_sensors: - if scene is not None and getattr(scene, sensor, None) is not None: - setattr(scene, sensor, None) - # 3. Upgrade SceneEntityCfg instances inside term.params dicts to the - # warp-extended variant (adds joint_mask / *_ids_wp wp.array fields - # that warp mdp kernels read). - self._upgrade_scene_entity_cfgs(cfg) - - # 4. Swap term.func across all groups. - warp_mdp_modules = self._mdp_modules_for(task_id) - # Always log which warp mdp modules were resolved so it's easy to debug - # missing-twin reports. - logger.info( - "WarpFrontend: warp mdp modules for %r → %s", - task_id, - [m.__name__ for m in warp_mdp_modules], - ) - for path in self._term_groups: - if path == ("actions",): - continue # actions don't have ``func`` — handled below - group = self._walk(cfg, path) - label = ".".join(path) - swap = _NameSwap( - warp_mdp_modules, "func", drop_if_missing=not self._strict, report=report, group_label=label - ) - swap.apply_to(group) +class DropUnsupportedSensorsRule(CompatRule): + """Drop scene sensors the warp runtime can't run yet.""" - # 5. Swap action class_type. An action with no warp class_type can't - # run on the warp manager, so this is always strict (raise). - action_swap = _NameSwap( - [importlib.import_module(self._warp_actions)], - attr="class_type", - drop_if_missing=False, - report=report, - group_label="actions", - ) - action_swap.apply_to(getattr(cfg, "actions", None)) - - # 6. Surface the report. - if report.missing: - level = logging.ERROR if self._strict else logging.WARNING - logger.log(level, report.format()) + name = "drop_unsupported_sensors" + applies_to = _BOTH - return report + def __init__(self, sensors: Iterable[str] = ("height_scanner",)): + self.sensors = tuple(sensors) - def build(self, cfg: Any, task_id: str): - """Adapt ``cfg`` and return a :class:`ManagerBasedRLEnvWarp` instance. + def apply(self, cfg, ctx, report): + scene = getattr(cfg, "scene", None) + if scene is None: + return + for sensor in self.sensors: + if getattr(scene, sensor, None) is not None: + setattr(scene, sensor, None) + report.changes.append(f"scene.{sensor} → None") - Always logs the missing-twin report (if any). With ``strict=True``, - any missing twin raises before the env is constructed. - """ - # Lazy: this is the first warp-lib load. Caller must already be inside - # the SimulationApp context, i.e. inside ``launch_simulation``. - from isaaclab_experimental.envs import ManagerBasedRLEnvWarp - self.adapt(cfg, task_id) - return ManagerBasedRLEnvWarp(cfg=cfg) +class PromoteSceneEntityCfgRule(CompatRule): + """Promote :class:`SceneEntityCfg` instances under term params to the warp variant. - # -- helpers -------------------------------------------------------------- + The warp variant adds cached ``joint_mask`` / ``joint_ids_wp`` / + ``body_ids_wp`` fields the warp mdp kernels read after :meth:`resolve`. + The class hierarchy is asserted at apply time — if the warp class no + longer subclasses the stable class (refactor or divergence), the rule + raises :class:`TypeError` so the assumption can never silently corrupt + instances. + """ - def _upgrade_scene_entity_cfgs(self, cfg: Any) -> None: - """Upgrade every stable :class:`SceneEntityCfg` to the warp variant. + name = "promote_scene_entity_cfg" + applies_to = _MANAGER_ONLY - Walks ``term.params`` dicts inside each term group and re-classes any - stable :class:`SceneEntityCfg` instance into the warp subclass so warp - mdp kernels can read ``joint_mask`` / ``joint_ids_wp`` / ``body_ids_wp`` - after :meth:`resolve`. - """ + def apply(self, cfg, ctx, report): from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _StableSE from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSE - def upgrade(obj: Any) -> None: - if isinstance(obj, _WarpSE) or not isinstance(obj, _StableSE): - return - # In-place class promotion + initialise warp-only fields. The class - # hierarchy guarantees compatible memory layout (warp inherits stable). - obj.__class__ = _WarpSE - obj.joint_mask = None - obj.joint_ids_wp = None - obj.body_ids_wp = None - - for path in self._term_groups: - group = self._walk(cfg, path) + if not issubclass(_WarpSE, _StableSE): + raise TypeError( + "PromoteSceneEntityCfgRule requires the warp SceneEntityCfg to subclass the stable one;" + f" got mro {[c.__name__ for c in _WarpSE.__mro__]}" + ) + + promoted = 0 + for path in _TERM_GROUPS_FOR_PROMOTION: + group = _walk(cfg, path) if group is None: continue for name in (n for n in dir(group) if not n.startswith("_")): @@ -299,36 +308,86 @@ def upgrade(obj: Any) -> None: if term is None: continue params = getattr(term, "params", None) - if isinstance(params, dict): - for v in params.values(): - upgrade(v) + if not isinstance(params, dict): + continue + for value in params.values(): + if isinstance(value, _WarpSE) or not isinstance(value, _StableSE): + continue + value.__class__ = _WarpSE + value.joint_mask = None + value.joint_ids_wp = None + value.body_ids_wp = None + promoted += 1 + if promoted: + report.changes.append(f"promoted {promoted} SceneEntityCfg instance(s) to warp variant") + + +class SwapMdpFunctionsRule(CompatRule): + """Replace ``term.func`` with the same-named callable from warp ``mdp`` modules. + + Walks observation / event / reward / termination / command / curriculum + groups. A re-export from stable code is rejected by checking + ``__module__``. Missing twins are dropped (term set to ``None``) unless + the context is strict, in which case they raise. + """ - @staticmethod - def _walk(root: Any, path: tuple[str, ...]) -> Any: - node = root - for attr in path: - node = getattr(node, attr, None) - if node is None: - return None - return node + name = "swap_mdp_functions" + applies_to = _MANAGER_ONLY + + GROUPS: ClassVar[tuple[tuple[str, ...], ...]] = ( + ("observations", "policy"), + ("events",), + ("rewards",), + ("terminations",), + ("commands",), + ("curriculum",), + ) + + def __init__( + self, + stable_root: str = "isaaclab_tasks", + warp_root: str = "isaaclab_tasks_experimental", + fallback_mdp: str = "isaaclab_experimental.envs.mdp", + ): + self.stable_root = stable_root + self.warp_root = warp_root + self.fallback_mdp = fallback_mdp + + def apply(self, cfg, ctx, report): + modules = self._mdp_modules_for(ctx.task_id) + logger.info("WarpFrontend: warp mdp modules → %s", [m.__name__ for m in modules]) + for path in self.GROUPS: + group = _walk(cfg, path) + _swap_named_attr( + group, + location=".".join(path), + attr="func", + modules=modules, + rule=self.name, + strict=ctx.strict, + report=report, + ) def _mdp_modules_for(self, task_id: str) -> list[ModuleType]: """Locate warp mdp modules that mirror the stable task's mdp. - Convention: replace ``isaaclab_tasks`` with ``isaaclab_tasks_experimental`` - in the stable cfg's module path; walk up looking for an ``mdp`` - sub-module on the warp side; always append the package-wide warp mdp - as a fallback for cross-task base terms. + Convention: replace :attr:`stable_root` with :attr:`warp_root` in the + stable cfg's module path, walk up looking for an ``mdp`` sub-module on + the warp side, and always append :attr:`fallback_mdp` for cross-task + base terms. """ modules: list[ModuleType] = [] try: import gymnasium as gym entry = gym.spec(task_id).kwargs.get("env_cfg_entry_point") - except Exception: + except (KeyError, AttributeError, ModuleNotFoundError, gym.error.NameNotFound): + # Spec is missing / kwargs missing the entry — fall back to the + # package-wide warp mdp module only. Real ImportError from a + # broken cfg module is *not* swallowed; it propagates. entry = None - if isinstance(entry, str) and entry.startswith(self._stable_root): - warp_pkg = entry.rsplit(".", 1)[0].replace(self._stable_root, self._warp_root, 1) + if isinstance(entry, str) and entry.startswith(self.stable_root): + warp_pkg = entry.rsplit(".", 1)[0].replace(self.stable_root, self.warp_root, 1) parts = warp_pkg.split(".") for depth in range(len(parts), 0, -1): try: @@ -337,7 +396,162 @@ def _mdp_modules_for(self, task_id: str) -> list[ModuleType]: except ImportError: continue try: - modules.append(importlib.import_module(self._fallback_mdp)) + modules.append(importlib.import_module(self.fallback_mdp)) except ImportError: - logger.warning("WarpFrontend: fallback mdp module %r not importable", self._fallback_mdp) + logger.warning("WarpFrontend: fallback mdp module %r not importable", self.fallback_mdp) return modules + + +class SwapActionClassTypeRule(CompatRule): + """Swap ``cfg.actions..class_type`` with the same-named warp class. + + Always strict: an action with no warp class can't run on the warp + runtime, so a missing twin raises :class:`LookupError`. + """ + + name = "swap_action_class_type" + applies_to = _MANAGER_ONLY + + def __init__(self, warp_actions_module: str = "isaaclab_experimental.envs.mdp.actions.joint_actions"): + self.warp_actions_module = warp_actions_module + + def apply(self, cfg, ctx, report): + actions = getattr(cfg, "actions", None) + if actions is None: + return + try: + module = importlib.import_module(self.warp_actions_module) + except ImportError as exc: + raise IncompatibleEnvError( + f"WarpFrontend: warp action module {self.warp_actions_module!r} not importable" + ) from exc + _swap_named_attr( + actions, + location="actions", + attr="class_type", + modules=[module], + rule=self.name, + strict=True, + report=report, + ) + + +# --------------------------------------------------------------------------- +# Frontend +# --------------------------------------------------------------------------- + + +class WarpFrontend: + """Run a stable env cfg on the warp runtime via a pluggable rule pipeline. + + The frontend classifies the input cfg as manager-based or direct, runs + the applicable :class:`CompatRule` instances, then constructs the + matching warp env class. + + Direct envs encode their runtime in the env class itself (each warp + direct env is a separate class with its own kernels), so the frontend + doesn't transform direct cfgs — it only verifies the registered + ``entry_point`` lives under :data:`_WARP_MODULE_PREFIXES` and dispatches + via :func:`gym.make`. A stable direct cfg + ``--frontend=warp`` raises + :class:`IncompatibleEnvError` with a clear message. + + Example:: + + with launch_simulation(cfg, args_cli): + env = WarpFrontend().build(cfg, task_id=args_cli.task) + if env.unwrapped.warp_compat_report.has_issues(): + print(env.unwrapped.warp_compat_report.format()) + """ + + DEFAULT_RULES: ClassVar[tuple[type[CompatRule], ...]] = ( + ResolvePhysicsPresetRule, + DropUnsupportedSensorsRule, + PromoteSceneEntityCfgRule, + SwapMdpFunctionsRule, + SwapActionClassTypeRule, + ) + + def __init__(self, rules: Sequence[CompatRule] | None = None, strict: bool = False): + self.rules: list[CompatRule] = list(rules) if rules is not None else [r() for r in self.DEFAULT_RULES] + self.strict = strict + + # -- public --------------------------------------------------------------- + + def adapt(self, cfg: Any, task_id: str) -> CompatReport: + """Run the rule pipeline; mutate ``cfg`` in place; return a report. + + The report is logged at ``WARNING`` (or ``ERROR`` in strict mode when + any issue is fatal). Missing twins raise :class:`LookupError` only + when ``strict=True``. + """ + kind = self._classify(cfg) + ctx = AdaptContext(task_id=task_id, kind=kind, strict=self.strict) + report = CompatReport() + for rule in self.rules: + if kind not in rule.applies_to: + continue + rule.apply(cfg, ctx, report) + report.rules_applied.append(rule.name) + if report: + level = logging.ERROR if self.strict and report.has_fatal() else logging.WARNING + logger.log(level, report.format()) + return report + + def build(self, cfg: Any, task_id: str, render_mode: str | None = None): + """Adapt ``cfg`` and construct a warp env. + + Returns an env instance with ``warp_compat_report`` attached on the + unwrapped env. ``render_mode`` is forwarded so ``--video`` keeps + working when the frontend is selected at the train-script level. + """ + # Lazy: this is the first warp-lib load. The caller must already be + # inside the SimulationApp context (i.e. inside ``launch_simulation``). + from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg + + report = self.adapt(cfg, task_id) + if isinstance(cfg, ManagerBasedRLEnvCfg): + from isaaclab_experimental.envs import ManagerBasedRLEnvWarp + + env = ManagerBasedRLEnvWarp(cfg=cfg, render_mode=render_mode) + elif isinstance(cfg, DirectRLEnvCfg): + self._verify_direct_warp(task_id) + import gymnasium as gym + + env = gym.make(task_id, cfg=cfg, render_mode=render_mode) + else: + raise IncompatibleEnvError( + f"WarpFrontend supports ManagerBasedRLEnvCfg or DirectRLEnvCfg, got {type(cfg).__name__}", + report=report, + ) + env.unwrapped.warp_compat_report = report + return env + + # -- helpers -------------------------------------------------------------- + + @staticmethod + def _classify(cfg: Any) -> CfgKind: + from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg + + if isinstance(cfg, ManagerBasedRLEnvCfg): + return CfgKind.MANAGER_BASED + if isinstance(cfg, DirectRLEnvCfg): + return CfgKind.DIRECT + raise IncompatibleEnvError( + f"WarpFrontend supports ManagerBasedRLEnvCfg or DirectRLEnvCfg, got {type(cfg).__name__}" + ) + + @staticmethod + def _verify_direct_warp(task_id: str) -> None: + import gymnasium as gym + + try: + spec = gym.spec(task_id) + except gym.error.NameNotFound as exc: + raise IncompatibleEnvError(f"Task {task_id!r} is not registered with gymnasium") from exc + ep = spec.entry_point + if isinstance(ep, str) and not ep.startswith(_WARP_MODULE_PREFIXES): + raise IncompatibleEnvError( + f"Direct env {task_id!r} entry_point {ep!r} is not a warp implementation." + f" --frontend=warp on a direct task requires the registered class to live under" + f" {list(_WARP_MODULE_PREFIXES)} (e.g. *-Direct-Warp-v0)." + ) From 0a9f2cd99e08378369bfa6fc7ae73a4b66ee4954 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 5 May 2026 17:45:36 +0000 Subject: [PATCH 06/36] Fix presets=newton injection for stable manager-based tasks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The earlier check inspected gym.spec(task).entry_point, which for stable manager-based tasks is "isaaclab.envs:ManagerBasedRLEnv" — the env class path, not the cfg path. So the startswith("isaaclab_tasks.manager_based") test always failed and presets=newton was never injected. Hydra then resolved every PresetCfg in the cfg tree (physics, contact_forces, etc.) to its default field, leaving the warp runtime with PhysX class_types it can't load. Switch to spec.kwargs["env_cfg_entry_point"], which actually points at the task cfg module (e.g. "isaaclab_tasks.manager_based.locomotion.velocity. config.anymal_d.flat_env_cfg:AnymalDFlatEnvCfg"), and the prefix check selects the right tasks. --- scripts/reinforcement_learning/rsl_rl/train.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index 15326eb4b196..9bb76d884555 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -102,17 +102,20 @@ # When the warp frontend is selected on a stable manager-based task, the cfg # must resolve any PresetCfg wrappers to their ``newton`` field. Hydra # resolves presets *before* the WarpFrontend runs, so we inject -# ``presets=newton`` here. We only inject for tasks registered under -# ``isaaclab_tasks.manager_based`` — direct tasks and pre-warp registrations -# don't carry a preset system, and injecting ``presets=newton`` against them -# causes Hydra to error before the frontend can produce its own diagnostic. +# ``presets=newton`` here. We only inject for tasks whose env_cfg_entry_point +# is under ``isaaclab_tasks.manager_based``; direct tasks and the pre-warp +# ``*-Warp-v0`` registrations don't carry the preset system, and injecting +# ``presets=newton`` against them causes Hydra to error before the frontend +# can produce its own diagnostic. Note: ``spec.entry_point`` is the env +# *class* path (e.g. ``isaaclab.envs:ManagerBasedRLEnv``) — we check the +# *cfg* entry point in ``spec.kwargs``. if args_cli.frontend == "warp" and args_cli.task is not None: try: _spec = gym.spec(args_cli.task) except gym.error.NameNotFound: _spec = None - _entry = _spec.entry_point if _spec is not None else None - _is_stable_manager = isinstance(_entry, str) and _entry.startswith("isaaclab_tasks.manager_based") + _cfg_entry = _spec.kwargs.get("env_cfg_entry_point") if _spec is not None else None + _is_stable_manager = isinstance(_cfg_entry, str) and _cfg_entry.startswith("isaaclab_tasks.manager_based") _explicit_preset = next((a for a in remaining_args if a.startswith("presets=")), None) if _is_stable_manager and _explicit_preset is None: remaining_args.append("presets=newton") From d558741194c923a2357c9f15c7c26b08efa0fdc4 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 6 May 2026 07:40:55 +0000 Subject: [PATCH 07/36] Refactor warp bridge into a frontend framework package The single-file warp_frontend.py grew into a real subsystem worth splitting out, so move it into a frontend/ package with explicit abstractions: - frontend/base.py: Frontend ABC, CompatRule (check + transform via a unified run() method), TaskResolver (centralised gym.spec introspection -> TaskMeta), Workflow / Runtime / Severity enums, Issue / Change / Report record types, register_frontend / get_frontend registry. Helpers walk_attrs / resolve_warp_twin / iter_term_attrs are shared utilities used by rules. - frontend/torch.py: TorchFrontend, the default. Pass-through to gym.make with one rule (WarnIfTaskIsWarpRegistered) for the contradiction case. - frontend/warp.py: WarpFrontend with the full rule pipeline. Includes a new CheckPhysicsIsNewton blocking rule that surfaces the PhysX-with-warp incompatibility (asset class_type strings resolve to isaaclab_physx.* classes that depend on omni.physics.tensors.api, which the warp runtime does not initialise). CLI: rename --frontend stable -> torch since the axis is *runtime*, not *stability tier*. The frontend selector now reads cleanly: --frontend torch -> default gym.make path --frontend warp -> experimental warp runtime via WarpFrontend train.py becomes a thin dispatcher: get_frontend(name) gives a Frontend instance, frontend.preprocess_hydra_args(...) handles preset injection, frontend.build(cfg, task) returns the env. No more inline conditional imports; no more inline preset-injection logic. env.unwrapped.frontend_report is the inspection point - callers and tests can read what changed and what was missing without re-running adapt(). To add a new compatibility check, write a CompatRule subclass and append it to the relevant frontend's `rules` tuple. To add a new runtime, subclass Frontend and call register_frontend(name, cls). --- .../reinforcement_learning/rsl_rl/train.py | 63 +- .../changelog.d/warp-manager-bridge.rst | 73 ++- .../envs/frontend/__init__.py | 100 ++++ .../envs/frontend/base.py | 486 +++++++++++++++ .../envs/frontend/torch.py | 72 +++ .../envs/frontend/warp.py | 453 ++++++++++++++ .../envs/warp_frontend.py | 557 ------------------ 7 files changed, 1186 insertions(+), 618 deletions(-) create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index 9bb76d884555..e146a0cc2575 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -70,13 +70,14 @@ parser.add_argument( "--frontend", type=str, - default="stable", - choices=["stable", "warp"], + default="torch", + choices=["torch", "warp"], help=( - "Runtime backend for the env. 'stable' uses isaaclab.envs.* (torch);" - " 'warp' routes through isaaclab_experimental.envs.warp_frontend.WarpFrontend," - " which adapts a manager-based stable cfg onto ManagerBasedRLEnvWarp or dispatches" - " a direct task to its registered warp env class." + "Runtime backend for the env. 'torch' uses isaaclab.envs.* (PhysX or Newton via" + " factory dispatch); 'warp' routes through the WarpFrontend, which adapts a" + " manager-based cfg onto ManagerBasedRLEnvWarp or dispatches a direct task to its" + " registered warp env class. See isaaclab_experimental.envs.frontend for the" + " pluggable rule pipeline." ), ) cli_args.add_rsl_rl_args(parser) @@ -99,32 +100,15 @@ # argparser and (optionally) the external callback function. remaining_args = list_intersection(remaining_args, remaining_args_env_registration) -# When the warp frontend is selected on a stable manager-based task, the cfg -# must resolve any PresetCfg wrappers to their ``newton`` field. Hydra -# resolves presets *before* the WarpFrontend runs, so we inject -# ``presets=newton`` here. We only inject for tasks whose env_cfg_entry_point -# is under ``isaaclab_tasks.manager_based``; direct tasks and the pre-warp -# ``*-Warp-v0`` registrations don't carry the preset system, and injecting -# ``presets=newton`` against them causes Hydra to error before the frontend -# can produce its own diagnostic. Note: ``spec.entry_point`` is the env -# *class* path (e.g. ``isaaclab.envs:ManagerBasedRLEnv``) — we check the -# *cfg* entry point in ``spec.kwargs``. -if args_cli.frontend == "warp" and args_cli.task is not None: - try: - _spec = gym.spec(args_cli.task) - except gym.error.NameNotFound: - _spec = None - _cfg_entry = _spec.kwargs.get("env_cfg_entry_point") if _spec is not None else None - _is_stable_manager = isinstance(_cfg_entry, str) and _cfg_entry.startswith("isaaclab_tasks.manager_based") - _explicit_preset = next((a for a in remaining_args if a.startswith("presets=")), None) - if _is_stable_manager and _explicit_preset is None: - remaining_args.append("presets=newton") - elif _is_stable_manager and _explicit_preset != "presets=newton": - logger.warning( - "--frontend=warp on %r expects presets=newton; got %r — adapter may fail to find a Newton physics cfg.", - args_cli.task, - _explicit_preset, - ) +# Build the chosen frontend and let it pre-process Hydra args. Frontends +# may inject preset selections (e.g. WarpFrontend appends ``presets=newton`` +# for stable manager-based tasks so PresetCfg wrappers resolve to the Newton +# field before Hydra builds the cfg). +from isaaclab_experimental.envs.frontend import get_frontend # noqa: E402 + +_frontend = get_frontend(args_cli.frontend) +if args_cli.task is not None: + remaining_args = _frontend.preprocess_hydra_args(args_cli.task, remaining_args) sys.argv = [sys.argv[0]] + remaining_args @@ -210,16 +194,13 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # set the log directory for the environment (works for all environment types) env_cfg.log_dir = log_dir - # create isaac environment + # create isaac environment via the chosen frontend's rule pipeline. + # The frontend may mutate env_cfg in place (preset resolution, + # SceneEntityCfg promotion, mdp twin swaps, ...) before constructing + # the env. ``env.unwrapped.frontend_report`` carries what changed + # and what was missing. render_mode = "rgb_array" if args_cli.video else None - if args_cli.frontend == "warp": - # Lazy: first warp-side import. Calling this after SimulationApp - # is already alive avoids racing pxr extension init. - from isaaclab_experimental.envs.warp_frontend import WarpFrontend - - env = WarpFrontend().build(env_cfg, task_id=args_cli.task, render_mode=render_mode) - else: - env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render_mode) + env = _frontend.build(env_cfg, task_id=args_cli.task, render_mode=render_mode) # convert to single-agent instance if required by the RL algorithm if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 881450b1312d..d7197a0a756e 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -1,26 +1,59 @@ Added ^^^^^ -* Added :class:`~isaaclab_experimental.envs.warp_frontend.WarpFrontend`, a - runtime adapter that lets any stable manager-based RL task config run on the - experimental warp runtime (:class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp`) - without a parallel ``-Warp-v0`` registration. The adapter is built on a - pluggable :class:`~isaaclab_experimental.envs.warp_frontend.CompatRule` - pipeline; new incompatibilities (sensor types, term-cfg fields, action - classes) are added by writing a small rule subclass instead of editing the - dispatcher. The default rules cover physics-preset resolution, dropping - unsupported sensors, in-place :class:`SceneEntityCfg` promotion, mdp - function swaps, and action-class swaps. The frontend also dispatches - direct envs by verifying their registered entry-point class lives under - ``isaaclab_experimental`` / ``isaaclab_tasks_experimental`` and routing - through :func:`gym.make` unchanged. - -* Added a ``--frontend={stable,warp}`` flag to ``rsl_rl/train.py``. When set - to ``warp`` the script auto-injects ``presets=newton`` (so Hydra picks the - Newton physics preset before the adapter runs), warns on conflicting - ``presets=`` overrides, and dispatches the env through ``WarpFrontend`` - instead of :func:`gym.make`. ``render_mode`` is forwarded so ``--video`` - keeps working under the warp frontend. +* Added :mod:`isaaclab_experimental.envs.frontend`, a small framework that + selects the runtime backend for IsaacLab tasks. A :class:`Frontend` takes + a stable env cfg + task id, runs a pluggable :class:`CompatRule` pipeline + against the (cfg, task, frontend) triple, and constructs the env on the + matching runtime. New runtimes plug in by subclassing :class:`Frontend` + and calling :func:`register_frontend`; new compatibility checks plug in + by subclassing :class:`CompatRule` and listing it in a frontend's + :attr:`Frontend.rules`. + + The framework ships two built-in frontends: + + * :class:`TorchFrontend` (``--frontend=torch``, default) — passes through + to :func:`gym.make`. Emits a warning if the task is registered under + the warp runtime. + * :class:`WarpFrontend` (``--frontend=warp``) — adapts a manager-based + stable cfg onto :class:`ManagerBasedRLEnvWarp` via the rule pipeline, + or dispatches a direct task to its registered warp env class. + + The default warp rules are: + + * :class:`CheckPhysicsIsNewton` — blocking check; PhysX physics with the + warp runtime is a hard incompatibility (``isaaclab_physx`` classes + depend on ``omni.physics.tensors``, which the warp runtime does not + initialise). + * :class:`ResolvePhysicsPreset` — collapses ``PresetCfg`` to its + ``newton`` field for programmatic callers (Hydra's preset resolution + handles the CLI case). + * :class:`DropUnsupportedSensors` — drops scene sensors warp can't run. + * :class:`PromoteSceneEntityCfg` — in-place class promotion for warp + cached fields, with an :func:`issubclass` assertion to fail loudly if + the warp class ever stops subclassing the stable one. + * :class:`SwapMdpFunctions` — name-based ``term.func`` replacement + against the warp ``mdp`` modules; rejects stable re-exports by + inspecting ``__module__``. + * :class:`SwapActionClassType` — strict swap of action ``class_type`` + to the warp twin; missing twin is :attr:`Severity.BLOCKING`. + * :class:`VerifyDirectIsWarp` — for direct cfgs, blocks if the + registered entry-point isn't a warp class. + + All rules emit :class:`Issue` (incompatibility) and / or :class:`Change` + (transformation applied) records into a :class:`Report` accessible on + ``env.unwrapped.frontend_report`` after :meth:`Frontend.build`. + + :class:`TaskResolver` centralises ``gym.spec`` introspection and + classifies a task into a :class:`TaskMeta` (workflow, registered + runtime, cfg class). Rules read from :class:`TaskMeta` rather than + poking gym directly. + +* Added a ``--frontend={torch,warp}`` flag to ``rsl_rl/train.py``. The + script delegates Hydra-arg pre-processing (``presets=newton`` injection, + conflicting-preset warnings) and env construction to the selected + frontend via :func:`get_frontend`; ``render_mode`` is forwarded so + ``--video`` keeps working under the warp frontend. Fixed ^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py new file mode 100644 index 000000000000..ad81605e6442 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py @@ -0,0 +1,100 @@ +# 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 + +"""Frontend framework: pluggable runtime selectors for IsaacLab tasks. + +A frontend (chosen via ``--frontend {torch,warp}``) is a thin dispatcher that +takes a stable env cfg + task id, runs a pluggable :class:`CompatRule` +pipeline against the (cfg, task, frontend) triple, and constructs the env on +the matching runtime. New runtimes plug in by subclassing :class:`Frontend` +and calling :func:`register_frontend`; new compatibility checks plug in by +subclassing :class:`CompatRule` and adding it to a frontend's +:attr:`Frontend.rules`. + +Public API:: + + from isaaclab_experimental.envs.frontend import get_frontend + frontend = get_frontend("warp") + env = frontend.build(env_cfg, task_id="Isaac-Cartpole-v0") + print(env.unwrapped.frontend_report.format()) +""" + +from __future__ import annotations + +from .base import ( + WARP_ROOT_PREFIXES, + Change, + CompatRule, + Frontend, + FrontendIncompatibleError, + Issue, + Report, + ResolveContext, + Runtime, + Severity, + TaskMeta, + TaskResolver, + Workflow, + available_frontends, + get_frontend, + iter_term_attrs, + register_frontend, + resolve_warp_twin, + walk_attrs, +) +from .torch import TorchFrontend, WarnIfTaskIsWarpRegistered +from .warp import ( + CheckPhysicsIsNewton, + DropUnsupportedSensors, + PromoteSceneEntityCfg, + ResolvePhysicsPreset, + SwapActionClassType, + SwapMdpFunctions, + VerifyDirectIsWarp, + WarpFrontend, +) + +# Register built-ins so ``get_frontend("torch" | "warp")`` works without +# the caller importing the concrete classes. +register_frontend(TorchFrontend.name, TorchFrontend) +register_frontend(WarpFrontend.name, WarpFrontend) + + +__all__ = [ + # core abstractions + "Frontend", + "CompatRule", + "TaskMeta", + "TaskResolver", + "Report", + "Issue", + "Change", + "Severity", + "Workflow", + "Runtime", + "ResolveContext", + "FrontendIncompatibleError", + "WARP_ROOT_PREFIXES", + # registry + "register_frontend", + "get_frontend", + "available_frontends", + # rule helpers + "walk_attrs", + "resolve_warp_twin", + "iter_term_attrs", + # built-in frontends + "TorchFrontend", + "WarpFrontend", + # built-in rules + "WarnIfTaskIsWarpRegistered", + "CheckPhysicsIsNewton", + "ResolvePhysicsPreset", + "DropUnsupportedSensors", + "PromoteSceneEntityCfg", + "SwapMdpFunctions", + "SwapActionClassType", + "VerifyDirectIsWarp", +] diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py new file mode 100644 index 000000000000..81fc21a33cf7 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py @@ -0,0 +1,486 @@ +# 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 + +"""Frontend framework — abstractions for runtime selection. + +A *frontend* is a user-facing runtime selector (chosen via ``--frontend +{torch,warp}``). It takes a stable env cfg and a registered gym task id and +returns a runnable env, having first run a pluggable pipeline of +compatibility checks and transforms against the (cfg, task, frontend) +triple. + +The framework is intentionally narrow: + +* :class:`TaskResolver` is the single point that reads ``gym.spec`` and + classifies a task into a :class:`TaskMeta` (workflow, registered + runtime, cfg class). Rules and frontends consume :class:`TaskMeta` + instead of poking gym directly, so the registration format can evolve + in one place. +* :class:`CompatRule` is a single check or transform applied during + resolution. Each rule yields :class:`Issue` records (incompatibilities + the frontend can't paper over) and / or :class:`Change` records + (transformations applied to the cfg). Subclasses implement + :meth:`CompatRule.run` and may override :meth:`CompatRule.applies_to` + to scope themselves by workflow / runtime. +* :class:`Frontend` is the dispatcher. Subclasses declare a name, a list + of rule classes, and a :meth:`Frontend.construct` strategy that builds + the env once rules pass. +* :func:`register_frontend` / :func:`get_frontend` form the registry CLI + hooks read. + +To add a new compatibility check, write a small :class:`CompatRule` and +list it in the relevant frontend's :attr:`Frontend.rules`. To add a new +runtime, subclass :class:`Frontend` and call :func:`register_frontend`. +""" + +from __future__ import annotations + +import logging +from abc import ABC, abstractmethod +from collections.abc import Iterable, Iterator +from dataclasses import dataclass, field +from enum import Enum +from typing import Any, ClassVar + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Constants +# --------------------------------------------------------------------------- + + +WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") +"""Module prefixes that mark a class as a warp implementation. + +The warp ``mdp`` packages do ``from isaaclab.envs.mdp import *``, so a +plain ``getattr`` lookup can return a stable symbol untouched. We accept +a candidate as a real warp twin only if its ``__module__`` lives under +one of these prefixes.""" + + +# --------------------------------------------------------------------------- +# Enums +# --------------------------------------------------------------------------- + + +class Workflow(str, Enum): + """Task workflow type.""" + + MANAGER_BASED = "manager_based" + DIRECT = "direct" + DIRECT_MARL = "direct_marl" + + +class Runtime(str, Enum): + """Runtime backend a task is registered against. + + A task whose ``entry_point`` lives under :data:`WARP_ROOT_PREFIXES` is + classified as ``WARP``. Tasks registered against ``isaaclab.envs.*`` + (the standard manager-based and direct env classes) are classified + as ``TORCH``; those env classes use ``FactoryBase`` to dispatch on + the active physics backend at construction time, so PhysX and Newton + physics both flow through the torch runtime path. + """ + + TORCH = "torch" + WARP = "warp" + UNKNOWN = "unknown" + + +class Severity(str, Enum): + """Severity of a compatibility :class:`Issue`.""" + + BLOCKING = "blocking" + """Frontend cannot build the env. :meth:`Frontend.build` raises.""" + WARNING = "warning" + """Surfaced to the user but not fatal (e.g. a term was dropped).""" + + +# --------------------------------------------------------------------------- +# Records +# --------------------------------------------------------------------------- + + +@dataclass +class TaskMeta: + """Static description of a registered gym task, produced by :class:`TaskResolver`.""" + + task_id: str + """Gym task id, e.g. ``Isaac-Cartpole-v0``.""" + spec: Any + """The :class:`gymnasium.envs.registration.EnvSpec` returned by ``gym.spec``.""" + cfg_class: type + """Concrete cfg type passed to the frontend.""" + workflow: Workflow + """Manager-based / direct / direct-marl.""" + runtime: Runtime + """Runtime the task is registered against (independent of the frontend asked for).""" + + @property + def env_cfg_entry_point(self) -> str | None: + """Module path of the cfg class as registered in ``spec.kwargs``.""" + return self.spec.kwargs.get("env_cfg_entry_point") if self.spec is not None else None + + @property + def entry_point(self) -> Any: + """Env class entry point as registered (string or class).""" + return self.spec.entry_point if self.spec is not None else None + + +@dataclass +class Issue: + """An incompatibility surfaced by a rule.""" + + rule: str + """Rule that produced this issue (matches :attr:`CompatRule.name`).""" + severity: Severity + message: str + """One-line human-readable description.""" + location: str = "" + """Optional cfg path the issue was found at (e.g. ``rewards.foo``).""" + detail: dict[str, Any] = field(default_factory=dict) + """Free-form rule-specific data (searched modules, expected names, ...).""" + + +@dataclass +class Change: + """A transformation a rule applied to the cfg.""" + + rule: str + description: str + + +@dataclass +class Report: + """Outcome of a frontend's rule pipeline.""" + + frontend: str + """Name of the frontend that produced this report.""" + task: TaskMeta + rules_run: list[str] = field(default_factory=list) + issues: list[Issue] = field(default_factory=list) + changes: list[Change] = field(default_factory=list) + + @property + def blocking(self) -> list[Issue]: + return [i for i in self.issues if i.severity == Severity.BLOCKING] + + def has_blocking(self) -> bool: + return any(i.severity == Severity.BLOCKING for i in self.issues) + + def __bool__(self) -> bool: + return bool(self.changes) or bool(self.issues) + + def format(self) -> str: + lines = [ + f"Frontend {self.frontend!r} on task {self.task.task_id!r}" + f" ({self.task.workflow.value} / registered runtime {self.task.runtime.value})" + ] + if self.changes: + lines.append(f" changes ({len(self.changes)}):") + lines.extend(f" [{c.rule}] {c.description}" for c in self.changes) + if self.issues: + lines.append(f" issues ({len(self.issues)}):") + for i in self.issues: + head = f" [{i.severity.value}/{i.rule}]" + where = f" {i.location}" if i.location else "" + lines.append(f"{head}{where} {i.message}") + return "\n".join(lines) + + +@dataclass +class ResolveContext: + """Per-call context handed to rules.""" + + frontend: str + """Name of the running frontend.""" + task: TaskMeta + strict: bool = False + """When True, rules may escalate warnings to blocking issues.""" + + +# --------------------------------------------------------------------------- +# Exceptions +# --------------------------------------------------------------------------- + + +class FrontendIncompatibleError(RuntimeError): + """Raised when a frontend cannot build the requested (task, cfg) pair.""" + + def __init__(self, message: str, report: Report | None = None): + super().__init__(message) + self.report = report + + +# --------------------------------------------------------------------------- +# CompatRule +# --------------------------------------------------------------------------- + + +class CompatRule(ABC): + """A single check / transform applied during frontend resolution. + + A rule's :meth:`run` method may yield :class:`Issue` records (the rule + detected an incompatibility), :class:`Change` records (the rule mutated + the cfg), or both. Pure-check and pure-transform rules are common; mixed + rules are useful when a transformation has a partial-failure mode (e.g. + a name swap that found 5 of 6 twins). + + Subclass and: + + * Set :attr:`name` to a short identifier used in the report. + * Implement :meth:`run` to do the work. + * Override :meth:`applies_to` to skip the rule when irrelevant. + """ + + name: ClassVar[str] + + def applies_to(self, ctx: ResolveContext) -> bool: + """Return True if this rule should run on the given context. + + Default: always applies. Override to scope by ``ctx.task.workflow``, + ``ctx.task.runtime``, ``ctx.frontend``, etc. + """ + return True + + @abstractmethod + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + """Inspect / mutate ``cfg`` and yield :class:`Issue` / :class:`Change` records.""" + + +# --------------------------------------------------------------------------- +# TaskResolver +# --------------------------------------------------------------------------- + + +class TaskResolver: + """Inspect a registered gym task and classify its workflow + runtime. + + All rules and frontends should call :meth:`resolve` rather than reading + ``gym.spec`` directly. Centralising the read keeps registration-format + knowledge in one place. + """ + + @classmethod + def resolve(cls, task_id: str, cfg: Any) -> TaskMeta: + """Return a :class:`TaskMeta` for ``(task_id, cfg)``.""" + import gymnasium as gym + + try: + spec = gym.spec(task_id) + except gym.error.NameNotFound: + spec = None + return TaskMeta( + task_id=task_id, + spec=spec, + cfg_class=type(cfg), + workflow=cls._classify_workflow(cfg), + runtime=cls._classify_runtime(spec), + ) + + @staticmethod + def _classify_workflow(cfg: Any) -> Workflow: + from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg + + if isinstance(cfg, ManagerBasedRLEnvCfg): + return Workflow.MANAGER_BASED + if isinstance(cfg, DirectMARLEnvCfg): + return Workflow.DIRECT_MARL + if isinstance(cfg, DirectRLEnvCfg): + return Workflow.DIRECT + raise FrontendIncompatibleError( + f"Cfg type {type(cfg).__name__!r} is not a recognised env cfg" + f" (expected ManagerBasedRLEnvCfg / DirectRLEnvCfg / DirectMARLEnvCfg subclass)." + ) + + @staticmethod + def _classify_runtime(spec: Any) -> Runtime: + if spec is None: + return Runtime.UNKNOWN + ep = spec.entry_point + if isinstance(ep, str): + if ep.startswith(WARP_ROOT_PREFIXES): + return Runtime.WARP + if ep.startswith(("isaaclab.envs", "isaaclab_tasks")): + return Runtime.TORCH + return Runtime.UNKNOWN + + +# --------------------------------------------------------------------------- +# Frontend +# --------------------------------------------------------------------------- + + +class Frontend(ABC): + """User-facing runtime selector. + + Subclasses declare: + + * :attr:`name`: CLI identifier used by ``--frontend`` and the registry. + * :attr:`rules`: rule classes the pipeline instantiates by default. + * :meth:`construct`: how to build the env once rules pass. + + Subclasses may also override: + + * :meth:`preprocess_hydra_args`: CLI-time Hydra arg munging (e.g. inject + a preset selection so Hydra resolves ``PresetCfg`` to the right field + before the cfg ever reaches us). + * :meth:`preprocess_cfg`: cfg pre-processing run before rules. + """ + + name: ClassVar[str] + rules: ClassVar[tuple[type[CompatRule], ...]] = () + + def __init__(self, rules: Iterable[CompatRule] | None = None, strict: bool = False): + self._rules: list[CompatRule] = [r() for r in type(self).rules] if rules is None else list(rules) + self.strict = strict + + # -- public --------------------------------------------------------------- + + def build(self, cfg: Any, task_id: str, **construct_kwargs: Any) -> Any: + """Resolve the task, run rules, and construct the env. + + Raises :class:`FrontendIncompatibleError` if any rule emits a + :class:`Severity.BLOCKING` issue. The returned env carries the + :class:`Report` on ``env.unwrapped.frontend_report`` for inspection. + """ + report = self.resolve(cfg, task_id) + self._log_report(report) + if report.has_blocking(): + raise FrontendIncompatibleError( + f"Frontend {self.name!r} cannot build {task_id!r}:\n{report.format()}", + report=report, + ) + env = self.construct(cfg, report.task, **construct_kwargs) + env.unwrapped.frontend_report = report + return env + + def resolve(self, cfg: Any, task_id: str) -> Report: + """Run the rule pipeline; mutate ``cfg`` in place; return a :class:`Report`. + + Use this directly for dry-run validation (tests, CLI ``--check``). + """ + meta = TaskResolver.resolve(task_id, cfg) + ctx = ResolveContext(frontend=self.name, task=meta, strict=self.strict) + report = Report(frontend=self.name, task=meta) + self.preprocess_cfg(cfg, ctx) + for rule in self._rules: + if not rule.applies_to(ctx): + continue + report.rules_run.append(rule.name) + for record in rule.run(cfg, ctx): + if isinstance(record, Issue): + report.issues.append(record) + elif isinstance(record, Change): + report.changes.append(record) + else: + raise TypeError(f"Rule {rule.name!r} yielded {type(record).__name__}; expected Issue or Change.") + return report + + # -- subclass hooks ------------------------------------------------------- + + @abstractmethod + def construct(self, cfg: Any, meta: TaskMeta, **kwargs: Any) -> Any: + """Build the env. Called only when no blocking issues were raised.""" + + def preprocess_cfg(self, cfg: Any, ctx: ResolveContext) -> None: + """Subclass hook for cfg pre-processing run before rules. Default: no-op.""" + + def preprocess_hydra_args(self, task_id: str, args: list[str]) -> list[str]: + """Subclass hook for CLI-time Hydra arg munging. Default: no-op. + + Called from the train script so frontends can inject preset + selections (or refuse incompatible ones) before Hydra builds the + cfg. Returns the (possibly modified) args list. + """ + return args + + # -- helpers -------------------------------------------------------------- + + def _log_report(self, report: Report) -> None: + if not report: + return + level = logging.ERROR if report.has_blocking() else logging.WARNING + logger.log(level, report.format()) + + +# --------------------------------------------------------------------------- +# Registry +# --------------------------------------------------------------------------- + + +_REGISTRY: dict[str, type[Frontend]] = {} + + +def register_frontend(name: str, cls: type[Frontend]) -> None: + """Register a frontend implementation under ``name``. + + The CLI ``--frontend`` flag and :func:`get_frontend` look up by this name. + Re-registering the same class is idempotent; re-registering a different + class raises :class:`ValueError`. + """ + existing = _REGISTRY.get(name) + if existing is not None and existing is not cls: + raise ValueError( + f"Frontend {name!r} is already registered to {existing.__name__};" + f" refusing to re-register to {cls.__name__}." + ) + _REGISTRY[name] = cls + + +def get_frontend(name: str, **kwargs: Any) -> Frontend: + """Look up a frontend by name and return a fresh instance. + + Extra kwargs are forwarded to :meth:`Frontend.__init__` (e.g. ``strict=True``). + """ + try: + cls = _REGISTRY[name] + except KeyError as exc: + raise ValueError(f"Unknown frontend {name!r}; available: {available_frontends()}.") from exc + return cls(**kwargs) + + +def available_frontends() -> list[str]: + """Return registered frontend names, sorted.""" + return sorted(_REGISTRY) + + +# --------------------------------------------------------------------------- +# Helpers shared by rules +# --------------------------------------------------------------------------- + + +def walk_attrs(root: Any, path: tuple[str, ...]) -> Any: + """Walk ``root.....`` returning ``None`` on any miss.""" + node = root + for attr in path: + node = getattr(node, attr, None) + if node is None: + return None + return node + + +def resolve_warp_twin(name: str, modules: Iterable[Any]) -> Any | None: + """Return ``name`` from ``modules`` if its ``__module__`` lives under a warp prefix.""" + for module in modules: + candidate = getattr(module, name, None) + if candidate is None: + continue + origin = getattr(candidate, "__module__", "") or "" + if origin.startswith(WARP_ROOT_PREFIXES): + return candidate + return None + + +def iter_term_attrs(group: Any) -> Iterator[tuple[str, Any]]: + """Yield ``(name, term)`` pairs from a manager-cfg group, skipping dunders.""" + if group is None: + return + for name in [n for n in dir(group) if not n.startswith("_")]: + term = getattr(group, name, None) + if term is None: + continue + yield name, term diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py new file mode 100644 index 000000000000..1c4054e79cda --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py @@ -0,0 +1,72 @@ +# 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 + +"""Torch (default) frontend. + +The torch frontend is a thin wrapper around :func:`gym.make`. It does not +mutate the cfg — the standard ``isaaclab.envs.*`` env classes use +``FactoryBase`` to dispatch on the active physics backend at construction +time, so PhysX and Newton physics both run through this single path. + +Its rule set is small: one warning when the user asks for the torch +frontend on a task that's *registered* against the warp runtime +(``entry_point`` under :data:`WARP_ROOT_PREFIXES`). That's a contradiction +of intent — the env class is a warp env regardless of the frontend flag — +so we surface it but don't block. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from typing import Any + +from .base import ( + Change, + CompatRule, + Frontend, + Issue, + ResolveContext, + Runtime, + Severity, + TaskMeta, +) + + +class WarnIfTaskIsWarpRegistered(CompatRule): + """Warn when a warp-registered task is asked to run on the torch frontend. + + The env class itself is a warp implementation; ``--frontend=torch`` will + still happily build it via ``gym.make`` (since the entry-point class is + what runs), but the user's stated intent says torch. We emit a warning + so the contradiction is visible. + """ + + name = "warn_if_task_is_warp_registered" + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + if ctx.task.runtime == Runtime.WARP: + yield Issue( + rule=self.name, + severity=Severity.WARNING, + message=( + f"task is registered against the warp runtime" + f" (entry_point={ctx.task.entry_point!r}); --frontend=torch" + f" will still build the warp env class. Consider --frontend=warp." + ), + location="task.entry_point", + detail={"runtime": ctx.task.runtime.value}, + ) + + +class TorchFrontend(Frontend): + """Default frontend: ``gym.make`` against the registered ``entry_point``.""" + + name = "torch" + rules = (WarnIfTaskIsWarpRegistered,) + + def construct(self, cfg: Any, meta: TaskMeta, **kwargs: Any) -> Any: + import gymnasium as gym + + return gym.make(meta.task_id, cfg=cfg, **kwargs) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py new file mode 100644 index 000000000000..1ce0c5b21704 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py @@ -0,0 +1,453 @@ +# 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 + +"""Warp frontend. + +Routes a stable manager-based task cfg onto :class:`ManagerBasedRLEnvWarp` +by running a pluggable :class:`CompatRule` pipeline. Direct envs encode +their runtime in the env class itself (each warp direct env is its own +class), so for direct cfgs the frontend just verifies the registered +entry-point lives under :data:`WARP_ROOT_PREFIXES` and forwards to +:func:`gym.make`. + +Rule pipeline (manager-based path): + +* :class:`CheckPhysicsIsNewton` — blocking issue if ``cfg.sim.physics`` + is PhysX-flavoured, since the warp runtime needs Newton physics. +* :class:`ResolvePhysicsPreset` — collapses ``PresetCfg`` wrappers (no-op + when Hydra already did so). +* :class:`DropUnsupportedSensors` — removes sensors warp can't run yet. +* :class:`PromoteSceneEntityCfg` — in-place class promotion to the warp + variant so warp mdp kernels see ``joint_mask`` / ``joint_ids_wp``. +* :class:`SwapMdpFunctions` — name-based ``term.func`` replacement against + the warp ``mdp`` modules. +* :class:`SwapActionClassType` — strict swap of action ``class_type`` to + the warp twin. +* :class:`VerifyDirectIsWarp` — only fires for direct cfgs; blocks if + the registered entry-point isn't a warp class. +""" + +from __future__ import annotations + +import importlib +import logging +from collections.abc import Iterable +from types import ModuleType +from typing import Any, ClassVar + +from .base import ( + WARP_ROOT_PREFIXES, + Change, + CompatRule, + Frontend, + FrontendIncompatibleError, + Issue, + ResolveContext, + Runtime, + Severity, + TaskMeta, + Workflow, + iter_term_attrs, + resolve_warp_twin, + walk_attrs, +) + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Rules +# --------------------------------------------------------------------------- + + +class CheckPhysicsIsNewton(CompatRule): + """Block if ``cfg.sim.physics`` isn't Newton. + + The warp runtime resolves asset / sensor ``class_type`` via the active + physics backend's module tree (``isaaclab_newton.*`` for Newton, + ``isaaclab_physx.*`` for PhysX). Loading a PhysX class under the warp + runtime fails on ``omni.physics.tensors.api`` (a Kit module the warp + runtime doesn't initialise), so a PhysX physics cfg is fundamentally + incompatible with this frontend. + + Hydra's preset resolution + :meth:`WarpFrontend.preprocess_hydra_args` + normally collapse ``PresetCfg`` wrappers to the ``newton`` field + before this rule runs; we still check, so a programmatic caller or a + misconfigured task fails fast and loudly here instead of crashing + deep in scene init. + """ + + name = "check_physics_is_newton" + + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.MANAGER_BASED + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + physics = getattr(getattr(cfg, "sim", None), "physics", None) + if physics is None: + return + cls = type(physics) + module = getattr(cls, "__module__", "") or "" + # Skip PresetCfg wrappers — they'll be unwrapped by ResolvePhysicsPreset. + if hasattr(physics, "newton") and not hasattr(physics, "class_type"): + return + if module.startswith("isaaclab_physx"): + yield Issue( + rule=self.name, + severity=Severity.BLOCKING, + message=( + f"sim.physics is {cls.__name__} ({module}); the warp runtime" + f" needs Newton physics. Pass `presets=newton` or use a Newton" + f" physics cfg explicitly." + ), + location="cfg.sim.physics", + detail={"physics_class": cls.__name__, "physics_module": module}, + ) + + +class ResolvePhysicsPreset(CompatRule): + """Collapse ``cfg.sim.physics`` from ``PresetCfg`` to its ``newton`` field. + + Hydra's preset resolution normally collapses the wrapper before the + frontend runs. This rule covers the residual case of programmatic use + of :meth:`Frontend.build` without Hydra, and custom physics cfgs that + still expose a ``newton`` attribute. + """ + + name = "resolve_physics_preset" + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + physics = getattr(getattr(cfg, "sim", None), "physics", None) + if physics is None or not hasattr(physics, "newton"): + return + cfg.sim.physics = physics.newton + yield Change( + rule=self.name, + description=f"sim.physics → {type(physics.newton).__name__}", + ) + + +class DropUnsupportedSensors(CompatRule): + """Drop scene sensors the warp runtime can't run yet. + + Default: ``("height_scanner",)``. Pass ``sensors=...`` at construction + time to override. + """ + + name = "drop_unsupported_sensors" + + def __init__(self, sensors: Iterable[str] = ("height_scanner",)): + self.sensors = tuple(sensors) + + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.MANAGER_BASED + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + scene = getattr(cfg, "scene", None) + if scene is None: + return + for sensor in self.sensors: + if getattr(scene, sensor, None) is not None: + setattr(scene, sensor, None) + yield Change(rule=self.name, description=f"scene.{sensor} → None") + + +class PromoteSceneEntityCfg(CompatRule): + """Promote :class:`SceneEntityCfg` instances under term params to the warp variant. + + The warp variant adds cached ``joint_mask`` / ``joint_ids_wp`` / + ``body_ids_wp`` fields that the warp mdp kernels read after + :meth:`resolve`. The class hierarchy is asserted at apply time — if + the warp class no longer subclasses the stable class, the rule raises + :class:`FrontendIncompatibleError` so the in-place ``__class__`` + promotion can never silently corrupt instances. + """ + + name = "promote_scene_entity_cfg" + + GROUPS: ClassVar[tuple[tuple[str, ...], ...]] = ( + ("observations", "policy"), + ("events",), + ("rewards",), + ("terminations",), + ("commands",), + ("curriculum",), + ("actions",), + ) + + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.MANAGER_BASED + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as Stable + + from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as Warp + + if not issubclass(Warp, Stable): + raise FrontendIncompatibleError( + f"Warp SceneEntityCfg must subclass stable SceneEntityCfg; got mro {[c.__name__ for c in Warp.__mro__]}" + ) + + promoted = 0 + for path in self.GROUPS: + group = walk_attrs(cfg, path) + if group is None: + continue + for _name, term in iter_term_attrs(group): + params = getattr(term, "params", None) + if not isinstance(params, dict): + continue + for value in params.values(): + if isinstance(value, Warp) or not isinstance(value, Stable): + continue + value.__class__ = Warp + value.joint_mask = None + value.joint_ids_wp = None + value.body_ids_wp = None + promoted += 1 + if promoted: + yield Change( + rule=self.name, + description=f"promoted {promoted} SceneEntityCfg instance(s) to warp variant", + ) + + +class SwapMdpFunctions(CompatRule): + """Replace ``term.func`` with the same-named callable from warp ``mdp`` modules. + + Walks observation / event / reward / termination / command / curriculum + groups. A re-export from stable code is rejected by checking + ``__module__``. Missing twins are dropped (term set to ``None``) and + surfaced as :attr:`Severity.WARNING`; in strict mode they're escalated + to :attr:`Severity.BLOCKING`. + """ + + name = "swap_mdp_functions" + + GROUPS: ClassVar[tuple[tuple[str, ...], ...]] = ( + ("observations", "policy"), + ("events",), + ("rewards",), + ("terminations",), + ("commands",), + ("curriculum",), + ) + + def __init__( + self, + stable_root: str = "isaaclab_tasks", + warp_root: str = "isaaclab_tasks_experimental", + fallback_mdp: str = "isaaclab_experimental.envs.mdp", + ): + self.stable_root = stable_root + self.warp_root = warp_root + self.fallback_mdp = fallback_mdp + + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.MANAGER_BASED + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + modules = self._mdp_modules(ctx.task) + logger.info("WarpFrontend: warp mdp modules → %s", [m.__name__ for m in modules]) + searched = tuple(m.__name__ for m in modules) + for path in self.GROUPS: + group = walk_attrs(cfg, path) + if group is None: + continue + location_prefix = ".".join(path) + for name, term in iter_term_attrs(group): + if not hasattr(term, "func"): + continue + stable = term.func + if not callable(stable): + continue + twin = resolve_warp_twin(stable.__name__, modules) + if twin is not None: + term.func = twin + continue + # No twin found: drop the term and report. + setattr(group, name, None) + yield Issue( + rule=self.name, + severity=Severity.BLOCKING if ctx.strict else Severity.WARNING, + message=(f"no warp twin for stable func={stable.__name__!r}; term dropped."), + location=f"{location_prefix}.{name}", + detail={"expected": stable.__name__, "searched": list(searched)}, + ) + + def _mdp_modules(self, task: TaskMeta) -> list[ModuleType]: + """Locate warp mdp modules that mirror the task's stable mdp.""" + modules: list[ModuleType] = [] + entry = task.env_cfg_entry_point + if isinstance(entry, str) and entry.startswith(self.stable_root): + warp_pkg = entry.rsplit(".", 1)[0].replace(self.stable_root, self.warp_root, 1) + parts = warp_pkg.split(".") + for depth in range(len(parts), 0, -1): + try: + modules.append(importlib.import_module(".".join(parts[:depth] + ["mdp"]))) + break + except ImportError: + continue + try: + modules.append(importlib.import_module(self.fallback_mdp)) + except ImportError: + logger.warning("WarpFrontend: fallback mdp module %r not importable", self.fallback_mdp) + return modules + + +class SwapActionClassType(CompatRule): + """Swap ``cfg.actions..class_type`` with the same-named warp class. + + Always strict at the term level: an action with no warp twin can't run + on the warp runtime, so a missing twin is :attr:`Severity.BLOCKING` + regardless of ``ctx.strict``. + """ + + name = "swap_action_class_type" + + def __init__(self, warp_actions_module: str = "isaaclab_experimental.envs.mdp.actions.joint_actions"): + self.warp_actions_module = warp_actions_module + + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.MANAGER_BASED + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + actions = getattr(cfg, "actions", None) + if actions is None: + return + try: + module = importlib.import_module(self.warp_actions_module) + except ImportError as exc: + yield Issue( + rule=self.name, + severity=Severity.BLOCKING, + message=(f"warp action module {self.warp_actions_module!r} not importable: {exc}"), + location="actions", + ) + return + searched = (module.__name__,) + for name, term in iter_term_attrs(actions): + if not hasattr(term, "class_type"): + continue + stable = term.class_type + if not callable(stable): + continue + twin = resolve_warp_twin(stable.__name__, [module]) + if twin is not None: + term.class_type = twin + continue + yield Issue( + rule=self.name, + severity=Severity.BLOCKING, + message=f"no warp twin for stable class_type={stable.__name__!r}", + location=f"actions.{name}", + detail={"expected": stable.__name__, "searched": list(searched)}, + ) + + +class VerifyDirectIsWarp(CompatRule): + """For direct envs, block if the registered entry-point isn't a warp class. + + Direct envs encode their runtime in the env class itself (each warp + direct env is a separate class with its own kernels), so the warp + frontend can't *adapt* a stable direct cfg — it can only refuse it + with a clear message. A direct task whose entry-point already lives + under :data:`WARP_ROOT_PREFIXES` is a pass-through. + """ + + name = "verify_direct_is_warp" + + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.DIRECT + + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: + if ctx.task.runtime == Runtime.WARP: + return + ep = ctx.task.entry_point + yield Issue( + rule=self.name, + severity=Severity.BLOCKING, + message=( + f"direct env entry_point {ep!r} is not a warp implementation." + f" --frontend=warp on a direct task requires the registered class to live under" + f" {list(WARP_ROOT_PREFIXES)} (e.g. *-Direct-Warp-v0)." + ), + location="task.entry_point", + detail={"entry_point": ep}, + ) + + +# --------------------------------------------------------------------------- +# WarpFrontend +# --------------------------------------------------------------------------- + + +class WarpFrontend(Frontend): + """Run a stable env cfg on the warp runtime. + + Manager-based cfgs get the full rule pipeline and are constructed on + :class:`ManagerBasedRLEnvWarp`. Direct cfgs run :class:`VerifyDirectIsWarp` + only and dispatch through :func:`gym.make`. + """ + + name = "warp" + rules = ( + CheckPhysicsIsNewton, + ResolvePhysicsPreset, + DropUnsupportedSensors, + PromoteSceneEntityCfg, + SwapMdpFunctions, + SwapActionClassType, + VerifyDirectIsWarp, + ) + + # -- construction --------------------------------------------------------- + + def construct(self, cfg: Any, meta: TaskMeta, **kwargs: Any) -> Any: + if meta.workflow == Workflow.MANAGER_BASED: + from isaaclab_experimental.envs import ManagerBasedRLEnvWarp + + return ManagerBasedRLEnvWarp(cfg=cfg, **kwargs) + if meta.workflow == Workflow.DIRECT: + import gymnasium as gym + + return gym.make(meta.task_id, cfg=cfg, **kwargs) + raise FrontendIncompatibleError( + f"WarpFrontend does not support workflow {meta.workflow.value!r} (task {meta.task_id!r})." + ) + + # -- CLI hook ------------------------------------------------------------- + + def preprocess_hydra_args(self, task_id: str, args: list[str]) -> list[str]: + """Inject ``presets=newton`` for stable manager-based tasks. + + Hydra resolves ``presets=...`` *before* the frontend runs, so the + injection has to happen at the CLI layer. We only inject for tasks + whose ``env_cfg_entry_point`` is under ``isaaclab_tasks.manager_based``; + other tasks (direct, pre-warp ``*-Warp-v0``) don't carry a preset + system and would error out. + + If the user already passed an explicit ``presets=`` we don't override, + but we warn when their preset isn't ``newton``. + """ + import gymnasium as gym + + try: + spec = gym.spec(task_id) + except gym.error.NameNotFound: + return args + cfg_ep = spec.kwargs.get("env_cfg_entry_point") + if not isinstance(cfg_ep, str) or not cfg_ep.startswith("isaaclab_tasks.manager_based"): + return args + explicit = next((a for a in args if a.startswith("presets=")), None) + if explicit is None: + return [*args, "presets=newton"] + if explicit != "presets=newton": + logger.warning( + "--frontend=warp on %r expects presets=newton; got %r — adapter may fail.", + task_id, + explicit, + ) + return args diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py deleted file mode 100644 index 23ea519f7cea..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/warp_frontend.py +++ /dev/null @@ -1,557 +0,0 @@ -# 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 - -"""Run a stable env cfg on the warp runtime via a pluggable rule pipeline. - -The frontend classifies the cfg as manager-based or direct, runs the -applicable :class:`CompatRule` instances against it, and constructs the -matching warp env class. New incompatibilities (e.g. a new sensor type warp -can't run, a new term-cfg field that needs upgrading) are added by writing a -small :class:`CompatRule` subclass and passing it through the constructor — -no surgery in the dispatcher. - -Module-level imports are deliberately limited to lightweight stdlib modules. -Warp library imports fire only inside :meth:`WarpFrontend.build`, which must -be called *after* :class:`SimulationApp` is alive, otherwise warp's lib load -races with Kit's USD/pxr extension initialisation. -""" - -from __future__ import annotations - -import importlib -import logging -from abc import ABC, abstractmethod -from collections.abc import Iterable, Sequence -from dataclasses import dataclass, field -from enum import Enum -from types import ModuleType -from typing import Any, ClassVar - -logger = logging.getLogger(__name__) - - -# --------------------------------------------------------------------------- -# Compatibility-rule framework -# --------------------------------------------------------------------------- - - -class CfgKind(str, Enum): - """Workflow type of an env cfg the frontend is asked to adapt.""" - - MANAGER_BASED = "manager_based" - DIRECT = "direct" - - -_BOTH = frozenset({CfgKind.MANAGER_BASED, CfgKind.DIRECT}) -_MANAGER_ONLY = frozenset({CfgKind.MANAGER_BASED}) - -_WARP_MODULE_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") -"""Module-path prefixes that distinguish a real warp twin from a stable -re-export. The warp ``mdp`` packages do ``from isaaclab.envs.mdp import *``, -so a plain ``getattr`` lookup can return the stable symbol untouched.""" - -_TERM_GROUPS_FOR_PROMOTION: tuple[tuple[str, ...], ...] = ( - ("observations", "policy"), - ("events",), - ("rewards",), - ("terminations",), - ("commands",), - ("curriculum",), - ("actions",), -) -"""Cfg groups walked when promoting :class:`SceneEntityCfg` instances. Includes -``actions`` because action params often carry a :class:`SceneEntityCfg`.""" - - -class IncompatibleEnvError(RuntimeError): - """Raised when the frontend can't run on the given cfg / task pair.""" - - def __init__(self, message: str, report: CompatReport | None = None): - super().__init__(message) - self.report = report - - -@dataclass -class CompatIssue: - """One thing the adapter looked for but couldn't resolve to a warp twin.""" - - rule: str - """Rule that produced this issue (matches :attr:`CompatRule.name`).""" - location: str - """Cfg path the issue was found at, e.g. ``rewards`` / ``actions``.""" - item: str - """Attribute name on the group, e.g. ``track_lin_vel_xy_exp``.""" - expected: str - """The symbol the rule searched for (the stable ``__name__``).""" - searched: tuple[str, ...] - """Module dotted-paths inspected, in order.""" - action: str - """Outcome: ``"dropped"``, ``"raised"``, or ``"left-stable"``.""" - - -@dataclass -class CompatReport: - """Outcome of running the rule pipeline against a cfg. - - ``changes`` is a human-readable list of mutations applied; ``issues`` - records every term the adapter couldn't resolve. A clean run has both - empty. - """ - - rules_applied: list[str] = field(default_factory=list) - changes: list[str] = field(default_factory=list) - issues: list[CompatIssue] = field(default_factory=list) - - def has_issues(self) -> bool: - return bool(self.issues) - - def has_fatal(self) -> bool: - return any(i.action == "raised" for i in self.issues) - - def __bool__(self) -> bool: - return bool(self.issues) or bool(self.changes) - - def format(self) -> str: - lines: list[str] = [] - if self.changes: - lines.append(f"WarpFrontend applied {len(self.changes)} change(s):") - lines.extend(f" - {c}" for c in self.changes) - if self.issues: - lines.append(f"WarpFrontend has {len(self.issues)} unresolved item(s):") - for i in self.issues: - lines.append( - f" - [{i.rule}] {i.location}.{i.item}: expected {i.expected!r}" - f" (searched {list(i.searched)}) → {i.action}" - ) - return "\n".join(lines) if lines else "WarpFrontend: no changes." - - -@dataclass -class AdaptContext: - """Per-call context handed to each rule.""" - - task_id: str - kind: CfgKind - strict: bool - - -class CompatRule(ABC): - """One step in the warp adaptation pipeline. - - A rule mutates ``cfg`` in place and appends to ``report``. To handle a - new incompatibility, subclass and implement :meth:`apply`. Rules declare - which workflow they apply to via :attr:`applies_to`; the pipeline skips - any rule whose ``applies_to`` doesn't include the cfg kind. - """ - - name: ClassVar[str] - applies_to: ClassVar[frozenset[CfgKind]] - - @abstractmethod - def apply(self, cfg: Any, ctx: AdaptContext, report: CompatReport) -> None: - """Mutate ``cfg`` in place and append issues / changes to ``report``.""" - - -# --------------------------------------------------------------------------- -# Helpers shared by rules -# --------------------------------------------------------------------------- - - -def _walk(root: Any, path: tuple[str, ...]) -> Any: - node = root - for attr in path: - node = getattr(node, attr, None) - if node is None: - return None - return node - - -def _resolve_warp_twin(name: str, modules: Sequence[ModuleType]) -> Any | None: - """Return ``name`` from ``modules`` if it lives under a warp prefix, else None.""" - for module in modules: - candidate = getattr(module, name, None) - if candidate is None: - continue - origin = getattr(candidate, "__module__", "") or "" - if origin.startswith(_WARP_MODULE_PREFIXES): - return candidate - return None - - -def _swap_named_attr( - group: Any, - location: str, - attr: str, - modules: Sequence[ModuleType], - *, - rule: str, - strict: bool, - report: CompatReport, -) -> None: - """Replace ``term.`` with the same-named callable from ``modules``. - - For each public attribute on ``group`` whose value has a callable ``attr`` - field, find a same-named symbol in ``modules`` whose ``__module__`` lives - under :data:`_WARP_MODULE_PREFIXES` and assign it. If no twin is found, - drop the term (set to ``None``) when ``strict`` is False, raise - :class:`LookupError` when True. Either way append a :class:`CompatIssue`. - """ - if group is None: - return - searched = tuple(m.__name__ for m in modules) - # Snapshot the attribute names so mutating ``group`` mid-loop is safe. - for name in [n for n in dir(group) if not n.startswith("_")]: - term = getattr(group, name, None) - if term is None or not hasattr(term, attr): - continue - stable = getattr(term, attr) - if not callable(stable): - continue - twin = _resolve_warp_twin(stable.__name__, modules) - if twin is not None: - setattr(term, attr, twin) - continue - issue = CompatIssue( - rule=rule, - location=location, - item=name, - expected=stable.__name__, - searched=searched, - action="raised" if strict else "dropped", - ) - report.issues.append(issue) - if strict: - raise LookupError( - f"WarpFrontend: cannot adapt {location}.{name} — no warp twin for " - f"stable {attr}={stable.__name__!r}. Searched {list(searched)}." - ) - setattr(group, name, None) - - -# --------------------------------------------------------------------------- -# Concrete rules -# --------------------------------------------------------------------------- - - -class ResolvePhysicsPresetRule(CompatRule): - """Collapse ``cfg.sim.physics`` from a :class:`PresetCfg` to its ``newton`` field. - - Hydra's preset resolution normally collapses the wrapper before the - frontend runs. This rule covers two residual cases: programmatic use of - :meth:`WarpFrontend.adapt` (no Hydra), and custom physics cfgs that still - expose a ``newton`` attribute. - """ - - name = "resolve_physics_preset" - applies_to = _BOTH - - def apply(self, cfg, ctx, report): - physics = getattr(getattr(cfg, "sim", None), "physics", None) - if physics is not None and hasattr(physics, "newton"): - cfg.sim.physics = physics.newton - report.changes.append(f"sim.physics → {type(physics.newton).__name__}") - - -class DropUnsupportedSensorsRule(CompatRule): - """Drop scene sensors the warp runtime can't run yet.""" - - name = "drop_unsupported_sensors" - applies_to = _BOTH - - def __init__(self, sensors: Iterable[str] = ("height_scanner",)): - self.sensors = tuple(sensors) - - def apply(self, cfg, ctx, report): - scene = getattr(cfg, "scene", None) - if scene is None: - return - for sensor in self.sensors: - if getattr(scene, sensor, None) is not None: - setattr(scene, sensor, None) - report.changes.append(f"scene.{sensor} → None") - - -class PromoteSceneEntityCfgRule(CompatRule): - """Promote :class:`SceneEntityCfg` instances under term params to the warp variant. - - The warp variant adds cached ``joint_mask`` / ``joint_ids_wp`` / - ``body_ids_wp`` fields the warp mdp kernels read after :meth:`resolve`. - The class hierarchy is asserted at apply time — if the warp class no - longer subclasses the stable class (refactor or divergence), the rule - raises :class:`TypeError` so the assumption can never silently corrupt - instances. - """ - - name = "promote_scene_entity_cfg" - applies_to = _MANAGER_ONLY - - def apply(self, cfg, ctx, report): - from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _StableSE - - from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSE - - if not issubclass(_WarpSE, _StableSE): - raise TypeError( - "PromoteSceneEntityCfgRule requires the warp SceneEntityCfg to subclass the stable one;" - f" got mro {[c.__name__ for c in _WarpSE.__mro__]}" - ) - - promoted = 0 - for path in _TERM_GROUPS_FOR_PROMOTION: - group = _walk(cfg, path) - if group is None: - continue - for name in (n for n in dir(group) if not n.startswith("_")): - term = getattr(group, name, None) - if term is None: - continue - params = getattr(term, "params", None) - if not isinstance(params, dict): - continue - for value in params.values(): - if isinstance(value, _WarpSE) or not isinstance(value, _StableSE): - continue - value.__class__ = _WarpSE - value.joint_mask = None - value.joint_ids_wp = None - value.body_ids_wp = None - promoted += 1 - if promoted: - report.changes.append(f"promoted {promoted} SceneEntityCfg instance(s) to warp variant") - - -class SwapMdpFunctionsRule(CompatRule): - """Replace ``term.func`` with the same-named callable from warp ``mdp`` modules. - - Walks observation / event / reward / termination / command / curriculum - groups. A re-export from stable code is rejected by checking - ``__module__``. Missing twins are dropped (term set to ``None``) unless - the context is strict, in which case they raise. - """ - - name = "swap_mdp_functions" - applies_to = _MANAGER_ONLY - - GROUPS: ClassVar[tuple[tuple[str, ...], ...]] = ( - ("observations", "policy"), - ("events",), - ("rewards",), - ("terminations",), - ("commands",), - ("curriculum",), - ) - - def __init__( - self, - stable_root: str = "isaaclab_tasks", - warp_root: str = "isaaclab_tasks_experimental", - fallback_mdp: str = "isaaclab_experimental.envs.mdp", - ): - self.stable_root = stable_root - self.warp_root = warp_root - self.fallback_mdp = fallback_mdp - - def apply(self, cfg, ctx, report): - modules = self._mdp_modules_for(ctx.task_id) - logger.info("WarpFrontend: warp mdp modules → %s", [m.__name__ for m in modules]) - for path in self.GROUPS: - group = _walk(cfg, path) - _swap_named_attr( - group, - location=".".join(path), - attr="func", - modules=modules, - rule=self.name, - strict=ctx.strict, - report=report, - ) - - def _mdp_modules_for(self, task_id: str) -> list[ModuleType]: - """Locate warp mdp modules that mirror the stable task's mdp. - - Convention: replace :attr:`stable_root` with :attr:`warp_root` in the - stable cfg's module path, walk up looking for an ``mdp`` sub-module on - the warp side, and always append :attr:`fallback_mdp` for cross-task - base terms. - """ - modules: list[ModuleType] = [] - try: - import gymnasium as gym - - entry = gym.spec(task_id).kwargs.get("env_cfg_entry_point") - except (KeyError, AttributeError, ModuleNotFoundError, gym.error.NameNotFound): - # Spec is missing / kwargs missing the entry — fall back to the - # package-wide warp mdp module only. Real ImportError from a - # broken cfg module is *not* swallowed; it propagates. - entry = None - if isinstance(entry, str) and entry.startswith(self.stable_root): - warp_pkg = entry.rsplit(".", 1)[0].replace(self.stable_root, self.warp_root, 1) - parts = warp_pkg.split(".") - for depth in range(len(parts), 0, -1): - try: - modules.append(importlib.import_module(".".join(parts[:depth] + ["mdp"]))) - break - except ImportError: - continue - try: - modules.append(importlib.import_module(self.fallback_mdp)) - except ImportError: - logger.warning("WarpFrontend: fallback mdp module %r not importable", self.fallback_mdp) - return modules - - -class SwapActionClassTypeRule(CompatRule): - """Swap ``cfg.actions..class_type`` with the same-named warp class. - - Always strict: an action with no warp class can't run on the warp - runtime, so a missing twin raises :class:`LookupError`. - """ - - name = "swap_action_class_type" - applies_to = _MANAGER_ONLY - - def __init__(self, warp_actions_module: str = "isaaclab_experimental.envs.mdp.actions.joint_actions"): - self.warp_actions_module = warp_actions_module - - def apply(self, cfg, ctx, report): - actions = getattr(cfg, "actions", None) - if actions is None: - return - try: - module = importlib.import_module(self.warp_actions_module) - except ImportError as exc: - raise IncompatibleEnvError( - f"WarpFrontend: warp action module {self.warp_actions_module!r} not importable" - ) from exc - _swap_named_attr( - actions, - location="actions", - attr="class_type", - modules=[module], - rule=self.name, - strict=True, - report=report, - ) - - -# --------------------------------------------------------------------------- -# Frontend -# --------------------------------------------------------------------------- - - -class WarpFrontend: - """Run a stable env cfg on the warp runtime via a pluggable rule pipeline. - - The frontend classifies the input cfg as manager-based or direct, runs - the applicable :class:`CompatRule` instances, then constructs the - matching warp env class. - - Direct envs encode their runtime in the env class itself (each warp - direct env is a separate class with its own kernels), so the frontend - doesn't transform direct cfgs — it only verifies the registered - ``entry_point`` lives under :data:`_WARP_MODULE_PREFIXES` and dispatches - via :func:`gym.make`. A stable direct cfg + ``--frontend=warp`` raises - :class:`IncompatibleEnvError` with a clear message. - - Example:: - - with launch_simulation(cfg, args_cli): - env = WarpFrontend().build(cfg, task_id=args_cli.task) - if env.unwrapped.warp_compat_report.has_issues(): - print(env.unwrapped.warp_compat_report.format()) - """ - - DEFAULT_RULES: ClassVar[tuple[type[CompatRule], ...]] = ( - ResolvePhysicsPresetRule, - DropUnsupportedSensorsRule, - PromoteSceneEntityCfgRule, - SwapMdpFunctionsRule, - SwapActionClassTypeRule, - ) - - def __init__(self, rules: Sequence[CompatRule] | None = None, strict: bool = False): - self.rules: list[CompatRule] = list(rules) if rules is not None else [r() for r in self.DEFAULT_RULES] - self.strict = strict - - # -- public --------------------------------------------------------------- - - def adapt(self, cfg: Any, task_id: str) -> CompatReport: - """Run the rule pipeline; mutate ``cfg`` in place; return a report. - - The report is logged at ``WARNING`` (or ``ERROR`` in strict mode when - any issue is fatal). Missing twins raise :class:`LookupError` only - when ``strict=True``. - """ - kind = self._classify(cfg) - ctx = AdaptContext(task_id=task_id, kind=kind, strict=self.strict) - report = CompatReport() - for rule in self.rules: - if kind not in rule.applies_to: - continue - rule.apply(cfg, ctx, report) - report.rules_applied.append(rule.name) - if report: - level = logging.ERROR if self.strict and report.has_fatal() else logging.WARNING - logger.log(level, report.format()) - return report - - def build(self, cfg: Any, task_id: str, render_mode: str | None = None): - """Adapt ``cfg`` and construct a warp env. - - Returns an env instance with ``warp_compat_report`` attached on the - unwrapped env. ``render_mode`` is forwarded so ``--video`` keeps - working when the frontend is selected at the train-script level. - """ - # Lazy: this is the first warp-lib load. The caller must already be - # inside the SimulationApp context (i.e. inside ``launch_simulation``). - from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg - - report = self.adapt(cfg, task_id) - if isinstance(cfg, ManagerBasedRLEnvCfg): - from isaaclab_experimental.envs import ManagerBasedRLEnvWarp - - env = ManagerBasedRLEnvWarp(cfg=cfg, render_mode=render_mode) - elif isinstance(cfg, DirectRLEnvCfg): - self._verify_direct_warp(task_id) - import gymnasium as gym - - env = gym.make(task_id, cfg=cfg, render_mode=render_mode) - else: - raise IncompatibleEnvError( - f"WarpFrontend supports ManagerBasedRLEnvCfg or DirectRLEnvCfg, got {type(cfg).__name__}", - report=report, - ) - env.unwrapped.warp_compat_report = report - return env - - # -- helpers -------------------------------------------------------------- - - @staticmethod - def _classify(cfg: Any) -> CfgKind: - from isaaclab.envs import DirectRLEnvCfg, ManagerBasedRLEnvCfg - - if isinstance(cfg, ManagerBasedRLEnvCfg): - return CfgKind.MANAGER_BASED - if isinstance(cfg, DirectRLEnvCfg): - return CfgKind.DIRECT - raise IncompatibleEnvError( - f"WarpFrontend supports ManagerBasedRLEnvCfg or DirectRLEnvCfg, got {type(cfg).__name__}" - ) - - @staticmethod - def _verify_direct_warp(task_id: str) -> None: - import gymnasium as gym - - try: - spec = gym.spec(task_id) - except gym.error.NameNotFound as exc: - raise IncompatibleEnvError(f"Task {task_id!r} is not registered with gymnasium") from exc - ep = spec.entry_point - if isinstance(ep, str) and not ep.startswith(_WARP_MODULE_PREFIXES): - raise IncompatibleEnvError( - f"Direct env {task_id!r} entry_point {ep!r} is not a warp implementation." - f" --frontend=warp on a direct task requires the registered class to live under" - f" {list(_WARP_MODULE_PREFIXES)} (e.g. *-Direct-Warp-v0)." - ) From 8934fe649a607bb066aab39abe7787a4264cc775 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 6 May 2026 07:52:27 +0000 Subject: [PATCH 08/36] Tighten frontend framework against review findings - SwapMdpFunctions: skip terms whose ``func.__module__`` is already under the warp prefixes. Without this, running the bridge against a task already registered under ``isaaclab_tasks_experimental`` (e.g. ``Isaac-Cartpole-Warp-v0 --frontend=warp``) would silently drop terms whose warp twin happens not to live in the resolved fallback module. Also tighten ``_mdp_modules`` to require the trailing dot when matching ``isaaclab_tasks`` so we don't double-replace the prefix and end up importing ``isaaclab_tasks_experimental_experimental.*``. - ResolvePhysicsPreset: scope to MANAGER_BASED via ``applies_to``. Direct cfgs aren't expected to carry ``PresetCfg`` wrappers; running this rule on them was a no-op but the scoping makes the contract explicit. - CheckPhysicsIsNewton: positively accept ``isaaclab_newton.*`` modules, block on ``isaaclab_physx.*``, warn on anything else. The previous rule only rejected PhysX, so a custom or third-party physics cfg in an unrelated module would slip through silently. - PromoteSceneEntityCfg: catch ``TypeError`` from the in-place ``__class__`` reassignment and surface it as a blocking issue. ``issubclass`` does not guarantee Python permits the layout change (slots, layout flags); failing loud at this seam is better than a cryptic crash mid-pipeline. - WarpFrontend.preprocess_hydra_args: normalise leading dashes when inspecting ``presets=``, so ``--presets=foo`` is treated the same as ``presets=foo`` (Hydra accepts both forms). - Frontend.resolve: hard-block when ``gym.spec`` returned no spec. Previously ``meta.runtime`` was ``UNKNOWN`` and ``construct`` would fail later with a less specific error; now the block fires before any rule runs. - train.py: import the frontend lazily and tolerate ``ImportError`` when ``--frontend=torch`` (the default). The experimental package is optional, so a missing install used to break the default path; now it falls back to ``gym.make`` for torch and only fails for ``warp``. - frontend/__init__.py: trim ``__all__`` and the wildcard re-export so helpers (``walk_attrs``, ``iter_term_attrs``, ``resolve_warp_twin``, ``WARP_ROOT_PREFIXES``) are no longer advertised as the public framework surface. They remain importable from ``frontend.base`` for users writing their own rules. --- .../reinforcement_learning/rsl_rl/train.py | 33 ++++++-- .../envs/frontend/__init__.py | 13 +-- .../envs/frontend/base.py | 16 ++++ .../envs/frontend/warp.py | 83 +++++++++++++++---- 4 files changed, 114 insertions(+), 31 deletions(-) diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index e146a0cc2575..e3801a08f88b 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -104,10 +104,26 @@ # may inject preset selections (e.g. WarpFrontend appends ``presets=newton`` # for stable manager-based tasks so PresetCfg wrappers resolve to the Newton # field before Hydra builds the cfg). -from isaaclab_experimental.envs.frontend import get_frontend # noqa: E402 - -_frontend = get_frontend(args_cli.frontend) -if args_cli.task is not None: +# +# The frontend package lives under ``isaaclab_experimental``, which is +# optional. If it isn't installed, ``--frontend=torch`` (the default) still +# needs to work — fall back to plain ``gym.make`` in that case. The warp +# selection requires the experimental package, so import failure there is +# fatal. +_frontend = None +try: + from isaaclab_experimental.envs.frontend import get_frontend # noqa: E402 + + _frontend = get_frontend(args_cli.frontend) +except ImportError as _frontend_import_err: + if args_cli.frontend != "torch": + raise SystemExit( + f"--frontend={args_cli.frontend} requires isaaclab_experimental to be installed," + f" but the import failed: {_frontend_import_err}" + ) from _frontend_import_err + logger.info("isaaclab_experimental not available; --frontend=torch will dispatch via plain gym.make.") + +if _frontend is not None and args_cli.task is not None: remaining_args = _frontend.preprocess_hydra_args(args_cli.task, remaining_args) sys.argv = [sys.argv[0]] + remaining_args @@ -198,9 +214,14 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # The frontend may mutate env_cfg in place (preset resolution, # SceneEntityCfg promotion, mdp twin swaps, ...) before constructing # the env. ``env.unwrapped.frontend_report`` carries what changed - # and what was missing. + # and what was missing. When the experimental frontend package isn't + # available we already validated --frontend=torch above, so a plain + # gym.make is the documented fallback. render_mode = "rgb_array" if args_cli.video else None - env = _frontend.build(env_cfg, task_id=args_cli.task, render_mode=render_mode) + if _frontend is not None: + env = _frontend.build(env_cfg, task_id=args_cli.task, render_mode=render_mode) + else: + env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render_mode) # convert to single-agent instance if required by the RL algorithm if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py index ad81605e6442..0f6e98b33974 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py @@ -24,7 +24,6 @@ from __future__ import annotations from .base import ( - WARP_ROOT_PREFIXES, Change, CompatRule, Frontend, @@ -39,10 +38,7 @@ Workflow, available_frontends, get_frontend, - iter_term_attrs, register_frontend, - resolve_warp_twin, - walk_attrs, ) from .torch import TorchFrontend, WarnIfTaskIsWarpRegistered from .warp import ( @@ -62,6 +58,10 @@ register_frontend(WarpFrontend.name, WarpFrontend) +# Public API. Internal helpers (``walk_attrs``, ``iter_term_attrs``, +# ``resolve_warp_twin``, ``WARP_ROOT_PREFIXES``) are importable from +# :mod:`isaaclab_experimental.envs.frontend.base` for users writing their own +# rules, but they are not advertised here as the supported framework surface. __all__ = [ # core abstractions "Frontend", @@ -76,15 +76,10 @@ "Runtime", "ResolveContext", "FrontendIncompatibleError", - "WARP_ROOT_PREFIXES", # registry "register_frontend", "get_frontend", "available_frontends", - # rule helpers - "walk_attrs", - "resolve_warp_twin", - "iter_term_attrs", # built-in frontends "TorchFrontend", "WarpFrontend", diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py index 81fc21a33cf7..dece605f3aaa 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py @@ -366,6 +366,22 @@ def resolve(self, cfg: Any, task_id: str) -> Report: meta = TaskResolver.resolve(task_id, cfg) ctx = ResolveContext(frontend=self.name, task=meta, strict=self.strict) report = Report(frontend=self.name, task=meta) + # If gym couldn't resolve the spec, the frontend has nothing to dispatch + # against. Block early with a clear message rather than letting + # downstream construct() fail with a NameNotFound. + if meta.spec is None: + report.issues.append( + Issue( + rule="task_resolver", + severity=Severity.BLOCKING, + message=( + f"task {task_id!r} is not registered with gymnasium." + " Make sure the task package is imported before the frontend runs." + ), + location="task.spec", + ) + ) + return report self.preprocess_cfg(cfg, ctx) for rule in self._rules: if not rule.applies_to(ctx): diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py index 1ce0c5b21704..9dbd3652400b 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py @@ -81,6 +81,12 @@ class CheckPhysicsIsNewton(CompatRule): name = "check_physics_is_newton" + NEWTON_MODULE_PREFIXES: ClassVar[tuple[str, ...]] = ("isaaclab_newton",) + """Module prefixes that mark a physics cfg as Newton-flavoured.""" + + PHYSX_MODULE_PREFIXES: ClassVar[tuple[str, ...]] = ("isaaclab_physx",) + """Module prefixes that mark a physics cfg as PhysX-flavoured (definitely incompatible).""" + def applies_to(self, ctx: ResolveContext) -> bool: return ctx.task.workflow == Workflow.MANAGER_BASED @@ -93,18 +99,21 @@ def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: # Skip PresetCfg wrappers — they'll be unwrapped by ResolvePhysicsPreset. if hasattr(physics, "newton") and not hasattr(physics, "class_type"): return - if module.startswith("isaaclab_physx"): - yield Issue( - rule=self.name, - severity=Severity.BLOCKING, - message=( - f"sim.physics is {cls.__name__} ({module}); the warp runtime" - f" needs Newton physics. Pass `presets=newton` or use a Newton" - f" physics cfg explicitly." - ), - location="cfg.sim.physics", - detail={"physics_class": cls.__name__, "physics_module": module}, - ) + if module.startswith(self.NEWTON_MODULE_PREFIXES): + return # OK + severity = Severity.BLOCKING if module.startswith(self.PHYSX_MODULE_PREFIXES) else Severity.WARNING + backend = "PhysX" if severity == Severity.BLOCKING else "unknown" + yield Issue( + rule=self.name, + severity=severity, + message=( + f"sim.physics is {cls.__name__} ({module}); the warp runtime" + f" needs a Newton physics cfg ({backend} detected). Pass" + f" `presets=newton` or use a Newton physics cfg explicitly." + ), + location="cfg.sim.physics", + detail={"physics_class": cls.__name__, "physics_module": module}, + ) class ResolvePhysicsPreset(CompatRule): @@ -118,6 +127,9 @@ class ResolvePhysicsPreset(CompatRule): name = "resolve_physics_preset" + def applies_to(self, ctx: ResolveContext) -> bool: + return ctx.task.workflow == Workflow.MANAGER_BASED + def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: physics = getattr(getattr(cfg, "sim", None), "physics", None) if physics is None or not hasattr(physics, "newton"): @@ -202,7 +214,28 @@ def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: for value in params.values(): if isinstance(value, Warp) or not isinstance(value, Stable): continue - value.__class__ = Warp + # ``__class__ =`` is permitted only when the layouts + # match (e.g. neither side adds ``__slots__`` over the + # other). ``issubclass`` does *not* guarantee this. If + # the runtime refuses, surface a blocking issue rather + # than crash mid-pipeline; the cfg is still safe because + # we set warp-only fields *after* the assignment. + try: + value.__class__ = Warp + except TypeError as exc: + yield Issue( + rule=self.name, + severity=Severity.BLOCKING, + message=( + f"in-place __class__ promotion to {Warp.__name__} failed:" + f" {exc}. The warp variant likely diverged in slots/layout" + f" from the stable one; rebuild cfg explicitly with the warp" + f" SceneEntityCfg." + ), + location=".".join(path), + detail={"warp_class": Warp.__name__, "stable_class": Stable.__name__}, + ) + return value.joint_mask = None value.joint_ids_wp = None value.body_ids_wp = None @@ -263,6 +296,14 @@ def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: stable = term.func if not callable(stable): continue + # Idempotency: if the term already references a warp-native + # callable (e.g. running the bridge against an already-warp + # task), don't try to swap. Without this guard the rule would + # ``resolve_warp_twin`` against modules that might not contain + # the same symbol and silently drop the term. + origin = getattr(stable, "__module__", "") or "" + if origin.startswith(WARP_ROOT_PREFIXES): + continue twin = resolve_warp_twin(stable.__name__, modules) if twin is not None: term.func = twin @@ -281,7 +322,12 @@ def _mdp_modules(self, task: TaskMeta) -> list[ModuleType]: """Locate warp mdp modules that mirror the task's stable mdp.""" modules: list[ModuleType] = [] entry = task.env_cfg_entry_point - if isinstance(entry, str) and entry.startswith(self.stable_root): + # Use a trailing dot when matching the stable root so a task registered + # under ``isaaclab_tasks_experimental.*`` (the warp side) doesn't match + # ``isaaclab_tasks`` and end up with a double-replaced + # ``isaaclab_tasks_experimental_experimental.*`` import path. + stable_prefix = self.stable_root + "." + if isinstance(entry, str) and entry.startswith(stable_prefix): warp_pkg = entry.rsplit(".", 1)[0].replace(self.stable_root, self.warp_root, 1) parts = warp_pkg.split(".") for depth in range(len(parts), 0, -1): @@ -441,10 +487,15 @@ def preprocess_hydra_args(self, task_id: str, args: list[str]) -> list[str]: cfg_ep = spec.kwargs.get("env_cfg_entry_point") if not isinstance(cfg_ep, str) or not cfg_ep.startswith("isaaclab_tasks.manager_based"): return args - explicit = next((a for a in args if a.startswith("presets=")), None) + + # Match both ``presets=foo`` and ``--presets=foo`` — Hydra accepts either. + def _is_preset_arg(arg: str) -> bool: + return arg.lstrip("-").startswith("presets=") + + explicit = next((a for a in args if _is_preset_arg(a)), None) if explicit is None: return [*args, "presets=newton"] - if explicit != "presets=newton": + if explicit.lstrip("-") != "presets=newton": logger.warning( "--frontend=warp on %r expects presets=newton; got %r — adapter may fail.", task_id, From 67050a863d5e295a730ca5a49edac3ffc909abe7 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 6 May 2026 07:58:25 +0000 Subject: [PATCH 09/36] Tighten frontend framework against second review pass - TaskResolver._classify_runtime: also accept class/callable entry points by inspecting __module__. gym.register accepts both ``"module:Class"`` strings and class objects; the old check only handled strings, so a warp-registered task using the class form classified as Runtime.UNKNOWN and the warn / verify rules silently disengaged. - SwapMdpFunctions._mdp_modules: narrow the exception match from ImportError to ModuleNotFoundError where ``exc.name`` matches the module being looked up. Previously a real ImportError raised inside an existing mdp module (broken import inside the package) would be silently swallowed and the rule would fall through to the fallback module, producing misleading "no warp twin" reports. --- .../isaaclab_experimental/envs/frontend/base.py | 15 +++++++++++---- .../isaaclab_experimental/envs/frontend/warp.py | 17 +++++++++++++---- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py index dece605f3aaa..120daf274aa7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py @@ -301,11 +301,18 @@ def _classify_runtime(spec: Any) -> Runtime: if spec is None: return Runtime.UNKNOWN ep = spec.entry_point + # ``entry_point`` may be a ``"module:Class"`` string (the common case) + # or a class/callable object. Inspect ``__module__`` for the latter so + # warp-registered tasks classified as such regardless of the + # registration form. if isinstance(ep, str): - if ep.startswith(WARP_ROOT_PREFIXES): - return Runtime.WARP - if ep.startswith(("isaaclab.envs", "isaaclab_tasks")): - return Runtime.TORCH + module = ep + else: + module = getattr(ep, "__module__", "") or "" + if module.startswith(WARP_ROOT_PREFIXES): + return Runtime.WARP + if module.startswith(("isaaclab.envs", "isaaclab_tasks")): + return Runtime.TORCH return Runtime.UNKNOWN diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py index 9dbd3652400b..cb7257944406 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py @@ -331,14 +331,23 @@ def _mdp_modules(self, task: TaskMeta) -> list[ModuleType]: warp_pkg = entry.rsplit(".", 1)[0].replace(self.stable_root, self.warp_root, 1) parts = warp_pkg.split(".") for depth in range(len(parts), 0, -1): + target = ".".join(parts[:depth] + ["mdp"]) try: - modules.append(importlib.import_module(".".join(parts[:depth] + ["mdp"]))) + modules.append(importlib.import_module(target)) break - except ImportError: - continue + except ModuleNotFoundError as exc: + # Only swallow "this candidate module does not exist". + # An ImportError raised *inside* a module that does exist + # is a real bug we should surface, not paper over by + # falling back. + if exc.name == target: + continue + raise try: modules.append(importlib.import_module(self.fallback_mdp)) - except ImportError: + except ModuleNotFoundError as exc: + if exc.name != self.fallback_mdp: + raise logger.warning("WarpFrontend: fallback mdp module %r not importable", self.fallback_mdp) return modules From e2cb7444bd87284d52fc27120d4cb9bb40367aa5 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 19 May 2026 07:26:18 +0000 Subject: [PATCH 10/36] Replace frontend rule pipeline with single adapter function MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collapses the CompatRule / Frontend / Report / Issue / Change framework (509+72+513+95 LOC across base/torch/warp/__init__) into one module (frontend.py, ~370 LOC). Net diff: 1270 → 864 LOC. Behavior changes: - Drop the pre-Hydra presets=newton injection. The warp frontend now hard-checks cfg.sim.physics is NewtonCfg at build time and tells the user to pass presets=newton on the CLI when it isn't. - Drop DropUnsupportedSensors. The Newton RayCaster (#5510) makes the height_scanner case obsolete; any future incompatible sensor should fail loudly with the sensor name rather than silently set None. - Merge SwapMdpFunctions + SwapActionClassType into one pass that swaps term.func or term.class_type uniformly for every group including actions. - Missing warp twin is always a hard failure (no strict / non-strict toggle). Partial swaps would leave torch funcs in a cfg consumed by warp managers, which only accept the kernel-style signature. - Replace SceneEntityCfg.__class__ = WarpSceneEntityCfg with a proper WarpSceneEntityCfg.from_stable() classmethod that copies every selection field through __init__. Train.py is unchanged in shape — two call sites, now using the top-level build(frontend, cfg, task_id) function. --- .../reinforcement_learning/rsl_rl/train.py | 43 +- .../changelog.d/warp-manager-bridge.rst | 88 ++- .../isaaclab_experimental/envs/frontend.py | 373 +++++++++++++ .../envs/frontend/__init__.py | 95 ---- .../envs/frontend/base.py | 509 ----------------- .../envs/frontend/torch.py | 72 --- .../envs/frontend/warp.py | 513 ------------------ .../managers/scene_entity_cfg.py | 24 + .../test/envs/test_frontend.py | 417 ++++++++++++++ 9 files changed, 864 insertions(+), 1270 deletions(-) create mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py create mode 100644 source/isaaclab_experimental/test/envs/test_frontend.py diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index f8f332bd18cb..23bff4218629 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -118,23 +118,14 @@ # intersection are pre-fold (the callback reads the user's original sys.argv), so # preset tokens like ``physics=NAME`` compare correctly here. Fold runs after. remaining_args = list_intersection(remaining_args, remaining_args_env_registration) -# Build the chosen frontend and let it pre-process Hydra args. Frontends -# may inject preset selections (e.g. WarpFrontend appends ``presets=newton`` -# for stable manager-based tasks so PresetCfg wrappers resolve to the Newton -# field before Hydra builds the cfg). Frontend injection runs *before* -# ``fold_preset_tokens`` so the injected tokens fold alongside any -# user-supplied ``physics=`` / ``presets=`` selectors. -# -# The frontend package lives under ``isaaclab_experimental``, which is -# optional. If it isn't installed, ``--frontend=torch`` (the default) still -# needs to work — fall back to plain ``gym.make`` in that case. The warp -# selection requires the experimental package, so import failure there is -# fatal. -_frontend = None -try: - from isaaclab_experimental.envs.frontend import get_frontend # noqa: E402 - _frontend = get_frontend(args_cli.frontend) +# Build path for ``--frontend=warp`` lives in ``isaaclab_experimental``, which is an +# optional package — torch (the default) must still work without it, so import lazily. +# Warp callers are required to pass ``presets=newton`` themselves; the frontend hard-checks +# it at build time rather than mutating Hydra args here. +_frontend_build = None +try: + from isaaclab_experimental.envs.frontend import build as _frontend_build # noqa: E402 except ImportError as _frontend_import_err: if args_cli.frontend != "torch": raise SystemExit( @@ -143,9 +134,6 @@ ) from _frontend_import_err logger.info("isaaclab_experimental not available; --frontend=torch will dispatch via plain gym.make.") -if _frontend is not None and args_cli.task is not None: - remaining_args = _frontend.preprocess_hydra_args(args_cli.task, remaining_args) - sys.argv = [sys.argv[0]] + fold_preset_tokens(remaining_args) # -- check RSL-RL version ---------------------------------------------------- @@ -230,16 +218,15 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # set the log directory for the environment (works for all environment types) env_cfg.log_dir = log_dir - # create isaac environment via the chosen frontend's rule pipeline. - # The frontend may mutate env_cfg in place (preset resolution, - # SceneEntityCfg promotion, mdp twin swaps, ...) before constructing - # the env. ``env.unwrapped.frontend_report`` carries what changed - # and what was missing. When the experimental frontend package isn't - # available we already validated --frontend=torch above, so a plain - # gym.make is the documented fallback. + # Build the env via the selected frontend. The warp frontend mutates env_cfg + # in place (SceneEntityCfg promotion + MDP func/class_type swap) and then + # constructs ``ManagerBasedRLEnvWarp``; missing warp twins are a hard failure. + # When ``isaaclab_experimental`` isn't installed, the argparse step above + # has already constrained --frontend to ``torch``, so the plain ``gym.make`` + # fallback is safe. render_mode = "rgb_array" if args_cli.video else None - if _frontend is not None: - env = _frontend.build(env_cfg, task_id=args_cli.task, render_mode=render_mode) + if _frontend_build is not None: + env = _frontend_build(args_cli.frontend, env_cfg, args_cli.task, render_mode=render_mode) else: env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render_mode) diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index d7197a0a756e..92dfd4f06f7b 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -1,59 +1,41 @@ Added ^^^^^ -* Added :mod:`isaaclab_experimental.envs.frontend`, a small framework that - selects the runtime backend for IsaacLab tasks. A :class:`Frontend` takes - a stable env cfg + task id, runs a pluggable :class:`CompatRule` pipeline - against the (cfg, task, frontend) triple, and constructs the env on the - matching runtime. New runtimes plug in by subclassing :class:`Frontend` - and calling :func:`register_frontend`; new compatibility checks plug in - by subclassing :class:`CompatRule` and listing it in a frontend's - :attr:`Frontend.rules`. - - The framework ships two built-in frontends: - - * :class:`TorchFrontend` (``--frontend=torch``, default) — passes through - to :func:`gym.make`. Emits a warning if the task is registered under - the warp runtime. - * :class:`WarpFrontend` (``--frontend=warp``) — adapts a manager-based - stable cfg onto :class:`ManagerBasedRLEnvWarp` via the rule pipeline, - or dispatches a direct task to its registered warp env class. - - The default warp rules are: - - * :class:`CheckPhysicsIsNewton` — blocking check; PhysX physics with the - warp runtime is a hard incompatibility (``isaaclab_physx`` classes - depend on ``omni.physics.tensors``, which the warp runtime does not - initialise). - * :class:`ResolvePhysicsPreset` — collapses ``PresetCfg`` to its - ``newton`` field for programmatic callers (Hydra's preset resolution - handles the CLI case). - * :class:`DropUnsupportedSensors` — drops scene sensors warp can't run. - * :class:`PromoteSceneEntityCfg` — in-place class promotion for warp - cached fields, with an :func:`issubclass` assertion to fail loudly if - the warp class ever stops subclassing the stable one. - * :class:`SwapMdpFunctions` — name-based ``term.func`` replacement - against the warp ``mdp`` modules; rejects stable re-exports by - inspecting ``__module__``. - * :class:`SwapActionClassType` — strict swap of action ``class_type`` - to the warp twin; missing twin is :attr:`Severity.BLOCKING`. - * :class:`VerifyDirectIsWarp` — for direct cfgs, blocks if the - registered entry-point isn't a warp class. - - All rules emit :class:`Issue` (incompatibility) and / or :class:`Change` - (transformation applied) records into a :class:`Report` accessible on - ``env.unwrapped.frontend_report`` after :meth:`Frontend.build`. - - :class:`TaskResolver` centralises ``gym.spec`` introspection and - classifies a task into a :class:`TaskMeta` (workflow, registered - runtime, cfg class). Rules read from :class:`TaskMeta` rather than - poking gym directly. - -* Added a ``--frontend={torch,warp}`` flag to ``rsl_rl/train.py``. The - script delegates Hydra-arg pre-processing (``presets=newton`` injection, - conflicting-preset warnings) and env construction to the selected - frontend via :func:`get_frontend`; ``render_mode`` is forwarded so - ``--video`` keeps working under the warp frontend. +* Added :mod:`isaaclab_experimental.envs.frontend`, a small runtime selector + used by ``--frontend {torch,warp}`` to choose how a task is constructed. + + * ``torch`` (default) dispatches via :func:`gym.make` unchanged. + * ``warp`` adapts a stable manager-based cfg in place and constructs + :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp`. The adapter + does three things, all hard-failing on incompatibility: + + 1. Requires :class:`~isaaclab_newton.physics.NewtonCfg` as the active + physics — the user is responsible for selecting it via + ``presets=newton``; no Hydra-arg mutation happens behind the scenes. + 2. Promotes every stable :class:`~isaaclab.managers.SceneEntityCfg` + embedded under term ``params`` to + :class:`isaaclab_experimental.managers.SceneEntityCfg` via the new + :meth:`~isaaclab_experimental.managers.SceneEntityCfg.from_stable` + classmethod (no ``__class__`` reassignment). + 3. Swaps every stable ``term.func`` *and* ``term.class_type`` (one pass, + handles observations / events / rewards / terminations / commands / + curriculum / actions) with its same-named warp twin from + ``isaaclab_tasks_experimental..mdp`` or + :mod:`isaaclab_experimental.envs.mdp`. Any missing twin raises + :class:`FrontendIncompatibleError` listing the affected term paths. + + Direct workflows aren't adapted; ``--frontend=warp`` on a direct task + requires the task to be pre-registered under ``isaaclab_experimental`` / + ``isaaclab_tasks_experimental`` (e.g. ``*-Direct-Warp-v0``). + +* Added :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable`, + a classmethod that builds a warp scene-entity cfg from a stable one by + copying every selection field through ``__init__``. + +* Added a ``--frontend {torch,warp}`` flag to ``rsl_rl/train.py``. The flag + selects the runtime via :func:`isaaclab_experimental.envs.frontend.build`; + ``isaaclab_experimental`` is treated as optional and ``--frontend=torch`` + falls back to ``gym.make`` when it isn't installed. Fixed ^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py new file mode 100644 index 000000000000..4dfc312d6481 --- /dev/null +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -0,0 +1,373 @@ +# 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 + +"""Runtime selector for IsaacLab tasks (``--frontend {torch,warp}``). + +Two responsibilities only: + +1. Decide which runtime constructs the env (torch via ``gym.make``, or warp via + :class:`ManagerBasedRLEnvWarp`). +2. For the warp runtime, adapt a stable manager-based cfg in place so the + warp managers can consume it (Newton physics + warp-twin term funcs and + action classes + warp variant of :class:`SceneEntityCfg`). + +The adaptation is a single function (:func:`_adapt_cfg_for_warp`); there is no +plugin framework. All warp MDP twins (functions *and* classes) must exist for +the chosen task — a missing twin is a hard failure, not a silent drop. +""" + +from __future__ import annotations + +import importlib +import logging +from collections.abc import Iterable, Iterator +from enum import StrEnum +from types import ModuleType +from typing import Any + +import gymnasium as gym + +from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg +from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _StableSceneEntityCfg + +logger = logging.getLogger(__name__) + + +__all__ = [ + "Frontend", + "FrontendIncompatibleError", + "Workflow", + "build", +] + + +# --------------------------------------------------------------------------- +# Enums + error +# --------------------------------------------------------------------------- + + +class Frontend(StrEnum): + """Runtime selector exposed by ``--frontend``.""" + + TORCH = "torch" + WARP = "warp" + + +class Workflow(StrEnum): + """Manager-based vs direct env workflow.""" + + MANAGER_BASED = "manager_based" + DIRECT = "direct" + + +class FrontendIncompatibleError(RuntimeError): + """Raised when the chosen frontend can't run the requested task.""" + + +# --------------------------------------------------------------------------- +# Public entry point +# --------------------------------------------------------------------------- + + +# Prefixes used to decide whether a registered task's entry-point lives under +# the warp packages. Used by the direct-workflow guard. +_WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") + +# Term containers walked by the cfg-adaptation step. Actions are included so +# the swap logic handles ``class_type`` and ``func`` in one pass. +_TERM_PATHS: tuple[tuple[str, ...], ...] = ( + ("observations", "policy"), + ("events",), + ("rewards",), + ("terminations",), + ("commands",), + ("curriculum",), + ("actions",), +) + + +def build( + frontend: Frontend | str, + env_cfg: Any, + task_id: str, + **construct_kwargs: Any, +) -> gym.Env: + """Construct the env on the selected runtime. + + Args: + frontend: ``"torch"`` (default IsaacLab path) or ``"warp"`` (warp managers + + :class:`ManagerBasedRLEnvWarp` for manager-based tasks). + env_cfg: Stable env cfg. Mutated in place when ``frontend == "warp"``. + task_id: Gym registration id, e.g. ``"Isaac-Cartpole-v0"``. + **construct_kwargs: Forwarded to the env constructor (``render_mode``, …). + + Returns: + The constructed :class:`gym.Env`. + + Raises: + FrontendIncompatibleError: If the warp runtime can't run the task + (wrong physics, missing MDP twins, direct task not registered + as a warp env). + """ + frontend = Frontend(frontend) + if frontend is Frontend.TORCH: + return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + + workflow = _detect_workflow(env_cfg) + if workflow is Workflow.DIRECT: + # Direct workflows aren't adapted — they must already be registered + # under the warp packages (e.g. ``Isaac-Cartpole-Direct-Warp-v0``). + _require_direct_is_warp_task(task_id) + return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + + _adapt_cfg_for_warp(env_cfg, task_id) + # Imported lazily so that ``--frontend=torch`` callers don't pay the + # ``isaaclab_experimental.envs`` import cost. + from isaaclab_experimental.envs import ManagerBasedRLEnvWarp + + return ManagerBasedRLEnvWarp(cfg=env_cfg, **construct_kwargs) + + +# --------------------------------------------------------------------------- +# Cfg adaptation (warp only) +# --------------------------------------------------------------------------- + + +def _adapt_cfg_for_warp(cfg: Any, task_id: str) -> None: + """Mutate ``cfg`` in place so warp managers can consume it. + + Three steps, each independently testable: + + 1. :func:`_require_newton_physics` — hard check that ``cfg.sim.physics`` is + :class:`~isaaclab_newton.physics.NewtonCfg`. The user is responsible for + selecting the Newton variant of the task's :class:`PresetCfg` via + ``presets=newton``; we don't auto-inject. + 2. :func:`_promote_scene_entity_cfgs` — replace stable + :class:`~isaaclab.managers.SceneEntityCfg` instances under each term's + ``params`` with the warp variant (which adds warp-cached ``joint_mask``, + ``joint_ids_wp``, ``body_ids_wp`` fields). + 3. :func:`_swap_mdp` — for every MDP term in every group (observations, + events, rewards, terminations, commands, curriculum, actions), replace + any stable ``func`` *or* ``class_type`` with its same-named warp twin. + A missing twin raises :class:`FrontendIncompatibleError` — partial + coverage is unsafe under the warp managers' kernel-only signature. + """ + _require_newton_physics(cfg, task_id) + _promote_scene_entity_cfgs(cfg) + _swap_mdp(cfg, task_id) + + +def _require_newton_physics(cfg: Any, task_id: str) -> None: + """Block unless ``cfg.sim.physics`` is :class:`NewtonCfg`. + + The warp managers' assets read state through :class:`NewtonManager`; + a :class:`PhysxCfg` (or unresolved :class:`PresetCfg`) is a hard + incompatibility. The fix is to pass ``presets=newton`` on the CLI so + Hydra resolves the task's :class:`PresetCfg` wrapper to the Newton field + before construction. + """ + from isaaclab_newton.physics import NewtonCfg + + physics = getattr(getattr(cfg, "sim", None), "physics", None) + if isinstance(physics, NewtonCfg): + return + raise FrontendIncompatibleError( + f"--frontend=warp on {task_id!r}: expected cfg.sim.physics to be NewtonCfg," + f" got {type(physics).__name__!r}. Pass `presets=newton` on the CLI so" + f" Hydra resolves the task's PresetCfg wrapper to the Newton variant." + ) + + +def _promote_scene_entity_cfgs(cfg: Any) -> None: + """Replace stable :class:`SceneEntityCfg` instances with the warp variant. + + Walks every ``term.params: dict`` under each term group and rebuilds any + stable :class:`SceneEntityCfg` value via + :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable`. The + warp variant subclasses the stable one, so type checks elsewhere stay + valid; the new fields (``joint_mask`` / ``joint_ids_wp`` / ``body_ids_wp``) + are filled at :meth:`resolve` time by the warp scene. + """ + from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSceneEntityCfg + + promoted = 0 + for path in _TERM_PATHS: + group = _walk_attrs(cfg, path) + if group is None: + continue + for _name, term in _iter_term_attrs(group): + params = getattr(term, "params", None) + if not isinstance(params, dict): + continue + for key, value in list(params.items()): + if isinstance(value, _WarpSceneEntityCfg) or not isinstance(value, _StableSceneEntityCfg): + continue + params[key] = _WarpSceneEntityCfg.from_stable(value) + promoted += 1 + if promoted: + logger.info("frontend.warp: promoted %d SceneEntityCfg instance(s) to warp variant", promoted) + + +def _swap_mdp(cfg: Any, task_id: str) -> None: + """Replace ``term.func`` and ``term.class_type`` with their warp twins. + + Walks the same term paths used by :func:`_promote_scene_entity_cfgs` and + on each term swaps whichever of ``func`` / ``class_type`` is set to a + stable-origin symbol. Twin lookup is name-based against the task's + matching ``isaaclab_tasks_experimental.<...>.mdp`` module and, as a + fallback, :mod:`isaaclab_experimental.envs.mdp`. Any missing twin raises + :class:`FrontendIncompatibleError` listing every affected term — partial + swaps would leave torch-style callables in the cfg and the warp managers + would call them with the wrong signature. + """ + modules = _warp_mdp_modules(task_id) + searched = tuple(m.__name__ for m in modules) + logger.info("frontend.warp: searching warp mdp modules %s", list(searched)) + + swapped = 0 + missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) + for path in _TERM_PATHS: + group = _walk_attrs(cfg, path) + if group is None: + continue + location_prefix = ".".join(path) + for name, term in _iter_term_attrs(group): + for attr in ("func", "class_type"): + stable = getattr(term, attr, None) + if stable is None or not _is_swap_candidate(stable): + continue + twin = _resolve_warp_twin(stable.__name__, modules) + if twin is None: + missing.append((f"{location_prefix}.{name}", attr, stable.__name__)) + continue + setattr(term, attr, twin) + swapped += 1 + + if missing: + lines = "\n ".join(f"{loc}.{attr}: no warp twin for {sym!r}" for loc, attr, sym in missing) + raise FrontendIncompatibleError( + f"--frontend=warp on {task_id!r}: missing warp MDP twins (searched {list(searched)}):\n {lines}" + ) + + logger.info("frontend.warp: swapped %d MDP symbol(s) to warp twins", swapped) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _detect_workflow(cfg: Any) -> Workflow: + """Classify the env cfg into manager-based or direct (used to pick build path).""" + if isinstance(cfg, ManagerBasedRLEnvCfg): + return Workflow.MANAGER_BASED + if isinstance(cfg, (DirectRLEnvCfg, DirectMARLEnvCfg)): + return Workflow.DIRECT + raise FrontendIncompatibleError( + f"Unrecognised env cfg type {type(cfg).__name__!r};" + f" expected ManagerBasedRLEnvCfg / DirectRLEnvCfg / DirectMARLEnvCfg subclass." + ) + + +def _require_direct_is_warp_task(task_id: str) -> None: + """For direct workflows, the task must be pre-registered under the warp packages.""" + try: + spec = gym.spec(task_id) + except gym.error.NameNotFound as exc: + raise FrontendIncompatibleError(f"--frontend=warp: task {task_id!r} is not registered with gymnasium.") from exc + ep = spec.entry_point + module = ep if isinstance(ep, str) else (getattr(ep, "__module__", "") or "") + if not module.startswith(_WARP_ROOT_PREFIXES): + raise FrontendIncompatibleError( + f"--frontend=warp on direct task {task_id!r}: entry_point {ep!r}" + f" is not under {list(_WARP_ROOT_PREFIXES)}. Direct tasks must be" + f" registered as a warp env class (e.g. *-Direct-Warp-v0)." + ) + + +def _warp_mdp_modules(task_id: str) -> list[ModuleType]: + """Locate warp MDP modules to consult for twin lookups. + + Order of preference: + + 1. The task-specific module, derived by replacing ``isaaclab_tasks`` with + ``isaaclab_tasks_experimental`` in the task's ``env_cfg_entry_point`` + package and walking up to the first existing ``.mdp`` submodule. + 2. The shared :mod:`isaaclab_experimental.envs.mdp` fallback (where + generic warp twins live). + """ + modules: list[ModuleType] = [] + try: + spec = gym.spec(task_id) + except gym.error.NameNotFound: + spec = None + entry = spec.kwargs.get("env_cfg_entry_point") if spec is not None else None + if isinstance(entry, str) and entry.startswith("isaaclab_tasks."): + warp_pkg = entry.rsplit(".", 1)[0].replace("isaaclab_tasks", "isaaclab_tasks_experimental", 1) + parts = warp_pkg.split(".") + for depth in range(len(parts), 0, -1): + target = ".".join(parts[:depth] + ["mdp"]) + try: + modules.append(importlib.import_module(target)) + break + except ModuleNotFoundError as exc: + # Only swallow "this candidate doesn't exist" — a real + # import error inside an existing module is a bug. + if exc.name == target: + continue + raise + # Generic fallback. + fallback = "isaaclab_experimental.envs.mdp" + try: + modules.append(importlib.import_module(fallback)) + except ModuleNotFoundError as exc: + if exc.name == fallback: + logger.warning("frontend.warp: fallback mdp module %r not importable", fallback) + else: + raise + return modules + + +def _resolve_warp_twin(name: str, modules: Iterable[ModuleType]) -> Any | None: + """Return the same-named symbol from ``modules`` that originates under the warp packages.""" + for module in modules: + candidate = getattr(module, name, None) + if candidate is None: + continue + origin = getattr(candidate, "__module__", "") or "" + if origin.startswith(_WARP_ROOT_PREFIXES): + return candidate + return None + + +def _is_swap_candidate(value: Any) -> bool: + """Heuristic: callable or class whose origin is *not already* warp.""" + if not callable(value): + return False + origin = getattr(value, "__module__", "") or "" + if origin.startswith(_WARP_ROOT_PREFIXES): + return False # already a warp twin (idempotent) + return True + + +def _walk_attrs(root: Any, path: tuple[str, ...]) -> Any: + """Walk ``root..…``; return ``None`` on any miss.""" + node = root + for attr in path: + node = getattr(node, attr, None) + if node is None: + return None + return node + + +def _iter_term_attrs(group: Any) -> Iterator[tuple[str, Any]]: + """Yield ``(name, term)`` pairs from a manager-cfg group, skipping dunders/Nones.""" + if group is None: + return + for name in [n for n in dir(group) if not n.startswith("_")]: + term = getattr(group, name, None) + if term is None: + continue + yield name, term diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py deleted file mode 100644 index 0f6e98b33974..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/__init__.py +++ /dev/null @@ -1,95 +0,0 @@ -# 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 - -"""Frontend framework: pluggable runtime selectors for IsaacLab tasks. - -A frontend (chosen via ``--frontend {torch,warp}``) is a thin dispatcher that -takes a stable env cfg + task id, runs a pluggable :class:`CompatRule` -pipeline against the (cfg, task, frontend) triple, and constructs the env on -the matching runtime. New runtimes plug in by subclassing :class:`Frontend` -and calling :func:`register_frontend`; new compatibility checks plug in by -subclassing :class:`CompatRule` and adding it to a frontend's -:attr:`Frontend.rules`. - -Public API:: - - from isaaclab_experimental.envs.frontend import get_frontend - frontend = get_frontend("warp") - env = frontend.build(env_cfg, task_id="Isaac-Cartpole-v0") - print(env.unwrapped.frontend_report.format()) -""" - -from __future__ import annotations - -from .base import ( - Change, - CompatRule, - Frontend, - FrontendIncompatibleError, - Issue, - Report, - ResolveContext, - Runtime, - Severity, - TaskMeta, - TaskResolver, - Workflow, - available_frontends, - get_frontend, - register_frontend, -) -from .torch import TorchFrontend, WarnIfTaskIsWarpRegistered -from .warp import ( - CheckPhysicsIsNewton, - DropUnsupportedSensors, - PromoteSceneEntityCfg, - ResolvePhysicsPreset, - SwapActionClassType, - SwapMdpFunctions, - VerifyDirectIsWarp, - WarpFrontend, -) - -# Register built-ins so ``get_frontend("torch" | "warp")`` works without -# the caller importing the concrete classes. -register_frontend(TorchFrontend.name, TorchFrontend) -register_frontend(WarpFrontend.name, WarpFrontend) - - -# Public API. Internal helpers (``walk_attrs``, ``iter_term_attrs``, -# ``resolve_warp_twin``, ``WARP_ROOT_PREFIXES``) are importable from -# :mod:`isaaclab_experimental.envs.frontend.base` for users writing their own -# rules, but they are not advertised here as the supported framework surface. -__all__ = [ - # core abstractions - "Frontend", - "CompatRule", - "TaskMeta", - "TaskResolver", - "Report", - "Issue", - "Change", - "Severity", - "Workflow", - "Runtime", - "ResolveContext", - "FrontendIncompatibleError", - # registry - "register_frontend", - "get_frontend", - "available_frontends", - # built-in frontends - "TorchFrontend", - "WarpFrontend", - # built-in rules - "WarnIfTaskIsWarpRegistered", - "CheckPhysicsIsNewton", - "ResolvePhysicsPreset", - "DropUnsupportedSensors", - "PromoteSceneEntityCfg", - "SwapMdpFunctions", - "SwapActionClassType", - "VerifyDirectIsWarp", -] diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py deleted file mode 100644 index 120daf274aa7..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/base.py +++ /dev/null @@ -1,509 +0,0 @@ -# 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 - -"""Frontend framework — abstractions for runtime selection. - -A *frontend* is a user-facing runtime selector (chosen via ``--frontend -{torch,warp}``). It takes a stable env cfg and a registered gym task id and -returns a runnable env, having first run a pluggable pipeline of -compatibility checks and transforms against the (cfg, task, frontend) -triple. - -The framework is intentionally narrow: - -* :class:`TaskResolver` is the single point that reads ``gym.spec`` and - classifies a task into a :class:`TaskMeta` (workflow, registered - runtime, cfg class). Rules and frontends consume :class:`TaskMeta` - instead of poking gym directly, so the registration format can evolve - in one place. -* :class:`CompatRule` is a single check or transform applied during - resolution. Each rule yields :class:`Issue` records (incompatibilities - the frontend can't paper over) and / or :class:`Change` records - (transformations applied to the cfg). Subclasses implement - :meth:`CompatRule.run` and may override :meth:`CompatRule.applies_to` - to scope themselves by workflow / runtime. -* :class:`Frontend` is the dispatcher. Subclasses declare a name, a list - of rule classes, and a :meth:`Frontend.construct` strategy that builds - the env once rules pass. -* :func:`register_frontend` / :func:`get_frontend` form the registry CLI - hooks read. - -To add a new compatibility check, write a small :class:`CompatRule` and -list it in the relevant frontend's :attr:`Frontend.rules`. To add a new -runtime, subclass :class:`Frontend` and call :func:`register_frontend`. -""" - -from __future__ import annotations - -import logging -from abc import ABC, abstractmethod -from collections.abc import Iterable, Iterator -from dataclasses import dataclass, field -from enum import Enum -from typing import Any, ClassVar - -logger = logging.getLogger(__name__) - - -# --------------------------------------------------------------------------- -# Constants -# --------------------------------------------------------------------------- - - -WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") -"""Module prefixes that mark a class as a warp implementation. - -The warp ``mdp`` packages do ``from isaaclab.envs.mdp import *``, so a -plain ``getattr`` lookup can return a stable symbol untouched. We accept -a candidate as a real warp twin only if its ``__module__`` lives under -one of these prefixes.""" - - -# --------------------------------------------------------------------------- -# Enums -# --------------------------------------------------------------------------- - - -class Workflow(str, Enum): - """Task workflow type.""" - - MANAGER_BASED = "manager_based" - DIRECT = "direct" - DIRECT_MARL = "direct_marl" - - -class Runtime(str, Enum): - """Runtime backend a task is registered against. - - A task whose ``entry_point`` lives under :data:`WARP_ROOT_PREFIXES` is - classified as ``WARP``. Tasks registered against ``isaaclab.envs.*`` - (the standard manager-based and direct env classes) are classified - as ``TORCH``; those env classes use ``FactoryBase`` to dispatch on - the active physics backend at construction time, so PhysX and Newton - physics both flow through the torch runtime path. - """ - - TORCH = "torch" - WARP = "warp" - UNKNOWN = "unknown" - - -class Severity(str, Enum): - """Severity of a compatibility :class:`Issue`.""" - - BLOCKING = "blocking" - """Frontend cannot build the env. :meth:`Frontend.build` raises.""" - WARNING = "warning" - """Surfaced to the user but not fatal (e.g. a term was dropped).""" - - -# --------------------------------------------------------------------------- -# Records -# --------------------------------------------------------------------------- - - -@dataclass -class TaskMeta: - """Static description of a registered gym task, produced by :class:`TaskResolver`.""" - - task_id: str - """Gym task id, e.g. ``Isaac-Cartpole-v0``.""" - spec: Any - """The :class:`gymnasium.envs.registration.EnvSpec` returned by ``gym.spec``.""" - cfg_class: type - """Concrete cfg type passed to the frontend.""" - workflow: Workflow - """Manager-based / direct / direct-marl.""" - runtime: Runtime - """Runtime the task is registered against (independent of the frontend asked for).""" - - @property - def env_cfg_entry_point(self) -> str | None: - """Module path of the cfg class as registered in ``spec.kwargs``.""" - return self.spec.kwargs.get("env_cfg_entry_point") if self.spec is not None else None - - @property - def entry_point(self) -> Any: - """Env class entry point as registered (string or class).""" - return self.spec.entry_point if self.spec is not None else None - - -@dataclass -class Issue: - """An incompatibility surfaced by a rule.""" - - rule: str - """Rule that produced this issue (matches :attr:`CompatRule.name`).""" - severity: Severity - message: str - """One-line human-readable description.""" - location: str = "" - """Optional cfg path the issue was found at (e.g. ``rewards.foo``).""" - detail: dict[str, Any] = field(default_factory=dict) - """Free-form rule-specific data (searched modules, expected names, ...).""" - - -@dataclass -class Change: - """A transformation a rule applied to the cfg.""" - - rule: str - description: str - - -@dataclass -class Report: - """Outcome of a frontend's rule pipeline.""" - - frontend: str - """Name of the frontend that produced this report.""" - task: TaskMeta - rules_run: list[str] = field(default_factory=list) - issues: list[Issue] = field(default_factory=list) - changes: list[Change] = field(default_factory=list) - - @property - def blocking(self) -> list[Issue]: - return [i for i in self.issues if i.severity == Severity.BLOCKING] - - def has_blocking(self) -> bool: - return any(i.severity == Severity.BLOCKING for i in self.issues) - - def __bool__(self) -> bool: - return bool(self.changes) or bool(self.issues) - - def format(self) -> str: - lines = [ - f"Frontend {self.frontend!r} on task {self.task.task_id!r}" - f" ({self.task.workflow.value} / registered runtime {self.task.runtime.value})" - ] - if self.changes: - lines.append(f" changes ({len(self.changes)}):") - lines.extend(f" [{c.rule}] {c.description}" for c in self.changes) - if self.issues: - lines.append(f" issues ({len(self.issues)}):") - for i in self.issues: - head = f" [{i.severity.value}/{i.rule}]" - where = f" {i.location}" if i.location else "" - lines.append(f"{head}{where} {i.message}") - return "\n".join(lines) - - -@dataclass -class ResolveContext: - """Per-call context handed to rules.""" - - frontend: str - """Name of the running frontend.""" - task: TaskMeta - strict: bool = False - """When True, rules may escalate warnings to blocking issues.""" - - -# --------------------------------------------------------------------------- -# Exceptions -# --------------------------------------------------------------------------- - - -class FrontendIncompatibleError(RuntimeError): - """Raised when a frontend cannot build the requested (task, cfg) pair.""" - - def __init__(self, message: str, report: Report | None = None): - super().__init__(message) - self.report = report - - -# --------------------------------------------------------------------------- -# CompatRule -# --------------------------------------------------------------------------- - - -class CompatRule(ABC): - """A single check / transform applied during frontend resolution. - - A rule's :meth:`run` method may yield :class:`Issue` records (the rule - detected an incompatibility), :class:`Change` records (the rule mutated - the cfg), or both. Pure-check and pure-transform rules are common; mixed - rules are useful when a transformation has a partial-failure mode (e.g. - a name swap that found 5 of 6 twins). - - Subclass and: - - * Set :attr:`name` to a short identifier used in the report. - * Implement :meth:`run` to do the work. - * Override :meth:`applies_to` to skip the rule when irrelevant. - """ - - name: ClassVar[str] - - def applies_to(self, ctx: ResolveContext) -> bool: - """Return True if this rule should run on the given context. - - Default: always applies. Override to scope by ``ctx.task.workflow``, - ``ctx.task.runtime``, ``ctx.frontend``, etc. - """ - return True - - @abstractmethod - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - """Inspect / mutate ``cfg`` and yield :class:`Issue` / :class:`Change` records.""" - - -# --------------------------------------------------------------------------- -# TaskResolver -# --------------------------------------------------------------------------- - - -class TaskResolver: - """Inspect a registered gym task and classify its workflow + runtime. - - All rules and frontends should call :meth:`resolve` rather than reading - ``gym.spec`` directly. Centralising the read keeps registration-format - knowledge in one place. - """ - - @classmethod - def resolve(cls, task_id: str, cfg: Any) -> TaskMeta: - """Return a :class:`TaskMeta` for ``(task_id, cfg)``.""" - import gymnasium as gym - - try: - spec = gym.spec(task_id) - except gym.error.NameNotFound: - spec = None - return TaskMeta( - task_id=task_id, - spec=spec, - cfg_class=type(cfg), - workflow=cls._classify_workflow(cfg), - runtime=cls._classify_runtime(spec), - ) - - @staticmethod - def _classify_workflow(cfg: Any) -> Workflow: - from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg - - if isinstance(cfg, ManagerBasedRLEnvCfg): - return Workflow.MANAGER_BASED - if isinstance(cfg, DirectMARLEnvCfg): - return Workflow.DIRECT_MARL - if isinstance(cfg, DirectRLEnvCfg): - return Workflow.DIRECT - raise FrontendIncompatibleError( - f"Cfg type {type(cfg).__name__!r} is not a recognised env cfg" - f" (expected ManagerBasedRLEnvCfg / DirectRLEnvCfg / DirectMARLEnvCfg subclass)." - ) - - @staticmethod - def _classify_runtime(spec: Any) -> Runtime: - if spec is None: - return Runtime.UNKNOWN - ep = spec.entry_point - # ``entry_point`` may be a ``"module:Class"`` string (the common case) - # or a class/callable object. Inspect ``__module__`` for the latter so - # warp-registered tasks classified as such regardless of the - # registration form. - if isinstance(ep, str): - module = ep - else: - module = getattr(ep, "__module__", "") or "" - if module.startswith(WARP_ROOT_PREFIXES): - return Runtime.WARP - if module.startswith(("isaaclab.envs", "isaaclab_tasks")): - return Runtime.TORCH - return Runtime.UNKNOWN - - -# --------------------------------------------------------------------------- -# Frontend -# --------------------------------------------------------------------------- - - -class Frontend(ABC): - """User-facing runtime selector. - - Subclasses declare: - - * :attr:`name`: CLI identifier used by ``--frontend`` and the registry. - * :attr:`rules`: rule classes the pipeline instantiates by default. - * :meth:`construct`: how to build the env once rules pass. - - Subclasses may also override: - - * :meth:`preprocess_hydra_args`: CLI-time Hydra arg munging (e.g. inject - a preset selection so Hydra resolves ``PresetCfg`` to the right field - before the cfg ever reaches us). - * :meth:`preprocess_cfg`: cfg pre-processing run before rules. - """ - - name: ClassVar[str] - rules: ClassVar[tuple[type[CompatRule], ...]] = () - - def __init__(self, rules: Iterable[CompatRule] | None = None, strict: bool = False): - self._rules: list[CompatRule] = [r() for r in type(self).rules] if rules is None else list(rules) - self.strict = strict - - # -- public --------------------------------------------------------------- - - def build(self, cfg: Any, task_id: str, **construct_kwargs: Any) -> Any: - """Resolve the task, run rules, and construct the env. - - Raises :class:`FrontendIncompatibleError` if any rule emits a - :class:`Severity.BLOCKING` issue. The returned env carries the - :class:`Report` on ``env.unwrapped.frontend_report`` for inspection. - """ - report = self.resolve(cfg, task_id) - self._log_report(report) - if report.has_blocking(): - raise FrontendIncompatibleError( - f"Frontend {self.name!r} cannot build {task_id!r}:\n{report.format()}", - report=report, - ) - env = self.construct(cfg, report.task, **construct_kwargs) - env.unwrapped.frontend_report = report - return env - - def resolve(self, cfg: Any, task_id: str) -> Report: - """Run the rule pipeline; mutate ``cfg`` in place; return a :class:`Report`. - - Use this directly for dry-run validation (tests, CLI ``--check``). - """ - meta = TaskResolver.resolve(task_id, cfg) - ctx = ResolveContext(frontend=self.name, task=meta, strict=self.strict) - report = Report(frontend=self.name, task=meta) - # If gym couldn't resolve the spec, the frontend has nothing to dispatch - # against. Block early with a clear message rather than letting - # downstream construct() fail with a NameNotFound. - if meta.spec is None: - report.issues.append( - Issue( - rule="task_resolver", - severity=Severity.BLOCKING, - message=( - f"task {task_id!r} is not registered with gymnasium." - " Make sure the task package is imported before the frontend runs." - ), - location="task.spec", - ) - ) - return report - self.preprocess_cfg(cfg, ctx) - for rule in self._rules: - if not rule.applies_to(ctx): - continue - report.rules_run.append(rule.name) - for record in rule.run(cfg, ctx): - if isinstance(record, Issue): - report.issues.append(record) - elif isinstance(record, Change): - report.changes.append(record) - else: - raise TypeError(f"Rule {rule.name!r} yielded {type(record).__name__}; expected Issue or Change.") - return report - - # -- subclass hooks ------------------------------------------------------- - - @abstractmethod - def construct(self, cfg: Any, meta: TaskMeta, **kwargs: Any) -> Any: - """Build the env. Called only when no blocking issues were raised.""" - - def preprocess_cfg(self, cfg: Any, ctx: ResolveContext) -> None: - """Subclass hook for cfg pre-processing run before rules. Default: no-op.""" - - def preprocess_hydra_args(self, task_id: str, args: list[str]) -> list[str]: - """Subclass hook for CLI-time Hydra arg munging. Default: no-op. - - Called from the train script so frontends can inject preset - selections (or refuse incompatible ones) before Hydra builds the - cfg. Returns the (possibly modified) args list. - """ - return args - - # -- helpers -------------------------------------------------------------- - - def _log_report(self, report: Report) -> None: - if not report: - return - level = logging.ERROR if report.has_blocking() else logging.WARNING - logger.log(level, report.format()) - - -# --------------------------------------------------------------------------- -# Registry -# --------------------------------------------------------------------------- - - -_REGISTRY: dict[str, type[Frontend]] = {} - - -def register_frontend(name: str, cls: type[Frontend]) -> None: - """Register a frontend implementation under ``name``. - - The CLI ``--frontend`` flag and :func:`get_frontend` look up by this name. - Re-registering the same class is idempotent; re-registering a different - class raises :class:`ValueError`. - """ - existing = _REGISTRY.get(name) - if existing is not None and existing is not cls: - raise ValueError( - f"Frontend {name!r} is already registered to {existing.__name__};" - f" refusing to re-register to {cls.__name__}." - ) - _REGISTRY[name] = cls - - -def get_frontend(name: str, **kwargs: Any) -> Frontend: - """Look up a frontend by name and return a fresh instance. - - Extra kwargs are forwarded to :meth:`Frontend.__init__` (e.g. ``strict=True``). - """ - try: - cls = _REGISTRY[name] - except KeyError as exc: - raise ValueError(f"Unknown frontend {name!r}; available: {available_frontends()}.") from exc - return cls(**kwargs) - - -def available_frontends() -> list[str]: - """Return registered frontend names, sorted.""" - return sorted(_REGISTRY) - - -# --------------------------------------------------------------------------- -# Helpers shared by rules -# --------------------------------------------------------------------------- - - -def walk_attrs(root: Any, path: tuple[str, ...]) -> Any: - """Walk ``root.....`` returning ``None`` on any miss.""" - node = root - for attr in path: - node = getattr(node, attr, None) - if node is None: - return None - return node - - -def resolve_warp_twin(name: str, modules: Iterable[Any]) -> Any | None: - """Return ``name`` from ``modules`` if its ``__module__`` lives under a warp prefix.""" - for module in modules: - candidate = getattr(module, name, None) - if candidate is None: - continue - origin = getattr(candidate, "__module__", "") or "" - if origin.startswith(WARP_ROOT_PREFIXES): - return candidate - return None - - -def iter_term_attrs(group: Any) -> Iterator[tuple[str, Any]]: - """Yield ``(name, term)`` pairs from a manager-cfg group, skipping dunders.""" - if group is None: - return - for name in [n for n in dir(group) if not n.startswith("_")]: - term = getattr(group, name, None) - if term is None: - continue - yield name, term diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py deleted file mode 100644 index 1c4054e79cda..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/torch.py +++ /dev/null @@ -1,72 +0,0 @@ -# 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 - -"""Torch (default) frontend. - -The torch frontend is a thin wrapper around :func:`gym.make`. It does not -mutate the cfg — the standard ``isaaclab.envs.*`` env classes use -``FactoryBase`` to dispatch on the active physics backend at construction -time, so PhysX and Newton physics both run through this single path. - -Its rule set is small: one warning when the user asks for the torch -frontend on a task that's *registered* against the warp runtime -(``entry_point`` under :data:`WARP_ROOT_PREFIXES`). That's a contradiction -of intent — the env class is a warp env regardless of the frontend flag — -so we surface it but don't block. -""" - -from __future__ import annotations - -from collections.abc import Iterable -from typing import Any - -from .base import ( - Change, - CompatRule, - Frontend, - Issue, - ResolveContext, - Runtime, - Severity, - TaskMeta, -) - - -class WarnIfTaskIsWarpRegistered(CompatRule): - """Warn when a warp-registered task is asked to run on the torch frontend. - - The env class itself is a warp implementation; ``--frontend=torch`` will - still happily build it via ``gym.make`` (since the entry-point class is - what runs), but the user's stated intent says torch. We emit a warning - so the contradiction is visible. - """ - - name = "warn_if_task_is_warp_registered" - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - if ctx.task.runtime == Runtime.WARP: - yield Issue( - rule=self.name, - severity=Severity.WARNING, - message=( - f"task is registered against the warp runtime" - f" (entry_point={ctx.task.entry_point!r}); --frontend=torch" - f" will still build the warp env class. Consider --frontend=warp." - ), - location="task.entry_point", - detail={"runtime": ctx.task.runtime.value}, - ) - - -class TorchFrontend(Frontend): - """Default frontend: ``gym.make`` against the registered ``entry_point``.""" - - name = "torch" - rules = (WarnIfTaskIsWarpRegistered,) - - def construct(self, cfg: Any, meta: TaskMeta, **kwargs: Any) -> Any: - import gymnasium as gym - - return gym.make(meta.task_id, cfg=cfg, **kwargs) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py deleted file mode 100644 index cb7257944406..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend/warp.py +++ /dev/null @@ -1,513 +0,0 @@ -# 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 - -"""Warp frontend. - -Routes a stable manager-based task cfg onto :class:`ManagerBasedRLEnvWarp` -by running a pluggable :class:`CompatRule` pipeline. Direct envs encode -their runtime in the env class itself (each warp direct env is its own -class), so for direct cfgs the frontend just verifies the registered -entry-point lives under :data:`WARP_ROOT_PREFIXES` and forwards to -:func:`gym.make`. - -Rule pipeline (manager-based path): - -* :class:`CheckPhysicsIsNewton` — blocking issue if ``cfg.sim.physics`` - is PhysX-flavoured, since the warp runtime needs Newton physics. -* :class:`ResolvePhysicsPreset` — collapses ``PresetCfg`` wrappers (no-op - when Hydra already did so). -* :class:`DropUnsupportedSensors` — removes sensors warp can't run yet. -* :class:`PromoteSceneEntityCfg` — in-place class promotion to the warp - variant so warp mdp kernels see ``joint_mask`` / ``joint_ids_wp``. -* :class:`SwapMdpFunctions` — name-based ``term.func`` replacement against - the warp ``mdp`` modules. -* :class:`SwapActionClassType` — strict swap of action ``class_type`` to - the warp twin. -* :class:`VerifyDirectIsWarp` — only fires for direct cfgs; blocks if - the registered entry-point isn't a warp class. -""" - -from __future__ import annotations - -import importlib -import logging -from collections.abc import Iterable -from types import ModuleType -from typing import Any, ClassVar - -from .base import ( - WARP_ROOT_PREFIXES, - Change, - CompatRule, - Frontend, - FrontendIncompatibleError, - Issue, - ResolveContext, - Runtime, - Severity, - TaskMeta, - Workflow, - iter_term_attrs, - resolve_warp_twin, - walk_attrs, -) - -logger = logging.getLogger(__name__) - - -# --------------------------------------------------------------------------- -# Rules -# --------------------------------------------------------------------------- - - -class CheckPhysicsIsNewton(CompatRule): - """Block if ``cfg.sim.physics`` isn't Newton. - - The warp runtime resolves asset / sensor ``class_type`` via the active - physics backend's module tree (``isaaclab_newton.*`` for Newton, - ``isaaclab_physx.*`` for PhysX). Loading a PhysX class under the warp - runtime fails on ``omni.physics.tensors.api`` (a Kit module the warp - runtime doesn't initialise), so a PhysX physics cfg is fundamentally - incompatible with this frontend. - - Hydra's preset resolution + :meth:`WarpFrontend.preprocess_hydra_args` - normally collapse ``PresetCfg`` wrappers to the ``newton`` field - before this rule runs; we still check, so a programmatic caller or a - misconfigured task fails fast and loudly here instead of crashing - deep in scene init. - """ - - name = "check_physics_is_newton" - - NEWTON_MODULE_PREFIXES: ClassVar[tuple[str, ...]] = ("isaaclab_newton",) - """Module prefixes that mark a physics cfg as Newton-flavoured.""" - - PHYSX_MODULE_PREFIXES: ClassVar[tuple[str, ...]] = ("isaaclab_physx",) - """Module prefixes that mark a physics cfg as PhysX-flavoured (definitely incompatible).""" - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.MANAGER_BASED - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - physics = getattr(getattr(cfg, "sim", None), "physics", None) - if physics is None: - return - cls = type(physics) - module = getattr(cls, "__module__", "") or "" - # Skip PresetCfg wrappers — they'll be unwrapped by ResolvePhysicsPreset. - if hasattr(physics, "newton") and not hasattr(physics, "class_type"): - return - if module.startswith(self.NEWTON_MODULE_PREFIXES): - return # OK - severity = Severity.BLOCKING if module.startswith(self.PHYSX_MODULE_PREFIXES) else Severity.WARNING - backend = "PhysX" if severity == Severity.BLOCKING else "unknown" - yield Issue( - rule=self.name, - severity=severity, - message=( - f"sim.physics is {cls.__name__} ({module}); the warp runtime" - f" needs a Newton physics cfg ({backend} detected). Pass" - f" `presets=newton` or use a Newton physics cfg explicitly." - ), - location="cfg.sim.physics", - detail={"physics_class": cls.__name__, "physics_module": module}, - ) - - -class ResolvePhysicsPreset(CompatRule): - """Collapse ``cfg.sim.physics`` from ``PresetCfg`` to its ``newton`` field. - - Hydra's preset resolution normally collapses the wrapper before the - frontend runs. This rule covers the residual case of programmatic use - of :meth:`Frontend.build` without Hydra, and custom physics cfgs that - still expose a ``newton`` attribute. - """ - - name = "resolve_physics_preset" - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.MANAGER_BASED - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - physics = getattr(getattr(cfg, "sim", None), "physics", None) - if physics is None or not hasattr(physics, "newton"): - return - cfg.sim.physics = physics.newton - yield Change( - rule=self.name, - description=f"sim.physics → {type(physics.newton).__name__}", - ) - - -class DropUnsupportedSensors(CompatRule): - """Drop scene sensors the warp runtime can't run yet. - - Default: ``("height_scanner",)``. Pass ``sensors=...`` at construction - time to override. - """ - - name = "drop_unsupported_sensors" - - def __init__(self, sensors: Iterable[str] = ("height_scanner",)): - self.sensors = tuple(sensors) - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.MANAGER_BASED - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - scene = getattr(cfg, "scene", None) - if scene is None: - return - for sensor in self.sensors: - if getattr(scene, sensor, None) is not None: - setattr(scene, sensor, None) - yield Change(rule=self.name, description=f"scene.{sensor} → None") - - -class PromoteSceneEntityCfg(CompatRule): - """Promote :class:`SceneEntityCfg` instances under term params to the warp variant. - - The warp variant adds cached ``joint_mask`` / ``joint_ids_wp`` / - ``body_ids_wp`` fields that the warp mdp kernels read after - :meth:`resolve`. The class hierarchy is asserted at apply time — if - the warp class no longer subclasses the stable class, the rule raises - :class:`FrontendIncompatibleError` so the in-place ``__class__`` - promotion can never silently corrupt instances. - """ - - name = "promote_scene_entity_cfg" - - GROUPS: ClassVar[tuple[tuple[str, ...], ...]] = ( - ("observations", "policy"), - ("events",), - ("rewards",), - ("terminations",), - ("commands",), - ("curriculum",), - ("actions",), - ) - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.MANAGER_BASED - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as Stable - - from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as Warp - - if not issubclass(Warp, Stable): - raise FrontendIncompatibleError( - f"Warp SceneEntityCfg must subclass stable SceneEntityCfg; got mro {[c.__name__ for c in Warp.__mro__]}" - ) - - promoted = 0 - for path in self.GROUPS: - group = walk_attrs(cfg, path) - if group is None: - continue - for _name, term in iter_term_attrs(group): - params = getattr(term, "params", None) - if not isinstance(params, dict): - continue - for value in params.values(): - if isinstance(value, Warp) or not isinstance(value, Stable): - continue - # ``__class__ =`` is permitted only when the layouts - # match (e.g. neither side adds ``__slots__`` over the - # other). ``issubclass`` does *not* guarantee this. If - # the runtime refuses, surface a blocking issue rather - # than crash mid-pipeline; the cfg is still safe because - # we set warp-only fields *after* the assignment. - try: - value.__class__ = Warp - except TypeError as exc: - yield Issue( - rule=self.name, - severity=Severity.BLOCKING, - message=( - f"in-place __class__ promotion to {Warp.__name__} failed:" - f" {exc}. The warp variant likely diverged in slots/layout" - f" from the stable one; rebuild cfg explicitly with the warp" - f" SceneEntityCfg." - ), - location=".".join(path), - detail={"warp_class": Warp.__name__, "stable_class": Stable.__name__}, - ) - return - value.joint_mask = None - value.joint_ids_wp = None - value.body_ids_wp = None - promoted += 1 - if promoted: - yield Change( - rule=self.name, - description=f"promoted {promoted} SceneEntityCfg instance(s) to warp variant", - ) - - -class SwapMdpFunctions(CompatRule): - """Replace ``term.func`` with the same-named callable from warp ``mdp`` modules. - - Walks observation / event / reward / termination / command / curriculum - groups. A re-export from stable code is rejected by checking - ``__module__``. Missing twins are dropped (term set to ``None``) and - surfaced as :attr:`Severity.WARNING`; in strict mode they're escalated - to :attr:`Severity.BLOCKING`. - """ - - name = "swap_mdp_functions" - - GROUPS: ClassVar[tuple[tuple[str, ...], ...]] = ( - ("observations", "policy"), - ("events",), - ("rewards",), - ("terminations",), - ("commands",), - ("curriculum",), - ) - - def __init__( - self, - stable_root: str = "isaaclab_tasks", - warp_root: str = "isaaclab_tasks_experimental", - fallback_mdp: str = "isaaclab_experimental.envs.mdp", - ): - self.stable_root = stable_root - self.warp_root = warp_root - self.fallback_mdp = fallback_mdp - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.MANAGER_BASED - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - modules = self._mdp_modules(ctx.task) - logger.info("WarpFrontend: warp mdp modules → %s", [m.__name__ for m in modules]) - searched = tuple(m.__name__ for m in modules) - for path in self.GROUPS: - group = walk_attrs(cfg, path) - if group is None: - continue - location_prefix = ".".join(path) - for name, term in iter_term_attrs(group): - if not hasattr(term, "func"): - continue - stable = term.func - if not callable(stable): - continue - # Idempotency: if the term already references a warp-native - # callable (e.g. running the bridge against an already-warp - # task), don't try to swap. Without this guard the rule would - # ``resolve_warp_twin`` against modules that might not contain - # the same symbol and silently drop the term. - origin = getattr(stable, "__module__", "") or "" - if origin.startswith(WARP_ROOT_PREFIXES): - continue - twin = resolve_warp_twin(stable.__name__, modules) - if twin is not None: - term.func = twin - continue - # No twin found: drop the term and report. - setattr(group, name, None) - yield Issue( - rule=self.name, - severity=Severity.BLOCKING if ctx.strict else Severity.WARNING, - message=(f"no warp twin for stable func={stable.__name__!r}; term dropped."), - location=f"{location_prefix}.{name}", - detail={"expected": stable.__name__, "searched": list(searched)}, - ) - - def _mdp_modules(self, task: TaskMeta) -> list[ModuleType]: - """Locate warp mdp modules that mirror the task's stable mdp.""" - modules: list[ModuleType] = [] - entry = task.env_cfg_entry_point - # Use a trailing dot when matching the stable root so a task registered - # under ``isaaclab_tasks_experimental.*`` (the warp side) doesn't match - # ``isaaclab_tasks`` and end up with a double-replaced - # ``isaaclab_tasks_experimental_experimental.*`` import path. - stable_prefix = self.stable_root + "." - if isinstance(entry, str) and entry.startswith(stable_prefix): - warp_pkg = entry.rsplit(".", 1)[0].replace(self.stable_root, self.warp_root, 1) - parts = warp_pkg.split(".") - for depth in range(len(parts), 0, -1): - target = ".".join(parts[:depth] + ["mdp"]) - try: - modules.append(importlib.import_module(target)) - break - except ModuleNotFoundError as exc: - # Only swallow "this candidate module does not exist". - # An ImportError raised *inside* a module that does exist - # is a real bug we should surface, not paper over by - # falling back. - if exc.name == target: - continue - raise - try: - modules.append(importlib.import_module(self.fallback_mdp)) - except ModuleNotFoundError as exc: - if exc.name != self.fallback_mdp: - raise - logger.warning("WarpFrontend: fallback mdp module %r not importable", self.fallback_mdp) - return modules - - -class SwapActionClassType(CompatRule): - """Swap ``cfg.actions..class_type`` with the same-named warp class. - - Always strict at the term level: an action with no warp twin can't run - on the warp runtime, so a missing twin is :attr:`Severity.BLOCKING` - regardless of ``ctx.strict``. - """ - - name = "swap_action_class_type" - - def __init__(self, warp_actions_module: str = "isaaclab_experimental.envs.mdp.actions.joint_actions"): - self.warp_actions_module = warp_actions_module - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.MANAGER_BASED - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - actions = getattr(cfg, "actions", None) - if actions is None: - return - try: - module = importlib.import_module(self.warp_actions_module) - except ImportError as exc: - yield Issue( - rule=self.name, - severity=Severity.BLOCKING, - message=(f"warp action module {self.warp_actions_module!r} not importable: {exc}"), - location="actions", - ) - return - searched = (module.__name__,) - for name, term in iter_term_attrs(actions): - if not hasattr(term, "class_type"): - continue - stable = term.class_type - if not callable(stable): - continue - twin = resolve_warp_twin(stable.__name__, [module]) - if twin is not None: - term.class_type = twin - continue - yield Issue( - rule=self.name, - severity=Severity.BLOCKING, - message=f"no warp twin for stable class_type={stable.__name__!r}", - location=f"actions.{name}", - detail={"expected": stable.__name__, "searched": list(searched)}, - ) - - -class VerifyDirectIsWarp(CompatRule): - """For direct envs, block if the registered entry-point isn't a warp class. - - Direct envs encode their runtime in the env class itself (each warp - direct env is a separate class with its own kernels), so the warp - frontend can't *adapt* a stable direct cfg — it can only refuse it - with a clear message. A direct task whose entry-point already lives - under :data:`WARP_ROOT_PREFIXES` is a pass-through. - """ - - name = "verify_direct_is_warp" - - def applies_to(self, ctx: ResolveContext) -> bool: - return ctx.task.workflow == Workflow.DIRECT - - def run(self, cfg: Any, ctx: ResolveContext) -> Iterable[Issue | Change]: - if ctx.task.runtime == Runtime.WARP: - return - ep = ctx.task.entry_point - yield Issue( - rule=self.name, - severity=Severity.BLOCKING, - message=( - f"direct env entry_point {ep!r} is not a warp implementation." - f" --frontend=warp on a direct task requires the registered class to live under" - f" {list(WARP_ROOT_PREFIXES)} (e.g. *-Direct-Warp-v0)." - ), - location="task.entry_point", - detail={"entry_point": ep}, - ) - - -# --------------------------------------------------------------------------- -# WarpFrontend -# --------------------------------------------------------------------------- - - -class WarpFrontend(Frontend): - """Run a stable env cfg on the warp runtime. - - Manager-based cfgs get the full rule pipeline and are constructed on - :class:`ManagerBasedRLEnvWarp`. Direct cfgs run :class:`VerifyDirectIsWarp` - only and dispatch through :func:`gym.make`. - """ - - name = "warp" - rules = ( - CheckPhysicsIsNewton, - ResolvePhysicsPreset, - DropUnsupportedSensors, - PromoteSceneEntityCfg, - SwapMdpFunctions, - SwapActionClassType, - VerifyDirectIsWarp, - ) - - # -- construction --------------------------------------------------------- - - def construct(self, cfg: Any, meta: TaskMeta, **kwargs: Any) -> Any: - if meta.workflow == Workflow.MANAGER_BASED: - from isaaclab_experimental.envs import ManagerBasedRLEnvWarp - - return ManagerBasedRLEnvWarp(cfg=cfg, **kwargs) - if meta.workflow == Workflow.DIRECT: - import gymnasium as gym - - return gym.make(meta.task_id, cfg=cfg, **kwargs) - raise FrontendIncompatibleError( - f"WarpFrontend does not support workflow {meta.workflow.value!r} (task {meta.task_id!r})." - ) - - # -- CLI hook ------------------------------------------------------------- - - def preprocess_hydra_args(self, task_id: str, args: list[str]) -> list[str]: - """Inject ``presets=newton`` for stable manager-based tasks. - - Hydra resolves ``presets=...`` *before* the frontend runs, so the - injection has to happen at the CLI layer. We only inject for tasks - whose ``env_cfg_entry_point`` is under ``isaaclab_tasks.manager_based``; - other tasks (direct, pre-warp ``*-Warp-v0``) don't carry a preset - system and would error out. - - If the user already passed an explicit ``presets=`` we don't override, - but we warn when their preset isn't ``newton``. - """ - import gymnasium as gym - - try: - spec = gym.spec(task_id) - except gym.error.NameNotFound: - return args - cfg_ep = spec.kwargs.get("env_cfg_entry_point") - if not isinstance(cfg_ep, str) or not cfg_ep.startswith("isaaclab_tasks.manager_based"): - return args - - # Match both ``presets=foo`` and ``--presets=foo`` — Hydra accepts either. - def _is_preset_arg(arg: str) -> bool: - return arg.lstrip("-").startswith("presets=") - - explicit = next((a for a in args if _is_preset_arg(a)), None) - if explicit is None: - return [*args, "presets=newton"] - if explicit.lstrip("-") != "presets=newton": - logger.warning( - "--frontend=warp on %r expects presets=newton; got %r — adapter may fail.", - task_id, - explicit, - ) - return args diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py index 1930f6ce1cb7..d92fe54b1198 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py @@ -34,6 +34,30 @@ class SceneEntityCfg(_SceneEntityCfg): """Integer indices of selected bodies — used for subset-sized body gathers.""" body_ids_wp: wp.array | None = None + @classmethod + def from_stable(cls, stable: _SceneEntityCfg) -> SceneEntityCfg: + """Build a warp scene-entity cfg from a stable one. + + Copies every selection field declared on the stable cfg (name, joint + names/ids, body names/ids, fixed-tendon names/ids, object-collection + names/ids, ``preserve_order``); warp-specific fields stay ``None`` + and are filled by :meth:`resolve` at scene build time. Used by the + warp frontend to promote :class:`SceneEntityCfg` instances embedded + in term ``params`` without resorting to a ``__class__`` reassign. + """ + return cls( + name=stable.name, + joint_names=stable.joint_names, + joint_ids=stable.joint_ids, + fixed_tendon_names=stable.fixed_tendon_names, + fixed_tendon_ids=stable.fixed_tendon_ids, + body_names=stable.body_names, + body_ids=stable.body_ids, + object_collection_names=stable.object_collection_names, + object_collection_ids=stable.object_collection_ids, + preserve_order=stable.preserve_order, + ) + def resolve(self, scene: InteractiveScene): # run the stable resolution first (fills joint_ids/body_ids from names/regex) super().resolve(scene) diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py new file mode 100644 index 000000000000..a35c21dd07ed --- /dev/null +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -0,0 +1,417 @@ +# 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 + +"""Tests for :mod:`isaaclab_experimental.envs.frontend`. + +Pure-Python unit tests; no app launch. Covers: + +* :class:`Frontend` / :class:`Workflow` enum surface. +* :func:`SceneEntityCfg.from_stable` field copy. +* :func:`_require_newton_physics` hard-check. +* :func:`_promote_scene_entity_cfgs` walks ``term.params`` dicts. +* :func:`_swap_mdp` swaps ``func`` *and* ``class_type``; raises with a path + list when twins are missing. +* :func:`_resolve_warp_twin` rejects stable-origin re-exports. +* :func:`_require_direct_is_warp_task` accepts warp-rooted entry points + and rejects stable ones. +""" + +from __future__ import annotations + +import types +import unittest +from typing import Any + +import gymnasium as gym +from isaaclab_experimental.envs.frontend import ( + Frontend, + FrontendIncompatibleError, + Workflow, + _is_swap_candidate, + _iter_term_attrs, + _promote_scene_entity_cfgs, + _require_direct_is_warp_task, + _require_newton_physics, + _resolve_warp_twin, + _swap_mdp, + _walk_attrs, +) +from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as WarpSceneEntityCfg +from isaaclab_newton.physics import NewtonCfg +from isaaclab_physx.physics import PhysxCfg + +from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as StableSceneEntityCfg + +# ====================================================================== +# Enums +# ====================================================================== + + +class TestEnums(unittest.TestCase): + def test_frontend_values(self): + self.assertEqual(Frontend.TORCH, "torch") + self.assertEqual(Frontend.WARP, "warp") + + def test_frontend_coercion(self): + self.assertIs(Frontend("torch"), Frontend.TORCH) + self.assertIs(Frontend("warp"), Frontend.WARP) + with self.assertRaises(ValueError): + Frontend("kit") + + def test_workflow_values(self): + self.assertEqual(Workflow.MANAGER_BASED, "manager_based") + self.assertEqual(Workflow.DIRECT, "direct") + + +# ====================================================================== +# SceneEntityCfg.from_stable +# ====================================================================== + + +class TestFromStable(unittest.TestCase): + def test_copies_minimum_fields(self): + stable = StableSceneEntityCfg(name="robot") + warp = WarpSceneEntityCfg.from_stable(stable) + self.assertIsInstance(warp, WarpSceneEntityCfg) + self.assertEqual(warp.name, "robot") + # Warp-only fields stay None until :meth:`resolve` runs. + self.assertIsNone(warp.joint_mask) + self.assertIsNone(warp.joint_ids_wp) + self.assertIsNone(warp.body_ids_wp) + + def test_copies_all_selection_fields(self): + stable = StableSceneEntityCfg( + name="robot", + joint_names=["lf_hip"], + joint_ids=[0, 1, 2], + fixed_tendon_names=["tendon_a"], + fixed_tendon_ids=[5], + body_names=["base", "lf_foot"], + body_ids=[0, 4], + object_collection_names=["objs"], + object_collection_ids=[7], + preserve_order=True, + ) + warp = WarpSceneEntityCfg.from_stable(stable) + for field in ( + "name", + "joint_names", + "joint_ids", + "fixed_tendon_names", + "fixed_tendon_ids", + "body_names", + "body_ids", + "object_collection_names", + "object_collection_ids", + "preserve_order", + ): + self.assertEqual(getattr(warp, field), getattr(stable, field), msg=f"field {field!r} mismatch") + + +# ====================================================================== +# _require_newton_physics +# ====================================================================== + + +class TestRequireNewtonPhysics(unittest.TestCase): + def _cfg_with(self, physics: Any) -> Any: + cfg = types.SimpleNamespace() + cfg.sim = types.SimpleNamespace(physics=physics) + return cfg + + def test_passes_for_newton(self): + cfg = self._cfg_with(NewtonCfg()) + _require_newton_physics(cfg, "Isaac-Test-v0") # no raise + + def test_rejects_physx(self): + cfg = self._cfg_with(PhysxCfg()) + with self.assertRaises(FrontendIncompatibleError) as exc: + _require_newton_physics(cfg, "Isaac-Test-v0") + self.assertIn("presets=newton", str(exc.exception)) + self.assertIn("PhysxCfg", str(exc.exception)) + + def test_rejects_none(self): + cfg = self._cfg_with(None) + with self.assertRaises(FrontendIncompatibleError): + _require_newton_physics(cfg, "Isaac-Test-v0") + + +# ====================================================================== +# _promote_scene_entity_cfgs +# ====================================================================== + + +class _Term: + """Minimal stand-in for a manager term cfg.""" + + def __init__(self, params: dict | None = None, func=None, class_type=None): + self.params = params if params is not None else {} + if func is not None: + self.func = func + if class_type is not None: + self.class_type = class_type + + +class _Group: + """Minimal stand-in for a manager-cfg group (e.g. RewardsCfg).""" + + def __init__(self, **terms: Any): + for name, term in terms.items(): + setattr(self, name, term) + + +class _ObsCfg: + def __init__(self, policy: _Group): + self.policy = policy + + +def _make_cfg(**groups: Any) -> Any: + cfg = types.SimpleNamespace() + for name, value in groups.items(): + setattr(cfg, name, value) + return cfg + + +class TestPromoteSceneEntityCfgs(unittest.TestCase): + def test_promotes_in_params(self): + stable = StableSceneEntityCfg(name="robot", joint_names=["lf_hip"]) + term = _Term(params={"asset_cfg": stable, "scale": 1.0}) + cfg = _make_cfg(rewards=_Group(track=term)) + _promote_scene_entity_cfgs(cfg) + promoted = term.params["asset_cfg"] + self.assertIsInstance(promoted, WarpSceneEntityCfg) + self.assertEqual(promoted.name, "robot") + self.assertEqual(promoted.joint_names, ["lf_hip"]) + # Non-SceneEntityCfg params are untouched. + self.assertEqual(term.params["scale"], 1.0) + + def test_skips_already_warp(self): + warp = WarpSceneEntityCfg(name="robot") + term = _Term(params={"asset_cfg": warp}) + cfg = _make_cfg(rewards=_Group(t=term)) + _promote_scene_entity_cfgs(cfg) + self.assertIs(term.params["asset_cfg"], warp) # unchanged identity + + def test_walks_all_term_paths(self): + # Drop a stable cfg in every supported group; all should promote. + groups = {} + terms: list[_Term] = [] + for group_name in ("rewards", "events", "terminations", "commands", "curriculum"): + t = _Term(params={"asset_cfg": StableSceneEntityCfg(name=group_name)}) + terms.append(t) + groups[group_name] = _Group(t=t) + # observations is nested as observations.policy + obs_term = _Term(params={"asset_cfg": StableSceneEntityCfg(name="obs")}) + terms.append(obs_term) + groups["observations"] = _ObsCfg(policy=_Group(t=obs_term)) + # actions group also walked + act_term = _Term(params={"asset_cfg": StableSceneEntityCfg(name="act")}) + terms.append(act_term) + groups["actions"] = _Group(t=act_term) + + cfg = _make_cfg(**groups) + _promote_scene_entity_cfgs(cfg) + for t in terms: + self.assertIsInstance(t.params["asset_cfg"], WarpSceneEntityCfg) + + +# ====================================================================== +# _swap_mdp +# ====================================================================== + + +# A fake "stable" mdp module the test fixture stands in for +# ``isaaclab_tasks..mdp`` — symbols here pretend to live there. +def _stable_func(env, **params): + return None + + +class _StableActionCls: + pass + + +_stable_func.__module__ = "isaaclab_tasks.fake_task.mdp" +_StableActionCls.__module__ = "isaaclab_tasks.fake_task.mdp" + + +# And a fake warp twin module the test installs into sys.modules under the +# expected name resolution path. Symbols here pretend to live under +# ``isaaclab_experimental.envs.mdp`` (the fallback). +def _warp_twin_func(env, out, **params): + return None + + +class _WarpActionCls: + pass + + +_warp_twin_func.__module__ = "isaaclab_experimental.envs.mdp" +_WarpActionCls.__module__ = "isaaclab_experimental.envs.mdp" + + +class _FakeMdpModule: + """Stand-in for a warp mdp module containing twins.""" + + __name__ = "test_fake_warp_mdp" + + +class TestSwapMdp(unittest.TestCase): + def _patch_modules(self, name_to_symbol: dict[str, Any]) -> _FakeMdpModule: + m = _FakeMdpModule() + for name, sym in name_to_symbol.items(): + setattr(m, name, sym) + return m + + def _patched_warp_mdp_modules(self, modules: list[Any]): + # Patch _warp_mdp_modules at the frontend module level so _swap_mdp + # uses our fake module list instead of doing real importlib lookups. + import isaaclab_experimental.envs.frontend as fe + + self._orig = fe._warp_mdp_modules + fe._warp_mdp_modules = lambda task_id: modules # type: ignore[assignment] + + def setUp(self) -> None: + self._orig = None + + def tearDown(self) -> None: + if self._orig is not None: + import isaaclab_experimental.envs.frontend as fe + + fe._warp_mdp_modules = self._orig + + def test_swaps_func_and_class_type(self): + fake = self._patch_modules({"_stable_func": _warp_twin_func, "_StableActionCls": _WarpActionCls}) + self._patched_warp_mdp_modules([fake]) + term_reward = _Term(func=_stable_func) + term_action = _Term(class_type=_StableActionCls) + cfg = _make_cfg(rewards=_Group(r=term_reward), actions=_Group(a=term_action)) + _swap_mdp(cfg, "Isaac-Test-v0") + self.assertIs(term_reward.func, _warp_twin_func) + self.assertIs(term_action.class_type, _WarpActionCls) + + def test_missing_twin_raises_with_path_list(self): + # No twins available — every term should be reported as missing. + fake = self._patch_modules({}) + self._patched_warp_mdp_modules([fake]) + term = _Term(func=_stable_func) + cfg = _make_cfg(rewards=_Group(track=term)) + with self.assertRaises(FrontendIncompatibleError) as exc: + _swap_mdp(cfg, "Isaac-Test-v0") + msg = str(exc.exception) + self.assertIn("rewards.track.func", msg) + self.assertIn("_stable_func", msg) + # The cfg term wasn't mutated (we hard-failed before partial application). + self.assertIs(term.func, _stable_func) + + def test_skips_already_warp(self): + fake = self._patch_modules({}) + self._patched_warp_mdp_modules([fake]) + term = _Term(func=_warp_twin_func) # already warp-origin + cfg = _make_cfg(rewards=_Group(r=term)) + _swap_mdp(cfg, "Isaac-Test-v0") # no raise + self.assertIs(term.func, _warp_twin_func) + + +# ====================================================================== +# Twin resolution +# ====================================================================== + + +class TestResolveWarpTwin(unittest.TestCase): + def test_accepts_warp_origin(self): + m = types.SimpleNamespace() + m.foo = _warp_twin_func + result = _resolve_warp_twin("foo", [m]) + self.assertIs(result, _warp_twin_func) + + def test_rejects_stable_origin(self): + m = types.SimpleNamespace() + m.foo = _stable_func # same name, stable origin + self.assertIsNone(_resolve_warp_twin("foo", [m])) + + def test_returns_none_when_absent(self): + m = types.SimpleNamespace() + self.assertIsNone(_resolve_warp_twin("missing", [m])) + + +# ====================================================================== +# Swap candidate heuristic +# ====================================================================== + + +class TestIsSwapCandidate(unittest.TestCase): + def test_stable_callable_is_candidate(self): + self.assertTrue(_is_swap_candidate(_stable_func)) + + def test_warp_callable_is_not(self): + self.assertFalse(_is_swap_candidate(_warp_twin_func)) + + def test_non_callable_is_not(self): + self.assertFalse(_is_swap_candidate(42)) + self.assertFalse(_is_swap_candidate("string")) + + +# ====================================================================== +# Direct workflow guard +# ====================================================================== + + +_DIRECT_TEST_TASKS = { + "_Frontend-Test-Warp-Direct-v0": ("isaaclab_tasks_experimental.fake:DirectEnv", True), + "_Frontend-Test-Stable-Direct-v0": ("isaaclab_tasks.fake:DirectEnv", False), +} + + +class TestRequireDirectIsWarpTask(unittest.TestCase): + @classmethod + def setUpClass(cls): + # Register stub tasks so ``gym.spec`` resolves them. Entry-point strings + # are never invoked (the guard only inspects them), so a fake import + # path is fine. + cls._registered: list[str] = [] + for task_id, (ep, _) in _DIRECT_TEST_TASKS.items(): + try: + gym.register(id=task_id, entry_point=ep, disable_env_checker=True) + cls._registered.append(task_id) + except gym.error.Error: + # Already registered from a previous run — that's fine. + pass + + def test_accepts_warp_rooted(self): + _require_direct_is_warp_task("_Frontend-Test-Warp-Direct-v0") # no raise + + def test_rejects_stable_rooted(self): + with self.assertRaises(FrontendIncompatibleError) as exc: + _require_direct_is_warp_task("_Frontend-Test-Stable-Direct-v0") + self.assertIn("isaaclab_experimental", str(exc.exception)) + + def test_rejects_unknown_task(self): + with self.assertRaises(FrontendIncompatibleError): + _require_direct_is_warp_task("Frontend-Test-NotRegistered-v0") + + +# ====================================================================== +# Walk helpers +# ====================================================================== + + +class TestWalkHelpers(unittest.TestCase): + def test_walk_attrs_hit(self): + root = types.SimpleNamespace(a=types.SimpleNamespace(b=types.SimpleNamespace(c=42))) + self.assertEqual(_walk_attrs(root, ("a", "b", "c")), 42) + + def test_walk_attrs_miss(self): + root = types.SimpleNamespace(a=types.SimpleNamespace()) + self.assertIsNone(_walk_attrs(root, ("a", "missing"))) + self.assertIsNone(_walk_attrs(root, ("missing", "b"))) + + def test_iter_term_attrs_skips_dunders_and_none(self): + g = types.SimpleNamespace(t1=_Term(), t2=None, _internal=_Term()) + names = sorted(n for n, _ in _iter_term_attrs(g)) + self.assertEqual(names, ["t1"]) + + +if __name__ == "__main__": + unittest.main() From bd27af41f81d175e40373924517d81c330b7b22c Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 26 May 2026 06:51:58 +0000 Subject: [PATCH 11/36] Simplify frontend cfg walker and unify term-cfg type contract Frontend (envs/frontend.py) - Replace _TERM_PATHS hardcode (with its policy-only observation limitation) with _walk_terms: a recursive ManagerTermBaseCfg discovery that descends any configclass and yields each term with its path. New cfg layouts and observation sub-groups (perception, critic, camera_images, ...) are picked up automatically with no framework change. - _promote_scene_entity_cfgs and _swap_mdp consume the new walker; delete _walk_attrs / _iter_term_attrs / _TERM_PATHS. - Per-promotion log now lists the actual SceneEntityCfg paths. - Rename _require_direct_is_warp_task to _assert_direct_warp_registration. Update _detect_workflow with a note for adding new cfg roots. Manager term cfg contract - Relax stable ObservationTermCfg / RewardTermCfg / TerminationTermCfg func annotation to Callable[..., torch.Tensor | None] so the warp func(env, out) -> None contract type-checks alongside the existing torch return-value contract. - Drop the now-redundant warp-side manager_term_cfg.py shim and redirect the 9 relative imports onto isaaclab.managers.manager_term_cfg. Tests - New TestWalkTerms cases verify the recursive type-driven discovery. - TestPromoteSceneEntityCfgs / TestSwapMdp use real term cfgs and configclass fixtures so they exercise the actual walker contract. --- .../reinforcement_learning/rsl_rl/train.py | 8 +- .../isaaclab/managers/manager_term_cfg.py | 6 +- .../isaaclab_experimental/envs/frontend.py | 156 +++++---- .../managers/__init__.py | 1 - .../managers/action_manager.py | 2 +- .../managers/command_manager.py | 3 +- .../managers/event_manager.py | 3 +- .../managers/manager_base.py | 2 +- .../managers/manager_term_cfg.py | 25 -- .../managers/observation_manager.py | 2 +- .../managers/reward_manager.py | 3 +- .../managers/termination_manager.py | 3 +- .../test/envs/test_frontend.py | 303 ++++++++++-------- .../classic/humanoid/mdp/rewards.py | 3 +- 14 files changed, 278 insertions(+), 242 deletions(-) delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index 23bff4218629..1f30de33eb12 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -218,12 +218,8 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # set the log directory for the environment (works for all environment types) env_cfg.log_dir = log_dir - # Build the env via the selected frontend. The warp frontend mutates env_cfg - # in place (SceneEntityCfg promotion + MDP func/class_type swap) and then - # constructs ``ManagerBasedRLEnvWarp``; missing warp twins are a hard failure. - # When ``isaaclab_experimental`` isn't installed, the argparse step above - # has already constrained --frontend to ``torch``, so the plain ``gym.make`` - # fallback is safe. + # Build the env via the selected frontend. Warp adapts env_cfg in place; + # missing warp twins are a hard failure. render_mode = "rgb_array" if args_cli.video else None if _frontend_build is not None: env = _frontend_build(args_cli.frontend, env_cfg, args_cli.task, render_mode=render_mode) diff --git a/source/isaaclab/isaaclab/managers/manager_term_cfg.py b/source/isaaclab/isaaclab/managers/manager_term_cfg.py index aa118f8e9784..9372fbd64662 100644 --- a/source/isaaclab/isaaclab/managers/manager_term_cfg.py +++ b/source/isaaclab/isaaclab/managers/manager_term_cfg.py @@ -152,7 +152,7 @@ class CurriculumTermCfg(ManagerTermBaseCfg): class ObservationTermCfg(ManagerTermBaseCfg): """Configuration for an observation term.""" - func: Callable[..., torch.Tensor] = MISSING + func: Callable[..., torch.Tensor | None] = MISSING """The name of the function to be called. This function should take the environment object and any other parameters @@ -316,7 +316,7 @@ class EventTermCfg(ManagerTermBaseCfg): class RewardTermCfg(ManagerTermBaseCfg): """Configuration for a reward term.""" - func: Callable[..., torch.Tensor] = MISSING + func: Callable[..., torch.Tensor | None] = MISSING """The name of the function to be called. This function should take the environment object and any other parameters @@ -344,7 +344,7 @@ class RewardTermCfg(ManagerTermBaseCfg): class TerminationTermCfg(ManagerTermBaseCfg): """Configuration for a termination term.""" - func: Callable[..., torch.Tensor] = MISSING + func: Callable[..., torch.Tensor | None] = MISSING """The name of the function to be called. This function should take the environment object and any other parameters diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 4dfc312d6481..f8b4acd2284a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -75,18 +75,6 @@ class FrontendIncompatibleError(RuntimeError): # the warp packages. Used by the direct-workflow guard. _WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") -# Term containers walked by the cfg-adaptation step. Actions are included so -# the swap logic handles ``class_type`` and ``func`` in one pass. -_TERM_PATHS: tuple[tuple[str, ...], ...] = ( - ("observations", "policy"), - ("events",), - ("rewards",), - ("terminations",), - ("commands",), - ("curriculum",), - ("actions",), -) - def build( frontend: Frontend | str, @@ -119,7 +107,7 @@ def build( if workflow is Workflow.DIRECT: # Direct workflows aren't adapted — they must already be registered # under the warp packages (e.g. ``Isaac-Cartpole-Direct-Warp-v0``). - _require_direct_is_warp_task(task_id) + _assert_direct_warp_registration(task_id) return gym.make(task_id, cfg=env_cfg, **construct_kwargs) _adapt_cfg_for_warp(env_cfg, task_id) @@ -148,11 +136,12 @@ def _adapt_cfg_for_warp(cfg: Any, task_id: str) -> None: :class:`~isaaclab.managers.SceneEntityCfg` instances under each term's ``params`` with the warp variant (which adds warp-cached ``joint_mask``, ``joint_ids_wp``, ``body_ids_wp`` fields). - 3. :func:`_swap_mdp` — for every MDP term in every group (observations, - events, rewards, terminations, commands, curriculum, actions), replace - any stable ``func`` *or* ``class_type`` with its same-named warp twin. - A missing twin raises :class:`FrontendIncompatibleError` — partial - coverage is unsafe under the warp managers' kernel-only signature. + 3. :func:`_swap_mdp` — for every MDP term found anywhere in the cfg tree + (discovered by :func:`_walk_terms` via :class:`ManagerTermBaseCfg` + subclassing, not by hard-coded attribute names), replace any stable + ``func`` *or* ``class_type`` with its same-named warp twin. A missing + twin raises :class:`FrontendIncompatibleError` — partial coverage is + unsafe under the warp managers' kernel-only signature. """ _require_newton_physics(cfg, task_id) _promote_scene_entity_cfgs(cfg) @@ -183,8 +172,8 @@ def _require_newton_physics(cfg: Any, task_id: str) -> None: def _promote_scene_entity_cfgs(cfg: Any) -> None: """Replace stable :class:`SceneEntityCfg` instances with the warp variant. - Walks every ``term.params: dict`` under each term group and rebuilds any - stable :class:`SceneEntityCfg` value via + Iterates every term cfg in the tree (via :func:`_walk_terms`) and rebuilds + any stable :class:`SceneEntityCfg` value under ``term.params`` through :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable`. The warp variant subclasses the stable one, so type checks elsewhere stay valid; the new fields (``joint_mask`` / ``joint_ids_wp`` / ``body_ids_wp``) @@ -192,35 +181,42 @@ def _promote_scene_entity_cfgs(cfg: Any) -> None: """ from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSceneEntityCfg - promoted = 0 - for path in _TERM_PATHS: - group = _walk_attrs(cfg, path) - if group is None: + promoted: list[str] = [] + for path, term in _walk_terms(cfg): + params = getattr(term, "params", None) + if not isinstance(params, dict): continue - for _name, term in _iter_term_attrs(group): - params = getattr(term, "params", None) - if not isinstance(params, dict): + for key, value in list(params.items()): + if isinstance(value, _WarpSceneEntityCfg) or not isinstance(value, _StableSceneEntityCfg): continue - for key, value in list(params.items()): - if isinstance(value, _WarpSceneEntityCfg) or not isinstance(value, _StableSceneEntityCfg): - continue - params[key] = _WarpSceneEntityCfg.from_stable(value) - promoted += 1 + params[key] = _WarpSceneEntityCfg.from_stable(value) + promoted.append(f"{'.'.join(path)}.params[{key!r}] ({value.name!r})") if promoted: - logger.info("frontend.warp: promoted %d SceneEntityCfg instance(s) to warp variant", promoted) + logger.info( + "frontend.warp: promoted %d SceneEntityCfg instance(s) to warp variant:\n %s", + len(promoted), + "\n ".join(promoted), + ) def _swap_mdp(cfg: Any, task_id: str) -> None: """Replace ``term.func`` and ``term.class_type`` with their warp twins. - Walks the same term paths used by :func:`_promote_scene_entity_cfgs` and - on each term swaps whichever of ``func`` / ``class_type`` is set to a - stable-origin symbol. Twin lookup is name-based against the task's - matching ``isaaclab_tasks_experimental.<...>.mdp`` module and, as a - fallback, :mod:`isaaclab_experimental.envs.mdp`. Any missing twin raises + Iterates every term cfg in the tree (via :func:`_walk_terms`) and on each + term swaps whichever of ``func`` / ``class_type`` is a stable-origin + callable. Twin lookup is name-based against the task's matching + ``isaaclab_tasks_experimental.<...>.mdp`` module and, as a fallback, + :mod:`isaaclab_experimental.envs.mdp`. Any missing twin raises :class:`FrontendIncompatibleError` listing every affected term — partial swaps would leave torch-style callables in the cfg and the warp managers would call them with the wrong signature. + + The warp-side side declarations (``out_dim``, ``axes``, ``observation_type``) + that the warp managers need at init are *not* supplied by this swap; they + travel with the warp twin function itself via its own + ``@generic_io_descriptor_warp(out_dim=…)`` decorator. This function only + substitutes the callable; the manager reads the new func's annotations + when it parses the term cfg. """ modules = _warp_mdp_modules(task_id) searched = tuple(m.__name__ for m in modules) @@ -228,22 +224,18 @@ def _swap_mdp(cfg: Any, task_id: str) -> None: swapped = 0 missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) - for path in _TERM_PATHS: - group = _walk_attrs(cfg, path) - if group is None: - continue - location_prefix = ".".join(path) - for name, term in _iter_term_attrs(group): - for attr in ("func", "class_type"): - stable = getattr(term, attr, None) - if stable is None or not _is_swap_candidate(stable): - continue - twin = _resolve_warp_twin(stable.__name__, modules) - if twin is None: - missing.append((f"{location_prefix}.{name}", attr, stable.__name__)) - continue - setattr(term, attr, twin) - swapped += 1 + for path, term in _walk_terms(cfg): + location = ".".join(path) + for attr in ("func", "class_type"): + stable = getattr(term, attr, None) + if stable is None or not _is_swap_candidate(stable): + continue + twin = _resolve_warp_twin(stable.__name__, modules) + if twin is None: + missing.append((location, attr, stable.__name__)) + continue + setattr(term, attr, twin) + swapped += 1 if missing: lines = "\n ".join(f"{loc}.{attr}: no warp twin for {sym!r}" for loc, attr, sym in missing) @@ -260,7 +252,13 @@ def _swap_mdp(cfg: Any, task_id: str) -> None: def _detect_workflow(cfg: Any) -> Workflow: - """Classify the env cfg into manager-based or direct (used to pick build path).""" + """Classify the env cfg into manager-based or direct (used to pick build path). + + Note: + The four env cfg roots (ManagerBasedEnvCfg, ManagerBasedRLEnvCfg, + DirectRLEnvCfg, DirectMARLEnvCfg) do not share a common base class. + When a new cfg root is added, extend the isinstance tuples below. + """ if isinstance(cfg, ManagerBasedRLEnvCfg): return Workflow.MANAGER_BASED if isinstance(cfg, (DirectRLEnvCfg, DirectMARLEnvCfg)): @@ -271,7 +269,7 @@ def _detect_workflow(cfg: Any) -> Workflow: ) -def _require_direct_is_warp_task(task_id: str) -> None: +def _assert_direct_warp_registration(task_id: str) -> None: """For direct workflows, the task must be pre-registered under the warp packages.""" try: spec = gym.spec(task_id) @@ -352,22 +350,38 @@ def _is_swap_candidate(value: Any) -> bool: return True -def _walk_attrs(root: Any, path: tuple[str, ...]) -> Any: - """Walk ``root..…``; return ``None`` on any miss.""" - node = root - for attr in path: - node = getattr(node, attr, None) - if node is None: - return None - return node +def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], Any]]: + """Yield ``(path, term)`` for every :class:`ManagerTermBaseCfg` in the cfg tree. + + Behavior at each node: + + * Match (:class:`ManagerTermBaseCfg` instance): yield ``(path, node)`` and stop — + do not descend into ``term.params`` / ``term.func``. + * Configclass: don't yield; recurse into every non-underscore attribute, + extending the path. ``observations``, ``rewards``, ``events``, sub-groups + like ``observations.policy`` / ``observations.perception``, and anything + nested deeper are reached transparently. + * Anything else (plain Python data, callables, non-configclass objects): + stop. No yield, no recursion. + Driven entirely by type — no attribute names are hardcoded — so future + cfg layouts (extra observation groups, new nesting, etc.) are picked up + automatically as long as their terms subclass :class:`ManagerTermBaseCfg`. + """ + from isaaclab.managers.manager_term_cfg import ManagerTermBaseCfg -def _iter_term_attrs(group: Any) -> Iterator[tuple[str, Any]]: - """Yield ``(name, term)`` pairs from a manager-cfg group, skipping dunders/Nones.""" - if group is None: + if isinstance(node, ManagerTermBaseCfg): + yield path, node + return + if not hasattr(node, "__dataclass_fields__"): return - for name in [n for n in dir(group) if not n.startswith("_")]: - term = getattr(group, name, None) - if term is None: + for name in dir(node): + if name.startswith("_"): + continue + try: + value = getattr(node, name, None) + except Exception: # noqa: BLE001 — defensive; some descriptors can raise on attribute access + continue + if value is None: continue - yield name, term + yield from _walk_terms(value, path + (name,)) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py b/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py index b4521b98434a..757da5def93f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.py @@ -17,7 +17,6 @@ # Override the stable implementation with the experimental fork. from .manager_base import ManagerTermBase # noqa: F401 -from .manager_term_cfg import ObservationTermCfg, RewardTermCfg, TerminationTermCfg # noqa: F401 from .observation_manager import ObservationManager # noqa: F401 from .reward_manager import RewardManager # noqa: F401 from .scene_entity_cfg import SceneEntityCfg # noqa: F401 diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py index 672af82bc8ab..902c74d6d095 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/action_manager.py @@ -20,9 +20,9 @@ from isaaclab.assets import AssetBase from isaaclab.envs.utils.io_descriptors import GenericActionIODescriptor +from isaaclab.managers.manager_term_cfg import ActionTermCfg from .manager_base import ManagerBase, ManagerTermBase -from .manager_term_cfg import ActionTermCfg if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py index 8b4e8f83dbe7..dfafeef5e206 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/command_manager.py @@ -17,10 +17,11 @@ import warp as wp from prettytable import PrettyTable +from isaaclab.managers.manager_term_cfg import CommandTermCfg + from isaaclab_experimental.utils.warp.kernels import compute_reset_scale, count_masked from .manager_base import ManagerBase, ManagerTermBase -from .manager_term_cfg import CommandTermCfg # import omni.kit.app diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py index 3b36613a2ac9..cc5b77222674 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/event_manager.py @@ -29,8 +29,9 @@ import warp as wp from prettytable import PrettyTable +from isaaclab.managers.manager_term_cfg import EventTermCfg + from .manager_base import ManagerBase -from .manager_term_cfg import EventTermCfg logger = logging.getLogger(__name__) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py index 6caea3eebcbb..699e27170e02 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py @@ -26,11 +26,11 @@ import warp as wp import isaaclab.utils.string as string_utils +from isaaclab.managers.manager_term_cfg import ManagerTermBaseCfg from isaaclab.utils import class_to_dict, string_to_callable from isaaclab_experimental.utils.warp import is_warp_capturable -from .manager_term_cfg import ManagerTermBaseCfg from .scene_entity_cfg import SceneEntityCfg # import omni.timeline diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py deleted file mode 100644 index 604b138003d4..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_term_cfg.py +++ /dev/null @@ -1,25 +0,0 @@ -# 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 - -"""Configuration terms for different managers (experimental, Warp-first). - -The warp manager classes accept the same term cfg shapes as the stable -managers, so this module simply re-exports the stable term cfg classes -to keep ``isinstance(stable_term, warp.TermCfg)`` true. This is what -lets the :class:`isaaclab_experimental.envs.warp_frontend.WarpFrontend` -adapter run a stable cfg through the warp runtime without rewrapping -every term. - -The ``func`` callable on each term is still expected to follow the -warp-first ``func(env, out, **params) -> None`` signature when run on -the warp runtime; only the *type* is shared with stable. -""" - -from __future__ import annotations - -# Re-export stable manager term cfg classes verbatim. -# `from … import *` carries `ObservationTermCfg`, `RewardTermCfg`, -# `TerminationTermCfg`, `ManagerTermBaseCfg`, etc. -from isaaclab.managers.manager_term_cfg import * # noqa: F401,F403 diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py index 74d0a9a955be..059ae2afdce1 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py @@ -55,6 +55,7 @@ import warp as wp from prettytable import PrettyTable +from isaaclab.managers.manager_term_cfg import ObservationGroupCfg, ObservationTermCfg from isaaclab.utils import class_to_dict from isaaclab_experimental.utils import modifiers, noise @@ -62,7 +63,6 @@ from isaaclab_experimental.utils.torch_utils import clone_obs_buffer from .manager_base import ManagerBase, ManagerTermBase -from .manager_term_cfg import ObservationGroupCfg, ObservationTermCfg if TYPE_CHECKING: from isaaclab.envs import ManagerBasedEnv diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py index 67dcbc055c2f..99e3d9af979c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py @@ -18,10 +18,11 @@ import warp as wp from prettytable import PrettyTable +from isaaclab.managers.manager_term_cfg import RewardTermCfg + from isaaclab_experimental.utils.warp.kernels import compute_reset_scale, count_masked from .manager_base import ManagerBase, ManagerTermBase -from .manager_term_cfg import RewardTermCfg if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py index 8a768651b292..732edf9f2fe2 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/termination_manager.py @@ -22,8 +22,9 @@ import warp as wp from prettytable import PrettyTable +from isaaclab.managers.manager_term_cfg import TerminationTermCfg + from .manager_base import ManagerBase, ManagerTermBase -from .manager_term_cfg import TerminationTermCfg if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnv diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index a35c21dd07ed..7f884674f58e 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -10,12 +10,13 @@ * :class:`Frontend` / :class:`Workflow` enum surface. * :func:`SceneEntityCfg.from_stable` field copy. * :func:`_require_newton_physics` hard-check. +* :func:`_walk_terms` recursive ManagerTermBaseCfg discovery. * :func:`_promote_scene_entity_cfgs` walks ``term.params`` dicts. * :func:`_swap_mdp` swaps ``func`` *and* ``class_type``; raises with a path list when twins are missing. * :func:`_resolve_warp_twin` rejects stable-origin re-exports. -* :func:`_require_direct_is_warp_task` accepts warp-rooted entry points - and rejects stable ones. +* :func:`_assert_direct_warp_registration` accepts warp-rooted entry + points and rejects stable ones. """ from __future__ import annotations @@ -29,20 +30,21 @@ Frontend, FrontendIncompatibleError, Workflow, + _assert_direct_warp_registration, _is_swap_candidate, - _iter_term_attrs, _promote_scene_entity_cfgs, - _require_direct_is_warp_task, _require_newton_physics, _resolve_warp_twin, _swap_mdp, - _walk_attrs, + _walk_terms, ) from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as WarpSceneEntityCfg from isaaclab_newton.physics import NewtonCfg from isaaclab_physx.physics import PhysxCfg +from isaaclab.managers.manager_term_cfg import EventTermCfg, ObservationTermCfg, RewardTermCfg from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as StableSceneEntityCfg +from isaaclab.utils.configclass import configclass # ====================================================================== # Enums @@ -139,116 +141,189 @@ def test_rejects_none(self): # ====================================================================== -# _promote_scene_entity_cfgs +# Configclass fixtures for the walker / swap tests. # ====================================================================== +# +# These mirror the real cfg shape so :func:`_walk_terms` descends into them +# (it only descends into objects with ``__dataclass_fields__``). Term cfgs +# use the real :class:`EventTermCfg`/:class:`RewardTermCfg`/:class:`ObservationTermCfg` +# so the walker's ``isinstance(ManagerTermBaseCfg)`` discriminator yields them. -class _Term: - """Minimal stand-in for a manager term cfg.""" +def _stable_func(env, **params): + return None - def __init__(self, params: dict | None = None, func=None, class_type=None): - self.params = params if params is not None else {} - if func is not None: - self.func = func - if class_type is not None: - self.class_type = class_type +class _StableActionCls: + pass -class _Group: - """Minimal stand-in for a manager-cfg group (e.g. RewardsCfg).""" - def __init__(self, **terms: Any): - for name, term in terms.items(): - setattr(self, name, term) +_stable_func.__module__ = "isaaclab_tasks.fake_task.mdp" +_StableActionCls.__module__ = "isaaclab_tasks.fake_task.mdp" -class _ObsCfg: - def __init__(self, policy: _Group): - self.policy = policy +def _warp_twin_func(env, out, **params): + return None -def _make_cfg(**groups: Any) -> Any: - cfg = types.SimpleNamespace() - for name, value in groups.items(): - setattr(cfg, name, value) - return cfg +class _WarpActionCls: + pass -class TestPromoteSceneEntityCfgs(unittest.TestCase): - def test_promotes_in_params(self): - stable = StableSceneEntityCfg(name="robot", joint_names=["lf_hip"]) - term = _Term(params={"asset_cfg": stable, "scale": 1.0}) - cfg = _make_cfg(rewards=_Group(track=term)) - _promote_scene_entity_cfgs(cfg) - promoted = term.params["asset_cfg"] - self.assertIsInstance(promoted, WarpSceneEntityCfg) - self.assertEqual(promoted.name, "robot") - self.assertEqual(promoted.joint_names, ["lf_hip"]) - # Non-SceneEntityCfg params are untouched. - self.assertEqual(term.params["scale"], 1.0) +_warp_twin_func.__module__ = "isaaclab_experimental.envs.mdp" +_WarpActionCls.__module__ = "isaaclab_experimental.envs.mdp" + + +@configclass +class _PolicyObsGroup: + """Stand-in for a per-task ObservationsCfg sub-group (e.g. PolicyCfg).""" + + o1: ObservationTermCfg | None = None + o2: ObservationTermCfg | None = None + + +@configclass +class _ExtraObsGroup: + """A second obs group (named arbitrarily) to exercise multi-group walks.""" + + o3: ObservationTermCfg | None = None - def test_skips_already_warp(self): - warp = WarpSceneEntityCfg(name="robot") - term = _Term(params={"asset_cfg": warp}) - cfg = _make_cfg(rewards=_Group(t=term)) - _promote_scene_entity_cfgs(cfg) - self.assertIs(term.params["asset_cfg"], warp) # unchanged identity - - def test_walks_all_term_paths(self): - # Drop a stable cfg in every supported group; all should promote. - groups = {} - terms: list[_Term] = [] - for group_name in ("rewards", "events", "terminations", "commands", "curriculum"): - t = _Term(params={"asset_cfg": StableSceneEntityCfg(name=group_name)}) - terms.append(t) - groups[group_name] = _Group(t=t) - # observations is nested as observations.policy - obs_term = _Term(params={"asset_cfg": StableSceneEntityCfg(name="obs")}) - terms.append(obs_term) - groups["observations"] = _ObsCfg(policy=_Group(t=obs_term)) - # actions group also walked - act_term = _Term(params={"asset_cfg": StableSceneEntityCfg(name="act")}) - terms.append(act_term) - groups["actions"] = _Group(t=act_term) - - cfg = _make_cfg(**groups) - _promote_scene_entity_cfgs(cfg) - for t in terms: - self.assertIsInstance(t.params["asset_cfg"], WarpSceneEntityCfg) + +@configclass +class _ObservationsCfg: + policy: _PolicyObsGroup | None = None + perception: _ExtraObsGroup | None = None + + +@configclass +class _RewardsCfg: + r1: RewardTermCfg | None = None + r2: RewardTermCfg | None = None + + +@configclass +class _EventsCfg: + e1: EventTermCfg | None = None + + +@configclass +class _CfgFixture: + observations: _ObservationsCfg | None = None + rewards: _RewardsCfg | None = None + events: _EventsCfg | None = None + + +def _term(func=None, params: dict | None = None) -> RewardTermCfg: + """Cheap RewardTermCfg builder for tests; the cfg class is irrelevant for swap/walk logic.""" + return RewardTermCfg(func=func or _stable_func, weight=1.0, params=params or {}) # ====================================================================== -# _swap_mdp +# _walk_terms # ====================================================================== -# A fake "stable" mdp module the test fixture stands in for -# ``isaaclab_tasks..mdp`` — symbols here pretend to live there. -def _stable_func(env, **params): - return None +class TestWalkTerms(unittest.TestCase): + def test_yields_each_term_with_its_path(self): + cfg = _CfgFixture( + rewards=_RewardsCfg(r1=_term(), r2=_term()), + events=_EventsCfg(e1=EventTermCfg(func=_stable_func, mode="reset")), + ) + # Configclass instances aren't hashable, so collect paths only. + paths = {".".join(p) for p, _ in _walk_terms(cfg)} + self.assertEqual(paths, {"rewards.r1", "rewards.r2", "events.e1"}) + + def test_descends_into_obs_subgroups(self): + cfg = _CfgFixture( + observations=_ObservationsCfg( + policy=_PolicyObsGroup(o1=ObservationTermCfg(func=_stable_func)), + perception=_ExtraObsGroup(o3=ObservationTermCfg(func=_stable_func)), + ), + ) + paths = {".".join(p) for p, _ in _walk_terms(cfg)} + # Discovery is purely type-driven; no obs group name is hardcoded. + self.assertEqual(paths, {"observations.policy.o1", "observations.perception.o3"}) + def test_stops_at_terms(self): + # The walker must not descend into term.params / term.func — yields the term itself. + nested_se_cfg = StableSceneEntityCfg(name="robot") + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": nested_se_cfg}))) + terms = list(_walk_terms(cfg)) + self.assertEqual(len(terms), 1) + _, term = terms[0] + self.assertIsInstance(term, RewardTermCfg) -class _StableActionCls: - pass + def test_skips_non_configclass_attrs(self): + # A namespace without __dataclass_fields__ is not descended into. + cfg = types.SimpleNamespace(some_plain_attr="hello") + self.assertEqual(list(_walk_terms(cfg)), []) + def test_skips_none_subtrees(self): + cfg = _CfgFixture(rewards=None, events=None) + self.assertEqual(list(_walk_terms(cfg)), []) -_stable_func.__module__ = "isaaclab_tasks.fake_task.mdp" -_StableActionCls.__module__ = "isaaclab_tasks.fake_task.mdp" +# ====================================================================== +# _promote_scene_entity_cfgs +# ====================================================================== -# And a fake warp twin module the test installs into sys.modules under the -# expected name resolution path. Symbols here pretend to live under -# ``isaaclab_experimental.envs.mdp`` (the fallback). -def _warp_twin_func(env, out, **params): - return None +class TestPromoteSceneEntityCfgs(unittest.TestCase): + def test_promotes_in_params(self): + cfg = _CfgFixture( + rewards=_RewardsCfg( + r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="robot", joint_names=["lf_hip"]), "scale": 1.0}) + ) + ) + _promote_scene_entity_cfgs(cfg) + promoted = cfg.rewards.r1.params["asset_cfg"] + self.assertIsInstance(promoted, WarpSceneEntityCfg) + self.assertEqual(promoted.name, "robot") + self.assertEqual(promoted.joint_names, ["lf_hip"]) + # Non-SceneEntityCfg params are untouched. + self.assertEqual(cfg.rewards.r1.params["scale"], 1.0) -class _WarpActionCls: - pass + def test_skips_already_warp(self): + # configclass init deep-copies params, so identity won't hold across + # construction; what we actually want to assert is "no re-promotion": + # the asset_cfg remains a WarpSceneEntityCfg (i.e., wasn't passed + # back through `from_stable`). + warp = WarpSceneEntityCfg(name="robot", joint_names=["lf_hip"]) + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": warp}))) + before = cfg.rewards.r1.params["asset_cfg"] + _promote_scene_entity_cfgs(cfg) + after = cfg.rewards.r1.params["asset_cfg"] + self.assertIsInstance(after, WarpSceneEntityCfg) + # The asset_cfg object was not replaced by another from_stable call. + self.assertIs(after, before) + + def test_walks_all_term_groups(self): + cfg = _CfgFixture( + rewards=_RewardsCfg(r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="r")})), + events=_EventsCfg( + e1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="e")}) + ), + observations=_ObservationsCfg( + policy=_PolicyObsGroup( + o1=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-pol")}) + ), + perception=_ExtraObsGroup( + o3=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-per")}) + ), + ), + ) + _promote_scene_entity_cfgs(cfg) + self.assertIsInstance(cfg.rewards.r1.params["asset_cfg"], WarpSceneEntityCfg) + self.assertIsInstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) + self.assertIsInstance(cfg.observations.policy.o1.params["asset_cfg"], WarpSceneEntityCfg) + # The perception sub-group is reached even though its attribute name is + # not hardcoded in the framework. + self.assertIsInstance(cfg.observations.perception.o3.params["asset_cfg"], WarpSceneEntityCfg) -_warp_twin_func.__module__ = "isaaclab_experimental.envs.mdp" -_WarpActionCls.__module__ = "isaaclab_experimental.envs.mdp" +# ====================================================================== +# _swap_mdp +# ====================================================================== class _FakeMdpModule: @@ -265,8 +340,6 @@ def _patch_modules(self, name_to_symbol: dict[str, Any]) -> _FakeMdpModule: return m def _patched_warp_mdp_modules(self, modules: list[Any]): - # Patch _warp_mdp_modules at the frontend module level so _swap_mdp - # uses our fake module list instead of doing real importlib lookups. import isaaclab_experimental.envs.frontend as fe self._orig = fe._warp_mdp_modules @@ -284,34 +357,32 @@ def tearDown(self) -> None: def test_swaps_func_and_class_type(self): fake = self._patch_modules({"_stable_func": _warp_twin_func, "_StableActionCls": _WarpActionCls}) self._patched_warp_mdp_modules([fake]) - term_reward = _Term(func=_stable_func) - term_action = _Term(class_type=_StableActionCls) - cfg = _make_cfg(rewards=_Group(r=term_reward), actions=_Group(a=term_action)) + term_reward = _term(func=_stable_func) + term_action = _term() + term_action.class_type = _StableActionCls # set attr to exercise class_type swap + cfg = _CfgFixture(rewards=_RewardsCfg(r1=term_reward, r2=term_action)) _swap_mdp(cfg, "Isaac-Test-v0") - self.assertIs(term_reward.func, _warp_twin_func) - self.assertIs(term_action.class_type, _WarpActionCls) + self.assertIs(cfg.rewards.r1.func, _warp_twin_func) + self.assertIs(cfg.rewards.r2.class_type, _WarpActionCls) def test_missing_twin_raises_with_path_list(self): - # No twins available — every term should be reported as missing. fake = self._patch_modules({}) self._patched_warp_mdp_modules([fake]) - term = _Term(func=_stable_func) - cfg = _make_cfg(rewards=_Group(track=term)) + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_stable_func))) with self.assertRaises(FrontendIncompatibleError) as exc: _swap_mdp(cfg, "Isaac-Test-v0") msg = str(exc.exception) - self.assertIn("rewards.track.func", msg) + self.assertIn("rewards.r1.func", msg) self.assertIn("_stable_func", msg) - # The cfg term wasn't mutated (we hard-failed before partial application). - self.assertIs(term.func, _stable_func) + # The cfg term wasn't mutated for the missing twin. + self.assertIs(cfg.rewards.r1.func, _stable_func) def test_skips_already_warp(self): fake = self._patch_modules({}) self._patched_warp_mdp_modules([fake]) - term = _Term(func=_warp_twin_func) # already warp-origin - cfg = _make_cfg(rewards=_Group(r=term)) + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_warp_twin_func))) _swap_mdp(cfg, "Isaac-Test-v0") # no raise - self.assertIs(term.func, _warp_twin_func) + self.assertIs(cfg.rewards.r1.func, _warp_twin_func) # ====================================================================== @@ -364,7 +435,7 @@ def test_non_callable_is_not(self): } -class TestRequireDirectIsWarpTask(unittest.TestCase): +class TestAssertDirectWarpRegistration(unittest.TestCase): @classmethod def setUpClass(cls): # Register stub tasks so ``gym.spec`` resolves them. Entry-point strings @@ -376,41 +447,19 @@ def setUpClass(cls): gym.register(id=task_id, entry_point=ep, disable_env_checker=True) cls._registered.append(task_id) except gym.error.Error: - # Already registered from a previous run — that's fine. pass def test_accepts_warp_rooted(self): - _require_direct_is_warp_task("_Frontend-Test-Warp-Direct-v0") # no raise + _assert_direct_warp_registration("_Frontend-Test-Warp-Direct-v0") # no raise def test_rejects_stable_rooted(self): with self.assertRaises(FrontendIncompatibleError) as exc: - _require_direct_is_warp_task("_Frontend-Test-Stable-Direct-v0") + _assert_direct_warp_registration("_Frontend-Test-Stable-Direct-v0") self.assertIn("isaaclab_experimental", str(exc.exception)) def test_rejects_unknown_task(self): with self.assertRaises(FrontendIncompatibleError): - _require_direct_is_warp_task("Frontend-Test-NotRegistered-v0") - - -# ====================================================================== -# Walk helpers -# ====================================================================== - - -class TestWalkHelpers(unittest.TestCase): - def test_walk_attrs_hit(self): - root = types.SimpleNamespace(a=types.SimpleNamespace(b=types.SimpleNamespace(c=42))) - self.assertEqual(_walk_attrs(root, ("a", "b", "c")), 42) - - def test_walk_attrs_miss(self): - root = types.SimpleNamespace(a=types.SimpleNamespace()) - self.assertIsNone(_walk_attrs(root, ("a", "missing"))) - self.assertIsNone(_walk_attrs(root, ("missing", "b"))) - - def test_iter_term_attrs_skips_dunders_and_none(self): - g = types.SimpleNamespace(t1=_Term(), t2=None, _internal=_Term()) - names = sorted(n for n, _ in _iter_term_attrs(g)) - self.assertEqual(names, ["t1"]) + _assert_direct_warp_registration("Frontend-Test-NotRegistered-v0") if __name__ == "__main__": diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py index f0e47dfbbf05..beecd526d245 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py @@ -23,9 +23,8 @@ from isaaclab.assets import Articulation if TYPE_CHECKING: - from isaaclab_experimental.managers.manager_term_cfg import RewardTermCfg - from isaaclab.envs import ManagerBasedRLEnv + from isaaclab.managers.manager_term_cfg import RewardTermCfg # --------------------------------------------------------------------------- From 21e8bba0d68db95e8a436982d107436a32974295 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 26 May 2026 07:07:27 +0000 Subject: [PATCH 12/36] Compress changelog fragment + add per-package fragments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The isaaclab_experimental fragment shrinks from 47 lines of nested narrative to 12 lines per the existing terse-fragment rule. Adds the matching fragments for the two other touched packages: isaaclab (the term-cfg type-hint relax) and isaaclab_tasks_experimental (.skip — the humanoid import redirect is internal). --- .../changelog.d/warp-manager-bridge.rst | 8 ++++ .../changelog.d/warp-manager-bridge.rst | 48 ++++--------------- .../changelog.d/warp-manager-bridge.skip | 1 + 3 files changed, 17 insertions(+), 40 deletions(-) create mode 100644 source/isaaclab/changelog.d/warp-manager-bridge.rst create mode 100644 source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.skip diff --git a/source/isaaclab/changelog.d/warp-manager-bridge.rst b/source/isaaclab/changelog.d/warp-manager-bridge.rst new file mode 100644 index 000000000000..8aa615a5294a --- /dev/null +++ b/source/isaaclab/changelog.d/warp-manager-bridge.rst @@ -0,0 +1,8 @@ +Changed +^^^^^^^ + +* Relaxed ``func`` annotation on :class:`~isaaclab.managers.ObservationTermCfg`, + :class:`~isaaclab.managers.RewardTermCfg`, and + :class:`~isaaclab.managers.TerminationTermCfg` to ``Callable[..., torch.Tensor | None]`` + so kernel-style ``func(env, out) -> None`` terms type-check alongside the + existing torch return-tensor form. diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 92dfd4f06f7b..3e198ce1db37 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -1,47 +1,15 @@ Added ^^^^^ -* Added :mod:`isaaclab_experimental.envs.frontend`, a small runtime selector - used by ``--frontend {torch,warp}`` to choose how a task is constructed. - - * ``torch`` (default) dispatches via :func:`gym.make` unchanged. - * ``warp`` adapts a stable manager-based cfg in place and constructs - :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp`. The adapter - does three things, all hard-failing on incompatibility: - - 1. Requires :class:`~isaaclab_newton.physics.NewtonCfg` as the active - physics — the user is responsible for selecting it via - ``presets=newton``; no Hydra-arg mutation happens behind the scenes. - 2. Promotes every stable :class:`~isaaclab.managers.SceneEntityCfg` - embedded under term ``params`` to - :class:`isaaclab_experimental.managers.SceneEntityCfg` via the new - :meth:`~isaaclab_experimental.managers.SceneEntityCfg.from_stable` - classmethod (no ``__class__`` reassignment). - 3. Swaps every stable ``term.func`` *and* ``term.class_type`` (one pass, - handles observations / events / rewards / terminations / commands / - curriculum / actions) with its same-named warp twin from - ``isaaclab_tasks_experimental..mdp`` or - :mod:`isaaclab_experimental.envs.mdp`. Any missing twin raises - :class:`FrontendIncompatibleError` listing the affected term paths. - - Direct workflows aren't adapted; ``--frontend=warp`` on a direct task - requires the task to be pre-registered under ``isaaclab_experimental`` / - ``isaaclab_tasks_experimental`` (e.g. ``*-Direct-Warp-v0``). - -* Added :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable`, - a classmethod that builds a warp scene-entity cfg from a stable one by - copying every selection field through ``__init__``. - -* Added a ``--frontend {torch,warp}`` flag to ``rsl_rl/train.py``. The flag - selects the runtime via :func:`isaaclab_experimental.envs.frontend.build`; - ``isaaclab_experimental`` is treated as optional and ``--frontend=torch`` - falls back to ``gym.make`` when it isn't installed. +* Added ``--frontend {torch,warp}`` to ``rsl_rl/train.py`` for selecting the env + runtime; default ``torch`` is unchanged. +* Added :mod:`isaaclab_experimental.envs.frontend` runtime selector and + :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable` used by + ``--frontend=warp`` to adapt stable cfgs onto the warp runtime. Fixed ^^^^^ -* Fixed a regression in :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` - introduced when the ``SimulationContext.get_setting`` API was reshaped: - the warp env now mirrors the stable env and probes - :meth:`~isaaclab.sim.SimulationContext.has_active_visualizers` instead of - splitting a string setting that no longer exists. +* Fixed :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` to probe + :meth:`~isaaclab.sim.SimulationContext.has_active_visualizers` after the + ``get_setting`` API was reshaped. diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.skip b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.skip new file mode 100644 index 000000000000..e55772b9bda3 --- /dev/null +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.skip @@ -0,0 +1 @@ +internal: redirect humanoid reward import to isaaclab.managers.manager_term_cfg From b932897dd2894af615b7c829da21cc6b0dbedc41 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 26 May 2026 07:20:12 +0000 Subject: [PATCH 13/36] Sync warp envs to stable visualizer / has_gui API Two missed-sync fixes carried alongside the manager_based viewport sync that already landed earlier in this branch: 1. DirectRLEnvWarp viewport controller now mirrors stable DirectRLEnv: '(has_gui or has_active_visualizers()) and has_kit()' gate, instantiate ViewportCameraController accordingly. Replaces the stale get_setting('/isaaclab/has_gui'/'render/offscreen') check and removes the commented-out instantiation that left viewport_camera_controller unconditionally None. 2. render(mode='rgb_array') in ManagerBasedRLEnvWarp and DirectRLEnvWarp now read SimulationContext.has_gui and has_offscreen_render properties instead of get_setting on keys that were removed when the simulation manager was refactored. Without this the gate silently fell through on None values. --- .../envs/direct_rl_env_warp.py | 30 ++++++++----------- .../envs/manager_based_rl_env_warp.py | 8 ++--- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py index 20c82e582690..979826e07345 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py @@ -27,15 +27,15 @@ from isaaclab.envs.common import VecEnvObs, VecEnvStepReturn from isaaclab.envs.direct_rl_env import DirectRLEnv from isaaclab.envs.direct_rl_env_cfg import DirectRLEnvCfg +from isaaclab.envs.ui import ViewportCameraController from isaaclab.envs.utils.spaces import sample_space, spec_to_gym_space - -# from isaaclab.envs.ui import ViewportCameraController from isaaclab.managers import EventManager from isaaclab.sim import SimulationContext from isaaclab.sim.utils import use_stage from isaaclab.utils.noise import NoiseModel from isaaclab.utils.seed import configure_seed from isaaclab.utils.timer import Timer +from isaaclab.utils.version import has_kit from isaaclab_experimental.envs.interactive_scene_warp import InteractiveSceneWarp from isaaclab_experimental.utils.warp_graph_cache import WarpGraphCache @@ -168,15 +168,12 @@ def __init__(self, cfg: DirectRLEnvCfg, render_mode: str | None = None, **kwargs # attach_stage_to_usd_context() print("[INFO]: Scene manager: ", self.scene) - # set up camera viewport controller - # viewport is not available in other rendering modes so the function will throw a warning - # FIXME: This needs to be fixed in the future when we unify the UI functionalities even for - # non-rendering modes. - has_gui = bool(self.sim.get_setting("/isaaclab/has_gui")) - offscreen_render = bool(self.sim.get_setting("/isaaclab/render/offscreen")) - if has_gui or offscreen_render: - # self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) - self.viewport_camera_controller = None + # Initialize when a Kit viewport exists. ViewportCameraController uses omni.kit + # (renderer camera); skip in kitless Newton-only runs where no Kit app is running. + # Mirrors stable :class:`isaaclab.envs.DirectRLEnv` (PR #5103 changed the visualizer API). + has_visualizers = self.sim.has_active_visualizers() + if (self.sim.has_gui or has_visualizers) and has_kit(): + self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) else: self.viewport_camera_controller = None @@ -571,13 +568,10 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # check that if any render could have happened - has_gui = bool(self.sim.get_setting("/isaaclab/has_gui")) - offscreen_render = bool(self.sim.get_setting("/isaaclab/render/offscreen")) - # Rendering is possible if we have GUI or offscreen rendering enabled - can_render = has_gui or offscreen_render - - if not can_render: + # Rendering is possible if we have GUI or offscreen rendering enabled — mirror + # stable (PR #4646 replaced /isaaclab/has_gui and /isaaclab/render/offscreen + # settings with cached SimulationContext properties). + if not (self.sim.has_gui or self.sim.has_offscreen_render): render_mode_name = "NO_GUI_OR_RENDERING" raise RuntimeError( f"Cannot render '{self.render_mode}' when the simulation render mode is" diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py index 2e1894e54003..06ba2db190ae 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py @@ -408,10 +408,10 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # check that if any render could have happened - has_gui = bool(self.sim.get_setting("/isaaclab/has_gui")) - offscreen_render = bool(self.sim.get_setting("/isaaclab/render/offscreen")) - if not (has_gui or offscreen_render): + # check that if any render could have happened — mirror stable + # (PR #4646 replaced /isaaclab/has_gui and /isaaclab/render/offscreen settings + # with cached SimulationContext properties). + if not (self.sim.has_gui or self.sim.has_offscreen_render): raise RuntimeError( f"Cannot render '{self.render_mode}' when the simulation render mode does not support" " rendering. Please set the simulation render mode to 'PARTIAL_RENDERING' or" From 0f3447541b8860cdd7b0efcd1b7a3b337994019d Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 27 May 2026 04:48:54 +0000 Subject: [PATCH 14/36] Rename CLI preset hint to newton_mjwarp The legacy bare 'newton'/'kamino' preset names were renamed on develop to 'newton_mjwarp'/'newton_kamino' to disambiguate from the Newton backend label. Update the warp-frontend hard-check error message, the `_adapt_cfg_for_warp`/`_require_newton_physics` docstrings, the rsl_rl/train.py comment, and the matching test assertion to spell the canonical preset name so users get the right CLI token in errors. --- scripts/reinforcement_learning/rsl_rl/train.py | 2 +- .../isaaclab_experimental/envs/frontend.py | 6 +++--- source/isaaclab_experimental/test/envs/test_frontend.py | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index 1f30de33eb12..65a4e03623b1 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -121,7 +121,7 @@ # Build path for ``--frontend=warp`` lives in ``isaaclab_experimental``, which is an # optional package — torch (the default) must still work without it, so import lazily. -# Warp callers are required to pass ``presets=newton`` themselves; the frontend hard-checks +# Warp callers are required to pass ``presets=newton_mjwarp`` themselves; the frontend hard-checks # it at build time rather than mutating Hydra args here. _frontend_build = None try: diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index f8b4acd2284a..518cebb45e3a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -131,7 +131,7 @@ def _adapt_cfg_for_warp(cfg: Any, task_id: str) -> None: 1. :func:`_require_newton_physics` — hard check that ``cfg.sim.physics`` is :class:`~isaaclab_newton.physics.NewtonCfg`. The user is responsible for selecting the Newton variant of the task's :class:`PresetCfg` via - ``presets=newton``; we don't auto-inject. + ``presets=newton_mjwarp``; we don't auto-inject. 2. :func:`_promote_scene_entity_cfgs` — replace stable :class:`~isaaclab.managers.SceneEntityCfg` instances under each term's ``params`` with the warp variant (which adds warp-cached ``joint_mask``, @@ -153,7 +153,7 @@ def _require_newton_physics(cfg: Any, task_id: str) -> None: The warp managers' assets read state through :class:`NewtonManager`; a :class:`PhysxCfg` (or unresolved :class:`PresetCfg`) is a hard - incompatibility. The fix is to pass ``presets=newton`` on the CLI so + incompatibility. The fix is to pass ``presets=newton_mjwarp`` on the CLI so Hydra resolves the task's :class:`PresetCfg` wrapper to the Newton field before construction. """ @@ -164,7 +164,7 @@ def _require_newton_physics(cfg: Any, task_id: str) -> None: return raise FrontendIncompatibleError( f"--frontend=warp on {task_id!r}: expected cfg.sim.physics to be NewtonCfg," - f" got {type(physics).__name__!r}. Pass `presets=newton` on the CLI so" + f" got {type(physics).__name__!r}. Pass `presets=newton_mjwarp` on the CLI so" f" Hydra resolves the task's PresetCfg wrapper to the Newton variant." ) diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index 7f884674f58e..28666ed78e34 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -131,7 +131,7 @@ def test_rejects_physx(self): cfg = self._cfg_with(PhysxCfg()) with self.assertRaises(FrontendIncompatibleError) as exc: _require_newton_physics(cfg, "Isaac-Test-v0") - self.assertIn("presets=newton", str(exc.exception)) + self.assertIn("presets=newton_mjwarp", str(exc.exception)) self.assertIn("PhysxCfg", str(exc.exception)) def test_rejects_none(self): From 1a66c3d449a7281cd1816dff65f838acace35247 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 4 Jun 2026 23:34:55 +0000 Subject: [PATCH 15/36] Self-adapt stable cfg inside warp env construction Move the stable->warp cfg adaptation out of the train.py --frontend path and into ManagerBasedEnvWarp.__init__, so a task registered directly as *-Warp-v0 (with env_cfg_entry_point pointing at the stable cfg) goes through the exact same Newton-physics check, SceneEntityCfg promotion and MDP twin swap. Twin lookup is now keyed off the stable cfg class module (type(cfg).__module__) instead of the gym task id, so it no longer needs a registration to resolve. Adaptation is idempotent. This lets the warp side reuse stable env cfgs instead of carrying parallel copies that drift. --- .../isaaclab_experimental/envs/frontend.py | 53 +++++++++++-------- .../envs/manager_based_env_warp.py | 8 +++ 2 files changed, 40 insertions(+), 21 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 518cebb45e3a..2f186d3617d8 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -39,6 +39,7 @@ "Frontend", "FrontendIncompatibleError", "Workflow", + "adapt_cfg_for_warp", "build", ] @@ -110,9 +111,11 @@ def build( _assert_direct_warp_registration(task_id) return gym.make(task_id, cfg=env_cfg, **construct_kwargs) - _adapt_cfg_for_warp(env_cfg, task_id) # Imported lazily so that ``--frontend=torch`` callers don't pay the - # ``isaaclab_experimental.envs`` import cost. + # ``isaaclab_experimental.envs`` import cost. The warp env adapts the stable + # cfg in its own ``__init__`` (see :func:`adapt_cfg_for_warp`), so a task + # registered directly as ``*-Warp-v0`` (constructed straight from the stable + # cfg) goes through the exact same adaptation as ``--frontend=warp``. from isaaclab_experimental.envs import ManagerBasedRLEnvWarp return ManagerBasedRLEnvWarp(cfg=env_cfg, **construct_kwargs) @@ -123,8 +126,14 @@ def build( # --------------------------------------------------------------------------- -def _adapt_cfg_for_warp(cfg: Any, task_id: str) -> None: - """Mutate ``cfg`` in place so warp managers can consume it. +def adapt_cfg_for_warp(cfg: Any) -> None: + """Mutate a stable manager-based ``cfg`` in place so warp managers can consume it. + + Called from :meth:`ManagerBasedEnvWarp.__init__`, so it runs identically + whether the env is built via ``--frontend=warp`` on a stable task id or by + constructing a ``*-Warp-v0`` registration straight from the stable cfg. + Idempotent: re-running on an already-adapted cfg is a no-op (the steps below + skip warp-origin symbols / already-promoted entities). Three steps, each independently testable: @@ -143,12 +152,13 @@ def _adapt_cfg_for_warp(cfg: Any, task_id: str) -> None: twin raises :class:`FrontendIncompatibleError` — partial coverage is unsafe under the warp managers' kernel-only signature. """ - _require_newton_physics(cfg, task_id) + label = type(cfg).__name__ + _require_newton_physics(cfg, label) _promote_scene_entity_cfgs(cfg) - _swap_mdp(cfg, task_id) + _swap_mdp(cfg, label) -def _require_newton_physics(cfg: Any, task_id: str) -> None: +def _require_newton_physics(cfg: Any, label: str) -> None: """Block unless ``cfg.sim.physics`` is :class:`NewtonCfg`. The warp managers' assets read state through :class:`NewtonManager`; @@ -163,7 +173,7 @@ def _require_newton_physics(cfg: Any, task_id: str) -> None: if isinstance(physics, NewtonCfg): return raise FrontendIncompatibleError( - f"--frontend=warp on {task_id!r}: expected cfg.sim.physics to be NewtonCfg," + f"warp env {label!r}: expected cfg.sim.physics to be NewtonCfg," f" got {type(physics).__name__!r}. Pass `presets=newton_mjwarp` on the CLI so" f" Hydra resolves the task's PresetCfg wrapper to the Newton variant." ) @@ -199,7 +209,7 @@ def _promote_scene_entity_cfgs(cfg: Any) -> None: ) -def _swap_mdp(cfg: Any, task_id: str) -> None: +def _swap_mdp(cfg: Any, label: str) -> None: """Replace ``term.func`` and ``term.class_type`` with their warp twins. Iterates every term cfg in the tree (via :func:`_walk_terms`) and on each @@ -218,7 +228,7 @@ def _swap_mdp(cfg: Any, task_id: str) -> None: substitutes the callable; the manager reads the new func's annotations when it parses the term cfg. """ - modules = _warp_mdp_modules(task_id) + modules = _warp_mdp_modules(type(cfg).__module__) searched = tuple(m.__name__ for m in modules) logger.info("frontend.warp: searching warp mdp modules %s", list(searched)) @@ -240,7 +250,7 @@ def _swap_mdp(cfg: Any, task_id: str) -> None: if missing: lines = "\n ".join(f"{loc}.{attr}: no warp twin for {sym!r}" for loc, attr, sym in missing) raise FrontendIncompatibleError( - f"--frontend=warp on {task_id!r}: missing warp MDP twins (searched {list(searched)}):\n {lines}" + f"warp env {label!r}: missing warp MDP twins (searched {list(searched)}):\n {lines}" ) logger.info("frontend.warp: swapped %d MDP symbol(s) to warp twins", swapped) @@ -285,25 +295,26 @@ def _assert_direct_warp_registration(task_id: str) -> None: ) -def _warp_mdp_modules(task_id: str) -> list[ModuleType]: +def _warp_mdp_modules(cfg_module: str) -> list[ModuleType]: """Locate warp MDP modules to consult for twin lookups. + The lookup is keyed off the *stable* cfg class's module + (``type(cfg).__module__``) rather than the gym task id, so it resolves the + same twins whether the env is built via ``--frontend=warp`` or constructed + directly from a ``*-Warp-v0`` registration. + Order of preference: 1. The task-specific module, derived by replacing ``isaaclab_tasks`` with - ``isaaclab_tasks_experimental`` in the task's ``env_cfg_entry_point`` - package and walking up to the first existing ``.mdp`` submodule. + ``isaaclab_tasks_experimental`` in ``cfg_module`` and walking up to the + first existing ``.mdp`` submodule. This relies on the experimental + package mirroring the stable ``core/`` layout. 2. The shared :mod:`isaaclab_experimental.envs.mdp` fallback (where generic warp twins live). """ modules: list[ModuleType] = [] - try: - spec = gym.spec(task_id) - except gym.error.NameNotFound: - spec = None - entry = spec.kwargs.get("env_cfg_entry_point") if spec is not None else None - if isinstance(entry, str) and entry.startswith("isaaclab_tasks."): - warp_pkg = entry.rsplit(".", 1)[0].replace("isaaclab_tasks", "isaaclab_tasks_experimental", 1) + if isinstance(cfg_module, str) and cfg_module.startswith("isaaclab_tasks."): + warp_pkg = cfg_module.replace("isaaclab_tasks", "isaaclab_tasks_experimental", 1) parts = warp_pkg.split(".") for depth in range(len(parts), 0, -1): target = ".".join(parts[:depth] + ["mdp"]) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py index 9c05dc207700..707a3978ee05 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py @@ -73,6 +73,14 @@ def __init__(self, cfg: ManagerBasedEnvCfg): RuntimeError: If a simulation context already exists. The environment must always create one since it configures the simulation context and controls the simulation. """ + # Adapt a stable manager-based cfg to the warp runtime in place: assert + # Newton physics, promote SceneEntityCfg to the warp variant, and swap + # every MDP func/class to its warp twin. Idempotent, so an already-warp + # cfg passes through untouched. This lets a ``*-Warp-v0`` task point its + # env_cfg_entry_point at the stable cfg rather than carry a drifting copy. + from isaaclab_experimental.envs.frontend import adapt_cfg_for_warp + + adapt_cfg_for_warp(cfg) # check that the config is valid cfg.validate() # store inputs to class From 40db07a58fb9329eb5d0f1f4aee8dac92b4b3e9f Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 4 Jun 2026 23:54:05 +0000 Subject: [PATCH 16/36] Mirror core/ layout in tasks_experimental; reuse stable cfgs Flatten isaaclab_tasks_experimental from the legacy manager_based/ | direct/ | classic/ trees into core// mirroring isaaclab_tasks/core, so the frontend's stable->warp module-path rewrite resolves twins again after the stable migration. Manager-based warp tasks now reuse the stable env cfg (env_cfg_entry_point points at isaaclab_tasks.core...; physics + MDP twins are swapped at construction) instead of carrying parallel copies that drift; the drift cfgs are deleted. Direct warp tasks keep their own env class + cfg. Twin lookup keys off each stable symbol's own module, so ant reusing manager_humanoid's mdp resolves with no per-task shim (mirrors core, which gives manager_ant no mdp/ of its own). --- .../isaaclab_experimental/envs/frontend.py | 66 ++-- .../{direct => core}/allegro_hand/__init__.py | 2 +- .../allegro_hand/allegro_hand_warp_env_cfg.py | 0 .../core/cartpole/__init__.py | 53 ++++ .../cartpole/cartpole_warp_env.py | 0 .../cartpole/cartpole_warp_env_cfg.py | 0 .../classic => core}/cartpole/mdp/__init__.py | 0 .../cartpole/mdp/__init__.pyi | 0 .../classic => core}/cartpole/mdp/rewards.py | 0 .../ant => core/direct_ant}/__init__.py | 0 .../ant => core/direct_ant}/ant_env_warp.py | 2 +- .../direct_ant}/ant_env_warp_cfg.py | 0 .../direct_humanoid}/__init__.py | 0 .../direct_humanoid}/humanoid_warp_env.py | 2 +- .../direct_humanoid}/humanoid_warp_env_cfg.py | 0 .../direct_locomotion}/__init__.py | 0 .../direct_locomotion}/locomotion_env_warp.py | 0 .../inhand_manipulation}/__init__.py | 0 .../inhand_manipulation_warp_env.py | 2 +- .../ant => core/manager_ant}/__init__.py | 6 +- .../manager_humanoid}/__init__.py | 6 +- .../manager_humanoid}/mdp/__init__.py | 0 .../manager_humanoid}/mdp/__init__.pyi | 0 .../manager_humanoid}/mdp/observations.py | 0 .../manager_humanoid}/mdp/rewards.py | 0 .../manipulation => core}/reach/__init__.py | 0 .../reach/config/__init__.py | 0 .../reach/config/franka/__init__.py | 8 +- .../reach/config/ur_10/__init__.py | 8 +- .../reach/mdp/__init__.py | 0 .../reach/mdp/__init__.pyi | 0 .../reach/mdp/rewards.py | 0 .../locomotion => core}/velocity/__init__.py | 0 .../velocity/config/__init__.py | 0 .../velocity/config/a1/__init__.py | 8 +- .../velocity/config/anymal_b/__init__.py | 8 +- .../velocity/config/anymal_c/__init__.py | 8 +- .../velocity/config/anymal_d/__init__.py | 12 +- .../velocity/config/cassie/__init__.py | 8 +- .../velocity/config/g1/__init__.py | 12 +- .../velocity/config/go1/__init__.py | 8 +- .../velocity/config/go2/__init__.py | 8 +- .../velocity/config/h1/__init__.py | 12 +- .../velocity/mdp/__init__.py | 0 .../velocity/mdp/__init__.pyi | 0 .../velocity/mdp/curriculums.py | 0 .../velocity/mdp/rewards.py | 0 .../velocity/mdp/terminations.py | 0 .../direct/__init__.py | 10 - .../direct/cartpole/__init__.py | 29 -- .../manager_based/__init__.py | 10 - .../manager_based/classic/__init__.py | 12 - .../manager_based/classic/ant/ant_env_cfg.py | 197 ------------ .../classic/cartpole/__init__.py | 30 -- .../classic/cartpole/cartpole_env_cfg.py | 199 ------------ .../classic/humanoid/humanoid_env_cfg.py | 232 -------------- .../manager_based/locomotion/__init__.py | 6 - .../velocity/config/a1/flat_env_cfg.py | 60 ---- .../velocity/config/a1/rough_env_cfg.py | 91 ------ .../velocity/config/anymal_b/flat_env_cfg.py | 60 ---- .../velocity/config/anymal_b/rough_env_cfg.py | 34 -- .../velocity/config/anymal_c/flat_env_cfg.py | 52 --- .../velocity/config/anymal_c/rough_env_cfg.py | 40 --- .../velocity/config/anymal_d/flat_env_cfg.py | 46 --- .../velocity/config/anymal_d/rough_env_cfg.py | 37 --- .../velocity/config/cassie/flat_env_cfg.py | 45 --- .../velocity/config/cassie/rough_env_cfg.py | 96 ------ .../velocity/config/g1/flat_env_cfg.py | 58 ---- .../velocity/config/g1/rough_env_cfg.py | 178 ----------- .../velocity/config/go1/flat_env_cfg.py | 46 --- .../velocity/config/go1/rough_env_cfg.py | 61 ---- .../velocity/config/go2/flat_env_cfg.py | 46 --- .../velocity/config/go2/rough_env_cfg.py | 60 ---- .../velocity/config/h1/flat_env_cfg.py | 46 --- .../velocity/config/h1/rough_env_cfg.py | 131 -------- .../locomotion/velocity/velocity_env_cfg.py | 296 ------------------ .../manager_based/manipulation/__init__.py | 6 - .../reach/config/franka/joint_pos_env_cfg.py | 74 ----- .../reach/config/ur_10/joint_pos_env_cfg.py | 74 ----- .../manipulation/reach/reach_env_cfg.py | 206 ------------ 80 files changed, 177 insertions(+), 2630 deletions(-) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/allegro_hand/__init__.py (92%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/allegro_hand/allegro_hand_warp_env_cfg.py (100%) create mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/cartpole/cartpole_warp_env.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/cartpole/cartpole_warp_env_cfg.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/ant => core/direct_ant}/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/ant => core/direct_ant}/ant_env_warp.py (82%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/ant => core/direct_ant}/ant_env_warp_cfg.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/humanoid => core/direct_humanoid}/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/humanoid => core/direct_humanoid}/humanoid_warp_env.py (83%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/humanoid => core/direct_humanoid}/humanoid_warp_env_cfg.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/inhand_manipulation => core/direct_locomotion}/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/locomotion => core/direct_locomotion}/locomotion_env_warp.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/locomotion => core/inhand_manipulation}/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/inhand_manipulation/inhand_manipulation_warp_env.py (99%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic/ant => core/manager_ant}/__init__.py (77%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic/humanoid => core/manager_humanoid}/__init__.py (76%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic/humanoid => core/manager_humanoid}/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic/humanoid => core/manager_humanoid}/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic/humanoid => core/manager_humanoid}/mdp/observations.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic/humanoid => core/manager_humanoid}/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/config/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/config/franka/__init__.py (76%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/config/ur_10/__init__.py (79%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/a1/__init__.py (77%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_b/__init__.py (78%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_c/__init__.py (80%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_d/__init__.py (79%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/cassie/__init__.py (74%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/g1/__init__.py (77%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/go1/__init__.py (74%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/go2/__init__.py (74%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/h1/__init__.py (77%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/curriculums.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/terminations.py (100%) delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 2f186d3617d8..2b85e474da8f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -214,12 +214,15 @@ def _swap_mdp(cfg: Any, label: str) -> None: Iterates every term cfg in the tree (via :func:`_walk_terms`) and on each term swaps whichever of ``func`` / ``class_type`` is a stable-origin - callable. Twin lookup is name-based against the task's matching - ``isaaclab_tasks_experimental.<...>.mdp`` module and, as a fallback, - :mod:`isaaclab_experimental.envs.mdp`. Any missing twin raises - :class:`FrontendIncompatibleError` listing every affected term — partial - swaps would leave torch-style callables in the cfg and the warp managers - would call them with the wrong signature. + callable. Twin lookup is name-based against the warp mirror of the *stable + symbol's own module* (:func:`_warp_mdp_modules`) plus the + :mod:`isaaclab_experimental.envs.mdp` fallback. Keying off the symbol's + module — not the cfg's — means a task that borrows another task's MDP (e.g. + ``manager_ant`` reuses ``manager_humanoid.mdp``) resolves to the right warp + twins without a per-task shim, mirroring the stable ``core/`` layout. Any + missing twin raises :class:`FrontendIncompatibleError` listing every + affected term — partial swaps would leave torch-style callables in the cfg + and the warp managers would call them with the wrong signature. The warp-side side declarations (``out_dim``, ``axes``, ``observation_type``) that the warp managers need at init are *not* supplied by this swap; they @@ -228,9 +231,8 @@ def _swap_mdp(cfg: Any, label: str) -> None: substitutes the callable; the manager reads the new func's annotations when it parses the term cfg. """ - modules = _warp_mdp_modules(type(cfg).__module__) - searched = tuple(m.__name__ for m in modules) - logger.info("frontend.warp: searching warp mdp modules %s", list(searched)) + module_cache: dict[str, list[ModuleType]] = {} + searched: set[str] = set() swapped = 0 missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) @@ -240,7 +242,11 @@ def _swap_mdp(cfg: Any, label: str) -> None: stable = getattr(term, attr, None) if stable is None or not _is_swap_candidate(stable): continue - twin = _resolve_warp_twin(stable.__name__, modules) + origin = getattr(stable, "__module__", "") or "" + if origin not in module_cache: + module_cache[origin] = _warp_mdp_modules(origin) + searched.update(m.__name__ for m in module_cache[origin]) + twin = _resolve_warp_twin(stable.__name__, module_cache[origin]) if twin is None: missing.append((location, attr, stable.__name__)) continue @@ -250,7 +256,7 @@ def _swap_mdp(cfg: Any, label: str) -> None: if missing: lines = "\n ".join(f"{loc}.{attr}: no warp twin for {sym!r}" for loc, attr, sym in missing) raise FrontendIncompatibleError( - f"warp env {label!r}: missing warp MDP twins (searched {list(searched)}):\n {lines}" + f"warp env {label!r}: missing warp MDP twins (searched {sorted(searched)}):\n {lines}" ) logger.info("frontend.warp: swapped %d MDP symbol(s) to warp twins", swapped) @@ -295,36 +301,40 @@ def _assert_direct_warp_registration(task_id: str) -> None: ) -def _warp_mdp_modules(cfg_module: str) -> list[ModuleType]: - """Locate warp MDP modules to consult for twin lookups. +def _warp_mdp_modules(symbol_module: str) -> list[ModuleType]: + """Locate warp MDP modules to consult for a stable symbol's twin. - The lookup is keyed off the *stable* cfg class's module - (``type(cfg).__module__``) rather than the gym task id, so it resolves the - same twins whether the env is built via ``--frontend=warp`` or constructed - directly from a ``*-Warp-v0`` registration. + The lookup is keyed off the *stable symbol's own module* + (``func.__module__`` / ``class_type.__module__``), e.g. + ``isaaclab_tasks.core.manager_humanoid.mdp.rewards``. We mirror that path + into the experimental package and walk up to the nearest importable module, + then append the shared fallback. Keying off the symbol's module — not the + cfg's — resolves the right twins even when a task borrows another task's MDP + (``manager_ant`` reuses ``manager_humanoid.mdp``), so the experimental + package can mirror the stable ``core/`` layout one-to-one without per-task + re-export shims. Order of preference: - 1. The task-specific module, derived by replacing ``isaaclab_tasks`` with - ``isaaclab_tasks_experimental`` in ``cfg_module`` and walking up to the - first existing ``.mdp`` submodule. This relies on the experimental - package mirroring the stable ``core/`` layout. + 1. The warp mirror of ``symbol_module`` (or its nearest importable ancestor, + e.g. the ``...mdp`` package when the exact submodule isn't mirrored). 2. The shared :mod:`isaaclab_experimental.envs.mdp` fallback (where generic warp twins live). """ modules: list[ModuleType] = [] - if isinstance(cfg_module, str) and cfg_module.startswith("isaaclab_tasks."): - warp_pkg = cfg_module.replace("isaaclab_tasks", "isaaclab_tasks_experimental", 1) - parts = warp_pkg.split(".") + if isinstance(symbol_module, str) and symbol_module.startswith("isaaclab_tasks."): + warp_mod = symbol_module.replace("isaaclab_tasks", "isaaclab_tasks_experimental", 1) + parts = warp_mod.split(".") for depth in range(len(parts), 0, -1): - target = ".".join(parts[:depth] + ["mdp"]) + target = ".".join(parts[:depth]) try: modules.append(importlib.import_module(target)) break except ModuleNotFoundError as exc: - # Only swallow "this candidate doesn't exist" — a real - # import error inside an existing module is a bug. - if exc.name == target: + # Keep walking up while the missing module is part of the path + # we're probing; a genuine import error inside an existing + # module (missing third-party dep, etc.) must surface. + if exc.name and warp_mod.startswith(exc.name): continue raise # Generic fallback. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/allegro_hand/__init__.py similarity index 92% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/allegro_hand/__init__.py index 95e9aafb7800..2bd91e74598b 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/allegro_hand/__init__.py @@ -13,7 +13,7 @@ # Register Gym environments. ## -inhand_task_entry = "isaaclab_tasks_experimental.direct.inhand_manipulation" +inhand_task_entry = "isaaclab_tasks_experimental.core.inhand_manipulation" stable_agents = "isaaclab_tasks.core.allegro_hand.agents" gym.register( diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/allegro_hand_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/allegro_hand/allegro_hand_warp_env_cfg.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/allegro_hand_warp_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/allegro_hand/allegro_hand_warp_env_cfg.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py new file mode 100644 index 000000000000..d5d93b3dba48 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py @@ -0,0 +1,53 @@ +# 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 + +""" +Cartpole balancing environment (warp entry points). + +Mirrors stable ``isaaclab_tasks.core.cartpole``: the manager-based warp task +reuses the stable cfg (no parallel copy), while the direct warp task keeps its +own env class + cfg here since direct envs encode behaviour in the class. +""" + +import gymnasium as gym + +# Reuse agent configs from the stable task package. +from isaaclab_tasks.core.cartpole import agents + +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + +## +# Register Gym environments. +## + +# Manager-based: stable cfg adapted to warp at construction. +gym.register( + id="Isaac-Cartpole-Warp-v0", + entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{_stable_pkg}.cartpole_manager_env_cfg:CartpoleEnvCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_manager_ppo_cfg.yaml", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_manager_ppo_cfg:CartpolePPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_manager_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_manager_ppo_cfg.yaml", + }, +) + +# Direct: dedicated warp env class + local cfg (not adaptable from a cfg). +gym.register( + id="Isaac-Cartpole-Direct-Warp-v0", + entry_point=f"{__name__}.cartpole_warp_env:CartpoleWarpEnv", + disable_env_checker=True, + kwargs={ + "env_cfg_entry_point": f"{__name__}.cartpole_warp_env_cfg:CartpoleWarpEnvCfg", + "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_direct_ppo_cfg:CartpolePPORunnerCfg", + "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_direct_ppo_cfg.yaml", + }, +) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/cartpole_warp_env.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/cartpole_warp_env.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/cartpole_warp_env_cfg.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/cartpole_warp_env_cfg.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/ant_env_warp.py similarity index 82% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/ant_env_warp.py index 2bd7390039b7..d9eba6dfeba1 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/ant_env_warp.py @@ -5,7 +5,7 @@ from __future__ import annotations -from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv +from isaaclab_tasks_experimental.core.direct_locomotion.locomotion_env_warp import LocomotionWarpEnv from .ant_env_warp_cfg import AntWarpEnvCfg diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/ant_env_warp_cfg.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/ant_env_warp_cfg.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/humanoid_warp_env.py similarity index 83% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/humanoid_warp_env.py index 2fd0ac8433e2..f704a6a8859a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/humanoid_warp_env.py @@ -5,7 +5,7 @@ from __future__ import annotations -from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv +from isaaclab_tasks_experimental.core.direct_locomotion.locomotion_env_warp import LocomotionWarpEnv from .humanoid_warp_env_cfg import HumanoidWarpEnvCfg diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/humanoid_warp_env_cfg.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/humanoid_warp_env_cfg.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_locomotion/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_locomotion/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_locomotion/locomotion_env_warp.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_locomotion/locomotion_env_warp.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/inhand_manipulation/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/inhand_manipulation/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/inhand_manipulation/inhand_manipulation_warp_env.py similarity index 99% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/inhand_manipulation/inhand_manipulation_warp_env.py index d5bc6a2ad529..b3f1f4abb789 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/inhand_manipulation/inhand_manipulation_warp_env.py @@ -19,7 +19,7 @@ from isaaclab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane if TYPE_CHECKING: - from isaaclab_tasks_experimental.direct.allegro_hand.allegro_hand_warp_env_cfg import AllegroHandWarpEnvCfg + from isaaclab_tasks_experimental.core.allegro_hand.allegro_hand_warp_env_cfg import AllegroHandWarpEnvCfg @wp.kernel diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py similarity index 77% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py index 643996b7f730..26996b4881f9 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py @@ -12,6 +12,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.manager_ant import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -21,7 +25,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.ant_env_cfg:AntEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.ant_env_cfg:AntEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AntPPORunnerCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py similarity index 76% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py index c1d30e76a9e2..183b42d2aaeb 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py @@ -12,6 +12,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.manager_humanoid import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -21,7 +25,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.humanoid_env_cfg:HumanoidEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.humanoid_env_cfg:HumanoidEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:HumanoidPPORunnerCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/observations.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/observations.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py similarity index 76% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py index 9f01c7b2e729..a82f977588fd 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.reach.config.franka import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -21,7 +25,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:FrankaReachEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.joint_pos_env_cfg:FrankaReachEnvCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaReachPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", @@ -33,7 +37,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:FrankaReachEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.joint_pos_env_cfg:FrankaReachEnvCfg_PLAY", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaReachPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py similarity index 79% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py index cdff71bf6523..03843620488d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py @@ -11,12 +11,16 @@ # import gymnasium as gym # from isaaclab_tasks.core.reach.config.ur_10 import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + # gym.register( # id="Isaac-Reach-UR10-Warp-v0", # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:UR10ReachEnvCfg", +# "env_cfg_entry_point": f"{_stable_pkg}.joint_pos_env_cfg:UR10ReachEnvCfg", # "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", @@ -28,7 +32,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:UR10ReachEnvCfg_PLAY", +# "env_cfg_entry_point": f"{_stable_pkg}.joint_pos_env_cfg:UR10ReachEnvCfg_PLAY", # "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py similarity index 77% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py index 598d37c28c73..92ca6742257f 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.contrib.velocity.config.a1 import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeA1FlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:UnitreeA1FlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeA1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", @@ -29,7 +33,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeA1FlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:UnitreeA1FlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeA1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py similarity index 78% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py index e33364fd7cff..fcb1393f5092 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.contrib.velocity.config.anymal_b import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalBFlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:AnymalBFlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerCfg", "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerWithSymmetryCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", @@ -29,7 +33,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalBFlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:AnymalBFlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerCfg", "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerWithSymmetryCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py similarity index 80% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py index 58f71adc0d06..7ee48552d0d2 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.contrib.velocity.config.anymal_c import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalCFlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:AnymalCFlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerCfg", "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerWithSymmetryCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml", @@ -30,7 +34,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalCFlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:AnymalCFlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerCfg", "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerWithSymmetryCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py similarity index 79% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py index 20dda722e09c..611ec20f9540 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.velocity.config.anymal_d import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -20,7 +24,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:AnymalDRoughEnvCfg", +# "env_cfg_entry_point": f"{_stable_pkg}.rough_env_cfg:AnymalDRoughEnvCfg", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDRoughPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", # }, @@ -31,7 +35,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:AnymalDRoughEnvCfg_PLAY", +# "env_cfg_entry_point": f"{_stable_pkg}.rough_env_cfg:AnymalDRoughEnvCfg_PLAY", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDRoughPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", # }, @@ -42,7 +46,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalDFlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:AnymalDFlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDFlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, @@ -53,7 +57,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalDFlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:AnymalDFlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDFlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py similarity index 74% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py index e3af41334541..db4c9858b764 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.velocity.config.cassie import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:CassieFlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:CassieFlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CassieFlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, @@ -28,7 +32,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:CassieFlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:CassieFlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CassieFlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py similarity index 77% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py index f49e103f431a..5a9e6bfa9e9c 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.velocity.config.g1 import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:G1RoughEnvCfg", +# "env_cfg_entry_point": f"{_stable_pkg}.rough_env_cfg:G1RoughEnvCfg", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1RoughPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", # }, @@ -29,7 +33,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:G1RoughEnvCfg_PLAY", +# "env_cfg_entry_point": f"{_stable_pkg}.rough_env_cfg:G1RoughEnvCfg_PLAY", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1RoughPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", # }, @@ -40,7 +44,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:G1FlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:G1FlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, @@ -51,7 +55,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:G1FlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:G1FlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py similarity index 74% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py index 3206b985ea0e..bbdb15b7da88 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.contrib.velocity.config.go1 import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo1FlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:UnitreeGo1FlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, @@ -28,7 +32,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo1FlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:UnitreeGo1FlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py similarity index 74% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py index 041579201f35..0e0d42e604ba 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.velocity.config.go2 import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo2FlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:UnitreeGo2FlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo2FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, @@ -28,7 +32,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo2FlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:UnitreeGo2FlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo2FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py similarity index 77% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py index c731af7ca986..2c1de23e1679 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py @@ -8,6 +8,10 @@ # Reuse agent configs from the stable task package. from isaaclab_tasks.core.velocity.config.h1 import agents +# Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) +# and MDP twins are swapped at construction (see adapt_cfg_for_warp). +_stable_pkg = agents.__name__.rsplit(".", 1)[0] + ## # Register Gym environments. ## @@ -17,7 +21,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:H1RoughEnvCfg", +# "env_cfg_entry_point": f"{_stable_pkg}.rough_env_cfg:H1RoughEnvCfg", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1RoughPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", # }, @@ -28,7 +32,7 @@ # entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", # disable_env_checker=True, # kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:H1RoughEnvCfg_PLAY", +# "env_cfg_entry_point": f"{_stable_pkg}.rough_env_cfg:H1RoughEnvCfg_PLAY", # "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1RoughPPORunnerCfg", # "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", # }, @@ -39,7 +43,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:H1FlatEnvCfg", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:H1FlatEnvCfg", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, @@ -50,7 +54,7 @@ entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:H1FlatEnvCfg_PLAY", + "env_cfg_entry_point": f"{_stable_pkg}.flat_env_cfg:H1FlatEnvCfg_PLAY", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1FlatPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", }, diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/curriculums.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/curriculums.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/terminations.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/terminations.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py deleted file mode 100644 index 3e2b7945ebde..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# 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 - -""" -Direct workflow environments. -""" - -import gymnasium as gym diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py deleted file mode 100644 index 48021a84f4d5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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 - -""" -Cartpole balancing environment. -""" - -import gymnasium as gym - -## -# Register Gym environments. -## - -stable_agents = "isaaclab_tasks.core.cartpole.agents" - -gym.register( - id="Isaac-Cartpole-Direct-Warp-v0", - entry_point=f"{__name__}.cartpole_warp_env:CartpoleWarpEnv", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.cartpole_warp_env_cfg:CartpoleWarpEnvCfg", - "rl_games_cfg_entry_point": f"{stable_agents}:rl_games_direct_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{stable_agents}.rsl_rl_direct_ppo_cfg:CartpolePPORunnerCfg", - "skrl_cfg_entry_point": f"{stable_agents}:skrl_direct_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{stable_agents}:sb3_direct_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py deleted file mode 100644 index 7f23883e6332..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# 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 - -"""Experimental registrations for manager-based tasks. - -We intentionally only register new Gym IDs pointing at experimental entry points. -Task definitions (configs/mdp) remain in `isaaclab_tasks` to avoid duplication. -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py deleted file mode 100644 index 79c13e2aa8f4..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# 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 - -"""Classic environments for control. - -These environments are based on the MuJoCo environments provided by OpenAI. - -Reference: - https://github.com/openai/gym/tree/master/gym/envs/mujoco -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py deleted file mode 100644 index 66a9131011f3..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py +++ /dev/null @@ -1,197 +0,0 @@ -# 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 - -# Ant reuses humanoid's experimental MDP (mirrors stable pattern). -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp as mdp - -## -# Pre-defined configs -## -from isaaclab_assets.robots.ant import ANT_CFG # isort: skip - - -@configclass -class MySceneCfg(InteractiveSceneCfg): - """Configuration for the terrain scene with an ant robot.""" - - # terrain - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="plane", - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg( - friction_combine_mode="average", - restitution_combine_mode="average", - static_friction=1.0, - dynamic_friction=1.0, - restitution=0.0, - ), - debug_vis=False, - ) - - # robot - robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - - # lights - light = AssetBaseCfg( - prim_path="/World/light", - spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), - ) - - -## -# MDP settings -## - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=7.5) - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for the policy.""" - - base_height = ObsTerm(func=mdp.base_pos_z) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel) - base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) - base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) - base_up_proj = ObsTerm(func=mdp.base_up_proj) - base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) - joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={"pose_range": {}, "velocity_range": {}}, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "position_range": (-0.2, 0.2), - "velocity_range": (-0.1, 0.1), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # (1) Reward for moving forward - progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)}) - # (2) Stay alive bonus - alive = RewTerm(func=mdp.is_alive, weight=0.5) - # (3) Reward for non-upright posture - upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93}) - # (4) Reward for moving in the right direction - move_to_target = RewTerm( - func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)} - ) - # (5) Penalty for large action commands - action_l2 = RewTerm(func=mdp.action_l2, weight=-0.005) - # (6) Penalty for energy consumption - energy = RewTerm(func=mdp.power_consumption, weight=-0.05, params={"gear_ratio": {".*": 15.0}}) - # (7) Penalty for reaching close to joint limits - joint_pos_limits = RewTerm( - func=mdp.joint_pos_limits_penalty_ratio, weight=-0.1, params={"threshold": 0.99, "gear_ratio": {".*": 15.0}} - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - # (1) Terminate if the episode length is exceeded - time_out = DoneTerm(func=mdp.time_out, time_out=True) - # (2) Terminate if the robot falls - torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.31}) - - -## -# Environment configuration -## - - -@configclass -class AntEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the MuJoCo-style Ant walking environment.""" - - # Simulation settings - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=38, - nconmax=15, - ls_iterations=10, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - # Scene settings - scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0, clone_in_fabric=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 2 - self.episode_length_s = 16.0 - # simulation settings - self.sim.dt = 1 / 120.0 - self.sim.render_interval = self.decimation - # default friction material - self.sim.physics_material.static_friction = 1.0 - self.sim.physics_material.dynamic_friction = 1.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py deleted file mode 100644 index 9f46551de255..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# 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 - -""" -Cartpole balancing environment (experimental manager-based entry point). -""" - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.cartpole import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Cartpole-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_manager_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_manager_ppo_cfg:CartpolePPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_manager_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_manager_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py deleted file mode 100644 index ae187a593a16..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py +++ /dev/null @@ -1,199 +0,0 @@ -# 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 - -import math - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg, AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp as mdp - -## -# Pre-defined configs -## -from isaaclab_assets.robots.cartpole import CARTPOLE_CFG # isort:skip - - -## -# Scene definition -## - - -@configclass -class CartpoleSceneCfg(InteractiveSceneCfg): - """Configuration for a cart-pole scene.""" - - # ground plane - # ground = AssetBaseCfg( - # prim_path="/World/ground", - # spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)), - # ) - - # cartpole - robot: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - - # lights - dome_light = AssetBaseCfg( - prim_path="/World/DomeLight", - spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0), - ) - - -## -# MDP settings -## - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=100.0) - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for policy group.""" - - # observation terms (order preserved) - joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel) - - def __post_init__(self) -> None: - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - # reset - reset_cart_position = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), - "position_range": (-1.0, 1.0), - "velocity_range": (-0.5, 0.5), - }, - ) - - reset_pole_position = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), - "position_range": (-0.25 * math.pi, 0.25 * math.pi), - "velocity_range": (-0.25 * math.pi, 0.25 * math.pi), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # (1) Constant running reward - alive = RewTerm(func=mdp.is_alive, weight=1.0) - # (2) Failure penalty - terminating = RewTerm(func=mdp.is_terminated, weight=-2.0) - # (3) Primary task: keep pole upright - pole_pos = RewTerm( - func=mdp.joint_pos_target_l2, - weight=-1.0, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0}, - ) - # (4) Shaping tasks: lower cart velocity - cart_vel = RewTerm( - func=mdp.joint_vel_l1, - weight=-0.01, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])}, - ) - # (5) Shaping tasks: lower pole angular velocity - pole_vel = RewTerm( - func=mdp.joint_vel_l1, - weight=-0.005, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])}, - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - # (1) Time out - time_out = DoneTerm(func=mdp.time_out, time_out=True) - # (2) Cart out of bounds - cart_out_of_bounds = DoneTerm( - func=mdp.joint_pos_out_of_manual_limit, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), "bounds": (-3.0, 3.0)}, - ) - - -## -# Environment configuration -## - - -@configclass -class CartpoleEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the cartpole environment.""" - - # Scene settings - scene: CartpoleSceneCfg = CartpoleSceneCfg(num_envs=4096, env_spacing=4.0, clone_in_fabric=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - events: EventCfg = EventCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - # Simulation settings - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=5, - nconmax=3, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - use_cuda_graph=True, - ) - ) - - # Post initialization - def __post_init__(self) -> None: - """Post initialization.""" - # general settings - self.decimation = 2 - self.episode_length_s = 5 - # viewer settings - self.viewer.eye = (8.0, 0.0, 5.0) - # simulation settings - self.sim.dt = 1 / 120 - self.sim.render_interval = self.decimation diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py deleted file mode 100644 index 9de689ffb98e..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py +++ /dev/null @@ -1,232 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp as mdp - -from isaaclab_assets.robots.humanoid import HUMANOID_CFG # isort:skip - - -## -# Scene definition -## - - -@configclass -class MySceneCfg(InteractiveSceneCfg): - """Configuration for the terrain scene with a humanoid robot.""" - - # terrain - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="plane", - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0, dynamic_friction=1.0, restitution=0.0), - debug_vis=False, - ) - - # robot - robot = HUMANOID_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - - # lights - light = AssetBaseCfg( - prim_path="/World/light", - spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), - ) - - -## -# MDP settings -## - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_effort = mdp.JointEffortActionCfg( - asset_name="robot", - joint_names=[".*"], - scale={ - ".*_waist.*": 67.5, - ".*_upper_arm.*": 67.5, - "pelvis": 67.5, - ".*_lower_arm": 45.0, - ".*_thigh:0": 45.0, - ".*_thigh:1": 135.0, - ".*_thigh:2": 45.0, - ".*_shin": 90.0, - ".*_foot.*": 22.5, - }, - ) - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for the policy.""" - - base_height = ObsTerm(func=mdp.base_pos_z) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25) - base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) - base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) - base_up_proj = ObsTerm(func=mdp.base_up_proj) - base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) - joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={"pose_range": {}, "velocity_range": {}}, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "position_range": (-0.2, 0.2), - "velocity_range": (-0.1, 0.1), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # (1) Reward for moving forward - progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)}) - # (2) Stay alive bonus - alive = RewTerm(func=mdp.is_alive, weight=2.0) - # (3) Reward for non-upright posture - upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93}) - # (4) Reward for moving in the right direction - move_to_target = RewTerm( - func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)} - ) - # (5) Penalty for large action commands - action_l2 = RewTerm(func=mdp.action_l2, weight=-0.01) - # (6) Penalty for energy consumption - energy = RewTerm( - func=mdp.power_consumption, - weight=-0.005, - params={ - "gear_ratio": { - ".*_waist.*": 67.5, - ".*_upper_arm.*": 67.5, - "pelvis": 67.5, - ".*_lower_arm": 45.0, - ".*_thigh:0": 45.0, - ".*_thigh:1": 135.0, - ".*_thigh:2": 45.0, - ".*_shin": 90.0, - ".*_foot.*": 22.5, - } - }, - ) - # (7) Penalty for reaching close to joint limits - joint_pos_limits = RewTerm( - func=mdp.joint_pos_limits_penalty_ratio, - weight=-0.25, - params={ - "threshold": 0.98, - "gear_ratio": { - ".*_waist.*": 67.5, - ".*_upper_arm.*": 67.5, - "pelvis": 67.5, - ".*_lower_arm": 45.0, - ".*_thigh:0": 45.0, - ".*_thigh:1": 135.0, - ".*_thigh:2": 45.0, - ".*_shin": 90.0, - ".*_foot.*": 22.5, - }, - }, - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - # (1) Terminate if the episode length is exceeded - time_out = DoneTerm(func=mdp.time_out, time_out=True) - # (2) Terminate if the robot falls - torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.8}) - - -@configclass -class HumanoidEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the MuJoCo-style Humanoid walking environment.""" - - # Scene settings - scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0, clone_in_fabric=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 2 - self.episode_length_s = 16.0 - # simulation settings - self.sim: SimulationCfg = SimulationCfg( - dt=1 / 120.0, - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=80, - nconmax=25, - ls_iterations=15, - cone="pyramidal", - update_data_interval=2, - impratio=1, - integrator="implicitfast", - ), - num_substeps=2, - debug_mode=False, - ), - ) - # self.sim.dt = 1 / 120.0 - self.sim.render_interval = self.decimation - # default friction material - self.sim.physics_material.static_friction = 1.0 - self.sim.physics_material.dynamic_friction = 1.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py deleted file mode 100644 index 0660d38f0658..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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 - -"""Locomotion experimental task registrations (manager-based).""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py deleted file mode 100644 index f213286d0cfb..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py +++ /dev/null @@ -1,60 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import UnitreeA1RoughEnvCfg - - -@configclass -class UnitreeA1FlatEnvCfg(UnitreeA1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=60, - nconmax=30, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # override rewards - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 0.25 - - # change terrain to flat - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - # no height scan - # self.scene.height_scanner = None - # self.observations.policy.height_scan = None - # no terrain curriculum - self.curriculum.terrain_levels = None - - -class UnitreeA1FlatEnvCfg_PLAY(UnitreeA1FlatEnvCfg): - def __post_init__(self) -> None: - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing event - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py deleted file mode 100644 index ee0f236043a2..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py +++ /dev/null @@ -1,91 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - TerminationsCfg, -) - -from isaaclab_assets.robots.unitree import UNITREE_A1_CFG # isort: skip - - -class TerminationsCfg_A1(TerminationsCfg): - base_too_low = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.2}) - - -@configclass -class UnitreeA1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - terminations: TerminationsCfg_A1 = TerminationsCfg_A1() - - def __post_init__(self): - # post init of parent - super().__post_init__() - - self.scene.robot = UNITREE_A1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 - - # reduce action scale - self.actions.joint_pos.scale = 0.25 - - # event - self.events.push_robot = None - # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation - # self.events.add_base_mass.params["mass_distribution_params"] = (-1.0, 3.0) - # self.events.add_base_mass.params["asset_cfg"].body_names = "trunk" - self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - - # rewards - self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" - self.rewards.feet_air_time.weight = 0.01 - self.rewards.undesired_contacts.params["sensor_cfg"].body_names = ".*thigh" - self.rewards.dof_torques_l2.weight = -0.0002 - self.rewards.track_lin_vel_xy_exp.weight = 1.5 - self.rewards.track_ang_vel_z_exp.weight = 0.75 - self.rewards.dof_acc_l2.weight = -2.5e-7 - self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk" - - -@configclass -class UnitreeA1RoughEnvCfg_PLAY(UnitreeA1RoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # spawn the robot randomly in the grid (instead of their terrain levels) - self.scene.terrain.max_init_terrain_level = None - # reduce the number of terrains to save memory - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing event - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py deleted file mode 100644 index a5c825bf2e98..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py +++ /dev/null @@ -1,60 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import AnymalBRoughEnvCfg - - -@configclass -class AnymalBFlatEnvCfg(AnymalBRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=75, - nconmax=15, - cone="elliptic", - impratio=100, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # override rewards - self.rewards.flat_orientation_l2.weight = -5.0 - self.rewards.dof_torques_l2.weight = -2.5e-5 - self.rewards.feet_air_time.weight = 0.5 - # change terrain to flat - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - # no height scan - self.scene.height_scanner = None - self.observations.policy.height_scan = None - # no terrain curriculum - self.curriculum.terrain_levels = None - - -class AnymalBFlatEnvCfg_PLAY(AnymalBFlatEnvCfg): - def __post_init__(self) -> None: - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing event - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py deleted file mode 100644 index 3a7d80af470f..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py +++ /dev/null @@ -1,34 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -from isaaclab_assets import ANYMAL_B_CFG # isort: skip - - -@configclass -class AnymalBRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = ANYMAL_B_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.manager_call_max_mode = {"Scene": 1} - - -@configclass -class AnymalBRoughEnvCfg_PLAY(AnymalBRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py deleted file mode 100644 index 3cc348a97675..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py +++ /dev/null @@ -1,52 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import AnymalCRoughEnvCfg - - -@configclass -class AnymalCFlatEnvCfg(AnymalCRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=120, - nconmax=15, - cone="elliptic", - impratio=100, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # override rewards - self.rewards.flat_orientation_l2.weight = -5.0 - self.rewards.dof_torques_l2.weight = -2.5e-5 - self.rewards.feet_air_time.weight = 0.5 - # change terrain to flat - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - # no terrain curriculum - self.curriculum.terrain_levels = None - - -class AnymalCFlatEnvCfg_PLAY(AnymalCFlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py deleted file mode 100644 index 1d2f2676c64a..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py +++ /dev/null @@ -1,40 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip - - -@configclass -class AnymalCRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - # switch robot to anymal-c - self.scene.robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.robot.actuators["legs"].armature = 0.01 - self.manager_call_max_mode = {"Scene": 1} - - -@configclass -class AnymalCRoughEnvCfg_PLAY(AnymalCRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py deleted file mode 100644 index 702443e815e2..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py +++ /dev/null @@ -1,46 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import AnymalDRoughEnvCfg - - -@configclass -class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=60, - nconmax=25, - cone="elliptic", - impratio=100.0, - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - super().__post_init__() - self.rewards.flat_orientation_l2.weight = -5.0 - self.rewards.dof_torques_l2.weight = -2.5e-5 - self.rewards.feet_air_time.weight = 0.5 - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - - -class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py deleted file mode 100644 index 71f49edd2e68..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py +++ /dev/null @@ -1,37 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets.robots.anymal import ANYMAL_D_CFG # isort: skip - - -@configclass -class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.manager_call_max_mode = {"Scene": 1} - - -@configclass -class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py deleted file mode 100644 index 818c7aa30a1e..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py +++ /dev/null @@ -1,45 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import CassieRoughEnvCfg - - -@configclass -class CassieFlatEnvCfg(CassieRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=52, - nconmax=15, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - super().__post_init__() - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 5.0 - self.rewards.joint_deviation_hip.params["asset_cfg"].joint_names = ["hip_rotation_.*"] - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - - -class CassieFlatEnvCfg_PLAY(CassieFlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py deleted file mode 100644 index 2fc44ea36cdc..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py +++ /dev/null @@ -1,96 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - RewardsCfg, -) - -from isaaclab_assets.robots.cassie import CASSIE_CFG # isort: skip - - -@configclass -class CassieRewardsCfg(RewardsCfg): - termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) - feet_air_time = RewTerm( - func=mdp.feet_air_time_positive_biped, - weight=2.5, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*toe"), - "command_name": "base_velocity", - "threshold": 0.3, - }, - ) - joint_deviation_hip = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["hip_abduction_.*", "hip_rotation_.*"])}, - ) - joint_deviation_toes = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["toe_joint_.*"])}, - ) - dof_pos_limits = RewTerm( - func=mdp.joint_pos_limits, - weight=-1.0, - params={"asset_cfg": SceneEntityCfg("robot", joint_names="toe_joint_.*")}, - ) - - -@configclass -class CassieRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - rewards: CassieRewardsCfg = CassieRewardsCfg() - - def __post_init__(self): - super().__post_init__() - self.scene.robot = CASSIE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.actions.joint_pos.scale = 0.5 - self.events.push_robot = None - # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation - # self.events.add_base_mass = None - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*pelvis"] - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.terminations.base_contact.params["sensor_cfg"].body_names = [".*pelvis"] - self.rewards.undesired_contacts = None - self.rewards.dof_torques_l2.weight = -5.0e-6 - self.rewards.track_lin_vel_xy_exp.weight = 2.0 - self.rewards.track_ang_vel_z_exp.weight = 1.0 - self.rewards.action_rate_l2.weight *= 1.5 - self.rewards.dof_acc_l2.weight *= 1.5 - - -@configclass -class CassieRoughEnvCfg_PLAY(CassieRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py deleted file mode 100644 index e99dd95ff82f..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py +++ /dev/null @@ -1,58 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import G1RoughEnvCfg - - -@configclass -class G1FlatEnvCfg(G1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=95, - nconmax=10, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - super().__post_init__() - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - self.rewards.track_ang_vel_z_exp.weight = 1.0 - self.rewards.lin_vel_z_l2.weight = -0.2 - self.rewards.action_rate_l2.weight = -0.005 - self.rewards.dof_acc_l2.weight = -1.0e-7 - self.rewards.feet_air_time.weight = 0.75 - self.rewards.feet_air_time.params["threshold"] = 0.4 - self.rewards.dof_torques_l2.weight = -2.0e-6 - self.rewards.dof_torques_l2.params["asset_cfg"] = SceneEntityCfg( - "robot", joint_names=[".*_hip_.*", ".*_knee_joint"] - ) - self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (-0.5, 0.5) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - - -class G1FlatEnvCfg_PLAY(G1FlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py deleted file mode 100644 index 7f9d12d0f201..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py +++ /dev/null @@ -1,178 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - RewardsCfg, -) - -## -# Pre-defined configs -## -from isaaclab_assets import G1_MINIMAL_CFG # isort: skip - - -@configclass -class G1Rewards(RewardsCfg): - """Reward terms for the MDP.""" - - termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) - track_lin_vel_xy_exp = RewTerm( - func=mdp.track_lin_vel_xy_yaw_frame_exp, - weight=1.0, - params={"command_name": "base_velocity", "std": 0.5}, - ) - track_ang_vel_z_exp = RewTerm( - func=mdp.track_ang_vel_z_world_exp, weight=2.0, params={"command_name": "base_velocity", "std": 0.5} - ) - feet_air_time = RewTerm( - func=mdp.feet_air_time_positive_biped, - weight=0.25, - params={ - "command_name": "base_velocity", - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*_ankle_roll_link"), - "threshold": 0.4, - }, - ) - feet_slide = RewTerm( - func=mdp.feet_slide, - weight=-0.1, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*_ankle_roll_link"), - "asset_cfg": SceneEntityCfg("robot", body_names=".*_ankle_roll_link"), - }, - ) - dof_pos_limits = RewTerm( - func=mdp.joint_pos_limits, - weight=-1.0, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_ankle_pitch_joint", ".*_ankle_roll_joint"])}, - ) - joint_deviation_hip = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.1, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_hip_yaw_joint", ".*_hip_roll_joint"])}, - ) - joint_deviation_arms = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.1, - params={ - "asset_cfg": SceneEntityCfg( - "robot", - joint_names=[ - ".*_shoulder_pitch_joint", - ".*_shoulder_roll_joint", - ".*_shoulder_yaw_joint", - ".*_elbow_pitch_joint", - ".*_elbow_roll_joint", - ], - ) - }, - ) - joint_deviation_fingers = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.05, - params={ - "asset_cfg": SceneEntityCfg( - "robot", - joint_names=[ - ".*_five_joint", - ".*_three_joint", - ".*_six_joint", - ".*_four_joint", - ".*_zero_joint", - ".*_one_joint", - ".*_two_joint", - ], - ) - }, - ) - joint_deviation_torso = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.1, - params={"asset_cfg": SceneEntityCfg("robot", joint_names="torso_joint")}, - ) - - -@configclass -class G1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - rewards: G1Rewards = G1Rewards() - - def __post_init__(self): - super().__post_init__() - self.scene.robot = G1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.events.push_robot = None - # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation - # self.events.add_base_mass = None - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.base_external_force_torque.params["asset_cfg"].body_names = ["torso_link"] - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - - # Rewards - self.rewards.lin_vel_z_l2.weight = 0.0 - self.rewards.undesired_contacts = None - self.rewards.flat_orientation_l2.weight = -1.0 - self.rewards.action_rate_l2.weight = -0.005 - self.rewards.dof_acc_l2.weight = -1.25e-7 - self.rewards.dof_acc_l2.params["asset_cfg"] = SceneEntityCfg( - "robot", joint_names=[".*_hip_.*", ".*_knee_joint"] - ) - self.rewards.dof_torques_l2.weight = -1.5e-7 - self.rewards.dof_torques_l2.params["asset_cfg"] = SceneEntityCfg( - "robot", joint_names=[".*_hip_.*", ".*_knee_joint", ".*_ankle_.*"] - ) - - # Commands - self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (-0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - - # terminations - self.terminations.base_contact.params["sensor_cfg"].body_names = "torso_link" - - -@configclass -class G1RoughEnvCfg_PLAY(G1RoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.episode_length_s = 40.0 - # spawn the robot randomly in the grid (instead of their terrain levels) - self.scene.terrain.max_init_terrain_level = None - # reduce the number of terrains to save memory - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - - self.commands.base_velocity.ranges.lin_vel_x = (1.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - self.commands.base_velocity.ranges.heading = (0.0, 0.0) - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py deleted file mode 100644 index dd4012882075..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py +++ /dev/null @@ -1,46 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import UnitreeGo1RoughEnvCfg - - -@configclass -class UnitreeGo1FlatEnvCfg(UnitreeGo1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=60, - nconmax=25, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - super().__post_init__() - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 0.25 - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - - -class UnitreeGo1FlatEnvCfg_PLAY(UnitreeGo1FlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py deleted file mode 100644 index cb3a602394a6..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py +++ /dev/null @@ -1,61 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -from isaaclab_assets.robots.unitree import UNITREE_GO1_CFG # isort: skip - - -@configclass -class UnitreeGo1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = UNITREE_GO1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.manager_call_max_mode = {"Scene": 1} - self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 - self.actions.joint_pos.scale = 0.25 - self.events.push_robot = None - self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" - self.rewards.feet_air_time.weight = 0.01 - self.rewards.undesired_contacts = None - self.rewards.dof_torques_l2.weight = -0.0002 - self.rewards.track_lin_vel_xy_exp.weight = 1.5 - self.rewards.track_ang_vel_z_exp.weight = 0.75 - self.rewards.dof_acc_l2.weight = -2.5e-7 - self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk" - - -@configclass -class UnitreeGo1RoughEnvCfg_PLAY(UnitreeGo1RoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py deleted file mode 100644 index 349cc450ca9f..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py +++ /dev/null @@ -1,46 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import UnitreeGo2RoughEnvCfg - - -@configclass -class UnitreeGo2FlatEnvCfg(UnitreeGo2RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=65, - nconmax=35, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - super().__post_init__() - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 0.25 - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - - -class UnitreeGo2FlatEnvCfg_PLAY(UnitreeGo2FlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py deleted file mode 100644 index a25748da9885..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py +++ /dev/null @@ -1,60 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -from isaaclab_assets.robots.unitree import UNITREE_GO2_CFG # isort: skip - - -@configclass -class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = UNITREE_GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 - self.actions.joint_pos.scale = 0.25 - self.events.push_robot = None - self.events.base_external_force_torque.params["asset_cfg"].body_names = "base" - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" - self.rewards.feet_air_time.weight = 0.01 - self.rewards.undesired_contacts = None - self.rewards.dof_torques_l2.weight = -0.0002 - self.rewards.track_lin_vel_xy_exp.weight = 1.5 - self.rewards.track_ang_vel_z_exp.weight = 0.75 - self.rewards.dof_acc_l2.weight = -2.5e-7 - self.terminations.base_contact.params["sensor_cfg"].body_names = "base" - - -@configclass -class UnitreeGo2RoughEnvCfg_PLAY(UnitreeGo2RoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py deleted file mode 100644 index a7021343464a..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py +++ /dev/null @@ -1,46 +0,0 @@ -# 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 - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from .rough_env_cfg import H1RoughEnvCfg - - -@configclass -class H1FlatEnvCfg(H1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=65, - nconmax=15, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - super().__post_init__() - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - self.rewards.feet_air_time.weight = 1.0 - self.rewards.feet_air_time.params["threshold"] = 0.6 - - -class H1FlatEnvCfg_PLAY(H1FlatEnvCfg): - def __post_init__(self) -> None: - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py deleted file mode 100644 index 1b65e018c9e4..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py +++ /dev/null @@ -1,131 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - RewardsCfg, -) - -## -# Pre-defined configs -## -from isaaclab_assets import H1_MINIMAL_CFG # isort: skip - - -@configclass -class H1Rewards(RewardsCfg): - """Reward terms for the MDP.""" - - termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) - lin_vel_z_l2 = None - track_lin_vel_xy_exp = RewTerm( - func=mdp.track_lin_vel_xy_yaw_frame_exp, - weight=1.0, - params={"command_name": "base_velocity", "std": 0.5}, - ) - track_ang_vel_z_exp = RewTerm( - func=mdp.track_ang_vel_z_world_exp, weight=1.0, params={"command_name": "base_velocity", "std": 0.5} - ) - feet_air_time = RewTerm( - func=mdp.feet_air_time_positive_biped, - weight=0.25, - params={ - "command_name": "base_velocity", - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*ankle_link"), - "threshold": 0.4, - }, - ) - feet_slide = RewTerm( - func=mdp.feet_slide, - weight=-0.25, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*ankle_link"), - "asset_cfg": SceneEntityCfg("robot", body_names=".*ankle_link"), - }, - ) - dof_pos_limits = RewTerm( - func=mdp.joint_pos_limits, weight=-1.0, params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*_ankle")} - ) - joint_deviation_hip = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_hip_yaw", ".*_hip_roll"])}, - ) - joint_deviation_arms = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_shoulder_.*", ".*_elbow"])}, - ) - joint_deviation_torso = RewTerm( - func=mdp.joint_deviation_l1, weight=-0.1, params={"asset_cfg": SceneEntityCfg("robot", joint_names="torso")} - ) - - -@configclass -class H1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - rewards: H1Rewards = H1Rewards() - - def __post_init__(self): - super().__post_init__() - self.scene.robot = H1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.events.push_robot = None - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*torso_link"] - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.rewards.undesired_contacts = None - self.rewards.flat_orientation_l2.weight = -1.0 - self.rewards.dof_torques_l2.weight = 0.0 - self.rewards.action_rate_l2.weight = -0.005 - self.rewards.dof_acc_l2.weight = -1.25e-7 - self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - self.terminations.base_contact.params["sensor_cfg"].body_names = ".*torso_link" - - -@configclass -class H1RoughEnvCfg_PLAY(H1RoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.episode_length_s = 40.0 - # spawn the robot randomly in the grid (instead of their terrain levels) - self.scene.terrain.max_init_terrain_level = None - # reduce the number of terrains to save memory - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - - self.commands.base_velocity.ranges.lin_vel_x = (1.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - self.commands.base_velocity.ranges.heading = (0.0, 0.0) - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py deleted file mode 100644 index 52d53c3db268..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py +++ /dev/null @@ -1,296 +0,0 @@ -# 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 - -import math -from dataclasses import MISSING - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg, AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import CurriculumTermCfg as CurrTerm -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sensors import ContactSensorCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR -from isaaclab.utils.configclass import configclass -from isaaclab.utils.noise import UniformNoiseCfg as Unoise - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp - -## -# Pre-defined configs -## -from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip - - -## -# Scene definition -## - - -@configclass -class MySceneCfg(InteractiveSceneCfg): - """Configuration for the terrain scene with a legged robot.""" - - # ground terrain - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="generator", - terrain_generator=ROUGH_TERRAINS_CFG, - max_init_terrain_level=5, - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg( - friction_combine_mode="multiply", - restitution_combine_mode="multiply", - static_friction=1.0, - dynamic_friction=1.0, - ), - visual_material=sim_utils.MdlFileCfg( - mdl_path=f"{ISAACLAB_NUCLEUS_DIR}/Materials/TilesMarbleSpiderWhiteBrickBondHoned/TilesMarbleSpiderWhiteBrickBondHoned.mdl", - project_uvw=True, - texture_scale=(0.25, 0.25), - ), - debug_vis=False, - ) - # robots - robot: ArticulationCfg = MISSING - # sensors - contact_forces = ContactSensorCfg( - prim_path="{ENV_REGEX_NS}/Robot/.*", - filter_prim_paths_expr=[], - history_length=3, - track_air_time=True, - ) - # lights - sky_light = AssetBaseCfg( - prim_path="/World/skyLight", - spawn=sim_utils.DomeLightCfg( - intensity=750.0, - texture_file=f"{ISAAC_NUCLEUS_DIR}/Materials/Textures/Skies/PolyHaven/kloofendal_43d_clear_puresky_4k.hdr", - ), - ) - - -## -# MDP settings -## - - -@configclass -class CommandsCfg: - """Command specifications for the MDP.""" - - base_velocity = mdp.UniformVelocityCommandCfg( - asset_name="robot", - resampling_time_range=(10.0, 10.0), - rel_standing_envs=0.02, - rel_heading_envs=1.0, - heading_command=True, - heading_control_stiffness=0.5, - debug_vis=True, - ranges=mdp.UniformVelocityCommandCfg.Ranges( - lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi) - ), - ) - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) - - -@configclass -class PolicyCfg(ObsGroup): - """Observations for policy group.""" - - # observation terms (order preserved) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1)) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2)) - projected_gravity = ObsTerm( - func=mdp.projected_gravity, - noise=Unoise(n_min=-0.05, n_max=0.05), - ) - velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"}) - joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) - joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = True - self.concatenate_terms = True - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - # FIXME(warp-migration): COM randomization in exp manager-based locomotion currently causes - # NaNs and is temporarily disabled. - # base_com = EventTerm( - # func=mdp.randomize_rigid_body_com, - # mode="startup", - # params={ - # "asset_cfg": SceneEntityCfg("robot", body_names="base"), - # "com_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05), "z": (-0.01, 0.01)}, - # }, - # ) - base_com = None - - # reset - base_external_force_torque = EventTerm( - func=mdp.apply_external_force_torque, - mode="reset", - params={ - "asset_cfg": SceneEntityCfg("robot", body_names="base"), - "force_range": (0.0, 0.0), - "torque_range": (-0.0, 0.0), - }, - ) - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={ - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (-0.5, 0.5), - "y": (-0.5, 0.5), - "z": (-0.5, 0.5), - "roll": (-0.5, 0.5), - "pitch": (-0.5, 0.5), - "yaw": (-0.5, 0.5), - }, - }, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_scale, - mode="reset", - params={ - "position_range": (0.5, 1.5), - "velocity_range": (0.0, 0.0), - }, - ) - - # interval - push_robot = EventTerm( - func=mdp.push_by_setting_velocity, - mode="interval", - interval_range_s=(10.0, 15.0), - params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # -- task - track_lin_vel_xy_exp = RewTerm( - func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} - ) - track_ang_vel_z_exp = RewTerm( - func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} - ) - # -- penalties - lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) - ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) - dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) - dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) - action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) - feet_air_time = RewTerm( - func=mdp.feet_air_time, - weight=0.125, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), - "command_name": "base_velocity", - "threshold": 0.5, - }, - ) - undesired_contacts = RewTerm( - func=mdp.undesired_contacts, - weight=-1.0, - params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, - ) - # -- optional penalties - flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) - dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - time_out = DoneTerm(func=mdp.time_out, time_out=True) - base_contact = DoneTerm( - func=mdp.illegal_contact, - params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, - ) - - -@configclass -class CurriculumCfg: - """Curriculum terms for the MDP.""" - - terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) - - -## -# Environment configuration -## - - -@configclass -class LocomotionVelocityRoughEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the locomotion velocity-tracking environment.""" - - # Scene settings - scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5, replicate_physics=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - commands: CommandsCfg = CommandsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - curriculum: CurriculumCfg = CurriculumCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 4 - self.episode_length_s = 20.0 - # simulation settings - self.sim.dt = 1.0 / 200.0 - self.sim.render_interval = self.decimation - self.sim.physics_material = self.scene.terrain.physics_material - # update sensor update periods - if self.scene.contact_forces is not None: - self.scene.contact_forces.update_period = self.sim.dt - # check if terrain levels curriculum is enabled - if getattr(self.curriculum, "terrain_levels", None) is not None: - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.curriculum = True - else: - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.curriculum = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py deleted file mode 100644 index 6cd56351b6e5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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 - -from .reach import * diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py deleted file mode 100644 index d6d36afd15f5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py +++ /dev/null @@ -1,74 +0,0 @@ -# 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 - -import math - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp -from isaaclab_tasks_experimental.manager_based.manipulation.reach.reach_env_cfg import ReachEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets import FRANKA_PANDA_CFG # isort: skip - - -## -# Environment configuration -## - - -@configclass -class FrankaReachEnvCfg(ReachEnvCfg): - sim: SimulationCfg = SimulationCfg( - dt=1 / 60, - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=50, - nconmax=20, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ), - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # switch robot to franka - self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - # override rewards - self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["panda_hand"] - self.rewards.end_effector_position_tracking_fine_grained.params["asset_cfg"].body_names = ["panda_hand"] - self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["panda_hand"] - - # override actions - self.actions.arm_action = mdp.JointPositionActionCfg( - asset_name="robot", joint_names=["panda_joint.*"], scale=0.5, use_default_offset=True - ) - # override command generator body - # end-effector is along z-direction - self.commands.ee_pose.body_name = "panda_hand" - self.commands.ee_pose.ranges.pitch = (math.pi, math.pi) - - -@configclass -class FrankaReachEnvCfg_PLAY(FrankaReachEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py deleted file mode 100644 index 42104e23b1b2..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py +++ /dev/null @@ -1,74 +0,0 @@ -# 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 - -import math - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp -from isaaclab_tasks_experimental.manager_based.manipulation.reach.reach_env_cfg import ReachEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets import UR10_CFG # isort: skip - - -## -# Environment configuration -## - - -@configclass -class UR10ReachEnvCfg(ReachEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=50, - nconmax=20, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # switch robot to ur10 - self.scene.robot = UR10_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - # override events - self.events.reset_robot_joints.params["position_range"] = (0.75, 1.25) - # override rewards - self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["ee_link"] - self.rewards.end_effector_position_tracking_fine_grained.params["asset_cfg"].body_names = ["ee_link"] - self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["ee_link"] - # override actions - self.actions.arm_action = mdp.JointPositionActionCfg( - asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True - ) - # override command generator body - # end-effector is along x-direction - self.commands.ee_pose.body_name = "ee_link" - self.commands.ee_pose.ranges.pitch = (math.pi / 2, math.pi / 2) - - -@configclass -class UR10ReachEnvCfg_PLAY(UR10ReachEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py deleted file mode 100644 index e83a27e44db5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py +++ /dev/null @@ -1,206 +0,0 @@ -# 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 - -from dataclasses import MISSING - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg, AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import ActionTermCfg as ActionTerm -from isaaclab.managers import CurriculumTermCfg as CurrTerm -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.utils.configclass import configclass -from isaaclab.utils.noise import UniformNoiseCfg as Unoise - -import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp - -## -# Scene definition -## - - -@configclass -class ReachSceneCfg(InteractiveSceneCfg): - """Configuration for the scene with a robotic arm.""" - - # world - ground = AssetBaseCfg( - prim_path="/World/ground", - spawn=sim_utils.GroundPlaneCfg(), - init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)), - ) - - # robots - robot: ArticulationCfg = MISSING - - # lights - light = AssetBaseCfg( - prim_path="/World/light", - spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=2500.0), - ) - - -## -# MDP settings -## - - -@configclass -class CommandsCfg: - """Command terms for the MDP.""" - - ee_pose = mdp.UniformPoseCommandCfg( - asset_name="robot", - body_name=MISSING, - resampling_time_range=(4.0, 4.0), - debug_vis=True, - ranges=mdp.UniformPoseCommandCfg.Ranges( - pos_x=(0.35, 0.65), - pos_y=(-0.2, 0.2), - pos_z=(0.15, 0.5), - roll=(0.0, 0.0), - pitch=MISSING, # depends on end-effector axis - yaw=(-3.14, 3.14), - ), - ) - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - arm_action: ActionTerm = MISSING - gripper_action: ActionTerm | None = None - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for policy group.""" - - # observation terms (order preserved) - joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) - joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) - pose_command = ObsTerm(func=mdp.generated_commands, params={"command_name": "ee_pose"}) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = True - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={"pose_range": {}, "velocity_range": {}}, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_scale, - mode="reset", - params={ - "position_range": (0.5, 1.5), - "velocity_range": (0.0, 0.0), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # task terms - end_effector_position_tracking = RewTerm( - func=mdp.position_command_error, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"}, - ) - end_effector_position_tracking_fine_grained = RewTerm( - func=mdp.position_command_error_tanh, - weight=0.1, - params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "std": 0.1, "command_name": "ee_pose"}, - ) - end_effector_orientation_tracking = RewTerm( - func=mdp.orientation_command_error, - weight=-0.1, - params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"}, - ) - - # action penalty - action_rate = RewTerm(func=mdp.action_rate_l2, weight=-0.0001) - joint_vel = RewTerm( - func=mdp.joint_vel_l2, - weight=-0.0001, - params={"asset_cfg": SceneEntityCfg("robot")}, - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - time_out = DoneTerm(func=mdp.time_out, time_out=True) - - -@configclass -class CurriculumCfg: - """Curriculum terms for the MDP.""" - - action_rate = CurrTerm( - func=mdp.modify_reward_weight, params={"term_name": "action_rate", "weight": -0.005, "num_steps": 4500} - ) - - joint_vel = CurrTerm( - func=mdp.modify_reward_weight, params={"term_name": "joint_vel", "weight": -0.001, "num_steps": 4500} - ) - - -## -# Environment configuration -## - - -@configclass -class ReachEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the reach end-effector pose tracking environment.""" - - # Scene settings - scene: ReachSceneCfg = ReachSceneCfg(num_envs=4096, env_spacing=2.5) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - commands: CommandsCfg = CommandsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - curriculum: CurriculumCfg = CurriculumCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 2 - self.sim.render_interval = self.decimation - self.episode_length_s = 12.0 - self.viewer.eye = (3.5, 3.5, 3.5) - # simulation settings - self.sim.dt = 1.0 / 60.0 From 817758733266126023d72147cbfbbdd1853309e3 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Fri, 5 Jun 2026 00:11:10 +0000 Subject: [PATCH 17/36] Limit warp cfg adaptation to warp-managed term groups + coverage test Only observation/reward/termination/action terms are swapped to warp twins and have their SceneEntityCfg promoted; event, curriculum, recorder and command terms run on the stable (torch) managers, so their stable funcs are left in place. This lets the warp env reuse the full stable cfg (domain randomization events, reward curricula, etc.) instead of a trimmed copy. Add a parametrized coverage test that, for every manager-based *-Warp-v0 task, loads its stable cfg and asserts adapt_cfg_for_warp succeeds (all warp-managed twins resolve). Three tasks are xfail(strict) pending warp twins: cartpole survival_success_rate, ant/humanoid body_incoming_wrench. Also add the missing core/__init__.py so the registration walk descends into the migrated package. --- .../isaaclab_experimental/envs/frontend.py | 12 +++ .../test/envs/test_frontend.py | 6 +- .../test/envs/test_frontend_cfg_conversion.py | 92 +++++++++++++++++++ .../core/reach/config/ur_10/__init__.py | 2 +- 4 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 2b85e474da8f..7a3eebd95f28 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -76,6 +76,14 @@ class FrontendIncompatibleError(RuntimeError): # the warp packages. Used by the direct-workflow guard. _WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") +# Top-level cfg groups whose managers run warp-first. Only terms under these are +# adapted (SceneEntityCfg promotion + MDP twin swap); the event, curriculum, +# recorder and command managers run on the stable (torch) implementation, so +# their stable funcs/SceneEntityCfgs are left untouched. A stable term left on a +# warp manager would break, so a missing twin in these groups is a hard error; +# a stable term on a stable manager is correct, so those groups are skipped. +_WARP_MANAGED_GROUPS: frozenset[str] = frozenset({"observations", "rewards", "terminations", "actions"}) + def build( frontend: Frontend | str, @@ -193,6 +201,8 @@ def _promote_scene_entity_cfgs(cfg: Any) -> None: promoted: list[str] = [] for path, term in _walk_terms(cfg): + if not path or path[0] not in _WARP_MANAGED_GROUPS: + continue params = getattr(term, "params", None) if not isinstance(params, dict): continue @@ -237,6 +247,8 @@ def _swap_mdp(cfg: Any, label: str) -> None: swapped = 0 missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) for path, term in _walk_terms(cfg): + if not path or path[0] not in _WARP_MANAGED_GROUPS: + continue location = ".".join(path) for attr in ("func", "class_type"): stable = getattr(term, attr, None) diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index 28666ed78e34..bd43f3c42611 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -313,12 +313,16 @@ def test_walks_all_term_groups(self): ), ) _promote_scene_entity_cfgs(cfg) + # Warp-managed groups (rewards, observations incl. sub-groups) are promoted. self.assertIsInstance(cfg.rewards.r1.params["asset_cfg"], WarpSceneEntityCfg) - self.assertIsInstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) self.assertIsInstance(cfg.observations.policy.o1.params["asset_cfg"], WarpSceneEntityCfg) # The perception sub-group is reached even though its attribute name is # not hardcoded in the framework. self.assertIsInstance(cfg.observations.perception.o3.params["asset_cfg"], WarpSceneEntityCfg) + # Events run on the stable (torch) manager, so their SceneEntityCfg is + # left untouched — promoting it would hand a warp variant to a torch manager. + self.assertIsInstance(cfg.events.e1.params["asset_cfg"], StableSceneEntityCfg) + self.assertNotIsInstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) # ====================================================================== diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py new file mode 100644 index 000000000000..14af767d8d83 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -0,0 +1,92 @@ +# 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 + +"""Coverage test: every manager-based ``*-Warp-v0`` task adapts cleanly from its stable cfg. + +For each registered manager-based warp task we load the *stable* env cfg it points +at, force Newton physics, and run :func:`adapt_cfg_for_warp` — the same adaptation +the warp env runs in its ``__init__``. A pass proves the SceneEntityCfg promotion +and the MDP twin swap succeed for every warp-managed term (observations / rewards / +terminations / actions). This is the guard against drift: if a stable cfg later +gains a warp-managed term with no warp twin, the matching case fails here instead +of at training time. +""" + +from __future__ import annotations + +import importlib + +import gymnasium as gym +import isaaclab_tasks_experimental # noqa: F401 +import pytest +from isaaclab_experimental.envs.frontend import adapt_cfg_for_warp +from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg + +# Registering the task packages is the whole point — import for side effects. +import isaaclab_tasks # noqa: F401 + +# Manager-based warp tasks are exactly those whose entry point is the shared warp +# env class; direct ``*-Direct-Warp-v0`` tasks register their own env class and +# are not cfg-adapted, so they are excluded here. +_MANAGER_WARP_ENTRY_POINT = "isaaclab_experimental.envs:ManagerBasedRLEnvWarp" + + +def _manager_warp_tasks() -> list[tuple[str, str]]: + """Return ``(task_id, env_cfg_entry_point)`` for every manager-based warp task.""" + tasks: list[tuple[str, str]] = [] + for task_id, spec in gym.registry.items(): + if spec.entry_point != _MANAGER_WARP_ENTRY_POINT: + continue + cfg_entry = (spec.kwargs or {}).get("env_cfg_entry_point") + if isinstance(cfg_entry, str): + tasks.append((task_id, cfg_entry)) + return sorted(tasks) + + +def _instantiate_cfg(cfg_entry_point: str): + """Import ``module:Class`` and instantiate the stable env cfg.""" + module_path, class_name = cfg_entry_point.split(":") + return getattr(importlib.import_module(module_path), class_name)() + + +_MANAGER_WARP_TASKS = _manager_warp_tasks() + +# Tasks whose stable cfg still includes a warp-managed term with no warp twin. +# These are tracked for implementation; delete the entry once the twin lands +# (xfail is strict, so an unexpected pass fails the suite and flags the cleanup). +_PENDING_WARP_TWINS = { + "Isaac-Cartpole-Warp-v0": "reward 'survival_success_rate'", + "Isaac-Ant-Warp-v0": "observation 'body_incoming_wrench'", + "Isaac-Humanoid-Warp-v0": "observation 'body_incoming_wrench'", +} + + +def _params(): + cases = [] + for task_id, cfg_entry_point in _MANAGER_WARP_TASKS: + marks = () + if task_id in _PENDING_WARP_TWINS: + marks = pytest.mark.xfail( + strict=True, + reason=f"pending warp twin for {_PENDING_WARP_TWINS[task_id]}", + ) + cases.append(pytest.param(task_id, cfg_entry_point, marks=marks, id=task_id)) + return cases + + +def test_manager_warp_tasks_are_registered(): + """Sanity: the package actually registered manager-based warp tasks.""" + assert _MANAGER_WARP_TASKS, "no manager-based '*-Warp-v0' tasks registered" + + +@pytest.mark.parametrize("task_id, cfg_entry_point", _params()) +def test_stable_cfg_adapts_to_warp(task_id: str, cfg_entry_point: str): + """The stable cfg behind each warp task adapts without a missing twin.""" + cfg = _instantiate_cfg(cfg_entry_point) + # The warp env requires Newton physics (normally via ``presets=newton_mjwarp``); + # set it directly so the test does not depend on Hydra preset resolution. + cfg.sim.physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) + # Raises FrontendIncompatibleError if any warp-managed term lacks a warp twin. + adapt_cfg_for_warp(cfg) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py index 03843620488d..afeaffba8433 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/ur_10/__init__.py @@ -13,7 +13,7 @@ # Warp tasks reuse the stable env cfgs; only physics (presets=newton_mjwarp) # and MDP twins are swapped at construction (see adapt_cfg_for_warp). -_stable_pkg = agents.__name__.rsplit(".", 1)[0] +# _stable_pkg = agents.__name__.rsplit(".", 1)[0] # gym.register( # id="Isaac-Reach-UR10-Warp-v0", From 28033c89b992cbfb6654eef1545154ee6bd6cb56 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Fri, 5 Jun 2026 00:16:58 +0000 Subject: [PATCH 18/36] Match consolidated cartpole IDs: drop -v0 from warp cartpole tasks Stable cartpole was consolidated to unversioned ids (Isaac-Cartpole, Isaac-Cartpole-Direct); mirror that on the warp side so each warp task pairs 1:1 with its stable counterpart. Other tasks keep -Warp-v0 because their stable ids still carry -v0 on develop. --- .../isaaclab_experimental/envs/frontend.py | 2 +- .../test/envs/test_frontend_cfg_conversion.py | 2 +- .../isaaclab_tasks_experimental/core/cartpole/__init__.py | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 7a3eebd95f28..dc79bca5a5d8 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -115,7 +115,7 @@ def build( workflow = _detect_workflow(env_cfg) if workflow is Workflow.DIRECT: # Direct workflows aren't adapted — they must already be registered - # under the warp packages (e.g. ``Isaac-Cartpole-Direct-Warp-v0``). + # under the warp packages (e.g. ``Isaac-Cartpole-Direct-Warp``). _assert_direct_warp_registration(task_id) return gym.make(task_id, cfg=env_cfg, **construct_kwargs) diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 14af767d8d83..88fc1a424906 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -57,7 +57,7 @@ def _instantiate_cfg(cfg_entry_point: str): # These are tracked for implementation; delete the entry once the twin lands # (xfail is strict, so an unexpected pass fails the suite and flags the cleanup). _PENDING_WARP_TWINS = { - "Isaac-Cartpole-Warp-v0": "reward 'survival_success_rate'", + "Isaac-Cartpole-Warp": "reward 'survival_success_rate'", "Isaac-Ant-Warp-v0": "observation 'body_incoming_wrench'", "Isaac-Humanoid-Warp-v0": "observation 'body_incoming_wrench'", } diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py index d5d93b3dba48..fd5463ad023f 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py @@ -26,7 +26,7 @@ # Manager-based: stable cfg adapted to warp at construction. gym.register( - id="Isaac-Cartpole-Warp-v0", + id="Isaac-Cartpole-Warp", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ @@ -40,7 +40,7 @@ # Direct: dedicated warp env class + local cfg (not adaptable from a cfg). gym.register( - id="Isaac-Cartpole-Direct-Warp-v0", + id="Isaac-Cartpole-Direct-Warp", entry_point=f"{__name__}.cartpole_warp_env:CartpoleWarpEnv", disable_env_checker=True, kwargs={ From 87a03b7d01f7c4428d80cfcb56fed73b88151540 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Fri, 5 Jun 2026 00:38:59 +0000 Subject: [PATCH 19/36] Add warp twins: cartpole survival_success_rate, body_incoming_wrench MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Implements the two missing warp MDP twins so the full stable cfg adapts for every manager-based *-Warp task (clears the xfails in the conversion test): - cartpole `survival_success_rate`: ManagerTermBase reward mirroring stable — zero reward contribution, logs Metrics/success_rate (time-out rate) on reset. - generic `body_incoming_wrench`: observation reading the Newton joint-wrench sensor and gathering per-body force+torque, following the existing sensor-reading twins (undesired_contacts/illegal_contact). Lives in the shared fallback mdp so it is task-agnostic. Extends the observation manager's `body:N` out_dim resolution to also read `sensor_cfg` (not just `asset_cfg`), since wrench obs select bodies via a sensor entity. --- .../envs/mdp/observations.py | 46 +++++++++++++++++++ .../managers/observation_manager.py | 9 ++-- .../test/envs/test_frontend_cfg_conversion.py | 6 +-- .../core/cartpole/mdp/__init__.pyi | 3 +- .../core/cartpole/mdp/rewards.py | 30 ++++++++++++ 5 files changed, 84 insertions(+), 10 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py index 808231c8faf6..e36ddd189f27 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py @@ -367,3 +367,49 @@ def generated_commands(env: ManagerBasedEnv, out, command_name: str) -> None: fn._cmd_name = command_name fn._is_warmed_up = True wp.copy(out, fn._cmd_wp) + + +""" +Sensors. +""" + + +@wp.kernel +def _body_incoming_wrench_kernel( + force: wp.array(dtype=wp.vec3f, ndim=2), + torque: wp.array(dtype=wp.vec3f, ndim=2), + body_ids: wp.array(dtype=wp.int32), + out: wp.array(dtype=wp.float32, ndim=2), +): + env_id = wp.tid() + for k in range(body_ids.shape[0]): + b = body_ids[k] + f = force[env_id, b] + t = torque[env_id, b] + out[env_id, k * 6 + 0] = f[0] + out[env_id, k * 6 + 1] = f[1] + out[env_id, k * 6 + 2] = f[2] + out[env_id, k * 6 + 3] = t[0] + out[env_id, k * 6 + 4] = t[1] + out[env_id, k * 6 + 5] = t[2] + + +@generic_io_descriptor_warp(out_dim="body:6", observation_type="BodyState", on_inspect=[record_shape, record_dtype]) +def body_incoming_wrench(env: ManagerBasedEnv, out, sensor_cfg: SceneEntityCfg) -> None: + """Incoming spatial wrench [N, N·m] on selected bodies, laid out per body as ``[fx, fy, fz, tx, ty, tz]``. + + Warp-first override of :func:`isaaclab.envs.mdp.observations.body_incoming_wrench`. Reads the + Newton joint-wrench sensor and gathers the force/torque of the bodies selected by ``sensor_cfg`` + into ``out`` (shape ``(num_envs, 6 * num_selected_bodies)``). + """ + sensor = env.scene.sensors[sensor_cfg.name] + force = sensor.data.force + torque = sensor.data.torque + if force is None or torque is None: + raise RuntimeError("Joint wrench sensor data is not initialized. Call sim.reset() before reading observations.") + wp.launch( + kernel=_body_incoming_wrench_kernel, + dim=env.num_envs, + inputs=[force.warp, torque.warp, sensor_cfg.body_ids_wp, out], + device=env.device, + ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py index 059ae2afdce1..46c93f891fa5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/observation_manager.py @@ -922,11 +922,12 @@ def _resolve_out_dim(self, out_dim: int | str, term_cfg: ObservationTermCfg) -> if isinstance(out_dim, str) and out_dim.startswith("body:"): per_body = int(out_dim.split(":")[1]) - asset_cfg = term_cfg.params.get("asset_cfg") - body_ids = getattr(asset_cfg, "body_ids", None) + # Body selection may live on an asset (articulation) or a sensor entity. + entity_cfg = term_cfg.params.get("asset_cfg") or term_cfg.params.get("sensor_cfg") + body_ids = getattr(entity_cfg, "body_ids", None) if body_ids is None or body_ids == slice(None): - asset = self._env.scene[asset_cfg.name] - return per_body * len(asset.body_names) + entity = self._env.scene[entity_cfg.name] + return per_body * len(entity.body_names) return per_body * len(body_ids) if out_dim == "command": diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 88fc1a424906..ea3afda6d300 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -56,11 +56,7 @@ def _instantiate_cfg(cfg_entry_point: str): # Tasks whose stable cfg still includes a warp-managed term with no warp twin. # These are tracked for implementation; delete the entry once the twin lands # (xfail is strict, so an unexpected pass fails the suite and flags the cleanup). -_PENDING_WARP_TWINS = { - "Isaac-Cartpole-Warp": "reward 'survival_success_rate'", - "Isaac-Ant-Warp-v0": "observation 'body_incoming_wrench'", - "Isaac-Humanoid-Warp-v0": "observation 'body_incoming_wrench'", -} +_PENDING_WARP_TWINS: dict[str, str] = {} def _params(): diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi index 377068405c79..657186c2539b 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi @@ -5,10 +5,11 @@ __all__ = [ "joint_pos_target_l2", + "survival_success_rate", ] # Forward stable MDP terms and experimental Warp-first overrides lazily, then # override with cartpole-specific terms below. from isaaclab_experimental.envs.mdp import * # noqa: F401, F403 -from .rewards import joint_pos_target_l2 +from .rewards import joint_pos_target_l2, survival_success_rate diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py index 2678ef03de65..ced0dadaad91 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py @@ -9,9 +9,12 @@ import warp as wp from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.managers.manager_base import ManagerTermBase from isaaclab_experimental.utils.warp.utils import wrap_to_pi if TYPE_CHECKING: + from isaaclab_experimental.managers.manager_term_cfg import RewardTermCfg + from isaaclab.assets import Articulation from isaaclab.envs import ManagerBasedRLEnv @@ -43,3 +46,30 @@ def joint_pos_target_l2(env: ManagerBasedRLEnv, out, target: float, asset_cfg: S inputs=[asset.data.joint_pos.warp, asset_cfg.joint_mask, out, target], device=env.device, ) + + +class survival_success_rate(ManagerTermBase): + """Logs the mean time-out (survival) rate of the resetting envs; contributes zero reward. + + Mirrors the stable term: the reward value is always zero (so it is registered with + ``weight=0.0``) and the only effect is logging ``Metrics/success_rate`` on reset, where + success is defined as the episode ending by time-out rather than an early termination. + """ + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + + def reset(self, env_mask: wp.array | None = None) -> None: + # ``time_outs`` is exposed as a torch tensor by the warp termination manager. + time_outs = self._env.termination_manager.time_outs + if env_mask is None: + survived = time_outs.float().mean() + else: + selected = time_outs[wp.to_torch(env_mask).bool()] + survived = selected.float().mean() if selected.numel() > 0 else time_outs.new_zeros(()) + self._env.extras.setdefault("log", {})["Metrics/success_rate"] = float(survived.item()) + + def __call__(self, env: ManagerBasedRLEnv, out) -> None: + # Pure logging term: the reward contribution is zero. The reward manager pre-zeroes + # ``out`` each step, but zero it explicitly so the term is correct independent of that. + out.zero_() From 3c8a8ae63a980cdec0fc2834c5633735f97ceca0 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Fri, 5 Jun 2026 00:48:06 +0000 Subject: [PATCH 20/36] Swap action-term class_type in warp adaptation; fix cartpole agents The cfg walker only matched ManagerTermBaseCfg, but ActionTermCfg is a separate base (not a subclass) carrying a swappable class_type. As a result action terms kept their stable class and the warp ActionManager rejected them ("not of type ActionType") when a *-Warp task reused a stable cfg. Match ActionTermCfg in _walk_terms so action class_type is swapped too, and guard it in the conversion test. Also fix the cartpole warp registration agent entry points to the current stable modules (rsl_rl_ppo_cfg:Cartpole[Direct]PPORunnerCfg, sb3_ppo_cfg) after the cartpole consolidation renamed them. --- .../isaaclab_experimental/envs/frontend.py | 23 +++++++++++-------- .../test/envs/test_frontend_cfg_conversion.py | 16 +++++++++++++ .../core/cartpole/__init__.py | 8 +++---- 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index dc79bca5a5d8..f2d379ece46a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -384,26 +384,31 @@ def _is_swap_candidate(value: Any) -> bool: def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], Any]]: - """Yield ``(path, term)`` for every :class:`ManagerTermBaseCfg` in the cfg tree. + """Yield ``(path, term)`` for every MDP term cfg in the cfg tree. + + A "term" is a :class:`ManagerTermBaseCfg` (observation/reward/termination/ + event/curriculum) *or* an :class:`ActionTermCfg` — the latter is a separate + base that is **not** a ``ManagerTermBaseCfg`` subclass, yet carries a + swappable ``class_type``, so it must be matched explicitly. Behavior at each node: - * Match (:class:`ManagerTermBaseCfg` instance): yield ``(path, node)`` and stop — - do not descend into ``term.params`` / ``term.func``. + * Match (a term cfg instance): yield ``(path, node)`` and stop — do not + descend into ``term.params`` / ``term.func`` / ``term.class_type``. * Configclass: don't yield; recurse into every non-underscore attribute, - extending the path. ``observations``, ``rewards``, ``events``, sub-groups - like ``observations.policy`` / ``observations.perception``, and anything - nested deeper are reached transparently. + extending the path. ``observations``, ``rewards``, ``events``, ``actions``, + sub-groups like ``observations.policy`` / ``observations.perception``, and + anything nested deeper are reached transparently. * Anything else (plain Python data, callables, non-configclass objects): stop. No yield, no recursion. Driven entirely by type — no attribute names are hardcoded — so future cfg layouts (extra observation groups, new nesting, etc.) are picked up - automatically as long as their terms subclass :class:`ManagerTermBaseCfg`. + automatically as long as their terms subclass one of the term base cfgs. """ - from isaaclab.managers.manager_term_cfg import ManagerTermBaseCfg + from isaaclab.managers.manager_term_cfg import ActionTermCfg, ManagerTermBaseCfg - if isinstance(node, ManagerTermBaseCfg): + if isinstance(node, (ManagerTermBaseCfg, ActionTermCfg)): yield path, node return if not hasattr(node, "__dataclass_fields__"): diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index ea3afda6d300..934542d5d525 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -77,6 +77,9 @@ def test_manager_warp_tasks_are_registered(): assert _MANAGER_WARP_TASKS, "no manager-based '*-Warp-v0' tasks registered" +_WARP_ROOTS = ("isaaclab_experimental", "isaaclab_tasks_experimental") + + @pytest.mark.parametrize("task_id, cfg_entry_point", _params()) def test_stable_cfg_adapts_to_warp(task_id: str, cfg_entry_point: str): """The stable cfg behind each warp task adapts without a missing twin.""" @@ -86,3 +89,16 @@ def test_stable_cfg_adapts_to_warp(task_id: str, cfg_entry_point: str): cfg.sim.physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) # Raises FrontendIncompatibleError if any warp-managed term lacks a warp twin. adapt_cfg_for_warp(cfg) + + # Action terms carry a ``class_type`` (not a ``func``) and live on a base that + # is not a ManagerTermBaseCfg; guard that the adapter still swaps them to the + # warp ActionTerm, otherwise the warp ActionManager rejects them at runtime. + actions = getattr(cfg, "actions", None) + if actions is not None: + for name, term in vars(actions).items(): + class_type = getattr(term, "class_type", None) + if class_type is not None: + assert class_type.__module__.startswith(_WARP_ROOTS), ( + f"{task_id}: action term '{name}' class_type was not swapped to a warp twin" + f" (got {class_type.__module__}.{class_type.__name__})" + ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py index fd5463ad023f..1ebde1b42bbd 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py @@ -32,9 +32,9 @@ kwargs={ "env_cfg_entry_point": f"{_stable_pkg}.cartpole_manager_env_cfg:CartpoleEnvCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_manager_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_manager_ppo_cfg:CartpolePPORunnerCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpolePPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_manager_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_manager_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", }, ) @@ -46,8 +46,8 @@ kwargs={ "env_cfg_entry_point": f"{__name__}.cartpole_warp_env_cfg:CartpoleWarpEnvCfg", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_direct_ppo_cfg:CartpolePPORunnerCfg", + "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpoleDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_direct_ppo_cfg.yaml", + "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", }, ) From d587a49a1bbf00ef86e8334c925a08bd6025d0e1 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Fri, 5 Jun 2026 00:57:22 +0000 Subject: [PATCH 21/36] Treat events as warp-managed; make survival_success_rate graph-safe The warp EventManager invokes term funcs with a Warp env-mask, so a stable event func breaks at runtime (torch index by wp.array). Add events to the warp-managed groups so their funcs are swapped to warp twins; only curriculum, recorder and command managers fall back to stable. Cartpole (reset_joints_by_offset) and reach now adapt and cartpole trains end-to-end on warp. Rewrite cartpole survival_success_rate as a plain zero-reward term func: its stable form logs a metric on reset via a host readback, which is incompatible with the reward manager's CUDA-graph-captured reset; the warp twin keeps the zero reward and omits the diagnostic metric. Velocity tasks remain xfail in the conversion test pending warp twins for randomize_rigid_body_mass / randomize_rigid_body_material (domain randomization). --- .../isaaclab_experimental/envs/frontend.py | 14 ++++---- .../test/envs/test_frontend.py | 19 +++++++--- .../test/envs/test_frontend_cfg_conversion.py | 24 +++++++------ .../core/cartpole/mdp/rewards.py | 35 +++++-------------- 4 files changed, 46 insertions(+), 46 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index f2d379ece46a..a3882949d826 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -77,12 +77,14 @@ class FrontendIncompatibleError(RuntimeError): _WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") # Top-level cfg groups whose managers run warp-first. Only terms under these are -# adapted (SceneEntityCfg promotion + MDP twin swap); the event, curriculum, -# recorder and command managers run on the stable (torch) implementation, so -# their stable funcs/SceneEntityCfgs are left untouched. A stable term left on a -# warp manager would break, so a missing twin in these groups is a hard error; -# a stable term on a stable manager is correct, so those groups are skipped. -_WARP_MANAGED_GROUPS: frozenset[str] = frozenset({"observations", "rewards", "terminations", "actions"}) +# adapted (SceneEntityCfg promotion + MDP twin swap). The event manager is +# warp-first too — it invokes term funcs with a Warp env-mask, so a stable event +# func (which expects torch ``env_ids``) breaks at runtime; its funcs must be +# swapped to warp twins. The curriculum, recorder and command managers run on the +# stable (torch) implementation, so their terms are left untouched. A stable term +# left on a warp manager would break, so a missing twin in these groups is a hard +# error; a stable term on a stable manager is correct, so those groups are skipped. +_WARP_MANAGED_GROUPS: frozenset[str] = frozenset({"observations", "rewards", "terminations", "actions", "events"}) def build( diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index bd43f3c42611..5ba58490c385 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -206,11 +206,17 @@ class _EventsCfg: e1: EventTermCfg | None = None +@configclass +class _CurriculumCfg: + c1: EventTermCfg | None = None + + @configclass class _CfgFixture: observations: _ObservationsCfg | None = None rewards: _RewardsCfg | None = None events: _EventsCfg | None = None + curriculum: _CurriculumCfg | None = None def _term(func=None, params: dict | None = None) -> RewardTermCfg: @@ -311,18 +317,23 @@ def test_walks_all_term_groups(self): o3=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-per")}) ), ), + curriculum=_CurriculumCfg( + c1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="c")}) + ), ) _promote_scene_entity_cfgs(cfg) - # Warp-managed groups (rewards, observations incl. sub-groups) are promoted. + # Warp-managed groups (rewards, observations incl. sub-groups, events) are promoted. self.assertIsInstance(cfg.rewards.r1.params["asset_cfg"], WarpSceneEntityCfg) self.assertIsInstance(cfg.observations.policy.o1.params["asset_cfg"], WarpSceneEntityCfg) # The perception sub-group is reached even though its attribute name is # not hardcoded in the framework. self.assertIsInstance(cfg.observations.perception.o3.params["asset_cfg"], WarpSceneEntityCfg) - # Events run on the stable (torch) manager, so their SceneEntityCfg is + # The event manager is warp-first, so its terms are promoted too. + self.assertIsInstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) + # Curriculum runs on the stable (torch) manager, so its SceneEntityCfg is # left untouched — promoting it would hand a warp variant to a torch manager. - self.assertIsInstance(cfg.events.e1.params["asset_cfg"], StableSceneEntityCfg) - self.assertNotIsInstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) + self.assertIsInstance(cfg.curriculum.c1.params["asset_cfg"], StableSceneEntityCfg) + self.assertNotIsInstance(cfg.curriculum.c1.params["asset_cfg"], WarpSceneEntityCfg) # ====================================================================== diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 934542d5d525..6d0bdba4166e 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -53,21 +53,25 @@ def _instantiate_cfg(cfg_entry_point: str): _MANAGER_WARP_TASKS = _manager_warp_tasks() -# Tasks whose stable cfg still includes a warp-managed term with no warp twin. -# These are tracked for implementation; delete the entry once the twin lands -# (xfail is strict, so an unexpected pass fails the suite and flags the cleanup). -_PENDING_WARP_TWINS: dict[str, str] = {} + +def _pending_reason(task_id: str) -> str | None: + """Reason a task's cfg cannot yet fully adapt, or ``None`` if it should pass. + + Tracked for implementation; remove an entry once its warp twin lands (xfail is + strict, so an unexpected pass fails the suite and flags the cleanup). + """ + # Velocity locomotion tasks randomize body mass + material in their event terms, + # which have no warp twins yet (would need Newton articulation mass/material setters). + if task_id.startswith("Isaac-Velocity-"): + return "pending warp event twins: randomize_rigid_body_mass / randomize_rigid_body_material" + return None def _params(): cases = [] for task_id, cfg_entry_point in _MANAGER_WARP_TASKS: - marks = () - if task_id in _PENDING_WARP_TWINS: - marks = pytest.mark.xfail( - strict=True, - reason=f"pending warp twin for {_PENDING_WARP_TWINS[task_id]}", - ) + reason = _pending_reason(task_id) + marks = pytest.mark.xfail(strict=True, reason=reason) if reason else () cases.append(pytest.param(task_id, cfg_entry_point, marks=marks, id=task_id)) return cases diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py index ced0dadaad91..7830edabbae1 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py @@ -9,12 +9,9 @@ import warp as wp from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers.manager_base import ManagerTermBase from isaaclab_experimental.utils.warp.utils import wrap_to_pi if TYPE_CHECKING: - from isaaclab_experimental.managers.manager_term_cfg import RewardTermCfg - from isaaclab.assets import Articulation from isaaclab.envs import ManagerBasedRLEnv @@ -48,28 +45,14 @@ def joint_pos_target_l2(env: ManagerBasedRLEnv, out, target: float, asset_cfg: S ) -class survival_success_rate(ManagerTermBase): - """Logs the mean time-out (survival) rate of the resetting envs; contributes zero reward. +def survival_success_rate(env: ManagerBasedRLEnv, out) -> None: + """Zero-reward placeholder mirroring the stable ``survival_success_rate`` term. - Mirrors the stable term: the reward value is always zero (so it is registered with - ``weight=0.0``) and the only effect is logging ``Metrics/success_rate`` on reset, where - success is defined as the episode ending by time-out rather than an early termination. + The stable term contributes zero reward (registered with ``weight=0.0``) and its only + effect is logging ``Metrics/success_rate`` on reset. That logging needs a host readback + of the time-out mask, which is incompatible with the warp reward manager's + CUDA-graph-captured reset, so the warp twin keeps the zero reward and omits the diagnostic + metric. Implemented as a plain term func (not a :class:`ManagerTermBase`) since there is no + graph-safe per-reset state to maintain. """ - - def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): - super().__init__(cfg, env) - - def reset(self, env_mask: wp.array | None = None) -> None: - # ``time_outs`` is exposed as a torch tensor by the warp termination manager. - time_outs = self._env.termination_manager.time_outs - if env_mask is None: - survived = time_outs.float().mean() - else: - selected = time_outs[wp.to_torch(env_mask).bool()] - survived = selected.float().mean() if selected.numel() > 0 else time_outs.new_zeros(()) - self._env.extras.setdefault("log", {})["Metrics/success_rate"] = float(survived.item()) - - def __call__(self, env: ManagerBasedRLEnv, out) -> None: - # Pure logging term: the reward contribution is zero. The reward manager pre-zeroes - # ``out`` each step, but zero it explicitly so the term is correct independent of that. - out.zero_() + out.zero_() From 855588fda941b857759c445bb00428c906a7ea61 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Tue, 9 Jun 2026 06:17:11 +0000 Subject: [PATCH 22/36] Align warp env ids with develop torch names after cleanup renames Develop's task-cleanup PRs dropped the -v0 suffix from the core Ant, Humanoid, and Reach-Franka torch ids. The warp variants follow a fixed pattern (torch id with -Warp inserted before any -Play/-v0 suffix), so sync the six affected registrations and their doc references: Isaac-Ant-Warp-v0 -> Isaac-Ant-Warp Isaac-Ant-Direct-Warp-v0 -> Isaac-Ant-Direct-Warp Isaac-Humanoid-Warp-v0 -> Isaac-Humanoid-Warp Isaac-Humanoid-Direct-Warp-v0 -> Isaac-Humanoid-Direct-Warp Isaac-Reach-Franka-Warp-v0 -> Isaac-Reach-Franka-Warp Isaac-Reach-Franka-Warp-Play-v0 -> Isaac-Reach-Franka-Warp-Play Cartpole already conformed; contrib and core-velocity tasks kept -v0 upstream, so their warp ids are unchanged. --- .../physical-backends/newton/warp-environments.rst | 10 +++++----- docs/source/overview/environments.rst | 6 +++--- .../isaaclab_tasks_experimental/core/__init__.py | 12 ++++++++++++ .../core/direct_ant/__init__.py | 2 +- .../core/direct_humanoid/__init__.py | 2 +- .../core/manager_ant/__init__.py | 2 +- .../core/manager_humanoid/__init__.py | 2 +- .../core/reach/config/franka/__init__.py | 4 ++-- 8 files changed, 26 insertions(+), 14 deletions(-) create mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index 94a2dad20c87..86068a232bcb 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -32,8 +32,8 @@ Direct Warp Environments ^^^^^^^^^^^^^^^^^^^^^^^^ - ``Isaac-Cartpole-Direct-Warp-v0`` — Cartpole balance -- ``Isaac-Ant-Direct-Warp-v0`` — Ant locomotion -- ``Isaac-Humanoid-Direct-Warp-v0`` — Humanoid locomotion +- ``Isaac-Ant-Direct-Warp`` — Ant locomotion +- ``Isaac-Humanoid-Direct-Warp`` — Humanoid locomotion - ``Isaac-Repose-Cube-Allegro-Direct-Warp-v0`` — Allegro hand cube repose @@ -43,8 +43,8 @@ Manager-Based Warp Environments **Classic** - ``Isaac-Cartpole-Warp-v0`` -- ``Isaac-Ant-Warp-v0`` -- ``Isaac-Humanoid-Warp-v0`` +- ``Isaac-Ant-Warp`` +- ``Isaac-Humanoid-Warp`` **Locomotion (Flat)** @@ -61,7 +61,7 @@ Manager-Based Warp Environments **Manipulation** -- ``Isaac-Reach-Franka-Warp-v0`` +- ``Isaac-Reach-Franka-Warp`` - ``Isaac-Reach-UR10-Warp-v0`` diff --git a/docs/source/overview/environments.rst b/docs/source/overview/environments.rst index 08ca2372f504..0b4eac1144b0 100644 --- a/docs/source/overview/environments.rst +++ b/docs/source/overview/environments.rst @@ -857,7 +857,7 @@ inferencing, including reading from an already trained checkpoint and disabling - **Workflow** - **RL Library** - **Presets** - * - Isaac-Ant-Direct-Warp-v0 + * - Isaac-Ant-Direct-Warp - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) @@ -867,7 +867,7 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Ant-Warp-v0 + * - Isaac-Ant-Warp - - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) @@ -1055,7 +1055,7 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **skrl** (AMP) - - * - Isaac-Humanoid-Direct-Warp-v0 + * - Isaac-Humanoid-Direct-Warp - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py new file mode 100644 index 000000000000..5491e12e3855 --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py @@ -0,0 +1,12 @@ +# 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 + +"""Warp entry points for the core task families. + +Mirrors the ``isaaclab_tasks.core`` layout. Manager-based tasks register +``*-Warp-v0`` ids that reuse the stable env cfgs (adapted to the warp runtime at +construction); direct tasks register their own warp env classes here. Task +definitions (cfgs) live in ``isaaclab_tasks`` to avoid duplication. +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/__init__.py index 33d5ac926387..79106ae272bd 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_ant/__init__.py @@ -16,7 +16,7 @@ stable_agents = "isaaclab_tasks.core.locomotion.ant.agents" gym.register( - id="Isaac-Ant-Direct-Warp-v0", + id="Isaac-Ant-Direct-Warp", entry_point=f"{__name__}.ant_env_warp:AntWarpEnv", disable_env_checker=True, kwargs={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/__init__.py index c38d7dd955e5..a9ab94d9f4ac 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/direct_humanoid/__init__.py @@ -16,7 +16,7 @@ stable_agents = "isaaclab_tasks.core.locomotion.humanoid.agents" gym.register( - id="Isaac-Humanoid-Direct-Warp-v0", + id="Isaac-Humanoid-Direct-Warp", entry_point=f"{__name__}.humanoid_warp_env:HumanoidWarpEnv", disable_env_checker=True, kwargs={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py index 76a22111d486..a55544cb793d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_ant/__init__.py @@ -21,7 +21,7 @@ ## gym.register( - id="Isaac-Ant-Warp-v0", + id="Isaac-Ant-Warp", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py index 537d2a9aceaf..ebf7f2909a9e 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/manager_humanoid/__init__.py @@ -21,7 +21,7 @@ ## gym.register( - id="Isaac-Humanoid-Warp-v0", + id="Isaac-Humanoid-Warp", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py index a82f977588fd..b94ba1315fdc 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/config/franka/__init__.py @@ -21,7 +21,7 @@ ## gym.register( - id="Isaac-Reach-Franka-Warp-v0", + id="Isaac-Reach-Franka-Warp", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ @@ -33,7 +33,7 @@ ) gym.register( - id="Isaac-Reach-Franka-Warp-Play-v0", + id="Isaac-Reach-Franka-Warp-Play", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", disable_env_checker=True, kwargs={ From b6341271983ae633fbc663e79da3321d69d52eae Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 15 Jul 2026 17:28:20 -0700 Subject: [PATCH 23/36] Register --frontend in the shared RL training CLI Define the flag once in add_common_train_args so every RL library's train and benchmark entrypoint exposes it, instead of registering it per-script for RSL-RL only. create_isaaclab_env now reads the argument directly, so a caller that misses the shared registration fails loudly rather than silently defaulting to the torch runtime. Also drop the frontend dispatch from the deprecated rsl_rl/train.py wrapper; deprecated entrypoints should not grow new features. --- scripts/reinforcement_learning/common.py | 14 ++++++- .../reinforcement_learning/rsl_rl/train.py | 38 +------------------ .../rsl_rl/train_rsl_rl.py | 10 ----- .../test_reinforcement_learning_common.py | 13 ++++++- .../changelog.d/warp-manager-bridge.rst | 5 ++- 5 files changed, 30 insertions(+), 50 deletions(-) diff --git a/scripts/reinforcement_learning/common.py b/scripts/reinforcement_learning/common.py index 8edc124b469b..a36b5ac9266b 100644 --- a/scripts/reinforcement_learning/common.py +++ b/scripts/reinforcement_learning/common.py @@ -257,6 +257,18 @@ def add_common_train_args( ) parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") + parser.add_argument( + "--frontend", + type=str, + choices=["torch", "warp"], + default="torch", + help=( + "Runtime that constructs the environment. 'torch' uses the registered stable environment via" + " gym.make. 'warp' (experimental) adapts a manager-based task config onto the Warp runtime, or" + " dispatches a direct task to its registered Warp environment; requires isaaclab_experimental" + " and `presets=newton_mjwarp`." + ), + ) if include_agent: parser.add_argument("--agent", type=str, default=agent_default, help=agent_help) parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") @@ -415,7 +427,7 @@ def create_isaaclab_env( The created Gymnasium environment. """ render_mode = "rgb_array" if args_cli.video else None - frontend = getattr(args_cli, "frontend", "torch") + frontend = args_cli.frontend if frontend == "torch": env = gym.make(task, cfg=env_cfg, render_mode=render_mode) else: diff --git a/scripts/reinforcement_learning/rsl_rl/train.py b/scripts/reinforcement_learning/rsl_rl/train.py index a494e375f470..c9be857d41f5 100644 --- a/scripts/reinforcement_learning/rsl_rl/train.py +++ b/scripts/reinforcement_learning/rsl_rl/train.py @@ -79,19 +79,6 @@ "--ray-proc-id", "-rid", type=int, default=None, help="Automatically configured by Ray integration, otherwise None." ) parser.add_argument("--external_callback", default=None, help="Fully qualified path to an externally defined callback.") -parser.add_argument( - "--frontend", - type=str, - default="torch", - choices=["torch", "warp"], - help=( - "Runtime backend for the env. 'torch' uses isaaclab.envs.* (PhysX or Newton via" - " factory dispatch); 'warp' routes through the WarpFrontend, which adapts a" - " manager-based cfg onto ManagerBasedRLEnvWarp or dispatches a direct task to its" - " registered warp env class. See isaaclab_experimental.envs.frontend for the" - " pluggable rule pipeline." - ), -) cli_args.add_rsl_rl_args(parser) add_launcher_args(parser) args_cli, remaining_args = setup_preset_cli(parser) @@ -113,22 +100,6 @@ # intersection share the same token vocabulary (the callback reads the user's # original sys.argv), so preset tokens like ``physics=NAME`` compare correctly. remaining_args = list_intersection(remaining_args, remaining_args_env_registration) - -# Build path for ``--frontend=warp`` lives in ``isaaclab_experimental``, which is an -# optional package — torch (the default) must still work without it, so import lazily. -# Warp callers are required to pass ``presets=newton_mjwarp`` themselves; the frontend hard-checks -# it at build time rather than mutating Hydra args here. -_frontend_build = None -try: - from isaaclab_experimental.envs.frontend import build as _frontend_build # noqa: E402 -except ImportError as _frontend_import_err: - if args_cli.frontend != "torch": - raise SystemExit( - f"--frontend={args_cli.frontend} requires isaaclab_experimental to be installed," - f" but the import failed: {_frontend_import_err}" - ) from _frontend_import_err - logger.info("isaaclab_experimental not available; --frontend=torch will dispatch via plain gym.make.") - sys.argv = [sys.argv[0]] + remaining_args # -- check RSL-RL version ---------------------------------------------------- @@ -213,13 +184,8 @@ def main(env_cfg: ManagerBasedRLEnvCfg | DirectRLEnvCfg | DirectMARLEnvCfg, agen # set the log directory for the environment (works for all environment types) env_cfg.log_dir = log_dir - # Build the env via the selected frontend. Warp adapts env_cfg in place; - # missing warp twins are a hard failure. - render_mode = "rgb_array" if args_cli.video else None - if _frontend_build is not None: - env = _frontend_build(args_cli.frontend, env_cfg, args_cli.task, render_mode=render_mode) - else: - env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render_mode) + # create isaac environment + env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None) # convert to single-agent instance if required by the RL algorithm if isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): diff --git a/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py b/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py index 670da05b7f97..8f5c797cad40 100644 --- a/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py +++ b/scripts/reinforcement_learning/rsl_rl/train_rsl_rl.py @@ -82,16 +82,6 @@ def _parse_args(argv: list[str]) -> argparse.Namespace: default=None, help="Fully qualified path to an externally defined callback.", ) - parser.add_argument( - "--frontend", - choices=["torch", "warp"], - default="torch", - help=( - "Environment runtime. 'torch' uses the registered stable environment; " - "'warp' adapts a manager-based config to ManagerBasedRLEnvWarp or requires " - "a registered Warp environment for direct tasks." - ), - ) CLI_ARGS.add_rsl_rl_args(parser) add_isaaclab_launcher_args(parser) # setup_preset_cli registers preset-selection help text + runs parse_known_args diff --git a/source/isaaclab/test/test_reinforcement_learning_common.py b/source/isaaclab/test/test_reinforcement_learning_common.py index 9b3a5f3836ac..9de4173bd8f7 100644 --- a/source/isaaclab/test/test_reinforcement_learning_common.py +++ b/source/isaaclab/test/test_reinforcement_learning_common.py @@ -221,6 +221,17 @@ def test_enable_cameras_for_video_enables_cameras_for_sensor_capture() -> None: assert args_cli.enable_cameras +def test_common_train_args_register_frontend_with_torch_default() -> None: + """Every RL library CLI exposes ``--frontend`` and defaults to the torch runtime.""" + parser = argparse.ArgumentParser() + add_common_train_args(parser, agent_default=None, agent_help="", include_agent=False) + + assert parser.parse_args([]).frontend == "torch" + assert parser.parse_args(["--frontend", "warp"]).frontend == "warp" + with pytest.raises(SystemExit): + parser.parse_args(["--frontend", "tensorflow"]) + + def test_create_isaaclab_env_uses_registered_torch_env_by_default(monkeypatch: pytest.MonkeyPatch) -> None: """The shared factory preserves the existing Gym path when no frontend is selected.""" expected_env = object() @@ -232,7 +243,7 @@ def fake_make(task: str, **kwargs: Any) -> Any: return expected_env monkeypatch.setattr(_rl_common.gym, "make", fake_make) - args_cli = argparse.Namespace(video=False) + args_cli = argparse.Namespace(video=False, frontend="torch") env = create_isaaclab_env("Isaac-Test", env_cfg, args_cli, convert_marl_to_single_agent=False) diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index a645acf116ca..4b3996529ba8 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -1,8 +1,9 @@ Added ^^^^^ -* Added ``--frontend {torch,warp}`` to the RSL-RL training entrypoint for - selecting the environment runtime; default ``torch`` is unchanged. +* Added ``--frontend {torch,warp}`` to the shared reinforcement-learning + training CLI (all supported RL libraries) for selecting the environment + runtime; default ``torch`` is unchanged. * Added :mod:`isaaclab_experimental.envs.frontend` runtime selector and :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable` used by ``--frontend=warp`` to adapt stable cfgs onto the warp runtime. From 826779f328a30c8932c0eacb83a0386a59633149 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 15 Jul 2026 17:34:39 -0700 Subject: [PATCH 24/36] Report success-rate metric from the Warp Cartpole reward twin The Warp survival_success_rate twin wrote zeros and dropped the Metrics/success_rate value that the stable class-based term flushes into extras on reset, so torch and warp runs of the same task were not comparable on the success metric. Rebuild the twin as a Warp ManagerTermBase class that accumulates the timed-out fraction of just-reset envs in device buffers and exposes it as a persistent tensor view through the reward manager's reset extras. Class reward terms may now return such views from reset(); the reward manager merges them, which keeps the whole reset stage CUDA-graph capturable (no host readback). --- .../managers/manager_base.py | 12 ++- .../managers/reward_manager.py | 9 ++- .../changelog.d/warp-manager-bridge.rst | 3 + .../classic/cartpole/mdp/rewards.py | 73 +++++++++++++++++-- 4 files changed, 85 insertions(+), 12 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py index 699e27170e02..7954800d87c9 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py @@ -37,6 +37,8 @@ if TYPE_CHECKING: + import torch + from isaaclab.envs import ManagerBasedEnv # import logger @@ -107,14 +109,20 @@ def __name__(self) -> str: Operations. """ - def reset(self, env_mask: wp.array | None = None) -> None: + def reset(self, env_mask: wp.array | None = None) -> dict[str, torch.Tensor] | None: """Resets the manager term (mask-based). Args: env_mask: Boolean mask of shape (num_envs,) indicating which envs to reset. If None, all envs are considered. + + Returns: + An optional dictionary of logging values to merge into the owning manager's + reset extras. To stay CUDA-graph capturable, values must be persistent + tensor views over device buffers written by kernels (no host readback); + the same objects must be returned on every call. """ - pass + return None def serialize(self) -> dict: """General serialization call. Includes the configuration dict.""" diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py b/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py index 99e3d9af979c..7dd6b85bd6ed 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/reward_manager.py @@ -272,9 +272,14 @@ def reset( device=self.device, ) - # reset all the reward terms + # reset all the reward terms; class terms may expose logging values as + # persistent tensor views (see :meth:`ManagerTermBase.reset`), which are + # merged into the manager's reset extras. Merging the same views again on + # subsequent resets is a no-op, so this stays capture-safe. for term_cfg in self._class_term_cfgs: - term_cfg.func.reset(env_mask=env_mask) + term_extras = term_cfg.func.reset(env_mask=env_mask) + if term_extras: + self._reset_extras.update(term_extras) return self._reset_extras diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst index 86ae1af09452..4ac20a99187a 100644 --- a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst @@ -3,3 +3,6 @@ Fixed * Fixed the direct Warp Cartpole task to match the stable task's observations, reset ranges, termination condition, reward scaling, and scene configuration. +* Fixed the Warp Cartpole ``survival_success_rate`` twin to report the + ``Metrics/success_rate`` value on-device instead of silently dropping the + metric. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py index b54267ac5ea8..6049af38ad78 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py @@ -8,12 +8,15 @@ from typing import TYPE_CHECKING import warp as wp -from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab_experimental.managers import ManagerTermBase, SceneEntityCfg from isaaclab_experimental.utils.warp.utils import wrap_to_pi if TYPE_CHECKING: + import torch + from isaaclab.assets import Articulation from isaaclab.envs import ManagerBasedRLEnv + from isaaclab.managers import RewardTermCfg @wp.kernel @@ -45,12 +48,66 @@ def joint_pos_target_l2(env: ManagerBasedRLEnv, out, target: float, asset_cfg: S ) -def survival_success_rate(env: ManagerBasedRLEnv, out) -> None: - """Write a zero reward for the stable Cartpole success-rate metric term. +@wp.kernel +def _survival_counts_kernel( + env_mask: wp.array(dtype=wp.bool), + time_outs: wp.array(dtype=wp.bool), + counts: wp.array(dtype=wp.int32), +): + env_index = wp.tid() + if env_mask[env_index]: + wp.atomic_add(counts, 0, 1) + if time_outs[env_index]: + wp.atomic_add(counts, 1, 1) + + +@wp.kernel +def _survival_rate_kernel( + counts: wp.array(dtype=wp.int32), + success_rate: wp.array(dtype=wp.float32), +): + if counts[0] > 0: + success_rate[0] = wp.float32(counts[1]) / wp.float32(counts[0]) + else: + success_rate[0] = 0.0 + + +class survival_success_rate(ManagerTermBase): + """Tracks episode survival as the success metric (Warp-first). - The stable term logs the episode survival rate during reset. That logging - requires a host readback of the time-out mask and is not compatible with - the Warp reward manager's CUDA-graph-captured reset. This twin preserves - the term's zero reward without performing the diagnostic readback. + Twin of :class:`isaaclab_tasks.core.cartpole.mdp.rewards.survival_success_rate`. + Returns zero reward (pure metric tracking). On reset, computes the fraction of + just-reset environments that timed out (survived the full episode) entirely + on-device and exposes it as ``Metrics/success_rate`` through the reward + manager's reset extras. Unlike the stable term, there is no host readback, so + the computation stays CUDA-graph capturable. """ - out.zero_() + + def __init__(self, cfg: RewardTermCfg, env: ManagerBasedRLEnv): + super().__init__(cfg, env) + # [0] number of just-reset envs, [1] number of those that timed out + self._counts_wp = wp.zeros((2,), dtype=wp.int32, device=env.device) + self._success_rate_wp = wp.zeros((1,), dtype=wp.float32, device=env.device) + # persistent 0-dim tensor view: kernels refresh the value on every reset/replay + self._reset_extras = {"Metrics/success_rate": wp.to_torch(self._success_rate_wp)[0]} + + def reset(self, env_mask: wp.array | None = None) -> dict[str, torch.Tensor]: + if env_mask is None: + env_mask = self._env.resolve_env_mask() + self._counts_wp.zero_() + wp.launch( + kernel=_survival_counts_kernel, + dim=self.num_envs, + inputs=[env_mask, self._env.termination_manager.time_outs_wp, self._counts_wp], + device=self.device, + ) + wp.launch( + kernel=_survival_rate_kernel, + dim=1, + inputs=[self._counts_wp, self._success_rate_wp], + device=self.device, + ) + return self._reset_extras + + def __call__(self, env: ManagerBasedRLEnv, out: wp.array) -> None: + out.zero_() From ac01de7e48bf54fdfda75a938cc74b98991d6d3b Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 15 Jul 2026 17:52:08 -0700 Subject: [PATCH 25/36] Resolve warp MDP twins through registered task routes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace the frontend's hardcoded stable-to-experimental module table with a registry that experimental task packages populate at import time via register_mdp_route(), so adding a task family no longer requires editing the frontend module. Twin lookup previously keyed only off the symbol's defining module, which missed every twin that overrides a symbol defined in a core or shared package: the stable reach rewards live in isaaclab.envs.mdp and the humanoid observations in the shared locomotion package, so their task-specific warp twins were never consulted and the stable Humanoid, Ant, and Reach tasks could not adapt at all. Resolution now consults the warp mirror of the cfg's own task MDP namespace first (routed from the cfg class hierarchy), then the mirror of the symbol's package, then the shared fallback — mirroring how a stable cfg consumes its mdp namespace. This makes the stable Ant, Humanoid, and Reach joint-pos tasks adapt cleanly under --frontend=warp. Also convert test_frontend.py to pytest style and cover the new registry (longest-prefix match, conflict rejection, broken-target error, cfg-hierarchy resolution). --- .../isaaclab_experimental/envs/frontend.py | 244 +++--- .../test/envs/test_frontend.py | 727 +++++++++--------- .../manager_based/classic/ant/__init__.py | 9 + .../classic/cartpole/__init__.py | 5 + .../classic/humanoid/__init__.py | 6 + .../locomotion/velocity/__init__.py | 5 + .../manipulation/reach/__init__.py | 5 + 7 files changed, 564 insertions(+), 437 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 0af62048df02..780685198e7c 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -41,6 +41,7 @@ "Workflow", "adapt_cfg_for_warp", "build", + "register_mdp_route", ] @@ -76,29 +77,54 @@ class FrontendIncompatibleError(RuntimeError): # the warp packages. Used by the direct-workflow guard. _WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") -# Stable task MDP packages and their Warp-first counterparts. The stable task -# package is organized by public task domain while the experimental package -# separates manager-based workflows by family, so the module trees are not -# one-to-one. Keep the routing at the package boundary and preserve any -# submodule suffix (for example, ``.rewards``). -_WARP_MDP_MODULE_ROUTES: tuple[tuple[str, str], ...] = ( - ( - "isaaclab_tasks.core.cartpole.mdp", - "isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp", - ), - ( - "isaaclab_tasks.core.locomotion.humanoid.mdp", - "isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp", - ), - ( - "isaaclab_tasks.core.velocity.mdp", - "isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp", - ), - ( - "isaaclab_tasks.core.reach.mdp", - "isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp", - ), -) +# Stable package prefixes mapped to the warp MDP module that twins their terms. +# The stable task package is organized by public task domain while the +# experimental package separates manager-based workflows by family, so the +# module trees are not one-to-one. The registry is populated by the experimental +# task packages themselves via :func:`register_mdp_route` at import time, so +# adding a new task family never requires editing this module. +_WARP_MDP_MODULE_ROUTES: dict[str, str] = {} + +# Root package that provides task-specific warp MDP twins. Imported (lazily, at +# swap time) so its task packages run their register_mdp_route() calls even when +# the caller only imported the stable task package. +_TWIN_PROVIDER_PACKAGE = "isaaclab_tasks_experimental" + + +def register_mdp_route(stable_package: str, warp_mdp_module: str) -> None: + """Register the warp MDP module that twins a stable package's terms. + + Experimental task packages call this at import time to declare where the + warp twins of a stable task's MDP terms live. :func:`_swap_mdp` consults + the registry to resolve task-specific twins for ``--frontend=warp``. Twin + lookup is by symbol name on ``warp_mdp_module`` itself, mirroring how a + stable cfg consumes its ``mdp`` namespace — so the module should re-export + everything the task needs (task-specific twins plus the generic forwards). + + Two kinds of keys are useful: + + * A *task package* (e.g. ``"isaaclab_tasks.core.reach"``) routes every cfg + class defined under it. This also covers terms whose stable functions are + defined in core/shared packages but overridden by task-specific twins. + * An *MDP package* (e.g. ``"isaaclab_tasks.core.locomotion.humanoid.mdp"``) + routes symbols *defined* under it, which serves other tasks that borrow + those terms. + + Args: + stable_package: Stable package prefix to route (longest match wins). + warp_mdp_module: Warp MDP module providing the twins, e.g. + ``"isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp"``. + + Raises: + ValueError: If ``stable_package`` is already routed to a different module. + """ + existing = _WARP_MDP_MODULE_ROUTES.get(stable_package) + if existing is not None and existing != warp_mdp_module: + raise ValueError( + f"MDP route conflict for {stable_package!r}: already routed to {existing!r}, got {warp_mdp_module!r}." + ) + _WARP_MDP_MODULE_ROUTES[stable_package] = warp_mdp_module + # Top-level cfg groups whose managers run warp-first. Only terms under these are # adapted (SceneEntityCfg promotion + MDP twin swap). The event manager is @@ -248,23 +274,26 @@ def _swap_mdp(cfg: Any, label: str) -> None: Iterates every term cfg in the tree (via :func:`_walk_terms`) and on each term swaps whichever of ``func`` / ``class_type`` is a stable-origin - callable. Twin lookup is name-based against the warp mirror of the *stable - symbol's own module* (:func:`_warp_mdp_modules`) plus the - :mod:`isaaclab_experimental.envs.mdp` fallback. Keying off the symbol's - module — not the cfg's — means a task that borrows another task's MDP (e.g. - ``manager_ant`` reuses ``manager_humanoid.mdp``) resolves to the right warp - twins without a per-task shim, mirroring the stable ``core/`` layout. Any - missing twin raises :class:`FrontendIncompatibleError` listing every - affected term — partial swaps would leave torch-style callables in the cfg - and the warp managers would call them with the wrong signature. - - The warp-side side declarations (``out_dim``, ``axes``, ``observation_type``) + callable. Twin lookup is name-based, in the order given by + :func:`_twin_modules`: the warp mirror of the cfg's own task MDP namespace + first (task twins win, even for symbols defined in core packages), then the + mirror of the symbol's defining package (covers terms borrowed from another + task family, e.g. the Ant task reusing Humanoid MDP terms), then the shared + :mod:`isaaclab_experimental.envs.mdp` fallback. Any missing twin raises + :class:`FrontendIncompatibleError` listing every affected term — partial + swaps would leave torch-style callables in the cfg and the warp managers + would call them with the wrong signature. + + The warp-side declarations (``out_dim``, ``axes``, ``observation_type``) that the warp managers need at init are *not* supplied by this swap; they travel with the warp twin function itself via its own ``@generic_io_descriptor_warp(out_dim=…)`` decorator. This function only substitutes the callable; the manager reads the new func's annotations when it parses the term cfg. """ + _ensure_twin_providers_imported() + + cfg_route_modules = _cfg_route_modules(cfg) module_cache: dict[str, list[ModuleType]] = {} searched: set[str] = set() @@ -280,7 +309,7 @@ def _swap_mdp(cfg: Any, label: str) -> None: continue origin = getattr(stable, "__module__", "") or "" if origin not in module_cache: - module_cache[origin] = _warp_mdp_modules(origin) + module_cache[origin] = _twin_modules(origin, cfg_route_modules) searched.update(m.__name__ for m in module_cache[origin]) twin = _resolve_warp_twin(stable.__name__, module_cache[origin]) if twin is None: @@ -337,62 +366,94 @@ def _assert_direct_warp_registration(task_id: str) -> None: ) -def _warp_mdp_modules(symbol_module: str) -> list[ModuleType]: - """Locate warp MDP modules to consult for a stable symbol's twin. +def _match_route(module: str) -> str | None: + """Return the routed warp MDP module for ``module``, longest prefix wins.""" + if not isinstance(module, str) or not module: + return None + best_key: str | None = None + for stable_prefix in _WARP_MDP_MODULE_ROUTES: + if module == stable_prefix or module.startswith(f"{stable_prefix}."): + if best_key is None or len(stable_prefix) > len(best_key): + best_key = stable_prefix + return _WARP_MDP_MODULE_ROUTES[best_key] if best_key is not None else None + + +def _import_routed_module(target: str) -> ModuleType: + """Import a registered route target; a broken registration is a hard error.""" + try: + return importlib.import_module(target) + except ImportError as exc: + raise FrontendIncompatibleError(f"registered warp MDP route target {target!r} failed to import: {exc}") from exc - The lookup is keyed off the *stable symbol's own module* - (``func.__module__`` / ``class_type.__module__``), e.g. - ``isaaclab_tasks.core.locomotion.humanoid.mdp.rewards``. The stable module - is routed to its manager-based experimental counterpart, then walked up to - the nearest importable module. Keying off the symbol's module — not the - cfg's — resolves the right twins even when a task borrows another task's - MDP (the Ant task reuses Humanoid MDP terms). - Order of preference: +def _cfg_route_modules(cfg: Any) -> list[ModuleType]: + """Warp MDP modules routed from the cfg's class hierarchy, subclass first. - 1. The routed Warp counterpart of ``symbol_module`` (or its nearest importable ancestor, - e.g. the ``...mdp`` package when the exact submodule isn't mirrored). - 2. The shared :mod:`isaaclab_experimental.envs.mdp` fallback (where - generic warp twins live). + A stable cfg consumes terms through its task's ``mdp`` namespace, which + re-exports symbols that may be *defined* in core or shared packages. The + warp mirror of that namespace is therefore the primary place to resolve + twins, and it is found by routing the modules of ``type(cfg).__mro__`` — + the subclass module first (robot-specific cfgs), then base-cfg modules + (task-family bases). """ modules: list[ModuleType] = [] - warp_mod = _warp_mdp_module_name(symbol_module) - if warp_mod is not None: - parts = warp_mod.split(".") - for depth in range(len(parts), 0, -1): - target = ".".join(parts[:depth]) - try: - modules.append(importlib.import_module(target)) - break - except ModuleNotFoundError as exc: - # Keep walking up while the missing module is part of the path - # we're probing; a genuine import error inside an existing - # module (missing third-party dep, etc.) must surface. - if exc.name and warp_mod.startswith(exc.name): - continue - raise - # Generic fallback. + for klass in type(cfg).__mro__: + target = _match_route(getattr(klass, "__module__", "") or "") + if target is None: + continue + module = _import_routed_module(target) + if module not in modules: + modules.append(module) + return modules + + +def _twin_modules(symbol_module: str, cfg_route_modules: list[ModuleType]) -> list[ModuleType]: + """Warp modules to consult for a stable symbol's twin, in preference order. + + 1. The warp mirrors of the cfg's own task MDP namespace + (:func:`_cfg_route_modules`) — task-specific twins win, including twins + for symbols defined in core/shared packages. + 2. The warp mirror routed from the symbol's defining package — covers terms + borrowed from another task family's MDP package. + 3. The shared :mod:`isaaclab_experimental.envs.mdp` fallback (where generic + warp twins live). + """ + modules = list(cfg_route_modules) + target = _match_route(symbol_module) + if target is not None: + module = _import_routed_module(target) + if module not in modules: + modules.append(module) fallback = "isaaclab_experimental.envs.mdp" try: - modules.append(importlib.import_module(fallback)) + fallback_module = importlib.import_module(fallback) except ModuleNotFoundError as exc: - if exc.name == fallback: - logger.warning("frontend.warp: fallback mdp module %r not importable", fallback) - else: + if exc.name != fallback: raise + logger.warning("frontend.warp: fallback mdp module %r not importable", fallback) + else: + if fallback_module not in modules: + modules.append(fallback_module) return modules -def _warp_mdp_module_name(symbol_module: str) -> str | None: - """Return the routed experimental MDP module for a stable task symbol.""" - if not isinstance(symbol_module, str): - return None - for stable_prefix, warp_prefix in _WARP_MDP_MODULE_ROUTES: - if symbol_module == stable_prefix: - return warp_prefix - if symbol_module.startswith(f"{stable_prefix}."): - return f"{warp_prefix}{symbol_module[len(stable_prefix) :]}" - return None +def _ensure_twin_providers_imported() -> None: + """Import the twin-provider package so its MDP routes are registered. + + Route registration happens as an import side effect of the experimental + task packages. A caller running ``--frontend=warp`` on a stable task id + has no other reason to import :mod:`isaaclab_tasks_experimental`, so the + swap triggers it here. A missing provider package is not an error by + itself — the swap then fails with the explicit missing-twin report. + """ + try: + importlib.import_module(_TWIN_PROVIDER_PACKAGE) + except ModuleNotFoundError as exc: + # Only swallow "the provider package is not installed"; a genuine import + # error inside an existing package must surface. + if exc.name != _TWIN_PROVIDER_PACKAGE: + raise + logger.warning("frontend.warp: twin provider package %r is not installed", _TWIN_PROVIDER_PACKAGE) def _resolve_warp_twin(name: str, modules: Iterable[ModuleType]) -> Any | None: @@ -429,13 +490,20 @@ def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[s * Match (a term cfg instance): yield ``(path, node)`` and stop — do not descend into ``term.params`` / ``term.func`` / ``term.class_type``. - * Configclass: don't yield; recurse into every non-underscore attribute, - extending the path. ``observations``, ``rewards``, ``events``, ``actions``, - sub-groups like ``observations.policy`` / ``observations.perception``, and - anything nested deeper are reached transparently. + * Configclass: don't yield; recurse into every non-underscore *instance* + attribute (``vars(node)``), extending the path. ``observations``, + ``rewards``, ``events``, ``actions``, sub-groups like + ``observations.policy`` / ``observations.perception``, and anything + nested deeper are reached transparently. * Anything else (plain Python data, callables, non-configclass objects): stop. No yield, no recursion. + Iterating the instance ``__dict__`` mirrors how the warp managers consume + group cfgs (they iterate ``cfg.__dict__.items()``), so the walker sees + exactly the terms the managers will see — including terms assigned in + ``__post_init__`` — while never descending into methods or nested class + objects, which live on the class rather than the instance. + Driven entirely by type — no attribute names are hardcoded — so future cfg layouts (extra observation groups, new nesting, etc.) are picked up automatically as long as their terms subclass one of the term base cfgs. @@ -447,13 +515,7 @@ def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[s return if not hasattr(node, "__dataclass_fields__"): return - for name in dir(node): - if name.startswith("_"): - continue - try: - value = getattr(node, name, None) - except Exception: # noqa: BLE001 — defensive; some descriptors can raise on attribute access - continue - if value is None: + for name, value in vars(node).items(): + if name.startswith("_") or value is None: continue yield from _walk_terms(value, path + (name,)) diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index a7af62ee146e..03e39287e679 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -10,12 +10,13 @@ * :class:`Frontend` / :class:`Workflow` enum surface. * :func:`SceneEntityCfg.from_stable` field copy. * :func:`_require_newton_physics` hard-check. -* :func:`_walk_terms` recursive ManagerTermBaseCfg discovery. +* :func:`_walk_terms` recursive ManagerTermBaseCfg discovery over instance + attributes (nested class objects are not descended into). +* :func:`register_mdp_route` / :func:`_match_route` route registry. +* :func:`_cfg_route_modules` cfg-hierarchy route resolution. * :func:`_promote_scene_entity_cfgs` walks ``term.params`` dicts. * :func:`_swap_mdp` swaps ``func`` *and* ``class_type``; raises with a path list when twins are missing. -* :func:`_warp_mdp_module_name` routes stable task modules to the current - experimental manager-based package layout. * :func:`_resolve_warp_twin` rejects stable-origin re-exports. * :func:`_assert_direct_warp_registration` accepts warp-rooted entry points and rejects stable ones. @@ -23,25 +24,21 @@ from __future__ import annotations +import contextlib +import importlib import types -import unittest from typing import Any from unittest.mock import patch import gymnasium as gym +import isaaclab_experimental.envs.frontend as fe +import pytest from isaaclab_experimental.envs.frontend import ( Frontend, FrontendIncompatibleError, Workflow, - _assert_direct_warp_registration, - _is_swap_candidate, - _promote_scene_entity_cfgs, - _require_newton_physics, - _resolve_warp_twin, - _swap_mdp, - _walk_terms, - _warp_mdp_module_name, build, + register_mdp_route, ) from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as WarpSceneEntityCfg from isaaclab_newton.physics import NewtonCfg @@ -53,133 +50,13 @@ from isaaclab.utils.configclass import configclass # ====================================================================== -# Enums -# ====================================================================== - - -class TestEnums(unittest.TestCase): - def test_frontend_values(self): - self.assertEqual(Frontend.TORCH, "torch") - self.assertEqual(Frontend.WARP, "warp") - - def test_frontend_coercion(self): - self.assertIs(Frontend("torch"), Frontend.TORCH) - self.assertIs(Frontend("warp"), Frontend.WARP) - with self.assertRaises(ValueError): - Frontend("kit") - - def test_workflow_values(self): - self.assertEqual(Workflow.MANAGER_BASED, "manager_based") - self.assertEqual(Workflow.DIRECT, "direct") - - -class TestBuild(unittest.TestCase): - def test_warp_manager_build_adapts_cfg_before_construction(self): - import isaaclab_experimental.envs as envs - import isaaclab_experimental.envs.frontend as frontend_module - - cfg = object.__new__(ManagerBasedRLEnvCfg) - expected_env = object() - calls: list[tuple[str, Any]] = [] - - def fake_adapt(received_cfg: Any) -> None: - calls.append(("adapt", received_cfg)) - - def fake_env(*, cfg: Any, **kwargs: Any) -> Any: - calls.append(("construct", cfg)) - return expected_env - - with ( - patch.object(frontend_module, "adapt_cfg_for_warp", fake_adapt), - patch.object(envs, "ManagerBasedRLEnvWarp", fake_env), - ): - env = build("warp", cfg, "Isaac-Test") - - self.assertIs(env, expected_env) - self.assertEqual(calls, [("adapt", cfg), ("construct", cfg)]) - - -# ====================================================================== -# SceneEntityCfg.from_stable -# ====================================================================== - - -class TestFromStable(unittest.TestCase): - def test_copies_minimum_fields(self): - stable = StableSceneEntityCfg(name="robot") - warp = WarpSceneEntityCfg.from_stable(stable) - self.assertIsInstance(warp, WarpSceneEntityCfg) - self.assertEqual(warp.name, "robot") - # Warp-only fields stay None until :meth:`resolve` runs. - self.assertIsNone(warp.joint_mask) - self.assertIsNone(warp.joint_ids_wp) - self.assertIsNone(warp.body_ids_wp) - - def test_copies_all_selection_fields(self): - stable = StableSceneEntityCfg( - name="robot", - joint_names=["lf_hip"], - joint_ids=[0, 1, 2], - fixed_tendon_names=["tendon_a"], - fixed_tendon_ids=[5], - body_names=["base", "lf_foot"], - body_ids=[0, 4], - object_collection_names=["objs"], - object_collection_ids=[7], - preserve_order=True, - ) - warp = WarpSceneEntityCfg.from_stable(stable) - for field in ( - "name", - "joint_names", - "joint_ids", - "fixed_tendon_names", - "fixed_tendon_ids", - "body_names", - "body_ids", - "object_collection_names", - "object_collection_ids", - "preserve_order", - ): - self.assertEqual(getattr(warp, field), getattr(stable, field), msg=f"field {field!r} mismatch") - - -# ====================================================================== -# _require_newton_physics -# ====================================================================== - - -class TestRequireNewtonPhysics(unittest.TestCase): - def _cfg_with(self, physics: Any) -> Any: - cfg = types.SimpleNamespace() - cfg.sim = types.SimpleNamespace(physics=physics) - return cfg - - def test_passes_for_newton(self): - cfg = self._cfg_with(NewtonCfg()) - _require_newton_physics(cfg, "Isaac-Test-v0") # no raise - - def test_rejects_physx(self): - cfg = self._cfg_with(PhysxCfg()) - with self.assertRaises(FrontendIncompatibleError) as exc: - _require_newton_physics(cfg, "Isaac-Test-v0") - self.assertIn("presets=newton_mjwarp", str(exc.exception)) - self.assertIn("PhysxCfg", str(exc.exception)) - - def test_rejects_none(self): - cfg = self._cfg_with(None) - with self.assertRaises(FrontendIncompatibleError): - _require_newton_physics(cfg, "Isaac-Test-v0") - - -# ====================================================================== -# Configclass fixtures for the walker / swap tests. -# ====================================================================== +# Fixtures: fake stable/warp symbols and configclass trees. # # These mirror the real cfg shape so :func:`_walk_terms` descends into them # (it only descends into objects with ``__dataclass_fields__``). Term cfgs # use the real :class:`EventTermCfg`/:class:`RewardTermCfg`/:class:`ObservationTermCfg` # so the walker's ``isinstance(ManagerTermBaseCfg)`` discriminator yields them. +# ====================================================================== def _stable_func(env, **params): @@ -256,116 +133,246 @@ def _term(func=None, params: dict | None = None) -> RewardTermCfg: return RewardTermCfg(func=func or _stable_func, weight=1.0, params=params or {}) +@pytest.fixture +def fake_routes(monkeypatch: pytest.MonkeyPatch) -> dict[str, str]: + """Isolate the module-level route registry for a test.""" + routes: dict[str, str] = {} + monkeypatch.setattr(fe, "_WARP_MDP_MODULE_ROUTES", routes) + return routes + + +# ====================================================================== +# Enums +# ====================================================================== + + +def test_frontend_values(): + assert Frontend.TORCH == "torch" + assert Frontend.WARP == "warp" + + +def test_frontend_coercion(): + assert Frontend("torch") is Frontend.TORCH + assert Frontend("warp") is Frontend.WARP + with pytest.raises(ValueError): + Frontend("kit") + + +def test_workflow_values(): + assert Workflow.MANAGER_BASED == "manager_based" + assert Workflow.DIRECT == "direct" + + +# ====================================================================== +# build() +# ====================================================================== + + +def test_warp_manager_build_adapts_cfg_before_construction(): + import isaaclab_experimental.envs as envs + + cfg = object.__new__(ManagerBasedRLEnvCfg) + expected_env = object() + calls: list[tuple[str, Any]] = [] + + def fake_adapt(received_cfg: Any) -> None: + calls.append(("adapt", received_cfg)) + + def fake_env(*, cfg: Any, **kwargs: Any) -> Any: + calls.append(("construct", cfg)) + return expected_env + + with ( + patch.object(fe, "adapt_cfg_for_warp", fake_adapt), + patch.object(envs, "ManagerBasedRLEnvWarp", fake_env), + ): + env = build("warp", cfg, "Isaac-Test") + + assert env is expected_env + assert calls == [("adapt", cfg), ("construct", cfg)] + + +# ====================================================================== +# SceneEntityCfg.from_stable +# ====================================================================== + + +def test_from_stable_copies_minimum_fields(): + stable = StableSceneEntityCfg(name="robot") + warp = WarpSceneEntityCfg.from_stable(stable) + assert isinstance(warp, WarpSceneEntityCfg) + assert warp.name == "robot" + # Warp-only fields stay None until :meth:`resolve` runs. + assert warp.joint_mask is None + assert warp.joint_ids_wp is None + assert warp.body_ids_wp is None + + +def test_from_stable_copies_all_selection_fields(): + stable = StableSceneEntityCfg( + name="robot", + joint_names=["lf_hip"], + joint_ids=[0, 1, 2], + fixed_tendon_names=["tendon_a"], + fixed_tendon_ids=[5], + body_names=["base", "lf_foot"], + body_ids=[0, 4], + object_collection_names=["objs"], + object_collection_ids=[7], + preserve_order=True, + ) + warp = WarpSceneEntityCfg.from_stable(stable) + for field in ( + "name", + "joint_names", + "joint_ids", + "fixed_tendon_names", + "fixed_tendon_ids", + "body_names", + "body_ids", + "object_collection_names", + "object_collection_ids", + "preserve_order", + ): + assert getattr(warp, field) == getattr(stable, field), f"field {field!r} mismatch" + + +# ====================================================================== +# _require_newton_physics +# ====================================================================== + + +def _cfg_with_physics(physics: Any) -> Any: + cfg = types.SimpleNamespace() + cfg.sim = types.SimpleNamespace(physics=physics) + return cfg + + +def test_require_newton_passes_for_newton(): + fe._require_newton_physics(_cfg_with_physics(NewtonCfg()), "Isaac-Test-v0") # no raise + + +def test_require_newton_rejects_physx(): + with pytest.raises(FrontendIncompatibleError) as exc: + fe._require_newton_physics(_cfg_with_physics(PhysxCfg()), "Isaac-Test-v0") + assert "presets=newton_mjwarp" in str(exc.value) + assert "PhysxCfg" in str(exc.value) + + +def test_require_newton_rejects_none(): + with pytest.raises(FrontendIncompatibleError): + fe._require_newton_physics(_cfg_with_physics(None), "Isaac-Test-v0") + + # ====================================================================== # _walk_terms # ====================================================================== -class TestWalkTerms(unittest.TestCase): - def test_yields_each_term_with_its_path(self): - cfg = _CfgFixture( - rewards=_RewardsCfg(r1=_term(), r2=_term()), - events=_EventsCfg(e1=EventTermCfg(func=_stable_func, mode="reset")), - ) - # Configclass instances aren't hashable, so collect paths only. - paths = {".".join(p) for p, _ in _walk_terms(cfg)} - self.assertEqual(paths, {"rewards.r1", "rewards.r2", "events.e1"}) - - def test_descends_into_obs_subgroups(self): - cfg = _CfgFixture( - observations=_ObservationsCfg( - policy=_PolicyObsGroup(o1=ObservationTermCfg(func=_stable_func)), - perception=_ExtraObsGroup(o3=ObservationTermCfg(func=_stable_func)), - ), - ) - paths = {".".join(p) for p, _ in _walk_terms(cfg)} - # Discovery is purely type-driven; no obs group name is hardcoded. - self.assertEqual(paths, {"observations.policy.o1", "observations.perception.o3"}) +def test_walk_terms_yields_each_term_with_its_path(): + cfg = _CfgFixture( + rewards=_RewardsCfg(r1=_term(), r2=_term()), + events=_EventsCfg(e1=EventTermCfg(func=_stable_func, mode="reset")), + ) + # Configclass instances aren't hashable, so collect paths only. + paths = {".".join(p) for p, _ in fe._walk_terms(cfg)} + assert paths == {"rewards.r1", "rewards.r2", "events.e1"} + + +def test_walk_terms_descends_into_obs_subgroups(): + cfg = _CfgFixture( + observations=_ObservationsCfg( + policy=_PolicyObsGroup(o1=ObservationTermCfg(func=_stable_func)), + perception=_ExtraObsGroup(o3=ObservationTermCfg(func=_stable_func)), + ), + ) + paths = {".".join(p) for p, _ in fe._walk_terms(cfg)} + # Discovery is purely type-driven; no obs group name is hardcoded. + assert paths == {"observations.policy.o1", "observations.perception.o3"} + + +def test_walk_terms_stops_at_terms(): + # The walker must not descend into term.params / term.func — yields the term itself. + nested_se_cfg = StableSceneEntityCfg(name="robot") + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": nested_se_cfg}))) + terms = list(fe._walk_terms(cfg)) + assert len(terms) == 1 + _, term = terms[0] + assert isinstance(term, RewardTermCfg) + + +def test_walk_terms_skips_non_configclass_attrs(): + # A namespace without __dataclass_fields__ is not descended into. + cfg = types.SimpleNamespace(some_plain_attr="hello") + assert list(fe._walk_terms(cfg)) == [] - def test_stops_at_terms(self): - # The walker must not descend into term.params / term.func — yields the term itself. - nested_se_cfg = StableSceneEntityCfg(name="robot") - cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": nested_se_cfg}))) - terms = list(_walk_terms(cfg)) - self.assertEqual(len(terms), 1) - _, term = terms[0] - self.assertIsInstance(term, RewardTermCfg) - def test_skips_non_configclass_attrs(self): - # A namespace without __dataclass_fields__ is not descended into. - cfg = types.SimpleNamespace(some_plain_attr="hello") - self.assertEqual(list(_walk_terms(cfg)), []) +def test_walk_terms_skips_none_subtrees(): + cfg = _CfgFixture(rewards=None, events=None) + assert list(fe._walk_terms(cfg)) == [] - def test_skips_none_subtrees(self): - cfg = _CfgFixture(rewards=None, events=None) - self.assertEqual(list(_walk_terms(cfg)), []) + +@configclass +class _GroupWithNestedClass: + """Mirrors the real ``ObservationsCfg.PolicyCfg`` nested-class pattern.""" + + @configclass + class TemplateCfg: + t1: ObservationTermCfg | None = None + + o1: ObservationTermCfg | None = None + + +def test_walk_terms_ignores_nested_class_objects(): + # The walker iterates instance attributes only (mirroring the warp managers' + # ``cfg.__dict__`` consumption), so a nested class object — reachable as an + # attribute on the instance — must never contribute paths. + cfg = _GroupWithNestedClass(o1=ObservationTermCfg(func=_stable_func)) + paths = {".".join(p) for p, _ in fe._walk_terms(cfg)} + assert paths == {"o1"} # ====================================================================== -# _promote_scene_entity_cfgs +# Route registry # ====================================================================== -class TestPromoteSceneEntityCfgs(unittest.TestCase): - def test_promotes_in_params(self): - cfg = _CfgFixture( - rewards=_RewardsCfg( - r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="robot", joint_names=["lf_hip"]), "scale": 1.0}) - ) - ) - _promote_scene_entity_cfgs(cfg) - promoted = cfg.rewards.r1.params["asset_cfg"] - self.assertIsInstance(promoted, WarpSceneEntityCfg) - self.assertEqual(promoted.name, "robot") - self.assertEqual(promoted.joint_names, ["lf_hip"]) - # Non-SceneEntityCfg params are untouched. - self.assertEqual(cfg.rewards.r1.params["scale"], 1.0) - - def test_skips_already_warp(self): - # configclass init deep-copies params, so identity won't hold across - # construction; what we actually want to assert is "no re-promotion": - # the asset_cfg remains a WarpSceneEntityCfg (i.e., wasn't passed - # back through `from_stable`). - warp = WarpSceneEntityCfg(name="robot", joint_names=["lf_hip"]) - cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": warp}))) - before = cfg.rewards.r1.params["asset_cfg"] - _promote_scene_entity_cfgs(cfg) - after = cfg.rewards.r1.params["asset_cfg"] - self.assertIsInstance(after, WarpSceneEntityCfg) - # The asset_cfg object was not replaced by another from_stable call. - self.assertIs(after, before) - - def test_walks_all_term_groups(self): - cfg = _CfgFixture( - rewards=_RewardsCfg(r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="r")})), - events=_EventsCfg( - e1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="e")}) - ), - observations=_ObservationsCfg( - policy=_PolicyObsGroup( - o1=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-pol")}) - ), - perception=_ExtraObsGroup( - o3=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-per")}) - ), - ), - curriculum=_CurriculumCfg( - c1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="c")}) - ), - ) - _promote_scene_entity_cfgs(cfg) - # Warp-managed groups (rewards, observations incl. sub-groups, events) are promoted. - self.assertIsInstance(cfg.rewards.r1.params["asset_cfg"], WarpSceneEntityCfg) - self.assertIsInstance(cfg.observations.policy.o1.params["asset_cfg"], WarpSceneEntityCfg) - # The perception sub-group is reached even though its attribute name is - # not hardcoded in the framework. - self.assertIsInstance(cfg.observations.perception.o3.params["asset_cfg"], WarpSceneEntityCfg) - # The event manager is warp-first, so its terms are promoted too. - self.assertIsInstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) - # Curriculum runs on the stable (torch) manager, so its SceneEntityCfg is - # left untouched — promoting it would hand a warp variant to a torch manager. - self.assertIsInstance(cfg.curriculum.c1.params["asset_cfg"], StableSceneEntityCfg) - self.assertNotIsInstance(cfg.curriculum.c1.params["asset_cfg"], WarpSceneEntityCfg) +def test_register_mdp_route_and_longest_prefix_match(fake_routes: dict[str, str]): + register_mdp_route("isaaclab_tasks.core.locomotion", "warp.locomotion.mdp") + register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", "warp.humanoid.mdp") + + # Longest registered prefix wins. + assert fe._match_route("isaaclab_tasks.core.locomotion.humanoid.mdp.rewards") == "warp.humanoid.mdp" + assert fe._match_route("isaaclab_tasks.core.locomotion.ant.mdp") == "warp.locomotion.mdp" + # Exact package match works too. + assert fe._match_route("isaaclab_tasks.core.locomotion.humanoid") == "warp.humanoid.mdp" + # Prefix matching is per package segment, not per character. + assert fe._match_route("isaaclab_tasks.core.locomotion_extras.mdp") is None + assert fe._match_route("isaaclab.envs.mdp.rewards") is None + + +def test_register_mdp_route_is_idempotent(fake_routes: dict[str, str]): + register_mdp_route("isaaclab_tasks.core.cartpole", "warp.cartpole.mdp") + register_mdp_route("isaaclab_tasks.core.cartpole", "warp.cartpole.mdp") # no raise + assert fake_routes == {"isaaclab_tasks.core.cartpole": "warp.cartpole.mdp"} + + +def test_register_mdp_route_rejects_conflicts(fake_routes: dict[str, str]): + register_mdp_route("isaaclab_tasks.core.cartpole", "warp.cartpole.mdp") + with pytest.raises(ValueError): + register_mdp_route("isaaclab_tasks.core.cartpole", "warp.other.mdp") + + +def test_cfg_route_modules_resolves_cfg_class_module(fake_routes: dict[str, str]): + # Route this test module's own name so the fixture cfg class matches. + register_mdp_route(__name__, "math") + assert fe._cfg_route_modules(_CfgFixture()) == [importlib.import_module("math")] + + +def test_cfg_route_modules_raises_on_broken_target(fake_routes: dict[str, str]): + register_mdp_route(__name__, "definitely_not_an_importable_module") + with pytest.raises(FrontendIncompatibleError): + fe._cfg_route_modules(_CfgFixture()) # ====================================================================== @@ -379,116 +386,149 @@ class _FakeMdpModule: __name__ = "test_fake_warp_mdp" -class TestSwapMdp(unittest.TestCase): - def _patch_modules(self, name_to_symbol: dict[str, Any]) -> _FakeMdpModule: - m = _FakeMdpModule() - for name, sym in name_to_symbol.items(): - setattr(m, name, sym) - return m - - def _patched_warp_mdp_modules(self, modules: list[Any]): - import isaaclab_experimental.envs.frontend as fe - - self._orig = fe._warp_mdp_modules - fe._warp_mdp_modules = lambda task_id: modules # type: ignore[assignment] - - def setUp(self) -> None: - self._orig = None - - def tearDown(self) -> None: - if self._orig is not None: - import isaaclab_experimental.envs.frontend as fe - - fe._warp_mdp_modules = self._orig - - def test_swaps_func_and_class_type(self): - fake = self._patch_modules({"_stable_func": _warp_twin_func, "_StableActionCls": _WarpActionCls}) - self._patched_warp_mdp_modules([fake]) - term_reward = _term(func=_stable_func) - term_action = _term() - term_action.class_type = _StableActionCls # set attr to exercise class_type swap - cfg = _CfgFixture(rewards=_RewardsCfg(r1=term_reward, r2=term_action)) - _swap_mdp(cfg, "Isaac-Test-v0") - self.assertIs(cfg.rewards.r1.func, _warp_twin_func) - self.assertIs(cfg.rewards.r2.class_type, _WarpActionCls) - - def test_missing_twin_raises_with_path_list(self): - fake = self._patch_modules({}) - self._patched_warp_mdp_modules([fake]) - cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_stable_func))) - with self.assertRaises(FrontendIncompatibleError) as exc: - _swap_mdp(cfg, "Isaac-Test-v0") - msg = str(exc.exception) - self.assertIn("rewards.r1.func", msg) - self.assertIn("_stable_func", msg) - # The cfg term wasn't mutated for the missing twin. - self.assertIs(cfg.rewards.r1.func, _stable_func) - - def test_skips_already_warp(self): - fake = self._patch_modules({}) - self._patched_warp_mdp_modules([fake]) - cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_warp_twin_func))) - _swap_mdp(cfg, "Isaac-Test-v0") # no raise - self.assertIs(cfg.rewards.r1.func, _warp_twin_func) +def _fake_mdp_module(name_to_symbol: dict[str, Any]) -> _FakeMdpModule: + module = _FakeMdpModule() + for name, symbol in name_to_symbol.items(): + setattr(module, name, symbol) + return module + + +def _patch_twin_modules(monkeypatch: pytest.MonkeyPatch, modules: list[Any]) -> None: + """Pin twin resolution to ``modules`` and keep unit tests hermetic.""" + monkeypatch.setattr(fe, "_ensure_twin_providers_imported", lambda: None) + monkeypatch.setattr(fe, "_cfg_route_modules", lambda cfg: []) + monkeypatch.setattr(fe, "_twin_modules", lambda symbol_module, cfg_route_modules: modules) + + +def test_swap_mdp_swaps_func_and_class_type(monkeypatch: pytest.MonkeyPatch): + fake = _fake_mdp_module({"_stable_func": _warp_twin_func, "_StableActionCls": _WarpActionCls}) + _patch_twin_modules(monkeypatch, [fake]) + term_reward = _term(func=_stable_func) + term_action = _term() + term_action.class_type = _StableActionCls # set attr to exercise class_type swap + cfg = _CfgFixture(rewards=_RewardsCfg(r1=term_reward, r2=term_action)) + fe._swap_mdp(cfg, "Isaac-Test-v0") + assert cfg.rewards.r1.func is _warp_twin_func + assert cfg.rewards.r2.class_type is _WarpActionCls + + +def test_swap_mdp_missing_twin_raises_with_path_list(monkeypatch: pytest.MonkeyPatch): + _patch_twin_modules(monkeypatch, [_fake_mdp_module({})]) + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_stable_func))) + with pytest.raises(FrontendIncompatibleError) as exc: + fe._swap_mdp(cfg, "Isaac-Test-v0") + msg = str(exc.value) + assert "rewards.r1.func" in msg + assert "_stable_func" in msg + # The cfg term wasn't mutated for the missing twin. + assert cfg.rewards.r1.func is _stable_func + + +def test_swap_mdp_skips_already_warp(monkeypatch: pytest.MonkeyPatch): + _patch_twin_modules(monkeypatch, [_fake_mdp_module({})]) + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_warp_twin_func))) + fe._swap_mdp(cfg, "Isaac-Test-v0") # no raise + assert cfg.rewards.r1.func is _warp_twin_func # ====================================================================== -# Twin module routing and resolution +# _promote_scene_entity_cfgs # ====================================================================== -class TestWarpMdpModuleName(unittest.TestCase): - def test_routes_task_submodule_to_current_experimental_layout(self): - self.assertEqual( - _warp_mdp_module_name("isaaclab_tasks.core.cartpole.mdp.rewards"), - "isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp.rewards", +def test_promote_scene_entity_cfgs_promotes_in_params(): + cfg = _CfgFixture( + rewards=_RewardsCfg( + r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="robot", joint_names=["lf_hip"]), "scale": 1.0}) ) + ) + fe._promote_scene_entity_cfgs(cfg) + promoted = cfg.rewards.r1.params["asset_cfg"] + assert isinstance(promoted, WarpSceneEntityCfg) + assert promoted.name == "robot" + assert promoted.joint_names == ["lf_hip"] + # Non-SceneEntityCfg params are untouched. + assert cfg.rewards.r1.params["scale"] == 1.0 + + +def test_promote_scene_entity_cfgs_skips_already_warp(): + # configclass init deep-copies params, so identity won't hold across + # construction; what we actually want to assert is "no re-promotion": + # the asset_cfg remains a WarpSceneEntityCfg (i.e., wasn't passed + # back through `from_stable`). + warp = WarpSceneEntityCfg(name="robot", joint_names=["lf_hip"]) + cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": warp}))) + before = cfg.rewards.r1.params["asset_cfg"] + fe._promote_scene_entity_cfgs(cfg) + after = cfg.rewards.r1.params["asset_cfg"] + assert isinstance(after, WarpSceneEntityCfg) + # The asset_cfg object was not replaced by another from_stable call. + assert after is before + + +def test_promote_scene_entity_cfgs_walks_all_term_groups(): + cfg = _CfgFixture( + rewards=_RewardsCfg(r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="r")})), + events=_EventsCfg( + e1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="e")}) + ), + observations=_ObservationsCfg( + policy=_PolicyObsGroup( + o1=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-pol")}) + ), + perception=_ExtraObsGroup( + o3=ObservationTermCfg(func=_stable_func, params={"asset_cfg": StableSceneEntityCfg(name="o-per")}) + ), + ), + curriculum=_CurriculumCfg( + c1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="c")}) + ), + ) + fe._promote_scene_entity_cfgs(cfg) + # Warp-managed groups (rewards, observations incl. sub-groups, events) are promoted. + assert isinstance(cfg.rewards.r1.params["asset_cfg"], WarpSceneEntityCfg) + assert isinstance(cfg.observations.policy.o1.params["asset_cfg"], WarpSceneEntityCfg) + # The perception sub-group is reached even though its attribute name is + # not hardcoded in the framework. + assert isinstance(cfg.observations.perception.o3.params["asset_cfg"], WarpSceneEntityCfg) + # The event manager is warp-first, so its terms are promoted too. + assert isinstance(cfg.events.e1.params["asset_cfg"], WarpSceneEntityCfg) + # Curriculum runs on the stable (torch) manager, so its SceneEntityCfg is + # left untouched — promoting it would hand a warp variant to a torch manager. + assert isinstance(cfg.curriculum.c1.params["asset_cfg"], StableSceneEntityCfg) + assert not isinstance(cfg.curriculum.c1.params["asset_cfg"], WarpSceneEntityCfg) - def test_routes_exact_task_mdp_package(self): - self.assertEqual( - _warp_mdp_module_name("isaaclab_tasks.core.velocity.mdp"), - "isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp", - ) - def test_rejects_unregistered_task_module(self): - self.assertIsNone(_warp_mdp_module_name("isaaclab_tasks.core.unknown.mdp")) +# ====================================================================== +# Twin resolution and swap-candidate heuristic +# ====================================================================== + - def test_rejects_non_task_module(self): - self.assertIsNone(_warp_mdp_module_name("isaaclab.envs.mdp.rewards")) +def test_resolve_warp_twin_accepts_warp_origin(): + module = types.SimpleNamespace(foo=_warp_twin_func) + assert fe._resolve_warp_twin("foo", [module]) is _warp_twin_func -class TestResolveWarpTwin(unittest.TestCase): - def test_accepts_warp_origin(self): - m = types.SimpleNamespace() - m.foo = _warp_twin_func - result = _resolve_warp_twin("foo", [m]) - self.assertIs(result, _warp_twin_func) +def test_resolve_warp_twin_rejects_stable_origin(): + module = types.SimpleNamespace(foo=_stable_func) # same name, stable origin + assert fe._resolve_warp_twin("foo", [module]) is None - def test_rejects_stable_origin(self): - m = types.SimpleNamespace() - m.foo = _stable_func # same name, stable origin - self.assertIsNone(_resolve_warp_twin("foo", [m])) - def test_returns_none_when_absent(self): - m = types.SimpleNamespace() - self.assertIsNone(_resolve_warp_twin("missing", [m])) +def test_resolve_warp_twin_returns_none_when_absent(): + assert fe._resolve_warp_twin("missing", [types.SimpleNamespace()]) is None -# ====================================================================== -# Swap candidate heuristic -# ====================================================================== +def test_is_swap_candidate_stable_callable(): + assert fe._is_swap_candidate(_stable_func) -class TestIsSwapCandidate(unittest.TestCase): - def test_stable_callable_is_candidate(self): - self.assertTrue(_is_swap_candidate(_stable_func)) +def test_is_swap_candidate_rejects_warp_callable(): + assert not fe._is_swap_candidate(_warp_twin_func) - def test_warp_callable_is_not(self): - self.assertFalse(_is_swap_candidate(_warp_twin_func)) - def test_non_callable_is_not(self): - self.assertFalse(_is_swap_candidate(42)) - self.assertFalse(_is_swap_candidate("string")) +def test_is_swap_candidate_rejects_non_callables(): + assert not fe._is_swap_candidate(42) + assert not fe._is_swap_candidate("string") # ====================================================================== @@ -497,37 +537,32 @@ def test_non_callable_is_not(self): _DIRECT_TEST_TASKS = { - "_Frontend-Test-Warp-Direct-v0": ("isaaclab_tasks_experimental.fake:DirectEnv", True), - "_Frontend-Test-Stable-Direct-v0": ("isaaclab_tasks.fake:DirectEnv", False), + "_Frontend-Test-Warp-Direct-v0": "isaaclab_tasks_experimental.fake:DirectEnv", + "_Frontend-Test-Stable-Direct-v0": "isaaclab_tasks.fake:DirectEnv", } -class TestAssertDirectWarpRegistration(unittest.TestCase): - @classmethod - def setUpClass(cls): - # Register stub tasks so ``gym.spec`` resolves them. Entry-point strings - # are never invoked (the guard only inspects them), so a fake import - # path is fine. - cls._registered: list[str] = [] - for task_id, (ep, _) in _DIRECT_TEST_TASKS.items(): - try: - gym.register(id=task_id, entry_point=ep, disable_env_checker=True) - cls._registered.append(task_id) - except gym.error.Error: - pass +@pytest.fixture(scope="module", autouse=True) +def _register_direct_stub_tasks(): + # Register stub tasks so ``gym.spec`` resolves them. Entry-point strings + # are never invoked (the guard only inspects them), so a fake import + # path is fine. + for task_id, entry_point in _DIRECT_TEST_TASKS.items(): + with contextlib.suppress(gym.error.Error): + gym.register(id=task_id, entry_point=entry_point, disable_env_checker=True) + yield + - def test_accepts_warp_rooted(self): - _assert_direct_warp_registration("_Frontend-Test-Warp-Direct-v0") # no raise +def test_direct_guard_accepts_warp_rooted(): + fe._assert_direct_warp_registration("_Frontend-Test-Warp-Direct-v0") # no raise - def test_rejects_stable_rooted(self): - with self.assertRaises(FrontendIncompatibleError) as exc: - _assert_direct_warp_registration("_Frontend-Test-Stable-Direct-v0") - self.assertIn("isaaclab_experimental", str(exc.exception)) - def test_rejects_unknown_task(self): - with self.assertRaises(FrontendIncompatibleError): - _assert_direct_warp_registration("Frontend-Test-NotRegistered-v0") +def test_direct_guard_rejects_stable_rooted(): + with pytest.raises(FrontendIncompatibleError) as exc: + fe._assert_direct_warp_registration("_Frontend-Test-Stable-Direct-v0") + assert "isaaclab_experimental" in str(exc.value) -if __name__ == "__main__": - unittest.main() +def test_direct_guard_rejects_unknown_task(): + with pytest.raises(FrontendIncompatibleError): + fe._assert_direct_warp_registration("Frontend-Test-NotRegistered-v0") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py index af513e675f03..668e758521c4 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py @@ -9,6 +9,15 @@ import gymnasium as gym +from isaaclab_experimental.envs.frontend import register_mdp_route + +# The stable Ant task borrows Humanoid MDP terms, so its warp twins live in the +# experimental humanoid package. +register_mdp_route( + "isaaclab_tasks.core.locomotion.ant", + "isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp", +) + # Reuse agent configs from the stable task package. from isaaclab_tasks.core.locomotion.ant import agents diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py index 9f46551de255..2ab0e3555059 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py @@ -9,6 +9,11 @@ import gymnasium as gym +from isaaclab_experimental.envs.frontend import register_mdp_route + +# Warp twins for the stable cartpole MDP terms live in this package's ``mdp``. +register_mdp_route("isaaclab_tasks.core.cartpole", f"{__name__}.mdp") + # Reuse agent configs from the stable task package. from isaaclab_tasks.core.cartpole import agents diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py index 0bcd020bcd4c..6d2d958b759b 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py @@ -9,6 +9,12 @@ import gymnasium as gym +from isaaclab_experimental.envs.frontend import register_mdp_route + +# Warp twins for the stable humanoid MDP terms live in this package's ``mdp``. +# The stable Ant task borrows Humanoid MDP terms, so this route serves it too. +register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", f"{__name__}.mdp") + # Reuse agent configs from the stable task package. from isaaclab_tasks.core.locomotion.humanoid import agents diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py index 0857176a3fc7..9ddf530c28e0 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py @@ -4,3 +4,8 @@ # SPDX-License-Identifier: BSD-3-Clause """Velocity locomotion experimental task registrations (manager-based).""" + +from isaaclab_experimental.envs.frontend import register_mdp_route + +# Warp twins for the stable velocity MDP terms live in this package's ``mdp``. +register_mdp_route("isaaclab_tasks.core.velocity", f"{__name__}.mdp") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py index fe34199f2321..8589501220cc 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py @@ -4,3 +4,8 @@ # SPDX-License-Identifier: BSD-3-Clause """Reach experimental task registrations (manager-based).""" + +from isaaclab_experimental.envs.frontend import register_mdp_route + +# Warp twins for the stable reach MDP terms live in this package's ``mdp``. +register_mdp_route("isaaclab_tasks.core.reach", f"{__name__}.mdp") From cd45040a1056aa2eb676cf0ad68d8ad73c20d6e4 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 15 Jul 2026 18:12:42 -0700 Subject: [PATCH 26/36] Replace duplicated warp task configs with stable-cfg reuse Every manager-based *-Warp-v0 task duplicated its stable environment configuration file-for-file, so each stable task rewrite had to be mirrored by hand (as happened with the Cartpole rewrite). ManagerBasedRLEnvWarp now adapts its cfg in __init__, so warp env construction accepts stable-derived cfgs directly. On top of that: - Drop the Cartpole, Humanoid, Ant, and Reach-Franka warp registrations and their duplicated cfgs; the stable ids run on warp via --frontend warp presets=newton_mjwarp. Their packages keep only the warp MDP twins and the route registration. - Rewrite the velocity *-Warp-v0 variants as thin subclasses of the stable flat cfgs that only disable the rigid-body material/mass randomization events, which have no warp twins yet. The duplicated velocity base cfg, per-robot cfgs, and unregistered rough cfgs are removed; the variants now select Newton via presets=newton_mjwarp like every other task. - Cover both paths in test_frontend_cfg_conversion.py: the stable ids with full twin coverage adapt cleanly, and every registered warp variant still adapts. - Update the warp environments documentation and the generated environment list accordingly. --- .../newton/warp-environments.rst | 42 ++- docs/source/overview/environments.rst | 20 -- .../changelog.d/warp-manager-bridge.rst | 9 + .../isaaclab_experimental/envs/frontend.py | 7 +- .../envs/manager_based_rl_env_warp.py | 8 + .../test/envs/test_frontend.py | 20 +- .../test/envs/test_frontend_cfg_conversion.py | 102 ++++-- .../changelog.d/warp-manager-bridge.minor.rst | 30 ++ .../changelog.d/warp-manager-bridge.rst | 8 - .../manager_based/classic/ant/__init__.py | 28 +- .../manager_based/classic/ant/ant_env_cfg.py | 197 ------------ .../classic/cartpole/__init__.py | 28 +- .../classic/cartpole/cartpole_env_cfg.py | 199 ------------ .../classic/humanoid/__init__.py | 29 +- .../classic/humanoid/humanoid_env_cfg.py | 232 -------------- .../locomotion/velocity/__init__.py | 29 +- .../velocity/config/a1/flat_env_cfg.py | 59 +--- .../velocity/config/a1/rough_env_cfg.py | 91 ------ .../velocity/config/anymal_b/flat_env_cfg.py | 63 ++-- .../velocity/config/anymal_b/rough_env_cfg.py | 34 -- .../velocity/config/anymal_c/flat_env_cfg.py | 51 +-- .../velocity/config/anymal_c/rough_env_cfg.py | 40 --- .../velocity/config/anymal_d/__init__.py | 25 -- .../velocity/config/anymal_d/flat_env_cfg.py | 47 ++- .../velocity/config/anymal_d/rough_env_cfg.py | 37 --- .../velocity/config/cassie/flat_env_cfg.py | 46 ++- .../velocity/config/cassie/rough_env_cfg.py | 96 ------ .../locomotion/velocity/config/g1/__init__.py | 22 -- .../velocity/config/g1/flat_env_cfg.py | 61 ++-- .../velocity/config/g1/rough_env_cfg.py | 178 ----------- .../velocity/config/go1/flat_env_cfg.py | 47 ++- .../velocity/config/go1/rough_env_cfg.py | 61 ---- .../velocity/config/go2/flat_env_cfg.py | 47 ++- .../velocity/config/go2/rough_env_cfg.py | 60 ---- .../locomotion/velocity/config/h1/__init__.py | 22 -- .../velocity/config/h1/flat_env_cfg.py | 45 +-- .../velocity/config/h1/rough_env_cfg.py | 131 -------- .../locomotion/velocity/velocity_env_cfg.py | 296 ------------------ .../manipulation/reach/__init__.py | 8 +- .../manipulation/reach/config/__init__.py | 4 - .../reach/config/franka/__init__.py | 41 --- .../reach/config/franka/joint_pos_env_cfg.py | 74 ----- .../reach/config/ur_10/__init__.py | 36 --- .../reach/config/ur_10/joint_pos_env_cfg.py | 74 ----- .../manipulation/reach/reach_env_cfg.py | 206 ------------ 45 files changed, 359 insertions(+), 2631 deletions(-) create mode 100644 source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst delete mode 100644 source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index 05c5bc848422..8f682ddcb047 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -37,33 +37,41 @@ Direct Warp Environments - ``Isaac-Reorient-Cube-Allegro-Direct-Warp-v0`` — Allegro hand cube reorient -Manager-Based Warp Environments -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Manager-Based Warp Execution (``--frontend warp``) +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -**Classic** +Manager-based tasks do not need a parallel warp registration: the shared RL +CLI exposes ``--frontend {torch,warp}``, and ``--frontend warp`` adapts the +*stable* task configuration onto the warp runtime at build time (swapping each +MDP term for its warp twin). Select the Newton solver explicitly with +``presets=newton_mjwarp``. Stable tasks with full twin coverage: -- ``Isaac-Cartpole-Warp-v0`` -- ``Isaac-Ant-Warp-v0`` -- ``Isaac-Humanoid-Warp-v0`` +- ``Isaac-Cartpole`` +- ``Isaac-Ant`` +- ``Isaac-Humanoid`` +- ``Isaac-Reach-Franka`` +- ``Isaac-Reach-UR10`` -**Locomotion (Flat)** +A missing twin is a hard error listing the affected terms, so a partially +covered task fails at build time rather than silently changing behavior. + +**Locomotion (Flat) — registered warp variants** + +The velocity tasks still register ``*-Warp-v0`` variants because their stable +configurations contain randomization events without warp twins yet; the +variants reuse the stable flat configurations and only disable those events. +They also require ``presets=newton_mjwarp``. - ``Isaac-Velocity-Flat-AnymalB-Warp-v0`` - ``Isaac-Velocity-Flat-AnymalC-Warp-v0`` - ``Isaac-Velocity-Flat-AnymalD-Warp-v0`` - ``Isaac-Velocity-Flat-Cassie-Warp-v0`` - ``Isaac-Velocity-Flat-G1-Warp-v0`` -- ``Isaac-Velocity-Flat-G1-Warp-v1`` - ``Isaac-Velocity-Flat-H1-Warp-v0`` - ``Isaac-Velocity-Flat-UnitreeA1-Warp-v0`` - ``Isaac-Velocity-Flat-UnitreeGo1-Warp-v0`` - ``Isaac-Velocity-Flat-UnitreeGo2-Warp-v0`` -**Manipulation** - -- ``Isaac-Reach-Franka-Warp-v0`` -- ``Isaac-Reach-UR10-Warp-v0`` - Quick Start ~~~~~~~~~~~ @@ -74,9 +82,13 @@ Quick Start ./isaaclab.sh train --rl_library rsl_rl \ --task Isaac-Cartpole-Direct-Warp-v0 --num_envs 4096 - # Manager-based workflow + # Manager-based workflow: stable task on the warp runtime + ./isaaclab.sh train --rl_library rsl_rl \ + --task Isaac-Cartpole --frontend warp presets=newton_mjwarp --num_envs 4096 + + # Manager-based workflow: registered warp variant ./isaaclab.sh train --rl_library rsl_rl \ - --task Isaac-Velocity-Flat-AnymalC-Warp-v0 --num_envs 4096 + --task Isaac-Velocity-Flat-AnymalD-Warp-v0 presets=newton_mjwarp --num_envs 4096 All RL libraries with warp-compatible wrappers are supported: RSL-RL, RL Games, SKRL, and Stable-Baselines3. diff --git a/docs/source/overview/environments.rst b/docs/source/overview/environments.rst index b82b1bc83e06..8c821bf47bdb 100644 --- a/docs/source/overview/environments.rst +++ b/docs/source/overview/environments.rst @@ -880,11 +880,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Ant-Warp-v0 - - - - Manager Based - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - - * - IsaacContrib-Assemble-Trocar-G129-Dex3 - IsaacContrib-Assemble-Trocar-G129-Dex3-Eval - Manager Based @@ -940,11 +935,6 @@ inferencing, including reading from an already trained checkpoint and disabling - **skrl** (PPO, BOX_BOX, BOX_DISCRETE, BOX_MULTIDISCRETE, DICT_BOX, DICT_DISCRETE, DICT_MULTIDISCRETE, DISCRETE_BOX, DISCRETE_DISCRETE, DISCRETE_MULTIDISCRETE, MULTIDISCRETE_BOX, MULTIDISCRETE_DISCRETE, MULTIDISCRETE_MULTIDISCRETE, TUPLE_BOX, TUPLE_DISCRETE, TUPLE_MULTIDISCRETE) - | **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` | **presets=** ``box_box``, ``box_discrete``, ``box_multidiscrete``, ``dict_box``, ``dict_discrete``, ``dict_multidiscrete``, ``discrete_box``, ``discrete_discrete``, ``discrete_multidiscrete``, ``multidiscrete_box``, ``multidiscrete_discrete``, ``multidiscrete_multidiscrete``, ``tuple_box``, ``tuple_discrete``, ``tuple_multidiscrete`` - * - Isaac-Cartpole-Warp-v0 - - - - Manager Based - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - - * - IsaacContrib-Deploy-GearAssembly-Rizon4s-Grav-ROS-Inference - - Manager Based @@ -1060,11 +1050,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Humanoid-Warp-v0 - - - - Manager Based - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - - * - Isaac-Lift-Cloth-Franka - - Manager Based @@ -1231,11 +1216,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Reach-Franka-Warp-v0 - - Isaac-Reach-Franka-Warp-Play-v0 - - Manager Based - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - IsaacContrib-Reach-OpenArm - IsaacContrib-Reach-OpenArm-Play - Manager Based diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 4b3996529ba8..ccb21e9b301f 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -8,6 +8,15 @@ Added :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable` used by ``--frontend=warp`` to adapt stable cfgs onto the warp runtime. +Changed +^^^^^^^ + +* Changed :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` to adapt + its configuration in ``__init__`` via + :func:`~isaaclab_experimental.envs.frontend.adapt_cfg_for_warp`, so + registered warp task variants can derive from stable configurations instead + of duplicating them. + Fixed ^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 780685198e7c..eefc9327476f 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -172,12 +172,11 @@ def build( return gym.make(task_id, cfg=env_cfg, **construct_kwargs) # Imported lazily so that ``--frontend=torch`` callers don't pay the - # ``isaaclab_experimental.envs`` import cost. Registered ``*-Warp-v0`` tasks - # already provide Warp-native configs; the frontend path adapts stable configs - # immediately before constructing the Warp environment. + # ``isaaclab_experimental.envs`` import cost. The env adapts the cfg itself + # in ``__init__`` (see :func:`adapt_cfg_for_warp`), so stable cfgs and + # warp-native cfgs take the same path. from isaaclab_experimental.envs import ManagerBasedRLEnvWarp - adapt_cfg_for_warp(env_cfg) return ManagerBasedRLEnvWarp(cfg=env_cfg, **construct_kwargs) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py index 06ba2db190ae..a90489264a48 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py @@ -93,6 +93,14 @@ def __init__(self, cfg: ManagerBasedRLEnvCfg, render_mode: str | None = None, ** render_mode: The render mode for the environment. Defaults to None, which is similar to ``"human"``. """ + # Adapt the cfg for the warp managers (Newton physics check, SceneEntityCfg + # promotion, MDP twin swap). Idempotent: a warp-native cfg passes through + # unchanged, and a stable-derived cfg (``--frontend=warp`` or a registered + # warp task variant subclassing a stable cfg) is adapted in place. + from isaaclab_experimental.envs.frontend import adapt_cfg_for_warp + + adapt_cfg_for_warp(cfg) + # -- counter for curriculum self.common_step_counter = 0 diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index 03e39287e679..ee374ed1f9ef 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -168,28 +168,24 @@ def test_workflow_values(): # ====================================================================== -def test_warp_manager_build_adapts_cfg_before_construction(): +def test_warp_manager_build_constructs_warp_env_with_cfg(): + # Cfg adaptation happens inside ManagerBasedRLEnvWarp.__init__, so build() + # only selects the env class and forwards the cfg and construct kwargs. import isaaclab_experimental.envs as envs cfg = object.__new__(ManagerBasedRLEnvCfg) expected_env = object() - calls: list[tuple[str, Any]] = [] - - def fake_adapt(received_cfg: Any) -> None: - calls.append(("adapt", received_cfg)) + calls: list[tuple[Any, Any]] = [] def fake_env(*, cfg: Any, **kwargs: Any) -> Any: - calls.append(("construct", cfg)) + calls.append((cfg, kwargs)) return expected_env - with ( - patch.object(fe, "adapt_cfg_for_warp", fake_adapt), - patch.object(envs, "ManagerBasedRLEnvWarp", fake_env), - ): - env = build("warp", cfg, "Isaac-Test") + with patch.object(envs, "ManagerBasedRLEnvWarp", fake_env): + env = build("warp", cfg, "Isaac-Test", render_mode="rgb_array") assert env is expected_env - assert calls == [("adapt", cfg), ("construct", cfg)] + assert calls == [(cfg, {"render_mode": "rgb_array"})] # ====================================================================== diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 909ca8dec08e..8ad8716bfd89 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -3,12 +3,21 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Coverage tests for manager-based Warp task configuration adaptation. +"""Coverage tests for warp task configuration adaptation. -For each registered manager-based Warp task, load its environment configuration, -force Newton physics, and run :func:`adapt_cfg_for_warp` — the same adaptation the -Warp environment runs in its ``__init__``. A dedicated stable Cartpole case also -guards the stable-to-experimental module routing used by ``--frontend warp``. +Two sweeps, both running :func:`adapt_cfg_for_warp` — the same adaptation +:class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` runs in its +``__init__``: + +* Every *stable* task id with declared warp twin coverage: resolve the + ``newton_mjwarp`` preset and adapt the stable cfg, exactly what + ``--frontend warp`` does. +* Every registered manager-based ``*-Warp-v0`` variant (velocity deltas whose + stable cfgs still contain terms without warp twins): load its env cfg, + resolve presets, and adapt. + +A dedicated stable Cartpole case also guards the stable-to-experimental +module routing used by ``--frontend warp``. """ from __future__ import annotations @@ -19,16 +28,32 @@ import isaaclab_tasks_experimental # noqa: F401 import pytest from isaaclab_experimental.envs.frontend import adapt_cfg_for_warp -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +from isaaclab_newton.physics import NewtonCfg # Registering the task packages is the whole point — import for side effects. import isaaclab_tasks # noqa: F401 +from isaaclab_tasks.utils.hydra import resolve_presets + +# Stable task ids whose MDP terms are fully twinned: ``--frontend warp`` adapts +# their cfgs directly, with no parallel ``*-Warp-v0`` registration. Extend this +# list when a new task family gains full twin coverage. +_STABLE_TASKS_WITH_WARP_COVERAGE = [ + "Isaac-Ant", + "Isaac-Cartpole", + "Isaac-Humanoid", + "Isaac-Reach-Franka", + "Isaac-Reach-Franka-Play", + "Isaac-Reach-UR10", + "Isaac-Reach-UR10-Play", +] # Manager-based warp tasks are exactly those whose entry point is the shared warp # env class; direct ``*-Direct-Warp-v0`` tasks register their own env class and # are not cfg-adapted, so they are excluded here. _MANAGER_WARP_ENTRY_POINT = "isaaclab_experimental.envs:ManagerBasedRLEnvWarp" +_WARP_ROOTS = ("isaaclab_experimental", "isaaclab_tasks_experimental") + def _manager_warp_tasks() -> list[tuple[str, str]]: """Return ``(task_id, env_cfg_entry_point)`` for every manager-based warp task.""" @@ -42,36 +67,50 @@ def _manager_warp_tasks() -> list[tuple[str, str]]: return sorted(tasks) -def _instantiate_cfg(cfg_entry_point: str): - """Import ``module:Class`` and instantiate the stable env cfg.""" +def _load_adapted_cfg(cfg_entry_point: str): + """Instantiate an env cfg, resolve the Newton preset, and adapt it for warp.""" module_path, class_name = cfg_entry_point.split(":") - return getattr(importlib.import_module(module_path), class_name)() + cfg = getattr(importlib.import_module(module_path), class_name)() + cfg = resolve_presets(cfg, selected=("newton_mjwarp",)) + assert isinstance(cfg.sim.physics, NewtonCfg), "task does not provide a newton_mjwarp physics preset" + # Raises FrontendIncompatibleError if any warp-managed term lacks a warp twin. + adapt_cfg_for_warp(cfg) + return cfg -_MANAGER_WARP_TASKS = _manager_warp_tasks() +def _cfg_entry_point(task_id: str) -> str: + cfg_entry = (gym.spec(task_id).kwargs or {}).get("env_cfg_entry_point") + assert isinstance(cfg_entry, str), f"{task_id}: no env_cfg_entry_point" + return cfg_entry -def _params(): - return [pytest.param(task_id, cfg_entry_point, id=task_id) for task_id, cfg_entry_point in _MANAGER_WARP_TASKS] +_MANAGER_WARP_TASKS = _manager_warp_tasks() def test_manager_warp_tasks_are_registered(): - """Sanity: the package actually registered manager-based warp tasks.""" - assert _MANAGER_WARP_TASKS, "no manager-based '*-Warp-v0' tasks registered" - - -_WARP_ROOTS = ("isaaclab_experimental", "isaaclab_tasks_experimental") - - -@pytest.mark.parametrize("task_id, cfg_entry_point", _params()) -def test_registered_cfg_adapts_to_warp(task_id: str, cfg_entry_point: str): - """Each registered manager-based Warp cfg adapts without a missing twin.""" - cfg = _instantiate_cfg(cfg_entry_point) - # The warp env requires Newton physics (normally via ``presets=newton_mjwarp``); - # set it directly so the test does not depend on Hydra preset resolution. - cfg.sim.physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) - # Raises FrontendIncompatibleError if any warp-managed term lacks a warp twin. - adapt_cfg_for_warp(cfg) + """Sanity: every expected velocity warp task variant is registered.""" + expected = { + f"Isaac-Velocity-Flat-{robot}-Warp{suffix}-v0" + for robot in ("AnymalB", "AnymalC", "AnymalD", "Cassie", "G1", "H1", "UnitreeA1", "UnitreeGo1", "UnitreeGo2") + for suffix in ("", "-Play") + } + registered = {task_id for task_id, _ in _MANAGER_WARP_TASKS} + assert registered == expected, f"missing: {sorted(expected - registered)}; extra: {sorted(registered - expected)}" + + +@pytest.mark.parametrize("task_id", _STABLE_TASKS_WITH_WARP_COVERAGE, ids=_STABLE_TASKS_WITH_WARP_COVERAGE) +def test_stable_task_cfg_adapts_to_warp(task_id: str): + """Each covered stable task adapts without a missing twin (the --frontend warp path).""" + _load_adapted_cfg(_cfg_entry_point(task_id)) + + +@pytest.mark.parametrize( + "task_id, cfg_entry_point", + [pytest.param(task_id, cfg_entry, id=task_id) for task_id, cfg_entry in _MANAGER_WARP_TASKS], +) +def test_registered_warp_variant_cfg_adapts(task_id: str, cfg_entry_point: str): + """Each registered ``*-Warp-v0`` variant cfg adapts without a missing twin.""" + cfg = _load_adapted_cfg(cfg_entry_point) # Action terms carry a ``class_type`` (not a ``func``) and live on a base that # is not a ManagerTermBaseCfg; guard that the adapter still swaps them to the @@ -91,12 +130,7 @@ def test_stable_cartpole_cfg_adapts_to_current_warp_module_layout(): """The stable Cartpole cfg resolves task-specific twins in the current package layout.""" from isaaclab_experimental.managers.action_manager import ActionTerm - from isaaclab_tasks.core.cartpole.cartpole_manager_env_cfg import CartpoleEnvCfg - - cfg = CartpoleEnvCfg() - cfg.sim.physics = NewtonCfg(solver_cfg=MJWarpSolverCfg(), num_substeps=1) - - adapt_cfg_for_warp(cfg) + cfg = _load_adapted_cfg(_cfg_entry_point("Isaac-Cartpole")) assert cfg.rewards.pole_pos.func.__module__.startswith( "isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp" diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst new file mode 100644 index 000000000000..dfb8c6270757 --- /dev/null +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst @@ -0,0 +1,30 @@ +Changed +^^^^^^^ + +* **Breaking:** Changed the manager-based velocity ``*-Warp-v0`` task variants + to reuse the stable flat configurations, disabling only the randomization + events that have no warp twins yet. The variants now require selecting the + Newton solver on the CLI via ``presets=newton_mjwarp`` instead of + hard-coding it in the configuration. + +Removed +^^^^^^^ + +* **Breaking:** Removed the duplicated manager-based warp task registrations + ``Isaac-Cartpole-Warp-v0``, ``Isaac-Humanoid-Warp-v0``, ``Isaac-Ant-Warp-v0``, + ``Isaac-Reach-Franka-Warp-v0``, and ``Isaac-Reach-Franka-Warp-Play-v0`` + together with their duplicated environment configurations. Run the stable + task ids with ``--frontend warp`` and ``presets=newton_mjwarp`` instead, + e.g. ``--task Isaac-Cartpole --frontend warp presets=newton_mjwarp``. +* Removed the unregistered rough velocity warp configurations; rough-terrain + warp tasks remain unsupported until :class:`~isaaclab.terrains.TerrainImporter` + gains Warp APIs. + +Fixed +^^^^^ + +* Fixed the direct Warp Cartpole task to match the stable task's observations, + reset ranges, termination condition, reward scaling, and scene configuration. +* Fixed the Warp Cartpole ``survival_success_rate`` twin to report the + ``Metrics/success_rate`` value on-device instead of silently dropping the + metric. diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst deleted file mode 100644 index 4ac20a99187a..000000000000 --- a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.rst +++ /dev/null @@ -1,8 +0,0 @@ -Fixed -^^^^^ - -* Fixed the direct Warp Cartpole task to match the stable task's observations, - reset ranges, termination condition, reward scaling, and scene configuration. -* Fixed the Warp Cartpole ``survival_success_rate`` twin to report the - ``Metrics/success_rate`` value on-device instead of silently dropping the - metric. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py index 668e758521c4..0263ee66c216 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py @@ -3,11 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Ant locomotion environment (experimental manager-based entry point). -""" +"""Warp MDP route for the stable Ant task. -import gymnasium as gym +There is no separate task registration: run the stable ``Isaac-Ant`` task with +``--frontend warp`` and ``presets=newton_mjwarp``. +""" from isaaclab_experimental.envs.frontend import register_mdp_route @@ -17,23 +17,3 @@ "isaaclab_tasks.core.locomotion.ant", "isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp", ) - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.locomotion.ant import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Ant-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.ant_env_cfg:AntEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AntPPORunnerCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_manager_ppo_cfg.yaml", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_manager_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_manager_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py deleted file mode 100644 index 66a9131011f3..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/ant_env_cfg.py +++ /dev/null @@ -1,197 +0,0 @@ -# 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 - -# Ant reuses humanoid's experimental MDP (mirrors stable pattern). -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp as mdp - -## -# Pre-defined configs -## -from isaaclab_assets.robots.ant import ANT_CFG # isort: skip - - -@configclass -class MySceneCfg(InteractiveSceneCfg): - """Configuration for the terrain scene with an ant robot.""" - - # terrain - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="plane", - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg( - friction_combine_mode="average", - restitution_combine_mode="average", - static_friction=1.0, - dynamic_friction=1.0, - restitution=0.0, - ), - debug_vis=False, - ) - - # robot - robot = ANT_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - - # lights - light = AssetBaseCfg( - prim_path="/World/light", - spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), - ) - - -## -# MDP settings -## - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=[".*"], scale=7.5) - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for the policy.""" - - base_height = ObsTerm(func=mdp.base_pos_z) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel) - base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) - base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) - base_up_proj = ObsTerm(func=mdp.base_up_proj) - base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) - joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.2) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={"pose_range": {}, "velocity_range": {}}, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "position_range": (-0.2, 0.2), - "velocity_range": (-0.1, 0.1), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # (1) Reward for moving forward - progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)}) - # (2) Stay alive bonus - alive = RewTerm(func=mdp.is_alive, weight=0.5) - # (3) Reward for non-upright posture - upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93}) - # (4) Reward for moving in the right direction - move_to_target = RewTerm( - func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)} - ) - # (5) Penalty for large action commands - action_l2 = RewTerm(func=mdp.action_l2, weight=-0.005) - # (6) Penalty for energy consumption - energy = RewTerm(func=mdp.power_consumption, weight=-0.05, params={"gear_ratio": {".*": 15.0}}) - # (7) Penalty for reaching close to joint limits - joint_pos_limits = RewTerm( - func=mdp.joint_pos_limits_penalty_ratio, weight=-0.1, params={"threshold": 0.99, "gear_ratio": {".*": 15.0}} - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - # (1) Terminate if the episode length is exceeded - time_out = DoneTerm(func=mdp.time_out, time_out=True) - # (2) Terminate if the robot falls - torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.31}) - - -## -# Environment configuration -## - - -@configclass -class AntEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the MuJoCo-style Ant walking environment.""" - - # Simulation settings - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=38, - nconmax=15, - ls_iterations=10, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - # Scene settings - scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0, clone_in_fabric=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 2 - self.episode_length_s = 16.0 - # simulation settings - self.sim.dt = 1 / 120.0 - self.sim.render_interval = self.decimation - # default friction material - self.sim.physics_material.static_friction = 1.0 - self.sim.physics_material.dynamic_friction = 1.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py index 2ab0e3555059..e527f251fb5c 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py @@ -3,33 +3,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Cartpole balancing environment (experimental manager-based entry point). -""" +"""Warp MDP twins for the stable Cartpole task. -import gymnasium as gym +There is no separate task registration: run the stable ``Isaac-Cartpole`` task +with ``--frontend warp`` and ``presets=newton_mjwarp``. +""" from isaaclab_experimental.envs.frontend import register_mdp_route # Warp twins for the stable cartpole MDP terms live in this package's ``mdp``. register_mdp_route("isaaclab_tasks.core.cartpole", f"{__name__}.mdp") - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.cartpole import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Cartpole-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.cartpole_env_cfg:CartpoleEnvCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_manager_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_manager_ppo_cfg:CartpolePPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_manager_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_manager_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py deleted file mode 100644 index ae187a593a16..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/cartpole_env_cfg.py +++ /dev/null @@ -1,199 +0,0 @@ -# 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 - -import math - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg, AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp as mdp - -## -# Pre-defined configs -## -from isaaclab_assets.robots.cartpole import CARTPOLE_CFG # isort:skip - - -## -# Scene definition -## - - -@configclass -class CartpoleSceneCfg(InteractiveSceneCfg): - """Configuration for a cart-pole scene.""" - - # ground plane - # ground = AssetBaseCfg( - # prim_path="/World/ground", - # spawn=sim_utils.GroundPlaneCfg(size=(100.0, 100.0)), - # ) - - # cartpole - robot: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - - # lights - dome_light = AssetBaseCfg( - prim_path="/World/DomeLight", - spawn=sim_utils.DomeLightCfg(color=(0.9, 0.9, 0.9), intensity=500.0), - ) - - -## -# MDP settings -## - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_effort = mdp.JointEffortActionCfg(asset_name="robot", joint_names=["slider_to_cart"], scale=100.0) - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for policy group.""" - - # observation terms (order preserved) - joint_pos_rel = ObsTerm(func=mdp.joint_pos_rel) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel) - - def __post_init__(self) -> None: - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - # reset - reset_cart_position = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), - "position_range": (-1.0, 1.0), - "velocity_range": (-0.5, 0.5), - }, - ) - - reset_pole_position = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), - "position_range": (-0.25 * math.pi, 0.25 * math.pi), - "velocity_range": (-0.25 * math.pi, 0.25 * math.pi), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # (1) Constant running reward - alive = RewTerm(func=mdp.is_alive, weight=1.0) - # (2) Failure penalty - terminating = RewTerm(func=mdp.is_terminated, weight=-2.0) - # (3) Primary task: keep pole upright - pole_pos = RewTerm( - func=mdp.joint_pos_target_l2, - weight=-1.0, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"]), "target": 0.0}, - ) - # (4) Shaping tasks: lower cart velocity - cart_vel = RewTerm( - func=mdp.joint_vel_l1, - weight=-0.01, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"])}, - ) - # (5) Shaping tasks: lower pole angular velocity - pole_vel = RewTerm( - func=mdp.joint_vel_l1, - weight=-0.005, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["cart_to_pole"])}, - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - # (1) Time out - time_out = DoneTerm(func=mdp.time_out, time_out=True) - # (2) Cart out of bounds - cart_out_of_bounds = DoneTerm( - func=mdp.joint_pos_out_of_manual_limit, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["slider_to_cart"]), "bounds": (-3.0, 3.0)}, - ) - - -## -# Environment configuration -## - - -@configclass -class CartpoleEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the cartpole environment.""" - - # Scene settings - scene: CartpoleSceneCfg = CartpoleSceneCfg(num_envs=4096, env_spacing=4.0, clone_in_fabric=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - events: EventCfg = EventCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - # Simulation settings - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=5, - nconmax=3, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - use_cuda_graph=True, - ) - ) - - # Post initialization - def __post_init__(self) -> None: - """Post initialization.""" - # general settings - self.decimation = 2 - self.episode_length_s = 5 - # viewer settings - self.viewer.eye = (8.0, 0.0, 5.0) - # simulation settings - self.sim.dt = 1 / 120 - self.sim.render_interval = self.decimation diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py index 6d2d958b759b..0d31a47ece94 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py @@ -3,34 +3,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Humanoid locomotion environment (experimental manager-based entry point). -""" +"""Warp MDP twins for the stable Humanoid task. -import gymnasium as gym +There is no separate task registration: run the stable ``Isaac-Humanoid`` task +with ``--frontend warp`` and ``presets=newton_mjwarp``. +""" from isaaclab_experimental.envs.frontend import register_mdp_route # Warp twins for the stable humanoid MDP terms live in this package's ``mdp``. -# The stable Ant task borrows Humanoid MDP terms, so this route serves it too. register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", f"{__name__}.mdp") - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.locomotion.humanoid import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Humanoid-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.humanoid_env_cfg:HumanoidEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:HumanoidPPORunnerCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_manager_ppo_cfg.yaml", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_manager_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_manager_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py deleted file mode 100644 index 9de689ffb98e..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/humanoid_env_cfg.py +++ /dev/null @@ -1,232 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp as mdp - -from isaaclab_assets.robots.humanoid import HUMANOID_CFG # isort:skip - - -## -# Scene definition -## - - -@configclass -class MySceneCfg(InteractiveSceneCfg): - """Configuration for the terrain scene with a humanoid robot.""" - - # terrain - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="plane", - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg(static_friction=1.0, dynamic_friction=1.0, restitution=0.0), - debug_vis=False, - ) - - # robot - robot = HUMANOID_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - - # lights - light = AssetBaseCfg( - prim_path="/World/light", - spawn=sim_utils.DistantLightCfg(color=(0.75, 0.75, 0.75), intensity=3000.0), - ) - - -## -# MDP settings -## - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_effort = mdp.JointEffortActionCfg( - asset_name="robot", - joint_names=[".*"], - scale={ - ".*_waist.*": 67.5, - ".*_upper_arm.*": 67.5, - "pelvis": 67.5, - ".*_lower_arm": 45.0, - ".*_thigh:0": 45.0, - ".*_thigh:1": 135.0, - ".*_thigh:2": 45.0, - ".*_shin": 90.0, - ".*_foot.*": 22.5, - }, - ) - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for the policy.""" - - base_height = ObsTerm(func=mdp.base_pos_z) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel, scale=0.25) - base_yaw_roll = ObsTerm(func=mdp.base_yaw_roll) - base_angle_to_target = ObsTerm(func=mdp.base_angle_to_target, params={"target_pos": (1000.0, 0.0, 0.0)}) - base_up_proj = ObsTerm(func=mdp.base_up_proj) - base_heading_proj = ObsTerm(func=mdp.base_heading_proj, params={"target_pos": (1000.0, 0.0, 0.0)}) - joint_pos_norm = ObsTerm(func=mdp.joint_pos_limit_normalized) - joint_vel_rel = ObsTerm(func=mdp.joint_vel_rel, scale=0.1) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = False - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={"pose_range": {}, "velocity_range": {}}, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_offset, - mode="reset", - params={ - "position_range": (-0.2, 0.2), - "velocity_range": (-0.1, 0.1), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # (1) Reward for moving forward - progress = RewTerm(func=mdp.progress_reward, weight=1.0, params={"target_pos": (1000.0, 0.0, 0.0)}) - # (2) Stay alive bonus - alive = RewTerm(func=mdp.is_alive, weight=2.0) - # (3) Reward for non-upright posture - upright = RewTerm(func=mdp.upright_posture_bonus, weight=0.1, params={"threshold": 0.93}) - # (4) Reward for moving in the right direction - move_to_target = RewTerm( - func=mdp.move_to_target_bonus, weight=0.5, params={"threshold": 0.8, "target_pos": (1000.0, 0.0, 0.0)} - ) - # (5) Penalty for large action commands - action_l2 = RewTerm(func=mdp.action_l2, weight=-0.01) - # (6) Penalty for energy consumption - energy = RewTerm( - func=mdp.power_consumption, - weight=-0.005, - params={ - "gear_ratio": { - ".*_waist.*": 67.5, - ".*_upper_arm.*": 67.5, - "pelvis": 67.5, - ".*_lower_arm": 45.0, - ".*_thigh:0": 45.0, - ".*_thigh:1": 135.0, - ".*_thigh:2": 45.0, - ".*_shin": 90.0, - ".*_foot.*": 22.5, - } - }, - ) - # (7) Penalty for reaching close to joint limits - joint_pos_limits = RewTerm( - func=mdp.joint_pos_limits_penalty_ratio, - weight=-0.25, - params={ - "threshold": 0.98, - "gear_ratio": { - ".*_waist.*": 67.5, - ".*_upper_arm.*": 67.5, - "pelvis": 67.5, - ".*_lower_arm": 45.0, - ".*_thigh:0": 45.0, - ".*_thigh:1": 135.0, - ".*_thigh:2": 45.0, - ".*_shin": 90.0, - ".*_foot.*": 22.5, - }, - }, - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - # (1) Terminate if the episode length is exceeded - time_out = DoneTerm(func=mdp.time_out, time_out=True) - # (2) Terminate if the robot falls - torso_height = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.8}) - - -@configclass -class HumanoidEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the MuJoCo-style Humanoid walking environment.""" - - # Scene settings - scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=5.0, clone_in_fabric=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 2 - self.episode_length_s = 16.0 - # simulation settings - self.sim: SimulationCfg = SimulationCfg( - dt=1 / 120.0, - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=80, - nconmax=25, - ls_iterations=15, - cone="pyramidal", - update_data_interval=2, - impratio=1, - integrator="implicitfast", - ), - num_substeps=2, - debug_mode=False, - ), - ) - # self.sim.dt = 1 / 120.0 - self.sim.render_interval = self.decimation - # default friction material - self.sim.physics_material.static_friction = 1.0 - self.sim.physics_material.dynamic_friction = 1.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py index 9ddf530c28e0..436c1da089b6 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py @@ -3,9 +3,36 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Velocity locomotion experimental task registrations (manager-based).""" +"""Velocity locomotion experimental task registrations (manager-based). + +The per-robot ``*-Warp-v0`` variants reuse the stable flat cfgs and only +disable the randomization events that have no warp twins yet (see +:func:`disable_unsupported_randomization_events`). Once those twins exist, +the variants can be dropped in favor of ``--frontend warp`` on the stable +task ids. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING from isaaclab_experimental.envs.frontend import register_mdp_route +if TYPE_CHECKING: + from isaaclab.envs import ManagerBasedRLEnvCfg + # Warp twins for the stable velocity MDP terms live in this package's ``mdp``. register_mdp_route("isaaclab_tasks.core.velocity", f"{__name__}.mdp") + + +def disable_unsupported_randomization_events(cfg: ManagerBasedRLEnvCfg) -> None: + """Disable stable randomization events that have no warp twins yet. + + The warp event manager invokes term functions with a Warp env mask, and no + warp twins exist yet for the rigid-body material/mass randomization events. + A stable term on a warp manager is a hard error at adaptation time, so the + warp task variants disable these terms until twins are available. + """ + for name in ("physics_material", "add_base_mass"): + if getattr(cfg.events, name, None) is not None: + setattr(cfg.events, name, None) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py index f213286d0cfb..d58290799424 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py @@ -3,58 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable Unitree A1 flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import UnitreeA1RoughEnvCfg +from isaaclab_tasks.contrib.velocity.config.a1.flat_env_cfg import UnitreeA1FlatEnvCfg as _StableUnitreeA1FlatEnvCfg +from isaaclab_tasks.contrib.velocity.config.a1.flat_env_cfg import ( + UnitreeA1FlatEnvCfg_PLAY as _StableUnitreeA1FlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class UnitreeA1FlatEnvCfg(UnitreeA1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=60, - nconmax=30, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class UnitreeA1FlatEnvCfg(_StableUnitreeA1FlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): - # post init of parent super().__post_init__() + disable_unsupported_randomization_events(self) - # override rewards - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 0.25 - - # change terrain to flat - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - # no height scan - # self.scene.height_scanner = None - # self.observations.policy.height_scan = None - # no terrain curriculum - self.curriculum.terrain_levels = None +@configclass +class UnitreeA1FlatEnvCfg_PLAY(_StableUnitreeA1FlatEnvCfg_PLAY): + """Play variant of :class:`UnitreeA1FlatEnvCfg` for the warp runtime.""" -class UnitreeA1FlatEnvCfg_PLAY(UnitreeA1FlatEnvCfg): - def __post_init__(self) -> None: - # post init of parent + def __post_init__(self): super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing event - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py deleted file mode 100644 index ee0f236043a2..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/rough_env_cfg.py +++ /dev/null @@ -1,91 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - TerminationsCfg, -) - -from isaaclab_assets.robots.unitree import UNITREE_A1_CFG # isort: skip - - -class TerminationsCfg_A1(TerminationsCfg): - base_too_low = DoneTerm(func=mdp.root_height_below_minimum, params={"minimum_height": 0.2}) - - -@configclass -class UnitreeA1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - terminations: TerminationsCfg_A1 = TerminationsCfg_A1() - - def __post_init__(self): - # post init of parent - super().__post_init__() - - self.scene.robot = UNITREE_A1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 - - # reduce action scale - self.actions.joint_pos.scale = 0.25 - - # event - self.events.push_robot = None - # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation - # self.events.add_base_mass.params["mass_distribution_params"] = (-1.0, 3.0) - # self.events.add_base_mass.params["asset_cfg"].body_names = "trunk" - self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - - # rewards - self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" - self.rewards.feet_air_time.weight = 0.01 - self.rewards.undesired_contacts.params["sensor_cfg"].body_names = ".*thigh" - self.rewards.dof_torques_l2.weight = -0.0002 - self.rewards.track_lin_vel_xy_exp.weight = 1.5 - self.rewards.track_ang_vel_z_exp.weight = 0.75 - self.rewards.dof_acc_l2.weight = -2.5e-7 - self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk" - - -@configclass -class UnitreeA1RoughEnvCfg_PLAY(UnitreeA1RoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # spawn the robot randomly in the grid (instead of their terrain levels) - self.scene.terrain.max_init_terrain_level = None - # reduce the number of terrains to save memory - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing event - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py index a5c825bf2e98..900d87e64227 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py @@ -3,58 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable AnymalB flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import AnymalBRoughEnvCfg +from isaaclab_tasks.contrib.velocity.config.anymal_b.flat_env_cfg import AnymalBFlatEnvCfg as _StableAnymalBFlatEnvCfg +from isaaclab_tasks.contrib.velocity.config.anymal_b.flat_env_cfg import ( + AnymalBFlatEnvCfg_PLAY as _StableAnymalBFlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class AnymalBFlatEnvCfg(AnymalBRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=75, - nconmax=15, - cone="elliptic", - impratio=100, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class AnymalBFlatEnvCfg(_StableAnymalBFlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): - # post init of parent super().__post_init__() + disable_unsupported_randomization_events(self) - # override rewards - self.rewards.flat_orientation_l2.weight = -5.0 - self.rewards.dof_torques_l2.weight = -2.5e-5 - self.rewards.feet_air_time.weight = 0.5 - # change terrain to flat - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - # no height scan - self.scene.height_scanner = None - self.observations.policy.height_scan = None - # no terrain curriculum - self.curriculum.terrain_levels = None - - -class AnymalBFlatEnvCfg_PLAY(AnymalBFlatEnvCfg): - def __post_init__(self) -> None: - # post init of parent - super().__post_init__() - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing event - self.events.base_external_force_torque = None - self.events.push_robot = None +@configclass +class AnymalBFlatEnvCfg_PLAY(_StableAnymalBFlatEnvCfg_PLAY): + """Play variant of :class:`AnymalBFlatEnvCfg` for the warp runtime.""" + + def __post_init__(self): + super().__post_init__() + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py deleted file mode 100644 index 3a7d80af470f..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/rough_env_cfg.py +++ /dev/null @@ -1,34 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -from isaaclab_assets import ANYMAL_B_CFG # isort: skip - - -@configclass -class AnymalBRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = ANYMAL_B_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.manager_call_max_mode = {"Scene": 1} - - -@configclass -class AnymalBRoughEnvCfg_PLAY(AnymalBRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py index 3cc348a97675..edb8ffd7a90e 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py @@ -3,50 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable AnymalC flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import AnymalCRoughEnvCfg +from isaaclab_tasks.contrib.velocity.config.anymal_c.flat_env_cfg import AnymalCFlatEnvCfg as _StableAnymalCFlatEnvCfg +from isaaclab_tasks.contrib.velocity.config.anymal_c.flat_env_cfg import ( + AnymalCFlatEnvCfg_PLAY as _StableAnymalCFlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class AnymalCFlatEnvCfg(AnymalCRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=120, - nconmax=15, - cone="elliptic", - impratio=100, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class AnymalCFlatEnvCfg(_StableAnymalCFlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): - # post init of parent super().__post_init__() + disable_unsupported_randomization_events(self) - # override rewards - self.rewards.flat_orientation_l2.weight = -5.0 - self.rewards.dof_torques_l2.weight = -2.5e-5 - self.rewards.feet_air_time.weight = 0.5 - # change terrain to flat - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - # no terrain curriculum - self.curriculum.terrain_levels = None +@configclass +class AnymalCFlatEnvCfg_PLAY(_StableAnymalCFlatEnvCfg_PLAY): + """Play variant of :class:`AnymalCFlatEnvCfg` for the warp runtime.""" -class AnymalCFlatEnvCfg_PLAY(AnymalCFlatEnvCfg): - def __post_init__(self) -> None: + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py deleted file mode 100644 index 1d2f2676c64a..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/rough_env_cfg.py +++ /dev/null @@ -1,40 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets.robots.anymal import ANYMAL_C_CFG # isort: skip - - -@configclass -class AnymalCRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - # switch robot to anymal-c - self.scene.robot = ANYMAL_C_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.robot.actuators["legs"].armature = 0.01 - self.manager_call_max_mode = {"Scene": 1} - - -@configclass -class AnymalCRoughEnvCfg_PLAY(AnymalCRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py index 3722de03ed4e..e54ed0b4d6ca 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py @@ -12,31 +12,6 @@ # Register Gym environments. ## -# Rough env disabled: requires isaaclab_physx which is not yet available on dev/newton. -# The package exists on upstream/develop (commit 308400f1d35) but has not been merged. -# Re-enable once dev/newton picks up isaaclab_physx. -# gym.register( -# id="Isaac-Velocity-Rough-AnymalD-Warp-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:AnymalDRoughEnvCfg", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDRoughPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", -# }, -# ) - -# gym.register( -# id="Isaac-Velocity-Rough-AnymalD-Warp-Play-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:AnymalDRoughEnvCfg_PLAY", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDRoughPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", -# }, -# ) - gym.register( id="Isaac-Velocity-Flat-AnymalD-Warp-v0", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py index 702443e815e2..ca010dffb13c 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py @@ -3,44 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable AnymalD flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import AnymalDRoughEnvCfg +from isaaclab_tasks.core.velocity.config.anymal_d.flat_env_cfg import AnymalDFlatEnvCfg as _StableAnymalDFlatEnvCfg +from isaaclab_tasks.core.velocity.config.anymal_d.flat_env_cfg import ( + AnymalDFlatEnvCfg_PLAY as _StableAnymalDFlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class AnymalDFlatEnvCfg(AnymalDRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=60, - nconmax=25, - cone="elliptic", - impratio=100.0, - ), - num_substeps=1, - debug_mode=False, - ) - ) +class AnymalDFlatEnvCfg(_StableAnymalDFlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): super().__post_init__() - self.rewards.flat_orientation_l2.weight = -5.0 - self.rewards.dof_torques_l2.weight = -2.5e-5 - self.rewards.feet_air_time.weight = 0.5 - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None + disable_unsupported_randomization_events(self) + +@configclass +class AnymalDFlatEnvCfg_PLAY(_StableAnymalDFlatEnvCfg_PLAY): + """Play variant of :class:`AnymalDFlatEnvCfg` for the warp runtime.""" -class AnymalDFlatEnvCfg_PLAY(AnymalDFlatEnvCfg): - def __post_init__(self) -> None: + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py deleted file mode 100644 index 71f49edd2e68..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/rough_env_cfg.py +++ /dev/null @@ -1,37 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets.robots.anymal import ANYMAL_D_CFG # isort: skip - - -@configclass -class AnymalDRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = ANYMAL_D_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.manager_call_max_mode = {"Scene": 1} - - -@configclass -class AnymalDRoughEnvCfg_PLAY(AnymalDRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py index 818c7aa30a1e..4b42afa8a3a5 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py @@ -3,43 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable Cassie flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import CassieRoughEnvCfg +from isaaclab_tasks.core.velocity.config.cassie.flat_env_cfg import CassieFlatEnvCfg as _StableCassieFlatEnvCfg +from isaaclab_tasks.core.velocity.config.cassie.flat_env_cfg import ( + CassieFlatEnvCfg_PLAY as _StableCassieFlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class CassieFlatEnvCfg(CassieRoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=52, - nconmax=15, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class CassieFlatEnvCfg(_StableCassieFlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): super().__post_init__() - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 5.0 - self.rewards.joint_deviation_hip.params["asset_cfg"].joint_names = ["hip_rotation_.*"] - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None + disable_unsupported_randomization_events(self) + +@configclass +class CassieFlatEnvCfg_PLAY(_StableCassieFlatEnvCfg_PLAY): + """Play variant of :class:`CassieFlatEnvCfg` for the warp runtime.""" -class CassieFlatEnvCfg_PLAY(CassieFlatEnvCfg): - def __post_init__(self) -> None: + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py deleted file mode 100644 index 2fc44ea36cdc..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/rough_env_cfg.py +++ /dev/null @@ -1,96 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - RewardsCfg, -) - -from isaaclab_assets.robots.cassie import CASSIE_CFG # isort: skip - - -@configclass -class CassieRewardsCfg(RewardsCfg): - termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) - feet_air_time = RewTerm( - func=mdp.feet_air_time_positive_biped, - weight=2.5, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*toe"), - "command_name": "base_velocity", - "threshold": 0.3, - }, - ) - joint_deviation_hip = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["hip_abduction_.*", "hip_rotation_.*"])}, - ) - joint_deviation_toes = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=["toe_joint_.*"])}, - ) - dof_pos_limits = RewTerm( - func=mdp.joint_pos_limits, - weight=-1.0, - params={"asset_cfg": SceneEntityCfg("robot", joint_names="toe_joint_.*")}, - ) - - -@configclass -class CassieRoughEnvCfg(LocomotionVelocityRoughEnvCfg): - rewards: CassieRewardsCfg = CassieRewardsCfg() - - def __post_init__(self): - super().__post_init__() - self.scene.robot = CASSIE_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.actions.joint_pos.scale = 0.5 - self.events.push_robot = None - # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation - # self.events.add_base_mass = None - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*pelvis"] - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.terminations.base_contact.params["sensor_cfg"].body_names = [".*pelvis"] - self.rewards.undesired_contacts = None - self.rewards.dof_torques_l2.weight = -5.0e-6 - self.rewards.track_lin_vel_xy_exp.weight = 2.0 - self.rewards.track_ang_vel_z_exp.weight = 1.0 - self.rewards.action_rate_l2.weight *= 1.5 - self.rewards.dof_acc_l2.weight *= 1.5 - - -@configclass -class CassieRoughEnvCfg_PLAY(CassieRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py index f49e103f431a..47d6909f9356 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py @@ -12,28 +12,6 @@ # Register Gym environments. ## -# gym.register( -# id="Isaac-Velocity-Rough-G1-Warp-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:G1RoughEnvCfg", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1RoughPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", -# }, -# ) - - -# gym.register( -# id="Isaac-Velocity-Rough-G1-Warp-Play-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:G1RoughEnvCfg_PLAY", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1RoughPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", -# }, -# ) gym.register( id="Isaac-Velocity-Flat-G1-Warp-v0", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py index e99dd95ff82f..9c2011fe13c8 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py @@ -3,56 +3,31 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable G1 flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import G1RoughEnvCfg +from isaaclab_tasks.core.velocity.config.g1.flat_env_cfg import G1FlatEnvCfg as _StableG1FlatEnvCfg +from isaaclab_tasks.core.velocity.config.g1.flat_env_cfg import G1FlatEnvCfg_PLAY as _StableG1FlatEnvCfg_PLAY + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class G1FlatEnvCfg(G1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=95, - nconmax=10, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class G1FlatEnvCfg(_StableG1FlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): super().__post_init__() - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - self.rewards.track_ang_vel_z_exp.weight = 1.0 - self.rewards.lin_vel_z_l2.weight = -0.2 - self.rewards.action_rate_l2.weight = -0.005 - self.rewards.dof_acc_l2.weight = -1.0e-7 - self.rewards.feet_air_time.weight = 0.75 - self.rewards.feet_air_time.params["threshold"] = 0.4 - self.rewards.dof_torques_l2.weight = -2.0e-6 - self.rewards.dof_torques_l2.params["asset_cfg"] = SceneEntityCfg( - "robot", joint_names=[".*_hip_.*", ".*_knee_joint"] - ) - self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (-0.5, 0.5) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - - -class G1FlatEnvCfg_PLAY(G1FlatEnvCfg): - def __post_init__(self) -> None: + disable_unsupported_randomization_events(self) + + +@configclass +class G1FlatEnvCfg_PLAY(_StableG1FlatEnvCfg_PLAY): + """Play variant of :class:`G1FlatEnvCfg` for the warp runtime.""" + + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py deleted file mode 100644 index 7f9d12d0f201..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/rough_env_cfg.py +++ /dev/null @@ -1,178 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - RewardsCfg, -) - -## -# Pre-defined configs -## -from isaaclab_assets import G1_MINIMAL_CFG # isort: skip - - -@configclass -class G1Rewards(RewardsCfg): - """Reward terms for the MDP.""" - - termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) - track_lin_vel_xy_exp = RewTerm( - func=mdp.track_lin_vel_xy_yaw_frame_exp, - weight=1.0, - params={"command_name": "base_velocity", "std": 0.5}, - ) - track_ang_vel_z_exp = RewTerm( - func=mdp.track_ang_vel_z_world_exp, weight=2.0, params={"command_name": "base_velocity", "std": 0.5} - ) - feet_air_time = RewTerm( - func=mdp.feet_air_time_positive_biped, - weight=0.25, - params={ - "command_name": "base_velocity", - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*_ankle_roll_link"), - "threshold": 0.4, - }, - ) - feet_slide = RewTerm( - func=mdp.feet_slide, - weight=-0.1, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*_ankle_roll_link"), - "asset_cfg": SceneEntityCfg("robot", body_names=".*_ankle_roll_link"), - }, - ) - dof_pos_limits = RewTerm( - func=mdp.joint_pos_limits, - weight=-1.0, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_ankle_pitch_joint", ".*_ankle_roll_joint"])}, - ) - joint_deviation_hip = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.1, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_hip_yaw_joint", ".*_hip_roll_joint"])}, - ) - joint_deviation_arms = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.1, - params={ - "asset_cfg": SceneEntityCfg( - "robot", - joint_names=[ - ".*_shoulder_pitch_joint", - ".*_shoulder_roll_joint", - ".*_shoulder_yaw_joint", - ".*_elbow_pitch_joint", - ".*_elbow_roll_joint", - ], - ) - }, - ) - joint_deviation_fingers = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.05, - params={ - "asset_cfg": SceneEntityCfg( - "robot", - joint_names=[ - ".*_five_joint", - ".*_three_joint", - ".*_six_joint", - ".*_four_joint", - ".*_zero_joint", - ".*_one_joint", - ".*_two_joint", - ], - ) - }, - ) - joint_deviation_torso = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.1, - params={"asset_cfg": SceneEntityCfg("robot", joint_names="torso_joint")}, - ) - - -@configclass -class G1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - rewards: G1Rewards = G1Rewards() - - def __post_init__(self): - super().__post_init__() - self.scene.robot = G1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.events.push_robot = None - # TODO: TEMPORARILY DISABLED - adding this causes NaNs in the simulation - # self.events.add_base_mass = None - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.base_external_force_torque.params["asset_cfg"].body_names = ["torso_link"] - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - - # Rewards - self.rewards.lin_vel_z_l2.weight = 0.0 - self.rewards.undesired_contacts = None - self.rewards.flat_orientation_l2.weight = -1.0 - self.rewards.action_rate_l2.weight = -0.005 - self.rewards.dof_acc_l2.weight = -1.25e-7 - self.rewards.dof_acc_l2.params["asset_cfg"] = SceneEntityCfg( - "robot", joint_names=[".*_hip_.*", ".*_knee_joint"] - ) - self.rewards.dof_torques_l2.weight = -1.5e-7 - self.rewards.dof_torques_l2.params["asset_cfg"] = SceneEntityCfg( - "robot", joint_names=[".*_hip_.*", ".*_knee_joint", ".*_ankle_.*"] - ) - - # Commands - self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (-0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - - # terminations - self.terminations.base_contact.params["sensor_cfg"].body_names = "torso_link" - - -@configclass -class G1RoughEnvCfg_PLAY(G1RoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.episode_length_s = 40.0 - # spawn the robot randomly in the grid (instead of their terrain levels) - self.scene.terrain.max_init_terrain_level = None - # reduce the number of terrains to save memory - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - - self.commands.base_velocity.ranges.lin_vel_x = (1.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - self.commands.base_velocity.ranges.heading = (0.0, 0.0) - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py index dd4012882075..c54355196dab 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py @@ -3,44 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable Unitree Go1 flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import UnitreeGo1RoughEnvCfg +from isaaclab_tasks.contrib.velocity.config.go1.flat_env_cfg import UnitreeGo1FlatEnvCfg as _StableUnitreeGo1FlatEnvCfg +from isaaclab_tasks.contrib.velocity.config.go1.flat_env_cfg import ( + UnitreeGo1FlatEnvCfg_PLAY as _StableUnitreeGo1FlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class UnitreeGo1FlatEnvCfg(UnitreeGo1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=60, - nconmax=25, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class UnitreeGo1FlatEnvCfg(_StableUnitreeGo1FlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): super().__post_init__() - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 0.25 - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None + disable_unsupported_randomization_events(self) + +@configclass +class UnitreeGo1FlatEnvCfg_PLAY(_StableUnitreeGo1FlatEnvCfg_PLAY): + """Play variant of :class:`UnitreeGo1FlatEnvCfg` for the warp runtime.""" -class UnitreeGo1FlatEnvCfg_PLAY(UnitreeGo1FlatEnvCfg): - def __post_init__(self) -> None: + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py deleted file mode 100644 index cb3a602394a6..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/rough_env_cfg.py +++ /dev/null @@ -1,61 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -from isaaclab_assets.robots.unitree import UNITREE_GO1_CFG # isort: skip - - -@configclass -class UnitreeGo1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = UNITREE_GO1_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.manager_call_max_mode = {"Scene": 1} - self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 - self.actions.joint_pos.scale = 0.25 - self.events.push_robot = None - self.events.base_external_force_torque.params["asset_cfg"].body_names = "trunk" - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" - self.rewards.feet_air_time.weight = 0.01 - self.rewards.undesired_contacts = None - self.rewards.dof_torques_l2.weight = -0.0002 - self.rewards.track_lin_vel_xy_exp.weight = 1.5 - self.rewards.track_ang_vel_z_exp.weight = 0.75 - self.rewards.dof_acc_l2.weight = -2.5e-7 - self.terminations.base_contact.params["sensor_cfg"].body_names = "trunk" - - -@configclass -class UnitreeGo1RoughEnvCfg_PLAY(UnitreeGo1RoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py index 349cc450ca9f..a54d94dabcc9 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py @@ -3,44 +3,33 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable Unitree Go2 flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import UnitreeGo2RoughEnvCfg +from isaaclab_tasks.core.velocity.config.go2.flat_env_cfg import UnitreeGo2FlatEnvCfg as _StableUnitreeGo2FlatEnvCfg +from isaaclab_tasks.core.velocity.config.go2.flat_env_cfg import ( + UnitreeGo2FlatEnvCfg_PLAY as _StableUnitreeGo2FlatEnvCfg_PLAY, +) + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class UnitreeGo2FlatEnvCfg(UnitreeGo2RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=65, - nconmax=35, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class UnitreeGo2FlatEnvCfg(_StableUnitreeGo2FlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): super().__post_init__() - self.rewards.flat_orientation_l2.weight = -2.5 - self.rewards.feet_air_time.weight = 0.25 - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None + disable_unsupported_randomization_events(self) + +@configclass +class UnitreeGo2FlatEnvCfg_PLAY(_StableUnitreeGo2FlatEnvCfg_PLAY): + """Play variant of :class:`UnitreeGo2FlatEnvCfg` for the warp runtime.""" -class UnitreeGo2FlatEnvCfg_PLAY(UnitreeGo2FlatEnvCfg): - def __post_init__(self) -> None: + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py deleted file mode 100644 index a25748da9885..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/rough_env_cfg.py +++ /dev/null @@ -1,60 +0,0 @@ -# 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 - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import LocomotionVelocityRoughEnvCfg - -from isaaclab_assets.robots.unitree import UNITREE_GO2_CFG # isort: skip - - -@configclass -class UnitreeGo2RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.robot = UNITREE_GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.scene.terrain.terrain_generator.sub_terrains["boxes"].grid_height_range = (0.025, 0.1) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_range = (0.01, 0.06) - self.scene.terrain.terrain_generator.sub_terrains["random_rough"].noise_step = 0.01 - self.actions.joint_pos.scale = 0.25 - self.events.push_robot = None - self.events.base_external_force_torque.params["asset_cfg"].body_names = "base" - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.rewards.feet_air_time.params["sensor_cfg"].body_names = ".*_foot" - self.rewards.feet_air_time.weight = 0.01 - self.rewards.undesired_contacts = None - self.rewards.dof_torques_l2.weight = -0.0002 - self.rewards.track_lin_vel_xy_exp.weight = 1.5 - self.rewards.track_ang_vel_z_exp.weight = 0.75 - self.rewards.dof_acc_l2.weight = -2.5e-7 - self.terminations.base_contact.params["sensor_cfg"].body_names = "base" - - -@configclass -class UnitreeGo2RoughEnvCfg_PLAY(UnitreeGo2RoughEnvCfg): - def __post_init__(self): - super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.scene.terrain.max_init_terrain_level = None - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py index c731af7ca986..07deee5ee458 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py @@ -12,28 +12,6 @@ # Register Gym environments. ## -# gym.register( -# id="Isaac-Velocity-Rough-H1-Warp-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:H1RoughEnvCfg", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1RoughPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", -# }, -# ) - -# gym.register( -# id="Isaac-Velocity-Rough-H1-Warp-Play-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.rough_env_cfg:H1RoughEnvCfg_PLAY", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1RoughPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_rough_ppo_cfg.yaml", -# }, -# ) - gym.register( id="Isaac-Velocity-Flat-H1-Warp-v0", entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py index a7021343464a..088d5786b223 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py @@ -3,44 +3,31 @@ # # SPDX-License-Identifier: BSD-3-Clause -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg +"""Warp variants of the stable H1 flat velocity task configuration.""" -from isaaclab.sim import SimulationCfg from isaaclab.utils.configclass import configclass -from .rough_env_cfg import H1RoughEnvCfg +from isaaclab_tasks.core.velocity.config.h1.flat_env_cfg import H1FlatEnvCfg as _StableH1FlatEnvCfg +from isaaclab_tasks.core.velocity.config.h1.flat_env_cfg import H1FlatEnvCfg_PLAY as _StableH1FlatEnvCfg_PLAY + +from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( + disable_unsupported_randomization_events, +) @configclass -class H1FlatEnvCfg(H1RoughEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=65, - nconmax=15, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) +class H1FlatEnvCfg(_StableH1FlatEnvCfg): + """Stable flat cfg with the randomization events lacking warp twins disabled.""" def __post_init__(self): super().__post_init__() - self.scene.terrain.terrain_type = "plane" - self.scene.terrain.terrain_generator = None - self.curriculum.terrain_levels = None - self.rewards.feet_air_time.weight = 1.0 - self.rewards.feet_air_time.params["threshold"] = 0.6 + disable_unsupported_randomization_events(self) + +@configclass +class H1FlatEnvCfg_PLAY(_StableH1FlatEnvCfg_PLAY): + """Play variant of :class:`H1FlatEnvCfg` for the warp runtime.""" -class H1FlatEnvCfg_PLAY(H1FlatEnvCfg): - def __post_init__(self) -> None: + def __post_init__(self): super().__post_init__() - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.observations.policy.enable_corruption = False - self.events.base_external_force_torque = None - self.events.push_robot = None + disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py deleted file mode 100644 index 1b65e018c9e4..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/rough_env_cfg.py +++ /dev/null @@ -1,131 +0,0 @@ -# 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 - -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg - -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp -from isaaclab_tasks_experimental.manager_based.locomotion.velocity.velocity_env_cfg import ( - LocomotionVelocityRoughEnvCfg, - RewardsCfg, -) - -## -# Pre-defined configs -## -from isaaclab_assets import H1_MINIMAL_CFG # isort: skip - - -@configclass -class H1Rewards(RewardsCfg): - """Reward terms for the MDP.""" - - termination_penalty = RewTerm(func=mdp.is_terminated, weight=-200.0) - lin_vel_z_l2 = None - track_lin_vel_xy_exp = RewTerm( - func=mdp.track_lin_vel_xy_yaw_frame_exp, - weight=1.0, - params={"command_name": "base_velocity", "std": 0.5}, - ) - track_ang_vel_z_exp = RewTerm( - func=mdp.track_ang_vel_z_world_exp, weight=1.0, params={"command_name": "base_velocity", "std": 0.5} - ) - feet_air_time = RewTerm( - func=mdp.feet_air_time_positive_biped, - weight=0.25, - params={ - "command_name": "base_velocity", - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*ankle_link"), - "threshold": 0.4, - }, - ) - feet_slide = RewTerm( - func=mdp.feet_slide, - weight=-0.25, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*ankle_link"), - "asset_cfg": SceneEntityCfg("robot", body_names=".*ankle_link"), - }, - ) - dof_pos_limits = RewTerm( - func=mdp.joint_pos_limits, weight=-1.0, params={"asset_cfg": SceneEntityCfg("robot", joint_names=".*_ankle")} - ) - joint_deviation_hip = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_hip_yaw", ".*_hip_roll"])}, - ) - joint_deviation_arms = RewTerm( - func=mdp.joint_deviation_l1, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", joint_names=[".*_shoulder_.*", ".*_elbow"])}, - ) - joint_deviation_torso = RewTerm( - func=mdp.joint_deviation_l1, weight=-0.1, params={"asset_cfg": SceneEntityCfg("robot", joint_names="torso")} - ) - - -@configclass -class H1RoughEnvCfg(LocomotionVelocityRoughEnvCfg): - rewards: H1Rewards = H1Rewards() - - def __post_init__(self): - super().__post_init__() - self.scene.robot = H1_MINIMAL_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - self.events.push_robot = None - self.events.reset_robot_joints.params["position_range"] = (1.0, 1.0) - self.events.base_external_force_torque.params["asset_cfg"].body_names = [".*torso_link"] - self.events.reset_base.params = { - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (0.0, 0.0), - "y": (0.0, 0.0), - "z": (0.0, 0.0), - "roll": (0.0, 0.0), - "pitch": (0.0, 0.0), - "yaw": (0.0, 0.0), - }, - } - self.events.base_com = None - self.rewards.undesired_contacts = None - self.rewards.flat_orientation_l2.weight = -1.0 - self.rewards.dof_torques_l2.weight = 0.0 - self.rewards.action_rate_l2.weight = -0.005 - self.rewards.dof_acc_l2.weight = -1.25e-7 - self.commands.base_velocity.ranges.lin_vel_x = (0.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - self.terminations.base_contact.params["sensor_cfg"].body_names = ".*torso_link" - - -@configclass -class H1RoughEnvCfg_PLAY(H1RoughEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - self.episode_length_s = 40.0 - # spawn the robot randomly in the grid (instead of their terrain levels) - self.scene.terrain.max_init_terrain_level = None - # reduce the number of terrains to save memory - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.num_rows = 5 - self.scene.terrain.terrain_generator.num_cols = 5 - self.scene.terrain.terrain_generator.curriculum = False - - self.commands.base_velocity.ranges.lin_vel_x = (1.0, 1.0) - self.commands.base_velocity.ranges.lin_vel_y = (0.0, 0.0) - self.commands.base_velocity.ranges.ang_vel_z = (-1.0, 1.0) - self.commands.base_velocity.ranges.heading = (0.0, 0.0) - # disable randomization for play - self.observations.policy.enable_corruption = False - # remove random pushing - self.events.base_external_force_torque = None - self.events.push_robot = None diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py deleted file mode 100644 index 52d53c3db268..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/velocity_env_cfg.py +++ /dev/null @@ -1,296 +0,0 @@ -# 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 - -import math -from dataclasses import MISSING - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg, AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import CurriculumTermCfg as CurrTerm -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sensors import ContactSensorCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR, ISAACLAB_NUCLEUS_DIR -from isaaclab.utils.configclass import configclass -from isaaclab.utils.noise import UniformNoiseCfg as Unoise - -import isaaclab_tasks_experimental.manager_based.locomotion.velocity.mdp as mdp - -## -# Pre-defined configs -## -from isaaclab.terrains.config.rough import ROUGH_TERRAINS_CFG # isort: skip - - -## -# Scene definition -## - - -@configclass -class MySceneCfg(InteractiveSceneCfg): - """Configuration for the terrain scene with a legged robot.""" - - # ground terrain - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="generator", - terrain_generator=ROUGH_TERRAINS_CFG, - max_init_terrain_level=5, - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg( - friction_combine_mode="multiply", - restitution_combine_mode="multiply", - static_friction=1.0, - dynamic_friction=1.0, - ), - visual_material=sim_utils.MdlFileCfg( - mdl_path=f"{ISAACLAB_NUCLEUS_DIR}/Materials/TilesMarbleSpiderWhiteBrickBondHoned/TilesMarbleSpiderWhiteBrickBondHoned.mdl", - project_uvw=True, - texture_scale=(0.25, 0.25), - ), - debug_vis=False, - ) - # robots - robot: ArticulationCfg = MISSING - # sensors - contact_forces = ContactSensorCfg( - prim_path="{ENV_REGEX_NS}/Robot/.*", - filter_prim_paths_expr=[], - history_length=3, - track_air_time=True, - ) - # lights - sky_light = AssetBaseCfg( - prim_path="/World/skyLight", - spawn=sim_utils.DomeLightCfg( - intensity=750.0, - texture_file=f"{ISAAC_NUCLEUS_DIR}/Materials/Textures/Skies/PolyHaven/kloofendal_43d_clear_puresky_4k.hdr", - ), - ) - - -## -# MDP settings -## - - -@configclass -class CommandsCfg: - """Command specifications for the MDP.""" - - base_velocity = mdp.UniformVelocityCommandCfg( - asset_name="robot", - resampling_time_range=(10.0, 10.0), - rel_standing_envs=0.02, - rel_heading_envs=1.0, - heading_command=True, - heading_control_stiffness=0.5, - debug_vis=True, - ranges=mdp.UniformVelocityCommandCfg.Ranges( - lin_vel_x=(-1.0, 1.0), lin_vel_y=(-1.0, 1.0), ang_vel_z=(-1.0, 1.0), heading=(-math.pi, math.pi) - ), - ) - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - joint_pos = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True) - - -@configclass -class PolicyCfg(ObsGroup): - """Observations for policy group.""" - - # observation terms (order preserved) - base_lin_vel = ObsTerm(func=mdp.base_lin_vel, noise=Unoise(n_min=-0.1, n_max=0.1)) - base_ang_vel = ObsTerm(func=mdp.base_ang_vel, noise=Unoise(n_min=-0.2, n_max=0.2)) - projected_gravity = ObsTerm( - func=mdp.projected_gravity, - noise=Unoise(n_min=-0.05, n_max=0.05), - ) - velocity_commands = ObsTerm(func=mdp.generated_commands, params={"command_name": "base_velocity"}) - joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) - joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-1.5, n_max=1.5)) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = True - self.concatenate_terms = True - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - # FIXME(warp-migration): COM randomization in exp manager-based locomotion currently causes - # NaNs and is temporarily disabled. - # base_com = EventTerm( - # func=mdp.randomize_rigid_body_com, - # mode="startup", - # params={ - # "asset_cfg": SceneEntityCfg("robot", body_names="base"), - # "com_range": {"x": (-0.05, 0.05), "y": (-0.05, 0.05), "z": (-0.01, 0.01)}, - # }, - # ) - base_com = None - - # reset - base_external_force_torque = EventTerm( - func=mdp.apply_external_force_torque, - mode="reset", - params={ - "asset_cfg": SceneEntityCfg("robot", body_names="base"), - "force_range": (0.0, 0.0), - "torque_range": (-0.0, 0.0), - }, - ) - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={ - "pose_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5), "yaw": (-3.14, 3.14)}, - "velocity_range": { - "x": (-0.5, 0.5), - "y": (-0.5, 0.5), - "z": (-0.5, 0.5), - "roll": (-0.5, 0.5), - "pitch": (-0.5, 0.5), - "yaw": (-0.5, 0.5), - }, - }, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_scale, - mode="reset", - params={ - "position_range": (0.5, 1.5), - "velocity_range": (0.0, 0.0), - }, - ) - - # interval - push_robot = EventTerm( - func=mdp.push_by_setting_velocity, - mode="interval", - interval_range_s=(10.0, 15.0), - params={"velocity_range": {"x": (-0.5, 0.5), "y": (-0.5, 0.5)}}, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # -- task - track_lin_vel_xy_exp = RewTerm( - func=mdp.track_lin_vel_xy_exp, weight=1.0, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} - ) - track_ang_vel_z_exp = RewTerm( - func=mdp.track_ang_vel_z_exp, weight=0.5, params={"command_name": "base_velocity", "std": math.sqrt(0.25)} - ) - # -- penalties - lin_vel_z_l2 = RewTerm(func=mdp.lin_vel_z_l2, weight=-2.0) - ang_vel_xy_l2 = RewTerm(func=mdp.ang_vel_xy_l2, weight=-0.05) - dof_torques_l2 = RewTerm(func=mdp.joint_torques_l2, weight=-1.0e-5) - dof_acc_l2 = RewTerm(func=mdp.joint_acc_l2, weight=-2.5e-7) - action_rate_l2 = RewTerm(func=mdp.action_rate_l2, weight=-0.01) - feet_air_time = RewTerm( - func=mdp.feet_air_time, - weight=0.125, - params={ - "sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*FOOT"), - "command_name": "base_velocity", - "threshold": 0.5, - }, - ) - undesired_contacts = RewTerm( - func=mdp.undesired_contacts, - weight=-1.0, - params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names=".*THIGH"), "threshold": 1.0}, - ) - # -- optional penalties - flat_orientation_l2 = RewTerm(func=mdp.flat_orientation_l2, weight=0.0) - dof_pos_limits = RewTerm(func=mdp.joint_pos_limits, weight=0.0) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - time_out = DoneTerm(func=mdp.time_out, time_out=True) - base_contact = DoneTerm( - func=mdp.illegal_contact, - params={"sensor_cfg": SceneEntityCfg("contact_forces", body_names="base"), "threshold": 1.0}, - ) - - -@configclass -class CurriculumCfg: - """Curriculum terms for the MDP.""" - - terrain_levels = CurrTerm(func=mdp.terrain_levels_vel) - - -## -# Environment configuration -## - - -@configclass -class LocomotionVelocityRoughEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the locomotion velocity-tracking environment.""" - - # Scene settings - scene: MySceneCfg = MySceneCfg(num_envs=4096, env_spacing=2.5, replicate_physics=True) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - commands: CommandsCfg = CommandsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - curriculum: CurriculumCfg = CurriculumCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 4 - self.episode_length_s = 20.0 - # simulation settings - self.sim.dt = 1.0 / 200.0 - self.sim.render_interval = self.decimation - self.sim.physics_material = self.scene.terrain.physics_material - # update sensor update periods - if self.scene.contact_forces is not None: - self.scene.contact_forces.update_period = self.sim.dt - # check if terrain levels curriculum is enabled - if getattr(self.curriculum, "terrain_levels", None) is not None: - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.curriculum = True - else: - if self.scene.terrain.terrain_generator is not None: - self.scene.terrain.terrain_generator.curriculum = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py index 8589501220cc..09abb3d8aafc 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py @@ -3,7 +3,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Reach experimental task registrations (manager-based).""" +"""Warp MDP twins for the stable Reach tasks. + +There is no separate task registration: run the stable joint-position reach +tasks (``Isaac-Reach-Franka``, ``Isaac-Reach-UR10``) with ``--frontend warp`` +and ``presets=newton_mjwarp``. The IK and OSC variants require controller +action twins that do not exist yet. +""" from isaaclab_experimental.envs.frontend import register_mdp_route diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py deleted file mode 100644 index 460a30569089..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -# 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 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py deleted file mode 100644 index 9f01c7b2e729..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/__init__.py +++ /dev/null @@ -1,41 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.reach.config.franka import agents - -## -# Register Gym environments. -## - -## -# Joint Position Control -## - -gym.register( - id="Isaac-Reach-Franka-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:FrankaReachEnvCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaReachPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Reach-Franka-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:FrankaReachEnvCfg_PLAY", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:FrankaReachPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py deleted file mode 100644 index d6d36afd15f5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/franka/joint_pos_env_cfg.py +++ /dev/null @@ -1,74 +0,0 @@ -# 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 - -import math - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp -from isaaclab_tasks_experimental.manager_based.manipulation.reach.reach_env_cfg import ReachEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets import FRANKA_PANDA_CFG # isort: skip - - -## -# Environment configuration -## - - -@configclass -class FrankaReachEnvCfg(ReachEnvCfg): - sim: SimulationCfg = SimulationCfg( - dt=1 / 60, - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=50, - nconmax=20, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ), - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # switch robot to franka - self.scene.robot = FRANKA_PANDA_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - # override rewards - self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["panda_hand"] - self.rewards.end_effector_position_tracking_fine_grained.params["asset_cfg"].body_names = ["panda_hand"] - self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["panda_hand"] - - # override actions - self.actions.arm_action = mdp.JointPositionActionCfg( - asset_name="robot", joint_names=["panda_joint.*"], scale=0.5, use_default_offset=True - ) - # override command generator body - # end-effector is along z-direction - self.commands.ee_pose.body_name = "panda_hand" - self.commands.ee_pose.ranges.pitch = (math.pi, math.pi) - - -@configclass -class FrankaReachEnvCfg_PLAY(FrankaReachEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py deleted file mode 100644 index cdff71bf6523..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# 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 - -# UR10 env disabled: USD asset has composition errors (broken asset file). -# Fails on both torch baseline and warp with: -# RuntimeError: USD stage has composition errors while loading provided stage -# Re-enable once the UR10 USD asset is fixed. - -# import gymnasium as gym -# from isaaclab_tasks.core.reach.config.ur_10 import agents - -# gym.register( -# id="Isaac-Reach-UR10-Warp-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:UR10ReachEnvCfg", -# "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", -# }, -# ) - -# gym.register( -# id="Isaac-Reach-UR10-Warp-Play-v0", -# entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", -# disable_env_checker=True, -# kwargs={ -# "env_cfg_entry_point": f"{__name__}.joint_pos_env_cfg:UR10ReachEnvCfg_PLAY", -# "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_ppo_cfg.yaml", -# "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UR10ReachPPORunnerCfg", -# "skrl_cfg_entry_point": f"{agents.__name__}:skrl_ppo_cfg.yaml", -# }, -# ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py deleted file mode 100644 index 42104e23b1b2..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/config/ur_10/joint_pos_env_cfg.py +++ /dev/null @@ -1,74 +0,0 @@ -# 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 - -import math - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp -from isaaclab_tasks_experimental.manager_based.manipulation.reach.reach_env_cfg import ReachEnvCfg - -## -# Pre-defined configs -## -from isaaclab_assets import UR10_CFG # isort: skip - - -## -# Environment configuration -## - - -@configclass -class UR10ReachEnvCfg(ReachEnvCfg): - sim: SimulationCfg = SimulationCfg( - physics=NewtonCfg( - solver_cfg=MJWarpSolverCfg( - njmax=50, - nconmax=20, - cone="pyramidal", - impratio=1, - integrator="implicitfast", - ), - num_substeps=1, - debug_mode=False, - ) - ) - - def __post_init__(self): - # post init of parent - super().__post_init__() - - # switch robot to ur10 - self.scene.robot = UR10_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot") - # override events - self.events.reset_robot_joints.params["position_range"] = (0.75, 1.25) - # override rewards - self.rewards.end_effector_position_tracking.params["asset_cfg"].body_names = ["ee_link"] - self.rewards.end_effector_position_tracking_fine_grained.params["asset_cfg"].body_names = ["ee_link"] - self.rewards.end_effector_orientation_tracking.params["asset_cfg"].body_names = ["ee_link"] - # override actions - self.actions.arm_action = mdp.JointPositionActionCfg( - asset_name="robot", joint_names=[".*"], scale=0.5, use_default_offset=True - ) - # override command generator body - # end-effector is along x-direction - self.commands.ee_pose.body_name = "ee_link" - self.commands.ee_pose.ranges.pitch = (math.pi / 2, math.pi / 2) - - -@configclass -class UR10ReachEnvCfg_PLAY(UR10ReachEnvCfg): - def __post_init__(self): - # post init of parent - super().__post_init__() - # make a smaller scene for play - self.scene.num_envs = 50 - self.scene.env_spacing = 2.5 - # disable randomization for play - self.observations.policy.enable_corruption = False diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py deleted file mode 100644 index e83a27e44db5..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/reach_env_cfg.py +++ /dev/null @@ -1,206 +0,0 @@ -# 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 - -from dataclasses import MISSING - -from isaaclab_experimental.managers import ObservationTermCfg as ObsTerm -from isaaclab_experimental.managers import RewardTermCfg as RewTerm -from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_experimental.managers import TerminationTermCfg as DoneTerm - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg, AssetBaseCfg -from isaaclab.envs import ManagerBasedRLEnvCfg -from isaaclab.managers import ActionTermCfg as ActionTerm -from isaaclab.managers import CurriculumTermCfg as CurrTerm -from isaaclab.managers import EventTermCfg as EventTerm -from isaaclab.managers import ObservationGroupCfg as ObsGroup -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.utils.configclass import configclass -from isaaclab.utils.noise import UniformNoiseCfg as Unoise - -import isaaclab_tasks_experimental.manager_based.manipulation.reach.mdp as mdp - -## -# Scene definition -## - - -@configclass -class ReachSceneCfg(InteractiveSceneCfg): - """Configuration for the scene with a robotic arm.""" - - # world - ground = AssetBaseCfg( - prim_path="/World/ground", - spawn=sim_utils.GroundPlaneCfg(), - init_state=AssetBaseCfg.InitialStateCfg(pos=(0.0, 0.0, -1.05)), - ) - - # robots - robot: ArticulationCfg = MISSING - - # lights - light = AssetBaseCfg( - prim_path="/World/light", - spawn=sim_utils.DomeLightCfg(color=(0.75, 0.75, 0.75), intensity=2500.0), - ) - - -## -# MDP settings -## - - -@configclass -class CommandsCfg: - """Command terms for the MDP.""" - - ee_pose = mdp.UniformPoseCommandCfg( - asset_name="robot", - body_name=MISSING, - resampling_time_range=(4.0, 4.0), - debug_vis=True, - ranges=mdp.UniformPoseCommandCfg.Ranges( - pos_x=(0.35, 0.65), - pos_y=(-0.2, 0.2), - pos_z=(0.15, 0.5), - roll=(0.0, 0.0), - pitch=MISSING, # depends on end-effector axis - yaw=(-3.14, 3.14), - ), - ) - - -@configclass -class ActionsCfg: - """Action specifications for the MDP.""" - - arm_action: ActionTerm = MISSING - gripper_action: ActionTerm | None = None - - -@configclass -class ObservationsCfg: - """Observation specifications for the MDP.""" - - @configclass - class PolicyCfg(ObsGroup): - """Observations for policy group.""" - - # observation terms (order preserved) - joint_pos = ObsTerm(func=mdp.joint_pos_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) - joint_vel = ObsTerm(func=mdp.joint_vel_rel, noise=Unoise(n_min=-0.01, n_max=0.01)) - pose_command = ObsTerm(func=mdp.generated_commands, params={"command_name": "ee_pose"}) - actions = ObsTerm(func=mdp.last_action) - - def __post_init__(self): - self.enable_corruption = True - self.concatenate_terms = True - - # observation groups - policy: PolicyCfg = PolicyCfg() - - -@configclass -class EventCfg: - """Configuration for events.""" - - reset_base = EventTerm( - func=mdp.reset_root_state_uniform, - mode="reset", - params={"pose_range": {}, "velocity_range": {}}, - ) - - reset_robot_joints = EventTerm( - func=mdp.reset_joints_by_scale, - mode="reset", - params={ - "position_range": (0.5, 1.5), - "velocity_range": (0.0, 0.0), - }, - ) - - -@configclass -class RewardsCfg: - """Reward terms for the MDP.""" - - # task terms - end_effector_position_tracking = RewTerm( - func=mdp.position_command_error, - weight=-0.2, - params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"}, - ) - end_effector_position_tracking_fine_grained = RewTerm( - func=mdp.position_command_error_tanh, - weight=0.1, - params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "std": 0.1, "command_name": "ee_pose"}, - ) - end_effector_orientation_tracking = RewTerm( - func=mdp.orientation_command_error, - weight=-0.1, - params={"asset_cfg": SceneEntityCfg("robot", body_names=MISSING), "command_name": "ee_pose"}, - ) - - # action penalty - action_rate = RewTerm(func=mdp.action_rate_l2, weight=-0.0001) - joint_vel = RewTerm( - func=mdp.joint_vel_l2, - weight=-0.0001, - params={"asset_cfg": SceneEntityCfg("robot")}, - ) - - -@configclass -class TerminationsCfg: - """Termination terms for the MDP.""" - - time_out = DoneTerm(func=mdp.time_out, time_out=True) - - -@configclass -class CurriculumCfg: - """Curriculum terms for the MDP.""" - - action_rate = CurrTerm( - func=mdp.modify_reward_weight, params={"term_name": "action_rate", "weight": -0.005, "num_steps": 4500} - ) - - joint_vel = CurrTerm( - func=mdp.modify_reward_weight, params={"term_name": "joint_vel", "weight": -0.001, "num_steps": 4500} - ) - - -## -# Environment configuration -## - - -@configclass -class ReachEnvCfg(ManagerBasedRLEnvCfg): - """Configuration for the reach end-effector pose tracking environment.""" - - # Scene settings - scene: ReachSceneCfg = ReachSceneCfg(num_envs=4096, env_spacing=2.5) - # Basic settings - observations: ObservationsCfg = ObservationsCfg() - actions: ActionsCfg = ActionsCfg() - commands: CommandsCfg = CommandsCfg() - # MDP settings - rewards: RewardsCfg = RewardsCfg() - terminations: TerminationsCfg = TerminationsCfg() - events: EventCfg = EventCfg() - curriculum: CurriculumCfg = CurriculumCfg() - - def __post_init__(self): - """Post initialization.""" - # general settings - self.decimation = 2 - self.sim.render_interval = self.decimation - self.episode_length_s = 12.0 - self.viewer.eye = (3.5, 3.5, 3.5) - # simulation settings - self.sim.dt = 1.0 / 60.0 From 910baeeee66573342e4f9fd2681b98d083070943 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 15 Jul 2026 18:32:44 -0700 Subject: [PATCH 27/36] Share stable cfgs with direct warp envs via warp_entry_point Direct warp tasks duplicated their stable task configuration in a parallel *-Direct-Warp-v0 registration, so every stable cfg change had to be mirrored by hand. A stable direct registration can now declare its warp implementation with a warp_entry_point kwarg (mirroring env_cfg_entry_point); --frontend warp constructs that class with the stable cfg and swaps nothing else. Declared for Isaac-Cartpole-Direct, Isaac-Ant-Direct, and Isaac-Humanoid-Direct, whose warp cfgs matched the stable ones field-for-field; their *-Direct-Warp-v0 registrations and duplicated cfgs are removed and the env classes annotate the stable cfg types. The Allegro reorient warp task keeps its own registration: its cube is modeled as an articulation, unlike the stable task's rigid object, so the configurations genuinely differ. --- .../newton/warp-environments.rst | 19 +++- docs/source/overview/environments.rst | 15 --- .../changelog.d/warp-manager-bridge.rst | 6 + .../isaaclab_experimental/envs/frontend.py | 52 +++++++-- .../test/envs/test_frontend.py | 39 +++++-- .../test/envs/test_frontend_cfg_conversion.py | 35 +++++- .../changelog.d/warp-manager-bridge.rst | 7 ++ .../isaaclab_tasks/core/cartpole/__init__.py | 1 + .../core/locomotion/ant/__init__.py | 1 + .../core/locomotion/humanoid/__init__.py | 1 + .../changelog.d/warp-manager-bridge.minor.rst | 7 ++ .../direct/ant/__init__.py | 28 +---- .../direct/ant/ant_env_warp.py | 8 +- .../direct/ant/ant_env_warp_cfg.py | 82 -------------- .../direct/cartpole/__init__.py | 29 +---- .../direct/cartpole/cartpole_warp_env.py | 6 +- .../direct/cartpole/cartpole_warp_env_cfg.py | 74 ------------ .../direct/humanoid/__init__.py | 28 +---- .../direct/humanoid/humanoid_warp_env.py | 8 +- .../direct/humanoid/humanoid_warp_env_cfg.py | 105 ------------------ 20 files changed, 175 insertions(+), 376 deletions(-) create mode 100644 source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env_cfg.py diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index 8f682ddcb047..f1c1aee930ad 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -31,9 +31,18 @@ Available Environments Direct Warp Environments ^^^^^^^^^^^^^^^^^^^^^^^^ -- ``Isaac-Cartpole-Direct-Warp-v0`` — Cartpole balance -- ``Isaac-Ant-Direct-Warp-v0`` — Ant locomotion -- ``Isaac-Humanoid-Direct-Warp-v0`` — Humanoid locomotion +Direct tasks share the stable task configuration: the stable registration +declares its warp implementation through the ``warp_entry_point`` kwarg +(mirroring ``env_cfg_entry_point``), and ``--frontend warp`` swaps only the +environment class. Stable tasks with a declared warp implementation: + +- ``Isaac-Cartpole-Direct`` — Cartpole balance +- ``Isaac-Ant-Direct`` — Ant locomotion +- ``Isaac-Humanoid-Direct`` — Humanoid locomotion + +Warp-native direct task with its own registration and configuration (the cube +is modeled differently than in the stable task): + - ``Isaac-Reorient-Cube-Allegro-Direct-Warp-v0`` — Allegro hand cube reorient @@ -78,9 +87,9 @@ Quick Start .. code-block:: bash - # Direct workflow + # Direct workflow: stable task, warp env implementation ./isaaclab.sh train --rl_library rsl_rl \ - --task Isaac-Cartpole-Direct-Warp-v0 --num_envs 4096 + --task Isaac-Cartpole-Direct --frontend warp presets=newton_mjwarp --num_envs 4096 # Manager-based workflow: stable task on the warp runtime ./isaaclab.sh train --rl_library rsl_rl \ diff --git a/docs/source/overview/environments.rst b/docs/source/overview/environments.rst index 8c821bf47bdb..5568f77e2820 100644 --- a/docs/source/overview/environments.rst +++ b/docs/source/overview/environments.rst @@ -875,11 +875,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Ant-Direct-Warp-v0 - - - - Direct - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - IsaacContrib-Assemble-Trocar-G129-Dex3 - IsaacContrib-Assemble-Trocar-G129-Dex3-Eval - Manager Based @@ -924,11 +919,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - **physics=** ``newton_kamino``, ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Cartpole-Direct-Warp-v0 - - - - Direct - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - - * - IsaacContrib-Cartpole-Showcase-Direct - - Direct @@ -1045,11 +1035,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Humanoid-Direct-Warp-v0 - - - - Direct - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Lift-Cloth-Franka - - Manager Based diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index ccb21e9b301f..9cb34541bee0 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -7,6 +7,12 @@ Added * Added :mod:`isaaclab_experimental.envs.frontend` runtime selector and :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable` used by ``--frontend=warp`` to adapt stable cfgs onto the warp runtime. +* Added :func:`isaaclab_experimental.envs.frontend.register_mdp_route` so task + packages declare where their warp MDP twins live; the frontend holds no + per-task table. +* Added ``warp_entry_point`` registration support: a stable direct task may + declare its warp environment class, which ``--frontend=warp`` constructs + with the stable configuration. Changed ^^^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index eefc9327476f..72e892aebd60 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -166,10 +166,16 @@ def build( workflow = _detect_workflow(env_cfg) if workflow is Workflow.DIRECT: - # Direct workflows aren't adapted — they must already be registered - # under the warp packages (e.g. ``Isaac-Cartpole-Direct-Warp``). - _assert_direct_warp_registration(task_id) - return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + # Direct workflows aren't cfg-adapted: a hand-written warp env class + # implements the task. Preferred path: the stable registration declares + # it via ``warp_entry_point`` and shares the stable cfg. Fallback: the + # task itself is registered under the warp packages (warp-native cfg). + env_class = _resolve_direct_warp_class(task_id) + if env_class is None: + _assert_direct_warp_registration(task_id) + return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + _require_newton_physics(env_cfg, type(env_cfg).__name__) + return env_class(cfg=env_cfg, **construct_kwargs) # Imported lazily so that ``--frontend=torch`` callers don't pay the # ``isaaclab_experimental.envs`` import cost. The env adapts the cfg itself @@ -349,19 +355,49 @@ def _detect_workflow(cfg: Any) -> Workflow: ) -def _assert_direct_warp_registration(task_id: str) -> None: - """For direct workflows, the task must be pre-registered under the warp packages.""" +def _resolve_direct_warp_class(task_id: str) -> type | None: + """Return the warp env class a stable direct task declares, if any. + + Stable direct registrations may carry a ``warp_entry_point`` kwarg of the + form ``"module.path:ClassName"`` (mirroring ``env_cfg_entry_point``) naming + the warp implementation of the same task. The class is constructed with the + *stable* cfg, so the task needs no parallel warp registration or duplicated + configuration. + """ try: spec = gym.spec(task_id) except gym.error.NameNotFound as exc: raise FrontendIncompatibleError(f"--frontend=warp: task {task_id!r} is not registered with gymnasium.") from exc + target = (spec.kwargs or {}).get("warp_entry_point") + if not isinstance(target, str): + return None + module_name, _, class_name = target.partition(":") + try: + module = importlib.import_module(module_name) + except ImportError as exc: + raise FrontendIncompatibleError( + f"--frontend=warp: task {task_id!r} declares warp_entry_point {target!r}, but it failed to import: {exc}" + ) from exc + env_class = getattr(module, class_name, None) + if env_class is None: + raise FrontendIncompatibleError( + f"--frontend=warp: task {task_id!r} declares warp_entry_point {target!r}," + f" but {class_name!r} is not defined in {module_name!r}." + ) + return env_class + + +def _assert_direct_warp_registration(task_id: str) -> None: + """For direct workflows without a ``warp_entry_point``, the task must be warp-registered.""" + spec = gym.spec(task_id) ep = spec.entry_point module = ep if isinstance(ep, str) else (getattr(ep, "__module__", "") or "") if not module.startswith(_WARP_ROOT_PREFIXES): raise FrontendIncompatibleError( f"--frontend=warp on direct task {task_id!r}: entry_point {ep!r}" - f" is not under {list(_WARP_ROOT_PREFIXES)}. Direct tasks must be" - f" registered as a warp env class (e.g. *-Direct-Warp-v0)." + f" is not under {list(_WARP_ROOT_PREFIXES)}. Direct tasks must either" + f" declare a `warp_entry_point` in their stable registration or be" + f" registered as a warp env class." ) diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index ee374ed1f9ef..f112a6ddf562 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -533,8 +533,11 @@ def test_is_swap_candidate_rejects_non_callables(): _DIRECT_TEST_TASKS = { - "_Frontend-Test-Warp-Direct-v0": "isaaclab_tasks_experimental.fake:DirectEnv", - "_Frontend-Test-Stable-Direct-v0": "isaaclab_tasks.fake:DirectEnv", + "_Frontend-Test-Warp-Direct-v0": ("isaaclab_tasks_experimental.fake:DirectEnv", None), + "_Frontend-Test-Stable-Direct-v0": ("isaaclab_tasks.fake:DirectEnv", None), + "_Frontend-Test-Declared-Direct-v0": ("isaaclab_tasks.fake:DirectEnv", "types:SimpleNamespace"), + "_Frontend-Test-Broken-Direct-v0": ("isaaclab_tasks.fake:DirectEnv", "definitely_not_a_module:Env"), + "_Frontend-Test-Missing-Class-Direct-v0": ("isaaclab_tasks.fake:DirectEnv", "types:NoSuchClass"), } @@ -542,10 +545,12 @@ def test_is_swap_candidate_rejects_non_callables(): def _register_direct_stub_tasks(): # Register stub tasks so ``gym.spec`` resolves them. Entry-point strings # are never invoked (the guard only inspects them), so a fake import - # path is fine. - for task_id, entry_point in _DIRECT_TEST_TASKS.items(): + # path is fine. ``warp_entry_point`` targets are imported, so the valid + # stub points at a real stdlib symbol. + for task_id, (entry_point, warp_entry_point) in _DIRECT_TEST_TASKS.items(): + kwargs = {"warp_entry_point": warp_entry_point} if warp_entry_point else {} with contextlib.suppress(gym.error.Error): - gym.register(id=task_id, entry_point=entry_point, disable_env_checker=True) + gym.register(id=task_id, entry_point=entry_point, disable_env_checker=True, kwargs=kwargs) yield @@ -559,6 +564,26 @@ def test_direct_guard_rejects_stable_rooted(): assert "isaaclab_experimental" in str(exc.value) -def test_direct_guard_rejects_unknown_task(): +def test_resolve_direct_warp_class_returns_declared_class(): + import types as types_module + + assert fe._resolve_direct_warp_class("_Frontend-Test-Declared-Direct-v0") is types_module.SimpleNamespace + + +def test_resolve_direct_warp_class_returns_none_without_declaration(): + assert fe._resolve_direct_warp_class("_Frontend-Test-Stable-Direct-v0") is None + + +def test_resolve_direct_warp_class_rejects_broken_module(): + with pytest.raises(FrontendIncompatibleError): + fe._resolve_direct_warp_class("_Frontend-Test-Broken-Direct-v0") + + +def test_resolve_direct_warp_class_rejects_missing_class(): + with pytest.raises(FrontendIncompatibleError): + fe._resolve_direct_warp_class("_Frontend-Test-Missing-Class-Direct-v0") + + +def test_resolve_direct_warp_class_rejects_unknown_task(): with pytest.raises(FrontendIncompatibleError): - fe._assert_direct_warp_registration("Frontend-Test-NotRegistered-v0") + fe._resolve_direct_warp_class("Frontend-Test-NotRegistered-v0") diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 8ad8716bfd89..5509ec25a6f6 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -48,8 +48,8 @@ ] # Manager-based warp tasks are exactly those whose entry point is the shared warp -# env class; direct ``*-Direct-Warp-v0`` tasks register their own env class and -# are not cfg-adapted, so they are excluded here. +# env class; direct tasks provide their own env class (via ``warp_entry_point`` +# or a warp-native registration) and are not cfg-adapted, so they are excluded here. _MANAGER_WARP_ENTRY_POINT = "isaaclab_experimental.envs:ManagerBasedRLEnvWarp" _WARP_ROOTS = ("isaaclab_experimental", "isaaclab_tasks_experimental") @@ -126,6 +126,37 @@ def test_registered_warp_variant_cfg_adapts(task_id: str, cfg_entry_point: str): ) +def _direct_tasks_with_warp_entry_point() -> list[tuple[str, str]]: + """Return ``(task_id, warp_entry_point)`` for stable direct tasks declaring a warp env.""" + tasks: list[tuple[str, str]] = [] + for task_id, spec in gym.registry.items(): + target = (spec.kwargs or {}).get("warp_entry_point") + if isinstance(target, str): + tasks.append((task_id, target)) + return sorted(tasks) + + +_DIRECT_WARP_TASKS = _direct_tasks_with_warp_entry_point() + + +def test_direct_tasks_declare_expected_warp_entry_points(): + """Sanity: the stable direct tasks with warp implementations declare them.""" + declared = {task_id for task_id, _ in _DIRECT_WARP_TASKS} + assert {"Isaac-Cartpole-Direct", "Isaac-Ant-Direct", "Isaac-Humanoid-Direct"} <= declared + + +@pytest.mark.parametrize( + "task_id, warp_entry_point", + [pytest.param(task_id, target, id=task_id) for task_id, target in _DIRECT_WARP_TASKS], +) +def test_declared_direct_warp_entry_point_resolves(task_id: str, warp_entry_point: str): + """Each declared ``warp_entry_point`` imports and names a warp-rooted class.""" + module_path, class_name = warp_entry_point.split(":") + env_class = getattr(importlib.import_module(module_path), class_name) + assert isinstance(env_class, type), f"{task_id}: {warp_entry_point} is not a class" + assert env_class.__module__.startswith(_WARP_ROOTS) + + def test_stable_cartpole_cfg_adapts_to_current_warp_module_layout(): """The stable Cartpole cfg resolves task-specific twins in the current package layout.""" from isaaclab_experimental.managers.action_manager import ActionTerm diff --git a/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst b/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst new file mode 100644 index 000000000000..f34db06907a5 --- /dev/null +++ b/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst @@ -0,0 +1,7 @@ +Added +^^^^^ + +* Added ``warp_entry_point`` declarations to the ``Isaac-Cartpole-Direct``, + ``Isaac-Ant-Direct``, and ``Isaac-Humanoid-Direct`` registrations so + ``--frontend warp`` constructs the Warp implementation of these tasks with + the stable task configuration. diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py index bdb55030b3b2..45c6ca0572fa 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py @@ -25,6 +25,7 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.cartpole_direct_env_cfg:CartpoleEnvCfg", + "warp_entry_point": "isaaclab_tasks_experimental.direct.cartpole.cartpole_warp_env:CartpoleWarpEnv", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpoleDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py index 4adb37ca8eb6..ae86a5269bde 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py @@ -25,6 +25,7 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.ant_direct_env_cfg:AntEnvCfg", + "warp_entry_point": "isaaclab_tasks_experimental.direct.ant.ant_env_warp:AntWarpEnv", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AntDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py index d13b7697595a..0387402a7957 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py @@ -25,6 +25,7 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.humanoid_direct_env_cfg:HumanoidEnvCfg", + "warp_entry_point": "isaaclab_tasks_experimental.direct.humanoid.humanoid_warp_env:HumanoidWarpEnv", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:HumanoidDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst index dfb8c6270757..782b6f25ef9a 100644 --- a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst @@ -16,6 +16,13 @@ Removed together with their duplicated environment configurations. Run the stable task ids with ``--frontend warp`` and ``presets=newton_mjwarp`` instead, e.g. ``--task Isaac-Cartpole --frontend warp presets=newton_mjwarp``. +* **Breaking:** Removed the duplicated direct warp task registrations + ``Isaac-Cartpole-Direct-Warp-v0``, ``Isaac-Ant-Direct-Warp-v0``, and + ``Isaac-Humanoid-Direct-Warp-v0`` together with their duplicated + environment configurations; the stable registrations declare the warp + environment classes via ``warp_entry_point``. Run the stable task ids with + ``--frontend warp`` and ``presets=newton_mjwarp`` instead, e.g. + ``--task Isaac-Cartpole-Direct --frontend warp presets=newton_mjwarp``. * Removed the unregistered rough velocity warp configurations; rough-terrain warp tasks remain unsupported until :class:`~isaaclab.terrains.TerrainImporter` gains Warp APIs. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py index 33d5ac926387..fd466b5394a3 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py @@ -3,26 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Ant locomotion environment. -""" - -import gymnasium as gym +"""Warp implementation of the stable direct Ant task. -## -# Register Gym environments. -## - -stable_agents = "isaaclab_tasks.core.locomotion.ant.agents" - -gym.register( - id="Isaac-Ant-Direct-Warp-v0", - entry_point=f"{__name__}.ant_env_warp:AntWarpEnv", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.ant_env_warp_cfg:AntWarpEnvCfg", - "rl_games_cfg_entry_point": f"{stable_agents}:rl_games_direct_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{stable_agents}.rsl_rl_ppo_cfg:AntDirectPPORunnerCfg", - "skrl_cfg_entry_point": f"{stable_agents}:skrl_direct_ppo_cfg.yaml", - }, -) +There is no separate task registration: the stable ``Isaac-Ant-Direct`` +registration declares :class:`~isaaclab_tasks_experimental.direct.ant.ant_env_warp.AntWarpEnv` +as its ``warp_entry_point``; run it with ``--frontend warp`` and +``presets=newton_mjwarp``. +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py index 2bd7390039b7..17ce3c2ee788 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py @@ -5,13 +5,13 @@ from __future__ import annotations -from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv +from isaaclab_tasks.core.locomotion.ant.ant_direct_env_cfg import AntEnvCfg -from .ant_env_warp_cfg import AntWarpEnvCfg +from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv class AntWarpEnv(LocomotionWarpEnv): - cfg: AntWarpEnvCfg + cfg: AntEnvCfg - def __init__(self, cfg: AntWarpEnvCfg, render_mode: str | None = None, **kwargs): + def __init__(self, cfg: AntEnvCfg, render_mode: str | None = None, **kwargs): super().__init__(cfg, render_mode, **kwargs) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp_cfg.py deleted file mode 100644 index 6e8b7fb81a95..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp_cfg.py +++ /dev/null @@ -1,82 +0,0 @@ -# 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 - -from __future__ import annotations - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg -from isaaclab.envs import DirectRLEnvCfg -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass - -from isaaclab_assets import ANT_CFG - - -@configclass -class AntWarpEnvCfg(DirectRLEnvCfg): - # env - episode_length_s = 15.0 - decimation = 2 - action_scale = 0.5 - action_space = 8 - observation_space = 36 - state_space = 0 - - solver_cfg = MJWarpSolverCfg( - njmax=45, - nconmax=25, - cone="pyramidal", - integrator="implicitfast", - impratio=1, - ) - newton_cfg = NewtonCfg( - solver_cfg=solver_cfg, - num_substeps=1, - debug_mode=False, - use_cuda_graph=True, - ) - - # simulation - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=newton_cfg) - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="plane", - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg( - friction_combine_mode="average", - restitution_combine_mode="average", - static_friction=1.0, - dynamic_friction=1.0, - restitution=0.0, - ), - debug_vis=False, - ) - - # scene - scene: InteractiveSceneCfg = InteractiveSceneCfg( - num_envs=4096, env_spacing=4.0, replicate_physics=True, clone_in_fabric=True - ) - - # robot - robot: ArticulationCfg = ANT_CFG.replace(prim_path="/World/envs/env_.*/Robot") - joint_gears: list = [15, 15, 15, 15, 15, 15, 15, 15] - - heading_weight: float = 0.5 - up_weight: float = 0.1 - - energy_cost_scale: float = 0.05 - actions_cost_scale: float = 0.005 - alive_reward_scale: float = 0.5 - dof_vel_scale: float = 0.2 - - death_cost: float = -2.0 - termination_height: float = 0.31 - - angular_velocity_scale: float = 1.0 - contact_force_scale: float = 0.1 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py index a7fc9492fff6..8dea234be2f8 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py @@ -3,27 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Cartpole balancing environment. -""" - -import gymnasium as gym +"""Warp implementation of the stable direct Cartpole task. -## -# Register Gym environments. -## - -stable_agents = "isaaclab_tasks.core.cartpole.agents" - -gym.register( - id="Isaac-Cartpole-Direct-Warp-v0", - entry_point=f"{__name__}.cartpole_warp_env:CartpoleWarpEnv", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.cartpole_warp_env_cfg:CartpoleWarpEnvCfg", - "rl_games_cfg_entry_point": f"{stable_agents}:rl_games_direct_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{stable_agents}.rsl_rl_ppo_cfg:CartpoleDirectPPORunnerCfg", - "skrl_cfg_entry_point": f"{stable_agents}:skrl_direct_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{stable_agents}:sb3_ppo_cfg.yaml", - }, -) +There is no separate task registration: the stable ``Isaac-Cartpole-Direct`` +registration declares :class:`~isaaclab_tasks_experimental.direct.cartpole.cartpole_warp_env.CartpoleWarpEnv` +as its ``warp_entry_point``; run it with ``--frontend warp`` and +``presets=newton_mjwarp``. +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py index 3e8bee2c4070..8ebae3c986b7 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py @@ -17,7 +17,7 @@ from isaaclab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane if TYPE_CHECKING: - from .cartpole_warp_env_cfg import CartpoleWarpEnvCfg + from isaaclab_tasks.core.cartpole.cartpole_direct_env_cfg import CartpoleEnvCfg @wp.kernel @@ -184,9 +184,9 @@ def initialize_state( class CartpoleWarpEnv(DirectRLEnvWarp): - cfg: CartpoleWarpEnvCfg + cfg: CartpoleEnvCfg - def __init__(self, cfg: CartpoleWarpEnvCfg, render_mode: str | None = None, **kwargs) -> None: + def __init__(self, cfg: CartpoleEnvCfg, render_mode: str | None = None, **kwargs) -> None: super().__init__(cfg, render_mode, **kwargs) # Get the indices (develop API: find_joints returns (indices, names)) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env_cfg.py deleted file mode 100644 index a11299635cfa..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env_cfg.py +++ /dev/null @@ -1,74 +0,0 @@ -# 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 - -from __future__ import annotations - -import math - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -from isaaclab.assets import ArticulationCfg -from isaaclab.envs import DirectRLEnvCfg, ViewerCfg -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.utils.configclass import configclass - -from isaaclab_assets.robots.cartpole import CARTPOLE_CFG - - -@configclass -class CartpoleWarpEnvCfg(DirectRLEnvCfg): - # env - decimation = 2 - episode_length_s = 5.0 - action_scale = 100.0 # [N] - action_space = 1 - observation_space = 4 - state_space = 0 - - # viewer - viewer: ViewerCfg = ViewerCfg(eye=(8.0, 0.0, 5.0)) - - solver_cfg = MJWarpSolverCfg( - njmax=5, - nconmax=3, - cone="pyramidal", - integrator="implicitfast", - impratio=1, - ) - - newton_cfg = NewtonCfg( - solver_cfg=solver_cfg, - num_substeps=1, - debug_mode=False, - use_cuda_graph=True, - ) - - # simulation - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=newton_cfg) - - # robot - robot_cfg: ArticulationCfg = CARTPOLE_CFG.replace(prim_path="/World/envs/env_.*/Robot") - cart_dof_name = "slider_to_cart" - pole_dof_name = "cart_to_pole" - - # scene - scene: InteractiveSceneCfg = InteractiveSceneCfg( - num_envs=4096, env_spacing=4.0, replicate_physics=True, clone_in_fabric=True - ) - - # reset - max_cart_pos = 3.0 # the cart is reset if it exceeds that position [m] - initial_cart_position_range = (-1.0, 1.0) # [m] - initial_cart_velocity_range = (-0.5, 0.5) # [m/s] - initial_pole_angle_range = (-0.25 * math.pi, 0.25 * math.pi) # [rad] - initial_pole_velocity_range = (-0.25 * math.pi, 0.25 * math.pi) # [rad/s] - - # reward scales - rew_scale_alive = 1.0 - rew_scale_terminated = -2.0 - rew_scale_pole_pos = -1.0 - rew_scale_cart_vel = -0.01 - rew_scale_pole_vel = -0.005 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py index c38d7dd955e5..663e41a7c283 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py @@ -3,26 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Humanoid locomotion environment. -""" - -import gymnasium as gym +"""Warp implementation of the stable direct Humanoid task. -## -# Register Gym environments. -## - -stable_agents = "isaaclab_tasks.core.locomotion.humanoid.agents" - -gym.register( - id="Isaac-Humanoid-Direct-Warp-v0", - entry_point=f"{__name__}.humanoid_warp_env:HumanoidWarpEnv", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.humanoid_warp_env_cfg:HumanoidWarpEnvCfg", - "rl_games_cfg_entry_point": f"{stable_agents}:rl_games_direct_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{stable_agents}.rsl_rl_ppo_cfg:HumanoidDirectPPORunnerCfg", - "skrl_cfg_entry_point": f"{stable_agents}:skrl_direct_ppo_cfg.yaml", - }, -) +There is no separate task registration: the stable ``Isaac-Humanoid-Direct`` +registration declares :class:`~isaaclab_tasks_experimental.direct.humanoid.humanoid_warp_env.HumanoidWarpEnv` +as its ``warp_entry_point``; run it with ``--frontend warp`` and +``presets=newton_mjwarp``. +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py index 2fd0ac8433e2..113d761b711c 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py @@ -5,13 +5,13 @@ from __future__ import annotations -from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv +from isaaclab_tasks.core.locomotion.humanoid.humanoid_direct_env_cfg import HumanoidEnvCfg -from .humanoid_warp_env_cfg import HumanoidWarpEnvCfg +from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv class HumanoidWarpEnv(LocomotionWarpEnv): - cfg: HumanoidWarpEnvCfg + cfg: HumanoidEnvCfg - def __init__(self, cfg: HumanoidWarpEnvCfg, render_mode: str | None = None, **kwargs): + def __init__(self, cfg: HumanoidEnvCfg, render_mode: str | None = None, **kwargs): super().__init__(cfg, render_mode, **kwargs) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env_cfg.py deleted file mode 100644 index d7fa473eda38..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env_cfg.py +++ /dev/null @@ -1,105 +0,0 @@ -# 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 - -from __future__ import annotations - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg -from isaaclab.envs import DirectRLEnvCfg -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.terrains import TerrainImporterCfg -from isaaclab.utils.configclass import configclass - -from isaaclab_assets import HUMANOID_CFG - - -@configclass -class HumanoidWarpEnvCfg(DirectRLEnvCfg): - # env - episode_length_s = 15.0 - decimation = 2 - action_scale = 1.0 - action_space = 21 - observation_space = 75 - state_space = 0 - - solver_cfg = MJWarpSolverCfg( - njmax=80, - nconmax=25, - cone="pyramidal", - integrator="implicitfast", - update_data_interval=2, - impratio=1, - ) - newton_cfg = NewtonCfg( - solver_cfg=solver_cfg, - num_substeps=2, - debug_mode=False, - use_cuda_graph=True, - ) - - # simulation - sim: SimulationCfg = SimulationCfg(dt=1 / 120, render_interval=decimation, physics=newton_cfg) - terrain = TerrainImporterCfg( - prim_path="/World/ground", - terrain_type="plane", - collision_group=-1, - physics_material=sim_utils.RigidBodyMaterialCfg( - friction_combine_mode="average", - restitution_combine_mode="average", - static_friction=1.0, - dynamic_friction=1.0, - restitution=0.0, - ), - debug_vis=False, - ) - - # scene - scene: InteractiveSceneCfg = InteractiveSceneCfg( - num_envs=4096, env_spacing=4.0, replicate_physics=True, clone_in_fabric=True - ) - - # robot - robot: ArticulationCfg = HUMANOID_CFG.replace(prim_path="/World/envs/env_.*/Robot") - joint_gears: list = [ - 67.5000, # left_upper_arm - 67.5000, # left_upper_arm - 45.0000, # left_lower_arm - 67.5000, # lower_waist - 67.5000, # lower_waist - 67.5000, # pelvis - 45.0000, # left_thigh: x - 135.0000, # left_thigh: y - 45.0000, # left_thigh: z - 90.0000, # left_knee - 22.5, # left_foot - 22.5, # left_foot - 45.0000, # right_thigh: x - 135.0000, # right_thigh: y - 45.0000, # right_thigh: z - 90.0000, # right_knee - 22.5, # right_foot - 22.5, # right_foot - 67.5000, # right_upper_arm - 67.5000, # right_upper_arm - 45.0000, # right_lower_arm - ] - - heading_weight: float = 0.5 - up_weight: float = 0.1 - - energy_cost_scale: float = 0.05 - actions_cost_scale: float = 0.01 - alive_reward_scale: float = 2.0 - dof_vel_scale: float = 0.1 - - death_cost: float = -1.0 - termination_height: float = 0.8 - - angular_velocity_scale: float = 0.25 - contact_force_scale: float = 0.01 From 9e2d4c81050625a15c663b10b0edbdfe96e9683b Mon Sep 17 00:00:00 2001 From: jichuanh Date: Wed, 15 Jul 2026 23:59:39 -0700 Subject: [PATCH 28/36] Tidy frontend CLI helper and warp env cleanups Extract the --frontend flag into add_frontend_args so other entrypoints (e.g. play) can reuse it without pulling in all training arguments; add_common_train_args keeps calling it so every train and benchmark CLI registers the flag. Also derive SceneEntityCfg.from_stable from the stable dataclass fields instead of a hand-maintained list, drop single-use aliases in the wrench observation twin, and trim render comments to one line. --- scripts/reinforcement_learning/common.py | 37 +++++++++++++------ .../envs/direct_rl_env_warp.py | 8 +--- .../envs/manager_based_rl_env_warp.py | 4 +- .../envs/mdp/observations.py | 6 +-- .../managers/scene_entity_cfg.py | 21 ++--------- 5 files changed, 33 insertions(+), 43 deletions(-) diff --git a/scripts/reinforcement_learning/common.py b/scripts/reinforcement_learning/common.py index a36b5ac9266b..efebd09747fe 100644 --- a/scripts/reinforcement_learning/common.py +++ b/scripts/reinforcement_learning/common.py @@ -233,6 +233,30 @@ def resolve_play_checkpoint(checkpoint: str | None, framework: str, task: str) - return path +def add_frontend_args(parser: argparse.ArgumentParser) -> None: + """Add the environment-runtime selector argument. + + The flag is always registered so the CLI surface does not depend on + optional packages; the warp runtime itself is imported only when selected + (see :func:`create_isaaclab_env`). + + Args: + parser: The parser to add the argument to. + """ + parser.add_argument( + "--frontend", + type=str, + choices=["torch", "warp"], + default="torch", + help=( + "Runtime that constructs the environment. 'torch' uses the registered stable environment via" + " gym.make. 'warp' (experimental) adapts a manager-based task config onto the Warp runtime, or" + " dispatches a direct task to its registered Warp environment; requires isaaclab_experimental" + " and `presets=newton_mjwarp`." + ), + ) + + def add_common_train_args( parser: argparse.ArgumentParser, *, @@ -257,18 +281,7 @@ def add_common_train_args( ) parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.") parser.add_argument("--task", type=str, default=None, help="Name of the task.") - parser.add_argument( - "--frontend", - type=str, - choices=["torch", "warp"], - default="torch", - help=( - "Runtime that constructs the environment. 'torch' uses the registered stable environment via" - " gym.make. 'warp' (experimental) adapts a manager-based task config onto the Warp runtime, or" - " dispatches a direct task to its registered Warp environment; requires isaaclab_experimental" - " and `presets=newton_mjwarp`." - ), - ) + add_frontend_args(parser) if include_agent: parser.add_argument("--agent", type=str, default=agent_default, help=agent_help) parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment") diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py index ae57af4bb55f..f1c015c98515 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/direct_rl_env_warp.py @@ -170,9 +170,7 @@ def __init__(self, cfg: DirectRLEnvCfg, render_mode: str | None = None, **kwargs # Initialize when a Kit viewport exists. ViewportCameraController uses omni.kit # (renderer camera); skip in kitless Newton-only runs where no Kit app is running. - # Mirrors stable :class:`isaaclab.envs.DirectRLEnv` (PR #5103 changed the visualizer API). - has_visualizers = self.sim.has_active_visualizers() - if (self.sim.has_gui or has_visualizers) and has_kit(): + if (self.sim.has_gui or self.sim.has_active_visualizers()) and has_kit(): self.viewport_camera_controller = ViewportCameraController(self, self.cfg.viewer) else: self.viewport_camera_controller = None @@ -567,9 +565,7 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # Rendering is possible if we have GUI or offscreen rendering enabled — mirror - # stable (PR #4646 replaced /isaaclab/has_gui and /isaaclab/render/offscreen - # settings with cached SimulationContext properties). + # rendering requires a GUI or offscreen rendering (mirrors the stable env) if not (self.sim.has_gui or self.sim.has_offscreen_render): render_mode_name = "NO_GUI_OR_RENDERING" raise RuntimeError( diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py index a90489264a48..502c9a132042 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py @@ -416,9 +416,7 @@ def render(self, recompute: bool = False) -> np.ndarray | None: if self.render_mode == "human" or self.render_mode is None: return None elif self.render_mode == "rgb_array": - # check that if any render could have happened — mirror stable - # (PR #4646 replaced /isaaclab/has_gui and /isaaclab/render/offscreen settings - # with cached SimulationContext properties). + # rendering requires a GUI or offscreen rendering (mirrors the stable env) if not (self.sim.has_gui or self.sim.has_offscreen_render): raise RuntimeError( f"Cannot render '{self.render_mode}' when the simulation render mode does not support" diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py index e36ddd189f27..4bc49cc1e2ae 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py @@ -403,13 +403,11 @@ def body_incoming_wrench(env: ManagerBasedEnv, out, sensor_cfg: SceneEntityCfg) into ``out`` (shape ``(num_envs, 6 * num_selected_bodies)``). """ sensor = env.scene.sensors[sensor_cfg.name] - force = sensor.data.force - torque = sensor.data.torque - if force is None or torque is None: + if sensor.data.force is None or sensor.data.torque is None: raise RuntimeError("Joint wrench sensor data is not initialized. Call sim.reset() before reading observations.") wp.launch( kernel=_body_incoming_wrench_kernel, dim=env.num_envs, - inputs=[force.warp, torque.warp, sensor_cfg.body_ids_wp, out], + inputs=[sensor.data.force.warp, sensor.data.torque.warp, sensor_cfg.body_ids_wp, out], device=env.device, ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py index 1052a7ec25ed..f6d30489eeca 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py @@ -42,25 +42,10 @@ class SceneEntityCfg(_SceneEntityCfg): def from_stable(cls, stable: _SceneEntityCfg) -> SceneEntityCfg: """Build a warp scene-entity cfg from a stable one. - Copies every selection field declared on the stable cfg (name, joint - names/ids, body names/ids, fixed-tendon names/ids, object-collection - names/ids, ``preserve_order``); warp-specific fields stay ``None`` - and are filled by :meth:`resolve` at scene build time. Used by the - warp frontend to promote :class:`SceneEntityCfg` instances embedded - in term ``params`` without resorting to a ``__class__`` reassign. + Copies every field declared on the stable cfg; the warp-specific fields + stay ``None`` and are filled by :meth:`resolve` at scene build time. """ - return cls( - name=stable.name, - joint_names=stable.joint_names, - joint_ids=stable.joint_ids, - fixed_tendon_names=stable.fixed_tendon_names, - fixed_tendon_ids=stable.fixed_tendon_ids, - body_names=stable.body_names, - body_ids=stable.body_ids, - object_collection_names=stable.object_collection_names, - object_collection_ids=stable.object_collection_ids, - preserve_order=stable.preserve_order, - ) + return cls(**{name: getattr(stable, name) for name in _SceneEntityCfg.__dataclass_fields__}) def resolve(self, scene: InteractiveScene): # run the stable resolution first (fills joint_ids/body_ids from names/regex) From 132112c7dfcac9a863b9f08904180763ca1474c0 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 00:07:43 -0700 Subject: [PATCH 29/36] Mirror the stable core task layout in the experimental package MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The experimental task package still used the manager_based/direct split that the stable package left behind when it consolidated each task under core/. That mismatch was the only reason the warp MDP routing needed non-obvious mappings. Move the warp task packages to the same layout — core/cartpole, core/locomotion/{ant,humanoid}, core/velocity, core/reach, and core/reorient for the Allegro task — with each task package holding both its manager-based MDP twins and its direct warp env class, exactly like its stable counterpart. Routes and warp_entry_point declarations now read as the mechanical mirror they are. --- .../test/envs/test_frontend_cfg_conversion.py | 8 ++------ .../isaaclab_tasks/core/cartpole/__init__.py | 2 +- .../core/locomotion/ant/__init__.py | 2 +- .../core/locomotion/humanoid/__init__.py | 2 +- .../changelog.d/warp-manager-bridge.minor.rst | 4 ++++ .../{direct => core}/__init__.py | 6 +----- .../classic => core}/cartpole/__init__.py | 8 +++++--- .../cartpole/cartpole_warp_env.py | 0 .../classic => core}/cartpole/mdp/__init__.py | 0 .../classic => core}/cartpole/mdp/__init__.pyi | 0 .../classic => core}/cartpole/mdp/rewards.py | 0 .../locomotion}/__init__.py | 2 +- .../locomotion}/ant/__init__.py | 11 +++++++---- .../locomotion}/ant/ant_env_warp.py | 2 +- .../core/locomotion/humanoid/__init__.py | 18 ++++++++++++++++++ .../locomotion}/humanoid/humanoid_warp_env.py | 2 +- .../locomotion}/humanoid/mdp/__init__.py | 0 .../locomotion}/humanoid/mdp/__init__.pyi | 0 .../locomotion}/humanoid/mdp/observations.py | 0 .../locomotion}/humanoid/mdp/rewards.py | 0 .../locomotion/locomotion_env_warp.py | 0 .../manipulation => core}/reach/__init__.py | 0 .../reach/mdp/__init__.py | 0 .../reach/mdp/__init__.pyi | 0 .../manipulation => core}/reach/mdp/rewards.py | 0 .../locomotion => core/reorient}/__init__.py | 2 ++ .../reorient/config}/__init__.py | 2 ++ .../reorient/config}/allegro_hand/__init__.py | 2 +- .../allegro_hand/allegro_hand_warp_env_cfg.py | 0 .../reorient}/inhand_manipulation_warp_env.py | 4 +++- .../locomotion => core}/velocity/__init__.py | 0 .../velocity/config/__init__.py | 0 .../velocity/config/a1/__init__.py | 0 .../velocity/config/a1/flat_env_cfg.py | 2 +- .../velocity/config/anymal_b/__init__.py | 0 .../velocity/config/anymal_b/flat_env_cfg.py | 2 +- .../velocity/config/anymal_c/__init__.py | 0 .../velocity/config/anymal_c/flat_env_cfg.py | 2 +- .../velocity/config/anymal_d/__init__.py | 0 .../velocity/config/anymal_d/flat_env_cfg.py | 2 +- .../velocity/config/cassie/__init__.py | 0 .../velocity/config/cassie/flat_env_cfg.py | 2 +- .../velocity/config/g1/__init__.py | 0 .../velocity/config/g1/flat_env_cfg.py | 2 +- .../velocity/config/go1/__init__.py | 0 .../velocity/config/go1/flat_env_cfg.py | 2 +- .../velocity/config/go2/__init__.py | 0 .../velocity/config/go2/flat_env_cfg.py | 2 +- .../velocity/config/h1/__init__.py | 0 .../velocity/config/h1/flat_env_cfg.py | 2 +- .../velocity/mdp/__init__.py | 0 .../velocity/mdp/__init__.pyi | 0 .../velocity/mdp/curriculums.py | 0 .../velocity/mdp/rewards.py | 0 .../velocity/mdp/terminations.py | 0 .../direct/ant/__init__.py | 12 ------------ .../direct/cartpole/__init__.py | 12 ------------ .../direct/humanoid/__init__.py | 12 ------------ .../manager_based/__init__.py | 10 ---------- .../manager_based/classic/__init__.py | 12 ------------ .../manager_based/classic/humanoid/__init__.py | 15 --------------- .../manager_based/locomotion/__init__.py | 6 ------ 62 files changed, 60 insertions(+), 114 deletions(-) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/__init__.py (68%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/__init__.py (52%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/cartpole/cartpole_warp_env.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core}/cartpole/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core/locomotion}/__init__.py (79%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core/locomotion}/ant/__init__.py (50%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core/locomotion}/ant/ant_env_warp.py (83%) create mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core/locomotion}/humanoid/humanoid_warp_env.py (84%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core/locomotion}/humanoid/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core/locomotion}/humanoid/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core/locomotion}/humanoid/mdp/observations.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/classic => core/locomotion}/humanoid/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core}/locomotion/locomotion_env_warp.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/manipulation => core}/reach/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/locomotion => core/reorient}/__init__.py (75%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/inhand_manipulation => core/reorient/config}/__init__.py (77%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core/reorient/config}/allegro_hand/__init__.py (92%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct => core/reorient/config}/allegro_hand/allegro_hand_warp_env_cfg.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{direct/inhand_manipulation => core/reorient}/inhand_manipulation_warp_env.py (99%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/a1/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/a1/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_b/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_b/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_c/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_c/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_d/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/anymal_d/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/cassie/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/cassie/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/g1/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/g1/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/go1/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/go1/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/go2/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/go2/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/h1/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/config/h1/flat_env_cfg.py (93%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/curriculums.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/rewards.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/{manager_based/locomotion => core}/velocity/mdp/terminations.py (100%) delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 5509ec25a6f6..4fc8d100675b 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -163,10 +163,6 @@ def test_stable_cartpole_cfg_adapts_to_current_warp_module_layout(): cfg = _load_adapted_cfg(_cfg_entry_point("Isaac-Cartpole")) - assert cfg.rewards.pole_pos.func.__module__.startswith( - "isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp" - ) - assert cfg.rewards.success_rate.func.__module__.startswith( - "isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp" - ) + assert cfg.rewards.pole_pos.func.__module__.startswith("isaaclab_tasks_experimental.core.cartpole.mdp") + assert cfg.rewards.success_rate.func.__module__.startswith("isaaclab_tasks_experimental.core.cartpole.mdp") assert issubclass(cfg.actions.joint_effort.class_type, ActionTerm) diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py index 45c6ca0572fa..cc8bff65c70a 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/cartpole/__init__.py @@ -25,7 +25,7 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.cartpole_direct_env_cfg:CartpoleEnvCfg", - "warp_entry_point": "isaaclab_tasks_experimental.direct.cartpole.cartpole_warp_env:CartpoleWarpEnv", + "warp_entry_point": "isaaclab_tasks_experimental.core.cartpole.cartpole_warp_env:CartpoleWarpEnv", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CartpoleDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py index ae86a5269bde..1e506e5ef4ae 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/ant/__init__.py @@ -25,7 +25,7 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.ant_direct_env_cfg:AntEnvCfg", - "warp_entry_point": "isaaclab_tasks_experimental.direct.ant.ant_env_warp:AntWarpEnv", + "warp_entry_point": "isaaclab_tasks_experimental.core.locomotion.ant.ant_env_warp:AntWarpEnv", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AntDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py index 0387402a7957..e3cee56589b2 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/locomotion/humanoid/__init__.py @@ -25,7 +25,7 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.humanoid_direct_env_cfg:HumanoidEnvCfg", - "warp_entry_point": "isaaclab_tasks_experimental.direct.humanoid.humanoid_warp_env:HumanoidWarpEnv", + "warp_entry_point": "isaaclab_tasks_experimental.core.locomotion.humanoid.humanoid_warp_env:HumanoidWarpEnv", "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:HumanoidDirectPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst index 782b6f25ef9a..425d89c1651b 100644 --- a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst @@ -6,6 +6,10 @@ Changed events that have no warp twins yet. The variants now require selecting the Newton solver on the CLI via ``presets=newton_mjwarp`` instead of hard-coding it in the configuration. +* **Breaking:** Changed the package layout to mirror :mod:`isaaclab_tasks.core` + (``isaaclab_tasks_experimental.core.``), replacing the previous + ``manager_based``/``direct`` split. Update imports of the old paths to the + ``core`` equivalents (e.g. ``isaaclab_tasks_experimental.core.cartpole.mdp``). Removed ^^^^^^^ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py similarity index 68% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py index 3e2b7945ebde..bf495309161f 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/__init__.py @@ -3,8 +3,4 @@ # # SPDX-License-Identifier: BSD-3-Clause -""" -Direct workflow environments. -""" - -import gymnasium as gym +"""Warp-first task implementations mirroring the :mod:`isaaclab_tasks.core` layout.""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py similarity index 52% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py index e527f251fb5c..9a0eaa256a77 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py @@ -3,10 +3,12 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp MDP twins for the stable Cartpole task. +"""Warp implementations for the stable Cartpole tasks. -There is no separate task registration: run the stable ``Isaac-Cartpole`` task -with ``--frontend warp`` and ``presets=newton_mjwarp``. +Holds the MDP twins for the manager-based ``Isaac-Cartpole`` task and the +direct :class:`~isaaclab_tasks_experimental.core.cartpole.cartpole_warp_env.CartpoleWarpEnv` +declared by ``Isaac-Cartpole-Direct``. There is no separate task registration: +run the stable ids with ``--frontend warp`` and ``presets=newton_mjwarp``. """ from isaaclab_experimental.envs.frontend import register_mdp_route diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/cartpole_warp_env.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/cartpole_warp_env.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/cartpole_warp_env.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/cartpole/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py similarity index 79% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py index 6cd56351b6e5..e37ca86717b5 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py @@ -3,4 +3,4 @@ # # SPDX-License-Identifier: BSD-3-Clause -from .reach import * +"""Warp-first locomotion task implementations.""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py similarity index 50% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py index 0263ee66c216..277fea940e58 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py @@ -3,10 +3,13 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp MDP route for the stable Ant task. +"""Warp implementations for the stable Ant tasks. -There is no separate task registration: run the stable ``Isaac-Ant`` task with -``--frontend warp`` and ``presets=newton_mjwarp``. +Holds the direct +:class:`~isaaclab_tasks_experimental.core.locomotion.ant.ant_env_warp.AntWarpEnv` +declared by ``Isaac-Ant-Direct``; the manager-based MDP twins are borrowed from +the Humanoid package. There is no separate task registration: run the stable +ids with ``--frontend warp`` and ``presets=newton_mjwarp``. """ from isaaclab_experimental.envs.frontend import register_mdp_route @@ -15,5 +18,5 @@ # experimental humanoid package. register_mdp_route( "isaaclab_tasks.core.locomotion.ant", - "isaaclab_tasks_experimental.manager_based.classic.humanoid.mdp", + "isaaclab_tasks_experimental.core.locomotion.humanoid.mdp", ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/ant_env_warp.py similarity index 83% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/ant_env_warp.py index 17ce3c2ee788..7d8957e4d9c7 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/ant_env_warp.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/ant_env_warp.py @@ -7,7 +7,7 @@ from isaaclab_tasks.core.locomotion.ant.ant_direct_env_cfg import AntEnvCfg -from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv +from isaaclab_tasks_experimental.core.locomotion.locomotion_env_warp import LocomotionWarpEnv class AntWarpEnv(LocomotionWarpEnv): diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py new file mode 100644 index 000000000000..7f05dee5608e --- /dev/null +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py @@ -0,0 +1,18 @@ +# 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 + +"""Warp implementations for the stable Humanoid tasks. + +Holds the MDP twins for the manager-based ``Isaac-Humanoid`` task (also +serving the Ant task, which borrows them) and the direct +:class:`~isaaclab_tasks_experimental.core.locomotion.humanoid.humanoid_warp_env.HumanoidWarpEnv` +declared by ``Isaac-Humanoid-Direct``. There is no separate task registration: +run the stable ids with ``--frontend warp`` and ``presets=newton_mjwarp``. +""" + +from isaaclab_experimental.envs.frontend import register_mdp_route + +# Warp twins for the stable humanoid MDP terms live in this package's ``mdp``. +register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", f"{__name__}.mdp") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/humanoid_warp_env.py similarity index 84% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/humanoid_warp_env.py index 113d761b711c..2a843510717a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/humanoid_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/humanoid_warp_env.py @@ -7,7 +7,7 @@ from isaaclab_tasks.core.locomotion.humanoid.humanoid_direct_env_cfg import HumanoidEnvCfg -from isaaclab_tasks_experimental.direct.locomotion.locomotion_env_warp import LocomotionWarpEnv +from isaaclab_tasks_experimental.core.locomotion.locomotion_env_warp import LocomotionWarpEnv class HumanoidWarpEnv(LocomotionWarpEnv): diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/observations.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/observations.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/observations.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/locomotion_env_warp.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/manipulation/reach/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/__init__.py similarity index 75% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/__init__.py index 460a30569089..48bb97b31113 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/locomotion/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/__init__.py @@ -2,3 +2,5 @@ # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause + +"""Warp-first in-hand reorientation task implementations.""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py similarity index 77% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py index 460a30569089..771b55fc3605 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py @@ -2,3 +2,5 @@ # All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause + +"""Warp task registrations for reorientation robots.""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py similarity index 92% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py index e7fc129c633f..13ab818b132d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py @@ -13,7 +13,7 @@ # Register Gym environments. ## -inhand_task_entry = "isaaclab_tasks_experimental.direct.inhand_manipulation" +inhand_task_entry = "isaaclab_tasks_experimental.core.reorient" stable_agents = "isaaclab_tasks.core.reorient.config.allegro_hand.agents" gym.register( diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/allegro_hand_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/allegro_hand_warp_env_cfg.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/allegro_hand/allegro_hand_warp_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/allegro_hand_warp_env_cfg.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py similarity index 99% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py index 2082d470ff9b..ae8a8b30222c 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/inhand_manipulation/inhand_manipulation_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py @@ -20,7 +20,9 @@ from isaaclab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane if TYPE_CHECKING: - from isaaclab_tasks_experimental.direct.allegro_hand.allegro_hand_warp_env_cfg import AllegroHandWarpEnvCfg + from isaaclab_tasks_experimental.core.reorient.config.allegro_hand.allegro_hand_warp_env_cfg import ( + AllegroHandWarpEnvCfg, + ) @wp.kernel diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py index d58290799424..c9948d38a278 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/a1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py @@ -12,7 +12,7 @@ UnitreeA1FlatEnvCfg_PLAY as _StableUnitreeA1FlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py index 900d87e64227..0c01243aa7d0 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_b/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py @@ -12,7 +12,7 @@ AnymalBFlatEnvCfg_PLAY as _StableAnymalBFlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py index edb8ffd7a90e..7777d8274e6a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_c/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py @@ -12,7 +12,7 @@ AnymalCFlatEnvCfg_PLAY as _StableAnymalCFlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py index ca010dffb13c..ccd874878e2f 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/anymal_d/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py @@ -12,7 +12,7 @@ AnymalDFlatEnvCfg_PLAY as _StableAnymalDFlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py index 4b42afa8a3a5..37696377d675 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/cassie/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py @@ -12,7 +12,7 @@ CassieFlatEnvCfg_PLAY as _StableCassieFlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py index 9c2011fe13c8..e11424804874 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/g1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py @@ -10,7 +10,7 @@ from isaaclab_tasks.core.velocity.config.g1.flat_env_cfg import G1FlatEnvCfg as _StableG1FlatEnvCfg from isaaclab_tasks.core.velocity.config.g1.flat_env_cfg import G1FlatEnvCfg_PLAY as _StableG1FlatEnvCfg_PLAY -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py index c54355196dab..bbe78df0bd1b 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py @@ -12,7 +12,7 @@ UnitreeGo1FlatEnvCfg_PLAY as _StableUnitreeGo1FlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py index a54d94dabcc9..87eb63e6e2fa 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/go2/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py @@ -12,7 +12,7 @@ UnitreeGo2FlatEnvCfg_PLAY as _StableUnitreeGo2FlatEnvCfg_PLAY, ) -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py similarity index 93% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py index 088d5786b223..6c7ca5701261 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/config/h1/flat_env_cfg.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py @@ -10,7 +10,7 @@ from isaaclab_tasks.core.velocity.config.h1.flat_env_cfg import H1FlatEnvCfg as _StableH1FlatEnvCfg from isaaclab_tasks.core.velocity.config.h1.flat_env_cfg import H1FlatEnvCfg_PLAY as _StableH1FlatEnvCfg_PLAY -from isaaclab_tasks_experimental.manager_based.locomotion.velocity import ( +from isaaclab_tasks_experimental.core.velocity import ( disable_unsupported_randomization_events, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/curriculums.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/curriculums.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/curriculums.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/terminations.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/velocity/mdp/terminations.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/terminations.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py deleted file mode 100644 index fd466b5394a3..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/ant/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# 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 - -"""Warp implementation of the stable direct Ant task. - -There is no separate task registration: the stable ``Isaac-Ant-Direct`` -registration declares :class:`~isaaclab_tasks_experimental.direct.ant.ant_env_warp.AntWarpEnv` -as its ``warp_entry_point``; run it with ``--frontend warp`` and -``presets=newton_mjwarp``. -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py deleted file mode 100644 index 8dea234be2f8..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/cartpole/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# 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 - -"""Warp implementation of the stable direct Cartpole task. - -There is no separate task registration: the stable ``Isaac-Cartpole-Direct`` -registration declares :class:`~isaaclab_tasks_experimental.direct.cartpole.cartpole_warp_env.CartpoleWarpEnv` -as its ``warp_entry_point``; run it with ``--frontend warp`` and -``presets=newton_mjwarp``. -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py deleted file mode 100644 index 663e41a7c283..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/direct/humanoid/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# 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 - -"""Warp implementation of the stable direct Humanoid task. - -There is no separate task registration: the stable ``Isaac-Humanoid-Direct`` -registration declares :class:`~isaaclab_tasks_experimental.direct.humanoid.humanoid_warp_env.HumanoidWarpEnv` -as its ``warp_entry_point``; run it with ``--frontend warp`` and -``presets=newton_mjwarp``. -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py deleted file mode 100644 index 7f23883e6332..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -# 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 - -"""Experimental registrations for manager-based tasks. - -We intentionally only register new Gym IDs pointing at experimental entry points. -Task definitions (configs/mdp) remain in `isaaclab_tasks` to avoid duplication. -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py deleted file mode 100644 index 79c13e2aa8f4..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# 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 - -"""Classic environments for control. - -These environments are based on the MuJoCo environments provided by OpenAI. - -Reference: - https://github.com/openai/gym/tree/master/gym/envs/mujoco -""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py deleted file mode 100644 index 0d31a47ece94..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/classic/humanoid/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# 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 - -"""Warp MDP twins for the stable Humanoid task. - -There is no separate task registration: run the stable ``Isaac-Humanoid`` task -with ``--frontend warp`` and ``presets=newton_mjwarp``. -""" - -from isaaclab_experimental.envs.frontend import register_mdp_route - -# Warp twins for the stable humanoid MDP terms live in this package's ``mdp``. -register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", f"{__name__}.mdp") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py deleted file mode 100644 index 0660d38f0658..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/manager_based/locomotion/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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 - -"""Locomotion experimental task registrations (manager-based).""" From 5129070748eeca32dc9a727e411f9639e5c5f38b Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 00:08:41 -0700 Subject: [PATCH 30/36] Encapsulate the warp frontend machinery in a class MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Group the warp-side machinery — route registry, cfg adaptation steps, twin resolution, and both env build paths — under a WarpFrontend class instead of a flat set of module functions. The module-level build(), adapt_cfg_for_warp(), and register_mdp_route() API is unchanged for callers; the class gives the machinery one named owner, keeps the route registry as explicit class state, and leaves room for future frontends to subclass or replace it. --- .../isaaclab_experimental/envs/frontend.py | 956 ++++++++++-------- .../test/envs/test_frontend.py | 85 +- 2 files changed, 554 insertions(+), 487 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 72e892aebd60..ca5174c479f5 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -5,17 +5,20 @@ """Runtime selector for IsaacLab tasks (``--frontend {torch,warp}``). -Two responsibilities only: - -1. Decide which runtime constructs the env (torch via ``gym.make``, or warp via - :class:`ManagerBasedRLEnvWarp`). -2. For the warp runtime, adapt a stable manager-based cfg in place so the - warp managers can consume it (Newton physics + warp-twin term funcs and - action classes + warp variant of :class:`SceneEntityCfg`). - -The adaptation is a single function (:func:`_adapt_cfg_for_warp`); there is no -plugin framework. All warp MDP twins (functions *and* classes) must exist for -the chosen task — a missing twin is a hard failure, not a silent drop. +:func:`build` decides which runtime constructs the env: torch via ``gym.make``, +or warp via :class:`WarpFrontend`, which encapsulates everything the warp +runtime needs from a stable task definition: + +* Manager-based tasks: adapt the stable cfg in place (Newton physics check, + :class:`SceneEntityCfg` promotion, MDP twin swap) and construct + :class:`ManagerBasedRLEnvWarp`. All warp MDP twins (functions *and* classes) + must exist for the chosen task — a missing twin is a hard failure, not a + silent drop. +* Direct tasks: construct the warp env class the stable registration declares + via its ``warp_entry_point`` kwarg, sharing the stable cfg. + +Task packages declare where their warp MDP twins live with +:func:`register_mdp_route`; the frontend holds no per-task table. """ from __future__ import annotations @@ -25,7 +28,7 @@ from collections.abc import Iterable, Iterator from enum import StrEnum from types import ModuleType -from typing import Any +from typing import Any, ClassVar import gymnasium as gym @@ -38,6 +41,7 @@ __all__ = [ "Frontend", "FrontendIncompatibleError", + "WarpFrontend", "Workflow", "adapt_cfg_for_warp", "build", @@ -69,74 +73,10 @@ class FrontendIncompatibleError(RuntimeError): # --------------------------------------------------------------------------- -# Public entry point +# Public entry points # --------------------------------------------------------------------------- -# Prefixes used to decide whether a registered task's entry-point lives under -# the warp packages. Used by the direct-workflow guard. -_WARP_ROOT_PREFIXES: tuple[str, ...] = ("isaaclab_experimental", "isaaclab_tasks_experimental") - -# Stable package prefixes mapped to the warp MDP module that twins their terms. -# The stable task package is organized by public task domain while the -# experimental package separates manager-based workflows by family, so the -# module trees are not one-to-one. The registry is populated by the experimental -# task packages themselves via :func:`register_mdp_route` at import time, so -# adding a new task family never requires editing this module. -_WARP_MDP_MODULE_ROUTES: dict[str, str] = {} - -# Root package that provides task-specific warp MDP twins. Imported (lazily, at -# swap time) so its task packages run their register_mdp_route() calls even when -# the caller only imported the stable task package. -_TWIN_PROVIDER_PACKAGE = "isaaclab_tasks_experimental" - - -def register_mdp_route(stable_package: str, warp_mdp_module: str) -> None: - """Register the warp MDP module that twins a stable package's terms. - - Experimental task packages call this at import time to declare where the - warp twins of a stable task's MDP terms live. :func:`_swap_mdp` consults - the registry to resolve task-specific twins for ``--frontend=warp``. Twin - lookup is by symbol name on ``warp_mdp_module`` itself, mirroring how a - stable cfg consumes its ``mdp`` namespace — so the module should re-export - everything the task needs (task-specific twins plus the generic forwards). - - Two kinds of keys are useful: - - * A *task package* (e.g. ``"isaaclab_tasks.core.reach"``) routes every cfg - class defined under it. This also covers terms whose stable functions are - defined in core/shared packages but overridden by task-specific twins. - * An *MDP package* (e.g. ``"isaaclab_tasks.core.locomotion.humanoid.mdp"``) - routes symbols *defined* under it, which serves other tasks that borrow - those terms. - - Args: - stable_package: Stable package prefix to route (longest match wins). - warp_mdp_module: Warp MDP module providing the twins, e.g. - ``"isaaclab_tasks_experimental.manager_based.classic.cartpole.mdp"``. - - Raises: - ValueError: If ``stable_package`` is already routed to a different module. - """ - existing = _WARP_MDP_MODULE_ROUTES.get(stable_package) - if existing is not None and existing != warp_mdp_module: - raise ValueError( - f"MDP route conflict for {stable_package!r}: already routed to {existing!r}, got {warp_mdp_module!r}." - ) - _WARP_MDP_MODULE_ROUTES[stable_package] = warp_mdp_module - - -# Top-level cfg groups whose managers run warp-first. Only terms under these are -# adapted (SceneEntityCfg promotion + MDP twin swap). The event manager is -# warp-first too — it invokes term funcs with a Warp env-mask, so a stable event -# func (which expects torch ``env_ids``) breaks at runtime; its funcs must be -# swapped to warp twins. The curriculum, recorder and command managers run on the -# stable (torch) implementation, so their terms are left untouched. A stable term -# left on a warp manager would break, so a missing twin in these groups is a hard -# error; a stable term on a stable manager is correct, so those groups are skipped. -_WARP_MANAGED_GROUPS: frozenset[str] = frozenset({"observations", "rewards", "terminations", "actions", "events"}) - - def build( frontend: Frontend | str, env_cfg: Any, @@ -146,10 +86,10 @@ def build( """Construct the env on the selected runtime. Args: - frontend: ``"torch"`` (default IsaacLab path) or ``"warp"`` (warp managers - + :class:`ManagerBasedRLEnvWarp` for manager-based tasks). + frontend: ``"torch"`` (default IsaacLab path) or ``"warp"`` + (:class:`WarpFrontend`). env_cfg: Stable env cfg. Mutated in place when ``frontend == "warp"``. - task_id: Gym registration id, e.g. ``"Isaac-Cartpole-v0"``. + task_id: Gym registration id, e.g. ``"Isaac-Cartpole"``. **construct_kwargs: Forwarded to the env constructor (``render_mode``, …). Returns: @@ -157,400 +97,524 @@ def build( Raises: FrontendIncompatibleError: If the warp runtime can't run the task - (wrong physics, missing MDP twins, direct task not registered - as a warp env). + (wrong physics, missing MDP twins, direct task without a warp + implementation). """ frontend = Frontend(frontend) if frontend is Frontend.TORCH: return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + return WarpFrontend.build_env(env_cfg, task_id, **construct_kwargs) - workflow = _detect_workflow(env_cfg) - if workflow is Workflow.DIRECT: - # Direct workflows aren't cfg-adapted: a hand-written warp env class - # implements the task. Preferred path: the stable registration declares - # it via ``warp_entry_point`` and shares the stable cfg. Fallback: the - # task itself is registered under the warp packages (warp-native cfg). - env_class = _resolve_direct_warp_class(task_id) - if env_class is None: - _assert_direct_warp_registration(task_id) - return gym.make(task_id, cfg=env_cfg, **construct_kwargs) - _require_newton_physics(env_cfg, type(env_cfg).__name__) - return env_class(cfg=env_cfg, **construct_kwargs) - # Imported lazily so that ``--frontend=torch`` callers don't pay the - # ``isaaclab_experimental.envs`` import cost. The env adapts the cfg itself - # in ``__init__`` (see :func:`adapt_cfg_for_warp`), so stable cfgs and - # warp-native cfgs take the same path. - from isaaclab_experimental.envs import ManagerBasedRLEnvWarp +def adapt_cfg_for_warp(cfg: Any) -> None: + """Mutate a stable manager-based ``cfg`` in place so warp managers can consume it. - return ManagerBasedRLEnvWarp(cfg=env_cfg, **construct_kwargs) + Functional alias for :meth:`WarpFrontend.adapt_cfg`, used by + :class:`ManagerBasedRLEnvWarp` in its ``__init__``. + """ + WarpFrontend.adapt_cfg(cfg) # --------------------------------------------------------------------------- -# Cfg adaptation (warp only) +# Warp frontend # --------------------------------------------------------------------------- -def adapt_cfg_for_warp(cfg: Any) -> None: - """Mutate a stable manager-based ``cfg`` in place so warp managers can consume it. +class WarpFrontend: + """Builds environments on the warp runtime from stable task definitions. - Called by :func:`build` for ``--frontend=warp`` on a stable manager-based - task. Idempotent: re-running on an already-adapted cfg is a no-op (the steps - below skip Warp-origin symbols and already-promoted entities). - - Three steps, each independently testable: - - 1. :func:`_require_newton_physics` — hard check that ``cfg.sim.physics`` is - :class:`~isaaclab_newton.physics.NewtonCfg`. The user is responsible for - selecting the Newton variant of the task's :class:`PresetCfg` via - ``presets=newton_mjwarp``; we don't auto-inject. - 2. :func:`_promote_scene_entity_cfgs` — replace stable - :class:`~isaaclab.managers.SceneEntityCfg` instances under each term's - ``params`` with the warp variant (which adds warp-cached ``joint_mask``, - ``joint_ids_wp``, ``body_ids_wp`` fields). - 3. :func:`_swap_mdp` — for every MDP term found anywhere in the cfg tree - (discovered by :func:`_walk_terms` via :class:`ManagerTermBaseCfg` - subclassing, not by hard-coded attribute names), replace any stable - ``func`` *or* ``class_type`` with its same-named warp twin. A missing - twin raises :class:`FrontendIncompatibleError` — partial coverage is - unsafe under the warp managers' kernel-only signature. + The class is a stateless namespace apart from the MDP route registry + (:attr:`_mdp_routes`), which experimental task packages populate at import + time via :meth:`register_mdp_route`. The stable and experimental task trees + mirror each other (``isaaclab_tasks.core.X`` ↔ + ``isaaclab_tasks_experimental.core.X``), so most routes are the mechanical + mirror; the registry keeps routing explicit and accommodates exceptions + (the Ant task borrows the Humanoid twins). """ - label = type(cfg).__name__ - _require_newton_physics(cfg, label) - _promote_scene_entity_cfgs(cfg) - _swap_mdp(cfg, label) - -def _require_newton_physics(cfg: Any, label: str) -> None: - """Block unless ``cfg.sim.physics`` is :class:`NewtonCfg`. - - The warp managers' assets read state through :class:`NewtonManager`; - a :class:`PhysxCfg` (or unresolved :class:`PresetCfg`) is a hard - incompatibility. The fix is to pass ``presets=newton_mjwarp`` on the CLI so - Hydra resolves the task's :class:`PresetCfg` wrapper to the Newton field - before construction. - """ - from isaaclab_newton.physics import NewtonCfg - - physics = getattr(getattr(cfg, "sim", None), "physics", None) - if isinstance(physics, NewtonCfg): - return - raise FrontendIncompatibleError( - f"warp env {label!r}: expected cfg.sim.physics to be NewtonCfg," - f" got {type(physics).__name__!r}. Pass `presets=newton_mjwarp` on the CLI so" - f" Hydra resolves the task's PresetCfg wrapper to the Newton variant." + # Prefixes that identify warp-origin symbols and registrations. + WARP_ROOT_PREFIXES: ClassVar[tuple[str, ...]] = ("isaaclab_experimental", "isaaclab_tasks_experimental") + + # Top-level cfg groups whose managers run warp-first. Only terms under these + # are adapted (SceneEntityCfg promotion + MDP twin swap). The event manager + # is warp-first too — it invokes term funcs with a Warp env-mask, so a stable + # event func (which expects torch ``env_ids``) breaks at runtime; its funcs + # must be swapped to warp twins. The curriculum, recorder and command + # managers run on the stable (torch) implementation, so their terms are left + # untouched. A stable term left on a warp manager would break, so a missing + # twin in these groups is a hard error; a stable term on a stable manager is + # correct, so those groups are skipped. + WARP_MANAGED_GROUPS: ClassVar[frozenset[str]] = frozenset( + {"observations", "rewards", "terminations", "actions", "events"} ) + # Root package that provides task-specific warp MDP twins. Imported (lazily, + # at swap time) so its task packages run their register_mdp_route() calls + # even when the caller only imported the stable task package. + _TWIN_PROVIDER_PACKAGE: ClassVar[str] = "isaaclab_tasks_experimental" + + # Shared fallback module holding generic warp twins. + _FALLBACK_MDP_MODULE: ClassVar[str] = "isaaclab_experimental.envs.mdp" + + # Stable package prefixes mapped to the warp MDP module that twins their + # terms. Populated via register_mdp_route(); never edited here. + _mdp_routes: ClassVar[dict[str, str]] = {} + + # ------------------------------------------------------------------ + # Route registry + # ------------------------------------------------------------------ + + @classmethod + def register_mdp_route(cls, stable_package: str, warp_mdp_module: str) -> None: + """Register the warp MDP module that twins a stable package's terms. + + Experimental task packages call this at import time to declare where + the warp twins of a stable task's MDP terms live. Twin lookup is by + symbol name on ``warp_mdp_module`` itself, mirroring how a stable cfg + consumes its ``mdp`` namespace — so the module should re-export + everything the task needs (task-specific twins plus the generic + forwards). + + Two kinds of keys are useful: + + * A *task package* (e.g. ``"isaaclab_tasks.core.reach"``) routes every + cfg class defined under it. This also covers terms whose stable + functions are defined in core/shared packages but overridden by + task-specific twins. + * An *MDP package* (e.g. ``"isaaclab_tasks.core.locomotion.humanoid.mdp"``) + routes symbols *defined* under it, which serves other tasks that + borrow those terms. + + Args: + stable_package: Stable package prefix to route (longest match wins). + warp_mdp_module: Warp MDP module providing the twins, e.g. + ``"isaaclab_tasks_experimental.core.cartpole.mdp"``. + + Raises: + ValueError: If ``stable_package`` is already routed to a different module. + """ + existing = cls._mdp_routes.get(stable_package) + if existing is not None and existing != warp_mdp_module: + raise ValueError( + f"MDP route conflict for {stable_package!r}: already routed to {existing!r}, got {warp_mdp_module!r}." + ) + cls._mdp_routes[stable_package] = warp_mdp_module + + # ------------------------------------------------------------------ + # Env construction + # ------------------------------------------------------------------ + + @classmethod + def build_env(cls, env_cfg: Any, task_id: str, **construct_kwargs: Any) -> gym.Env: + """Construct the warp env for ``task_id`` from a stable env cfg.""" + if cls._detect_workflow(env_cfg) is Workflow.DIRECT: + return cls._build_direct_env(env_cfg, task_id, **construct_kwargs) + return cls._build_manager_env(env_cfg, **construct_kwargs) + + @classmethod + def _build_manager_env(cls, env_cfg: Any, **construct_kwargs: Any) -> gym.Env: + """Construct :class:`ManagerBasedRLEnvWarp`; the env adapts the cfg itself. + + Imported lazily so that ``--frontend=torch`` callers don't pay the + ``isaaclab_experimental.envs`` import cost. The env runs + :meth:`adapt_cfg` in ``__init__``, so stable cfgs and warp-native cfgs + take the same path. + """ + from isaaclab_experimental.envs import ManagerBasedRLEnvWarp + + return ManagerBasedRLEnvWarp(cfg=env_cfg, **construct_kwargs) + + @classmethod + def _build_direct_env(cls, env_cfg: Any, task_id: str, **construct_kwargs: Any) -> gym.Env: + """Construct a direct warp env. + + Direct workflows aren't cfg-adapted: a hand-written warp env class + implements the task. Preferred path: the stable registration declares + it via ``warp_entry_point`` and shares the stable cfg. Fallback: the + task itself is registered under the warp packages (warp-native cfg). + """ + env_class = cls._resolve_direct_warp_class(task_id) + if env_class is None: + cls._assert_direct_warp_registration(task_id) + return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + cls._require_newton_physics(env_cfg, type(env_cfg).__name__) + return env_class(cfg=env_cfg, **construct_kwargs) -def _promote_scene_entity_cfgs(cfg: Any) -> None: - """Replace stable :class:`SceneEntityCfg` instances with the warp variant. - - Iterates every term cfg in the tree (via :func:`_walk_terms`) and rebuilds - any stable :class:`SceneEntityCfg` value under ``term.params`` through - :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable`. The - warp variant subclasses the stable one, so type checks elsewhere stay - valid; the new fields (``joint_mask`` / ``joint_ids_wp`` / ``body_ids_wp``) - are filled at :meth:`resolve` time by the warp scene. - """ - from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSceneEntityCfg - - promoted: list[str] = [] - for path, term in _walk_terms(cfg): - if not path or path[0] not in _WARP_MANAGED_GROUPS: - continue - params = getattr(term, "params", None) - if not isinstance(params, dict): - continue - for key, value in list(params.items()): - if isinstance(value, _WarpSceneEntityCfg) or not isinstance(value, _StableSceneEntityCfg): - continue - params[key] = _WarpSceneEntityCfg.from_stable(value) - promoted.append(f"{'.'.join(path)}.params[{key!r}] ({value.name!r})") - if promoted: - logger.info( - "frontend.warp: promoted %d SceneEntityCfg instance(s) to warp variant:\n %s", - len(promoted), - "\n ".join(promoted), + # ------------------------------------------------------------------ + # Cfg adaptation (manager-based) + # ------------------------------------------------------------------ + + @classmethod + def adapt_cfg(cls, cfg: Any) -> None: + """Mutate a stable manager-based ``cfg`` in place for the warp managers. + + Idempotent: re-running on an already-adapted cfg is a no-op (the steps + below skip warp-origin symbols and already-promoted entities). + + Three steps, each independently testable: + + 1. :meth:`_require_newton_physics` — hard check that ``cfg.sim.physics`` + is :class:`~isaaclab_newton.physics.NewtonCfg`. The user is + responsible for selecting the Newton variant of the task's + :class:`PresetCfg` via ``presets=newton_mjwarp``; we don't auto-inject. + 2. :meth:`_promote_scene_entity_cfgs` — replace stable + :class:`~isaaclab.managers.SceneEntityCfg` instances under each + term's ``params`` with the warp variant (which adds warp-cached + ``joint_mask``, ``joint_ids_wp``, ``body_ids_wp`` fields). + 3. :meth:`_swap_mdp` — for every MDP term found anywhere in the cfg tree + (discovered by :meth:`_walk_terms` via :class:`ManagerTermBaseCfg` + subclassing, not by hard-coded attribute names), replace any stable + ``func`` *or* ``class_type`` with its same-named warp twin. A missing + twin raises :class:`FrontendIncompatibleError` — partial coverage is + unsafe under the warp managers' kernel-only signature. + """ + label = type(cfg).__name__ + cls._require_newton_physics(cfg, label) + cls._promote_scene_entity_cfgs(cfg) + cls._swap_mdp(cfg, label) + + @staticmethod + def _require_newton_physics(cfg: Any, label: str) -> None: + """Block unless ``cfg.sim.physics`` is :class:`NewtonCfg`. + + The warp managers' assets read state through :class:`NewtonManager`; + a :class:`PhysxCfg` (or unresolved :class:`PresetCfg`) is a hard + incompatibility. The fix is to pass ``presets=newton_mjwarp`` on the CLI + so Hydra resolves the task's :class:`PresetCfg` wrapper to the Newton + field before construction. + """ + from isaaclab_newton.physics import NewtonCfg + + physics = getattr(getattr(cfg, "sim", None), "physics", None) + if isinstance(physics, NewtonCfg): + return + raise FrontendIncompatibleError( + f"warp env {label!r}: expected cfg.sim.physics to be NewtonCfg," + f" got {type(physics).__name__!r}. Pass `presets=newton_mjwarp` on the CLI so" + f" Hydra resolves the task's PresetCfg wrapper to the Newton variant." ) - -def _swap_mdp(cfg: Any, label: str) -> None: - """Replace ``term.func`` and ``term.class_type`` with their warp twins. - - Iterates every term cfg in the tree (via :func:`_walk_terms`) and on each - term swaps whichever of ``func`` / ``class_type`` is a stable-origin - callable. Twin lookup is name-based, in the order given by - :func:`_twin_modules`: the warp mirror of the cfg's own task MDP namespace - first (task twins win, even for symbols defined in core packages), then the - mirror of the symbol's defining package (covers terms borrowed from another - task family, e.g. the Ant task reusing Humanoid MDP terms), then the shared - :mod:`isaaclab_experimental.envs.mdp` fallback. Any missing twin raises - :class:`FrontendIncompatibleError` listing every affected term — partial - swaps would leave torch-style callables in the cfg and the warp managers - would call them with the wrong signature. - - The warp-side declarations (``out_dim``, ``axes``, ``observation_type``) - that the warp managers need at init are *not* supplied by this swap; they - travel with the warp twin function itself via its own - ``@generic_io_descriptor_warp(out_dim=…)`` decorator. This function only - substitutes the callable; the manager reads the new func's annotations - when it parses the term cfg. - """ - _ensure_twin_providers_imported() - - cfg_route_modules = _cfg_route_modules(cfg) - module_cache: dict[str, list[ModuleType]] = {} - searched: set[str] = set() - - swapped = 0 - missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) - for path, term in _walk_terms(cfg): - if not path or path[0] not in _WARP_MANAGED_GROUPS: - continue - location = ".".join(path) - for attr in ("func", "class_type"): - stable = getattr(term, attr, None) - if stable is None or not _is_swap_candidate(stable): + @classmethod + def _promote_scene_entity_cfgs(cls, cfg: Any) -> None: + """Replace stable :class:`SceneEntityCfg` instances with the warp variant. + + Iterates every term cfg in the tree (via :meth:`_walk_terms`) and + rebuilds any stable :class:`SceneEntityCfg` value under ``term.params`` + through :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable`. + The warp variant subclasses the stable one, so type checks elsewhere + stay valid; the new fields (``joint_mask`` / ``joint_ids_wp`` / + ``body_ids_wp``) are filled at :meth:`resolve` time by the warp scene. + """ + from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as _WarpSceneEntityCfg + + promoted: list[str] = [] + for path, term in cls._walk_terms(cfg): + if not path or path[0] not in cls.WARP_MANAGED_GROUPS: continue - origin = getattr(stable, "__module__", "") or "" - if origin not in module_cache: - module_cache[origin] = _twin_modules(origin, cfg_route_modules) - searched.update(m.__name__ for m in module_cache[origin]) - twin = _resolve_warp_twin(stable.__name__, module_cache[origin]) - if twin is None: - missing.append((location, attr, stable.__name__)) + params = getattr(term, "params", None) + if not isinstance(params, dict): continue - setattr(term, attr, twin) - swapped += 1 - - if missing: - lines = "\n ".join(f"{loc}.{attr}: no warp twin for {sym!r}" for loc, attr, sym in missing) + for key, value in list(params.items()): + if isinstance(value, _WarpSceneEntityCfg) or not isinstance(value, _StableSceneEntityCfg): + continue + params[key] = _WarpSceneEntityCfg.from_stable(value) + promoted.append(f"{'.'.join(path)}.params[{key!r}] ({value.name!r})") + if promoted: + logger.info( + "frontend.warp: promoted %d SceneEntityCfg instance(s) to warp variant:\n %s", + len(promoted), + "\n ".join(promoted), + ) + + @classmethod + def _swap_mdp(cls, cfg: Any, label: str) -> None: + """Replace ``term.func`` and ``term.class_type`` with their warp twins. + + Iterates every term cfg in the tree (via :meth:`_walk_terms`) and on + each term swaps whichever of ``func`` / ``class_type`` is a + stable-origin callable. Twin lookup is name-based, in the order given by + :meth:`_twin_modules`: the warp mirror of the cfg's own task MDP + namespace first (task twins win, even for symbols defined in core + packages), then the mirror of the symbol's defining package (covers + terms borrowed from another task family, e.g. the Ant task reusing + Humanoid MDP terms), then the shared fallback. Any missing twin raises + :class:`FrontendIncompatibleError` listing every affected term — + partial swaps would leave torch-style callables in the cfg and the warp + managers would call them with the wrong signature. + + The warp-side declarations (``out_dim``, ``axes``, ``observation_type``) + that the warp managers need at init are *not* supplied by this swap; + they travel with the warp twin function itself via its own + ``@generic_io_descriptor_warp(out_dim=…)`` decorator. This method only + substitutes the callable; the manager reads the new func's annotations + when it parses the term cfg. + """ + cls._ensure_twin_providers_imported() + + cfg_route_modules = cls._cfg_route_modules(cfg) + module_cache: dict[str, list[ModuleType]] = {} + searched: set[str] = set() + + swapped = 0 + missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) + for path, term in cls._walk_terms(cfg): + if not path or path[0] not in cls.WARP_MANAGED_GROUPS: + continue + location = ".".join(path) + for attr in ("func", "class_type"): + stable = getattr(term, attr, None) + if stable is None or not cls._is_swap_candidate(stable): + continue + origin = getattr(stable, "__module__", "") or "" + if origin not in module_cache: + module_cache[origin] = cls._twin_modules(origin, cfg_route_modules) + searched.update(m.__name__ for m in module_cache[origin]) + twin = cls._resolve_warp_twin(stable.__name__, module_cache[origin]) + if twin is None: + missing.append((location, attr, stable.__name__)) + continue + setattr(term, attr, twin) + swapped += 1 + + if missing: + lines = "\n ".join(f"{loc}.{attr}: no warp twin for {sym!r}" for loc, attr, sym in missing) + raise FrontendIncompatibleError( + f"warp env {label!r}: missing warp MDP twins (searched {sorted(searched)}):\n {lines}" + ) + + logger.info("frontend.warp: swapped %d MDP symbol(s) to warp twins", swapped) + + # ------------------------------------------------------------------ + # Workflow detection and direct-task resolution + # ------------------------------------------------------------------ + + @staticmethod + def _detect_workflow(cfg: Any) -> Workflow: + """Classify the env cfg into manager-based or direct (used to pick build path). + + Note: + The env cfg roots (ManagerBasedRLEnvCfg, DirectRLEnvCfg, + DirectMARLEnvCfg) do not share a common base class. When a new cfg + root is added, extend the isinstance tuples below. + """ + if isinstance(cfg, ManagerBasedRLEnvCfg): + return Workflow.MANAGER_BASED + if isinstance(cfg, (DirectRLEnvCfg, DirectMARLEnvCfg)): + return Workflow.DIRECT raise FrontendIncompatibleError( - f"warp env {label!r}: missing warp MDP twins (searched {sorted(searched)}):\n {lines}" + f"Unrecognised env cfg type {type(cfg).__name__!r};" + f" expected ManagerBasedRLEnvCfg / DirectRLEnvCfg / DirectMARLEnvCfg subclass." ) - logger.info("frontend.warp: swapped %d MDP symbol(s) to warp twins", swapped) - - -# --------------------------------------------------------------------------- -# Helpers -# --------------------------------------------------------------------------- - - -def _detect_workflow(cfg: Any) -> Workflow: - """Classify the env cfg into manager-based or direct (used to pick build path). - - Note: - The four env cfg roots (ManagerBasedEnvCfg, ManagerBasedRLEnvCfg, - DirectRLEnvCfg, DirectMARLEnvCfg) do not share a common base class. - When a new cfg root is added, extend the isinstance tuples below. - """ - if isinstance(cfg, ManagerBasedRLEnvCfg): - return Workflow.MANAGER_BASED - if isinstance(cfg, (DirectRLEnvCfg, DirectMARLEnvCfg)): - return Workflow.DIRECT - raise FrontendIncompatibleError( - f"Unrecognised env cfg type {type(cfg).__name__!r};" - f" expected ManagerBasedRLEnvCfg / DirectRLEnvCfg / DirectMARLEnvCfg subclass." - ) - - -def _resolve_direct_warp_class(task_id: str) -> type | None: - """Return the warp env class a stable direct task declares, if any. - - Stable direct registrations may carry a ``warp_entry_point`` kwarg of the - form ``"module.path:ClassName"`` (mirroring ``env_cfg_entry_point``) naming - the warp implementation of the same task. The class is constructed with the - *stable* cfg, so the task needs no parallel warp registration or duplicated - configuration. - """ - try: + @staticmethod + def _resolve_direct_warp_class(task_id: str) -> type | None: + """Return the warp env class a stable direct task declares, if any. + + Stable direct registrations may carry a ``warp_entry_point`` kwarg of + the form ``"module.path:ClassName"`` (mirroring ``env_cfg_entry_point``) + naming the warp implementation of the same task. The class is + constructed with the *stable* cfg, so the task needs no parallel warp + registration or duplicated configuration. + """ + try: + spec = gym.spec(task_id) + except gym.error.NameNotFound as exc: + raise FrontendIncompatibleError( + f"--frontend=warp: task {task_id!r} is not registered with gymnasium." + ) from exc + target = (spec.kwargs or {}).get("warp_entry_point") + if not isinstance(target, str): + return None + module_name, _, class_name = target.partition(":") + try: + module = importlib.import_module(module_name) + except ImportError as exc: + raise FrontendIncompatibleError( + f"--frontend=warp: task {task_id!r} declares warp_entry_point {target!r}," + f" but it failed to import: {exc}" + ) from exc + env_class = getattr(module, class_name, None) + if env_class is None: + raise FrontendIncompatibleError( + f"--frontend=warp: task {task_id!r} declares warp_entry_point {target!r}," + f" but {class_name!r} is not defined in {module_name!r}." + ) + return env_class + + @classmethod + def _assert_direct_warp_registration(cls, task_id: str) -> None: + """For direct workflows without a ``warp_entry_point``, the task must be warp-registered.""" spec = gym.spec(task_id) - except gym.error.NameNotFound as exc: - raise FrontendIncompatibleError(f"--frontend=warp: task {task_id!r} is not registered with gymnasium.") from exc - target = (spec.kwargs or {}).get("warp_entry_point") - if not isinstance(target, str): + ep = spec.entry_point + module = ep if isinstance(ep, str) else (getattr(ep, "__module__", "") or "") + if not module.startswith(cls.WARP_ROOT_PREFIXES): + raise FrontendIncompatibleError( + f"--frontend=warp on direct task {task_id!r}: entry_point {ep!r}" + f" is not under {list(cls.WARP_ROOT_PREFIXES)}. Direct tasks must either" + f" declare a `warp_entry_point` in their stable registration or be" + f" registered as a warp env class." + ) + + # ------------------------------------------------------------------ + # Twin resolution + # ------------------------------------------------------------------ + + @classmethod + def _match_route(cls, module: str) -> str | None: + """Return the routed warp MDP module for ``module``, longest prefix wins.""" + if not isinstance(module, str) or not module: + return None + best_key: str | None = None + for stable_prefix in cls._mdp_routes: + if module == stable_prefix or module.startswith(f"{stable_prefix}."): + if best_key is None or len(stable_prefix) > len(best_key): + best_key = stable_prefix + return cls._mdp_routes[best_key] if best_key is not None else None + + @staticmethod + def _import_routed_module(target: str) -> ModuleType: + """Import a registered route target; a broken registration is a hard error.""" + try: + return importlib.import_module(target) + except ImportError as exc: + raise FrontendIncompatibleError( + f"registered warp MDP route target {target!r} failed to import: {exc}" + ) from exc + + @classmethod + def _cfg_route_modules(cls, cfg: Any) -> list[ModuleType]: + """Warp MDP modules routed from the cfg's class hierarchy, subclass first. + + A stable cfg consumes terms through its task's ``mdp`` namespace, which + re-exports symbols that may be *defined* in core or shared packages. The + warp mirror of that namespace is therefore the primary place to resolve + twins, and it is found by routing the modules of ``type(cfg).__mro__`` — + the subclass module first (robot-specific cfgs), then base-cfg modules + (task-family bases). + """ + modules: list[ModuleType] = [] + for klass in type(cfg).__mro__: + target = cls._match_route(getattr(klass, "__module__", "") or "") + if target is None: + continue + module = cls._import_routed_module(target) + if module not in modules: + modules.append(module) + return modules + + @classmethod + def _twin_modules(cls, symbol_module: str, cfg_route_modules: list[ModuleType]) -> list[ModuleType]: + """Warp modules to consult for a stable symbol's twin, in preference order. + + 1. The warp mirrors of the cfg's own task MDP namespace + (:meth:`_cfg_route_modules`) — task-specific twins win, including + twins for symbols defined in core/shared packages. + 2. The warp mirror routed from the symbol's defining package — covers + terms borrowed from another task family's MDP package. + 3. The shared fallback module (where generic warp twins live). + """ + modules = list(cfg_route_modules) + target = cls._match_route(symbol_module) + if target is not None: + module = cls._import_routed_module(target) + if module not in modules: + modules.append(module) + try: + fallback_module = importlib.import_module(cls._FALLBACK_MDP_MODULE) + except ModuleNotFoundError as exc: + if exc.name != cls._FALLBACK_MDP_MODULE: + raise + logger.warning("frontend.warp: fallback mdp module %r not importable", cls._FALLBACK_MDP_MODULE) + else: + if fallback_module not in modules: + modules.append(fallback_module) + return modules + + @classmethod + def _ensure_twin_providers_imported(cls) -> None: + """Import the twin-provider package so its MDP routes are registered. + + Route registration happens as an import side effect of the experimental + task packages. A caller running ``--frontend=warp`` on a stable task id + has no other reason to import the provider package, so the swap + triggers it here. A missing provider package is not an error by itself + — the swap then fails with the explicit missing-twin report. + """ + try: + importlib.import_module(cls._TWIN_PROVIDER_PACKAGE) + except ModuleNotFoundError as exc: + # Only swallow "the provider package is not installed"; a genuine + # import error inside an existing package must surface. + if exc.name != cls._TWIN_PROVIDER_PACKAGE: + raise + logger.warning("frontend.warp: twin provider package %r is not installed", cls._TWIN_PROVIDER_PACKAGE) + + @classmethod + def _resolve_warp_twin(cls, name: str, modules: Iterable[ModuleType]) -> Any | None: + """Return the same-named symbol from ``modules`` that originates under the warp packages.""" + for module in modules: + candidate = getattr(module, name, None) + if candidate is None: + continue + origin = getattr(candidate, "__module__", "") or "" + if origin.startswith(cls.WARP_ROOT_PREFIXES): + return candidate return None - module_name, _, class_name = target.partition(":") - try: - module = importlib.import_module(module_name) - except ImportError as exc: - raise FrontendIncompatibleError( - f"--frontend=warp: task {task_id!r} declares warp_entry_point {target!r}, but it failed to import: {exc}" - ) from exc - env_class = getattr(module, class_name, None) - if env_class is None: - raise FrontendIncompatibleError( - f"--frontend=warp: task {task_id!r} declares warp_entry_point {target!r}," - f" but {class_name!r} is not defined in {module_name!r}." - ) - return env_class - -def _assert_direct_warp_registration(task_id: str) -> None: - """For direct workflows without a ``warp_entry_point``, the task must be warp-registered.""" - spec = gym.spec(task_id) - ep = spec.entry_point - module = ep if isinstance(ep, str) else (getattr(ep, "__module__", "") or "") - if not module.startswith(_WARP_ROOT_PREFIXES): - raise FrontendIncompatibleError( - f"--frontend=warp on direct task {task_id!r}: entry_point {ep!r}" - f" is not under {list(_WARP_ROOT_PREFIXES)}. Direct tasks must either" - f" declare a `warp_entry_point` in their stable registration or be" - f" registered as a warp env class." - ) + @classmethod + def _is_swap_candidate(cls, value: Any) -> bool: + """Heuristic: callable or class whose origin is *not already* warp.""" + if not callable(value): + return False + origin = getattr(value, "__module__", "") or "" + if origin.startswith(cls.WARP_ROOT_PREFIXES): + return False # already a warp twin (idempotent) + return True + + @staticmethod + def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], Any]]: + """Yield ``(path, term)`` for every MDP term cfg in the cfg tree. + + A "term" is a :class:`ManagerTermBaseCfg` (observation/reward/ + termination/event/curriculum) *or* an :class:`ActionTermCfg` — the + latter is a separate base that is **not** a ``ManagerTermBaseCfg`` + subclass, yet carries a swappable ``class_type``, so it must be matched + explicitly. + + Behavior at each node: + + * Match (a term cfg instance): yield ``(path, node)`` and stop — do not + descend into ``term.params`` / ``term.func`` / ``term.class_type``. + * Configclass: don't yield; recurse into every non-underscore *instance* + attribute (``vars(node)``), extending the path. ``observations``, + ``rewards``, ``events``, ``actions``, sub-groups like + ``observations.policy``, and anything nested deeper are reached + transparently. + * Anything else (plain Python data, callables, non-configclass objects): + stop. No yield, no recursion. + + Iterating the instance ``__dict__`` mirrors how the warp managers + consume group cfgs (they iterate ``cfg.__dict__.items()``), so the + walker sees exactly the terms the managers will see — including terms + assigned in ``__post_init__`` — while never descending into methods or + nested class objects, which live on the class rather than the instance. + + Driven entirely by type — no attribute names are hardcoded — so future + cfg layouts (extra observation groups, new nesting, etc.) are picked up + automatically as long as their terms subclass one of the term base cfgs. + """ + from isaaclab.managers.manager_term_cfg import ActionTermCfg, ManagerTermBaseCfg + + if isinstance(node, (ManagerTermBaseCfg, ActionTermCfg)): + yield path, node + return + if not hasattr(node, "__dataclass_fields__"): + return + for name, value in vars(node).items(): + if name.startswith("_") or value is None: + continue + yield from WarpFrontend._walk_terms(value, path + (name,)) -def _match_route(module: str) -> str | None: - """Return the routed warp MDP module for ``module``, longest prefix wins.""" - if not isinstance(module, str) or not module: - return None - best_key: str | None = None - for stable_prefix in _WARP_MDP_MODULE_ROUTES: - if module == stable_prefix or module.startswith(f"{stable_prefix}."): - if best_key is None or len(stable_prefix) > len(best_key): - best_key = stable_prefix - return _WARP_MDP_MODULE_ROUTES[best_key] if best_key is not None else None - - -def _import_routed_module(target: str) -> ModuleType: - """Import a registered route target; a broken registration is a hard error.""" - try: - return importlib.import_module(target) - except ImportError as exc: - raise FrontendIncompatibleError(f"registered warp MDP route target {target!r} failed to import: {exc}") from exc - - -def _cfg_route_modules(cfg: Any) -> list[ModuleType]: - """Warp MDP modules routed from the cfg's class hierarchy, subclass first. - - A stable cfg consumes terms through its task's ``mdp`` namespace, which - re-exports symbols that may be *defined* in core or shared packages. The - warp mirror of that namespace is therefore the primary place to resolve - twins, and it is found by routing the modules of ``type(cfg).__mro__`` — - the subclass module first (robot-specific cfgs), then base-cfg modules - (task-family bases). - """ - modules: list[ModuleType] = [] - for klass in type(cfg).__mro__: - target = _match_route(getattr(klass, "__module__", "") or "") - if target is None: - continue - module = _import_routed_module(target) - if module not in modules: - modules.append(module) - return modules - - -def _twin_modules(symbol_module: str, cfg_route_modules: list[ModuleType]) -> list[ModuleType]: - """Warp modules to consult for a stable symbol's twin, in preference order. - - 1. The warp mirrors of the cfg's own task MDP namespace - (:func:`_cfg_route_modules`) — task-specific twins win, including twins - for symbols defined in core/shared packages. - 2. The warp mirror routed from the symbol's defining package — covers terms - borrowed from another task family's MDP package. - 3. The shared :mod:`isaaclab_experimental.envs.mdp` fallback (where generic - warp twins live). - """ - modules = list(cfg_route_modules) - target = _match_route(symbol_module) - if target is not None: - module = _import_routed_module(target) - if module not in modules: - modules.append(module) - fallback = "isaaclab_experimental.envs.mdp" - try: - fallback_module = importlib.import_module(fallback) - except ModuleNotFoundError as exc: - if exc.name != fallback: - raise - logger.warning("frontend.warp: fallback mdp module %r not importable", fallback) - else: - if fallback_module not in modules: - modules.append(fallback_module) - return modules - - -def _ensure_twin_providers_imported() -> None: - """Import the twin-provider package so its MDP routes are registered. - - Route registration happens as an import side effect of the experimental - task packages. A caller running ``--frontend=warp`` on a stable task id - has no other reason to import :mod:`isaaclab_tasks_experimental`, so the - swap triggers it here. A missing provider package is not an error by - itself — the swap then fails with the explicit missing-twin report. - """ - try: - importlib.import_module(_TWIN_PROVIDER_PACKAGE) - except ModuleNotFoundError as exc: - # Only swallow "the provider package is not installed"; a genuine import - # error inside an existing package must surface. - if exc.name != _TWIN_PROVIDER_PACKAGE: - raise - logger.warning("frontend.warp: twin provider package %r is not installed", _TWIN_PROVIDER_PACKAGE) - - -def _resolve_warp_twin(name: str, modules: Iterable[ModuleType]) -> Any | None: - """Return the same-named symbol from ``modules`` that originates under the warp packages.""" - for module in modules: - candidate = getattr(module, name, None) - if candidate is None: - continue - origin = getattr(candidate, "__module__", "") or "" - if origin.startswith(_WARP_ROOT_PREFIXES): - return candidate - return None - - -def _is_swap_candidate(value: Any) -> bool: - """Heuristic: callable or class whose origin is *not already* warp.""" - if not callable(value): - return False - origin = getattr(value, "__module__", "") or "" - if origin.startswith(_WARP_ROOT_PREFIXES): - return False # already a warp twin (idempotent) - return True - - -def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[str, ...], Any]]: - """Yield ``(path, term)`` for every MDP term cfg in the cfg tree. - - A "term" is a :class:`ManagerTermBaseCfg` (observation/reward/termination/ - event/curriculum) *or* an :class:`ActionTermCfg` — the latter is a separate - base that is **not** a ``ManagerTermBaseCfg`` subclass, yet carries a - swappable ``class_type``, so it must be matched explicitly. - - Behavior at each node: - - * Match (a term cfg instance): yield ``(path, node)`` and stop — do not - descend into ``term.params`` / ``term.func`` / ``term.class_type``. - * Configclass: don't yield; recurse into every non-underscore *instance* - attribute (``vars(node)``), extending the path. ``observations``, - ``rewards``, ``events``, ``actions``, sub-groups like - ``observations.policy`` / ``observations.perception``, and anything - nested deeper are reached transparently. - * Anything else (plain Python data, callables, non-configclass objects): - stop. No yield, no recursion. - - Iterating the instance ``__dict__`` mirrors how the warp managers consume - group cfgs (they iterate ``cfg.__dict__.items()``), so the walker sees - exactly the terms the managers will see — including terms assigned in - ``__post_init__`` — while never descending into methods or nested class - objects, which live on the class rather than the instance. - - Driven entirely by type — no attribute names are hardcoded — so future - cfg layouts (extra observation groups, new nesting, etc.) are picked up - automatically as long as their terms subclass one of the term base cfgs. - """ - from isaaclab.managers.manager_term_cfg import ActionTermCfg, ManagerTermBaseCfg - - if isinstance(node, (ManagerTermBaseCfg, ActionTermCfg)): - yield path, node - return - if not hasattr(node, "__dataclass_fields__"): - return - for name, value in vars(node).items(): - if name.startswith("_") or value is None: - continue - yield from _walk_terms(value, path + (name,)) +# Module-level alias used by the task packages at import time. +register_mdp_route = WarpFrontend.register_mdp_route diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index f112a6ddf562..e32d80fd2b99 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -135,9 +135,9 @@ def _term(func=None, params: dict | None = None) -> RewardTermCfg: @pytest.fixture def fake_routes(monkeypatch: pytest.MonkeyPatch) -> dict[str, str]: - """Isolate the module-level route registry for a test.""" + """Isolate the WarpFrontend route registry for a test.""" routes: dict[str, str] = {} - monkeypatch.setattr(fe, "_WARP_MDP_MODULE_ROUTES", routes) + monkeypatch.setattr(fe.WarpFrontend, "_mdp_routes", routes) return routes @@ -245,19 +245,19 @@ def _cfg_with_physics(physics: Any) -> Any: def test_require_newton_passes_for_newton(): - fe._require_newton_physics(_cfg_with_physics(NewtonCfg()), "Isaac-Test-v0") # no raise + fe.WarpFrontend._require_newton_physics(_cfg_with_physics(NewtonCfg()), "Isaac-Test-v0") # no raise def test_require_newton_rejects_physx(): with pytest.raises(FrontendIncompatibleError) as exc: - fe._require_newton_physics(_cfg_with_physics(PhysxCfg()), "Isaac-Test-v0") + fe.WarpFrontend._require_newton_physics(_cfg_with_physics(PhysxCfg()), "Isaac-Test-v0") assert "presets=newton_mjwarp" in str(exc.value) assert "PhysxCfg" in str(exc.value) def test_require_newton_rejects_none(): with pytest.raises(FrontendIncompatibleError): - fe._require_newton_physics(_cfg_with_physics(None), "Isaac-Test-v0") + fe.WarpFrontend._require_newton_physics(_cfg_with_physics(None), "Isaac-Test-v0") # ====================================================================== @@ -271,7 +271,7 @@ def test_walk_terms_yields_each_term_with_its_path(): events=_EventsCfg(e1=EventTermCfg(func=_stable_func, mode="reset")), ) # Configclass instances aren't hashable, so collect paths only. - paths = {".".join(p) for p, _ in fe._walk_terms(cfg)} + paths = {".".join(p) for p, _ in fe.WarpFrontend._walk_terms(cfg)} assert paths == {"rewards.r1", "rewards.r2", "events.e1"} @@ -282,7 +282,7 @@ def test_walk_terms_descends_into_obs_subgroups(): perception=_ExtraObsGroup(o3=ObservationTermCfg(func=_stable_func)), ), ) - paths = {".".join(p) for p, _ in fe._walk_terms(cfg)} + paths = {".".join(p) for p, _ in fe.WarpFrontend._walk_terms(cfg)} # Discovery is purely type-driven; no obs group name is hardcoded. assert paths == {"observations.policy.o1", "observations.perception.o3"} @@ -291,7 +291,7 @@ def test_walk_terms_stops_at_terms(): # The walker must not descend into term.params / term.func — yields the term itself. nested_se_cfg = StableSceneEntityCfg(name="robot") cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": nested_se_cfg}))) - terms = list(fe._walk_terms(cfg)) + terms = list(fe.WarpFrontend._walk_terms(cfg)) assert len(terms) == 1 _, term = terms[0] assert isinstance(term, RewardTermCfg) @@ -300,12 +300,12 @@ def test_walk_terms_stops_at_terms(): def test_walk_terms_skips_non_configclass_attrs(): # A namespace without __dataclass_fields__ is not descended into. cfg = types.SimpleNamespace(some_plain_attr="hello") - assert list(fe._walk_terms(cfg)) == [] + assert list(fe.WarpFrontend._walk_terms(cfg)) == [] def test_walk_terms_skips_none_subtrees(): cfg = _CfgFixture(rewards=None, events=None) - assert list(fe._walk_terms(cfg)) == [] + assert list(fe.WarpFrontend._walk_terms(cfg)) == [] @configclass @@ -324,7 +324,7 @@ def test_walk_terms_ignores_nested_class_objects(): # ``cfg.__dict__`` consumption), so a nested class object — reachable as an # attribute on the instance — must never contribute paths. cfg = _GroupWithNestedClass(o1=ObservationTermCfg(func=_stable_func)) - paths = {".".join(p) for p, _ in fe._walk_terms(cfg)} + paths = {".".join(p) for p, _ in fe.WarpFrontend._walk_terms(cfg)} assert paths == {"o1"} @@ -338,13 +338,13 @@ def test_register_mdp_route_and_longest_prefix_match(fake_routes: dict[str, str] register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", "warp.humanoid.mdp") # Longest registered prefix wins. - assert fe._match_route("isaaclab_tasks.core.locomotion.humanoid.mdp.rewards") == "warp.humanoid.mdp" - assert fe._match_route("isaaclab_tasks.core.locomotion.ant.mdp") == "warp.locomotion.mdp" + assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion.humanoid.mdp.rewards") == "warp.humanoid.mdp" + assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion.ant.mdp") == "warp.locomotion.mdp" # Exact package match works too. - assert fe._match_route("isaaclab_tasks.core.locomotion.humanoid") == "warp.humanoid.mdp" + assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion.humanoid") == "warp.humanoid.mdp" # Prefix matching is per package segment, not per character. - assert fe._match_route("isaaclab_tasks.core.locomotion_extras.mdp") is None - assert fe._match_route("isaaclab.envs.mdp.rewards") is None + assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion_extras.mdp") is None + assert fe.WarpFrontend._match_route("isaaclab.envs.mdp.rewards") is None def test_register_mdp_route_is_idempotent(fake_routes: dict[str, str]): @@ -362,13 +362,13 @@ def test_register_mdp_route_rejects_conflicts(fake_routes: dict[str, str]): def test_cfg_route_modules_resolves_cfg_class_module(fake_routes: dict[str, str]): # Route this test module's own name so the fixture cfg class matches. register_mdp_route(__name__, "math") - assert fe._cfg_route_modules(_CfgFixture()) == [importlib.import_module("math")] + assert fe.WarpFrontend._cfg_route_modules(_CfgFixture()) == [importlib.import_module("math")] def test_cfg_route_modules_raises_on_broken_target(fake_routes: dict[str, str]): register_mdp_route(__name__, "definitely_not_an_importable_module") with pytest.raises(FrontendIncompatibleError): - fe._cfg_route_modules(_CfgFixture()) + fe.WarpFrontend._cfg_route_modules(_CfgFixture()) # ====================================================================== @@ -391,9 +391,11 @@ def _fake_mdp_module(name_to_symbol: dict[str, Any]) -> _FakeMdpModule: def _patch_twin_modules(monkeypatch: pytest.MonkeyPatch, modules: list[Any]) -> None: """Pin twin resolution to ``modules`` and keep unit tests hermetic.""" - monkeypatch.setattr(fe, "_ensure_twin_providers_imported", lambda: None) - monkeypatch.setattr(fe, "_cfg_route_modules", lambda cfg: []) - monkeypatch.setattr(fe, "_twin_modules", lambda symbol_module, cfg_route_modules: modules) + monkeypatch.setattr(fe.WarpFrontend, "_ensure_twin_providers_imported", classmethod(lambda cls: None)) + monkeypatch.setattr(fe.WarpFrontend, "_cfg_route_modules", classmethod(lambda cls, cfg: [])) + monkeypatch.setattr( + fe.WarpFrontend, "_twin_modules", classmethod(lambda cls, symbol_module, cfg_route_modules: modules) + ) def test_swap_mdp_swaps_func_and_class_type(monkeypatch: pytest.MonkeyPatch): @@ -403,7 +405,7 @@ def test_swap_mdp_swaps_func_and_class_type(monkeypatch: pytest.MonkeyPatch): term_action = _term() term_action.class_type = _StableActionCls # set attr to exercise class_type swap cfg = _CfgFixture(rewards=_RewardsCfg(r1=term_reward, r2=term_action)) - fe._swap_mdp(cfg, "Isaac-Test-v0") + fe.WarpFrontend._swap_mdp(cfg, "Isaac-Test-v0") assert cfg.rewards.r1.func is _warp_twin_func assert cfg.rewards.r2.class_type is _WarpActionCls @@ -412,7 +414,7 @@ def test_swap_mdp_missing_twin_raises_with_path_list(monkeypatch: pytest.MonkeyP _patch_twin_modules(monkeypatch, [_fake_mdp_module({})]) cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_stable_func))) with pytest.raises(FrontendIncompatibleError) as exc: - fe._swap_mdp(cfg, "Isaac-Test-v0") + fe.WarpFrontend._swap_mdp(cfg, "Isaac-Test-v0") msg = str(exc.value) assert "rewards.r1.func" in msg assert "_stable_func" in msg @@ -423,7 +425,7 @@ def test_swap_mdp_missing_twin_raises_with_path_list(monkeypatch: pytest.MonkeyP def test_swap_mdp_skips_already_warp(monkeypatch: pytest.MonkeyPatch): _patch_twin_modules(monkeypatch, [_fake_mdp_module({})]) cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(func=_warp_twin_func))) - fe._swap_mdp(cfg, "Isaac-Test-v0") # no raise + fe.WarpFrontend._swap_mdp(cfg, "Isaac-Test-v0") # no raise assert cfg.rewards.r1.func is _warp_twin_func @@ -438,7 +440,7 @@ def test_promote_scene_entity_cfgs_promotes_in_params(): r1=_term(params={"asset_cfg": StableSceneEntityCfg(name="robot", joint_names=["lf_hip"]), "scale": 1.0}) ) ) - fe._promote_scene_entity_cfgs(cfg) + fe.WarpFrontend._promote_scene_entity_cfgs(cfg) promoted = cfg.rewards.r1.params["asset_cfg"] assert isinstance(promoted, WarpSceneEntityCfg) assert promoted.name == "robot" @@ -455,7 +457,7 @@ def test_promote_scene_entity_cfgs_skips_already_warp(): warp = WarpSceneEntityCfg(name="robot", joint_names=["lf_hip"]) cfg = _CfgFixture(rewards=_RewardsCfg(r1=_term(params={"asset_cfg": warp}))) before = cfg.rewards.r1.params["asset_cfg"] - fe._promote_scene_entity_cfgs(cfg) + fe.WarpFrontend._promote_scene_entity_cfgs(cfg) after = cfg.rewards.r1.params["asset_cfg"] assert isinstance(after, WarpSceneEntityCfg) # The asset_cfg object was not replaced by another from_stable call. @@ -480,7 +482,7 @@ def test_promote_scene_entity_cfgs_walks_all_term_groups(): c1=EventTermCfg(func=_stable_func, mode="reset", params={"asset_cfg": StableSceneEntityCfg(name="c")}) ), ) - fe._promote_scene_entity_cfgs(cfg) + fe.WarpFrontend._promote_scene_entity_cfgs(cfg) # Warp-managed groups (rewards, observations incl. sub-groups, events) are promoted. assert isinstance(cfg.rewards.r1.params["asset_cfg"], WarpSceneEntityCfg) assert isinstance(cfg.observations.policy.o1.params["asset_cfg"], WarpSceneEntityCfg) @@ -502,29 +504,29 @@ def test_promote_scene_entity_cfgs_walks_all_term_groups(): def test_resolve_warp_twin_accepts_warp_origin(): module = types.SimpleNamespace(foo=_warp_twin_func) - assert fe._resolve_warp_twin("foo", [module]) is _warp_twin_func + assert fe.WarpFrontend._resolve_warp_twin("foo", [module]) is _warp_twin_func def test_resolve_warp_twin_rejects_stable_origin(): module = types.SimpleNamespace(foo=_stable_func) # same name, stable origin - assert fe._resolve_warp_twin("foo", [module]) is None + assert fe.WarpFrontend._resolve_warp_twin("foo", [module]) is None def test_resolve_warp_twin_returns_none_when_absent(): - assert fe._resolve_warp_twin("missing", [types.SimpleNamespace()]) is None + assert fe.WarpFrontend._resolve_warp_twin("missing", [types.SimpleNamespace()]) is None def test_is_swap_candidate_stable_callable(): - assert fe._is_swap_candidate(_stable_func) + assert fe.WarpFrontend._is_swap_candidate(_stable_func) def test_is_swap_candidate_rejects_warp_callable(): - assert not fe._is_swap_candidate(_warp_twin_func) + assert not fe.WarpFrontend._is_swap_candidate(_warp_twin_func) def test_is_swap_candidate_rejects_non_callables(): - assert not fe._is_swap_candidate(42) - assert not fe._is_swap_candidate("string") + assert not fe.WarpFrontend._is_swap_candidate(42) + assert not fe.WarpFrontend._is_swap_candidate("string") # ====================================================================== @@ -555,35 +557,36 @@ def _register_direct_stub_tasks(): def test_direct_guard_accepts_warp_rooted(): - fe._assert_direct_warp_registration("_Frontend-Test-Warp-Direct-v0") # no raise + fe.WarpFrontend._assert_direct_warp_registration("_Frontend-Test-Warp-Direct-v0") # no raise def test_direct_guard_rejects_stable_rooted(): with pytest.raises(FrontendIncompatibleError) as exc: - fe._assert_direct_warp_registration("_Frontend-Test-Stable-Direct-v0") + fe.WarpFrontend._assert_direct_warp_registration("_Frontend-Test-Stable-Direct-v0") assert "isaaclab_experimental" in str(exc.value) def test_resolve_direct_warp_class_returns_declared_class(): import types as types_module - assert fe._resolve_direct_warp_class("_Frontend-Test-Declared-Direct-v0") is types_module.SimpleNamespace + env_class = fe.WarpFrontend._resolve_direct_warp_class("_Frontend-Test-Declared-Direct-v0") + assert env_class is types_module.SimpleNamespace def test_resolve_direct_warp_class_returns_none_without_declaration(): - assert fe._resolve_direct_warp_class("_Frontend-Test-Stable-Direct-v0") is None + assert fe.WarpFrontend._resolve_direct_warp_class("_Frontend-Test-Stable-Direct-v0") is None def test_resolve_direct_warp_class_rejects_broken_module(): with pytest.raises(FrontendIncompatibleError): - fe._resolve_direct_warp_class("_Frontend-Test-Broken-Direct-v0") + fe.WarpFrontend._resolve_direct_warp_class("_Frontend-Test-Broken-Direct-v0") def test_resolve_direct_warp_class_rejects_missing_class(): with pytest.raises(FrontendIncompatibleError): - fe._resolve_direct_warp_class("_Frontend-Test-Missing-Class-Direct-v0") + fe.WarpFrontend._resolve_direct_warp_class("_Frontend-Test-Missing-Class-Direct-v0") def test_resolve_direct_warp_class_rejects_unknown_task(): with pytest.raises(FrontendIncompatibleError): - fe._resolve_direct_warp_class("Frontend-Test-NotRegistered-v0") + fe.WarpFrontend._resolve_direct_warp_class("Frontend-Test-NotRegistered-v0") From e1066c21a80486b995fe6fcd1010d6358edd12de Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 01:23:05 -0700 Subject: [PATCH 31/36] Make the warp frontend module warp-only The shared RL CLI already peels off the torch path before importing the optional isaaclab_experimental package, so the frontend's own torch branch (module-level build() with a Frontend enum) was dead code that duplicated the gym.make dispatch. Remove it: create_isaaclab_env owns the torch/warp dispatch and calls WarpFrontend.build_env directly, and the module's public surface shrinks to WarpFrontend, Workflow, register_mdp_route, and the error type. Callers use WarpFrontend.adapt_cfg in place of the adapt_cfg_for_warp alias. --- scripts/reinforcement_learning/common.py | 9 +- .../test_reinforcement_learning_common.py | 8 +- .../changelog.d/warp-manager-bridge.rst | 2 +- .../isaaclab_experimental/envs/frontend.py | 91 ++++--------------- .../envs/manager_based_rl_env_warp.py | 4 +- .../test/envs/test_frontend.py | 19 +--- .../test/envs/test_frontend_cfg_conversion.py | 6 +- 7 files changed, 38 insertions(+), 101 deletions(-) diff --git a/scripts/reinforcement_learning/common.py b/scripts/reinforcement_learning/common.py index efebd09747fe..cd00334e393c 100644 --- a/scripts/reinforcement_learning/common.py +++ b/scripts/reinforcement_learning/common.py @@ -440,13 +440,14 @@ def create_isaaclab_env( The created Gymnasium environment. """ render_mode = "rgb_array" if args_cli.video else None - frontend = args_cli.frontend - if frontend == "torch": + if args_cli.frontend == "torch": env = gym.make(task, cfg=env_cfg, render_mode=render_mode) else: - from isaaclab_experimental.envs.frontend import build as build_frontend_env + # Imported lazily: the warp frontend lives in the optional + # isaaclab_experimental package, and the torch path must work without it. + from isaaclab_experimental.envs.frontend import WarpFrontend - env = build_frontend_env(frontend, env_cfg, task, render_mode=render_mode) + env = WarpFrontend.build_env(env_cfg, task, render_mode=render_mode) if convert_marl_to_single_agent and isinstance(env.unwrapped.cfg, DirectMARLEnvCfg): from isaaclab.envs import multi_agent_to_single_agent diff --git a/source/isaaclab/test/test_reinforcement_learning_common.py b/source/isaaclab/test/test_reinforcement_learning_common.py index 9de4173bd8f7..9e2b4c24e701 100644 --- a/source/isaaclab/test/test_reinforcement_learning_common.py +++ b/source/isaaclab/test/test_reinforcement_learning_common.py @@ -262,17 +262,17 @@ def test_create_isaaclab_env_uses_selected_warp_frontend(monkeypatch: pytest.Mon env_cfg = object() calls: list[tuple[Any, ...]] = [] - def fake_build(frontend: str, cfg: Any, task: str, **kwargs: Any) -> Any: - calls.append((frontend, cfg, task, kwargs)) + def fake_build_env(cfg: Any, task: str, **kwargs: Any) -> Any: + calls.append((cfg, task, kwargs)) return expected_env - monkeypatch.setattr(frontend_module, "build", fake_build) + monkeypatch.setattr(frontend_module.WarpFrontend, "build_env", fake_build_env) args_cli = argparse.Namespace(video=True, frontend="warp") env = create_isaaclab_env("Isaac-Test", env_cfg, args_cli, convert_marl_to_single_agent=False) assert env is expected_env - assert calls == [("warp", env_cfg, "Isaac-Test", {"render_mode": "rgb_array"})] + assert calls == [(env_cfg, "Isaac-Test", {"render_mode": "rgb_array"})] def test_dispatch_library_entrypoint_shows_help_without_library( diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 9cb34541bee0..1d56783ad0e9 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -19,7 +19,7 @@ Changed * Changed :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` to adapt its configuration in ``__init__`` via - :func:`~isaaclab_experimental.envs.frontend.adapt_cfg_for_warp`, so + :meth:`~isaaclab_experimental.envs.frontend.WarpFrontend.adapt_cfg`, so registered warp task variants can derive from stable configurations instead of duplicating them. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index ca5174c479f5..685fba4145bf 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -3,11 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Runtime selector for IsaacLab tasks (``--frontend {torch,warp}``). +"""Warp runtime frontend for IsaacLab tasks (``--frontend warp``). -:func:`build` decides which runtime constructs the env: torch via ``gym.make``, -or warp via :class:`WarpFrontend`, which encapsulates everything the warp -runtime needs from a stable task definition: +:class:`WarpFrontend` encapsulates everything the warp runtime needs from a +stable task definition: * Manager-based tasks: adapt the stable cfg in place (Newton physics check, :class:`SceneEntityCfg` promotion, MDP twin swap) and construct @@ -18,7 +17,9 @@ via its ``warp_entry_point`` kwarg, sharing the stable cfg. Task packages declare where their warp MDP twins live with -:func:`register_mdp_route`; the frontend holds no per-task table. +:func:`register_mdp_route`; the frontend holds no per-task table. The torch +runtime never touches this module — the shared RL CLI dispatches to plain +``gym.make`` before importing it, so this (optional) package stays warp-only. """ from __future__ import annotations @@ -39,28 +40,13 @@ __all__ = [ - "Frontend", "FrontendIncompatibleError", "WarpFrontend", "Workflow", - "adapt_cfg_for_warp", - "build", "register_mdp_route", ] -# --------------------------------------------------------------------------- -# Enums + error -# --------------------------------------------------------------------------- - - -class Frontend(StrEnum): - """Runtime selector exposed by ``--frontend``.""" - - TORCH = "torch" - WARP = "warp" - - class Workflow(StrEnum): """Manager-based vs direct env workflow.""" @@ -69,55 +55,7 @@ class Workflow(StrEnum): class FrontendIncompatibleError(RuntimeError): - """Raised when the chosen frontend can't run the requested task.""" - - -# --------------------------------------------------------------------------- -# Public entry points -# --------------------------------------------------------------------------- - - -def build( - frontend: Frontend | str, - env_cfg: Any, - task_id: str, - **construct_kwargs: Any, -) -> gym.Env: - """Construct the env on the selected runtime. - - Args: - frontend: ``"torch"`` (default IsaacLab path) or ``"warp"`` - (:class:`WarpFrontend`). - env_cfg: Stable env cfg. Mutated in place when ``frontend == "warp"``. - task_id: Gym registration id, e.g. ``"Isaac-Cartpole"``. - **construct_kwargs: Forwarded to the env constructor (``render_mode``, …). - - Returns: - The constructed :class:`gym.Env`. - - Raises: - FrontendIncompatibleError: If the warp runtime can't run the task - (wrong physics, missing MDP twins, direct task without a warp - implementation). - """ - frontend = Frontend(frontend) - if frontend is Frontend.TORCH: - return gym.make(task_id, cfg=env_cfg, **construct_kwargs) - return WarpFrontend.build_env(env_cfg, task_id, **construct_kwargs) - - -def adapt_cfg_for_warp(cfg: Any) -> None: - """Mutate a stable manager-based ``cfg`` in place so warp managers can consume it. - - Functional alias for :meth:`WarpFrontend.adapt_cfg`, used by - :class:`ManagerBasedRLEnvWarp` in its ``__init__``. - """ - WarpFrontend.adapt_cfg(cfg) - - -# --------------------------------------------------------------------------- -# Warp frontend -# --------------------------------------------------------------------------- + """Raised when the warp frontend can't run the requested task.""" class WarpFrontend: @@ -206,7 +144,18 @@ def register_mdp_route(cls, stable_package: str, warp_mdp_module: str) -> None: @classmethod def build_env(cls, env_cfg: Any, task_id: str, **construct_kwargs: Any) -> gym.Env: - """Construct the warp env for ``task_id`` from a stable env cfg.""" + """Construct the warp env for ``task_id`` from a stable env cfg. + + Args: + env_cfg: Stable env cfg. Manager-based cfgs are mutated in place. + task_id: Gym registration id, e.g. ``"Isaac-Cartpole"``. + **construct_kwargs: Forwarded to the env constructor (``render_mode``, …). + + Raises: + FrontendIncompatibleError: If the warp runtime can't run the task + (wrong physics, missing MDP twins, direct task without a warp + implementation). + """ if cls._detect_workflow(env_cfg) is Workflow.DIRECT: return cls._build_direct_env(env_cfg, task_id, **construct_kwargs) return cls._build_manager_env(env_cfg, **construct_kwargs) @@ -390,7 +339,7 @@ def _swap_mdp(cls, cfg: Any, label: str) -> None: @staticmethod def _detect_workflow(cfg: Any) -> Workflow: - """Classify the env cfg into manager-based or direct (used to pick build path). + """Classify the env cfg into manager-based or direct (used to pick the build path). Note: The env cfg roots (ManagerBasedRLEnvCfg, DirectRLEnvCfg, diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py index 502c9a132042..1c3535e887ec 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_rl_env_warp.py @@ -97,9 +97,9 @@ def __init__(self, cfg: ManagerBasedRLEnvCfg, render_mode: str | None = None, ** # promotion, MDP twin swap). Idempotent: a warp-native cfg passes through # unchanged, and a stable-derived cfg (``--frontend=warp`` or a registered # warp task variant subclassing a stable cfg) is adapted in place. - from isaaclab_experimental.envs.frontend import adapt_cfg_for_warp + from isaaclab_experimental.envs.frontend import WarpFrontend - adapt_cfg_for_warp(cfg) + WarpFrontend.adapt_cfg(cfg) # -- counter for curriculum self.common_step_counter = 0 diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index e32d80fd2b99..859f0b346769 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -7,7 +7,7 @@ Pure-Python unit tests; no app launch. Covers: -* :class:`Frontend` / :class:`Workflow` enum surface. +* :class:`Workflow` enum surface. * :func:`SceneEntityCfg.from_stable` field copy. * :func:`_require_newton_physics` hard-check. * :func:`_walk_terms` recursive ManagerTermBaseCfg discovery over instance @@ -34,10 +34,9 @@ import isaaclab_experimental.envs.frontend as fe import pytest from isaaclab_experimental.envs.frontend import ( - Frontend, FrontendIncompatibleError, + WarpFrontend, Workflow, - build, register_mdp_route, ) from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as WarpSceneEntityCfg @@ -146,18 +145,6 @@ def fake_routes(monkeypatch: pytest.MonkeyPatch) -> dict[str, str]: # ====================================================================== -def test_frontend_values(): - assert Frontend.TORCH == "torch" - assert Frontend.WARP == "warp" - - -def test_frontend_coercion(): - assert Frontend("torch") is Frontend.TORCH - assert Frontend("warp") is Frontend.WARP - with pytest.raises(ValueError): - Frontend("kit") - - def test_workflow_values(): assert Workflow.MANAGER_BASED == "manager_based" assert Workflow.DIRECT == "direct" @@ -182,7 +169,7 @@ def fake_env(*, cfg: Any, **kwargs: Any) -> Any: return expected_env with patch.object(envs, "ManagerBasedRLEnvWarp", fake_env): - env = build("warp", cfg, "Isaac-Test", render_mode="rgb_array") + env = WarpFrontend.build_env(cfg, "Isaac-Test", render_mode="rgb_array") assert env is expected_env assert calls == [(cfg, {"render_mode": "rgb_array"})] diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index 4fc8d100675b..f94ba002fb6c 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -5,7 +5,7 @@ """Coverage tests for warp task configuration adaptation. -Two sweeps, both running :func:`adapt_cfg_for_warp` — the same adaptation +Two sweeps, both running :meth:`WarpFrontend.adapt_cfg` — the same adaptation :class:`~isaaclab_experimental.envs.ManagerBasedRLEnvWarp` runs in its ``__init__``: @@ -27,7 +27,7 @@ import gymnasium as gym import isaaclab_tasks_experimental # noqa: F401 import pytest -from isaaclab_experimental.envs.frontend import adapt_cfg_for_warp +from isaaclab_experimental.envs.frontend import WarpFrontend from isaaclab_newton.physics import NewtonCfg # Registering the task packages is the whole point — import for side effects. @@ -74,7 +74,7 @@ def _load_adapted_cfg(cfg_entry_point: str): cfg = resolve_presets(cfg, selected=("newton_mjwarp",)) assert isinstance(cfg.sim.physics, NewtonCfg), "task does not provide a newton_mjwarp physics preset" # Raises FrontendIncompatibleError if any warp-managed term lacks a warp twin. - adapt_cfg_for_warp(cfg) + WarpFrontend.adapt_cfg(cfg) return cfg From 8694427778b94d829eb343d3afdaf21f0989fb6e Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 15:36:54 -0700 Subject: [PATCH 32/36] Resolve warp twins by package mirror instead of a registry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The experimental tree now mirrors the stable tree exactly, so twin routing needs no declarations: mirror the module root (isaaclab -> isaaclab_experimental, isaaclab_tasks -> isaaclab_tasks_experimental) and look the symbol up on the nearest .mdp package of the mirrored path — the cfg's own task namespace first, then the symbol's defining package. Resolution is a pure function of the installed package tree; misses accumulate across the whole cfg and are reported in a single hard failure listing every missing twin and all searched modules. This deletes register_mdp_route, the route registry, the twin-provider side-effect import, and all five task-package registration calls. The humanoid MDP twins move to core/locomotion/mdp — the true mirror of the stable shared locomotion package — which also removes the Ant special case (both tasks now resolve mechanically). --- .../isaaclab_experimental/envs/frontend.py | 197 +++++++----------- .../test/envs/test_frontend.py | 85 ++++---- .../core/cartpole/__init__.py | 5 - .../core/locomotion/__init__.py | 8 +- .../core/locomotion/ant/__init__.py | 20 +- .../core/locomotion/humanoid/__init__.py | 16 +- .../locomotion/{humanoid => }/mdp/__init__.py | 0 .../{humanoid => }/mdp/__init__.pyi | 0 .../{humanoid => }/mdp/observations.py | 0 .../locomotion/{humanoid => }/mdp/rewards.py | 0 .../core/reach/__init__.py | 5 - .../core/velocity/__init__.py | 6 - 12 files changed, 132 insertions(+), 210 deletions(-) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/{humanoid => }/mdp/__init__.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/{humanoid => }/mdp/__init__.pyi (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/{humanoid => }/mdp/observations.py (100%) rename source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/{humanoid => }/mdp/rewards.py (100%) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 685fba4145bf..29d14191a9bd 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -16,15 +16,20 @@ * Direct tasks: construct the warp env class the stable registration declares via its ``warp_entry_point`` kwarg, sharing the stable cfg. -Task packages declare where their warp MDP twins live with -:func:`register_mdp_route`; the frontend holds no per-task table. The torch -runtime never touches this module — the shared RL CLI dispatches to plain -``gym.make`` before importing it, so this (optional) package stays warp-only. +Twin resolution is purely mechanical: the experimental packages mirror the +stable tree (``isaaclab.* ↔ isaaclab_experimental.*``, +``isaaclab_tasks.* ↔ isaaclab_tasks_experimental.*``), and a stable symbol's +twin is looked up by name on the nearest ``.mdp`` package of the mirrored +path. There is no registration; anything unresolved is collected and reported +in one hard failure. The torch runtime never touches this module — the shared +RL CLI dispatches to plain ``gym.make`` before importing it, so this +(optional) package stays warp-only. """ from __future__ import annotations import importlib +import importlib.util import logging from collections.abc import Iterable, Iterator from enum import StrEnum @@ -43,7 +48,6 @@ "FrontendIncompatibleError", "WarpFrontend", "Workflow", - "register_mdp_route", ] @@ -61,17 +65,21 @@ class FrontendIncompatibleError(RuntimeError): class WarpFrontend: """Builds environments on the warp runtime from stable task definitions. - The class is a stateless namespace apart from the MDP route registry - (:attr:`_mdp_routes`), which experimental task packages populate at import - time via :meth:`register_mdp_route`. The stable and experimental task trees - mirror each other (``isaaclab_tasks.core.X`` ↔ - ``isaaclab_tasks_experimental.core.X``), so most routes are the mechanical - mirror; the registry keeps routing explicit and accommodates exceptions - (the Ant task borrows the Humanoid twins). + The class is a stateless namespace: twin resolution is a pure function of + the stable module paths and the mirrored package tree (:attr:`MIRROR_ROOTS`); + there is no registry and no import-order dependence. """ + # Stable package roots mirrored by their warp implementation packages. Twin + # resolution is purely mechanical: mirror the root, then look up the nearest + # enclosing ``.mdp`` package on the mirrored path. + MIRROR_ROOTS: ClassVar[dict[str, str]] = { + "isaaclab_tasks": "isaaclab_tasks_experimental", + "isaaclab": "isaaclab_experimental", + } + # Prefixes that identify warp-origin symbols and registrations. - WARP_ROOT_PREFIXES: ClassVar[tuple[str, ...]] = ("isaaclab_experimental", "isaaclab_tasks_experimental") + WARP_ROOT_PREFIXES: ClassVar[tuple[str, ...]] = tuple(MIRROR_ROOTS.values()) # Top-level cfg groups whose managers run warp-first. Only terms under these # are adapted (SceneEntityCfg promotion + MDP twin swap). The event manager @@ -86,58 +94,6 @@ class WarpFrontend: {"observations", "rewards", "terminations", "actions", "events"} ) - # Root package that provides task-specific warp MDP twins. Imported (lazily, - # at swap time) so its task packages run their register_mdp_route() calls - # even when the caller only imported the stable task package. - _TWIN_PROVIDER_PACKAGE: ClassVar[str] = "isaaclab_tasks_experimental" - - # Shared fallback module holding generic warp twins. - _FALLBACK_MDP_MODULE: ClassVar[str] = "isaaclab_experimental.envs.mdp" - - # Stable package prefixes mapped to the warp MDP module that twins their - # terms. Populated via register_mdp_route(); never edited here. - _mdp_routes: ClassVar[dict[str, str]] = {} - - # ------------------------------------------------------------------ - # Route registry - # ------------------------------------------------------------------ - - @classmethod - def register_mdp_route(cls, stable_package: str, warp_mdp_module: str) -> None: - """Register the warp MDP module that twins a stable package's terms. - - Experimental task packages call this at import time to declare where - the warp twins of a stable task's MDP terms live. Twin lookup is by - symbol name on ``warp_mdp_module`` itself, mirroring how a stable cfg - consumes its ``mdp`` namespace — so the module should re-export - everything the task needs (task-specific twins plus the generic - forwards). - - Two kinds of keys are useful: - - * A *task package* (e.g. ``"isaaclab_tasks.core.reach"``) routes every - cfg class defined under it. This also covers terms whose stable - functions are defined in core/shared packages but overridden by - task-specific twins. - * An *MDP package* (e.g. ``"isaaclab_tasks.core.locomotion.humanoid.mdp"``) - routes symbols *defined* under it, which serves other tasks that - borrow those terms. - - Args: - stable_package: Stable package prefix to route (longest match wins). - warp_mdp_module: Warp MDP module providing the twins, e.g. - ``"isaaclab_tasks_experimental.core.cartpole.mdp"``. - - Raises: - ValueError: If ``stable_package`` is already routed to a different module. - """ - existing = cls._mdp_routes.get(stable_package) - if existing is not None and existing != warp_mdp_module: - raise ValueError( - f"MDP route conflict for {stable_package!r}: already routed to {existing!r}, got {warp_mdp_module!r}." - ) - cls._mdp_routes[stable_package] = warp_mdp_module - # ------------------------------------------------------------------ # Env construction # ------------------------------------------------------------------ @@ -298,8 +254,6 @@ def _swap_mdp(cls, cfg: Any, label: str) -> None: substitutes the callable; the manager reads the new func's annotations when it parses the term cfg. """ - cls._ensure_twin_providers_imported() - cfg_route_modules = cls._cfg_route_modules(cfg) module_cache: dict[str, list[ModuleType]] = {} searched: set[str] = set() @@ -409,44 +363,68 @@ def _assert_direct_warp_registration(cls, task_id: str) -> None: # ------------------------------------------------------------------ @classmethod - def _match_route(cls, module: str) -> str | None: - """Return the routed warp MDP module for ``module``, longest prefix wins.""" + def _mirror_module(cls, module: str) -> str | None: + """Mechanical mirror of a stable module path, or ``None`` if not mirrored.""" if not isinstance(module, str) or not module: return None - best_key: str | None = None - for stable_prefix in cls._mdp_routes: - if module == stable_prefix or module.startswith(f"{stable_prefix}."): - if best_key is None or len(stable_prefix) > len(best_key): - best_key = stable_prefix - return cls._mdp_routes[best_key] if best_key is not None else None + root, _, rest = module.partition(".") + mirror_root = cls.MIRROR_ROOTS.get(root) + if mirror_root is None: + return None + return f"{mirror_root}.{rest}" if rest else mirror_root @staticmethod - def _import_routed_module(target: str) -> ModuleType: - """Import a registered route target; a broken registration is a hard error.""" + def _nearest_mdp_module(mirrored: str) -> str | None: + """Deepest existing ``.mdp`` package on a mirrored module path. + + If the path already contains an ``.mdp`` segment, the search starts at + that boundary (``...velocity.mdp.rewards`` resolves to + ``...velocity.mdp``); otherwise the path is walked upward until a + mirrored ``.mdp`` package exists. Existence is probed with + :func:`importlib.util.find_spec`; a prefix that does not exist simply + ends that probe, so resolution is a pure function of the installed + package tree. + """ + parts = mirrored.split(".") + if "mdp" in parts: + parts = parts[: parts.index("mdp")] + for depth in range(len(parts), 0, -1): + candidate = ".".join([*parts[:depth], "mdp"]) + try: + if importlib.util.find_spec(candidate) is not None: + return candidate + except ModuleNotFoundError: + continue + return None + + @staticmethod + def _import_twin_module(target: str) -> ModuleType: + """Import a resolved twin module; a module that exists but breaks is a hard error.""" try: return importlib.import_module(target) except ImportError as exc: - raise FrontendIncompatibleError( - f"registered warp MDP route target {target!r} failed to import: {exc}" - ) from exc + raise FrontendIncompatibleError(f"warp twin module {target!r} exists but failed to import: {exc}") from exc @classmethod def _cfg_route_modules(cls, cfg: Any) -> list[ModuleType]: - """Warp MDP modules routed from the cfg's class hierarchy, subclass first. + """Warp MDP mirrors of the cfg's class hierarchy, subclass first. A stable cfg consumes terms through its task's ``mdp`` namespace, which re-exports symbols that may be *defined* in core or shared packages. The warp mirror of that namespace is therefore the primary place to resolve - twins, and it is found by routing the modules of ``type(cfg).__mro__`` — + twins; it is found by mirroring the modules of ``type(cfg).__mro__`` — the subclass module first (robot-specific cfgs), then base-cfg modules (task-family bases). """ modules: list[ModuleType] = [] for klass in type(cfg).__mro__: - target = cls._match_route(getattr(klass, "__module__", "") or "") + mirrored = cls._mirror_module(getattr(klass, "__module__", "") or "") + if mirrored is None: + continue + target = cls._nearest_mdp_module(mirrored) if target is None: continue - module = cls._import_routed_module(target) + module = cls._import_twin_module(target) if module not in modules: modules.append(module) return modules @@ -458,46 +436,21 @@ def _twin_modules(cls, symbol_module: str, cfg_route_modules: list[ModuleType]) 1. The warp mirrors of the cfg's own task MDP namespace (:meth:`_cfg_route_modules`) — task-specific twins win, including twins for symbols defined in core/shared packages. - 2. The warp mirror routed from the symbol's defining package — covers - terms borrowed from another task family's MDP package. - 3. The shared fallback module (where generic warp twins live). + 2. The mirror of the symbol's defining package — covers terms borrowed + from another task family and, for core-defined symbols, the shared + :mod:`isaaclab_experimental.envs.mdp` twins (the mirror of + :mod:`isaaclab.envs.mdp`). """ modules = list(cfg_route_modules) - target = cls._match_route(symbol_module) - if target is not None: - module = cls._import_routed_module(target) - if module not in modules: - modules.append(module) - try: - fallback_module = importlib.import_module(cls._FALLBACK_MDP_MODULE) - except ModuleNotFoundError as exc: - if exc.name != cls._FALLBACK_MDP_MODULE: - raise - logger.warning("frontend.warp: fallback mdp module %r not importable", cls._FALLBACK_MDP_MODULE) - else: - if fallback_module not in modules: - modules.append(fallback_module) + mirrored = cls._mirror_module(symbol_module) + if mirrored is not None: + target = cls._nearest_mdp_module(mirrored) + if target is not None: + module = cls._import_twin_module(target) + if module not in modules: + modules.append(module) return modules - @classmethod - def _ensure_twin_providers_imported(cls) -> None: - """Import the twin-provider package so its MDP routes are registered. - - Route registration happens as an import side effect of the experimental - task packages. A caller running ``--frontend=warp`` on a stable task id - has no other reason to import the provider package, so the swap - triggers it here. A missing provider package is not an error by itself - — the swap then fails with the explicit missing-twin report. - """ - try: - importlib.import_module(cls._TWIN_PROVIDER_PACKAGE) - except ModuleNotFoundError as exc: - # Only swallow "the provider package is not installed"; a genuine - # import error inside an existing package must surface. - if exc.name != cls._TWIN_PROVIDER_PACKAGE: - raise - logger.warning("frontend.warp: twin provider package %r is not installed", cls._TWIN_PROVIDER_PACKAGE) - @classmethod def _resolve_warp_twin(cls, name: str, modules: Iterable[ModuleType]) -> Any | None: """Return the same-named symbol from ``modules`` that originates under the warp packages.""" @@ -563,7 +516,3 @@ def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[s if name.startswith("_") or value is None: continue yield from WarpFrontend._walk_terms(value, path + (name,)) - - -# Module-level alias used by the task packages at import time. -register_mdp_route = WarpFrontend.register_mdp_route diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index 859f0b346769..b0ad962082f1 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -12,8 +12,8 @@ * :func:`_require_newton_physics` hard-check. * :func:`_walk_terms` recursive ManagerTermBaseCfg discovery over instance attributes (nested class objects are not descended into). -* :func:`register_mdp_route` / :func:`_match_route` route registry. -* :func:`_cfg_route_modules` cfg-hierarchy route resolution. +* :meth:`_mirror_module` / :meth:`_nearest_mdp_module` deterministic mirror + resolution and :meth:`_cfg_route_modules` cfg-hierarchy resolution. * :func:`_promote_scene_entity_cfgs` walks ``term.params`` dicts. * :func:`_swap_mdp` swaps ``func`` *and* ``class_type``; raises with a path list when twins are missing. @@ -25,7 +25,6 @@ from __future__ import annotations import contextlib -import importlib import types from typing import Any from unittest.mock import patch @@ -37,7 +36,6 @@ FrontendIncompatibleError, WarpFrontend, Workflow, - register_mdp_route, ) from isaaclab_experimental.managers.scene_entity_cfg import SceneEntityCfg as WarpSceneEntityCfg from isaaclab_newton.physics import NewtonCfg @@ -132,14 +130,6 @@ def _term(func=None, params: dict | None = None) -> RewardTermCfg: return RewardTermCfg(func=func or _stable_func, weight=1.0, params=params or {}) -@pytest.fixture -def fake_routes(monkeypatch: pytest.MonkeyPatch) -> dict[str, str]: - """Isolate the WarpFrontend route registry for a test.""" - routes: dict[str, str] = {} - monkeypatch.setattr(fe.WarpFrontend, "_mdp_routes", routes) - return routes - - # ====================================================================== # Enums # ====================================================================== @@ -316,46 +306,52 @@ def test_walk_terms_ignores_nested_class_objects(): # ====================================================================== -# Route registry +# Mirror resolution # ====================================================================== -def test_register_mdp_route_and_longest_prefix_match(fake_routes: dict[str, str]): - register_mdp_route("isaaclab_tasks.core.locomotion", "warp.locomotion.mdp") - register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", "warp.humanoid.mdp") - - # Longest registered prefix wins. - assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion.humanoid.mdp.rewards") == "warp.humanoid.mdp" - assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion.ant.mdp") == "warp.locomotion.mdp" - # Exact package match works too. - assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion.humanoid") == "warp.humanoid.mdp" - # Prefix matching is per package segment, not per character. - assert fe.WarpFrontend._match_route("isaaclab_tasks.core.locomotion_extras.mdp") is None - assert fe.WarpFrontend._match_route("isaaclab.envs.mdp.rewards") is None - - -def test_register_mdp_route_is_idempotent(fake_routes: dict[str, str]): - register_mdp_route("isaaclab_tasks.core.cartpole", "warp.cartpole.mdp") - register_mdp_route("isaaclab_tasks.core.cartpole", "warp.cartpole.mdp") # no raise - assert fake_routes == {"isaaclab_tasks.core.cartpole": "warp.cartpole.mdp"} - +def test_mirror_module_maps_stable_roots(): + assert ( + fe.WarpFrontend._mirror_module("isaaclab_tasks.core.velocity.mdp.rewards") + == "isaaclab_tasks_experimental.core.velocity.mdp.rewards" + ) + assert fe.WarpFrontend._mirror_module("isaaclab.envs.mdp.events") == "isaaclab_experimental.envs.mdp.events" + assert fe.WarpFrontend._mirror_module("isaaclab_tasks") == "isaaclab_tasks_experimental" + # Unmirrored roots are not resolvable. + assert fe.WarpFrontend._mirror_module("torch.nn.functional") is None + assert fe.WarpFrontend._mirror_module("") is None + + +def test_nearest_mdp_module_truncates_at_mdp_boundary(): + # A symbol module resolves to its own mdp package on the mirrored path. + assert ( + fe.WarpFrontend._nearest_mdp_module("isaaclab_tasks_experimental.core.locomotion.mdp.rewards") + == "isaaclab_tasks_experimental.core.locomotion.mdp" + ) + assert fe.WarpFrontend._nearest_mdp_module("isaaclab_experimental.envs.mdp.events") == ( + "isaaclab_experimental.envs.mdp" + ) -def test_register_mdp_route_rejects_conflicts(fake_routes: dict[str, str]): - register_mdp_route("isaaclab_tasks.core.cartpole", "warp.cartpole.mdp") - with pytest.raises(ValueError): - register_mdp_route("isaaclab_tasks.core.cartpole", "warp.other.mdp") +def test_nearest_mdp_module_walks_up_cfg_paths(): + # A cfg module path walks up to the task family's mdp package. + assert ( + fe.WarpFrontend._nearest_mdp_module("isaaclab_tasks_experimental.core.velocity.config.anymal_d.flat_env_cfg") + == "isaaclab_tasks_experimental.core.velocity.mdp" + ) + # Nothing on the path provides an mdp package. + assert fe.WarpFrontend._nearest_mdp_module("isaaclab_tasks_experimental.nonexistent.task_pkg") is None -def test_cfg_route_modules_resolves_cfg_class_module(fake_routes: dict[str, str]): - # Route this test module's own name so the fixture cfg class matches. - register_mdp_route(__name__, "math") - assert fe.WarpFrontend._cfg_route_modules(_CfgFixture()) == [importlib.import_module("math")] +def test_cfg_route_modules_resolves_mirrored_hierarchy(): + # A class whose module mirrors into the experimental tree resolves to the + # task family's mdp package; unmirrored classes contribute nothing. + fixture_cls = type("FakeVelocityCfg", (), {}) + fixture_cls.__module__ = "isaaclab_tasks.core.velocity.config.anymal_d.flat_env_cfg" + modules = fe.WarpFrontend._cfg_route_modules(fixture_cls()) + assert [m.__name__ for m in modules] == ["isaaclab_tasks_experimental.core.velocity.mdp"] -def test_cfg_route_modules_raises_on_broken_target(fake_routes: dict[str, str]): - register_mdp_route(__name__, "definitely_not_an_importable_module") - with pytest.raises(FrontendIncompatibleError): - fe.WarpFrontend._cfg_route_modules(_CfgFixture()) + assert fe.WarpFrontend._cfg_route_modules(_CfgFixture()) == [] # ====================================================================== @@ -378,7 +374,6 @@ def _fake_mdp_module(name_to_symbol: dict[str, Any]) -> _FakeMdpModule: def _patch_twin_modules(monkeypatch: pytest.MonkeyPatch, modules: list[Any]) -> None: """Pin twin resolution to ``modules`` and keep unit tests hermetic.""" - monkeypatch.setattr(fe.WarpFrontend, "_ensure_twin_providers_imported", classmethod(lambda cls: None)) monkeypatch.setattr(fe.WarpFrontend, "_cfg_route_modules", classmethod(lambda cls, cfg: [])) monkeypatch.setattr( fe.WarpFrontend, "_twin_modules", classmethod(lambda cls, symbol_module, cfg_route_modules: modules) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py index 9a0eaa256a77..e8bc71c28dc3 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/cartpole/__init__.py @@ -10,8 +10,3 @@ declared by ``Isaac-Cartpole-Direct``. There is no separate task registration: run the stable ids with ``--frontend warp`` and ``presets=newton_mjwarp``. """ - -from isaaclab_experimental.envs.frontend import register_mdp_route - -# Warp twins for the stable cartpole MDP terms live in this package's ``mdp``. -register_mdp_route("isaaclab_tasks.core.cartpole", f"{__name__}.mdp") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py index e37ca86717b5..3fba47b723b6 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/__init__.py @@ -3,4 +3,10 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp-first locomotion task implementations.""" +"""Warp implementations for the stable locomotion tasks. + +The ``mdp`` package holds the twins for the shared +:mod:`isaaclab_tasks.core.locomotion.mdp` terms used by the Humanoid and Ant +tasks. There is no separate task registration: run the stable ids with +``--frontend warp`` and ``presets=newton_mjwarp``. +""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py index 277fea940e58..1be981faf7f0 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/ant/__init__.py @@ -3,20 +3,12 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp implementations for the stable Ant tasks. +"""Warp implementation of the stable direct Ant task. -Holds the direct +The manager-based MDP twins live in the shared +:mod:`isaaclab_tasks_experimental.core.locomotion.mdp` package (mirroring the +stable layout). The stable ``Isaac-Ant-Direct`` registration declares :class:`~isaaclab_tasks_experimental.core.locomotion.ant.ant_env_warp.AntWarpEnv` -declared by ``Isaac-Ant-Direct``; the manager-based MDP twins are borrowed from -the Humanoid package. There is no separate task registration: run the stable -ids with ``--frontend warp`` and ``presets=newton_mjwarp``. +as its ``warp_entry_point``; run the stable ids with ``--frontend warp`` and +``presets=newton_mjwarp``. """ - -from isaaclab_experimental.envs.frontend import register_mdp_route - -# The stable Ant task borrows Humanoid MDP terms, so its warp twins live in the -# experimental humanoid package. -register_mdp_route( - "isaaclab_tasks.core.locomotion.ant", - "isaaclab_tasks_experimental.core.locomotion.humanoid.mdp", -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py index 7f05dee5608e..b87d773f7b6d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/__init__.py @@ -3,16 +3,12 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp implementations for the stable Humanoid tasks. +"""Warp implementation of the stable direct Humanoid task. -Holds the MDP twins for the manager-based ``Isaac-Humanoid`` task (also -serving the Ant task, which borrows them) and the direct +The manager-based MDP twins live in the shared +:mod:`isaaclab_tasks_experimental.core.locomotion.mdp` package (mirroring the +stable layout). The stable ``Isaac-Humanoid-Direct`` registration declares :class:`~isaaclab_tasks_experimental.core.locomotion.humanoid.humanoid_warp_env.HumanoidWarpEnv` -declared by ``Isaac-Humanoid-Direct``. There is no separate task registration: -run the stable ids with ``--frontend warp`` and ``presets=newton_mjwarp``. +as its ``warp_entry_point``; run the stable ids with ``--frontend warp`` and +``presets=newton_mjwarp``. """ - -from isaaclab_experimental.envs.frontend import register_mdp_route - -# Warp twins for the stable humanoid MDP terms live in this package's ``mdp``. -register_mdp_route("isaaclab_tasks.core.locomotion.humanoid", f"{__name__}.mdp") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/__init__.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/__init__.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.pyi b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/__init__.pyi similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/__init__.pyi rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/__init__.pyi diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/observations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/observations.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py similarity index 100% rename from source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/humanoid/mdp/rewards.py rename to source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py index 09abb3d8aafc..1a9be132962a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reach/__init__.py @@ -10,8 +10,3 @@ and ``presets=newton_mjwarp``. The IK and OSC variants require controller action twins that do not exist yet. """ - -from isaaclab_experimental.envs.frontend import register_mdp_route - -# Warp twins for the stable reach MDP terms live in this package's ``mdp``. -register_mdp_route("isaaclab_tasks.core.reach", f"{__name__}.mdp") diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py index 436c1da089b6..b4d5fd3d214f 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py @@ -16,15 +16,9 @@ from typing import TYPE_CHECKING -from isaaclab_experimental.envs.frontend import register_mdp_route - if TYPE_CHECKING: from isaaclab.envs import ManagerBasedRLEnvCfg -# Warp twins for the stable velocity MDP terms live in this package's ``mdp``. -register_mdp_route("isaaclab_tasks.core.velocity", f"{__name__}.mdp") - - def disable_unsupported_randomization_events(cfg: ManagerBasedRLEnvCfg) -> None: """Disable stable randomization events that have no warp twins yet. From b510d31ea22eac7dc71dcd51994e7537387e21ff Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 15:50:28 -0700 Subject: [PATCH 33/36] Run velocity tasks on warp via the frontend; drop the last variants MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add warp adapters for the two stable startup randomization events (randomize_rigid_body_material, randomize_rigid_body_mass): the stable terms already dispatch to the active physics backend, so the adapters only convert the warp event manager's env-mask calling convention to the stable env-ids one and inherit the warp ManagerTermBase so the managers accept them as class terms. With those twins in place the stable flat velocity tasks adapt cleanly, so the 18 velocity *-Warp-v0 registrations and their delta configs are deleted — no manager-based warp registration remains, and the conversion test pins that end state. The Allegro reorient task id drops its stale -v0 suffix (Isaac-Reorient-Cube-Allegro-Direct-Warp). --- .../newton/warp-environments.rst | 30 ++---- docs/source/overview/environments.rst | 47 +--------- .../changelog.d/warp-manager-bridge.rst | 13 ++- .../isaaclab_experimental/envs/mdp/events.py | 93 +++++++++++++++++++ .../test/envs/test_frontend_cfg_conversion.py | 36 +++---- .../changelog.d/warp-manager-bridge.minor.rst | 20 ++-- .../reorient/config/allegro_hand/__init__.py | 2 +- .../core/velocity/__init__.py | 31 ++----- .../core/velocity/config/__init__.py | 9 -- .../core/velocity/config/a1/__init__.py | 37 -------- .../core/velocity/config/a1/flat_env_cfg.py | 35 ------- .../core/velocity/config/anymal_b/__init__.py | 37 -------- .../velocity/config/anymal_b/flat_env_cfg.py | 35 ------- .../core/velocity/config/anymal_c/__init__.py | 39 -------- .../velocity/config/anymal_c/flat_env_cfg.py | 35 ------- .../core/velocity/config/anymal_d/__init__.py | 35 ------- .../velocity/config/anymal_d/flat_env_cfg.py | 35 ------- .../core/velocity/config/cassie/__init__.py | 35 ------- .../velocity/config/cassie/flat_env_cfg.py | 35 ------- .../core/velocity/config/g1/__init__.py | 36 ------- .../core/velocity/config/g1/flat_env_cfg.py | 33 ------- .../core/velocity/config/go1/__init__.py | 35 ------- .../core/velocity/config/go1/flat_env_cfg.py | 35 ------- .../core/velocity/config/go2/__init__.py | 35 ------- .../core/velocity/config/go2/flat_env_cfg.py | 35 ------- .../core/velocity/config/h1/__init__.py | 35 ------- .../core/velocity/config/h1/flat_env_cfg.py | 33 ------- 27 files changed, 143 insertions(+), 773 deletions(-) delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index f1c1aee930ad..f572c68c6e4f 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -43,7 +43,7 @@ environment class. Stable tasks with a declared warp implementation: Warp-native direct task with its own registration and configuration (the cube is modeled differently than in the stable task): -- ``Isaac-Reorient-Cube-Allegro-Direct-Warp-v0`` — Allegro hand cube reorient +- ``Isaac-Reorient-Cube-Allegro-Direct-Warp`` — Allegro hand cube reorient Manager-Based Warp Execution (``--frontend warp``) @@ -58,28 +58,14 @@ MDP term for its warp twin). Select the Newton solver explicitly with - ``Isaac-Cartpole`` - ``Isaac-Ant`` - ``Isaac-Humanoid`` -- ``Isaac-Reach-Franka`` -- ``Isaac-Reach-UR10`` +- ``Isaac-Reach-Franka``, ``Isaac-Reach-UR10`` +- ``Isaac-Velocity-Flat-AnymalD``, ``-Cassie``, ``-G1``, ``-H1``, ``-UnitreeGo2`` + (and their ``-Play`` variants) A missing twin is a hard error listing the affected terms, so a partially covered task fails at build time rather than silently changing behavior. - -**Locomotion (Flat) — registered warp variants** - -The velocity tasks still register ``*-Warp-v0`` variants because their stable -configurations contain randomization events without warp twins yet; the -variants reuse the stable flat configurations and only disable those events. -They also require ``presets=newton_mjwarp``. - -- ``Isaac-Velocity-Flat-AnymalB-Warp-v0`` -- ``Isaac-Velocity-Flat-AnymalC-Warp-v0`` -- ``Isaac-Velocity-Flat-AnymalD-Warp-v0`` -- ``Isaac-Velocity-Flat-Cassie-Warp-v0`` -- ``Isaac-Velocity-Flat-G1-Warp-v0`` -- ``Isaac-Velocity-Flat-H1-Warp-v0`` -- ``Isaac-Velocity-Flat-UnitreeA1-Warp-v0`` -- ``Isaac-Velocity-Flat-UnitreeGo1-Warp-v0`` -- ``Isaac-Velocity-Flat-UnitreeGo2-Warp-v0`` +Rough-terrain velocity tasks remain unsupported until +:class:`~isaaclab.terrains.TerrainImporter` gains Warp APIs. Quick Start @@ -95,9 +81,9 @@ Quick Start ./isaaclab.sh train --rl_library rsl_rl \ --task Isaac-Cartpole --frontend warp presets=newton_mjwarp --num_envs 4096 - # Manager-based workflow: registered warp variant + # Manager-based workflow: velocity task on the warp runtime ./isaaclab.sh train --rl_library rsl_rl \ - --task Isaac-Velocity-Flat-AnymalD-Warp-v0 presets=newton_mjwarp --num_envs 4096 + --task Isaac-Velocity-Flat-AnymalD --frontend warp presets=newton_mjwarp --num_envs 4096 All RL libraries with warp-compatible wrappers are supported: RSL-RL, RL Games, SKRL, and Stable-Baselines3. diff --git a/docs/source/overview/environments.rst b/docs/source/overview/environments.rst index 5568f77e2820..8819ddd50dbb 100644 --- a/docs/source/overview/environments.rst +++ b/docs/source/overview/environments.rst @@ -1231,7 +1231,7 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Reorient-Cube-Allegro-Direct-Warp-v0 + * - Isaac-Reorient-Cube-Allegro-Direct-Warp - - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) @@ -1397,11 +1397,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-AnymalB-Warp-v0 - - Isaac-Velocity-Flat-AnymalB-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - IsaacContrib-Velocity-Flat-AnymalB - IsaacContrib-Velocity-Flat-AnymalB-Play - Manager Based @@ -1412,11 +1407,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Velocity-Flat-AnymalC-Warp-v0 - - Isaac-Velocity-Flat-AnymalC-Warp-Play-v0 - - Manager Based - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - IsaacContrib-Velocity-Flat-AnymalC - IsaacContrib-Velocity-Flat-AnymalC-Play - Manager Based @@ -1432,11 +1422,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO, DISTILLATION, DISTILLATION_RECURRENT, RECURRENT), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Velocity-Flat-AnymalD-Warp-v0 - - Isaac-Velocity-Flat-AnymalD-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Velocity-Flat-Cassie - - Manager Based @@ -1447,11 +1432,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-Cassie-Warp-v0 - - Isaac-Velocity-Flat-Cassie-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Velocity-Flat-Digit - - Manager Based @@ -1472,11 +1452,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-G1-Warp-v0 - - Isaac-Velocity-Flat-G1-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Velocity-Flat-H1 - - Manager Based @@ -1487,11 +1462,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-H1-Warp-v0 - - Isaac-Velocity-Flat-H1-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Velocity-Flat-Spot - - Manager Based @@ -1502,21 +1472,11 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-UnitreeA1-Warp-v0 - - Isaac-Velocity-Flat-UnitreeA1-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - - * - IsaacContrib-Velocity-Flat-UnitreeA1 - IsaacContrib-Velocity-Flat-UnitreeA1-Play - Manager Based - **rsl_rl** (PPO), **skrl** (PPO), **sb3** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-UnitreeGo1-Warp-v0 - - Isaac-Velocity-Flat-UnitreeGo1-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - IsaacContrib-Velocity-Flat-UnitreeGo1 - IsaacContrib-Velocity-Flat-UnitreeGo1-Play - Manager Based @@ -1532,11 +1492,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Manager Based - **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``physx`` - * - Isaac-Velocity-Flat-UnitreeGo2-Warp-v0 - - Isaac-Velocity-Flat-UnitreeGo2-Warp-Play-v0 - - Manager Based - - **rsl_rl** (PPO), **skrl** (PPO) - - * - IsaacContrib-Velocity-Rough-AnymalB - IsaacContrib-Velocity-Rough-AnymalB-Play - Manager Based diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 1d56783ad0e9..2a28c88089be 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -7,12 +7,19 @@ Added * Added :mod:`isaaclab_experimental.envs.frontend` runtime selector and :meth:`isaaclab_experimental.managers.SceneEntityCfg.from_stable` used by ``--frontend=warp`` to adapt stable cfgs onto the warp runtime. -* Added :func:`isaaclab_experimental.envs.frontend.register_mdp_route` so task - packages declare where their warp MDP twins live; the frontend holds no - per-task table. * Added ``warp_entry_point`` registration support: a stable direct task may declare its warp environment class, which ``--frontend=warp`` constructs with the stable configuration. +* Added warp adapters for the stable + :class:`~isaaclab.envs.mdp.events.randomize_rigid_body_material` and + :class:`~isaaclab.envs.mdp.events.randomize_rigid_body_mass` startup event + terms, so tasks using them run under ``--frontend=warp`` with randomization + active. +* Added deterministic warp twin resolution: a stable symbol's twin is looked + up on the mirrored experimental package tree (``isaaclab.* ↔ + isaaclab_experimental.*``, ``isaaclab_tasks.* ↔ + isaaclab_tasks_experimental.*``); missing twins are collected and reported + in one failure. No registration is needed. Changed ^^^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py index d9e61041a7ad..90e5696a6b10 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py @@ -26,13 +26,19 @@ from typing import TYPE_CHECKING +import torch import warp as wp +from isaaclab.envs.mdp.events import randomize_rigid_body_mass as _StableRandomizeRigidBodyMass +from isaaclab.envs.mdp.events import randomize_rigid_body_material as _StableRandomizeRigidBodyMaterial + +from isaaclab_experimental.managers import ManagerTermBase as _WarpManagerTermBase from isaaclab_experimental.managers import SceneEntityCfg from isaaclab_experimental.utils.warp import WarpCapturable if TYPE_CHECKING: from isaaclab.assets import Articulation + from isaaclab.envs import ManagerBasedEnv # --------------------------------------------------------------------------- # Randomize rigid body center of mass @@ -585,3 +591,90 @@ def reset_joints_by_scale( # Sync derived buffers (_previous_joint_vel, joint_acc) for reset envs. asset.write_joint_position_to_sim_mask(position=asset.data.joint_pos.warp, env_mask=env_mask) asset.write_joint_velocity_to_sim_mask(velocity=asset.data.joint_vel.warp, env_mask=env_mask) + + +# --------------------------------------------------------------------------- +# Startup-mode randomization (mask-signature adapters) +# --------------------------------------------------------------------------- +# +# The stable material/mass randomization terms already dispatch to the active +# physics backend (Newton included); only their calling convention differs — +# the warp EventManager invokes terms with a Warp env-mask while the stable +# class terms expect torch env indices. Both terms run in ``startup`` mode, +# once at construction and outside any captured path, so a host-side +# mask-to-ids conversion is acceptable. + + +def _mask_to_env_ids(env_mask: wp.array) -> torch.Tensor: + """Convert a Warp boolean env-mask to the torch index tensor the stable terms expect.""" + return torch.nonzero(wp.to_torch(env_mask), as_tuple=False).squeeze(-1) + + +class randomize_rigid_body_material(_StableRandomizeRigidBodyMaterial, _WarpManagerTermBase): + """Warp adapter for the stable, backend-dispatched material randomization term. + + Converts the warp event manager's env-mask calling convention to the stable + term's env-ids convention and delegates. Startup mode only. Inherits the + warp :class:`ManagerTermBase` so the warp managers accept it as a class term. + """ + + def __call__( + self, + env: ManagerBasedEnv, + env_mask: wp.array, + static_friction_range: tuple[float, float], + dynamic_friction_range: tuple[float, float], + restitution_range: tuple[float, float], + num_buckets: int, + asset_cfg: SceneEntityCfg, + make_consistent: bool = False, + ) -> None: + super().__call__( + env, + _mask_to_env_ids(env_mask), + static_friction_range, + dynamic_friction_range, + restitution_range, + num_buckets, + asset_cfg, + make_consistent, + ) + + def reset(self, env_mask: wp.array | None = None) -> None: + """Nothing to reset; materials are randomized once at startup.""" + return + + +class randomize_rigid_body_mass(_StableRandomizeRigidBodyMass, _WarpManagerTermBase): + """Warp adapter for the stable, backend-dispatched mass randomization term. + + Converts the warp event manager's env-mask calling convention to the stable + term's env-ids convention and delegates. Startup mode only. Inherits the + warp :class:`ManagerTermBase` so the warp managers accept it as a class term. + """ + + def __call__( + self, + env: ManagerBasedEnv, + env_mask: wp.array, + asset_cfg: SceneEntityCfg, + mass_distribution_params: tuple[float, float], + operation: str, + distribution: str = "uniform", + recompute_inertia: bool = True, + min_mass: float = 1e-6, + ) -> None: + super().__call__( + env, + _mask_to_env_ids(env_mask), + asset_cfg, + mass_distribution_params, + operation, + distribution, + recompute_inertia, + min_mass, + ) + + def reset(self, env_mask: wp.array | None = None) -> None: + """Nothing to reset; masses are randomized once at startup.""" + return diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index f94ba002fb6c..fc308dd8ca63 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -45,6 +45,16 @@ "Isaac-Reach-Franka-Play", "Isaac-Reach-UR10", "Isaac-Reach-UR10-Play", + "Isaac-Velocity-Flat-AnymalD", + "Isaac-Velocity-Flat-AnymalD-Play", + "Isaac-Velocity-Flat-Cassie", + "Isaac-Velocity-Flat-Cassie-Play", + "Isaac-Velocity-Flat-G1", + "Isaac-Velocity-Flat-G1-Play", + "Isaac-Velocity-Flat-H1", + "Isaac-Velocity-Flat-H1-Play", + "Isaac-Velocity-Flat-UnitreeGo2", + "Isaac-Velocity-Flat-UnitreeGo2-Play", ] # Manager-based warp tasks are exactly those whose entry point is the shared warp @@ -84,33 +94,15 @@ def _cfg_entry_point(task_id: str) -> str: return cfg_entry -_MANAGER_WARP_TASKS = _manager_warp_tasks() - - -def test_manager_warp_tasks_are_registered(): - """Sanity: every expected velocity warp task variant is registered.""" - expected = { - f"Isaac-Velocity-Flat-{robot}-Warp{suffix}-v0" - for robot in ("AnymalB", "AnymalC", "AnymalD", "Cassie", "G1", "H1", "UnitreeA1", "UnitreeGo1", "UnitreeGo2") - for suffix in ("", "-Play") - } - registered = {task_id for task_id, _ in _MANAGER_WARP_TASKS} - assert registered == expected, f"missing: {sorted(expected - registered)}; extra: {sorted(registered - expected)}" +def test_no_manager_warp_variants_remain(): + """End-state pin: manager-based warp execution needs no parallel registrations.""" + assert _manager_warp_tasks() == [], "unexpected ManagerBasedRLEnvWarp registrations reappeared" @pytest.mark.parametrize("task_id", _STABLE_TASKS_WITH_WARP_COVERAGE, ids=_STABLE_TASKS_WITH_WARP_COVERAGE) def test_stable_task_cfg_adapts_to_warp(task_id: str): """Each covered stable task adapts without a missing twin (the --frontend warp path).""" - _load_adapted_cfg(_cfg_entry_point(task_id)) - - -@pytest.mark.parametrize( - "task_id, cfg_entry_point", - [pytest.param(task_id, cfg_entry, id=task_id) for task_id, cfg_entry in _MANAGER_WARP_TASKS], -) -def test_registered_warp_variant_cfg_adapts(task_id: str, cfg_entry_point: str): - """Each registered ``*-Warp-v0`` variant cfg adapts without a missing twin.""" - cfg = _load_adapted_cfg(cfg_entry_point) + cfg = _load_adapted_cfg(_cfg_entry_point(task_id)) # Action terms carry a ``class_type`` (not a ``func``) and live on a base that # is not a ManagerTermBaseCfg; guard that the adapter still swaps them to the diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst index 425d89c1651b..dd6acda10e2e 100644 --- a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst @@ -1,11 +1,9 @@ Changed ^^^^^^^ -* **Breaking:** Changed the manager-based velocity ``*-Warp-v0`` task variants - to reuse the stable flat configurations, disabling only the randomization - events that have no warp twins yet. The variants now require selecting the - Newton solver on the CLI via ``presets=newton_mjwarp`` instead of - hard-coding it in the configuration. +* **Breaking:** Renamed ``Isaac-Reorient-Cube-Allegro-Direct-Warp-v0`` to + ``Isaac-Reorient-Cube-Allegro-Direct-Warp`` to follow the stable id plus + ``-Warp`` suffix convention. * **Breaking:** Changed the package layout to mirror :mod:`isaaclab_tasks.core` (``isaaclab_tasks_experimental.core.``), replacing the previous ``manager_based``/``direct`` split. Update imports of the old paths to the @@ -14,12 +12,14 @@ Changed Removed ^^^^^^^ -* **Breaking:** Removed the duplicated manager-based warp task registrations +* **Breaking:** Removed all manager-based ``*-Warp-v0`` task registrations — ``Isaac-Cartpole-Warp-v0``, ``Isaac-Humanoid-Warp-v0``, ``Isaac-Ant-Warp-v0``, - ``Isaac-Reach-Franka-Warp-v0``, and ``Isaac-Reach-Franka-Warp-Play-v0`` - together with their duplicated environment configurations. Run the stable - task ids with ``--frontend warp`` and ``presets=newton_mjwarp`` instead, - e.g. ``--task Isaac-Cartpole --frontend warp presets=newton_mjwarp``. + ``Isaac-Reach-Franka-Warp-v0``, ``Isaac-Reach-Franka-Warp-Play-v0``, and the + velocity variants (``Isaac-Velocity-Flat--Warp-v0`` and their + ``-Warp-Play-v0`` forms) — together with their environment configurations. + Run the stable task ids with ``--frontend warp`` and + ``presets=newton_mjwarp`` instead, e.g. + ``--task Isaac-Velocity-Flat-AnymalD --frontend warp presets=newton_mjwarp``. * **Breaking:** Removed the duplicated direct warp task registrations ``Isaac-Cartpole-Direct-Warp-v0``, ``Isaac-Ant-Direct-Warp-v0``, and ``Isaac-Humanoid-Direct-Warp-v0`` together with their duplicated diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py index 13ab818b132d..d3ccc4edc51b 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py @@ -17,7 +17,7 @@ stable_agents = "isaaclab_tasks.core.reorient.config.allegro_hand.agents" gym.register( - id="Isaac-Reorient-Cube-Allegro-Direct-Warp-v0", + id="Isaac-Reorient-Cube-Allegro-Direct-Warp", entry_point=f"{inhand_task_entry}.inhand_manipulation_warp_env:InHandManipulationWarpEnv", disable_env_checker=True, kwargs={ diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py index b4d5fd3d214f..f6510ad92c91 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/__init__.py @@ -3,30 +3,11 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Velocity locomotion experimental task registrations (manager-based). +"""Warp MDP twins for the stable velocity locomotion tasks. -The per-robot ``*-Warp-v0`` variants reuse the stable flat cfgs and only -disable the randomization events that have no warp twins yet (see -:func:`disable_unsupported_randomization_events`). Once those twins exist, -the variants can be dropped in favor of ``--frontend warp`` on the stable -task ids. +There is no separate task registration: run the stable flat velocity ids +(e.g. ``Isaac-Velocity-Flat-AnymalD``) with ``--frontend warp`` and +``presets=newton_mjwarp``. Rough-terrain variants remain unsupported until +:class:`~isaaclab.terrains.TerrainImporter` gains Warp APIs (no +``height_scan`` twin). """ - -from __future__ import annotations - -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from isaaclab.envs import ManagerBasedRLEnvCfg - -def disable_unsupported_randomization_events(cfg: ManagerBasedRLEnvCfg) -> None: - """Disable stable randomization events that have no warp twins yet. - - The warp event manager invokes term functions with a Warp env mask, and no - warp twins exist yet for the rigid-body material/mass randomization events. - A stable term on a warp manager is a hard error at adaptation time, so the - warp task variants disable these terms until twins are available. - """ - for name in ("physics_material", "add_base_mass"): - if getattr(cfg.events, name, None) is not None: - setattr(cfg.events, name, None) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py deleted file mode 100644 index 26f3257daef4..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# 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 - -"""Configurations for velocity-based locomotion environments.""" - -# We leave this file empty since we don't want to expose any configs in this package directly. -# We still need this file to import the "config" module in the parent package. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py deleted file mode 100644 index 5b79532a456e..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.contrib.velocity.config.a1 import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-UnitreeA1-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeA1FlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeA1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-UnitreeA1-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeA1FlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeA1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - "sb3_cfg_entry_point": f"{agents.__name__}:sb3_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py deleted file mode 100644 index c9948d38a278..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/a1/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable Unitree A1 flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.contrib.velocity.config.a1.flat_env_cfg import UnitreeA1FlatEnvCfg as _StableUnitreeA1FlatEnvCfg -from isaaclab_tasks.contrib.velocity.config.a1.flat_env_cfg import ( - UnitreeA1FlatEnvCfg_PLAY as _StableUnitreeA1FlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class UnitreeA1FlatEnvCfg(_StableUnitreeA1FlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class UnitreeA1FlatEnvCfg_PLAY(_StableUnitreeA1FlatEnvCfg_PLAY): - """Play variant of :class:`UnitreeA1FlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py deleted file mode 100644 index a6753cfb95ef..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.contrib.velocity.config.anymal_b import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-AnymalB-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalBFlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerCfg", - "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerWithSymmetryCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-AnymalB-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalBFlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerCfg", - "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalBFlatPPORunnerWithSymmetryCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py deleted file mode 100644 index 0c01243aa7d0..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_b/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable AnymalB flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.contrib.velocity.config.anymal_b.flat_env_cfg import AnymalBFlatEnvCfg as _StableAnymalBFlatEnvCfg -from isaaclab_tasks.contrib.velocity.config.anymal_b.flat_env_cfg import ( - AnymalBFlatEnvCfg_PLAY as _StableAnymalBFlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class AnymalBFlatEnvCfg(_StableAnymalBFlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class AnymalBFlatEnvCfg_PLAY(_StableAnymalBFlatEnvCfg_PLAY): - """Play variant of :class:`AnymalBFlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py deleted file mode 100644 index 9c9c2530e118..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.contrib.velocity.config.anymal_c import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-AnymalC-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalCFlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerCfg", - "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerWithSymmetryCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-AnymalC-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalCFlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerCfg", - "rsl_rl_with_symmetry_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalCFlatPPORunnerWithSymmetryCfg", - "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_flat_ppo_cfg.yaml", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py deleted file mode 100644 index 7777d8274e6a..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_c/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable AnymalC flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.contrib.velocity.config.anymal_c.flat_env_cfg import AnymalCFlatEnvCfg as _StableAnymalCFlatEnvCfg -from isaaclab_tasks.contrib.velocity.config.anymal_c.flat_env_cfg import ( - AnymalCFlatEnvCfg_PLAY as _StableAnymalCFlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class AnymalCFlatEnvCfg(_StableAnymalCFlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class AnymalCFlatEnvCfg_PLAY(_StableAnymalCFlatEnvCfg_PLAY): - """Play variant of :class:`AnymalCFlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py deleted file mode 100644 index e54ed0b4d6ca..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.velocity.config.anymal_d import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-AnymalD-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalDFlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDFlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-AnymalD-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:AnymalDFlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AnymalDFlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py deleted file mode 100644 index ccd874878e2f..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/anymal_d/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable AnymalD flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.core.velocity.config.anymal_d.flat_env_cfg import AnymalDFlatEnvCfg as _StableAnymalDFlatEnvCfg -from isaaclab_tasks.core.velocity.config.anymal_d.flat_env_cfg import ( - AnymalDFlatEnvCfg_PLAY as _StableAnymalDFlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class AnymalDFlatEnvCfg(_StableAnymalDFlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class AnymalDFlatEnvCfg_PLAY(_StableAnymalDFlatEnvCfg_PLAY): - """Play variant of :class:`AnymalDFlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py deleted file mode 100644 index e3af41334541..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.velocity.config.cassie import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-Cassie-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:CassieFlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CassieFlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-Cassie-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:CassieFlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:CassieFlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py deleted file mode 100644 index 37696377d675..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/cassie/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable Cassie flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.core.velocity.config.cassie.flat_env_cfg import CassieFlatEnvCfg as _StableCassieFlatEnvCfg -from isaaclab_tasks.core.velocity.config.cassie.flat_env_cfg import ( - CassieFlatEnvCfg_PLAY as _StableCassieFlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class CassieFlatEnvCfg(_StableCassieFlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class CassieFlatEnvCfg_PLAY(_StableCassieFlatEnvCfg_PLAY): - """Play variant of :class:`CassieFlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py deleted file mode 100644 index 47d6909f9356..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.velocity.config.g1 import agents - -## -# Register Gym environments. -## - - -gym.register( - id="Isaac-Velocity-Flat-G1-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:G1FlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-G1-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:G1FlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:G1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py deleted file mode 100644 index e11424804874..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/g1/flat_env_cfg.py +++ /dev/null @@ -1,33 +0,0 @@ -# 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 - -"""Warp variants of the stable G1 flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.core.velocity.config.g1.flat_env_cfg import G1FlatEnvCfg as _StableG1FlatEnvCfg -from isaaclab_tasks.core.velocity.config.g1.flat_env_cfg import G1FlatEnvCfg_PLAY as _StableG1FlatEnvCfg_PLAY - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class G1FlatEnvCfg(_StableG1FlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class G1FlatEnvCfg_PLAY(_StableG1FlatEnvCfg_PLAY): - """Play variant of :class:`G1FlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py deleted file mode 100644 index 417865511f5f..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.contrib.velocity.config.go1 import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-UnitreeGo1-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo1FlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-UnitreeGo1-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo1FlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py deleted file mode 100644 index bbe78df0bd1b..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go1/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable Unitree Go1 flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.contrib.velocity.config.go1.flat_env_cfg import UnitreeGo1FlatEnvCfg as _StableUnitreeGo1FlatEnvCfg -from isaaclab_tasks.contrib.velocity.config.go1.flat_env_cfg import ( - UnitreeGo1FlatEnvCfg_PLAY as _StableUnitreeGo1FlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class UnitreeGo1FlatEnvCfg(_StableUnitreeGo1FlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class UnitreeGo1FlatEnvCfg_PLAY(_StableUnitreeGo1FlatEnvCfg_PLAY): - """Play variant of :class:`UnitreeGo1FlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py deleted file mode 100644 index 2d7f3b3212b8..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.velocity.config.go2 import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-UnitreeGo2-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo2FlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo2FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-UnitreeGo2-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:UnitreeGo2FlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:UnitreeGo2FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py deleted file mode 100644 index 87eb63e6e2fa..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/go2/flat_env_cfg.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -"""Warp variants of the stable Unitree Go2 flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.core.velocity.config.go2.flat_env_cfg import UnitreeGo2FlatEnvCfg as _StableUnitreeGo2FlatEnvCfg -from isaaclab_tasks.core.velocity.config.go2.flat_env_cfg import ( - UnitreeGo2FlatEnvCfg_PLAY as _StableUnitreeGo2FlatEnvCfg_PLAY, -) - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class UnitreeGo2FlatEnvCfg(_StableUnitreeGo2FlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class UnitreeGo2FlatEnvCfg_PLAY(_StableUnitreeGo2FlatEnvCfg_PLAY): - """Play variant of :class:`UnitreeGo2FlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py deleted file mode 100644 index 07deee5ee458..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/__init__.py +++ /dev/null @@ -1,35 +0,0 @@ -# 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 - -import gymnasium as gym - -# Reuse agent configs from the stable task package. -from isaaclab_tasks.core.velocity.config.h1 import agents - -## -# Register Gym environments. -## - -gym.register( - id="Isaac-Velocity-Flat-H1-Warp-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:H1FlatEnvCfg", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) - -gym.register( - id="Isaac-Velocity-Flat-H1-Warp-Play-v0", - entry_point="isaaclab_experimental.envs:ManagerBasedRLEnvWarp", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.flat_env_cfg:H1FlatEnvCfg_PLAY", - "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:H1FlatPPORunnerCfg", - "skrl_cfg_entry_point": f"{agents.__name__}:skrl_flat_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py deleted file mode 100644 index 6c7ca5701261..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/config/h1/flat_env_cfg.py +++ /dev/null @@ -1,33 +0,0 @@ -# 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 - -"""Warp variants of the stable H1 flat velocity task configuration.""" - -from isaaclab.utils.configclass import configclass - -from isaaclab_tasks.core.velocity.config.h1.flat_env_cfg import H1FlatEnvCfg as _StableH1FlatEnvCfg -from isaaclab_tasks.core.velocity.config.h1.flat_env_cfg import H1FlatEnvCfg_PLAY as _StableH1FlatEnvCfg_PLAY - -from isaaclab_tasks_experimental.core.velocity import ( - disable_unsupported_randomization_events, -) - - -@configclass -class H1FlatEnvCfg(_StableH1FlatEnvCfg): - """Stable flat cfg with the randomization events lacking warp twins disabled.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) - - -@configclass -class H1FlatEnvCfg_PLAY(_StableH1FlatEnvCfg_PLAY): - """Play variant of :class:`H1FlatEnvCfg` for the warp runtime.""" - - def __post_init__(self): - super().__post_init__() - disable_unsupported_randomization_events(self) From ad86948fecc65b0aa14801557102adfc3c812481 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 17:00:13 -0700 Subject: [PATCH 34/36] Annotate frontend and fix stale benchmark docs Add one-line comments at the dense decision points of WarpFrontend (twin lookup order, mirror walk, collect-all-misses reporting). Replace the removed -Warp-v0 ids in the benchmarking guide with a same-task A/B that differs only in --frontend, with identical Newton physics on both runs. Add the missing changelog entry for the RewardManager merging class-term reset() extras into its episode logs. --- .../newton/warp-environments.rst | 21 ++++++++---- .../changelog.d/warp-manager-bridge.rst | 4 +++ .../isaaclab_experimental/envs/frontend.py | 33 +++++++++++-------- 3 files changed, 37 insertions(+), 21 deletions(-) diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index f572c68c6e4f..369b8c24b66e 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -273,25 +273,32 @@ to estimate the gain for your own task before committing to a migration. **Single-task A/B** +Run the same stable task id twice, differing only in ``--frontend``. Pass +``presets=newton_mjwarp`` to *both* runs so the physics backend is identical and the +measured difference isolates the frontend (manager pipeline + CUDA graph capture): + .. code-block:: bash - # Stable variant + # Torch frontend (stable managers) uv run isaaclab benchmark training \ --rl_library rsl_rl \ - --task -v0 \ + --task \ --num_envs 4096 \ --max_iterations 500 \ --benchmark_formatter summary \ - --output_path benchmarks/stable + --output_path benchmarks/torch \ + presets=newton_mjwarp - # Warp variant — same task with -Warp- suffix + # Warp frontend (warp managers, CUDA-graph captured) — same task id uv run isaaclab benchmark training \ --rl_library rsl_rl \ - --task -Warp-v0 \ + --task \ + --frontend warp \ --num_envs 4096 \ --max_iterations 500 \ --benchmark_formatter summary \ - --output_path benchmarks/warp + --output_path benchmarks/warp \ + presets=newton_mjwarp The ``summary`` formatter prints step time (min / mean / max) and total throughput. Compare "step time" between the two runs to estimate the gain per env step. @@ -299,7 +306,7 @@ The ``summary`` formatter prints step time (min / mean / max) and total throughp **Sweep across all available tasks** Run ``isaaclab benchmark training`` for each task in the stable set (cartpole, ant, humanoid, -locomotion, manipulation) and again with the ``-Warp-`` suffixed task ids, then diff the two output +locomotion, manipulation) and again with ``--frontend warp``, then diff the two output directories. **What to look at in the output** diff --git a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst index 2a28c88089be..de5082942259 100644 --- a/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_experimental/changelog.d/warp-manager-bridge.rst @@ -29,6 +29,10 @@ Changed :meth:`~isaaclab_experimental.envs.frontend.WarpFrontend.adapt_cfg`, so registered warp task variants can derive from stable configurations instead of duplicating them. +* Changed the experimental warp ``RewardManager`` to merge dictionaries + returned by class-based reward term ``reset()`` into its episode-log extras + (persistent Warp buffer views, CUDA-graph safe); used to report + ``Metrics/success_rate`` under ``--frontend warp``. Fixed ^^^^^ diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 29d14191a9bd..04d9d1886969 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -140,8 +140,10 @@ def _build_direct_env(cls, env_cfg: Any, task_id: str, **construct_kwargs: Any) """ env_class = cls._resolve_direct_warp_class(task_id) if env_class is None: + # No warp_entry_point: the task itself must be a warp-native registration. cls._assert_direct_warp_registration(task_id) return gym.make(task_id, cfg=env_cfg, **construct_kwargs) + # Declared warp class + stable cfg: swap only the env class. cls._require_newton_physics(env_cfg, type(env_cfg).__name__) return env_class(cfg=env_cfg, **construct_kwargs) @@ -215,11 +217,12 @@ def _promote_scene_entity_cfgs(cls, cfg: Any) -> None: promoted: list[str] = [] for path, term in cls._walk_terms(cfg): if not path or path[0] not in cls.WARP_MANAGED_GROUPS: - continue + continue # term runs on a stable manager; keep the stable entity params = getattr(term, "params", None) if not isinstance(params, dict): continue for key, value in list(params.items()): + # Skip non-entities and already-promoted values (idempotence). if isinstance(value, _WarpSceneEntityCfg) or not isinstance(value, _StableSceneEntityCfg): continue params[key] = _WarpSceneEntityCfg.from_stable(value) @@ -254,17 +257,18 @@ def _swap_mdp(cls, cfg: Any, label: str) -> None: substitutes the callable; the manager reads the new func's annotations when it parses the term cfg. """ + # Highest-priority twin source: warp mirrors of the cfg's own task namespace. cfg_route_modules = cls._cfg_route_modules(cfg) - module_cache: dict[str, list[ModuleType]] = {} - searched: set[str] = set() + module_cache: dict[str, list[ModuleType]] = {} # defining module -> modules to search + searched: set[str] = set() # module names, for the error message swapped = 0 missing: list[tuple[str, str, str]] = [] # (location, attr, symbol) for path, term in cls._walk_terms(cfg): if not path or path[0] not in cls.WARP_MANAGED_GROUPS: - continue + continue # term runs on a stable manager; leave it stable location = ".".join(path) - for attr in ("func", "class_type"): + for attr in ("func", "class_type"): # a term implements via either attr stable = getattr(term, attr, None) if stable is None or not cls._is_swap_candidate(stable): continue @@ -274,7 +278,7 @@ def _swap_mdp(cls, cfg: Any, label: str) -> None: searched.update(m.__name__ for m in module_cache[origin]) twin = cls._resolve_warp_twin(stable.__name__, module_cache[origin]) if twin is None: - missing.append((location, attr, stable.__name__)) + missing.append((location, attr, stable.__name__)) # collect every miss; report once below continue setattr(term, attr, twin) swapped += 1 @@ -367,7 +371,7 @@ def _mirror_module(cls, module: str) -> str | None: """Mechanical mirror of a stable module path, or ``None`` if not mirrored.""" if not isinstance(module, str) or not module: return None - root, _, rest = module.partition(".") + root, _, rest = module.partition(".") # only the top-level package root is swapped mirror_root = cls.MIRROR_ROOTS.get(root) if mirror_root is None: return None @@ -387,8 +391,8 @@ def _nearest_mdp_module(mirrored: str) -> str | None: """ parts = mirrored.split(".") if "mdp" in parts: - parts = parts[: parts.index("mdp")] - for depth in range(len(parts), 0, -1): + parts = parts[: parts.index("mdp")] # start the walk at the .mdp boundary + for depth in range(len(parts), 0, -1): # deepest prefix first candidate = ".".join([*parts[:depth], "mdp"]) try: if importlib.util.find_spec(candidate) is not None: @@ -417,7 +421,7 @@ def _cfg_route_modules(cls, cfg: Any) -> list[ModuleType]: (task-family bases). """ modules: list[ModuleType] = [] - for klass in type(cfg).__mro__: + for klass in type(cfg).__mro__: # subclass first: robot cfg wins over task-family base mirrored = cls._mirror_module(getattr(klass, "__module__", "") or "") if mirrored is None: continue @@ -442,6 +446,7 @@ def _twin_modules(cls, symbol_module: str, cfg_route_modules: list[ModuleType]) :mod:`isaaclab.envs.mdp`). """ modules = list(cfg_route_modules) + # Fallback: the mirror of the package that defines the symbol. mirrored = cls._mirror_module(symbol_module) if mirrored is not None: target = cls._nearest_mdp_module(mirrored) @@ -459,7 +464,7 @@ def _resolve_warp_twin(cls, name: str, modules: Iterable[ModuleType]) -> Any | N if candidate is None: continue origin = getattr(candidate, "__module__", "") or "" - if origin.startswith(cls.WARP_ROOT_PREFIXES): + if origin.startswith(cls.WARP_ROOT_PREFIXES): # re-exported stable symbols don't count return candidate return None @@ -508,11 +513,11 @@ def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[s from isaaclab.managers.manager_term_cfg import ActionTermCfg, ManagerTermBaseCfg if isinstance(node, (ManagerTermBaseCfg, ActionTermCfg)): - yield path, node + yield path, node # a term: yield and stop; never descend into params/func return if not hasattr(node, "__dataclass_fields__"): - return - for name, value in vars(node).items(): + return # plain data / callables: not a cfg subtree + for name, value in vars(node).items(): # instance attrs — the same view the managers iterate if name.startswith("_") or value is None: continue yield from WarpFrontend._walk_terms(value, path + (name,)) From fc37fa65ad95d1ac6e3f32e721329ef715899d37 Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 17:34:39 -0700 Subject: [PATCH 35/36] Fold Allegro warp reorient into the stable registration The stable cfg already resolves its cube to an articulation under the newton_mjwarp preset, so the duplicated warp cfg diverged only by pinning ls_iterations=15; the stable preset values now apply. Isaac-Reorient-Cube-Allegro-Direct declares the warp env class via warp_entry_point; the separate -Warp registration and its cfg package are deleted. A new end-state pin asserts no -Warp task ids remain, and the frontend stub-task fixture now unregisters its ids so later test modules see the real registry. --- .../newton/warp-environments.rst | 6 +- docs/source/overview/environments.rst | 5 - .../test/envs/test_frontend.py | 5 + .../test/envs/test_frontend_cfg_conversion.py | 13 +- .../changelog.d/warp-manager-bridge.rst | 7 +- .../reorient/config/allegro_hand/__init__.py | 3 + .../changelog.d/warp-manager-bridge.minor.rst | 14 +- .../core/reorient/config/__init__.py | 6 - .../reorient/config/allegro_hand/__init__.py | 29 ---- .../allegro_hand/allegro_hand_warp_env_cfg.py | 135 ------------------ .../reorient/inhand_manipulation_warp_env.py | 10 +- 11 files changed, 35 insertions(+), 198 deletions(-) delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py delete mode 100644 source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/allegro_hand_warp_env_cfg.py diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index 369b8c24b66e..988fe7ac561a 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -39,11 +39,7 @@ environment class. Stable tasks with a declared warp implementation: - ``Isaac-Cartpole-Direct`` — Cartpole balance - ``Isaac-Ant-Direct`` — Ant locomotion - ``Isaac-Humanoid-Direct`` — Humanoid locomotion - -Warp-native direct task with its own registration and configuration (the cube -is modeled differently than in the stable task): - -- ``Isaac-Reorient-Cube-Allegro-Direct-Warp`` — Allegro hand cube reorient +- ``Isaac-Reorient-Cube-Allegro-Direct`` — Allegro hand cube reorient Manager-Based Warp Execution (``--frontend warp``) diff --git a/docs/source/overview/environments.rst b/docs/source/overview/environments.rst index 8819ddd50dbb..dc17f390c2cf 100644 --- a/docs/source/overview/environments.rst +++ b/docs/source/overview/environments.rst @@ -1231,11 +1231,6 @@ inferencing, including reading from an already trained checkpoint and disabling - Direct - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - **physics=** ``newton_mjwarp``, ``ovphysx``, ``physx`` - * - Isaac-Reorient-Cube-Allegro-Direct-Warp - - - - Direct - - **rl_games** (PPO), **rsl_rl** (PPO), **skrl** (PPO) - - * - Isaac-Reorient-Cube-Allegro-Play - - Manager Based diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index b0ad962082f1..a5bbedd02214 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -531,11 +531,16 @@ def _register_direct_stub_tasks(): # are never invoked (the guard only inspects them), so a fake import # path is fine. ``warp_entry_point`` targets are imported, so the valid # stub points at a real stdlib symbol. + registered = [] for task_id, (entry_point, warp_entry_point) in _DIRECT_TEST_TASKS.items(): kwargs = {"warp_entry_point": warp_entry_point} if warp_entry_point else {} with contextlib.suppress(gym.error.Error): gym.register(id=task_id, entry_point=entry_point, disable_env_checker=True, kwargs=kwargs) + registered.append(task_id) yield + # Unregister so later test modules see the real, stub-free registry. + for task_id in registered: + gym.registry.pop(task_id, None) def test_direct_guard_accepts_warp_rooted(): diff --git a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py index fc308dd8ca63..ea534f3a4b33 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py +++ b/source/isaaclab_experimental/test/envs/test_frontend_cfg_conversion.py @@ -99,6 +99,12 @@ def test_no_manager_warp_variants_remain(): assert _manager_warp_tasks() == [], "unexpected ManagerBasedRLEnvWarp registrations reappeared" +def test_no_warp_task_registrations_remain(): + """End-state pin: warp execution needs no parallel ``-Warp`` task ids at all.""" + warp_ids = sorted(task_id for task_id in gym.registry if "-Warp" in task_id) + assert warp_ids == [], f"unexpected warp task registrations: {warp_ids}" + + @pytest.mark.parametrize("task_id", _STABLE_TASKS_WITH_WARP_COVERAGE, ids=_STABLE_TASKS_WITH_WARP_COVERAGE) def test_stable_task_cfg_adapts_to_warp(task_id: str): """Each covered stable task adapts without a missing twin (the --frontend warp path).""" @@ -134,7 +140,12 @@ def _direct_tasks_with_warp_entry_point() -> list[tuple[str, str]]: def test_direct_tasks_declare_expected_warp_entry_points(): """Sanity: the stable direct tasks with warp implementations declare them.""" declared = {task_id for task_id, _ in _DIRECT_WARP_TASKS} - assert {"Isaac-Cartpole-Direct", "Isaac-Ant-Direct", "Isaac-Humanoid-Direct"} <= declared + assert { + "Isaac-Cartpole-Direct", + "Isaac-Ant-Direct", + "Isaac-Humanoid-Direct", + "Isaac-Reorient-Cube-Allegro-Direct", + } <= declared @pytest.mark.parametrize( diff --git a/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst b/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst index f34db06907a5..7a9bdd89d0b5 100644 --- a/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst +++ b/source/isaaclab_tasks/changelog.d/warp-manager-bridge.rst @@ -2,6 +2,7 @@ Added ^^^^^ * Added ``warp_entry_point`` declarations to the ``Isaac-Cartpole-Direct``, - ``Isaac-Ant-Direct``, and ``Isaac-Humanoid-Direct`` registrations so - ``--frontend warp`` constructs the Warp implementation of these tasks with - the stable task configuration. + ``Isaac-Ant-Direct``, ``Isaac-Humanoid-Direct``, and + ``Isaac-Reorient-Cube-Allegro-Direct`` registrations so ``--frontend warp`` + constructs the Warp implementation of these tasks with the stable task + configuration. diff --git a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/__init__.py b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/__init__.py index c5ec71b59cfe..35393451e9e1 100644 --- a/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/__init__.py +++ b/source/isaaclab_tasks/isaaclab_tasks/core/reorient/config/allegro_hand/__init__.py @@ -47,6 +47,9 @@ disable_env_checker=True, kwargs={ "env_cfg_entry_point": f"{__name__}.allegro_hand_direct_env_cfg:AllegroHandEnvCfg", + "warp_entry_point": ( + "isaaclab_tasks_experimental.core.reorient.inhand_manipulation_warp_env:InHandManipulationWarpEnv" + ), "rl_games_cfg_entry_point": f"{agents.__name__}:rl_games_direct_ppo_cfg.yaml", "rsl_rl_cfg_entry_point": f"{agents.__name__}.rsl_rl_ppo_cfg:AllegroHandPPORunnerCfg", "skrl_cfg_entry_point": f"{agents.__name__}:skrl_direct_ppo_cfg.yaml", diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst index dd6acda10e2e..f29f10f3e6ab 100644 --- a/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-manager-bridge.minor.rst @@ -1,9 +1,6 @@ Changed ^^^^^^^ -* **Breaking:** Renamed ``Isaac-Reorient-Cube-Allegro-Direct-Warp-v0`` to - ``Isaac-Reorient-Cube-Allegro-Direct-Warp`` to follow the stable id plus - ``-Warp`` suffix convention. * **Breaking:** Changed the package layout to mirror :mod:`isaaclab_tasks.core` (``isaaclab_tasks_experimental.core.``), replacing the previous ``manager_based``/``direct`` split. Update imports of the old paths to the @@ -21,11 +18,12 @@ Removed ``presets=newton_mjwarp`` instead, e.g. ``--task Isaac-Velocity-Flat-AnymalD --frontend warp presets=newton_mjwarp``. * **Breaking:** Removed the duplicated direct warp task registrations - ``Isaac-Cartpole-Direct-Warp-v0``, ``Isaac-Ant-Direct-Warp-v0``, and - ``Isaac-Humanoid-Direct-Warp-v0`` together with their duplicated - environment configurations; the stable registrations declare the warp - environment classes via ``warp_entry_point``. Run the stable task ids with - ``--frontend warp`` and ``presets=newton_mjwarp`` instead, e.g. + ``Isaac-Cartpole-Direct-Warp-v0``, ``Isaac-Ant-Direct-Warp-v0``, + ``Isaac-Humanoid-Direct-Warp-v0``, and + ``Isaac-Reorient-Cube-Allegro-Direct-Warp-v0`` together with their + duplicated environment configurations; the stable registrations declare the + warp environment classes via ``warp_entry_point``. Run the stable task ids + with ``--frontend warp`` and ``presets=newton_mjwarp`` instead, e.g. ``--task Isaac-Cartpole-Direct --frontend warp presets=newton_mjwarp``. * Removed the unregistered rough velocity warp configurations; rough-terrain warp tasks remain unsupported until :class:`~isaaclab.terrains.TerrainImporter` diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py deleted file mode 100644 index 771b55fc3605..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# 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 - -"""Warp task registrations for reorientation robots.""" diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py deleted file mode 100644 index d3ccc4edc51b..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# 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 - -""" -Allegro Inhand Manipulation environment. -""" - -import gymnasium as gym - -## -# Register Gym environments. -## - -inhand_task_entry = "isaaclab_tasks_experimental.core.reorient" -stable_agents = "isaaclab_tasks.core.reorient.config.allegro_hand.agents" - -gym.register( - id="Isaac-Reorient-Cube-Allegro-Direct-Warp", - entry_point=f"{inhand_task_entry}.inhand_manipulation_warp_env:InHandManipulationWarpEnv", - disable_env_checker=True, - kwargs={ - "env_cfg_entry_point": f"{__name__}.allegro_hand_warp_env_cfg:AllegroHandWarpEnvCfg", - "rl_games_cfg_entry_point": f"{stable_agents}:rl_games_direct_ppo_cfg.yaml", - "rsl_rl_cfg_entry_point": f"{stable_agents}.rsl_rl_ppo_cfg:AllegroHandPPORunnerCfg", - "skrl_cfg_entry_point": f"{stable_agents}:skrl_direct_ppo_cfg.yaml", - }, -) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/allegro_hand_warp_env_cfg.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/allegro_hand_warp_env_cfg.py deleted file mode 100644 index 573b4f1d302d..000000000000 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/config/allegro_hand/allegro_hand_warp_env_cfg.py +++ /dev/null @@ -1,135 +0,0 @@ -# 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 - - -from isaaclab_newton.physics import MJWarpSolverCfg, NewtonCfg - -import isaaclab.sim as sim_utils -from isaaclab.assets import ArticulationCfg # , RigidObjectCfg -from isaaclab.envs import DirectRLEnvCfg -from isaaclab.markers import VisualizationMarkersCfg -from isaaclab.scene import InteractiveSceneCfg -from isaaclab.sim import SimulationCfg -from isaaclab.sim.spawners.materials.physics_materials_cfg import RigidBodyMaterialCfg -from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.utils.configclass import configclass - -from isaaclab_assets.robots.allegro import ALLEGRO_HAND_CFG - - -@configclass -class AllegroHandWarpEnvCfg(DirectRLEnvCfg): - # env - decimation = 4 - episode_length_s = 10.0 - action_space = 16 - observation_space = 124 # (full) - state_space = 0 - asymmetric_obs = False - obs_type = "full" - - solver_cfg = MJWarpSolverCfg( - solver="newton", - integrator="implicitfast", - njmax=80, - nconmax=70, - impratio=10.0, - cone="elliptic", - update_data_interval=2, - iterations=100, - ls_iterations=15, - # save_to_mjcf="AllegroHand.xml", - ) - - newton_cfg = NewtonCfg( - solver_cfg=solver_cfg, - num_substeps=2, - debug_mode=False, - ) - # simulation - sim: SimulationCfg = SimulationCfg( - dt=1 / 120, - render_interval=decimation, - physics_material=RigidBodyMaterialCfg( - static_friction=1.0, - dynamic_friction=1.0, - ), - physics=newton_cfg, - ) - # robot - robot_cfg: ArticulationCfg = ALLEGRO_HAND_CFG.replace(prim_path="/World/envs/env_.*/Robot") - - actuated_joint_names = [ - "index_joint_0", - "middle_joint_0", - "ring_joint_0", - "thumb_joint_0", - "index_joint_1", - "index_joint_2", - "index_joint_3", - "middle_joint_1", - "middle_joint_2", - "middle_joint_3", - "ring_joint_1", - "ring_joint_2", - "ring_joint_3", - "thumb_joint_1", - "thumb_joint_2", - "thumb_joint_3", - ] - fingertip_body_names = [ - "index_link_3", - "middle_link_3", - "ring_link_3", - "thumb_link_3", - ] - - # in-hand object - object_cfg: ArticulationCfg = ArticulationCfg( - prim_path="/World/envs/env_.*/object", - spawn=sim_utils.UsdFileCfg( - usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", - mass_props=sim_utils.MassPropertiesCfg(density=400.0), - scale=(1.2, 1.2, 1.2), - ), - # FIXME: it does seem to be a bug for ArticulationCfg for handling empty joint list - init_state=ArticulationCfg.InitialStateCfg( - pos=(0.0, -0.17, 0.565), rot=(0.0, 0.0, 0.0, 1.0), joint_pos={}, joint_vel={} - ), - actuators={}, - articulation_root_prim_path="", - ) - # goal object - goal_object_cfg: VisualizationMarkersCfg = VisualizationMarkersCfg( - prim_path="/Visuals/goal_marker", - markers={ - "goal": sim_utils.UsdFileCfg( - usd_path=f"{ISAAC_NUCLEUS_DIR}/Props/Blocks/DexCube/dex_cube_instanceable.usd", - scale=(1.2, 1.2, 1.2), - ) - }, - ) - # scene - scene: InteractiveSceneCfg = InteractiveSceneCfg( - num_envs=8192, env_spacing=0.75, replicate_physics=True, clone_in_fabric=True - ) - # reset - reset_position_noise = 0.01 # range of position at reset - reset_dof_pos_noise = 0.2 # range of dof pos at reset - reset_dof_vel_noise = 0.0 # range of dof vel at reset - # reward scales - dist_reward_scale = -10.0 - rot_reward_scale = 1.0 - rot_eps = 0.1 - action_penalty_scale = -0.0002 - reach_goal_bonus = 250 - fall_penalty = 0 - fall_dist = 0.24 - vel_obs_scale = 0.2 - success_tolerance = 0.2 - max_consecutive_success = 0 - av_factor = 0.1 - act_moving_average = 1.0 - force_torque_obs_scale = 10.0 diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py index ae8a8b30222c..e0deee854208 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/inhand_manipulation_warp_env.py @@ -20,9 +20,7 @@ from isaaclab.sim.spawners.from_files import GroundPlaneCfg, spawn_ground_plane if TYPE_CHECKING: - from isaaclab_tasks_experimental.core.reorient.config.allegro_hand.allegro_hand_warp_env_cfg import ( - AllegroHandWarpEnvCfg, - ) + from isaaclab_tasks.core.reorient.config.allegro_hand.allegro_hand_direct_env_cfg import AllegroHandEnvCfg @wp.kernel @@ -540,10 +538,10 @@ def rotation_distance(object_rot: wp.quatf, target_rot: wp.quatf) -> wp.float32: class InHandManipulationWarpEnv(DirectRLEnvWarp): - cfg: AllegroHandWarpEnvCfg # | ShadowHandWarpEnvCfg + cfg: AllegroHandEnvCfg # | ShadowHandEnvCfg - # def __init__(self, cfg: AllegroHandWarpEnvCfg | ShadowHandWarpEnvCfg, render_mode: str | None = None, **kwargs): - def __init__(self, cfg: AllegroHandWarpEnvCfg, render_mode: str | None = None, **kwargs): + # def __init__(self, cfg: AllegroHandEnvCfg | ShadowHandEnvCfg, render_mode: str | None = None, **kwargs): + def __init__(self, cfg: AllegroHandEnvCfg, render_mode: str | None = None, **kwargs): super().__init__(cfg, render_mode, **kwargs) # --------------------------------------------------------------------- From 716cef20979ca6c578a6e595812291c7b1a282fc Mon Sep 17 00:00:00 2001 From: jichuanh Date: Thu, 16 Jul 2026 01:58:10 -0700 Subject: [PATCH 36/36] Open the warp frontend to the OVPhysX backend Move the body-frame state helpers from isaaclab_newton.kernels to a new backend-neutral isaaclab.utils.warp.state_math module (they are pure frame math; a deprecation shim remains), widen the frontend physics gate to accept OvPhysxCfg alongside NewtonCfg, and add a backend data-parity test pinning that every data..warp view the warp MDP twins read exists on each warp-capable backend. With this, the twins carry no Newton dependency and warp-frontend tasks accept presets=ovphysx. --- .../newton/warp-environments.rst | 9 +- .../changelog.d/warp-frontend-ovphysx.rst | 6 + .../isaaclab/isaaclab/utils/warp/__init__.pyi | 4 + .../isaaclab/utils/warp/state_math.py | 31 ++++++ .../changelog.d/warp-frontend-ovphysx.rst | 9 ++ .../isaaclab_experimental/envs/frontend.py | 46 +++++--- .../envs/mdp/observations.py | 3 +- .../isaaclab_experimental/envs/mdp/rewards.py | 3 +- .../test/envs/test_backend_data_parity.py | 103 ++++++++++++++++++ .../test/envs/test_frontend.py | 22 ++-- .../changelog.d/warp-frontend-ovphysx.rst | 7 ++ .../isaaclab_newton/kernels/state_kernels.py | 36 +++--- .../changelog.d/warp-frontend-ovphysx.skip | 2 + .../core/locomotion/mdp/observations.py | 3 +- .../core/locomotion/mdp/rewards.py | 2 +- 15 files changed, 232 insertions(+), 54 deletions(-) create mode 100644 source/isaaclab/changelog.d/warp-frontend-ovphysx.rst create mode 100644 source/isaaclab/isaaclab/utils/warp/state_math.py create mode 100644 source/isaaclab_experimental/changelog.d/warp-frontend-ovphysx.rst create mode 100644 source/isaaclab_experimental/test/envs/test_backend_data_parity.py create mode 100644 source/isaaclab_newton/changelog.d/warp-frontend-ovphysx.rst create mode 100644 source/isaaclab_tasks_experimental/changelog.d/warp-frontend-ovphysx.skip diff --git a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst index 988fe7ac561a..c66185936f09 100644 --- a/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst +++ b/docs/source/overview/core-concepts/physical-backends/newton/warp-environments.rst @@ -227,11 +227,12 @@ specific to warp envs; for Newton physics limitations see :doc:`supported-featur **Physics backend** -- **Newton only.** PhysX is not supported under the warp env path. Asset and sensor +- **Newton or OVPhysX.** The warp env path requires a warp-capable physics backend: + configure the cfg with a Newton block (``presets=newton_mjwarp``) or an OVPhysX block + (``presets=ovphysx``). Classic PhysX is not supported — its asset and sensor ``class_type`` fields resolve to ``isaaclab_physx.*`` classes that depend on - ``omni.physics.tensors`` (a Kit module the warp runtime does not initialise), and several - warp APIs (env-mask reset, CUDA graph capture) require the Newton articulation. Configure - the cfg with a Newton physics block (or ``physics=newton_mjwarp``). + ``omni.physics.tensors`` (a Kit module the warp runtime does not initialise) and lack + the warp APIs (env-mask reset, CUDA graph capture) the warp managers require. **MDP coverage** diff --git a/source/isaaclab/changelog.d/warp-frontend-ovphysx.rst b/source/isaaclab/changelog.d/warp-frontend-ovphysx.rst new file mode 100644 index 000000000000..14ce168b6358 --- /dev/null +++ b/source/isaaclab/changelog.d/warp-frontend-ovphysx.rst @@ -0,0 +1,6 @@ +Added +^^^^^ + +* Added :mod:`isaaclab.utils.warp.state_math` with the backend-neutral + body-frame state helpers ``rotate_vec_to_body_frame``, + ``body_lin_vel_from_root``, and ``body_ang_vel_from_root``. diff --git a/source/isaaclab/isaaclab/utils/warp/__init__.pyi b/source/isaaclab/isaaclab/utils/warp/__init__.pyi index 7be5ce3ed1c8..218c34e28856 100644 --- a/source/isaaclab/isaaclab/utils/warp/__init__.pyi +++ b/source/isaaclab/isaaclab/utils/warp/__init__.pyi @@ -6,14 +6,18 @@ __all__ = [ "ParticleMeshCounter", "ProxyArray", + "body_ang_vel_from_root", + "body_lin_vel_from_root", "convert_to_warp_mesh", "make_box_region_mesh", "make_frustum_region_mesh", "raycast_dynamic_meshes", "raycast_mesh", "raycast_single_mesh", + "rotate_vec_to_body_frame", ] from .ops import convert_to_warp_mesh, raycast_dynamic_meshes, raycast_mesh, raycast_single_mesh from .particle_mesh import ParticleMeshCounter, make_box_region_mesh, make_frustum_region_mesh from .proxy_array import ProxyArray +from .state_math import body_ang_vel_from_root, body_lin_vel_from_root, rotate_vec_to_body_frame diff --git a/source/isaaclab/isaaclab/utils/warp/state_math.py b/source/isaaclab/isaaclab/utils/warp/state_math.py new file mode 100644 index 000000000000..b034b397a076 --- /dev/null +++ b/source/isaaclab/isaaclab/utils/warp/state_math.py @@ -0,0 +1,31 @@ +# 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 + +"""Warp helper functions for body-frame state computations. + +These ``@wp.func`` helpers are used by warp-first MDP terms (observations, +rewards) that need to project root-frame quantities into body frames. They are +pure frame math over warp types and carry no physics-backend dependency. +""" + +import warp as wp + + +@wp.func +def rotate_vec_to_body_frame(vec_w: wp.vec3f, pose_w: wp.transformf) -> wp.vec3f: + """Rotate a world-frame vector into the body frame defined by pose_w.""" + return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), vec_w) + + +@wp.func +def body_lin_vel_from_root(pose_w: wp.transformf, vel_w: wp.spatial_vectorf) -> wp.vec3f: + """Extract body-frame linear velocity from root pose and spatial velocity.""" + return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), wp.spatial_top(vel_w)) + + +@wp.func +def body_ang_vel_from_root(pose_w: wp.transformf, vel_w: wp.spatial_vectorf) -> wp.vec3f: + """Extract body-frame angular velocity from root pose and spatial velocity.""" + return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), wp.spatial_bottom(vel_w)) diff --git a/source/isaaclab_experimental/changelog.d/warp-frontend-ovphysx.rst b/source/isaaclab_experimental/changelog.d/warp-frontend-ovphysx.rst new file mode 100644 index 000000000000..db7f42b5307e --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/warp-frontend-ovphysx.rst @@ -0,0 +1,9 @@ +Added +^^^^^ + +* Added OVPhysX support to the warp frontend: the physics gate now accepts + :class:`~isaaclab_ovphysx.physics.OvPhysxCfg` in addition to + :class:`~isaaclab_newton.physics.NewtonCfg`, so warp-frontend tasks run with + ``presets=ovphysx`` as well as ``presets=newton_mjwarp``. +* Added a backend data-parity test pinning that every ``data..warp`` + view the warp MDP twins read exists on each warp-capable backend. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 04d9d1886969..1d8fe8d17c55 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -144,7 +144,7 @@ def _build_direct_env(cls, env_cfg: Any, task_id: str, **construct_kwargs: Any) cls._assert_direct_warp_registration(task_id) return gym.make(task_id, cfg=env_cfg, **construct_kwargs) # Declared warp class + stable cfg: swap only the env class. - cls._require_newton_physics(env_cfg, type(env_cfg).__name__) + cls._require_warp_capable_physics(env_cfg, type(env_cfg).__name__) return env_class(cfg=env_cfg, **construct_kwargs) # ------------------------------------------------------------------ @@ -160,10 +160,10 @@ def adapt_cfg(cls, cfg: Any) -> None: Three steps, each independently testable: - 1. :meth:`_require_newton_physics` — hard check that ``cfg.sim.physics`` - is :class:`~isaaclab_newton.physics.NewtonCfg`. The user is - responsible for selecting the Newton variant of the task's - :class:`PresetCfg` via ``presets=newton_mjwarp``; we don't auto-inject. + 1. :meth:`_require_warp_capable_physics` — hard check that ``cfg.sim.physics`` + selects a warp-capable backend (Newton or OVPhysX). The user is + responsible for selecting the variant of the task's :class:`PresetCfg` + via ``presets=newton_mjwarp`` or ``presets=ovphysx``; we don't auto-inject. 2. :meth:`_promote_scene_entity_cfgs` — replace stable :class:`~isaaclab.managers.SceneEntityCfg` instances under each term's ``params`` with the warp variant (which adds warp-cached @@ -176,29 +176,39 @@ def adapt_cfg(cls, cfg: Any) -> None: unsafe under the warp managers' kernel-only signature. """ label = type(cfg).__name__ - cls._require_newton_physics(cfg, label) + cls._require_warp_capable_physics(cfg, label) cls._promote_scene_entity_cfgs(cfg) cls._swap_mdp(cfg, label) @staticmethod - def _require_newton_physics(cfg: Any, label: str) -> None: - """Block unless ``cfg.sim.physics`` is :class:`NewtonCfg`. - - The warp managers' assets read state through :class:`NewtonManager`; - a :class:`PhysxCfg` (or unresolved :class:`PresetCfg`) is a hard - incompatibility. The fix is to pass ``presets=newton_mjwarp`` on the CLI - so Hydra resolves the task's :class:`PresetCfg` wrapper to the Newton - field before construction. + def _require_warp_capable_physics(cfg: Any, label: str) -> None: + """Block unless ``cfg.sim.physics`` selects a warp-capable backend. + + The warp managers read state through warp views and reset assets with + persistent boolean masks; the Newton and OVPhysX backends implement + that contract. A :class:`PhysxCfg` (or unresolved :class:`PresetCfg`) + is a hard incompatibility. The fix is to pass ``presets=newton_mjwarp`` + (or ``presets=ovphysx``) on the CLI so Hydra resolves the task's + :class:`PresetCfg` wrapper to a warp-capable variant before construction. """ from isaaclab_newton.physics import NewtonCfg + capable: tuple[type, ...] = (NewtonCfg,) + try: + from isaaclab_ovphysx.physics import OvPhysxCfg + except ImportError: + pass + else: + capable = (*capable, OvPhysxCfg) + physics = getattr(getattr(cfg, "sim", None), "physics", None) - if isinstance(physics, NewtonCfg): + if isinstance(physics, capable): return raise FrontendIncompatibleError( - f"warp env {label!r}: expected cfg.sim.physics to be NewtonCfg," - f" got {type(physics).__name__!r}. Pass `presets=newton_mjwarp` on the CLI so" - f" Hydra resolves the task's PresetCfg wrapper to the Newton variant." + f"warp env {label!r}: expected cfg.sim.physics to be one of" + f" {[c.__name__ for c in capable]}, got {type(physics).__name__!r}. Pass" + f" `presets=newton_mjwarp` (or `presets=ovphysx`) on the CLI so Hydra" + f" resolves the task's PresetCfg wrapper to a warp-capable variant." ) @classmethod diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py index 4bc49cc1e2ae..60bdaa61c791 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py @@ -21,7 +21,8 @@ import torch import warp as wp -from isaaclab_newton.kernels.state_kernels import ( + +from isaaclab.utils.warp.state_math import ( body_ang_vel_from_root, body_lin_vel_from_root, rotate_vec_to_body_frame, diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py index 338d27c99c5e..3a1bb02065f6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py @@ -18,7 +18,8 @@ from typing import TYPE_CHECKING import warp as wp -from isaaclab_newton.kernels.state_kernels import ( + +from isaaclab.utils.warp.state_math import ( body_ang_vel_from_root, body_lin_vel_from_root, rotate_vec_to_body_frame, diff --git a/source/isaaclab_experimental/test/envs/test_backend_data_parity.py b/source/isaaclab_experimental/test/envs/test_backend_data_parity.py new file mode 100644 index 000000000000..e40badf83147 --- /dev/null +++ b/source/isaaclab_experimental/test/envs/test_backend_data_parity.py @@ -0,0 +1,103 @@ +# 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 + +"""Backend data-parity coverage for the warp MDP twins. + +The warp MDP twins read simulation state exclusively through ``data..warp`` +views on the factory-dispatched asset and sensor data classes. This test pins +that every field a twin reads exists on **each warp-capable backend** (Newton, +OVPhysX), so a backend gap fails here rather than deep inside a training run. + +The field lists mirror the twins' actual reads (``grep -o 'data\\.[a-z_]+\\.warp'`` +over :mod:`isaaclab_experimental.envs.mdp` and the task twin packages); extend +them when a twin starts reading a new field. +""" + +from __future__ import annotations + +import importlib +import inspect + +import pytest + +# Articulation data fields read by the warp MDP twins. Direct warp envs are +# intentionally excluded: they are declared per backend via ``warp_entry_point`` +# and may use backend-specific extensions (e.g. the Newton-native Allegro env +# reads the split ``joint_pos_limits_lower``/``_upper`` fields). +_ARTICULATION_FIELDS = [ + "applied_torque", + "body_com_pos_b", + "body_lin_vel_w", + "body_pos_w", + "body_quat_w", + "default_joint_pos", + "default_joint_vel", + "default_root_pose", + "default_root_vel", + "joint_acc", + "joint_pos", + "joint_vel", + "root_ang_vel_w", + "root_com_vel_w", + "root_lin_vel_w", + "root_link_pose_w", + "root_pos_w", + "root_quat_w", + "root_vel_w", + "soft_joint_pos_limits", + "soft_joint_vel_limits", +] + +# Contact-sensor data fields read by the warp MDP twins. +_CONTACT_SENSOR_FIELDS = [ + "current_air_time", + "current_contact_time", + "last_air_time", + "net_forces_w_history", +] + +# Joint-wrench-sensor data fields read by the warp MDP twins. +_JOINT_WRENCH_FIELDS = [ + "force", + "torque", +] + +# Warp-capable backends: package root -> data-class module paths. +_BACKENDS = { + "newton": "isaaclab_newton", + "ovphysx": "isaaclab_ovphysx", +} + +_DATA_CLASSES = { + "articulation": ("{pkg}.assets.articulation.articulation_data", "ArticulationData", _ARTICULATION_FIELDS), + "contact_sensor": ("{pkg}.sensors.contact_sensor.contact_sensor_data", "ContactSensorData", _CONTACT_SENSOR_FIELDS), + "joint_wrench": ( + "{pkg}.sensors.joint_wrench.joint_wrench_sensor_data", + "JointWrenchSensorData", + _JOINT_WRENCH_FIELDS, + ), +} + + +def _exposes(cls: type, name: str) -> bool: + """Whether ``cls`` declares ``name`` as a descriptor/attribute or annotation.""" + try: + inspect.getattr_static(cls, name) + return True + except AttributeError: + pass + return any(name in getattr(klass, "__annotations__", {}) for klass in cls.__mro__) + + +@pytest.mark.parametrize("backend", sorted(_BACKENDS), ids=sorted(_BACKENDS)) +@pytest.mark.parametrize("data_kind", sorted(_DATA_CLASSES), ids=sorted(_DATA_CLASSES)) +def test_backend_exposes_twin_data_fields(backend: str, data_kind: str): + """Every field the warp twins read exists on the backend's data class.""" + module_tpl, class_name, fields = _DATA_CLASSES[data_kind] + module = importlib.import_module(module_tpl.format(pkg=_BACKENDS[backend])) + data_class = getattr(module, class_name) + + missing = [field for field in fields if not _exposes(data_class, field)] + assert not missing, f"{backend} {class_name} lacks fields read by warp twins: {missing}" diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index a5bbedd02214..e00b580c17bc 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -9,7 +9,7 @@ * :class:`Workflow` enum surface. * :func:`SceneEntityCfg.from_stable` field copy. -* :func:`_require_newton_physics` hard-check. +* :func:`_require_warp_capable_physics` hard-check. * :func:`_walk_terms` recursive ManagerTermBaseCfg discovery over instance attributes (nested class objects are not descended into). * :meth:`_mirror_module` / :meth:`_nearest_mdp_module` deterministic mirror @@ -211,7 +211,7 @@ def test_from_stable_copies_all_selection_fields(): # ====================================================================== -# _require_newton_physics +# _require_warp_capable_physics # ====================================================================== @@ -221,20 +221,26 @@ def _cfg_with_physics(physics: Any) -> Any: return cfg -def test_require_newton_passes_for_newton(): - fe.WarpFrontend._require_newton_physics(_cfg_with_physics(NewtonCfg()), "Isaac-Test-v0") # no raise +def test_require_warp_capable_passes_for_newton(): + fe.WarpFrontend._require_warp_capable_physics(_cfg_with_physics(NewtonCfg()), "Isaac-Test-v0") # no raise -def test_require_newton_rejects_physx(): +def test_require_warp_capable_passes_for_ovphysx(): + from isaaclab_ovphysx.physics import OvPhysxCfg + + fe.WarpFrontend._require_warp_capable_physics(_cfg_with_physics(OvPhysxCfg()), "Isaac-Test-v0") # no raise + + +def test_require_warp_capable_rejects_physx(): with pytest.raises(FrontendIncompatibleError) as exc: - fe.WarpFrontend._require_newton_physics(_cfg_with_physics(PhysxCfg()), "Isaac-Test-v0") + fe.WarpFrontend._require_warp_capable_physics(_cfg_with_physics(PhysxCfg()), "Isaac-Test-v0") assert "presets=newton_mjwarp" in str(exc.value) assert "PhysxCfg" in str(exc.value) -def test_require_newton_rejects_none(): +def test_require_warp_capable_rejects_none(): with pytest.raises(FrontendIncompatibleError): - fe.WarpFrontend._require_newton_physics(_cfg_with_physics(None), "Isaac-Test-v0") + fe.WarpFrontend._require_warp_capable_physics(_cfg_with_physics(None), "Isaac-Test-v0") # ====================================================================== diff --git a/source/isaaclab_newton/changelog.d/warp-frontend-ovphysx.rst b/source/isaaclab_newton/changelog.d/warp-frontend-ovphysx.rst new file mode 100644 index 000000000000..92bbdcb44c97 --- /dev/null +++ b/source/isaaclab_newton/changelog.d/warp-frontend-ovphysx.rst @@ -0,0 +1,7 @@ +Deprecated +^^^^^^^^^^ + +* Deprecated :mod:`isaaclab_newton.kernels.state_kernels` in favor of + :mod:`isaaclab.utils.warp.state_math`; the helpers are pure frame math with + no Newton dependency. The forwarding shim will be removed in a future + release. diff --git a/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py b/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py index 9bb7a39e3b2c..6c002c3489e5 100644 --- a/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py +++ b/source/isaaclab_newton/isaaclab_newton/kernels/state_kernels.py @@ -3,28 +3,24 @@ # # SPDX-License-Identifier: BSD-3-Clause -"""Warp helper functions for body-frame state computations. +"""Deprecated location of the body-frame state helpers. -These ``@wp.func`` helpers are used by warp-first MDP terms (observations, -rewards) that need to project root-frame quantities into body frames. +The helpers are pure frame math with no Newton dependency and have moved to +:mod:`isaaclab.utils.warp.state_math`. This forwarding shim will be removed in +a future release. """ -import warp as wp +import warnings +from isaaclab.utils.warp.state_math import ( # noqa: F401 + body_ang_vel_from_root, + body_lin_vel_from_root, + rotate_vec_to_body_frame, +) -@wp.func -def rotate_vec_to_body_frame(vec_w: wp.vec3f, pose_w: wp.transformf) -> wp.vec3f: - """Rotate a world-frame vector into the body frame defined by pose_w.""" - return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), vec_w) - - -@wp.func -def body_lin_vel_from_root(pose_w: wp.transformf, vel_w: wp.spatial_vectorf) -> wp.vec3f: - """Extract body-frame linear velocity from root pose and spatial velocity.""" - return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), wp.spatial_top(vel_w)) - - -@wp.func -def body_ang_vel_from_root(pose_w: wp.transformf, vel_w: wp.spatial_vectorf) -> wp.vec3f: - """Extract body-frame angular velocity from root pose and spatial velocity.""" - return wp.quat_rotate_inv(wp.transform_get_rotation(pose_w), wp.spatial_bottom(vel_w)) +warnings.warn( + "'isaaclab_newton.kernels.state_kernels' has moved to 'isaaclab.utils.warp.state_math'." + " Update your imports; this forwarding shim will be removed in a future release.", + DeprecationWarning, + stacklevel=2, +) diff --git a/source/isaaclab_tasks_experimental/changelog.d/warp-frontend-ovphysx.skip b/source/isaaclab_tasks_experimental/changelog.d/warp-frontend-ovphysx.skip new file mode 100644 index 000000000000..4c99f0c4f9bb --- /dev/null +++ b/source/isaaclab_tasks_experimental/changelog.d/warp-frontend-ovphysx.skip @@ -0,0 +1,2 @@ +Internal: updated locomotion MDP imports to the relocated +``isaaclab.utils.warp.state_math`` helpers; no user-facing behavior change. diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py index 4d9ab39b4ff7..4ff542a2d21d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/observations.py @@ -16,7 +16,8 @@ import warp as wp from isaaclab_experimental.envs.utils.io_descriptors import generic_io_descriptor_warp from isaaclab_experimental.managers import SceneEntityCfg -from isaaclab_newton.kernels.state_kernels import rotate_vec_to_body_frame + +from isaaclab.utils.warp.state_math import rotate_vec_to_body_frame if TYPE_CHECKING: from isaaclab.assets import Articulation diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py index a090d3a16f69..1a43d1b6b65a 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/mdp/rewards.py @@ -17,9 +17,9 @@ import warp as wp from isaaclab_experimental.managers import SceneEntityCfg from isaaclab_experimental.managers.manager_base import ManagerTermBase -from isaaclab_newton.kernels.state_kernels import rotate_vec_to_body_frame import isaaclab.utils.string as string_utils +from isaaclab.utils.warp.state_math import rotate_vec_to_body_frame if TYPE_CHECKING: from isaaclab_experimental.managers.manager_term_cfg import RewardTermCfg