-
Notifications
You must be signed in to change notification settings - Fork 2.7k
[FEATURE] Add history_length to Sensors
#2655
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Milotrince
wants to merge
13
commits into
Genesis-Embodied-AI:main
Choose a base branch
from
Milotrince:sensor_history
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
6df6761
fix errors when n_envs>0 for mouse_interaction and kin probe debug_draw
Milotrince b3f49b5
add sensor history_length
Milotrince 1c58510
detect update_ground_truth_only
Milotrince 1e91b64
Revert unrelated change
Milotrince c8fc05f
add contact sensor link filtering
Milotrince add94c1
cleanup default update_ground_truth_only
Milotrince 703bb94
cleanup history cache
Milotrince f38da3d
address claude review and cleanup
Milotrince 4289448
fix fastcache on temperature sensor
Milotrince 05c99da
camera sensor not support history
Milotrince a22e6aa
fix proximity draw debug on cpu
Milotrince 436859a
address claude review 2
Milotrince 1f23d3a
address minor review comments
Milotrince File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,16 +1,15 @@ | ||
| import functools | ||
| from dataclasses import dataclass, field | ||
| from functools import partial | ||
| from typing import TYPE_CHECKING, ClassVar, Generic, Sequence, Type, TypeVar, get_args, get_origin | ||
|
|
||
| from typing_extensions import TypeVar as TypeVarWithDefault | ||
| from typing import TYPE_CHECKING, ClassVar, Generic, Sequence, TypeVar, get_args, get_origin | ||
|
|
||
| import numpy as np | ||
| import quadrants as qd | ||
| import torch | ||
| from typing_extensions import TypeVar as TypeVarWithDefault | ||
|
|
||
| import genesis as gs | ||
| from genesis.typing import NumArrayType, NumericType | ||
| from genesis.repr_base import RBC | ||
| from genesis.typing import NumArrayType, NumericType | ||
| from genesis.utils.geom import euler_to_quat | ||
| from genesis.utils.misc import broadcast_tensor, concat_with_tensor, make_tensor_field | ||
|
|
||
|
|
@@ -39,6 +38,19 @@ def _to_tuple(*values: NumArrayType, length_per_value: int = 3) -> tuple[Numeric | |
| return full_tuple | ||
|
|
||
|
|
||
| def assert_measured_cache_will_update(method): | ||
| @functools.wraps(method) | ||
| def wrapper(self, *args, **kwargs): | ||
| if not self._shared_metadata.update_ground_truth_only: | ||
| gs.raise_exception( | ||
| "Tried to update noise option but update_ground_truth_only is True. " | ||
| "Set a noisy option to nonzero value so that the measured cache will be updated." | ||
| ) | ||
| return method(self, *args, **kwargs) | ||
|
|
||
| return wrapper | ||
|
|
||
|
|
||
| # Note: dataclass is used as opposed to pydantic.BaseModel since torch.Tensors are not supported by default | ||
| @dataclass | ||
| class SharedSensorMetadata: | ||
|
|
@@ -48,6 +60,10 @@ class SharedSensorMetadata: | |
|
|
||
| cache_sizes: list[int] = field(default_factory=list) | ||
| delays_ts: torch.Tensor = make_tensor_field((0, 0), dtype_factory=lambda: gs.tc_int) | ||
| history_lengths: list[int] = field(default_factory=list) | ||
| # If True, skip _update_shared_cache for this sensor class. Defaults True; concrete sensors set False when they | ||
| # need per-step measured-cache updates (cameras set True in BaseCameraSensor.build for lazy render-on-read). | ||
| update_ground_truth_only: bool = True | ||
|
|
||
| def __del__(self): | ||
| try: | ||
|
|
@@ -120,41 +136,66 @@ def __init__(self, sensor_options: "SensorOptions", sensor_idx: int, sensor_mana | |
| self._manager: "SensorManager" = sensor_manager | ||
| self._shared_metadata: SharedSensorMetadataT = sensor_manager._sensors_metadata[type(self)] | ||
| self._is_built = False | ||
| self._history_length: int = self._options.history_length | ||
|
|
||
| self._dt = self._manager._sim.dt | ||
| self._delay_ts = round(self._options.delay / self._dt) | ||
|
|
||
| self._cache_slices: list[slice] = [] | ||
| return_format = self._get_return_format() | ||
| assert len(return_format) > 0 | ||
| if isinstance(return_format[0], int): | ||
| return_format = (return_format,) | ||
| self._return_shapes: tuple[tuple[int, ...], ...] = return_format | ||
| intrinsic_shapes: tuple[tuple[int, ...], ...] = ( | ||
| (return_format,) if isinstance(return_format[0], int) else return_format | ||
| ) | ||
| self._intrinsic_return_shapes: tuple[tuple[int, ...], ...] = intrinsic_shapes | ||
|
|
||
| self._cache_size = 0 | ||
| for shape in self._return_shapes: | ||
| for shape in intrinsic_shapes: | ||
| data_size = np.prod(shape) | ||
| self._cache_slices.append(slice(self._cache_size, self._cache_size + data_size)) | ||
| self._cache_size += data_size | ||
|
|
||
| # Slices into the per-sensor tensor from get_cloned_from_cache (history stacks H frames on dim 1). | ||
| self._read_flat_slices: list[slice] = [] | ||
| read_off = 0 | ||
| for shape in intrinsic_shapes: | ||
| p = np.prod(shape) | ||
| span = p * self._history_length if self._history_length > 0 else p | ||
| self._read_flat_slices.append(slice(read_off, read_off + span)) | ||
| read_off += span | ||
|
|
||
| if self._history_length > 0: | ||
| self._return_shapes = tuple((self._history_length, *s) for s in intrinsic_shapes) | ||
| else: | ||
| self._return_shapes = intrinsic_shapes | ||
|
|
||
| self._cache_idx: int = -1 # initialized by SensorManager during build | ||
|
|
||
| # =============================== methods to implement =============================== | ||
|
|
||
| def _options_require_measured_cache(self): | ||
| return np.any(np.abs(self._options.delay) > gs.EPS) | ||
|
|
||
| def build(self): | ||
| """ | ||
| Build the sensor. | ||
|
|
||
| This method is called by SensorManager during the scene build phase. | ||
| This is where any shared metadata should be initialized. | ||
| """ | ||
| if self._options_require_measured_cache(): | ||
| self._shared_metadata.update_ground_truth_only = False | ||
|
|
||
| self._shared_metadata.delays_ts = concat_with_tensor( | ||
| self._shared_metadata.delays_ts, | ||
| self._delay_ts, | ||
| expand=(self._manager._sim._B, 1), | ||
| dim=1, | ||
| ) | ||
| self._shared_metadata.cache_sizes.append(self._cache_size) | ||
| self._shared_metadata.history_lengths.append(self._options.history_length) | ||
| if self._delay_ts > 0: | ||
| self._shared_metadata.update_ground_truth_only = False | ||
|
|
||
| @classmethod | ||
| def reset(cls, shared_metadata: SharedSensorMetadataT, shared_ground_truth_cache: torch.Tensor, envs_idx): | ||
|
|
@@ -207,7 +248,9 @@ def _update_shared_cache( | |
| Update the shared sensor cache for all sensors of this class using metadata in SensorManager. | ||
|
|
||
| The information in shared_cache should be the final measured sensor data after all noise and post-processing. | ||
| NOTE: The implementation should include applying the delay using the `_apply_delay_to_shared_cache()` method. | ||
| ``buffered_data`` is a sliced view of the per-dtype ground-truth ring: SensorManager has already written this | ||
| step's GT into the current slot; use ``_apply_delay_to_shared_cache(..., buffered_data, ...)`` for read delay | ||
| (do not call ``set`` on it for that GT block). | ||
| """ | ||
| raise NotImplementedError(f"{cls.__name__} has not implemented `update_shared_cache()`.") | ||
|
|
||
|
|
@@ -282,7 +325,7 @@ def _apply_delay_to_shared_cache( | |
| shared_cache : torch.Tensor | ||
| The shared cache tensor. | ||
| buffered_data : TensorRingBuffer | ||
| The buffered data tensor. | ||
| Ground-truth timeline ring for this sensor class slice (current step already written by SensorManager). | ||
| cur_jitter_ts : torch.Tensor | None | ||
| The current jitter in timesteps (divided by simulation dt) before the sensor data is read. | ||
| interpolate : Sequence[bool] | None | ||
|
|
@@ -327,7 +370,12 @@ def _get_formatted_data(self, tensor: torch.Tensor, envs_idx=None) -> torch.Tens | |
| tensor_chunk = tensor[envs_idx].reshape((len(envs_idx), -1)) | ||
|
|
||
| for i, shape in enumerate(self._return_shapes): | ||
| field_data = tensor_chunk[..., self._cache_slices[i]].reshape((len(envs_idx), *shape)) | ||
| sl = self._read_flat_slices[i] | ||
| if self._history_length > 0: | ||
| intrinsic_shape = self._intrinsic_return_shapes[i] | ||
| field_data = tensor_chunk[..., sl].reshape((len(envs_idx), self._history_length, *intrinsic_shape)) | ||
| else: | ||
| field_data = tensor_chunk[..., sl].reshape((len(envs_idx), *shape)) | ||
| if self._manager._sim.n_envs == 0: | ||
| field_data = field_data[0] | ||
| return_values.append(field_data) | ||
|
|
@@ -443,27 +491,33 @@ class NoisySensorMixin(Generic[NoisySensorMetadataMixinT]): | |
| """ | ||
|
|
||
| @gs.assert_built | ||
| @assert_measured_cache_will_update | ||
| def set_resolution(self, resolution, envs_idx=None): | ||
| self._set_metadata_field(resolution, self._shared_metadata.resolution, self._cache_size, envs_idx) | ||
|
|
||
| @gs.assert_built | ||
| @assert_measured_cache_will_update | ||
| def set_bias(self, bias, envs_idx=None): | ||
| self._set_metadata_field(bias, self._shared_metadata.bias, self._cache_size, envs_idx) | ||
|
|
||
| @gs.assert_built | ||
| @assert_measured_cache_will_update | ||
| def set_random_walk(self, random_walk, envs_idx=None): | ||
| self._set_metadata_field(random_walk, self._shared_metadata.random_walk, self._cache_size, envs_idx) | ||
|
|
||
| @gs.assert_built | ||
| @assert_measured_cache_will_update | ||
| def set_noise(self, noise, envs_idx=None): | ||
| self._set_metadata_field(noise, self._shared_metadata.noise, self._cache_size, envs_idx) | ||
|
|
||
| @gs.assert_built | ||
| @assert_measured_cache_will_update | ||
| def set_jitter(self, jitter, envs_idx=None): | ||
| jitter_ts = np.asarray(jitter, dtype=gs.np_float) / self._dt | ||
| self._set_metadata_field(jitter_ts, self._shared_metadata.jitter_ts, 1, envs_idx) | ||
|
|
||
| @gs.assert_built | ||
| @assert_measured_cache_will_update | ||
| def set_delay(self, delay, envs_idx=None): | ||
| self._set_metadata_field(delay, self._shared_metadata.delay_in_steps, 1, envs_idx) | ||
|
|
||
|
|
@@ -496,6 +550,17 @@ def build(self): | |
| self._shared_metadata.cur_jitter_ts = torch.zeros_like(self._shared_metadata.jitter_ts, device=gs.device) | ||
| self._shared_metadata.interpolate.append(self._options.interpolate) | ||
|
|
||
| def _options_require_measured_cache(self) -> bool: | ||
| return super()._options_require_measured_cache() or ( | ||
| self._options.jitter > gs.EPS | ||
| or (self._options.interpolate and (self._delay_ts > 0 or self._options.jitter > gs.EPS)) | ||
| or np.any(np.abs(self._options.bias) > gs.EPS) | ||
| or np.any(np.abs(self._options.noise) > gs.EPS) | ||
| or np.any(np.abs(self._options.random_walk) > gs.EPS) | ||
| or np.any(np.abs(self._options.resolution) > gs.EPS) | ||
| or np.any(np.array(self._options.jitter) > gs.EPS) | ||
| ) | ||
|
Milotrince marked this conversation as resolved.
Comment on lines
+553
to
+562
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm not a huge fan of this branching. I would rather always have measured cache always enabled.
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. let's check how much it affects performance |
||
|
|
||
| @classmethod | ||
| def reset(cls, shared_metadata: NoisySensorMetadataMixin, shared_ground_truth_cache: torch.Tensor, envs_idx): | ||
| super().reset(shared_metadata, shared_ground_truth_cache, envs_idx) | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why adding this helper? I hate one-liner functions.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
sensor classes extend this with super()