Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
41 changes: 41 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,47 @@ 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.

An external task may register ``rlinf_runner_context`` in its Gym specification
kwargs as a ``module:callable`` string. The callable receives the RLinf runner
and CLI environment overrides and returns a context manager around worker
initialization and training. Tasks without this entry run as before. Keep
service-specific behavior in the downstream task.


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 are appended, so they take precedence on matching fields.


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

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* Applied RLinf camera cropping even when the rendered image already matched the requested resize dimensions.
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.
81 changes: 68 additions & 13 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 Down Expand Up @@ -255,6 +256,14 @@ def patched_get_model(model_cfg, torch_dtype=None) -> object:
rl_head_config=model_cfg.rl_head_config,
)

if "gpu_resize_width" in cfg or "gpu_resize_height" in cfg:

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.

🔴 Critical · Implementation — Match metadata to evaluation images

Model metadata uses training resize settings, while evaluation workers apply their own settings. Different dimensions fail GR00T video validation; derive metadata from the consuming split or reject incompatible split dimensions.

# 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():
width, height = video.resolution
video.resolution = (cfg.get("gpu_resize_width", width), cfg.get("gpu_resize_height", height))
modality_transform.set_metadata(input_metadata)

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.

P2 Metadata changes lack direct tests

No test calls the patched loader to exercise this metadata update. Existing tests only check whether the loader was replaced and separately check camera pixels. Swapped dimensions or changes to the wrong metadata object could pass all those tests.

Add a loader test with non-square resize dimensions. Check the metadata passed to set_metadata, verify the original metadata stays unchanged, and cover setting only one dimension.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!


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 +404,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 All @@ -428,6 +436,34 @@ def _register_isaaclab_envs() -> None:
logger.debug(f"REGISTER_ISAACLAB_ENVS now contains: {list(REGISTER_ISAACLAB_ENVS.keys())}")


def _prepare_camera_image(image: torch.Tensor, cfg: dict) -> torch.Tensor:

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 · Design Architecture — Move image processing to utils.images

The contribution guide assigns image processing to utils.images. This generic crop/resize helper creates a second owner in the RLinf adapter; move the transformation there and keep configuration translation here.

"""Crop a batch of RGB frames and resize to the policy input dimensions on the image device."""

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 camera tensor ownership

The helper requires BHWC input and can return the original tensor, a view, or a new tensor. Document shapes, dtype preservation, and aliasing so callers know whether the result owns storage.

batch, height, width, _ = image.shape
size = (cfg.get("gpu_resize_height", height), cfg.get("gpu_resize_width", width))
fraction = cfg.get("gpu_crop_scale", 0.0)
if fraction:
if not 0 < fraction < 1:
raise ValueError("gpu_crop_scale must be in [0, 1).")
h, w = max(1, int(height * (1 - fraction))), max(1, int(width * (1 - fraction)))
if cfg.get("gpu_crop_random", False):
tops = torch.randint(height - h + 1, (batch, 1), device=image.device)
lefts = torch.randint(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 = (height - h) // 2, (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 _create_generic_env_wrapper(task_id: str) -> type:
"""Create a generic wrapper class for an IsaacLab task.

Expand Down Expand Up @@ -468,16 +504,20 @@ def __init__(self, cfg, num_envs: int, seed_offset: int, total_num_processes: in
self._hold_pose_on_midchunk_reset = _get_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 +537,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 = _get_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 +570,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

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.

move "import" to the beginning

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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,
Expand Down Expand Up @@ -567,7 +614,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 = {**_get_isaaclab_cfg(), **self.cfg.get("isaaclab", {})}

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 · Scope Complexity — Resolve split settings once

Every observation allocates and merges the same configuration dictionary. Resolve fixed split settings during worker initialization and reuse them for observations and held-action padding.

success_cfg = cfg.get("success_observation")
self._success_observation = (

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.

This observation is the first obs of one new episode after reset returned by step(), not the final obs.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The 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 = {
Expand All @@ -581,14 +636,14 @@ 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"] = _prepare_camera_image(camera_obs[main_key], cfg)

# 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 = [_prepare_camera_image(camera_obs[k], cfg) 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 +657,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 Down
104 changes: 94 additions & 10 deletions source/isaaclab_contrib/test/rl/test_rlinf_extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,11 @@ def __init__(self, cfg, num_envs, seed_offset, total_num_processes, worker_info)


@pytest.fixture(autouse=True)
def _reset_extension_state():
def _reset_extension_state(monkeypatch):
"""Reset extension module-level caches before each test."""
ext._registered = False
ext._full_cfg_cache = None
monkeypatch.delenv("ISAACLAB_RLINF_TASK", raising=False)
# Reset mock registries
sim_io = _rlinf_mocks["rlinf.models.embodiment.gr00t.simulation_io"]
sim_io.OBS_CONVERSION.clear()
Expand Down Expand Up @@ -245,9 +246,71 @@ def test_get_isaaclab_cfg_missing_section(self, yaml_config_file: str) -> None:
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("explicit_success", [True, False], ids=["success-observation", "legacy-termination"])
def test_episode_success_distinguishes_failure_and_timeout(explicit_success, set_config_env):

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 — Annotate the test return

This new test omits the required -> None return annotation used by neighboring tests. Add it.

"""A failure termination is not a win when the recipe supplies an explicit success observation."""
from omegaconf import OmegaConf

options = {"success_observation": {"group": "metrics", "key": "success"}} if explicit_success else {}
worker = ext._create_generic_env_wrapper("test")(OmegaConf.create({"isaaclab": options}), 3, 0, 1, None)
worker.returns = torch.zeros(3)
worker.success_once = torch.zeros(3, dtype=torch.bool)
worker.elapsed_steps = torch.ones(3)
worker._chunk_done = torch.zeros(3, dtype=torch.bool)
success = torch.tensor([[True], [False], [True]])
worker._wrap_obs({"metrics": {"success": success}})
# Observation storage can be reused after wrapping; the recorded outcome must retain its value.
success.zero_()
info = worker._record_metrics(torch.tensor([2.0, -1.0, 0.0]), torch.tensor([True, True, False]), {})
assert info["episode"]["success_once"].tolist() == [True, not explicit_success, False]
assert worker._chunk_done.tolist() == [True, True, False]
worker._wrap_obs({"metrics": {"success": success}})
info = worker._record_metrics(torch.ones(3), torch.zeros(3, dtype=torch.bool), {})
assert info["episode"]["success_once"].tolist() == [True, not explicit_success, False]
torch.testing.assert_close(info["episode"]["return"], torch.tensor([3.0, 0.0, 1.0]))


class TestObsConversion:
"""Tests for ``_convert_isaaclab_obs_to_gr00t``."""

def test_camera_crop_applies_when_resize_matches_input(self, set_config_env) -> None:

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 — Correct the test class description

The new tests exercise worker _wrap_obs, but the enclosing class says it tests _convert_isaaclab_obs_to_gr00t. Broaden the description or move these tests.

from omegaconf import OmegaConf

options = {
"main_images": "head",
"extra_view_images": [],
"gpu_resize_height": 4,
"gpu_resize_width": 4,
"gpu_crop_scale": 0.5,
"gpu_crop_random": False,
}
worker = ext._create_generic_env_wrapper("test")(OmegaConf.create({"isaaclab": options}), 1, 0, 1, None)
image = torch.arange(16, dtype=torch.uint8).reshape(1, 4, 4, 1).expand(-1, -1, -1, 3)
result = worker._wrap_obs({"camera_images": {"head": image}})["main_images"]
assert result.shape == image.shape
assert result[0, [0, 0, 3, 3], [0, 3, 0, 3], 0].tolist() == [5, 6, 9, 10]

def test_policy_camera_crop_uses_evaluation_options_for_all_views(self, set_config_env) -> None:
from omegaconf import OmegaConf

options = {
"states": [{"key": "joints", "slice": [1, 3]}],
"main_images": "head",
"extra_view_images": ["wrist"],
"gpu_resize_height": 2,
"gpu_resize_width": 3,
"gpu_crop_scale": 0.5,
"gpu_crop_random": False,
}
worker = ext._create_generic_env_wrapper("test")(OmegaConf.create({"isaaclab": options}), 2, 0, 1, None)
head = torch.arange(2 * 4 * 6 * 3, dtype=torch.uint8).reshape(2, 4, 6, 3)
wrist = head.flip((2,))
joints = torch.arange(8).reshape(2, 4)
obs = worker._wrap_obs({"policy": {"joints": joints}, "camera_images": {"head": head, "wrist": wrist}})
torch.testing.assert_close(obs["states"], joints[:, 1:3])
torch.testing.assert_close(obs["main_images"], head[:, 1:3, 1:4])
torch.testing.assert_close(obs["extra_view_images"], wrist[:, None, 1:3, 1:4])

def test_extra_view_images_conversion(self, set_config_env) -> None:
"""Extra view images should be split into separate GR00T video keys."""
ext._load_full_cfg()
Expand Down Expand Up @@ -393,14 +456,16 @@ def test_default_tag_values(self) -> None:
class TestTaskRegistration:
"""Tests for ``_register_isaaclab_envs``."""

def test_tasks_registered_from_yaml(self, set_config_env) -> None:
"""Task IDs from train and eval sections should be registered."""
@pytest.mark.parametrize("override", [None, "Isaac-Test-Cosmos-v0"])
def test_tasks_registered_for_worker(self, set_config_env, monkeypatch, override) -> None:
"""The worker can select the CLI task or the distinct train and eval tasks in the recipe."""
if override:
monkeypatch.setenv("ISAACLAB_RLINF_TASK", override)
ext._load_full_cfg()
ext._register_isaaclab_envs()

registry = _rlinf_mocks["rlinf.envs.isaaclab"].REGISTER_ISAACLAB_ENVS
assert "Isaac-Test-Task-v0" in registry
assert "Isaac-Test-Task-Eval-v0" in registry
assert set(registry) == ({override} if override else {"Isaac-Test-Task-v0", "Isaac-Test-Task-Eval-v0"})
base = _rlinf_mocks["rlinf.envs.isaaclab.isaaclab_env"].IsaaclabBaseEnv
for env_cls in registry.values():
assert issubclass(env_cls, base)
Expand Down Expand Up @@ -431,11 +496,28 @@ def test_empty_config_no_registration(self, yaml_config_file: str) -> None:
# ---------------------------------------------------------------------------


@pytest.mark.parametrize("hold_pose,device", [(False, "cpu"), *((True, device) for device in test_devices())])
def test_midchunk_reset_does_not_replay_old_episode_actions(monkeypatch, hold_pose, device):
@pytest.mark.parametrize(
"hold_pose,device,prefix_pad,suffix_pad",
[
(False, "cpu", 0, 0),
*((True, device, prefix, suffix) for device in test_devices() for prefix, suffix in ((0, 0), (2, 1))),

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 · Test Quality — Avoid crossing padding with devices

Padding adds no device-specific adapter branch, while existing unpadded rows cover device transfers. Keep one padded row rather than repeating it on every device.

],
)
def test_midchunk_reset_does_not_replay_old_episode_actions(monkeypatch, hold_pose, device, prefix_pad, suffix_pad):
"""Only reset worlds hold their returned joint positions, until the next chunk."""
monkeypatch.setattr(
ext, "_full_cfg_cache", {"env": {"train": {"isaaclab": {"hold_pose_on_midchunk_reset": hold_pose}}}}
ext,
"_full_cfg_cache",
{
"env": {
"train": {
"isaaclab": {
"hold_pose_on_midchunk_reset": hold_pose,
"action_mapping": {"prefix_pad": prefix_pad, "suffix_pad": suffix_pad},
}
}
}
},
)
base = _rlinf_mocks["rlinf.envs.isaaclab.isaaclab_env"].IsaaclabBaseEnv
states = torch.tensor([[0.2, 0.3], [0.4, 0.5]], device=device)
Expand All @@ -457,11 +539,13 @@ def chunk_step(self, actions):
monkeypatch.setattr(base, "chunk_step", chunk_step, raising=False)
env = ext._create_generic_env_wrapper("test")(None, 2, 0, 1, None)
env.device = device
actions = torch.ones(2, 2) # The RLinf env worker receives action chunks on the CPU.
actions = torch.ones(2, prefix_pad + 2 + suffix_pad) # RLinf receives padded action chunks on the CPU.
env.chunk_step(torch.stack([actions, actions * 2], dim=1))
expected = (actions * 2).to(device)
if hold_pose:
expected[0] = states[0]
expected[0] = torch.cat(
(torch.zeros(prefix_pad, device=device), states[0], torch.zeros(suffix_pad, device=device))
)
torch.testing.assert_close(step.call_args.args[0], expected)
env.step(actions * 3)
torch.testing.assert_close(step.call_args.args[0], actions * 3)
Expand Down
Loading