Skip to content
Open
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
53 changes: 53 additions & 0 deletions docs/source/experimental-features/rlinf_vla_posttraining.rst
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,59 @@ Do not set this aarch64 path on x86_64 Linux. If it was inherited from a
previous setup, run ``unset LD_PRELOAD`` before launching Isaac Lab.


External task recipes and policy inputs
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The CLI's ``--task`` overrides the task IDs in the recipe for both training and
validation workers. Without it, each split retains its own task ID. Simulator
subprocesses discover installed tasks through the ``isaaclab.tasks`` entry-point
group, so downstream tasks do not need to be copied into Isaac Lab.

Camera preprocessing is configured under each split's ``isaaclab`` section with
``gpu_resize_height``, ``gpu_resize_width``, ``gpu_crop_scale`` and
``gpu_crop_random``. Cropping runs before resizing on the image device, for both
main and extra camera views. The default crop scale is zero. GR00T N1.5 requires
the final train/eval image dimensions to match; incompatible dimensions raise an
error when loading the policy. Random training crops and center evaluation crops
may still differ while producing the same output dimensions.

A training recipe may set ``runner.isaaclab_context`` to a ``module:callable``
string to manage optional services around worker initialization and training:

.. code-block:: yaml

runner:
isaaclab_context: my_demo.training:service_context

The callable receives the RLinf runner and CLI environment overrides and returns
a context manager. Its cleanup runs after training, including on an exception.
Recipes without this setting run as before. Keep service-specific behavior in the
downstream task; the context is training configuration and is not passed to Gym
environment constructors.


Episode success metrics
~~~~~~~~~~~~~~~~~~~~~~~

For tasks with both success and failure terminations, configure an explicit Boolean
success observation under each split's ``isaaclab`` section:

.. code-block:: yaml

success_observation:
group: metrics
key: success

The adapter records success only when this observation is true on a terminated step.
The task must expose the completed episode's outcome on that step, including when the
simulator resets automatically. Without this setting, existing recipes continue to
count task terminations as success. Timeouts alone do not count as success.

Train and evaluation retain their own ``init_params.env_overrides`` from the recipe.
Command-line environment overrides replace recipe entries with the same key before
being appended, including preset selectors such as ``physics`` and ``renderer``.


Quick Start
-----------

Expand Down
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.
Empty file.
50 changes: 50 additions & 0 deletions source/isaaclab/isaaclab/utils/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
return resized.to(image.dtype)


def normalize_rgb(
images: torch.Tensor,
channel_dim: int = -1,
Expand Down
16 changes: 16 additions & 0 deletions source/isaaclab/test/utils/test_images.py
Original file line number Diff line number Diff line change
Expand Up @@ -339,3 +339,19 @@ def test_single_batch_produces_channel_first_grid(self, device):
images = torch.ones((1, 2, 3, 3), device=device)
grid = make_camera_output_grid(images)
assert grid.shape == (3, 2, 3)


def test_crop_resize_preserves_dtype_device_and_storage_ownership() -> None:
"""No-op and center-only crops borrow input storage; a resize owns its output."""
image = torch.arange(16, dtype=torch.uint8).reshape(1, 4, 4, 1)
assert images_utils.crop_and_resize_images(image) is image
cropped = images_utils.crop_and_resize_images(image, height=2, width=2, crop_scale=0.5)
assert cropped.tolist() == [[[[5], [6]], [[9], [10]]]]
cropped[0, 0, 0, 0] = 99
assert image[0, 1, 1, 0].item() == 99
resized = images_utils.crop_and_resize_images(image, height=2, width=3)
assert resized.shape == (1, 2, 3, 1)
assert resized.dtype == image.dtype and resized.device == image.device
original = image.clone()
resized.zero_()
torch.testing.assert_close(image, original)
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.
* 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.
Empty file.
84 changes: 68 additions & 16 deletions source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -255,6 +258,28 @@ def patched_get_model(model_cfg, torch_dtype=None) -> object:
rl_head_config=model_cfg.rl_head_config,
)

evaluation_cfg = {**cfg, **_load_full_cfg().get("env", {}).get("eval", {}).get("isaaclab", {})}
resize_keys = ("gpu_resize_width", "gpu_resize_height")
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():
Expand Down Expand Up @@ -395,17 +420,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)

Expand Down Expand Up @@ -463,21 +487,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()
Expand All @@ -497,7 +532,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
Expand Down Expand Up @@ -526,9 +565,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

# 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,
Expand All @@ -554,7 +596,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.
Expand All @@ -567,7 +609,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 = (
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 = {
Expand All @@ -581,14 +631,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)

Expand All @@ -602,7 +654,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")
Expand All @@ -625,7 +677,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:
Expand Down
Loading