From b7bb82bdd60d63f015841433461f0d3a6815f160 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 14:52:15 -0800 Subject: [PATCH 01/13] Return the terrain env origins as a ProxyArray --- ...jichuanh-warp-stable-foundations.added.rst | 6 +++++ ...chuanh-warp-stable-foundations.changed.rst | 6 +++++ .../jichuanh-warp-stable-foundations.major | 0 .../isaaclab/scene/interactive_scene.py | 12 ++++++--- .../isaaclab/sensors/camera/camera.py | 6 ++++- .../isaaclab/terrains/terrain_importer.py | 17 +++++++++--- .../test/scene/test_interactive_scene.py | 7 ++--- .../test/sensors/test_camera_pose_inputs.py | 26 +++++++++++++++++++ .../test/terrains/test_terrain_importer.py | 2 +- ...chuanh-warp-stable-foundations.changed.rst | 3 +++ .../jichuanh-warp-stable-foundations.major | 0 ...chuanh-warp-stable-foundations.removed.rst | 3 +++ .../envs/manager_based_env_warp.py | 10 ++----- .../jichuanh-warp-stable-foundations.skip | 0 .../test/assets/test_articulation.py | 2 +- ...chuanh-warp-stable-foundations.changed.rst | 2 ++ .../core/locomotion/locomotion_env_warp.py | 2 +- .../core/reorient/reorient_warp_env.py | 4 +-- 18 files changed, 83 insertions(+), 25 deletions(-) create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst create mode 100644 source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.major create mode 100644 source/isaaclab/test/sensors/test_camera_pose_inputs.py create mode 100644 source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst create mode 100644 source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.major create mode 100644 source/isaaclab_experimental/changelog.d/jichuanh-warp-stable-foundations.removed.rst create mode 100644 source/isaaclab_ov/changelog.d/jichuanh-warp-stable-foundations.skip create mode 100644 source/isaaclab_tasks_experimental/changelog.d/jichuanh-warp-stable-foundations.changed.rst 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..eb4e9eb6ad2d --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst @@ -0,0 +1,6 @@ +* 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. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst new file mode 100644 index 000000000000..cfce4cb0eb1e --- /dev/null +++ b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst @@ -0,0 +1,6 @@ +* **Breaking:** Changed :attr:`~isaaclab.scene.InteractiveScene.env_origins` and + :attr:`~isaaclab.terrains.TerrainImporter.env_origins` to a :class:`~isaaclab.utils.warp.ProxyArray` of + ``wp.vec3f``, so Warp code reads the origins without a conversion. Torch code reads ``env_origins.torch``, of shape + ``(num_envs, 3)``. Indexing, arithmetic and torch functions on the ProxyArray itself still work with a one-time + deprecation warning, but ``isinstance(..., torch.Tensor)``, ``.shape``, ``.dtype`` and ``.device`` now describe the + Warp array, as for the position fields of the asset data. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.major b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.major new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index c56abacd263a..21c4a2b2fdda 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -47,6 +47,7 @@ from ..sim import SimulationContext from ..sim.utils.stage import get_current_stage, get_current_stage_id from ..utils import instantiate, validate +from ..utils.warp import ProxyArray from .interactive_scene_cfg import InteractiveSceneCfg if TYPE_CHECKING: @@ -314,16 +315,19 @@ def num_envs(self) -> int: return self.cfg.num_envs @property - def env_origins(self) -> torch.Tensor: - """Per-env world origins, shape ``(num_envs, 3)``.""" + def env_origins(self) -> ProxyArray: + """Per-env world origins [m] as a :class:`~isaaclab.utils.warp.ProxyArray` of ``wp.vec3f``. + + Torch code reads ``.torch``, of shape ``(num_envs, 3)``; Warp code reads ``.warp``, of shape ``(num_envs,)``. + """ if self._terrain is not None: return self._terrain.env_origins 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) + if not isinstance(self._env_origins, ProxyArray): + self._env_origins = ProxyArray(wp.array(self._env_origins, dtype=wp.vec3f, device=self.device)) return self._env_origins @property diff --git a/source/isaaclab/isaaclab/sensors/camera/camera.py b/source/isaaclab/isaaclab/sensors/camera/camera.py index 159d5426587b..50354cd7edf4 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera.py @@ -993,7 +993,11 @@ def _update_camera_state( def _as_device_tensor(self, value: np.ndarray | torch.Tensor | Sequence, num_cols: int) -> torch.Tensor: """Convert array-like input to a float32 tensor of shape (N, ``num_cols``) on the camera device.""" - if isinstance(value, np.ndarray): + if isinstance(value, ProxyArray): + # deprecation bridge: callers such as ``set_world_poses_from_view(eyes, scene.env_origins)`` + ProxyArray._warn_implicit() + value = value.torch + elif isinstance(value, np.ndarray): value = torch.from_numpy(value) elif not isinstance(value, torch.Tensor): value = torch.tensor(value) diff --git a/source/isaaclab/isaaclab/terrains/terrain_importer.py b/source/isaaclab/isaaclab/terrains/terrain_importer.py index 9437ec197009..313425fdf40f 100644 --- a/source/isaaclab/isaaclab/terrains/terrain_importer.py +++ b/source/isaaclab/isaaclab/terrains/terrain_importer.py @@ -11,11 +11,13 @@ import numpy as np import torch import trimesh +import warp as wp from .. import sim as sim_utils from ..markers import VisualizationMarkers from ..markers.config import FRAME_MARKER_CFG from ..utils import instantiate, replace, to_dict, validate +from ..utils.warp import ProxyArray from .utils import create_prim_from_mesh if TYPE_CHECKING: @@ -52,8 +54,11 @@ 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).""" + env_origins: ProxyArray + """The origins of the environments [m] as a :class:`~isaaclab.utils.warp.ProxyArray` of ``wp.vec3f``. + + Torch code reads ``.torch``, of shape (num_envs, 3); Warp code reads ``.warp``, of shape (num_envs,). + """ def __init__(self, cfg: TerrainImporterCfg): """Initialize the terrain importer. @@ -347,14 +352,18 @@ def configure_env_origins(self, origins: np.ndarray | torch.Tensor | None = None # store the origins self.terrain_origins = origins.to(self.device, dtype=torch.float) # compute environment origins - self.env_origins = self._compute_env_origins_curriculum(self.cfg.num_envs, self.terrain_origins) + self.env_origins = ProxyArray( + wp.array(self._compute_env_origins_curriculum(self.cfg.num_envs, self.terrain_origins), dtype=wp.vec3f) + ) else: self.terrain_origins = None # check if env spacing is valid if self.cfg.env_spacing is None: raise ValueError("Environment spacing must be specified for configuring grid-like origins.") # compute environment origins - self.env_origins = self._compute_env_origins_grid(self.cfg.num_envs, self.cfg.env_spacing) + self.env_origins = ProxyArray( + wp.array(self._compute_env_origins_grid(self.cfg.num_envs, self.cfg.env_spacing), dtype=wp.vec3f) + ) def update_env_origins(self, env_ids: torch.Tensor, move_up: torch.Tensor, move_down: torch.Tensor): """Update the environment origins based on the terrain levels.""" diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 40946843a879..6764f9faa334 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -25,6 +25,7 @@ from isaaclab.sim import build_simulation_context from isaaclab.utils import configclass, instantiate, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR +from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.integration @@ -149,7 +150,7 @@ def test_relative_deformable_state(): ) scene = SimpleNamespace( device="cpu", - env_origins=env_origins, + env_origins=ProxyArray(wp.from_torch(env_origins, dtype=wp.vec3f)), _articulations={}, _cable_objects={}, _deformable_objects={"object": deformable}, @@ -256,7 +257,7 @@ def test_empty_scene_leaves_clone_lifecycle_to_caller(): assert sim.get_clone_plan() is None 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)) + torch.testing.assert_close(scene.env_origins.torch, torch.from_numpy(grid_positions)) 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)) @@ -277,7 +278,7 @@ 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)) + torch.testing.assert_close(scene.env_origins.torch, torch.from_numpy(positions)) 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/sensors/test_camera_pose_inputs.py b/source/isaaclab/test/sensors/test_camera_pose_inputs.py new file mode 100644 index 000000000000..c679e4a24204 --- /dev/null +++ b/source/isaaclab/test/sensors/test_camera_pose_inputs.py @@ -0,0 +1,26 @@ +# 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 + +"""Kit-less tests for the array inputs that the camera pose setters accept.""" + +import pytest +import torch +import warp as wp + +from isaaclab.sensors.camera import Camera +from isaaclab.utils.warp import ProxyArray + +pytestmark = [pytest.mark.unit, pytest.mark.kitless] + + +def test_pose_input_accepts_proxy_array(): + """A ProxyArray such as ``scene.env_origins`` converts through its torch view, also on CPU.""" + camera = Camera.__new__(Camera) + camera._device = "cpu" + origins = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]) + + converted = camera._as_device_tensor(ProxyArray(wp.from_torch(origins, dtype=wp.vec3f)), 3) + + torch.testing.assert_close(converted, origins) diff --git a/source/isaaclab/test/terrains/test_terrain_importer.py b/source/isaaclab/test/terrains/test_terrain_importer.py index 9c36c51e6d3c..734beb73fa6c 100644 --- a/source/isaaclab/test/terrains/test_terrain_importer.py +++ b/source/isaaclab/test/terrains/test_terrain_importer.py @@ -93,7 +93,7 @@ def test_plane(num_envs, env_spacing): terrain_importer = TerrainImporter(terrain_importer_cfg) # These square grids are centered on the world origin. - origins = terrain_importer.env_origins + origins = terrain_importer.env_origins.torch half_span = (int(np.sqrt(num_envs)) - 1) * env_spacing / 2.0 assert origins.shape == (num_envs, 3) assert origins.device == torch.device("cuda:0") 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/manager_based_env_warp.py b/source/isaaclab_experimental/isaaclab_experimental/envs/manager_based_env_warp.py index 2fe63fdf9920..ebefac8c5b78 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.warp def resolve_env_mask( self, diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-stable-foundations.skip b/source/isaaclab_ov/changelog.d/jichuanh-warp-stable-foundations.skip new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/source/isaaclab_ov/test/assets/test_articulation.py b/source/isaaclab_ov/test/assets/test_articulation.py index 1c18f8f81023..b2d6cd74c5e6 100644 --- a/source/isaaclab_ov/test/assets/test_articulation.py +++ b/source/isaaclab_ov/test/assets/test_articulation.py @@ -753,7 +753,7 @@ def test_heterogeneous_articulation_clone_indexed_state(device, variant, tmp_pat assert robot.num_joints == 1 assert robot.num_bodies == 2 assert robot.root_view.prim_paths == [f"/World/envs/env_{i}/Robot" for i in range(scene.num_envs)] - torch.testing.assert_close(robot.data.root_pos_w.torch, scene.env_origins) + torch.testing.assert_close(robot.data.root_pos_w.torch, scene.env_origins.torch) selected = torch.tensor([5, 3], device=device) positions = torch.tensor([[0.25], [-0.4]], device=device) robot.write_joint_state_to_sim(positions, torch.zeros_like(positions), env_ids=selected) 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/locomotion/locomotion_env_warp.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/locomotion/locomotion_env_warp.py index dfcfad6e0f55..a97c14a2b15a 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.warp 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/reorient/reorient_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py index c42cdaa053d7..66ee846d9545 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 @@ -581,8 +581,8 @@ def __init__(self, cfg: AllegroHandEnvCfg, render_mode: str | None = None, **kwa self.y_unit_vec = wp.vec3f(0.0, 1.0, 0.0) 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) + # Per-env origins (Warp view for kernels; the Torch env uses `self.scene.env_origins.torch`). + self.env_origins = self.scene.env_origins.warp # --------------------------------------------------------------------- # Warp buffers From eb3aeac15e9a5820b555b3f1b5e6edff07c5462e Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Fri, 13 Nov 2026 14:52:30 -0800 Subject: [PATCH 02/13] Resolve Warp selections on the stable SceneEntityCfg and remove the experimental fork --- .../isaaclab/managers/scene_entity_cfg.py | 51 ++++++- .../test/managers/test_scene_entity_cfg.py | 70 +++++++++ .../isaaclab_experimental/envs/frontend.py | 51 +------ .../isaaclab_experimental/envs/mdp/events.py | 12 +- .../envs/mdp/observations.py | 2 +- .../isaaclab_experimental/envs/mdp/rewards.py | 86 +++++------ .../envs/mdp/terminations.py | 29 ++-- .../managers/__init__.pyi | 2 - .../managers/manager_base.py | 4 +- .../managers/scene_entity_cfg.py | 73 --------- .../test/envs/mdp/parity_helpers.py | 8 +- .../test/envs/test_frontend.py | 139 ------------------ .../core/cartpole/mdp/rewards.py | 20 +-- .../core/locomotion/mdp/observations.py | 2 +- .../core/locomotion/mdp/rewards.py | 2 +- .../core/velocity/mdp/rewards.py | 2 +- 16 files changed, 206 insertions(+), 347 deletions(-) delete mode 100644 source/isaaclab_experimental/isaaclab_experimental/managers/scene_entity_cfg.py diff --git a/source/isaaclab/isaaclab/managers/scene_entity_cfg.py b/source/isaaclab/isaaclab/managers/scene_entity_cfg.py index 5cd82c44922b..c9593e74608b 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,17 @@ 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 _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/test/managers/test_scene_entity_cfg.py b/source/isaaclab/test/managers/test_scene_entity_cfg.py index 828b2b79791b..f07c33ccd789 100644 --- a/source/isaaclab/test/managers/test_scene_entity_cfg.py +++ b/source/isaaclab/test/managers/test_scene_entity_cfg.py @@ -6,22 +6,31 @@ """Scene selections resolve on the host, then finalize to device indices used without synchronization.""" import copy +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, replace 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 +117,64 @@ 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] + # the torch selections keep their form + subset.finalize("cpu") + assert subset.joint_ids.dtype == torch.long + assert full.joint_ids == slice(None) + + +def test_copies_share_the_warp_ids(scene): + """Configuration copies made after :meth:`resolve_warp_ids` share the Warp ids instead of copying device memory.""" + scene = _Scene(scene) + cfg = SceneEntityCfg("robot", joint_names=["part_1"]) + cfg.resolve(scene) + cfg.resolve_warp_ids(scene) + + for copied in (cfg.copy(), clone(cfg), replace(cfg, name="robot"), copy.deepcopy(cfg)): + assert copied.joint_ids_wp is cfg.joint_ids_wp + assert copied.body_ids_wp is cfg.body_ids_wp + + +@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 still shares the Warp ids.""" + 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 diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index cb0105a6b06b..4ec0bca567ff 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,24 @@ 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): 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 +233,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 +669,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/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..c235e8741698 100644 --- a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py +++ b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py @@ -484,17 +484,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): 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/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/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/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/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: From d76f8a609ae8712f3dd6b5d10493a237332dfd50 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:24:40 -0800 Subject: [PATCH 03/13] Import warp in the scene test that builds env origins as a ProxyArray The import came from Part 2b's scene test, which no longer changes this file. --- source/isaaclab/test/scene/test_interactive_scene.py | 1 + 1 file changed, 1 insertion(+) diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 6764f9faa334..6cb23f70469e 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -12,6 +12,7 @@ import numpy as np import pytest import torch +import warp as wp from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg import isaaclab.sim as sim_utils From 256ca44ffc9dcdfa8d20cd5196b99ebf81277ad9 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:32:44 -0800 Subject: [PATCH 04/13] Check the Warp joint observations against torch for a reordered joint selection A selection resolved with preserve_order=True keeps the configured joint order; the Warp gather must produce the same columns as the torch term. --- .../test/envs/mdp/test_observations_warp_parity.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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..7a2ef8fb636b 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 @@ -198,9 +198,10 @@ def all_joints_cfg(): return MockSceneEntityCfg("robot", list(range(NUM_JOINTS)), 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): + """A joint subset in asset order, and the same joints reordered as ``preserve_order=True`` resolves them.""" + return MockSceneEntityCfg("robot", request.param, NUM_JOINTS, DEVICE) # ============================================================================ From fdcb3959383e40bf9727a369d4c1c6d3f74a66a7 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:49:42 -0800 Subject: [PATCH 05/13] Drop the ProxyArray branch of the camera pose input conversion Camera._as_device_tensor already converts a ProxyArray through its array interface, with the same values and the same one-time deprecation warning, and no caller passes the scene's env origins to a camera pose setter. Remove the branch and its test. --- .../isaaclab/sensors/camera/camera.py | 6 +---- .../test/sensors/test_camera_pose_inputs.py | 26 ------------------- 2 files changed, 1 insertion(+), 31 deletions(-) delete mode 100644 source/isaaclab/test/sensors/test_camera_pose_inputs.py diff --git a/source/isaaclab/isaaclab/sensors/camera/camera.py b/source/isaaclab/isaaclab/sensors/camera/camera.py index 50354cd7edf4..159d5426587b 100644 --- a/source/isaaclab/isaaclab/sensors/camera/camera.py +++ b/source/isaaclab/isaaclab/sensors/camera/camera.py @@ -993,11 +993,7 @@ def _update_camera_state( def _as_device_tensor(self, value: np.ndarray | torch.Tensor | Sequence, num_cols: int) -> torch.Tensor: """Convert array-like input to a float32 tensor of shape (N, ``num_cols``) on the camera device.""" - if isinstance(value, ProxyArray): - # deprecation bridge: callers such as ``set_world_poses_from_view(eyes, scene.env_origins)`` - ProxyArray._warn_implicit() - value = value.torch - elif isinstance(value, np.ndarray): + if isinstance(value, np.ndarray): value = torch.from_numpy(value) elif not isinstance(value, torch.Tensor): value = torch.tensor(value) diff --git a/source/isaaclab/test/sensors/test_camera_pose_inputs.py b/source/isaaclab/test/sensors/test_camera_pose_inputs.py deleted file mode 100644 index c679e4a24204..000000000000 --- a/source/isaaclab/test/sensors/test_camera_pose_inputs.py +++ /dev/null @@ -1,26 +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 - -"""Kit-less tests for the array inputs that the camera pose setters accept.""" - -import pytest -import torch -import warp as wp - -from isaaclab.sensors.camera import Camera -from isaaclab.utils.warp import ProxyArray - -pytestmark = [pytest.mark.unit, pytest.mark.kitless] - - -def test_pose_input_accepts_proxy_array(): - """A ProxyArray such as ``scene.env_origins`` converts through its torch view, also on CPU.""" - camera = Camera.__new__(Camera) - camera._device = "cpu" - origins = torch.tensor([[0.0, 1.0, 2.0], [3.0, 4.0, 5.0]]) - - converted = camera._as_device_tensor(ProxyArray(wp.from_torch(origins, dtype=wp.vec3f)), 3) - - torch.testing.assert_close(converted, origins) From a6d8a9786780041af0cc1d1b2f9bbe7ed7af699a Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:49:53 -0800 Subject: [PATCH 06/13] Describe the three steps of WarpFrontend.adapt_cfg once The header still announced four steps and repeated the noise step that the list now names as its third item. --- .../isaaclab_experimental/envs/frontend.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py index 4ec0bca567ff..8e27d977d64a 100644 --- a/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py +++ b/source/isaaclab_experimental/isaaclab_experimental/envs/frontend.py @@ -171,8 +171,7 @@ def adapt_cfg(cls, cfg: Any) -> None: Idempotent: re-running on an already-adapted cfg is a no-op (the steps 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`. From 86cfd8daeee0e456819774baaccc633836da2953 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:50:01 -0800 Subject: [PATCH 07/13] Restore the reorient Warp env's env origins comment Only the line that takes the Warp view of the env origins had to change. --- .../core/reorient/reorient_warp_env.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 66ee846d9545..2f132f4665e7 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 @@ -581,7 +581,7 @@ def __init__(self, cfg: AllegroHandEnvCfg, render_mode: str | None = None, **kwa self.y_unit_vec = wp.vec3f(0.0, 1.0, 0.0) self.z_unit_vec = wp.vec3f(0.0, 0.0, 1.0) - # Per-env origins (Warp view for kernels; the Torch env uses `self.scene.env_origins.torch`). + # Per-env origins (Warp view for kernels; Torch env uses `self.scene.env_origins` directly). self.env_origins = self.scene.env_origins.warp # --------------------------------------------------------------------- From 8c389254cb5ddb697038fe86d913f16ed2d78dbf Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:50:27 -0800 Subject: [PATCH 08/13] Trim the scene entity configuration tests to what they own Fold the copy-sharing test into the subclass deep-copy test: copy, clone and replace share one configclass path that test_configclass covers, so one clone line proves the field metadata and the deep-copy assertions prove __deepcopy__. Drop the finalize tail of the Warp id resolution test, which repeats test_finalize_moves_resolved_selections_to_device. --- .../test/managers/test_scene_entity_cfg.py | 23 ++++--------------- 1 file changed, 5 insertions(+), 18 deletions(-) diff --git a/source/isaaclab/test/managers/test_scene_entity_cfg.py b/source/isaaclab/test/managers/test_scene_entity_cfg.py index f07c33ccd789..337beec9119f 100644 --- a/source/isaaclab/test/managers/test_scene_entity_cfg.py +++ b/source/isaaclab/test/managers/test_scene_entity_cfg.py @@ -19,7 +19,7 @@ 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, replace +from isaaclab.utils import clone, configclass from isaaclab.utils.string import resolve_matching_names pytestmark = pytest.mark.unit @@ -140,22 +140,6 @@ def test_resolve_warp_ids_fills_the_selection_order(scene): 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] - # the torch selections keep their form - subset.finalize("cpu") - assert subset.joint_ids.dtype == torch.long - assert full.joint_ids == slice(None) - - -def test_copies_share_the_warp_ids(scene): - """Configuration copies made after :meth:`resolve_warp_ids` share the Warp ids instead of copying device memory.""" - scene = _Scene(scene) - cfg = SceneEntityCfg("robot", joint_names=["part_1"]) - cfg.resolve(scene) - cfg.resolve_warp_ids(scene) - - for copied in (cfg.copy(), clone(cfg), replace(cfg, name="robot"), copy.deepcopy(cfg)): - assert copied.joint_ids_wp is cfg.joint_ids_wp - assert copied.body_ids_wp is cfg.body_ids_wp @configclass @@ -166,7 +150,8 @@ class _SelectionCfg(SceneEntityCfg): def test_deepcopy_keeps_resolved_subclass_state(scene): - """A deep copy keeps the fields the constructor does not take and still shares the Warp ids.""" + """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) @@ -178,3 +163,5 @@ def test_deepcopy_keeps_resolved_subclass_state(scene): 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 From 3d3ccf5e5e6d53b952231eacb47c34718e1a368a Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:51:46 -0800 Subject: [PATCH 09/13] Resolve the reordered parity subset through the real scene entity configuration The joint-subset observation parity cases built their selection with a mock that wrote the Warp ids straight from the list, so a resolve_warp_ids that sorted the ids would not fail them. They now resolve a SceneEntityCfg by joint name with preserve_order=True, then resolve_warp_ids, on the mock articulation; the mock scene gains the keys() and device that resolution reads. --- .../test/envs/mdp/parity_helpers.py | 4 ++++ .../test/envs/mdp/test_observations_warp_parity.py | 11 ++++++++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py index c235e8741698..ce0daff70c0c 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 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 7a2ef8fb636b..b1cc97f7e1b4 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 @@ -199,9 +200,13 @@ def all_joints_cfg(): @pytest.fixture(params=[[0, 2, 5, 8], [8, 0, 5, 2]], ids=["sorted", "reordered"]) -def subset_cfg(request): - """A joint subset in asset order, and the same joints reordered as ``preserve_order=True`` resolves them.""" - return MockSceneEntityCfg("robot", request.param, NUM_JOINTS, DEVICE) +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 # ============================================================================ From f8115f6b59d5c6564112c354d1b794314026e9e1 Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Sun, 15 Nov 2026 17:52:08 -0800 Subject: [PATCH 10/13] Drop the unused joint count of the parity tests' scene entity mock Its only use, building a joint mask, went with the mask. --- source/isaaclab_experimental/test/envs/mdp/parity_helpers.py | 2 +- .../test/envs/mdp/test_events_warp_parity.py | 2 +- .../test/envs/mdp/test_observations_warp_parity.py | 2 +- .../test/envs/mdp/test_rewards_warp_parity.py | 4 ++-- .../test/envs/mdp/test_terminations_warp_parity.py | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py index ce0daff70c0c..78950b4f9eea 100644 --- a/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py +++ b/source/isaaclab_experimental/test/envs/mdp/parity_helpers.py @@ -490,7 +490,7 @@ def prev_action(self) -> torch.Tensor: class MockSceneEntityCfg: """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 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 b1cc97f7e1b4..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 @@ -196,7 +196,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) @pytest.fixture(params=[[0, 2, 5, 8], [8, 0, 5, 2]], ids=["sorted", "reordered"]) 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() From 2724709e7e6831b97f8ca52f68818cf25722cc5d Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 10:30:22 -0800 Subject: [PATCH 11/13] Serialize a SceneEntityCfg with Warp ids: lists in to_dict, validated, pickled without them --- .../jichuanh-warp-stable-foundations.added.rst | 3 ++- .../isaaclab/managers/scene_entity_cfg.py | 11 +++++++++++ source/isaaclab/isaaclab/utils/configclass.py | 5 +++++ source/isaaclab/isaaclab/utils/dict.py | 4 ++++ .../test/managers/test_scene_entity_cfg.py | 17 +++++++++++++++++ 5 files changed, 39 insertions(+), 1 deletion(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst index eb4e9eb6ad2d..c43284e3828d 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst @@ -3,4 +3,5 @@ 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. + 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. diff --git a/source/isaaclab/isaaclab/managers/scene_entity_cfg.py b/source/isaaclab/isaaclab/managers/scene_entity_cfg.py index c9593e74608b..44f3e89bdd4a 100644 --- a/source/isaaclab/isaaclab/managers/scene_entity_cfg.py +++ b/source/isaaclab/isaaclab/managers/scene_entity_cfg.py @@ -221,6 +221,17 @@ def __deepcopy__(self, memo: dict) -> SceneEntityCfg: 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/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 337beec9119f..8ecfad6fcadb 100644 --- a/source/isaaclab/test/managers/test_scene_entity_cfg.py +++ b/source/isaaclab/test/managers/test_scene_entity_cfg.py @@ -6,6 +6,7 @@ """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 @@ -142,6 +143,22 @@ def test_resolve_warp_ids_fills_the_selection_order(scene): 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.""" From ef26a72db98eb0037645ec1f24394e2f5c07fa3e Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 10:36:53 -0800 Subject: [PATCH 12/13] Keep env_origins a torch tensor and add env_origins_wp, its Warp view, for Warp code --- ...jichuanh-warp-stable-foundations.added.rst | 3 +++ ...chuanh-warp-stable-foundations.changed.rst | 6 ----- ...=> jichuanh-warp-stable-foundations.minor} | 0 .../isaaclab/scene/interactive_scene.py | 26 ++++++++++++------ .../isaaclab/terrains/terrain_importer.py | 27 ++++++++++--------- .../test/scene/test_interactive_scene.py | 10 +++---- .../test/terrains/test_terrain_importer.py | 5 +++- .../envs/manager_based_env_warp.py | 2 +- .../jichuanh-warp-stable-foundations.skip | 0 .../test/assets/test_articulation.py | 2 +- .../core/locomotion/locomotion_env_warp.py | 2 +- .../core/reorient/reorient_warp_env.py | 2 +- 12 files changed, 49 insertions(+), 36 deletions(-) delete mode 100644 source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst rename source/isaaclab/changelog.d/{jichuanh-warp-stable-foundations.major => jichuanh-warp-stable-foundations.minor} (100%) delete mode 100644 source/isaaclab_ov/changelog.d/jichuanh-warp-stable-foundations.skip diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst index c43284e3828d..b4cbbfc1b12e 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst @@ -5,3 +5,6 @@ ``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 environment origins as a ``wp.vec3f`` Warp view of + ``env_origins`` for Warp code. ``env_origins`` stays a :class:`torch.Tensor`. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst deleted file mode 100644 index cfce4cb0eb1e..000000000000 --- a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.changed.rst +++ /dev/null @@ -1,6 +0,0 @@ -* **Breaking:** Changed :attr:`~isaaclab.scene.InteractiveScene.env_origins` and - :attr:`~isaaclab.terrains.TerrainImporter.env_origins` to a :class:`~isaaclab.utils.warp.ProxyArray` of - ``wp.vec3f``, so Warp code reads the origins without a conversion. Torch code reads ``env_origins.torch``, of shape - ``(num_envs, 3)``. Indexing, arithmetic and torch functions on the ProxyArray itself still work with a one-time - deprecation warning, but ``isinstance(..., torch.Tensor)``, ``.shape``, ``.dtype`` and ``.device`` now describe the - Warp array, as for the position fields of the asset data. diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.major b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.minor similarity index 100% rename from source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.major rename to source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.minor diff --git a/source/isaaclab/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index 21c4a2b2fdda..47fb8ab5273d 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -47,7 +47,6 @@ from ..sim import SimulationContext from ..sim.utils.stage import get_current_stage, get_current_stage_id from ..utils import instantiate, validate -from ..utils.warp import ProxyArray from .interactive_scene_cfg import InteractiveSceneCfg if TYPE_CHECKING: @@ -315,21 +314,32 @@ def num_envs(self) -> int: return self.cfg.num_envs @property - def env_origins(self) -> ProxyArray: - """Per-env world origins [m] as a :class:`~isaaclab.utils.warp.ProxyArray` of ``wp.vec3f``. - - Torch code reads ``.torch``, of shape ``(num_envs, 3)``; Warp code reads ``.warp``, of shape ``(num_envs,)``. - """ + def env_origins(self) -> torch.Tensor: + """Per-env world origins, shape ``(num_envs, 3)``.""" if self._terrain is not None: return self._terrain.env_origins 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, ProxyArray): - self._env_origins = ProxyArray(wp.array(self._env_origins, dtype=wp.vec3f, device=self.device)) + 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 + @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. + + A view of :attr:`env_origins`: both share one memory, so a write of either shows in the other. + """ + if self._terrain is not None: + return self._terrain.env_origins_wp + origins = self.env_origins + cached = getattr(self, "_env_origins_wp", None) + if cached is None or cached[0] is not origins: + cached = self._env_origins_wp = (origins, wp.from_torch(origins, dtype=wp.vec3f)) + return cached[1] + @property def terrain(self) -> TerrainImporter | None: """The terrain in the scene. If None, then the scene has no terrain. diff --git a/source/isaaclab/isaaclab/terrains/terrain_importer.py b/source/isaaclab/isaaclab/terrains/terrain_importer.py index 313425fdf40f..c6fe7fd714c3 100644 --- a/source/isaaclab/isaaclab/terrains/terrain_importer.py +++ b/source/isaaclab/isaaclab/terrains/terrain_importer.py @@ -17,7 +17,6 @@ from ..markers import VisualizationMarkers from ..markers.config import FRAME_MARKER_CFG from ..utils import instantiate, replace, to_dict, validate -from ..utils.warp import ProxyArray from .utils import create_prim_from_mesh if TYPE_CHECKING: @@ -54,11 +53,8 @@ class TerrainImporter: Otherwise, the environment origins are computed based on the grid spacing. """ - env_origins: ProxyArray - """The origins of the environments [m] as a :class:`~isaaclab.utils.warp.ProxyArray` of ``wp.vec3f``. - - Torch code reads ``.torch``, of shape (num_envs, 3); Warp code reads ``.warp``, of shape (num_envs,). - """ + env_origins: torch.Tensor + """The origins of the environments. Shape is (num_envs, 3).""" def __init__(self, cfg: TerrainImporterCfg): """Initialize the terrain importer. @@ -147,6 +143,17 @@ def flat_patches(self) -> dict[str, torch.Tensor]: """ return self._terrain_flat_patches + @property + def env_origins_wp(self) -> wp.array: + """The origins of the environments as a Warp array of ``wp.vec3f``, shape (num_envs,), for Warp code. + + A view of :attr:`env_origins`: both share one memory, so a write of either shows in the other. + """ + cached = getattr(self, "_env_origins_wp", None) + if cached is None or cached[0] is not self.env_origins: + cached = self._env_origins_wp = (self.env_origins, wp.from_torch(self.env_origins, dtype=wp.vec3f)) + return cached[1] + @property def terrain_names(self) -> list[str]: """A list of names of the imported terrains.""" @@ -352,18 +359,14 @@ def configure_env_origins(self, origins: np.ndarray | torch.Tensor | None = None # store the origins self.terrain_origins = origins.to(self.device, dtype=torch.float) # compute environment origins - self.env_origins = ProxyArray( - wp.array(self._compute_env_origins_curriculum(self.cfg.num_envs, self.terrain_origins), dtype=wp.vec3f) - ) + self.env_origins = self._compute_env_origins_curriculum(self.cfg.num_envs, self.terrain_origins) else: self.terrain_origins = None # check if env spacing is valid if self.cfg.env_spacing is None: raise ValueError("Environment spacing must be specified for configuring grid-like origins.") # compute environment origins - self.env_origins = ProxyArray( - wp.array(self._compute_env_origins_grid(self.cfg.num_envs, self.cfg.env_spacing), dtype=wp.vec3f) - ) + self.env_origins = self._compute_env_origins_grid(self.cfg.num_envs, self.cfg.env_spacing) def update_env_origins(self, env_ids: torch.Tensor, move_up: torch.Tensor, move_down: torch.Tensor): """Update the environment origins based on the terrain levels.""" diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 6cb23f70469e..1ca5b90b25bd 100644 --- a/source/isaaclab/test/scene/test_interactive_scene.py +++ b/source/isaaclab/test/scene/test_interactive_scene.py @@ -12,7 +12,6 @@ import numpy as np import pytest import torch -import warp as wp from isaaclab_physx.sim.schemas import PhysxRigidBodyCfg import isaaclab.sim as sim_utils @@ -26,7 +25,6 @@ from isaaclab.sim import build_simulation_context from isaaclab.utils import configclass, instantiate, replace from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR -from isaaclab.utils.warp import ProxyArray pytestmark = pytest.mark.integration @@ -151,7 +149,7 @@ def test_relative_deformable_state(): ) scene = SimpleNamespace( device="cpu", - env_origins=ProxyArray(wp.from_torch(env_origins, dtype=wp.vec3f)), + env_origins=env_origins, _articulations={}, _cable_objects={}, _deformable_objects={"object": deformable}, @@ -258,7 +256,7 @@ def test_empty_scene_leaves_clone_lifecycle_to_caller(): assert sim.get_clone_plan() is None 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, torch.from_numpy(grid_positions)) + torch.testing.assert_close(scene.env_origins, torch.from_numpy(grid_positions)) 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)) @@ -279,7 +277,9 @@ 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, torch.from_numpy(positions)) + torch.testing.assert_close(scene.env_origins, torch.from_numpy(positions)) + # the Warp view follows the origins of the new clone plan + assert scene.env_origins_wp.ptr == scene.env_origins.data_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 734beb73fa6c..41e4cc54ac8a 100644 --- a/source/isaaclab/test/terrains/test_terrain_importer.py +++ b/source/isaaclab/test/terrains/test_terrain_importer.py @@ -93,12 +93,15 @@ def test_plane(num_envs, env_spacing): terrain_importer = TerrainImporter(terrain_importer_cfg) # These square grids are centered on the world origin. - origins = terrain_importer.env_origins.torch + origins = terrain_importer.env_origins half_span = (int(np.sqrt(num_envs)) - 1) * env_spacing / 2.0 assert origins.shape == (num_envs, 3) 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])) + # Warp code reads a view of the same memory + assert terrain_importer.env_origins_wp.ptr == origins.data_ptr() + assert terrain_importer.env_origins_wp.shape == (num_envs,) # check if mesh prim path exists mesh_prim_path = terrain_importer.cfg.prim_path + "/terrain" 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 ebefac8c5b78..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 @@ -276,7 +276,7 @@ def device(self): @property def env_origins_wp(self) -> wp.array: """Scene env origins as a warp ``vec3f`` array.""" - return self.scene.env_origins.warp + return self.scene.env_origins_wp def resolve_env_mask( self, diff --git a/source/isaaclab_ov/changelog.d/jichuanh-warp-stable-foundations.skip b/source/isaaclab_ov/changelog.d/jichuanh-warp-stable-foundations.skip deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/source/isaaclab_ov/test/assets/test_articulation.py b/source/isaaclab_ov/test/assets/test_articulation.py index b2d6cd74c5e6..1c18f8f81023 100644 --- a/source/isaaclab_ov/test/assets/test_articulation.py +++ b/source/isaaclab_ov/test/assets/test_articulation.py @@ -753,7 +753,7 @@ def test_heterogeneous_articulation_clone_indexed_state(device, variant, tmp_pat assert robot.num_joints == 1 assert robot.num_bodies == 2 assert robot.root_view.prim_paths == [f"/World/envs/env_{i}/Robot" for i in range(scene.num_envs)] - torch.testing.assert_close(robot.data.root_pos_w.torch, scene.env_origins.torch) + torch.testing.assert_close(robot.data.root_pos_w.torch, scene.env_origins) selected = torch.tensor([5, 3], device=device) positions = torch.tensor([[0.25], [-0.4]], device=device) robot.write_joint_state_to_sim(positions, torch.zeros_like(positions), env_ids=selected) 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 a97c14a2b15a..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 = self.scene.env_origins.warp + 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/reorient/reorient_warp_env.py b/source/isaaclab_tasks_experimental/isaaclab_tasks_experimental/core/reorient/reorient_warp_env.py index 2f132f4665e7..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 = self.scene.env_origins.warp + self.env_origins = self.scene.env_origins_wp # --------------------------------------------------------------------- # Warp buffers From 97665adb2e583a23e59d71b18fe6bb56a4bd58eb Mon Sep 17 00:00:00 2001 From: Jichuan Hu Date: Tue, 17 Nov 2026 10:56:25 -0800 Subject: [PATCH 13/13] Hold the env origins in a Warp array and read env_origins as its torch view --- ...jichuanh-warp-stable-foundations.added.rst | 5 ++- .../isaaclab/scene/interactive_scene.py | 39 ++++++++++++------- .../isaaclab/terrains/terrain_importer.py | 32 ++++++++++----- .../test/scene/test_interactive_scene.py | 5 ++- .../test/terrains/test_terrain_importer.py | 8 +++- 5 files changed, 61 insertions(+), 28 deletions(-) diff --git a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst index b4cbbfc1b12e..e3b9b2ebc4b9 100644 --- a/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst +++ b/source/isaaclab/changelog.d/jichuanh-warp-stable-foundations.added.rst @@ -6,5 +6,6 @@ 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 environment origins as a ``wp.vec3f`` Warp view of - ``env_origins`` for Warp code. ``env_origins`` stays a :class:`torch.Tensor`. + :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/isaaclab/scene/interactive_scene.py b/source/isaaclab/isaaclab/scene/interactive_scene.py index 47fb8ab5273d..d4dc67432a3d 100644 --- a/source/isaaclab/isaaclab/scene/interactive_scene.py +++ b/source/isaaclab/isaaclab/scene/interactive_scene.py @@ -315,30 +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 - 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 + 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. - A view of :attr:`env_origins`: both share one memory, so a write of either shows in the other. + It holds the origins; :attr:`env_origins` is its torch view. """ if self._terrain is not None: return self._terrain.env_origins_wp - origins = self.env_origins - cached = getattr(self, "_env_origins_wp", None) - if cached is None or cached[0] is not origins: - cached = self._env_origins_wp = (origins, wp.from_torch(origins, dtype=wp.vec3f)) - return cached[1] + 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 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 c6fe7fd714c3..d96df1cc20fb 100644 --- a/source/isaaclab/isaaclab/terrains/terrain_importer.py +++ b/source/isaaclab/isaaclab/terrains/terrain_importer.py @@ -53,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. @@ -144,15 +141,32 @@ def flat_patches(self) -> dict[str, torch.Tensor]: return self._terrain_flat_patches @property - def env_origins_wp(self) -> wp.array: + 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. - A view of :attr:`env_origins`: both share one memory, so a write of either shows in the other. + It holds the origins; :attr:`env_origins` is its torch view. """ - cached = getattr(self, "_env_origins_wp", None) - if cached is None or cached[0] is not self.env_origins: - cached = self._env_origins_wp = (self.env_origins, wp.from_torch(self.env_origins, dtype=wp.vec3f)) - return cached[1] + return getattr(self, "_env_origins_wp", None) @property def terrain_names(self) -> list[str]: diff --git a/source/isaaclab/test/scene/test_interactive_scene.py b/source/isaaclab/test/scene/test_interactive_scene.py index 1ca5b90b25bd..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,8 +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 view follows the origins of the new clone plan - assert scene.env_origins_wp.ptr == scene.env_origins.data_ptr() + # 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 41e4cc54ac8a..4b081306fd9b 100644 --- a/source/isaaclab/test/terrains/test_terrain_importer.py +++ b/source/isaaclab/test/terrains/test_terrain_importer.py @@ -99,9 +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])) - # Warp code reads a view of the same memory + # 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" @@ -131,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."""