diff --git a/docs/source/experimental-features/rlinf_vla_posttraining.rst b/docs/source/experimental-features/rlinf_vla_posttraining.rst index 81e72d0ea8d..d151b7e9a35 100644 --- a/docs/source/experimental-features/rlinf_vla_posttraining.rst +++ b/docs/source/experimental-features/rlinf_vla_posttraining.rst @@ -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 ----------- diff --git a/source/isaaclab/changelog.d/rlinf-image-preprocessing.added.rst b/source/isaaclab/changelog.d/rlinf-image-preprocessing.added.rst new file mode 100644 index 00000000000..b73e7daa0d7 --- /dev/null +++ b/source/isaaclab/changelog.d/rlinf-image-preprocessing.added.rst @@ -0,0 +1 @@ +* Added device-preserving BHWC crop and resize processing with an explicit output storage ownership contract. diff --git a/source/isaaclab/changelog.d/rlinf-image-preprocessing.minor b/source/isaaclab/changelog.d/rlinf-image-preprocessing.minor new file mode 100644 index 00000000000..e69de29bb2d diff --git a/source/isaaclab/isaaclab/utils/images.py b/source/isaaclab/isaaclab/utils/images.py index f131c93ead5..b122aab2bfe 100644 --- a/source/isaaclab/isaaclab/utils/images.py +++ b/source/isaaclab/isaaclab/utils/images.py @@ -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, diff --git a/source/isaaclab/test/utils/test_images.py b/source/isaaclab/test/utils/test_images.py index c35a288654e..0b6f9a04407 100644 --- a/source/isaaclab/test/utils/test_images.py +++ b/source/isaaclab/test/utils/test_images.py @@ -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) diff --git a/source/isaaclab_contrib/changelog.d/rlinf-camera-crop.fixed.rst b/source/isaaclab_contrib/changelog.d/rlinf-camera-crop.fixed.rst new file mode 100644 index 00000000000..189f856f3fd --- /dev/null +++ b/source/isaaclab_contrib/changelog.d/rlinf-camera-crop.fixed.rst @@ -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. diff --git a/source/isaaclab_contrib/changelog.d/rlinf-external-task.fixed.rst b/source/isaaclab_contrib/changelog.d/rlinf-external-task.fixed.rst new file mode 100644 index 00000000000..4e9d9bac138 --- /dev/null +++ b/source/isaaclab_contrib/changelog.d/rlinf-external-task.fixed.rst @@ -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. diff --git a/source/isaaclab_contrib/changelog.d/rlinf-policy-images.added.rst b/source/isaaclab_contrib/changelog.d/rlinf-policy-images.added.rst new file mode 100644 index 00000000000..0ebb061908d --- /dev/null +++ b/source/isaaclab_contrib/changelog.d/rlinf-policy-images.added.rst @@ -0,0 +1 @@ +* Added configurable GPU cropping and resizing of policy camera images with matching GR00T input metadata. diff --git a/source/isaaclab_contrib/changelog.d/rlinf-policy-images.minor b/source/isaaclab_contrib/changelog.d/rlinf-policy-images.minor new file mode 100644 index 00000000000..e69de29bb2d diff --git a/source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/extension.py b/source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/extension.py index 55f3995630f..1d91ab07fd1 100644 --- a/source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/extension.py +++ b/source/isaaclab_contrib/isaaclab_contrib/rl/rlinf/extension.py @@ -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 @@ -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(): @@ -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) @@ -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() @@ -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 @@ -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, @@ -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. @@ -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 = { @@ -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) @@ -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") @@ -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: diff --git a/source/isaaclab_contrib/test/rl/test_rlinf_extension.py b/source/isaaclab_contrib/test/rl/test_rlinf_extension.py index f0d0211dbac..b2f841452a5 100644 --- a/source/isaaclab_contrib/test/rl/test_rlinf_extension.py +++ b/source/isaaclab_contrib/test/rl/test_rlinf_extension.py @@ -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() @@ -245,8 +246,70 @@ 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) -> None: + """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``.""" + """Worker observation preprocessing and conversion into GR00T inputs.""" + + def test_camera_crop_applies_when_resize_matches_input(self, set_config_env) -> None: + 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.""" @@ -343,6 +406,89 @@ def test_no_padding(self, set_config_env, keys) -> None: np.testing.assert_array_equal(result, np.broadcast_to(expected, (2, 1, 3))) +@pytest.fixture() +def n15_loader(monkeypatch, tmp_path): + """Exercise the real adapter loader with lightweight model and transform dependencies.""" + from pydantic import BaseModel + + class VideoMetadata(BaseModel): + resolution: tuple[int, int] + + class Modalities(BaseModel): + video: dict[str, VideoMetadata] + + class Metadata(BaseModel): + modalities: Modalities + + metadata = Metadata(modalities=Modalities(video={"head": VideoMetadata(resolution=(320, 240))})) + model = mock.Mock(metadata=metadata) + transform = mock.Mock() + data_config = mock.Mock() + data_config.transform.return_value = transform + dependencies = { + "gr00t": {}, + "gr00t.experiment": {}, + "gr00t.experiment.data_config": {"load_data_config": lambda _: data_config}, + "rlinf.models.embodiment.gr00t.gr00t_n1d5": {}, + "rlinf.models.embodiment.gr00t.gr00t_n1d5.gr00t_action_model": { + "GR00T_N1_5_ForRLActionPrediction": mock.Mock(from_pretrained=mock.Mock(return_value=model)) + }, + "rlinf.models.embodiment.gr00t.utils": {"replace_dropout_with_identity": mock.Mock()}, + "rlinf.utils.patcher": {"Patcher": mock.Mock()}, + } + for name, attrs in dependencies.items(): + module = types.ModuleType(name) + vars(module).update(attrs) + monkeypatch.setitem(sys.modules, name, module) + gr00t = _rlinf_mocks["rlinf.models.embodiment.gr00t"] + monkeypatch.setattr(gr00t, "get_model", None, raising=False) + + def load(training, evaluation): + options = {"data_config_class": "test:DataConfig", **training} + monkeypatch.setattr( + ext, "_full_cfg_cache", {"env": {"train": {"isaaclab": options}, "eval": {"isaaclab": evaluation}}} + ) + ext._patch_gr00t_get_model(options) + model_cfg = types.SimpleNamespace( + model_path=str(tmp_path), + embodiment_tag="new_embodiment", + denoising_steps=4, + num_action_chunks=16, + obs_converter_type="isaaclab", + rl_head_config=types.SimpleNamespace(add_value_head=False, disable_dropout=False), + ) + gr00t.get_model(model_cfg) + return model, transform + + return load + + +@pytest.mark.parametrize( + "training,evaluation,expected", + [ + ({"gpu_resize_width": 256, "gpu_resize_height": 128}, {}, (256, 128)), + ({"gpu_resize_width": 192}, {}, (192, 240)), + ({"gpu_resize_height": 128}, {}, (320, 128)), + ({"gpu_resize_width": 192}, {"gpu_resize_height": 240}, (192, 240)), + ], +) +def test_n15_loader_sets_input_size_without_mutating_checkpoint_metadata( + n15_loader, training, evaluation, expected +) -> None: + """The transform sees width/height in metadata order, with unspecified dimensions retained.""" + model, transform = n15_loader(training, evaluation) + actual = transform.set_metadata.call_args.args[0] + assert actual.modalities.video["head"].resolution == expected + assert model.metadata.modalities.video["head"].resolution == (320, 240) + + +@pytest.mark.parametrize("training", [{"gpu_resize_width": 256, "gpu_resize_height": 128}, {}]) +def test_n15_loader_rejects_incompatible_evaluation_image_sizes(n15_loader, training) -> None: + """A shared policy must reject different final train/eval dimensions before rollout.""" + with pytest.raises(ValueError, match="matching train/eval image sizes"): + n15_loader(training, {"gpu_resize_width": 224, "gpu_resize_height": 224}) + + # --------------------------------------------------------------------------- # Tests: embodiment tag patching # --------------------------------------------------------------------------- @@ -393,14 +539,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) @@ -431,11 +579,31 @@ 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, 0, 0) for device in test_devices()), + (True, "cpu", 2, 1), + ], +) +def test_midchunk_reset_does_not_replay_old_episode_actions( + monkeypatch, hold_pose, device, prefix_pad, suffix_pad +) -> None: """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": 0, "suffix_pad": 0}, + } + } + } + }, ) base = _rlinf_mocks["rlinf.envs.isaaclab.isaaclab_env"].IsaaclabBaseEnv states = torch.tensor([[0.2, 0.3], [0.4, 0.5]], device=device) @@ -455,13 +623,16 @@ def chunk_step(self, actions): return [self.step(action, auto_reset=False) for action in actions.unbind(dim=1)] monkeypatch.setattr(base, "chunk_step", chunk_step, raising=False) - env = ext._create_generic_env_wrapper("test")(None, 2, 0, 1, None) + options = {"isaaclab": {"action_mapping": {"prefix_pad": prefix_pad, "suffix_pad": suffix_pad}}} + env = ext._create_generic_env_wrapper("test")(options, 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) diff --git a/source/isaaclab_rl/changelog.d/rlinf-external-task.fixed.rst b/source/isaaclab_rl/changelog.d/rlinf-external-task.fixed.rst new file mode 100644 index 00000000000..d4b5158299b --- /dev/null +++ b/source/isaaclab_rl/changelog.d/rlinf-external-task.fixed.rst @@ -0,0 +1,2 @@ +* Fixed RLinf training and playback to pass the CLI task override to worker registration. +* Preserved split-specific environment overrides from RLinf recipes when merging command-line overrides, replacing conflicting recipe keys including backend preset selectors. diff --git a/source/isaaclab_rl/changelog.d/rlinf-task-runner-context.added.rst b/source/isaaclab_rl/changelog.d/rlinf-task-runner-context.added.rst new file mode 100644 index 00000000000..f7d50dd1c8b --- /dev/null +++ b/source/isaaclab_rl/changelog.d/rlinf-task-runner-context.added.rst @@ -0,0 +1 @@ +* Added an optional ``runner.isaaclab_context`` training recipe setting around RLinf worker initialization and training, without adding environment constructor parameters. diff --git a/source/isaaclab_rl/changelog.d/rlinf-task-runner-context.minor b/source/isaaclab_rl/changelog.d/rlinf-task-runner-context.minor new file mode 100644 index 00000000000..e69de29bb2d diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/cli_args_rlinf.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/cli_args_rlinf.py index cd81f6abccc..6cb23368ac4 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/cli_args_rlinf.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/cli_args_rlinf.py @@ -10,6 +10,7 @@ import argparse import importlib.util import os +from collections.abc import Sequence from pathlib import Path from ..common import CHECKPOINT_SELECTORS, resolve_checkpoint_selector @@ -17,6 +18,17 @@ _BACKENDS_DIR = str(Path(__file__).parent.absolute()) +def merge_env_overrides(configured: Sequence[str], overrides: Sequence[str]) -> list[str]: + """Preserve recipe overrides except keys explicitly replaced by the CLI. + + Preset selectors such as ``physics`` accumulate in task composition, so an overridden + recipe selector must be removed rather than left ahead of its CLI replacement. + Hydra add/delete prefixes do not change which configuration key is being replaced. + """ + replaced = {item.partition("=")[0].lstrip("+-~") for item in overrides} + return [item for item in configured if item.partition("=")[0].lstrip("+-~") not in replaced] + list(overrides) + + def add_rlinf_args(parser: argparse.ArgumentParser) -> None: """Add RLinf arguments to the parser. @@ -78,12 +90,13 @@ def resolve_config_dir(config_name: str, explicit_path: str | None) -> str: return _BACKENDS_DIR -def configure_rlinf_environment(config_name: str, config_path: str | None) -> str: +def configure_rlinf_environment(config_name: str, config_path: str | None, task: str | None = None) -> str: """Export the environment variables RLinf reads at import time and return the config directory. Args: config_name: Name of the RLinf configuration file without extension. config_path: Explicit configuration directory, or None to search for it. + task: CLI task override for the train and eval workers, or None to use the YAML task IDs. """ config_dir = resolve_config_dir(config_name, config_path) # Ray 2.47+ turns the current project into a ``working_dir`` runtime environment when the driver is @@ -94,6 +107,7 @@ def configure_rlinf_environment(config_name: str, config_path: str | None) -> st # required for RLinf to register Isaac Lab tasks and converters os.environ.setdefault("RLINF_EXT_MODULE", "isaaclab_contrib.rl.rlinf.extension") os.environ["RLINF_CONFIG_FILE"] = str(Path(config_dir) / f"{config_name}.yaml") + os.environ["ISAACLAB_RLINF_TASK"] = task or "" # Ray rollout workers resolve data_config_class references like "gr00t_config:IsaacLabDataConfig" # from the config directory if config_dir not in os.environ.get("PYTHONPATH", ""): diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rlinf.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rlinf.py index 4d7374de577..b5a1ff81eb3 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rlinf.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/play_rlinf.py @@ -59,7 +59,7 @@ def run(argv: list[str]) -> None: """Launch RLinf evaluation.""" args_cli = _parse_args(argv) config_name = args_cli.config_name - config_dir = cli_args.configure_rlinf_environment(config_name, args_cli.config_path) + config_dir = cli_args.configure_rlinf_environment(config_name, args_cli.config_path, args_cli.task) # rlinf reads RLINF_EXT_MODULE and RLINF_CONFIG_FILE at import time, so it is imported after the setup above import rlinf # noqa: F401 @@ -82,7 +82,7 @@ def run(argv: list[str]) -> None: initialize_config_dir(config_dir=config_dir) cfg = compose(config_name=config_name) - task_id = cfg.env.eval.init_params.id + task_id = args_cli.task or cfg.env.eval.init_params.id logger.info(f"Task: {task_id}") # hyphens instead of colons in the time stamp; colons are invalid in Windows paths timestamp = datetime.now().strftime("%Y%m%d-%H-%M-%S") @@ -99,7 +99,7 @@ def run(argv: list[str]) -> None: cfg.runner.ckpt_path = cli_args.resolve_rlinf_checkpoint( args_cli.checkpoint, log_root_path=str(Path("logs") / "rlinf"), - task=args_cli.task or task_id, + task=task_id, config_name=config_name, ) if args_cli.video: @@ -115,7 +115,8 @@ def run(argv: list[str]) -> None: if args_cli.num_episodes is not None: cfg.algorithm.eval_rollout_epoch = args_cli.num_episodes for split in ("train", "eval"): - cfg.env[split].init_params.env_overrides = args_cli.env_overrides + configured = list(cfg.env[split].init_params.get("env_overrides") or ()) + cfg.env[split].init_params.env_overrides = cli_args.merge_env_overrides(configured, args_cli.env_overrides) cfg.rollout.model = OmegaConf.merge(cfg.actor.model, cfg.rollout.model) # Ray workers may launch from a different working directory. for model in (cfg.actor.model, cfg.rollout.model): diff --git a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rlinf.py b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rlinf.py index d4e69793a84..abacc631547 100644 --- a/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rlinf.py +++ b/source/isaaclab_rl/isaaclab_rl/entrypoints/backends/train_rlinf.py @@ -11,6 +11,7 @@ import logging import os import re +from contextlib import nullcontext from datetime import datetime from pathlib import Path @@ -60,7 +61,7 @@ def run(argv: list[str]) -> None: return config_name = args_cli.config_name - config_dir = cli_args.configure_rlinf_environment(config_name, args_cli.config_path) + config_dir = cli_args.configure_rlinf_environment(config_name, args_cli.config_path, args_cli.task) # rlinf reads RLINF_EXT_MODULE and RLINF_CONFIG_FILE at import time, so it is imported after the setup above import rlinf # noqa: F401 @@ -75,6 +76,8 @@ def run(argv: list[str]) -> None: from rlinf.workers.env.env_worker import EnvWorker from rlinf.workers.rollout.hf.huggingface_worker import MultiStepRolloutWorker + from isaaclab.utils.string import string_to_callable + mp.set_start_method("spawn", force=True) logger.info(f"Using config: {config_name}") @@ -83,7 +86,7 @@ def run(argv: list[str]) -> None: initialize_config_dir(config_dir=config_dir) cfg = compose(config_name=config_name) - task_id = cfg.env.train.init_params.id + task_id = args_cli.task or cfg.env.train.init_params.id logger.info(f"Task: {task_id}") # hyphens instead of colons in the time stamp; colons are invalid in Windows paths timestamp = datetime.now().strftime("%Y%m%d-%H-%M-%S") @@ -109,12 +112,13 @@ def run(argv: list[str]) -> None: if args_cli.only_eval: cfg.runner.only_eval = True for split in ("train", "eval"): - cfg.env[split].init_params.env_overrides = args_cli.env_overrides + configured = list(cfg.env[split].init_params.get("env_overrides") or ()) + cfg.env[split].init_params.env_overrides = cli_args.merge_env_overrides(configured, args_cli.env_overrides) if args_cli.checkpoint: checkpoint_path = cli_args.resolve_rlinf_checkpoint( args_cli.checkpoint, log_root_path=str(Path("logs") / "rlinf"), - task=args_cli.task or task_id, + task=task_id, config_name=config_name, ) for directory in Path(checkpoint_path).parents: @@ -128,9 +132,7 @@ def run(argv: list[str]) -> None: for model in (cfg.actor.model, cfg.rollout.model): model.model_path = str(Path(model.model_path).expanduser().resolve()) - write_run_manifest( - str(log_dir), library="rlinf", task=args_cli.task or task_id, metadata={"config_name": config_name} - ) + write_run_manifest(str(log_dir), library="rlinf", task=task_id, metadata={"config_name": config_name}) cfg = validate_cfg(cfg) cli_args.print_rlinf_banner( "RLinf Training Configuration", @@ -167,5 +169,9 @@ def run(argv: list[str]) -> None: ) runner = EmbodiedRunner(cfg=cfg, actor=actor_group, rollout=rollout_group, env=env_group) - runner.init_workers() - runner.run() + context = nullcontext() + if entry_point := cfg.runner.get("isaaclab_context"): + context = string_to_callable(entry_point)(runner, args_cli.env_overrides) + with context: + runner.init_workers() + runner.run() diff --git a/source/isaaclab_rl/test/test_entrypoints.py b/source/isaaclab_rl/test/test_entrypoints.py index 1d9928fa73a..cc06883178d 100644 --- a/source/isaaclab_rl/test/test_entrypoints.py +++ b/source/isaaclab_rl/test/test_entrypoints.py @@ -512,17 +512,54 @@ def test_rlinf_rejects_pretrained_checkpoint() -> None: resolve_rlinf_checkpoint("pretrained", log_root_path="logs/rlinf", task="Isaac-Task", config_name="ppo") -@pytest.mark.parametrize("backend", [train_rlinf, play_rlinf], ids=["train", "play"]) -def test_rlinf_launch_passes_checkpoint_and_model_config_to_workers(tmp_path: Path, monkeypatch, backend) -> None: - """Real CLI composition supplies the native RLinf weight/resume hooks before workers start.""" - validate = mock.Mock(side_effect=RuntimeError("worker boundary")) +@pytest.mark.parametrize( + "backend,boundary,with_context", + [ + (train_rlinf, "validation", False), + (play_rlinf, "validation", False), + (train_rlinf, None, False), + (train_rlinf, None, True), + (train_rlinf, "training", True), + ], + ids=["train-validation", "play-validation", "train-no-context", "train-context", "train-context-error"], +) +def test_rlinf_launch_passes_checkpoint_and_model_config_to_workers( + tmp_path: Path, monkeypatch, backend, boundary, with_context +) -> None: + """CLI composition preserves worker settings and cleans up a configured training context.""" + validate = mock.Mock(side_effect=RuntimeError("worker boundary") if boundary == "validation" else lambda cfg: cfg) + events = [] + runner = mock.Mock() + runner.init_workers.side_effect = lambda: events.append("initialize") + + def run_training(): + events.append("train") + if boundary == "training": + raise RuntimeError("training boundary") + + runner.run.side_effect = run_training + + @contextlib.contextmanager + def training_context(actual_runner, overrides): + assert actual_runner is runner + assert overrides == ["physics=newton_mjwarp", "env.scene.num_envs=2"] + events.append("enter") + try: + yield + finally: + events.append("exit") + + context_module = types.ModuleType("_rlinf_context_test") + context_module.training_context = training_context + monkeypatch.setitem(sys.modules, context_module.__name__, context_module) modules = { "rlinf": {}, "rlinf.config": {"validate_cfg": validate}, - "rlinf.runners.embodied_runner": {"EmbodiedRunner": mock.Mock()}, + "rlinf.runners.embodied_runner": {"EmbodiedRunner": mock.Mock(return_value=runner)}, "rlinf.runners.embodied_eval_runner": {"EmbodiedEvalRunner": mock.Mock()}, "rlinf.scheduler": {"Cluster": mock.Mock()}, "rlinf.utils.placement": {"HybridComponentPlacement": mock.Mock()}, + "rlinf.workers.actor.fsdp_actor_worker": {"EmbodiedFSDPActor": mock.Mock()}, "rlinf.workers.env.env_worker": {"EnvWorker": mock.Mock()}, "rlinf.workers.rollout.hf.huggingface_worker": {"MultiStepRolloutWorker": mock.Mock()}, } @@ -532,7 +569,13 @@ def test_rlinf_launch_passes_checkpoint_and_model_config_to_workers(tmp_path: Pa monkeypatch.setitem(sys.modules, name, module) monkeypatch.setattr(torch.multiprocessing, "set_start_method", lambda *args, **kwargs: None) monkeypatch.chdir(tmp_path) - for variable in ("PYTHONPATH", "RLINF_CONFIG_FILE", "RLINF_EXT_MODULE", "RAY_ENABLE_UV_RUN_RUNTIME_ENV"): + for variable in ( + "PYTHONPATH", + "RLINF_CONFIG_FILE", + "RLINF_EXT_MODULE", + "RAY_ENABLE_UV_RUN_RUNTIME_ENV", + "ISAACLAB_RLINF_TASK", + ): monkeypatch.delenv(variable, raising=False) step_dir = tmp_path / "checkpoints" / "global_step_400" weights = step_dir / "actor" / "model_state_dict" / "full_weights.pt" @@ -540,23 +583,69 @@ def test_rlinf_launch_passes_checkpoint_and_model_config_to_workers(tmp_path: Pa weights.touch() cfg = OmegaConf.create( { - "runner": {"logger": {"log_path": "unused"}}, + "runner": {"logger": {"log_path": "unused"}, "max_epochs": 1}, + "algorithm": {"loss_type": "actor_critic"}, + "cluster": {}, "actor": { - "model": {"model_path": "./base", "model_type": "gr00t", "rl_head_config": {"add_value_head": True}} + "group_name": "actor", + "model": {"model_path": "./base", "model_type": "gr00t", "rl_head_config": {"add_value_head": True}}, + }, + "rollout": { + "group_name": "rollout", + "model": {"model_path": "./rollout", "rl_head_config": {"disable_dropout": True}}, + }, + "env": { + "group_name": "env", + "train": { + "total_num_envs": 1, + "init_params": { + "id": "Test", + "env_overrides": ["physics=physx", "env.sim.physics.split=train", "env.scene.num_envs=8"], + }, + }, + "eval": { + "init_params": { + "id": "Test", + "env_overrides": ["physics=physx", "env.sim.physics.split=validation", "env.scene.num_envs=4"], + } + }, }, - "rollout": {"model": {"model_path": "./rollout", "rl_head_config": {"disable_dropout": True}}}, - "env": {"train": {"init_params": {"id": "Test"}}, "eval": {"init_params": {"id": "Test"}}}, } ) + if with_context: + cfg.runner.isaaclab_context = "_rlinf_context_test:training_context" OmegaConf.save(cfg, tmp_path / "ppo.yaml") checkpoint = step_dir if backend is train_rlinf else weights - args = ["--config_path", str(tmp_path), "--config_name", "ppo"] + args = ["--config_path", str(tmp_path), "--config_name", "ppo", "--task", "Test-Cosmos"] args += ["--checkpoint", str(checkpoint.relative_to(tmp_path))] - with pytest.raises(RuntimeError, match="worker boundary"): + args += ["physics=newton_mjwarp", "env.scene.num_envs=2"] + if boundary: + message = "worker boundary" if boundary == "validation" else "training boundary" + with pytest.raises(RuntimeError, match=message): + backend.run(args) + else: backend.run(args) + expected_events = [] if boundary == "validation" else ["initialize", "train"] + assert events == (["enter", *expected_events, "exit"] if with_context else expected_events) GlobalHydra.instance().clear() assert os.environ["RAY_ENABLE_UV_RUN_RUNTIME_ENV"] == "0" resolved = validate.call_args.args[0] + assert list(resolved.env.train.init_params.env_overrides) == [ + "env.sim.physics.split=train", + "physics=newton_mjwarp", + "env.scene.num_envs=2", + ] + assert list(resolved.env.eval.init_params.env_overrides) == [ + "env.sim.physics.split=validation", + "physics=newton_mjwarp", + "env.scene.num_envs=2", + ] + assert ( + resolved.env.train.init_params.id + == resolved.env.eval.init_params.id + == os.environ["ISAACLAB_RLINF_TASK"] + == "Test-Cosmos" + ) assert resolved.runner["resume_dir" if backend is train_rlinf else "ckpt_path"] == str(checkpoint) assert resolved.actor.model.model_path == str(tmp_path / "base") assert resolved.rollout.model.model_path == str(tmp_path / "rollout")