Skip to content

Support external RLinf tasks and explicit episode success - #9217

Open
KumoLiu wants to merge 2 commits into
isaac-sim:mainfrom
KumoLiu:yunl/feat/rlinf-external-demos
Open

KumoLiu wants to merge 2 commits into
isaac-sim:mainfrom
KumoLiu:yunl/feat/rlinf-external-demos

Conversation

@KumoLiu

@KumoLiu KumoLiu commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Support installed external tasks in RLinf training and playback while keeping task and service implementations downstream. These shared changes are separate from #9148 and do not require its Trocar assets or task update.

  • Register external tasks in simulator workers and consistently forward task selection, retaining distinct train/eval IDs when no CLI override is supplied.
  • Preserve split-specific settings while replacing recipe keys overridden by the CLI, including physics/renderer preset selectors.
  • Support explicit success observations for tasks with both success and failure terminations; retain legacy metrics when unset.
  • Crop and resize images on their existing device through isaaclab.utils.images, with worker split settings resolved once. Document dtype, layout and output storage ownership.
  • Validate matching GR00T N1.5 train/eval output sizes and adapt a metadata copy without mutating checkpoint metadata.
  • Support optional task-provided runner contexts around worker initialization and training, and padded hold actions after mid-chunk resets.

Consumers: medical-pad GR00T/GRPO demo and Trocar Cosmos demo. Only the latter also requires the task changes in #9148.

Validation

  • RLinf adapter: 37 passed; entrypoints: 59 passed; image utilities: 54 passed.
  • Medical-pad integration/configuration/action codec: 17 passed against this standalone branch.
  • Trocar demo: 11 passed against the combined Lab snapshot; the explicit-RTX configuration regression also passed.
  • Confirmed the CLI regression failed before the fix. Removing the size guard or restoring global action-padding settings makes the corresponding regression fail.
  • Full isaaclab --format checks, including changelog validation, passed.

GPU image-preprocessing measurement

Baseline: 7efebee54. Candidate: be4fa6814.

NVIDIA A100 80 GB PCIe, PyTorch 2.11.0+cu130, GPU 0. Each observation processes 32 environments × 3 uint8 BHWC camera views, 320×240 → 224×224 with a 5% crop, bilinear antialiasing and extra-view stacking. Each case uses 50 warmups and 250 measured observations in interleaved baseline/candidate batches. Outputs match bit for bit for center and seeded random crops.

Processing Baseline ms/observation Candidate ms/observation
Center crop 0.968 0.957
Random crop 1.513 1.511

These are mean wall times per observation, synchronized at batch boundaries. A stand-in environment isolates the real _wrap_obs implementation; rendering, IPC and model inference are excluded. The small differences do not establish an end-to-end training speedup.

Reproduce the preprocessing measurement

Run from the candidate checkout in an environment with Isaac Lab core dependencies installed. The baseline commit must be available locally. The stand-in supplies only the environment base; the benchmark extracts each revision's actual adapter methods.

CUDA_VISIBLE_DEVICES=0 PYTHONPATH="$PWD/source/isaaclab" uv run --no-sync python - <<'PY'
import ast
import collections.abc
import json
import logging
import statistics
import subprocess
import sys
import time
import types
from pathlib import Path

import numpy as np
import torch
from isaaclab.utils.images import crop_and_resize_images

root = Path.cwd()
path = 'source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/extension.py'
baseline = '7efebee5458484c29f7800114c5a0516d5f624b0'
source = subprocess.check_output(['git', 'show', baseline + ':' + path], cwd=root, text=True)

class Base:
    def __init__(self, cfg, num_envs, *args):
        self.cfg, self.num_envs = cfg, num_envs
        self.device, self.task_description = 'cuda:0', ''

module = types.ModuleType('rlinf.envs.isaaclab.isaaclab_env')
module.IsaaclabBaseEnv = Base
sys.modules[module.__name__] = module

def worker(code, cfg):
    tree = ast.parse(code)
    functions = [ast.get_source_segment(code, node) for node in tree.body if isinstance(node, ast.FunctionDef) and node.name in ('_prepare_camera_image', '_create_generic_env_wrapper')]
    scope = dict(torch=torch, np=np, collections=collections, logger=logging.getLogger('benchmark'), _get_isaaclab_cfg=lambda: cfg, crop_and_resize_images=crop_and_resize_images)
    exec('\n\n'.join(functions), scope)
    return scope['_create_generic_env_wrapper']('benchmark')({'isaaclab': cfg}, 32, 0, 1, None)

cfg = dict(main_images='head', extra_view_images=['left', 'right'], states=[dict(key='joints')], gpu_resize_height=224, gpu_resize_width=224, gpu_crop_scale=0.05)
obs = dict(camera_images={key: torch.randint(256, (32, 240, 320, 3), dtype=torch.uint8, device='cuda:0') for key in ('head', 'left', 'right')}, policy=dict(joints=torch.zeros(32, 29, device='cuda:0')))
results = []
with torch.inference_mode():
    for random in (False, True):
        cfg = {**cfg, 'gpu_crop_random': random}
        workers = dict(baseline=worker(source, cfg), candidate=worker((root/path).read_text(), cfg))
        torch.cuda.manual_seed_all(13)
        before = workers['baseline']._wrap_obs(obs)
        torch.cuda.manual_seed_all(13)
        after = workers['candidate']._wrap_obs(obs)
        for key in ('main_images', 'extra_view_images', 'states'):
            assert torch.equal(before[key], after[key]), key
        for w in workers.values():
            for _ in range(50): w._wrap_obs(obs)
        torch.cuda.synchronize()
        samples = {name: [] for name in workers}
        for repeat in range(10):
            names = list(workers) if repeat % 2 == 0 else list(reversed(workers))
            for name in names:
                torch.cuda.synchronize()
                start = time.perf_counter()
                for _ in range(25): workers[name]._wrap_obs(obs)
                torch.cuda.synchronize()
                samples[name].append((time.perf_counter()-start)*1000/25)
        results.append(dict(mode='random-crop' if random else 'center-crop', **{name: dict(mean_ms=statistics.mean(times), min_ms=min(times), max_ms=max(times)) for name,times in samples.items()}))
report = dict(baseline=baseline, candidate=subprocess.check_output(['git','rev-parse','HEAD'],cwd=root,text=True).strip(), gpu=torch.cuda.get_device_name(0), torch=torch.__version__, backend='PyTorch CUDA bilinear antialias; stand-in environment, no renderer/model inference', num_envs=32, cameras=3, input_bhwc=[32,240,320,3], output_hw=[224,224], dtype='uint8', crop_scale=.05, warmup_per_case=50, measured_observations_per_case=250, interleaved_batches=True, bit_exact_gpu_outputs=True, latency_includes='worker _wrap_obs, image processing, extra-view stacking and CUDA synchronization at batch boundaries; excludes rendering, IPC and policy inference', results=results)
print(json.dumps(report,indent=2))
PY

Remaining review item

The rlinf_runner_context constructor-keyword compatibility concern remains open for separate review; this update leaves that registration mechanism unchanged.

Type of change

  • Bug fix
  • New feature
  • Documentation update

@KumoLiu
KumoLiu requested a review from a team November 25, 2026 14:28
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Nov 25, 2026

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

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.

Isaac Lab Review Bot

Needs attention: Design and architecture (1), Scope and over-engineering (1), Compatibility and deprecation (1), Implementation (1), Style consistency (3), Test quality (1). Other reviewed categories look good.

  • PR description: Title and scope match; retain reported validation, remove test-edit narration, and benchmark per-observation camera processing with baseline/candidate revisions, command, hardware, backend, environment count, warmup, and latency.
  • Design and architecture: Generic crop/resize processing violates the contribution guide’s utils.images ownership rule; move the transformation there and retain RLinf configuration translation in the adapter.
  • Scope and over-engineering: Minimal implementation: Extend train_rlinf.py for context lifecycle, cli_args_rlinf.py for forwarding, play_rlinf.py for evaluation, and extension.py for worker adaptation; resolve split configuration once and move generic image processing to utils.images, eliminating per-observation dictionary merges. No source modules were added, and no parallel layer is required. Scope is cohesive; no split recommended.
  • API: API changes look good.
  • Compatibility and deprecation: Breaking changes: registering rlinf_runner_context adds a constructor keyword that existing task environments may reject; keep the hook outside Gym constructor kwargs or strip it before construction.
  • Implementation: GR00T metadata uses training resize dimensions while evaluation images use split-specific dimensions, causing validation failures; derive metadata from the consuming split or reject incompatible dimensions.
  • Style consistency: The camera helper omits its BHWC, dtype, and storage-aliasing contract; document these constraints so callers can distinguish borrowed storage from newly allocated output.
  • Test quality: Camera and entrypoint cases protect distinct boundaries, but crossing padding with every device repeats adapter behavior already covered by transfer tests; retain one padded case.

Significant concerns. Posted 8 inline findings.

Automated review; human maintainers own approval decisions.

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.

runner.run()
spec = registry.get(task_id)
context = nullcontext()
if spec and (entry_point := spec.kwargs.get("rlinf_runner_context")):

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 · Compatibility — Keep context out of constructor kwargs

Gym forwards specification kwargs to gym.make, so a registered rlinf_runner_context reaches task constructors that do not accept it. Store the hook separately or remove it before environment construction.

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.



def _prepare_camera_image(image: torch.Tensor, cfg: dict) -> torch.Tensor:
"""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.

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.



@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.

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.

"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.

@greptile-apps

greptile-apps Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect RLinf task setup and policy inputs across training and playback workflows.

Fix conflicting preset overrides before merging; a CLI physics change can currently stop training or playback.

Findings

  1. P1 CLI physics overrides fail ▶
  2. P2 Metadata changes lack direct tests ▶

Summary

This PR lets simulator workers discover external tasks and adds explicit episode success, per-split camera settings, and a task-provided training context.

  • RLinf workers can use installed tasks and keep each split’s settings.
  • Episode metrics can use a task’s explicit success signal.
  • RLinf policy inputs can use cropped and resized camera views.
  • External tasks can wrap RLinf worker setup and training in a context.
  • Held reset poses now match the padded action chunks.

Reviews (1) · Last reviewed commit: "Support external RLinf tasks with split ..." · Reviewed by Greptile

Comment on lines +114 to +115
configured = list(cfg.env[split].init_params.get("env_overrides") or ())
cfg.env[split].init_params.env_overrides = configured + args_cli.env_overrides

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.

P1 CLI physics overrides fail

If a recipe contains physics=physx and the user passes physics=newton_mjwarp, appending the lists sends both choices to resolve_task_config. _pick_alternative then raises ValueError because they select different alternatives for the same field. Training fails instead of using the CLI choice. Playback has the same problem.

Replace matching recipe selectors before appending CLI overrides.

Comment on lines +259 to +265
if "gpu_resize_width" in cfg or "gpu_resize_height" in cfg:
# 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!

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant