Skip to content

Support external RLinf tasks and explicit episode success - #9217

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

KumoLiu wants to merge 14 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.
  • Read success from pre-reset final_obs and preserve the first completed episode’s outcome through the action chunk. Reset-episode frames cannot erase a win or turn a completed failure into a win; legacy recipes retain their metrics.
  • Keep deterministic, device-preserving resizing in isaaclab.utils.images, round uint8 pixels to nearest, and leave augmentation in task observation processors. Resolve worker split settings once and document tensor layout and storage ownership.
  • Require paired GPU resize dimensions for GR00T N1.5 and validate matching train/eval output sizes and adapt a metadata copy without mutating checkpoint metadata.
  • Select an optional runner.isaaclab_context in the training recipe to manage worker initialization/training, without adding Gym constructor kwargs. Preserve 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: 39 passed; entrypoints: 67 passed; image utilities: 54 passed.
  • Medical-pad integration/configuration/action codec: 14 passed against this standalone branch.
  • Trocar demo: 11 passed against the combined Lab snapshot; the explicit-RTX configuration regression also passed.
  • Native RLinf 16-action chunk dispatch with real Lab autoreset passed success and failure checks on CPU, using stand-in world-model/classifier dependencies. The success observation becomes false immediately on reset, so this does not rely on tracker caching.
  • Incompatible train/eval sizes and legacy augmentation keys fail on the driver before RLinf validation or cluster startup.
  • Trocar task crop/configuration/rendering: 3 passed; updated PhysX/RTX smoke with task cropping enabled passed.
  • Full isaaclab --format checks, including changelog validation, passed.

GPU image-preprocessing measurement

Baseline: a3ff0b523. Candidate: combined snapshot 806b6f1fa, including the task-owned crop processor from #9148 and this PR's deterministic resizing.

NVIDIA A100 80 GB PCIe, PyTorch 2.11.0+cu130, GPU 0. Process 32 environments × 3 uint8 BHWC views, 320×240 → 224×224 after a 5% crop. Each case uses 50 warmups and 250 measured observations, with interleaved baseline/candidate batches and synchronization at batch boundaries. The measurement includes the actual crop/resize functions and observation-manager image copies; it excludes simulation, IPC, policy inference and extra-view stacking.

Processing Baseline ms/observation Candidate ms/observation
Center crop 0.958 1.057
Random crop 1.526 1.586

With matching crop offsets, pixel differences are at most one uint8 level because conversion now rounds rather than truncates. These results quantify preprocessing cost only and do not establish end-to-end training throughput or success-rate parity.

Reproduce the preprocessing measurement

Run from the tested combined snapshot with its task dependencies installed and the baseline commit available locally:

CUDA_VISIBLE_DEVICES=0 uv run --no-sync python - <<'PYCODE'
"""Compare the actual policy image functions, including observation-manager storage ownership."""
import ast,json,statistics,subprocess,time
from pathlib import Path
import torch
from isaaclab.utils.images import resize_images
from isaaclab_tasks.contrib.assemble_trocar.mdp.observations import crop_policy_camera
LAB=Path.cwd()
BASELINE='a3ff0b5235847231d6191dd487176699cb8e077f'
source=subprocess.check_output(['git','show',BASELINE+':source/isaaclab/isaaclab/utils/images.py'],cwd=LAB,text=True)
node=next(n for n in ast.parse(source).body if isinstance(n,ast.FunctionDef) and n.name=='crop_and_resize_images')
ns={'torch':torch};exec(ast.get_source_segment(source,node),ns);old_resize=ns['crop_and_resize_images']
images=[torch.randint(256,(32,240,320,3),device='cuda:0',dtype=torch.uint8) for _ in range(3)]
results=[]
with torch.inference_mode():
 for random in (False,True):
  def old():
   return [old_resize(image.clone(),height=224,width=224,crop_scale=.05,random_crop=random) for image in images]
  def new():
   # ObservationManager copies processor inputs and copies borrowed processor outputs.
   return [resize_images(crop_policy_camera(image.clone(),scale=.05,random_crop=random).clone(),height=224,width=224) for image in images]
  torch.cuda.manual_seed_all(13);before=old()
  torch.cuda.manual_seed_all(13);after=new()
  max_delta=max(int((a.to(torch.int16)-b.to(torch.int16)).abs().max()) for a,b in zip(before,after))
  assert max_delta<=1,max_delta
  for fn in (old,new):
   for _ in range(50):fn()
  torch.cuda.synchronize();samples={'baseline':[],'candidate':[]};functions={'baseline':old,'candidate':new}
  for repeat in range(10):
   order=['baseline','candidate'] if repeat%2==0 else ['candidate','baseline']
   for name in order:
    torch.cuda.synchronize();start=time.perf_counter()
    for _ in range(25):functions[name]()
    torch.cuda.synchronize();samples[name].append((time.perf_counter()-start)*1000/25)
  results.append({'crop':'random' if random else 'center','max_pixel_difference':max_delta,**{name:{'mean_ms':statistics.mean(values),'min_ms':min(values),'max_ms':max(values)} for name,values in samples.items()}})
report={'baseline':BASELINE,'candidate':subprocess.check_output(['git','rev-parse','HEAD'],cwd=LAB,text=True).strip(),'gpu':torch.cuda.get_device_name(0),'torch':torch.__version__,'envs':32,'views':3,'input_hw':[240,320],'output_hw':[224,224],'crop_scale':.05,'warmup':50,'measured':250,'includes':'actual crop and resize functions plus observation-manager image clones; excludes simulation, RPC, model inference','results':results}
path=Path('policy-image-processing.json');path.write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))
PYCODE

Based on main c1afcee17, including #9155 checkpoint selector fixes for separate train/eval task IDs.

Runner context configuration

Training recipes can set runner.isaaclab_context: module:callable. The callable receives the runner and merged training environment overrides (recipe plus CLI), then returns a context manager. The optional hook is used by the Trocar Cosmos demo to manage service GPU residency during collection and policy updates. Unset recipes use the normal training path. The context wraps worker initialization and training, including exception cleanup, and is never stored in Gym task constructor kwargs.

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!

"""


def crop_and_resize_images(

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.

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.

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.

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.

@Fanxing-LI Fanxing-LI Nov 26, 2026 •

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

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)

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.

Maybe here insert a round() could retain fractional part better before to uint8

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.

Added rounding before conversion back to uint8, with a regression test covering fractional interpolation values.

if not data_config_class or model_type == "gr00t_n1d7":
return

evaluation_cfg = {**cfg, **_load_full_cfg().get("env", {}).get("eval", {}).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.

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.

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.

Good point. Both train and play now validate the merged image configuration on the driver before launching workers, so configuration errors are reported directly.

Comment on lines 572 to 577
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.

cfg = _get_isaaclab_cfg()
cfg = self._isaaclab_cfg
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.

@Fanxing-LI
Fanxing-LI self-requested a review November 26, 2026 05:20

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

Please kindly consider whether resize image could be set outside the isaaclab codebase, just a suggestion, not request.

Besides, see aforementioned comments.

@KumoLiu
KumoLiu requested a review from Fanxing-LI November 26, 2026 06:43
validate_image_config rejects gpu_crop_scale and gpu_crop_random whenever
they are present. The H2 Sharpa recipes still carried neutral values that no
code reads, so their documented train and play commands failed at startup.

Add a test that launches every RLinf recipe shipped in isaaclab_tasks through
train_rlinf up to the worker boundary, then validates the raw recipe file the
way the extension's register() does.
@Fanxing-LI
Fanxing-LI requested a review from hujc7 as a code owner November 26, 2026 08:48
"""


def crop_and_resize_images(

@Fanxing-LI Fanxing-LI Nov 26, 2026 •

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

@Fanxing-LI

Copy link
Copy Markdown
Contributor

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Nov 26, 2026
@Fanxing-LI

Copy link
Copy Markdown
Contributor

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Nov 27, 2026

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.

3 participants