Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
* Fixed :class:`~isaaclab.sensors.SensorBase` refreshing sensors later than their ``update_period`` once the
sensor clock had run for some seconds. Whether a sensor is due was decided by subtracting two float32
timestamps that grow with the episode, and their rounding error exceeded the ``1e-6`` tolerance, so sensors
with ``update_period`` set to a multiple of the physics time step skipped refreshes (for example, the height
scanner of the locomotion tasks from 16 s into an episode, and sensors with long update periods at small
time steps within the first second). The time since the last refresh is now accumulated in float64.
Existing timestamp buffers and Warp kernel signatures were preserved. Custom sensors that allocate or
replace their own timestamp buffers automatically acquire elapsed-time tracking on first use.
Built-in sensors use the new ``*_elapsed_kernel`` entry points; direct callers of the existing kernels
continue to work with their original timestamp-based timing behavior.
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,8 @@ def _resolve_first_transition_tolerance(self, abs_tol: float | None) -> float:

Valid air and contact timers are integer multiples of the sensor update interval, so half an
interval is the midpoint between "one update ago" and "two updates ago". Using it as the
tolerance keeps the comparison robust to the float32 rounding error of the sensor clock,
which grows with simulated time and quickly exceeds any fixed tolerance.
tolerance keeps the comparison robust to the float32 rounding of the timers, which exceeds
any small fixed tolerance for periods of a few tenths of a second.

Args:
abs_tol: The caller-provided tolerance [s]. If None, half the sensor update interval
Expand Down
92 changes: 92 additions & 0 deletions source/isaaclab/isaaclab/sensors/kernels.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,95 @@ def reset_envs_kernel(
timestamp_last_update[env] = 0.0
# Set all reset sensors to outdated so that they are updated when data is called the next time.
is_outdated[env] = True


@wp.kernel
def update_timestamp_elapsed_kernel(
is_outdated: wp.array(dtype=wp.bool),
timestamp: wp.array(dtype=wp.float32),
elapsed_since_update: wp.array(dtype=wp.float64),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Keep legacy kernel launch contracts

Existing direct launches of the three timing and three backend contact kernels reject old argument counts or dtypes. Keep legacy entry points functional through deprecation, with targeted warnings, migration guidance, and old/new validation.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Preserve timing kernel launch contracts

Existing launches of the three timing kernels now fail argument validation or pass an update period where a due threshold is expected. Retain legacy entry points during a warned migration and validate both forms.

dt: wp.float64,
due_threshold: wp.float64,
):
"""Advances the sensor clocks and marks environments as outdated if the update period elapsed.

Due-ness is decided on the time elapsed since the last refresh, accumulated in float64 from zero.
Subtracting two float32 timestamps instead loses precision as the timestamps grow, which delays
refreshes once the episode has run for some seconds.

Args:
is_outdated: Boolean array indicating which envs need update.
timestamp: Current timestamp per env [s].
elapsed_since_update: Time since the last refresh per env [s].
dt: Simulation time step [s].
due_threshold: Elapsed time at which the sensor is due, ``update_period - 1e-6`` [s].
"""
env = wp.tid()
timestamp[env] = timestamp[env] + wp.float32(dt)
elapsed = elapsed_since_update[env] + dt
elapsed_since_update[env] = elapsed
if elapsed >= due_threshold:
is_outdated[env] = True


@wp.kernel
def update_outdated_envs_elapsed_kernel(
is_outdated: wp.array(dtype=wp.bool),
timestamp: wp.array(dtype=wp.float32),
timestamp_last_update: wp.array(dtype=wp.float32),
elapsed_since_update: wp.array(dtype=wp.float64),
):
"""Updates timestamp and clears outdated flag for outdated environments.

Args:
is_outdated: Boolean array indicating which envs need update. Will be set to False.
timestamp: Current timestamp per env.
timestamp_last_update: Last update timestamp per env. Will be set to current timestamp.
elapsed_since_update: Time since the last refresh per env. Will be set to 0.0.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — State elapsed-buffer units

The refresh and reset kernel docstrings omit seconds for the new elapsed-time argument, unlike the scheduling and backend descriptions. Add [s] to both.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Document elapsed-buffer units and shape

The new refresh and reset kernel arguments omit the elapsed array’s units and shape. Document seconds and the per-environment shape at both declarations, as the contribution guide requires.

"""
env = wp.tid()
if is_outdated[env]:
timestamp_last_update[env] = timestamp[env]
elapsed_since_update[env] = wp.float64(0.0)
is_outdated[env] = False


@wp.kernel
def reset_envs_elapsed_kernel(
reset_mask: wp.array(dtype=wp.bool),
is_outdated: wp.array(dtype=wp.bool),
timestamp: wp.array(dtype=wp.float32),
timestamp_last_update: wp.array(dtype=wp.float32),
elapsed_since_update: wp.array(dtype=wp.float64),
):
"""Resets the current and last update timestamps and marks environments as outdated for those being reset.

Args:
reset_mask: Boolean array indicating which envs to reset.
is_outdated: Boolean array indicating which envs need update. Will be set to True for reset envs.
timestamp: Current timestamp per env. Will be set to 0.0 for reset envs.
timestamp_last_update: Last update timestamp per env. Will be set to 0.0 for reset envs.
elapsed_since_update: Time since the last refresh per env. Will be set to 0.0 for reset envs.
"""
env = wp.tid()
if not reset_mask[env]:
return

# Reset the timestamp for the sensors
timestamp[env] = 0.0

timestamp_last_update[env] = 0.0
elapsed_since_update[env] = wp.float64(0.0)
# Set all reset sensors to outdated so that they are updated when data is called the next time.
is_outdated[env] = True


@wp.kernel
def initialize_elapsed_time_kernel(
timestamp: wp.array(dtype=wp.float32),
timestamp_last_update: wp.array(dtype=wp.float32),
elapsed_since_update: wp.array(dtype=wp.float64),
):
"""Initialize elapsed time from existing sensor timestamps when adopting timing buffers."""
env = wp.tid()
elapsed_since_update[env] = wp.float64(timestamp[env]) - wp.float64(timestamp_last_update[env])
79 changes: 68 additions & 11 deletions source/isaaclab/isaaclab/sensors/sensor_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,21 @@
from ..sim.utils.queries import get_first_matching_ancestor_prim
from ..sim.utils.transforms import resolve_prim_pose
from ..utils import index_fill_
from .kernels import reset_envs_kernel, update_outdated_envs_kernel, update_timestamp_kernel
from .kernels import (
initialize_elapsed_time_kernel,
reset_envs_elapsed_kernel,
update_outdated_envs_elapsed_kernel,
update_timestamp_elapsed_kernel,
)
from .kernels import (
reset_envs_kernel as reset_envs_kernel,
)
from .kernels import (
update_outdated_envs_kernel as update_outdated_envs_kernel,
)
from .kernels import (
update_timestamp_kernel as update_timestamp_kernel,
)

if TYPE_CHECKING:
from .sensor_base_cfg import SensorBaseCfg
Expand All @@ -48,6 +62,9 @@ class SensorBase(ABC):
sensor is updated at every simulation step.
"""

_elapsed_timestamp: wp.array | None = None
_elapsed_timestamp_last_update: wp.array | None = None

def __init__(self, cfg: SensorBaseCfg):
"""Initialize the sensor class.

Expand Down Expand Up @@ -187,9 +204,15 @@ def reset(self, env_ids: Sequence[int] | None = None, env_mask: wp.array | None
"""
env_mask = self._resolve_indices_and_mask(env_ids, env_mask)
wp.launch(
reset_envs_kernel,
reset_envs_elapsed_kernel,
dim=self._num_envs,
inputs=[env_mask, self._is_outdated, self._timestamp, self._timestamp_last_update],
inputs=[
env_mask,
self._is_outdated,
self._timestamp,
self._timestamp_last_update,
self._elapsed_since_update,
],
device=self._device,
)
self._data_dirty = True
Expand All @@ -201,9 +224,15 @@ def update(self, dt: float, force_recompute: bool = False):
self._data_dirty = True
# Update the timestamp for the sensors
wp.launch(
update_timestamp_kernel,
update_timestamp_elapsed_kernel,
dim=self._num_envs,
inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update, dt, self.cfg.update_period],
inputs=[
self._is_outdated,
self._timestamp,
self._elapsed_since_update,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Compatibility — Bridge custom timing-buffer allocation

Custom sensors allocating or resizing the former timing arrays now lack a correctly sized elapsed buffer, breaking update and reset. Keep that path functional during a warned, documented migration and validate both paths.

dt,
self.cfg.update_period - 1e-6,
],
device=self._device,
)
# Update the buffers; debug visualization refreshes lazily from its callback.
Expand Down Expand Up @@ -265,10 +294,7 @@ def _initialize_impl(self):
self._ALL_ENV_MASK = wp.ones((self._num_envs), dtype=wp.bool, device=self._device)
self._reset_mask = wp.zeros((self._num_envs), dtype=wp.bool, device=self._device)
self._reset_mask_torch = wp.to_torch(self._reset_mask)
# timestamp and outdated flags
self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device)
self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device)
self._timestamp_last_update = wp.zeros_like(self._timestamp)
self._create_timing_buffers()
self._data_dirty = True

# Initialize debug visualization handle
Expand Down Expand Up @@ -418,6 +444,37 @@ def _clear_debug_vis_handle(self) -> None:
Helper functions.
"""

def _create_timing_buffers(self) -> None:
"""Allocates the per-environment outdated flags, timestamps and elapsed times used to schedule updates.

Sensors can call this again after changing :attr:`_num_envs` and reallocating their environment masks.
"""
# timestamp and outdated flags

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Remove the stale allocation comment

The comment names only timestamps and outdated flags, omitting the new elapsed buffer, and merely narrates the assignments. Remove it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Style Consistency — Remove the allocation narration

The comment merely labels the following assignments, repeats the method summary, and omits the new elapsed buffer. Delete it.

self._is_outdated = wp.ones(self._num_envs, dtype=wp.bool, device=self._device)
self._timestamp = wp.zeros(self._num_envs, dtype=wp.float32, device=self._device)
self._timestamp_last_update = wp.zeros_like(self._timestamp)
self._elapsed_time_buffer = wp.zeros(self._num_envs, dtype=wp.float64, device=self._device)
self._elapsed_timestamp = self._timestamp
self._elapsed_timestamp_last_update = self._timestamp_last_update

@property
def _elapsed_since_update(self) -> wp.array:
"""Elapsed time since refresh, adopting timestamp buffers allocated by custom sensors."""
if (
self._elapsed_timestamp is not self._timestamp
or self._elapsed_timestamp_last_update is not self._timestamp_last_update
):
self._elapsed_time_buffer = wp.empty(self._timestamp.shape, dtype=wp.float64, device=self._timestamp.device)
wp.launch(
initialize_elapsed_time_kernel,
dim=self._num_envs,
inputs=[self._timestamp, self._timestamp_last_update, self._elapsed_time_buffer],
device=self._device,
)
self._elapsed_timestamp = self._timestamp
self._elapsed_timestamp_last_update = self._timestamp_last_update
return self._elapsed_time_buffer

def _update_outdated_buffers(self, force_recompute: bool = False) -> None:
"""Fills the sensor data for the outdated sensors."""
if not force_recompute and not self._data_dirty:
Expand All @@ -429,9 +486,9 @@ def _mark_buffers_updated(self) -> None:
"""Commit capture timestamps after the sensor's output buffers have been filled."""
# update timestamps and clear outdated flags
wp.launch(
update_outdated_envs_kernel,
update_outdated_envs_elapsed_kernel,
dim=self._num_envs,
inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update],
inputs=[self._is_outdated, self._timestamp, self._timestamp_last_update, self._elapsed_since_update],
device=self._device,
)
self._data_dirty = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -297,9 +297,7 @@ def __init__(self, renderer, name, update_period=0.0):
self._frame = ProxyArray(wp.zeros(2, dtype=wp.int64, device="cpu"))
self._ALL_INDICES = wp.array([0, 1], dtype=wp.int32, device="cpu")
self._ALL_ENV_MASK = wp.ones(2, dtype=wp.bool, device="cpu")
self._is_outdated = wp.ones(2, dtype=wp.bool, device="cpu")
self._timestamp = wp.zeros(2, device="cpu")
self._timestamp_last_update = wp.zeros(2, device="cpu")
self._create_timing_buffers()
self._data_dirty = True
self.pose = 0.0
self._view = SimpleNamespace(count=2, xform_world_space_writer=self._pose_writer)
Expand Down Expand Up @@ -329,9 +327,7 @@ def __init__(self, name, batches=None):
self._num_envs = 2
self._is_initialized = True
self._is_visualizing = False
self._is_outdated = wp.ones(2, dtype=wp.bool, device="cpu")
self._timestamp = wp.zeros(2, device="cpu")
self._timestamp_last_update = wp.zeros(2, device="cpu")
self._create_timing_buffers()
self._data_dirty = True
self._data = np.zeros(2, dtype=int)
self.name = name
Expand Down
123 changes: 123 additions & 0 deletions source/isaaclab/test/sensors/test_contact_timing_kernels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# 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

"""Contact timing and compatibility of the backend-specific Warp kernel entry points."""

import numpy as np
import pytest
import warp as wp
from isaaclab_newton.sensors.contact_sensor import contact_sensor_kernels as newton_kernels
from isaaclab_ov.sensors.contact_sensor import kernels as ov_kernels
from isaaclab_physx.sensors.contact_sensor import kernels as physx_kernels

from isaaclab.test.utils import DeviceScope, test_devices

pytestmark = [pytest.mark.unit, pytest.mark.kitless]


@pytest.mark.parametrize("device", test_devices(DeviceScope.CPU))
@pytest.mark.parametrize("backend", ["physx", "ovphysx", "newton"])
def test_contact_kernel_entry_points_preserve_timing_and_mask(backend, device):
"""Old timestamp callers and new elapsed-time callers update forces and transitions correctly."""
for use_elapsed in (False, True):
timestamp = wp.full(2, 8.25, dtype=wp.float32, device=device)
timing = (
[wp.full(2, 0.02, dtype=wp.float64, device=device)]
if use_elapsed
else [timestamp, wp.full(2, 8.0, dtype=wp.float32, device=device)]
)
mask = wp.array([True, False], dtype=wp.bool, device=device)
normal = wp.array([[(0.0, 0.0, 10.0)], [(0.0, 0.0, 20.0)]], dtype=wp.vec3f, device=device)
friction = wp.zeros((2, 1), dtype=wp.vec3f, device=device)
normal_history = wp.zeros((2, 2, 1), dtype=wp.vec3f, device=device)
total_history = wp.zeros_like(normal_history)
normal_output = wp.zeros_like(normal)
total_output = wp.zeros_like(normal)
air = wp.full((2, 1), 0.5, dtype=wp.float32, device=device)
contact = wp.zeros_like(air)
last_air = wp.full_like(air, -1.0)
last_contact = wp.full_like(air, -1.0)

if backend == "newton":
kernel = (
newton_kernels.update_contact_sensor_elapsed_kernel
if use_elapsed
else newton_kernels.update_contact_sensor_kernel
)
inputs = [
2,
0,
1.0,
mask,
normal,
None,
normal,
None,
friction,
None,
*timing,
total_history,
None,
normal_history,
None,
None,
None,
air,
contact,
last_air,
last_contact,
]
else:
if backend == "physx":
kernel = (
physx_kernels.update_net_forces_elapsed_kernel
if use_elapsed
else physx_kernels.update_net_forces_kernel
)
else:
kernel = (
ov_kernels.update_net_forces_ovphysx_elapsed_kernel
if use_elapsed
else ov_kernels.update_net_forces_ovphysx_kernel
)
inputs = [
normal.flatten(),
friction.flatten(),
None,
None,
mask,
2,
0,
2,
1.0,
*([timestamp, *timing] if use_elapsed else timing),
normal_output,
normal_history,
None,
None,
air,
contact,
last_air,
last_contact,
total_output,
total_history,
None,
None,
None,
None,
None,
None,
]
wp.launch(kernel, dim=(2, 1), inputs=inputs, device=device)

dt = 0.02 if use_elapsed else 0.25
np.testing.assert_allclose(contact.numpy(), [[dt], [0.0]], atol=1e-7, rtol=0)
np.testing.assert_allclose(last_air.numpy(), [[0.5 + dt], [-1.0]], atol=1e-7, rtol=0)
np.testing.assert_array_equal(air.numpy(), [[0.0], [0.5]])
np.testing.assert_array_equal(last_contact.numpy(), [[-1.0], [-1.0]])
expected_history = np.zeros((2, 2, 1, 3), dtype=np.float32)
expected_history[0, 0, 0, 2] = 10.0
np.testing.assert_array_equal(normal_history.numpy(), expected_history)
np.testing.assert_array_equal(total_history.numpy(), expected_history)
Loading
Loading