diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst new file mode 100644 index 000000000000..e3b9b2ebc4b9 --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst @@ -0,0 +1,11 @@ +* Added the ``joint_ids_wp`` and ``body_ids_wp`` fields to :class:`~isaaclab.managers.SceneEntityCfg`: ``int32`` + Warp arrays of the resolved joint and body indices, in the order of ``joint_ids`` and ``body_ids``, for Warp terms. + The new :meth:`~isaaclab.managers.SceneEntityCfg.resolve_warp_ids`, which the Warp managers call after + :meth:`~isaaclab.managers.SceneEntityCfg.resolve`, fills them; :meth:`~isaaclab.managers.SceneEntityCfg.resolve`, + ``joint_ids`` and ``body_ids`` are unchanged. Copies of the configuration, :func:`copy.deepcopy` included, share + them; ``to_dict`` stores them as lists, and a pickled configuration leaves them out (``None``) until + :meth:`~isaaclab.managers.SceneEntityCfg.resolve_warp_ids` runs again. +* Added :attr:`~isaaclab.scene.InteractiveScene.env_origins_wp` and + :attr:`~isaaclab.terrains.TerrainImporter.env_origins_wp`, the ``wp.vec3f`` Warp array that holds the environment + origins, for Warp code. ``env_origins`` stays a :class:`torch.Tensor`, now a view of that array: assigning + ``TerrainImporter.env_origins`` writes the new origins into it, so an earlier view of either stays current. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.minor b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.minor new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/managers/scene_entity_cfg.py b/source/isaaclab/isaaclab/managers/scene_entity_cfg.py index 5cd82c44922b..44f3e89bdd4a 100644 --- a/source/isaaclab/isaaclab/managers/scene_entity_cfg.py +++ b/source/isaaclab/isaaclab/managers/scene_entity_cfg.py @@ -7,10 +7,13 @@ from __future__ import annotations -from dataclasses import MISSING +import copy +from dataclasses import MISSING, field from typing import TYPE_CHECKING +import numpy as np import torch +import warp as wp from ..utils import configclass @@ -123,6 +126,22 @@ class for more details. """ + joint_ids_wp: wp.array | None = field(default=None, metadata={"copy": False}) + """The selected joints as an ``int32`` Warp array of indices, in the order of :attr:`joint_ids`. + Defaults to None. + + Filled by :meth:`resolve_warp_ids` for the Warp terms; torch terms read :attr:`joint_ids`. + :func:`~isaaclab.utils.clone`, :func:`~isaaclab.utils.replace` and :func:`copy.deepcopy` share it. + """ + + body_ids_wp: wp.array | None = field(default=None, metadata={"copy": False}) + """The selected bodies as an ``int32`` Warp array of indices, in the order of :attr:`body_ids`. + Defaults to None. + + Filled by :meth:`resolve_warp_ids` for the Warp terms; torch terms read :attr:`body_ids`. + :func:`~isaaclab.utils.clone`, :func:`~isaaclab.utils.replace` and :func:`copy.deepcopy` share it. + """ + def resolve(self, scene: InteractiveScene): """Resolves the scene entity and converts the joint and body names to indices. @@ -156,6 +175,25 @@ def resolve(self, scene: InteractiveScene): # convert object collection names to indices based on regex self._resolve_object_collection_names(scene) + def resolve_warp_ids(self, scene: InteractiveScene): + """Fill :attr:`joint_ids_wp` and :attr:`body_ids_wp` with the selected indices, in selection order. + + The Warp managers call it after :meth:`resolve` for their terms; torch terms do not need it. + A slice expands over the entity's joints or bodies (the sensors of a contact sensor) and a negative index + wraps, as in torch indexing. + + Args: + scene: The interactive scene instance. + """ + entity = scene[self.name] + if hasattr(entity, "num_joints"): + self.joint_ids_wp = wp.array( + np.arange(entity.num_joints, dtype=np.int32)[self.joint_ids], device=scene.device + ) + num_bodies = entity.num_sensors if hasattr(entity, "num_sensors") else getattr(entity, "num_bodies", None) + if num_bodies is not None: + self.body_ids_wp = wp.array(np.arange(num_bodies, dtype=np.int32)[self.body_ids], device=scene.device) + def finalize(self, device: str) -> None: """Move resolved index selections to the device. @@ -172,6 +210,28 @@ def finalize(self, device: str) -> None: if not isinstance(indices, (slice, torch.Tensor)): setattr(self, name, torch.tensor(indices, dtype=torch.long, device=device)) + def __deepcopy__(self, memo: dict) -> SceneEntityCfg: + """Deep-copy every field, ``init=False`` ones included. + + The Warp ids are shared: a Warp array cannot be deep-copied. + """ + memo[id(self)] = copied = copy.copy(self) + for name, value in vars(self).items(): + if not isinstance(value, wp.array): + setattr(copied, name, copy.deepcopy(value, memo)) + return copied + + def __copy__(self) -> SceneEntityCfg: + """Copy every field; the copy shares the Warp ids.""" + copied = object.__new__(type(self)) + copied.__dict__.update(vars(self)) + return copied + + def __getstate__(self) -> dict: + """Pickle without the Warp ids, which a Warp array cannot be: they unpickle as None, and + :meth:`resolve_warp_ids` fills them again.""" + return {**vars(self), "joint_ids_wp": None, "body_ids_wp": None} + def _resolve_joint_names(self, scene: InteractiveScene): # convert joint names to indices based on regex if self.joint_names is not None or self.joint_ids != slice(None): diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index c56abacd263a..d4dc67432a3d 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -315,16 +315,41 @@ def num_envs(self) -> int: @property def env_origins(self) -> torch.Tensor: - """Per-env world origins, shape ``(num_envs, 3)``.""" + """Per-env world origins, shape ``(num_envs, 3)``. + + A torch view of :attr:`env_origins_wp`, which holds them, so a write of either shows in the other. + """ if self._terrain is not None: return self._terrain.env_origins + self._update_env_origins() + return self._env_origins_torch + + @property + def env_origins_wp(self) -> wp.array: + """Per-env world origins as a Warp array of ``wp.vec3f``, shape ``(num_envs,)``, for Warp code. + + It holds the origins; :attr:`env_origins` is its torch view. + """ + if self._terrain is not None: + return self._terrain.env_origins_wp + self._update_env_origins() + return self._env_origins_wp + + def _update_env_origins(self): + """Write the origins of a new clone plan, or the first ones, into the held array, which keeps its address.""" plan = self.sim.get_clone_plan() if plan is not None and plan is not self._env_origins_plan: self._env_origins = plan.positions self._env_origins_plan = plan - if not isinstance(self._env_origins, torch.Tensor): - self._env_origins = torch.as_tensor(self._env_origins, device=self._ALL_INDICES.device) - return self._env_origins + if self._env_origins is getattr(self, "_env_origins_written", None): + return + origins = torch.as_tensor(self._env_origins, dtype=torch.float32) + if getattr(self, "_env_origins_wp", None) is None or self._env_origins_wp.shape[0] != origins.shape[0]: + device = wp.device_from_torch(self._ALL_INDICES.device) + self._env_origins_wp = wp.zeros(origins.shape[0], dtype=wp.vec3f, device=device) + self._env_origins_torch = wp.to_torch(self._env_origins_wp) + self._env_origins_torch.copy_(origins) + self._env_origins_written = self._env_origins @property def terrain(self) -> TerrainImporter | None: diff --git a/source/isaaclab/isaaclab/terrains/terrain_importer.py b/source/isaaclab/isaaclab/terrains/terrain_importer.py index 9437ec197009..d96df1cc20fb 100644 --- a/source/isaaclab/isaaclab/terrains/terrain_importer.py +++ b/source/isaaclab/isaaclab/terrains/terrain_importer.py @@ -11,6 +11,7 @@ import numpy as np import torch import trimesh +import warp as wp from .. import sim as sim_utils from ..markers import VisualizationMarkers @@ -52,9 +53,6 @@ class TerrainImporter: Otherwise, the environment origins are computed based on the grid spacing. """ - env_origins: torch.Tensor - """The origins of the environments. Shape is (num_envs, 3).""" - def __init__(self, cfg: TerrainImporterCfg): """Initialize the terrain importer. @@ -142,6 +140,34 @@ def flat_patches(self) -> dict[str, torch.Tensor]: """ return self._terrain_flat_patches + @property + def env_origins(self) -> torch.Tensor | None: + """The origins of the environments. Shape is (num_envs, 3). + + A torch view of :attr:`env_origins_wp`, which holds them, so a write of either shows in the other. Assigning + origins writes them into the held array, so a view taken earlier stays valid. + """ + return getattr(self, "_env_origins", None) + + @env_origins.setter + def env_origins(self, origins: torch.Tensor | np.ndarray | None): + if origins is None: + self._env_origins_wp = self._env_origins = None + return + origins = torch.as_tensor(origins, dtype=torch.float32) + if self.env_origins_wp is None or self.env_origins_wp.shape[0] != origins.shape[0]: + self._env_origins_wp = wp.zeros(origins.shape[0], dtype=wp.vec3f, device=self.device) + self._env_origins = wp.to_torch(self._env_origins_wp) + self._env_origins.copy_(origins) + + @property + def env_origins_wp(self) -> wp.array | None: + """The origins of the environments as a Warp array of ``wp.vec3f``, shape (num_envs,), for Warp code. + + It holds the origins; :attr:`env_origins` is its torch view. + """ + return getattr(self, "_env_origins_wp", None) + @property def terrain_names(self) -> list[str]: """A list of names of the imported terrains.""" diff --git a/source/isaaclab/isaaclab/utils/configclass.py b/source/isaaclab/isaaclab/utils/configclass.py index 282f2347e3e9..0580becd60c7 100644 --- a/source/isaaclab/isaaclab/utils/configclass.py +++ b/source/isaaclab/isaaclab/utils/configclass.py @@ -15,6 +15,8 @@ from dataclasses import MISSING, Field, dataclass, field from typing import Any, ClassVar, TypeVar +import warp as wp + from .dict import to_dict, update_from_dict from .string import ResolvableString @@ -366,6 +368,9 @@ def validate_config(self): current_path = f"{prefix}[{index}]" missing_fields.extend(_validate(item, prefix=current_path, _custom_validators=_custom_validators)) return missing_fields + elif isinstance(obj, wp.array): + # an array value, such as the Warp ids of a SceneEntityCfg, has no fields + return missing_fields elif isinstance(obj, dict): # Convert any non-string keys to strings to allow validation of dict with non-string keys if any(not isinstance(key, str) for key in obj.keys()): diff --git a/source/isaaclab/isaaclab/utils/dict.py b/source/isaaclab/isaaclab/utils/dict.py index 0869b73d08e6..fa1765487d40 100644 --- a/source/isaaclab/isaaclab/utils/dict.py +++ b/source/isaaclab/isaaclab/utils/dict.py @@ -13,6 +13,7 @@ from typing import Any import torch +import warp as wp from .array import TENSOR_TYPE_CONVERSIONS, TENSOR_TYPES from .string import ResolvableString, callable_to_string, string_to_slice @@ -48,6 +49,9 @@ def class_to_dict(obj: object) -> dict[str, Any]: # dict, which would mean that a torch.tensor would be stored as an empty dict. Instead we # want to store it directly as the tensor. return obj + elif isinstance(obj, wp.array): + # a Warp array (such as the Warp ids of a SceneEntityCfg) is stored as the list of its values + return obj.numpy().tolist() elif hasattr(obj, "__dict__"): obj_dict = obj.__dict__ else: diff --git a/source/isaaclab/test/managers/test_scene_entity_cfg.py b/source/isaaclab/test/managers/test_scene_entity_cfg.py index 828b2b79791b..8ecfad6fcadb 100644 --- a/source/isaaclab/test/managers/test_scene_entity_cfg.py +++ b/source/isaaclab/test/managers/test_scene_entity_cfg.py @@ -6,22 +6,32 @@ """Scene selections resolve on the host, then finalize to device indices used without synchronization.""" import copy +import pickle +from dataclasses import field from functools import partial from types import SimpleNamespace from unittest.mock import Mock import pytest import torch +import warp as wp from isaaclab.envs.mdp.events import apply_external_force_torque from isaaclab.envs.mdp.observations import joint_pos from isaaclab.managers import SceneEntityCfg from isaaclab.test.utils import DeviceScope, test_devices +from isaaclab.utils import clone, configclass from isaaclab.utils.string import resolve_matching_names pytestmark = pytest.mark.unit +class _Scene(dict): + """Entity lookup and device of :class:`~isaaclab.scene.InteractiveScene`.""" + + device = "cpu" + + @pytest.fixture def scene(): names = ["part_0", "part_1", "part_2", "part_3"] @@ -108,3 +118,67 @@ def test_external_force_uses_selected_body_count(scene): torch.testing.assert_close(kwargs["forces"], torch.full((2, 2, 3), 2.0)) torch.testing.assert_close(kwargs["torques"], torch.full((2, 2, 3), 3.0)) assert kwargs["body_ids"].tolist() == [3, 1] + + +def test_resolve_warp_ids_fills_the_selection_order(scene): + """Warp ids keep the resolved order and repeats, expand slices, and count the bodies of a contact sensor. + + :meth:`resolve` does no Warp work, so a scene without a device resolves the torch selections as on main. + """ + sensor_entity = SimpleNamespace(num_sensors=2, num_bodies=5) + subset = SceneEntityCfg("robot", joint_names=["part_2", "part_0"], preserve_order=True, body_ids=[3, 3, -1]) + full = SceneEntityCfg("robot") + sensor = SceneEntityCfg("sensor") + for cfg in (subset, full, sensor): + cfg.resolve(dict(scene, sensor=sensor_entity)) + assert cfg.joint_ids_wp is None and cfg.body_ids_wp is None + cfg.resolve_warp_ids(_Scene(scene, sensor=sensor_entity)) + + assert subset.joint_ids_wp.dtype == wp.int32 + assert subset.joint_ids_wp.numpy().tolist() == [2, 0] + assert subset.body_ids_wp.numpy().tolist() == [3, 3, 3] + assert full.joint_ids_wp.numpy().tolist() == [0, 1, 2, 3] + assert full.body_ids_wp.numpy().tolist() == [0, 1, 2, 3] + assert sensor.joint_ids_wp is None + assert sensor.body_ids_wp.numpy().tolist() == [0, 1] + + +def test_a_cfg_with_warp_ids_serializes(scene): + """With Warp ids, a configuration converts to a dictionary with the ids as lists and validates; it pickles + without them, and resolving the Warp ids again fills them.""" + scene = _Scene(scene) + cfg = SceneEntityCfg("robot", joint_names=["part_2", "part_0"], preserve_order=True) + cfg.resolve(scene) + cfg.resolve_warp_ids(scene) + + assert cfg.to_dict()["joint_ids_wp"] == [2, 0] + cfg.validate() + restored = pickle.loads(pickle.dumps(cfg)) + assert restored.joint_ids == [2, 0] and restored.joint_ids_wp is None and restored.body_ids_wp is None + restored.resolve_warp_ids(scene) + assert restored.joint_ids_wp.numpy().tolist() == [2, 0] + + +@configclass +class _SelectionCfg(SceneEntityCfg): + """Keeps resolved state in a field the constructor does not take, as the contrib selection configuration does.""" + + instance_ids: torch.Tensor = field(default_factory=lambda: torch.empty(0, dtype=torch.long), init=False) + + +def test_deepcopy_keeps_resolved_subclass_state(scene): + """A deep copy keeps the fields the constructor does not take and, like any configuration copy, shares the Warp + ids instead of copying device memory.""" + scene = _Scene(scene) + cfg = _SelectionCfg("robot", joint_names=["part_1"]) + cfg.resolve(scene) + cfg.resolve_warp_ids(scene) + cfg.instance_ids = torch.tensor([3, -1, 0]) + + copied = copy.deepcopy(cfg) + + torch.testing.assert_close(copied.instance_ids, cfg.instance_ids) + assert copied.instance_ids is not cfg.instance_ids + assert copied.joint_ids_wp is cfg.joint_ids_wp + assert copied.body_ids_wp is cfg.body_ids_wp + assert clone(cfg).joint_ids_wp is cfg.joint_ids_wp diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 40946843a879..f9d9e29b9049 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -257,6 +257,7 @@ def test_empty_scene_leaves_clone_lifecycle_to_caller(): env_template = scene.cfg.clone_cfg.clone_template grid_positions = cloner.grid_transforms(4, 1.0)[0] torch.testing.assert_close(scene.env_origins, torch.from_numpy(grid_positions)) + first_origins_ptr = scene.env_origins_wp.ptr env_0 = scene.stage.GetPrimAtPath(env_template.format(0)) assert env_0 and not env_0.GetAttribute("xformOpOrder").Get() assert all(not scene.stage.GetPrimAtPath(env_template.format(i)).IsValid() for i in range(1, 4)) @@ -278,6 +279,8 @@ def test_empty_scene_leaves_clone_lifecycle_to_caller(): assert sim.get_clone_plan() is plan assert all(scene.stage.GetPrimAtPath(f"{env_template.format(i)}/Cube").IsValid() for i in range(4)) torch.testing.assert_close(scene.env_origins, torch.from_numpy(positions)) + # the Warp array holds the origins of the new clone plan at its address, and env_origins is its view + assert scene.env_origins_wp.ptr == scene.env_origins.data_ptr() == first_origins_ptr for env_id, position in enumerate(positions): np.testing.assert_allclose( sim_utils.resolve_prim_pose(scene.stage.GetPrimAtPath(env_template.format(env_id)))[0], position diff --git a/source/isaaclab/test/terrains/test_terrain_importer.py b/source/isaaclab/test/terrains/test_terrain_importer.py index 9c36c51e6d3c..4b081306fd9b 100644 --- a/source/isaaclab/test/terrains/test_terrain_importer.py +++ b/source/isaaclab/test/terrains/test_terrain_importer.py @@ -99,6 +99,10 @@ def test_plane(num_envs, env_spacing): assert origins.device == torch.device("cuda:0") torch.testing.assert_close(origins[0].cpu(), torch.tensor([half_span, -half_span, 0.0])) torch.testing.assert_close(origins[-1].cpu(), torch.tensor([-half_span, half_span, 0.0])) + # the Warp array holds the origins and env_origins is its view + assert terrain_importer.env_origins_wp.ptr == origins.data_ptr() + assert terrain_importer.env_origins_wp.shape == (num_envs,) + origins_view = origins # check if mesh prim path exists mesh_prim_path = terrain_importer.cfg.prim_path + "/terrain" @@ -128,6 +132,11 @@ def test_plane(num_envs, env_spacing): mesh = _obtain_collision_mesh(mesh_prim_path, mesh_type="Plane") assert mesh is None + # assigning the origins again writes them into the held array, so the earlier view shows them + terrain_importer.env_origins = torch.ones(num_envs, 3, device="cuda:0") + assert terrain_importer.env_origins.data_ptr() == origins_view.data_ptr() + torch.testing.assert_close(origins_view, torch.ones(num_envs, 3, device="cuda:0")) + def test_usd(): """Imports terrain from a usd and tests that the resulting mesh has the correct size.""" diff --git a/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst b/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst new file mode 100644 index 000000000000..4496ccd30a24 --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst @@ -0,0 +1,3 @@ +* Changed the Warp joint penalties ``joint_torques_l2``, ``joint_vel_l1``, ``joint_vel_l2``, ``joint_acc_l2``, + ``joint_deviation_l1`` and ``joint_pos_limits``, and the termination ``joint_pos_out_of_manual_limit``, to loop over + the selected joints in the order of ``joint_ids``. A joint selected twice now counts twice, as in the torch terms. diff --git a/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.major b/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.major new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.removed.rst b/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.removed.rst new file mode 100644 index 000000000000..ef7ba6e29119 --- /dev/null +++ b/source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.removed.rst @@ -0,0 +1,3 @@ +* **Breaking:** Removed the Warp subclass ``isaaclab_experimental.managers.SceneEntityCfg``; the name now resolves to + :class:`isaaclab.managers.SceneEntityCfg`, whose ``joint_ids_wp`` and ``body_ids_wp`` the Warp managers fill. Its + ``joint_mask`` and ``from_stable`` are removed: Warp terms loop over ``joint_ids_wp``. diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index cb0105a6b06b..8e27d977d64a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -9,7 +9,7 @@ stable task definition: * Manager-based tasks: adapt the stable cfg in place (Newton physics check, - :class:`SceneEntityCfg` promotion, MDP twin swap) and construct + 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. @@ -44,7 +44,6 @@ import torch from isaaclab.envs import DirectMARLEnvCfg, DirectRLEnvCfg, ManagerBasedRLEnvCfg -from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _StableSceneEntityCfg logger = logging.getLogger(__name__) @@ -87,7 +86,7 @@ class WarpFrontend: 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 + # are adapted (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 @@ -170,27 +169,23 @@ 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). + below skip warp-origin symbols). - Four steps, each independently testable (the fourth, :meth:`_swap_noise_cfgs`, replaces - stable observation-noise cfgs with their warp-native twins): + Three steps, each independently testable: 1. :meth:`_require_newton_physics` — hard check that ``cfg.sim.physics`` is :class:`~isaaclab_newton.physics.NewtonCfg`. - 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 + 2. :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. + 3. :meth:`_swap_noise_cfgs` — replace every stable observation-noise + cfg with its warp-native twin; a noise cfg without a twin raises. """ label = type(cfg).__name__ cls._require_newton_physics(cfg, label) - cls._promote_scene_entity_cfgs(cfg) cls._swap_mdp(cfg, label) cls._swap_noise_cfgs(cfg, label) @@ -237,39 +232,6 @@ def _require_newton_physics(cfg: Any, label: str) -> None: " before constructing the environment." ) - @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 # 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) - 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. @@ -706,7 +668,7 @@ def _walk_terms(node: Any, path: tuple[str, ...] = ()) -> Iterator[tuple[tuple[s if isinstance(node, Mapping): # A manager group can be a dict of {name: term} instead of a # configclass; the warp managers accept both, so descend into dict - # values too or those terms would never be promoted/swapped. + # values too or those terms would never be swapped. for key, value in node.items(): if value is not None: yield from WarpFrontend._walk_terms(value, path + (str(key),)) 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 2fe63fdf9920..e65fc47fb3f6 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 @@ -275,14 +275,8 @@ def device(self): @property def env_origins_wp(self) -> wp.array: - """Scene env origins as a warp ``vec3f`` array. Cached on first access.""" - if not hasattr(self, "_env_origins_wp"): - origins = self.scene.env_origins - if isinstance(origins, wp.array): - self._env_origins_wp = origins - else: - self._env_origins_wp = wp.from_torch(origins, dtype=wp.vec3f) - return self._env_origins_wp + """Scene env origins as a warp ``vec3f`` array.""" + return self.scene.env_origins_wp def resolve_env_mask( self, diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py index 90e5696a6b10..ff985adf52e9 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/events.py @@ -19,7 +19,7 @@ Notes: - These terms assume the Newton/Warp backend (Warp arrays are available for joint state and defaults). -- For best performance, pass :class:`isaaclab_experimental.managers.SceneEntityCfg` so `joint_ids_wp` is cached. +- Pass :class:`isaaclab.managers.SceneEntityCfg`; the Warp managers fill its `joint_ids_wp` once at resolution. """ from __future__ import annotations @@ -31,9 +31,9 @@ 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.managers import SceneEntityCfg from isaaclab_experimental.managers import ManagerTermBase as _WarpManagerTermBase -from isaaclab_experimental.managers import SceneEntityCfg from isaaclab_experimental.utils.warp import WarpCapturable if TYPE_CHECKING: @@ -466,9 +466,9 @@ def reset_joints_by_offset( # Assume cfg params are already resolved by the manager stack (Warp-first workflow). if asset_cfg.joint_ids_wp is None: raise ValueError( - f"reset_joints_by_offset requires an experimental SceneEntityCfg with resolved joint_ids_wp, " + f"reset_joints_by_offset requires a SceneEntityCfg with resolved joint_ids_wp, " f"but got None for asset '{asset_cfg.name}'. " - "Use isaaclab_experimental.managers.SceneEntityCfg and ensure joint_names are set." + "Pass it as a term parameter, which the Warp managers resolve, and ensure joint_names are set." ) if not hasattr(env, "rng_state_wp") or env.rng_state_wp is None: raise AttributeError( @@ -557,9 +557,9 @@ def reset_joints_by_scale( if asset_cfg.joint_ids_wp is None: raise ValueError( - f"reset_joints_by_scale requires an experimental SceneEntityCfg with resolved joint_ids_wp, " + f"reset_joints_by_scale requires a SceneEntityCfg with resolved joint_ids_wp, " f"but got None for asset '{asset_cfg.name}'. " - "Use isaaclab_experimental.managers.SceneEntityCfg and ensure joint_names are set." + "Pass it as a term parameter, which the Warp managers resolve, and ensure joint_names are set." ) if not hasattr(env, "rng_state_wp") or env.rng_state_wp is None: raise AttributeError( diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py index f2e947fa9a06..e864be4806e6 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/observations.py @@ -22,6 +22,7 @@ import torch import warp as wp +from isaaclab.managers import SceneEntityCfg from isaaclab.utils.warp.math import body_ang_vel_from_root, body_lin_vel_from_root, rotate_vec_to_body_frame from isaaclab_experimental.envs.utils.io_descriptors import ( @@ -32,7 +33,6 @@ record_joint_vel_offsets, record_shape, ) -from isaaclab_experimental.managers import SceneEntityCfg if TYPE_CHECKING: from isaaclab.assets import Articulation diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py index 74f5fe60d24a..46b4c544bbfe 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/rewards.py @@ -19,9 +19,10 @@ import warp as wp +from isaaclab.managers import SceneEntityCfg from isaaclab.utils.warp.math import body_ang_vel_from_root, body_lin_vel_from_root, rotate_vec_to_body_frame -from isaaclab_experimental.managers import ManagerTermBase, SceneEntityCfg +from isaaclab_experimental.managers import ManagerTermBase if TYPE_CHECKING: from isaaclab.assets import Articulation @@ -246,16 +247,16 @@ def base_height_l2( # TODO(warp-migration): Revisit whether 2D kernel + wp.atomic_add is faster than 1D with inner loop -# for the following masked reduction kernels. Profile with typical joint counts (12-30). +# for the following selected-joint reduction kernels. Profile with typical joint counts (12-30). @wp.kernel -def _sum_sq_masked_kernel( - x: wp.array(dtype=wp.float32, ndim=2), joint_mask: wp.array(dtype=wp.bool), out: wp.array(dtype=wp.float32) +def _sum_sq_selected_kernel( + x: wp.array(dtype=wp.float32, ndim=2), joint_ids: wp.array(dtype=wp.int32), out: wp.array(dtype=wp.float32) ): i = wp.tid() s = float(0.0) - for j in range(x.shape[1]): - if joint_mask[j]: - s += x[i, j] * x[i, j] + for k in range(joint_ids.shape[0]): + v = x[i, joint_ids[k]] + s += v * v out[i] = s @@ -263,23 +264,22 @@ def joint_torques_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = Sc """Penalize joint torques applied on the articulation using L2 squared kernel.""" asset: Articulation = env.scene[asset_cfg.name] wp.launch( - kernel=_sum_sq_masked_kernel, + kernel=_sum_sq_selected_kernel, dim=env.num_envs, - inputs=[asset.actuators.applied_effort.warp, asset_cfg.joint_mask, out], + inputs=[asset.actuators.applied_effort.warp, asset_cfg.joint_ids_wp, out], device=env.device, ) # TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. @wp.kernel -def _sum_abs_masked_kernel( - x: wp.array(dtype=wp.float32, ndim=2), joint_mask: wp.array(dtype=wp.bool), out: wp.array(dtype=wp.float32) +def _sum_abs_selected_kernel( + x: wp.array(dtype=wp.float32, ndim=2), joint_ids: wp.array(dtype=wp.int32), out: wp.array(dtype=wp.float32) ): i = wp.tid() s = float(0.0) - for j in range(x.shape[1]): - if joint_mask[j]: - s += wp.abs(x[i, j]) + for k in range(joint_ids.shape[0]): + s += wp.abs(x[i, joint_ids[k]]) out[i] = s @@ -287,9 +287,9 @@ def joint_vel_l1(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg) -> None """Penalize joint velocities on the articulation using an L1-kernel. Writes into ``out``.""" asset: Articulation = env.scene[asset_cfg.name] wp.launch( - kernel=_sum_abs_masked_kernel, + kernel=_sum_abs_selected_kernel, dim=env.num_envs, - inputs=[asset.data.joint_vel.warp, asset_cfg.joint_mask, out], + inputs=[asset.data.joint_vel.warp, asset_cfg.joint_ids_wp, out], device=env.device, ) @@ -298,9 +298,9 @@ def joint_vel_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneE """Penalize joint velocities on the articulation using L2 squared kernel.""" asset: Articulation = env.scene[asset_cfg.name] wp.launch( - kernel=_sum_sq_masked_kernel, + kernel=_sum_sq_selected_kernel, dim=env.num_envs, - inputs=[asset.data.joint_vel.warp, asset_cfg.joint_mask, out], + inputs=[asset.data.joint_vel.warp, asset_cfg.joint_ids_wp, out], device=env.device, ) @@ -309,26 +309,26 @@ def joint_acc_l2(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = SceneE """Penalize joint accelerations on the articulation using L2 squared kernel.""" asset: Articulation = env.scene[asset_cfg.name] wp.launch( - kernel=_sum_sq_masked_kernel, + kernel=_sum_sq_selected_kernel, dim=env.num_envs, - inputs=[asset.data.joint_acc.warp, asset_cfg.joint_mask, out], + inputs=[asset.data.joint_acc.warp, asset_cfg.joint_ids_wp, out], device=env.device, ) # TODO(warp-migration): Revisit 2D kernel + wp.atomic_add vs 1D inner loop. @wp.kernel -def _sum_abs_diff_masked_kernel( +def _sum_abs_diff_selected_kernel( a: wp.array(dtype=wp.float32, ndim=2), b: wp.array(dtype=wp.float32, ndim=2), - joint_mask: wp.array(dtype=wp.bool), + joint_ids: wp.array(dtype=wp.int32), out: wp.array(dtype=wp.float32), ): i = wp.tid() s = float(0.0) - for j in range(a.shape[1]): - if joint_mask[j]: - s += wp.abs(a[i, j] - b[i, j]) + for k in range(joint_ids.shape[0]): + j = joint_ids[k] + s += wp.abs(a[i, j] - b[i, j]) out[i] = s @@ -336,9 +336,9 @@ def joint_deviation_l1(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = """Penalize joint positions that deviate from the default one.""" asset: Articulation = env.scene[asset_cfg.name] wp.launch( - kernel=_sum_abs_diff_masked_kernel, + kernel=_sum_abs_diff_selected_kernel, dim=env.num_envs, - inputs=[asset.data.joint_pos.warp, asset.data.default_joint_pos.warp, asset_cfg.joint_mask, out], + inputs=[asset.data.joint_pos.warp, asset.data.default_joint_pos.warp, asset_cfg.joint_ids_wp, out], device=env.device, ) @@ -348,25 +348,25 @@ def joint_deviation_l1(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = def _joint_pos_limits_kernel( joint_pos: wp.array(dtype=wp.float32, ndim=2), soft_joint_pos_limits: wp.array(dtype=wp.vec2f, ndim=2), - joint_mask: wp.array(dtype=wp.bool), + joint_ids: wp.array(dtype=wp.int32), out: wp.array(dtype=wp.float32), ): i = wp.tid() s = float(0.0) - for j in range(joint_pos.shape[1]): - if joint_mask[j]: - pos = joint_pos[i, j] - lim = soft_joint_pos_limits[i, j] - lower = lim.x - upper = lim.y - # penalty for exceeding lower limit - below = lower - pos - if below > 0.0: - s += below - # penalty for exceeding upper limit - above = pos - upper - if above > 0.0: - s += above + for k in range(joint_ids.shape[0]): + j = joint_ids[k] + pos = joint_pos[i, j] + lim = soft_joint_pos_limits[i, j] + lower = lim.x + upper = lim.y + # penalty for exceeding lower limit + below = lower - pos + if below > 0.0: + s += below + # penalty for exceeding upper limit + above = pos - upper + if above > 0.0: + s += above out[i] = s @@ -376,7 +376,7 @@ def joint_pos_limits(env: ManagerBasedRLEnv, out, asset_cfg: SceneEntityCfg = Sc wp.launch( kernel=_joint_pos_limits_kernel, dim=env.num_envs, - inputs=[asset.data.joint_pos.warp, asset.data.soft_joint_pos_limits.warp, asset_cfg.joint_mask, out], + inputs=[asset.data.joint_pos.warp, asset.data.soft_joint_pos_limits.warp, asset_cfg.joint_ids_wp, out], device=env.device, ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py index 8470f50d2b32..394bae1d6054 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/mdp/terminations.py @@ -19,9 +19,10 @@ import warp as wp +from isaaclab.managers import SceneEntityCfg from isaaclab.utils.warp.math import quat_error_magnitude -from isaaclab_experimental.managers import ManagerTermBase, SceneEntityCfg +from isaaclab_experimental.managers import ManagerTermBase if TYPE_CHECKING: from isaaclab.assets import Articulation @@ -191,17 +192,16 @@ def root_height_below_minimum( @wp.kernel def _joint_pos_out_of_manual_limit_kernel( joint_pos: wp.array(dtype=wp.float32, ndim=2), - joint_mask: wp.array(dtype=wp.bool), + joint_ids: wp.array(dtype=wp.int32), lower: float, upper: float, out: wp.array(dtype=wp.bool), ): - """2D kernel (num_envs, num_joints). ``out`` is pre-zeroed; only writes True.""" - i, j = wp.tid() - if joint_mask[j]: - v = joint_pos[i, j] - if v < lower or v > upper: - out[i] = True + """2D kernel (num_envs, num_selected_joints). ``out`` is pre-zeroed; only writes True.""" + i, k = wp.tid() + v = joint_pos[i, joint_ids[k]] + if v < lower or v > upper: + out[i] = True def joint_pos_out_of_manual_limit( @@ -209,20 +209,15 @@ def joint_pos_out_of_manual_limit( ) -> None: """Terminate when joint positions are outside configured bounds. Writes into ``out``.""" asset: Articulation = env.scene[asset_cfg.name] - if asset_cfg.joint_mask is None: + if asset_cfg.joint_ids_wp is None: raise ValueError( - f"joint_pos_out_of_manual_limit requires SceneEntityCfg with resolved joint_mask, " + f"joint_pos_out_of_manual_limit requires SceneEntityCfg with resolved joint_ids_wp, " f"but got None for asset '{asset_cfg.name}'." ) - if asset.data.joint_pos.warp.shape[1] != asset_cfg.joint_mask.shape[0]: - raise ValueError( - f"joint_mask length ({asset_cfg.joint_mask.shape[0]}) does not match " - f"joint_pos dim ({asset.data.joint_pos.warp.shape[1]}) for asset '{asset_cfg.name}'." - ) wp.launch( kernel=_joint_pos_out_of_manual_limit_kernel, - dim=(env.num_envs, asset.data.joint_pos.warp.shape[1]), - inputs=[asset.data.joint_pos.warp, asset_cfg.joint_mask, bounds[0], bounds[1], out], + dim=(env.num_envs, asset_cfg.joint_ids_wp.shape[0]), + inputs=[asset.data.joint_pos.warp, asset_cfg.joint_ids_wp, bounds[0], bounds[1], out], device=env.device, ) diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.pyi b/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.pyi index 18431a745b31..e0d2d9bab6c2 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.pyi +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/__init__.pyi @@ -23,7 +23,6 @@ __all__ = [ "TerminationTermCfg", "ObservationManager", "RewardManager", - "SceneEntityCfg", "TerminationManager", ] @@ -47,5 +46,4 @@ from .manager_term_cfg import ( ) from .observation_manager import ObservationManager from .reward_manager import RewardManager -from .scene_entity_cfg import SceneEntityCfg from .termination_manager import TerminationManager diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py index 4d4a7d8973bc..6817bce70ae7 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py +++ b/source/isaaclab_experimental/isaaclab_experimental/managers/manager_base.py @@ -28,12 +28,11 @@ import isaaclab.utils.string as string_utils from isaaclab.managers.manager_base import _populate_term_defaults from isaaclab.managers.manager_term_cfg import ManagerTermBaseCfg +from isaaclab.managers.scene_entity_cfg import SceneEntityCfg from isaaclab.utils import string_to_callable, to_dict from isaaclab_experimental.utils.warp import is_warp_capturable -from .scene_entity_cfg import SceneEntityCfg - # import omni.timeline @@ -439,6 +438,7 @@ def _process_term_cfg_at_play(self, term_name: str, term_cfg: ManagerTermBaseCfg # load the entity try: value.resolve(self._env.scene) + value.resolve_warp_ids(self._env.scene) except ValueError as e: raise ValueError(f"Error while parsing '{term_name}:{key}'. {e}") # log the entity for checking later diff --git a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py b/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py deleted file mode 100644 index f6d30489eeca..000000000000 --- a/source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py +++ /dev/null @@ -1,73 +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 fork of :class:`isaaclab.managers.SceneEntityCfg`. - -This adds Warp-only cached selections (e.g. a joint mask) while keeping compatibility -with the stable manager stack (which type-checks against the stable SceneEntityCfg). -""" - -from __future__ import annotations - -from typing import TYPE_CHECKING - -import warp as wp - -from isaaclab.assets import ArticulationCfg -from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as _SceneEntityCfg - -if TYPE_CHECKING: - from isaaclab.scene import InteractiveScene - - -class SceneEntityCfg(_SceneEntityCfg): - """Scene entity configuration with an optional Warp joint mask. - - Notes: - - `joint_mask` is intended for Warp kernels only. - """ - - joint_mask: wp.array | None = None - - """Integer indices of selected joints — used for subset-sized gathers where a boolean mask - cannot provide the mapping from output index k to joint index.""" - joint_ids_wp: wp.array | None = None - - """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 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: 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) - super().resolve(scene) - - entity = scene[self.name] - - # -- Warp joint mask / ids for articulations - if isinstance(entity.cfg, ArticulationCfg): - if self.joint_ids == slice(None): - joint_ids_list = list(range(entity.num_joints)) - mask_list = [True] * entity.num_joints - else: - joint_ids_list = list(self.joint_ids) - mask_list = [False] * entity.num_joints - for idx in joint_ids_list: - mask_list[idx] = True - self.joint_mask = wp.array(mask_list, dtype=wp.bool, device=scene.device) - self.joint_ids_wp = wp.array(joint_ids_list, dtype=wp.int32, device=scene.device) - - # -- Warp body ids - if self.body_ids is not None and self.body_ids != slice(None): - self.body_ids_wp = wp.array(list(self.body_ids), dtype=wp.int32, device=scene.device) - elif hasattr(entity, "num_bodies"): - self.body_ids_wp = wp.array(list(range(entity.num_bodies)), dtype=wp.int32, device=scene.device) diff --git a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py index 758b2f9ecbee..78950b4f9eea 100644 --- a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py +++ b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py @@ -393,10 +393,14 @@ def __init__(self, assets: dict, env_origins, sensors=None): self.articulations = dict(assets) self.rigid_objects = {} self.num_envs = NUM_ENVS + self.device = DEVICE def __getitem__(self, name: str): return self._assets[name] + def keys(self): + return self._assets.keys() + # --------------------------------------------------------------------------- # Root-state mutation helper @@ -484,17 +488,13 @@ def prev_action(self) -> torch.Tensor: class MockSceneEntityCfg: - """Unified cfg that works for both stable (joint_ids) and experimental (joint_mask / joint_ids_wp).""" + """Unified cfg that works for both stable (joint_ids) and Warp (joint_ids_wp) terms.""" - def __init__(self, name: str, joint_ids: list[int], num_joints: int, device: str): + def __init__(self, name: str, joint_ids: list[int], device: str): self.name = name self.joint_ids = joint_ids - # Experimental extras - mask = [False] * num_joints - for idx in joint_ids: - mask[idx] = True - self.joint_mask = wp.array(mask, dtype=wp.bool, device=device) + # Warp extras self.joint_ids_wp = wp.array(joint_ids, dtype=wp.int32, device=device) diff --git a/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py index e93e73267938..828805ecfcd9 100644 --- a/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py +++ b/source/isaaclab_experimental/test/envs/mdp/test_events_warp_parity.py @@ -108,7 +108,7 @@ class _Env: @pytest.fixture() def all_joints_cfg(): - return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), DEVICE) # ============================================================================ diff --git a/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py index 0f014cc2b3fd..aca5f570c6e0 100644 --- a/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py +++ b/source/isaaclab_experimental/test/envs/mdp/test_observations_warp_parity.py @@ -41,6 +41,7 @@ ) import isaaclab.envs.mdp.observations as stable_obs +from isaaclab.managers import SceneEntityCfg # ============================================================================ # Fixtures @@ -195,12 +196,17 @@ class _Env: @pytest.fixture() def all_joints_cfg(): - return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), DEVICE) -@pytest.fixture() -def subset_cfg(): - return MockSceneEntityCfg("robot", [0, 2, 5, 8], NUM_JOINTS, DEVICE) +@pytest.fixture(params=[[0, 2, 5, 8], [8, 0, 5, 2]], ids=["sorted", "reordered"]) +def subset_cfg(request, scene): + """A joint subset in asset order and reordered, resolved as a task resolves it: by name with + ``preserve_order=True``, then :meth:`SceneEntityCfg.resolve_warp_ids` for the Warp terms.""" + cfg = SceneEntityCfg("robot", joint_names=[f"joint_{i}" for i in request.param], preserve_order=True) + cfg.resolve(scene) + cfg.resolve_warp_ids(scene) + return cfg # ============================================================================ diff --git a/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py index c81f6f73ec89..be6e212733cf 100644 --- a/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py +++ b/source/isaaclab_experimental/test/envs/mdp/test_rewards_warp_parity.py @@ -210,13 +210,13 @@ class _Env: @pytest.fixture() def all_joints_cfg(): - return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), DEVICE) @pytest.fixture() def subset_cfg(): """Non-identity joint subset, so the masked kernels' false branch is exercised.""" - return MockSceneEntityCfg("robot", [0, 2, 5, 8], NUM_JOINTS, DEVICE) + return MockSceneEntityCfg("robot", [0, 2, 5, 8], DEVICE) @pytest.fixture() diff --git a/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py b/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py index 9676f2b06044..18e919afb0b6 100644 --- a/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py +++ b/source/isaaclab_experimental/test/envs/mdp/test_terminations_warp_parity.py @@ -208,13 +208,13 @@ class _Env: @pytest.fixture() def all_joints_cfg(): - return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), NUM_JOINTS, DEVICE) + return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), DEVICE) @pytest.fixture() def subset_cfg(): """Non-identity joint subset, so the masked kernel's false branch is exercised.""" - return MockSceneEntityCfg("robot", [0, 2, 5, 8], NUM_JOINTS, DEVICE) + return MockSceneEntityCfg("robot", [0, 2, 5, 8], DEVICE) @pytest.fixture() diff --git a/source/isaaclab_experimental/test/envs/test_frontend.py b/source/isaaclab_experimental/test/envs/test_frontend.py index 0ce54f95f1d3..1c63a36dd072 100644 --- a/source/isaaclab_experimental/test/envs/test_frontend.py +++ b/source/isaaclab_experimental/test/envs/test_frontend.py @@ -7,13 +7,11 @@ Pure-Python unit tests; no app launch. Covers: -* :func:`SceneEntityCfg.from_stable` field copy. * :func:`_require_newton_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 resolution and :meth:`_cfg_route_modules` cfg-hierarchy resolution. -* :func:`_promote_scene_entity_cfgs` walks ``term.params`` dicts. * :func:`_swap_mdp` raises with a path list when twins are missing and skips already-warp terms (the swap itself is covered by the real-registry tests in ``test_frontend_cfg_conversion.py``). @@ -36,13 +34,11 @@ FrontendIncompatibleError, WarpFrontend, ) -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.envs import ManagerBasedRLEnvCfg from isaaclab.managers.manager_term_cfg import EventTermCfg, ObservationTermCfg, RewardTermCfg -from isaaclab.managers.scene_entity_cfg import SceneEntityCfg as StableSceneEntityCfg from isaaclab.utils import configclass # ====================================================================== @@ -79,27 +75,6 @@ class _WarpActionCls: _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 - - -@configclass -class _ObservationsCfg: - policy: _PolicyObsGroup | None = None - perception: _ExtraObsGroup | None = None - - @configclass class _RewardsCfg: r1: RewardTermCfg | None = None @@ -111,17 +86,10 @@ 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: @@ -176,45 +144,6 @@ def fake_env(*, cfg: Any, **kwargs: Any) -> Any: assert cfg.scene is scene_cfg and scene_cfg.class_type is None -# ====================================================================== -# SceneEntityCfg.from_stable -# ====================================================================== - - -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" - assert isinstance(warp, WarpSceneEntityCfg) - # 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 - - # ====================================================================== # _require_newton_physics # ====================================================================== @@ -366,74 +295,6 @@ def test_swap_mdp_skips_already_warp(monkeypatch: pytest.MonkeyPatch): assert cfg.rewards.r1.func is _warp_twin_func -# ====================================================================== -# _promote_scene_entity_cfgs -# ====================================================================== - - -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.WarpFrontend._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.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. - 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.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) - # 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) - - # ====================================================================== # Twin resolution # ====================================================================== diff --git a/source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst b/source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst new file mode 100644 index 000000000000..16974fa69c19 --- /dev/null +++ b/source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst @@ -0,0 +1,2 @@ +* Changed the Warp Cartpole ``joint_pos_target_l2`` reward to loop over the selected joints in the order of + ``joint_ids``, as the torch term does. 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 0e7ac5ca0fcf..b93b1154edb2 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 @@ -8,9 +8,11 @@ from typing import TYPE_CHECKING import warp as wp -from isaaclab_experimental.managers import ManagerTermBase, SceneEntityCfg +from isaaclab_experimental.managers import ManagerTermBase from isaaclab_experimental.utils.warp.utils import wrap_to_pi +from isaaclab.managers import SceneEntityCfg + if TYPE_CHECKING: import torch @@ -22,29 +24,27 @@ @wp.kernel def _joint_pos_target_l2_kernel( joint_pos: wp.array(dtype=wp.float32, ndim=2), - joint_mask: wp.array(dtype=wp.bool), + joint_ids: wp.array(dtype=wp.int32), out: wp.array(dtype=wp.float32), target: float, ): - """Accumulate squared wrapped-to-pi joint-position deviation from target over masked joints.""" + """Accumulate squared wrapped-to-pi joint-position deviation from target over the selected joints.""" i = wp.tid() s = float(0.0) - for j in range(joint_pos.shape[1]): - if joint_mask[j]: - a = wrap_to_pi(joint_pos[i, j]) - d = a - target - s += d * d + for k in range(joint_ids.shape[0]): + a = wrap_to_pi(joint_pos[i, joint_ids[k]]) + d = a - target + s += d * d out[i] = s def joint_pos_target_l2(env: ManagerBasedRLEnv, out, target: float, asset_cfg: SceneEntityCfg) -> None: """Penalize joint position deviation from a target value. Writes into ``out``.""" asset: Articulation = env.scene[asset_cfg.name] - assert asset.data.joint_pos.warp.shape[1] == asset_cfg.joint_mask.shape[0] wp.launch( kernel=_joint_pos_target_l2_kernel, dim=env.num_envs, - inputs=[asset.data.joint_pos.warp, asset_cfg.joint_mask, out, target], + inputs=[asset.data.joint_pos.warp, asset_cfg.joint_ids_wp, out, target], device=env.device, ) diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py index dfcfad6e0f55..7877914be6a9 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py @@ -493,7 +493,7 @@ def __init__(self, cfg: DirectRLEnvCfg, render_mode: str | None = None, **kwargs self.rpy = wp.zeros((self.num_envs), dtype=wp.vec3f, device=self.sim.device) self.angle_to_target = wp.zeros((self.num_envs), dtype=wp.float32, device=self.sim.device) self.dof_pos_scaled = wp.zeros((self.num_envs, self.robot.num_joints), dtype=wp.float32, device=self.sim.device) - self.env_origins = wp.from_torch(self.scene.env_origins, dtype=wp.vec3f) + self.env_origins = self.scene.env_origins_wp self.actions_mapped = wp.zeros((self.num_envs, self.robot.num_joints), dtype=wp.float32, device=self.sim.device) # Initial states and targets 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 bf05de7435cd..c67fa8e8712b 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 @@ -15,8 +15,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.managers import SceneEntityCfg from isaaclab.utils.warp.math import rotate_vec_to_body_frame, yaw_from_quat if TYPE_CHECKING: 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 649c50928985..e5566130b41d 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 @@ -15,10 +15,10 @@ import torch import warp as wp -from isaaclab_experimental.managers import SceneEntityCfg from isaaclab_experimental.managers.manager_base import ManagerTermBase import isaaclab.utils.string as string_utils +from isaaclab.managers import SceneEntityCfg from isaaclab.utils.warp.math import rotate_vec_to_body_frame if TYPE_CHECKING: diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py index c42cdaa053d7..c3093495570c 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py @@ -582,7 +582,7 @@ def __init__(self, cfg: AllegroHandEnvCfg, render_mode: str | None = None, **kwa self.z_unit_vec = wp.vec3f(0.0, 0.0, 1.0) # Per-env origins (Warp view for kernels; Torch env uses `self.scene.env_origins` directly). - self.env_origins = wp.from_torch(self.scene.env_origins, dtype=wp.vec3f) + self.env_origins = self.scene.env_origins_wp # --------------------------------------------------------------------- # Warp buffers diff --git a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py index ae5c365bfade..b5380990518d 100644 --- a/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py +++ b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/velocity/mdp/rewards.py @@ -15,8 +15,8 @@ from typing import TYPE_CHECKING import warp as wp -from isaaclab_experimental.managers import SceneEntityCfg +from isaaclab.managers import SceneEntityCfg from isaaclab.utils.warp.math import yaw_quat if TYPE_CHECKING: