Repository navigation
Support external RLinf tasks and explicit episode success #9217
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
base: main
Are you sure you want to change the base?
Changes from 4 commits
7efebee
be4fa68
f59f3a5
ab05430
a3ff0b5
574349b
c27ab1d
99899bb
0c1d527
b46e12a
712c058
ef98405
5ad7349
1ee1a8a
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| * Added device-preserving BHWC crop and resize processing with an explicit output storage ownership contract. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -65,6 +65,56 @@ def is_normals_like(data_type: str) -> bool: | |
| """ | ||
|
|
||
|
|
||
| def crop_and_resize_images( | ||
| image: torch.Tensor, | ||
| height: int | None = None, | ||
| width: int | None = None, | ||
| crop_scale: float = 0.0, | ||
| random_crop: bool = False, | ||
| ) -> torch.Tensor: | ||
| """Crop and bilinearly resize a BHWC image batch on its existing device. | ||
|
|
||
| Args: | ||
| image: Four-dimensional ``(B, H, W, C)`` uint8 or floating-point images. | ||
| height: Output height, or None to retain the input height. | ||
| width: Output width, or None to retain the input width. | ||
| crop_scale: Fraction removed from each spatial dimension, in ``[0, 1)``. | ||
| random_crop: Select independent crop offsets per image instead of a center crop. | ||
|
|
||
| Returns: | ||
| Images with shape ``(B, height, width, C)``, preserving dtype and device. | ||
| A no-op returns the original tensor; a center crop without resizing returns a | ||
| view sharing its storage. Random indexing and resizing allocate new storage. | ||
| Callers that mutate borrowed output must clone it first. | ||
|
|
||
| Raises: | ||
| ValueError: If crop_scale is outside ``[0, 1)``. | ||
| """ | ||
| batch, source_height, source_width, _ = image.shape | ||
| size = (source_height if height is None else height, source_width if width is None else width) | ||
| if crop_scale: | ||
| if not 0 < crop_scale < 1: | ||
| raise ValueError("crop_scale must be in [0, 1).") | ||
| h, w = max(1, int(source_height * (1 - crop_scale))), max(1, int(source_width * (1 - crop_scale))) | ||
| if random_crop: | ||
| tops = torch.randint(source_height - h + 1, (batch, 1), device=image.device) | ||
| lefts = torch.randint(source_width - w + 1, (batch, 1), device=image.device) | ||
| rows = tops + torch.arange(h, device=image.device) | ||
| cols = lefts + torch.arange(w, device=image.device) | ||
| image = image[torch.arange(batch, device=image.device)[:, None, None], rows[:, :, None], cols[:, None, :]] | ||
| else: | ||
| top, left = (source_height - h) // 2, (source_width - w) // 2 | ||
| image = image[:, top : top + h, left : left + w] | ||
| if image.shape[1:3] == size: | ||
| return image | ||
| resized = torch.nn.functional.interpolate( | ||
| image.permute(0, 3, 1, 2).float(), size=size, mode="bilinear", align_corners=False, antialias=True | ||
| ).permute(0, 2, 3, 1) | ||
| if image.dtype == torch.uint8: | ||
| resized = resized.clamp(0, 255) | ||
|
Contributor
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. Maybe here insert a round() could retain fractional part better before to uint8
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. Added rounding before conversion back to uint8, with a regression test covering fractional interpolation values. |
||
| return resized.to(image.dtype) | ||
|
|
||
|
|
||
| def normalize_rgb( | ||
| images: torch.Tensor, | ||
| channel_dim: int = -1, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| * Applied RLinf camera cropping even when the rendered image already matched the requested resize dimensions. | ||
| * Required paired resize dimensions and validated matching GR00T N1.5 train/eval output image sizes and preserved checkpoint metadata when adapting input dimensions. | ||
| * Resolved worker split settings once for observation preprocessing and padded hold actions. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| * Fixed RLinf environment workers to register the selected Isaac Lab task and discover installed | ||
| external tasks in the simulator subprocess. | ||
| * Fixed RLinf success metrics for tasks with separate success and failure terminations when a success observation is configured. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| * Added configurable GPU cropping and resizing of policy camera images with matching GR00T input metadata. |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -17,6 +17,7 @@ | |
| isaaclab: &isaaclab_config # YAML anchor for reuse | ||
| task_description: "..." | ||
| main_images: "front_camera" | ||
| success_observation: {group: "metrics", key: "success"} | ||
| extra_view_images: ["left_wrist_camera", "right_wrist_camera"] | ||
| states: | ||
| - key: "robot_joint_state" | ||
|
|
@@ -30,8 +31,8 @@ | |
| eval: | ||
| isaaclab: *isaaclab_config # Reuse via YAML anchor | ||
|
|
||
| Task IDs are read automatically from ``env.train.init_params.id`` and | ||
| ``env.eval.init_params.id`` in the YAML config. | ||
| The CLI's ``--task`` selects the task ID for all workers. Otherwise the extension uses | ||
| ``env.train.init_params.id`` and ``env.eval.init_params.id`` from the YAML config. | ||
|
|
||
| Usage: | ||
| export RLINF_EXT_MODULE=isaaclab_contrib.rl.rlinf.extension | ||
|
|
@@ -52,6 +53,8 @@ | |
| import yaml | ||
| from rlinf.models.embodiment.gr00t import embodiment_tags | ||
|
|
||
| from isaaclab.utils.images import crop_and_resize_images | ||
|
|
||
| if TYPE_CHECKING: | ||
| import torch | ||
|
|
||
|
|
@@ -192,6 +195,15 @@ def _patch_gr00t_get_model(cfg: dict) -> None: | |
| if not data_config_class or model_type == "gr00t_n1d7": | ||
| return | ||
|
|
||
| evaluation_cfg = {**cfg, **_load_full_cfg().get("env", {}).get("eval", {}).get("isaaclab", {})} | ||
|
Contributor
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. This ValueError may could never be thrown out. See RLinf/scheduler/cluster/utils.py:90-110, where RLinf will catch the Exception and show another info at terminal.
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. Good point. Both train and play now validate the merged image configuration on the driver before launching workers, so configuration errors are reported directly. |
||
| resize_keys = ("gpu_resize_width", "gpu_resize_height") | ||
| for split, options in (("train", cfg), ("eval", evaluation_cfg)): | ||
| if (options.get("gpu_resize_width") is None) != (options.get("gpu_resize_height") is None): | ||
| raise ValueError( | ||
| f"GR00T N1.5 requires both gpu_resize_width and gpu_resize_height in {split}. " | ||
| "A missing dimension would depend on the camera resolution, which may differ from checkpoint metadata." | ||
| ) | ||
|
|
||
| import rlinf.models.embodiment.gr00t as rlinf_gr00t_mod | ||
|
|
||
| def patched_get_model(model_cfg, torch_dtype=None) -> object: | ||
|
|
@@ -255,6 +267,26 @@ def patched_get_model(model_cfg, torch_dtype=None) -> object: | |
| rl_head_config=model_cfg.rl_head_config, | ||
| ) | ||
|
|
||
| if any(options.get(key) is not None for options in (cfg, evaluation_cfg) for key in resize_keys): | ||
| # GR00T validates incoming video against the recording metadata. The env worker has already resized RGB. | ||
| input_metadata = model.metadata.model_copy(deep=True) | ||
| for video in input_metadata.modalities.video.values(): | ||
| training_size = tuple( | ||
| original if cfg.get(key) is None else cfg[key] | ||
| for key, original in zip(resize_keys, video.resolution) | ||
| ) | ||
| evaluation_size = tuple( | ||
| original if evaluation_cfg.get(key) is None else evaluation_cfg[key] | ||
| for key, original in zip(resize_keys, video.resolution) | ||
| ) | ||
| if training_size != evaluation_size: | ||
| raise ValueError( | ||
| "GR00T N1.5 requires matching train/eval image sizes after GPU resizing " | ||
| f"(width, height): train={training_size}, eval={evaluation_size}." | ||
| ) | ||
| video.resolution = training_size | ||
| modality_transform.set_metadata(input_metadata) | ||
|
|
||
| if rl_model_path: | ||
| rl_weights = Path(rl_model_path) / "actor" / "model_state_dict" / "full_weights.pt" | ||
| if not rl_weights.exists(): | ||
|
|
@@ -395,17 +427,16 @@ def _convert_gr00t_to_isaaclab_action(action_chunk: dict, chunk_size: int = 1) - | |
| def _register_isaaclab_envs() -> None: | ||
| """Register IsaacLab tasks into RLinf's REGISTER_ISAACLAB_ENVS map. | ||
|
|
||
| Task IDs are read from ``env.train.init_params.id`` and | ||
| ``env.eval.init_params.id`` in the YAML config. | ||
| Register the task selected by the launcher or the train and eval IDs from the YAML config. | ||
| """ | ||
| from rlinf.envs.isaaclab import REGISTER_ISAACLAB_ENVS | ||
|
|
||
| # Collect unique task IDs from the YAML config (train + eval) | ||
| full_cfg = _load_full_cfg() | ||
| env_cfg = full_cfg.get("env", {}) | ||
| task_override = os.environ.get("ISAACLAB_RLINF_TASK") | ||
| task_ids: list[str] = [] | ||
| for section in ("train", "eval"): | ||
| tid = env_cfg.get(section, {}).get("init_params", {}).get("id", "") | ||
| tid = task_override or env_cfg.get(section, {}).get("init_params", {}).get("id", "") | ||
| if tid and tid not in task_ids: | ||
| task_ids.append(tid) | ||
|
|
||
|
|
@@ -463,21 +494,32 @@ def __init__(self, cfg, num_envs: int, seed_offset: int, total_num_processes: in | |
| total_num_processes: Total number of worker processes. | ||
| worker_info: RLinf worker metadata. | ||
| """ | ||
| self._isaaclab_cfg = {**_get_isaaclab_cfg(), **(cfg.get("isaaclab", {}) if cfg is not None else {})} | ||
| self._image_options = { | ||
| "height": self._isaaclab_cfg.get("gpu_resize_height"), | ||
| "width": self._isaaclab_cfg.get("gpu_resize_width"), | ||
| "crop_scale": self._isaaclab_cfg.get("gpu_crop_scale", 0.0), | ||
| "random_crop": self._isaaclab_cfg.get("gpu_crop_random", False), | ||
| } | ||
| super().__init__(cfg, num_envs, seed_offset, total_num_processes, worker_info) | ||
|
|
||
| self._hold_pose_on_midchunk_reset = _get_isaaclab_cfg().get("hold_pose_on_midchunk_reset", False) | ||
| self._hold_pose_on_midchunk_reset = self._isaaclab_cfg.get("hold_pose_on_midchunk_reset", False) | ||
| self._chunk_done = None | ||
| self._hold_actions = None | ||
| self._success_observation = None | ||
|
|
||
| def _record_metrics(self, step_reward, terminations, infos): | ||
| """Override to use terminations (task completion) for success_once.""" | ||
| """Record configured success signals, falling back to task termination for existing recipes.""" | ||
|
|
||
| # RLinf may suppress terminations after this callback; Isaac Lab has already reset. | ||
| if self._chunk_done is not None: | ||
| self._chunk_done |= terminations | ||
| episode_info = {} | ||
| self.returns += step_reward | ||
| self.success_once = self.success_once | terminations.bool() | ||
| success = terminations.bool() | ||
| if self._success_observation is not None: | ||
| success = success & self._success_observation | ||
| self.success_once = self.success_once | success | ||
| episode_info["success_once"] = self.success_once.clone() | ||
| episode_info["return"] = self.returns.clone() | ||
| episode_info["episode_len"] = self.elapsed_steps.clone() | ||
|
|
@@ -497,7 +539,11 @@ def chunk_step(self, chunk_actions): | |
| def step(self, actions=None, auto_reset=True): | ||
| """Hold reset joints until the next chunk supplies actions for the new episode.""" | ||
| if self._chunk_done is not None and self._hold_actions is not None: | ||
| actions = torch.where(self._chunk_done[:, None], self._hold_actions.to(actions), actions) | ||
| hold = self._hold_actions.to(actions) | ||
| if hold.shape[-1] != actions.shape[-1]: | ||
| mapping = self._isaaclab_cfg.get("action_mapping", {}) | ||
| hold = torch.nn.functional.pad(hold, (mapping.get("prefix_pad", 0), mapping.get("suffix_pad", 0))) | ||
| actions = torch.where(self._chunk_done[:, None].to(actions.device), hold, actions) | ||
| obs, reward, terminated, truncated, info = super().step(actions, auto_reset) | ||
| if self._chunk_done is not None: | ||
| self._chunk_done |= truncated | ||
|
|
@@ -526,9 +572,12 @@ def make_env_isaaclab() -> tuple: | |
| import gymnasium as gym | ||
|
|
||
| from isaaclab.app import launch_simulation | ||
| from isaaclab.cli import load_external_tasks | ||
|
|
||
| from isaaclab_tasks.utils import parse_env_cfg | ||
|
Contributor
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. move "import" to the beginning
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. Moved the Gym, app, and CLI imports to module scope. Task imports remain inside the simulator subprocess to avoid registering tasks in actor and rollout workers. |
||
|
|
||
| # The spawned simulator has its own Gym registry, separate from the CLI's. | ||
| load_external_tasks() | ||
| isaac_env_cfg = parse_env_cfg( | ||
| self.isaaclab_env_id, | ||
| num_envs=self.cfg.init_params.num_envs, | ||
|
|
@@ -554,7 +603,7 @@ def _wrap_obs(self, obs: dict) -> dict: | |
| - ``"extra_view_images"``: ``(B, N, H, W, C)`` — stacked extra cameras. | ||
| - ``"states"``: ``(B, D)`` — concatenated state vector. | ||
| - ``"task_descriptions"``: ``list[str]`` — task descriptions. | ||
| Config is read from the YAML file via :func:`_get_isaaclab_cfg`. | ||
| Split configuration is resolved once when the worker is initialized. | ||
|
|
||
| Args: | ||
| obs: Raw observation dictionary from the IsaacLab environment. | ||
|
|
@@ -567,7 +616,15 @@ def _wrap_obs(self, obs: dict) -> dict: | |
| policy_obs = obs.get("policy", obs) | ||
| camera_obs = obs.get("camera_images", {}) | ||
|
|
||
| cfg = _get_isaaclab_cfg() | ||
| cfg = self._isaaclab_cfg | ||
| success_cfg = cfg.get("success_observation") | ||
| self._success_observation = ( | ||
|
Contributor
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. This observation is the first obs of one new episode after reset returned by step(), not the final obs.
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. You're right. Success metrics now read the pre-reset final_obs, rather than the returned observation. They also preserve the completed episode’s outcome across the remaining chunk steps. |
||
| torch.as_tensor(obs[success_cfg["group"]][success_cfg["key"]], device=self.device, dtype=torch.bool) | ||
| .reshape(self.num_envs) | ||
| .clone() | ||
| if success_cfg | ||
| else None | ||
| ) | ||
| # Get task description from config | ||
| task_desc = cfg.get("task_description", "") or self.task_description | ||
| rlinf_obs = { | ||
|
|
@@ -581,14 +638,16 @@ def _wrap_obs(self, obs: dict) -> dict: | |
| # main_images: single camera key -> (B, H, W, C) | ||
| main_key = cfg.get("main_images") | ||
| if main_key and main_key in camera_obs: | ||
| rlinf_obs["main_images"] = camera_obs[main_key] | ||
| rlinf_obs["main_images"] = crop_and_resize_images(camera_obs[main_key], **self._image_options) | ||
|
|
||
| # extra_view_images: camera key(s) -> stack to (B, N, H, W, C) | ||
| extra_keys = cfg.get("extra_view_images") | ||
| if extra_keys: | ||
| if isinstance(extra_keys, str): | ||
| extra_keys = [extra_keys] | ||
| extra_imgs = [camera_obs[k] for k in extra_keys if k in camera_obs] | ||
| extra_imgs = [ | ||
| crop_and_resize_images(camera_obs[k], **self._image_options) for k in extra_keys if k in camera_obs | ||
| ] | ||
| if extra_imgs: | ||
| rlinf_obs["extra_view_images"] = torch.stack(extra_imgs, dim=1) | ||
|
|
||
|
|
@@ -602,7 +661,7 @@ def _wrap_obs(self, obs: dict) -> dict: | |
| state = policy_obs.get(spec) | ||
| if state is not None: | ||
| state_parts.append(state) | ||
| elif isinstance(spec, dict): | ||
| elif isinstance(spec, collections.abc.Mapping): | ||
| state = policy_obs.get(spec.get("key")) | ||
| if state is not None: | ||
| slice_range = spec.get("slice") | ||
|
|
@@ -625,7 +684,7 @@ def add_image(self, obs: dict) -> np.ndarray | None: | |
| ``None`` if no camera image is available. | ||
| """ | ||
| camera_obs = obs.get("camera_images", {}) | ||
| cfg = _get_isaaclab_cfg() | ||
| cfg = self._isaaclab_cfg | ||
| # Try main_images key, fallback to first available camera | ||
| main_key = cfg.get("main_images") | ||
| if main_key and main_key in camera_obs: | ||
|
|
||
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.
Could this function be moved to external downsteam projects? because it is for visual data augmentation while isaaclab internal functions perfer to provide pre-processing such as normalization.
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.
Thanks, I moved crop augmentation to the task observation processor and removed the crop options from the RLinf adapter. The shared helper now only handles resizing.
Uh oh!
There was an error while loading. Please reload this page.
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.
This function is implemented here rather than building in GR00T where it transfers data between GPU and CPU for such function, in order to save time. But it looks different from others in this .py, I am not sure whether it should be here. @ooctipus