Repository navigation
[release/3.1.0] Backport pi0.5 evaluation and RLinf fixes and external task support - #9306
Conversation
…ing guide (isaac-sim#9155) # Description Follow-up to isaac-sim#7776. Verifying the RLinf VLA post-training guide end to end turned up two defects in the `isaaclab_rl` RLinf entry points and several problems in the guide itself. This PR fixes them and removes the remaining references to personal Hugging Face checkpoints. **Entry point fixes (`isaaclab_rl`)** - `isaaclab play --rl_library rlinf --checkpoint latest|best` never found a checkpoint. Playback looked up run manifests with `env.eval.init_params.id`, while training records `env.train.init_params.id`. All three shipped recipes use a distinct `...-Eval` id for evaluation, so the lookup always failed with `No compatible manifested run with a checkpoint was found`. Playback now resolves the selector against the training id, matching `train_rlinf.py`; an explicit `--task` still takes precedence. - A relative `--config_path` failed with `initialize_config_dir() requires an absolute config_dir as input`. The path is now resolved to an absolute directory before Hydra is initialized. - The launch test is now a train → play round trip with a relative config directory: training writes the run manifest, and playback resolves `latest` through it although the recipe's eval task id differs from its training id. Reverting either fix, or making training record the eval id, turns the test red with the original errors. **Documentation (`rlinf_vla_posttraining.rst`)** - Remove the paragraph that pointed at the task author's personal checkpoint repositories. - Move the `assemble_trocar` `hf download` from the prerequisites into a new "Assemble Trocar checkpoint" subsection after the Step 2 dependency pins, and run it with `uv run --no-sync`. With the lockfile's `huggingface-hub` 1.x and `typer` 0.27, `hf` downloads the files but exits non-zero with a `click.exceptions.Exit` traceback; any `huggingface-hub` < 1.0 works. The Step 2 floor is raised to `>=0.34`, the first release that ships the `hf` CLI. - Add `Environments/Grid` to the local-mirror subtree list; the default `GroundPlaneCfg` USD is loaded from there. - Mark flash-attn as optional for GR00T N1.7, which falls back to PyTorch SDPA attention with a warning when the package is missing (building it needs a CUDA 13 `nvcc` to match the lockfile's torch). - Add `--no-sync` to the `uv run isaaclab ...` commands in "Key Files" so they do not re-sync the environment. No linked issue. ## Type of change - Bug fix (non-breaking change which fixes an issue) - Documentation update ## Screenshots Not applicable (CLI and documentation changes). ## Validation - `uv run python -m pytest source/isaaclab_rl/test/test_entrypoints.py` passes (the one skrl parser test was deselected locally because `skrl` is not installed in my environment). - Mutation checks: reverting the playback fix fails the new test with the manifest `ValueError`; reverting the config-path fix fails it with the Hydra `initialize_config_dir()` error; making training record the eval id fails it with the manifest `ValueError`. - `pre-commit` on the changed files, the changelog gate (`tools/changelog/cli.py check`), and a Sphinx render of the guide pass. - No GPU training or evaluation runs were performed for this PR; the code changes are confined to CLI argument handling. ## Checklist Docker and GPU tests run on demand. Push the commits you want tested, then comment `run-ci` on the pull request, or `run-ci ovstage` to include kitless OVStage rendering tests for that run. Subsequent pushes and plain `run-ci` comments do not run OVStage tests unless you comment `run-ci ovstage` again. - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `uv run isaaclab --format` - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have validated the changed behavior with focused coverage and applied the [test-audit criteria](https://github.com/isaac-sim/IsaacLab/blob/HEAD/skills/developer/test-audit/SKILL.md) to any test changes - [x] I have added a changelog fragment under `source/<pkg>/changelog.d/` for every touched package (do **not** edit `CHANGELOG.rst` or bump package versions — CI handles that) - [x] I have added my name to the `CONTRIBUTORS.md` or my name already exists there (cherry picked from commit c1afcee)
## Description Evaluate pi0.5 on `IsaacContrib-TableTop-PickPlace-Franka` from merged isaac-sim#9165 with one command. The first run fetches a pinned OpenPI revision, prepares its separate Python 3.11 environment, anonymously downloads the joint-position checkpoint and starts inference. Subsequent runs reuse the caches. Evaluation shuts down its inference process on completion or interruption. The PR adds two scripts: the evaluator owns scene setup, trial scheduling and local process lifetime; the server entrypoint owns OpenPI model configuration and loading. There are no framework, task, asset or dependency-file changes. OpenPI's dependencies stay outside the Isaac Lab environment. Any idle world requests the next global task-family ID and resets to a fresh object count, category composition, assets and table. Each episode records its instruction, objects, mesh variants, table variant and success/timeout. Completed worlds discard their remaining action chunk and hold their reset arm pose with the gripper open. Every terminal result counts, including one-step episodes. The client uses the standard OpenPI WebSocket protocol, querying active worlds serially. No custom batch adapter is required. Camera updates follow the action chunk interval; both views are letterboxed to 224 × 224, and DROID gripper closure maps to the environment's binary command. ## Run With Isaac Lab installed on Linux and an NVIDIA GPU, git and uv available: ```bash uv run --with msgpack python scripts/large_models/pi05_evaluate.py --viz none ``` No manual OpenPI installation, server launch or Google login is required. The first run downloads the approximately 12.4 GB `gs://openpi-assets-simeval/pi05_droid_jointpos` checkpoint. Source/environment are cached under `~/.cache/isaaclab/pi05`; weights/tokenizer use `~/.cache/openpi` (`OPENPI_DATA_HOME` overrides it). Inference uses the first visible GPU without JAX preallocation; simulation and inference must fit in available GPU memory. Optional controls: - `--num_envs 4 --trials 2`: two trials per task family, distributed across four worlds. - `--policy-device 1`: select another inference GPU through `CUDA_VISIBLE_DEVICES`. - `--checkpoint /path/to/pi05_droid_jointpos`: reuse existing weights. - `--policy HOST:PORT`: use an existing standard OpenPI joint-position server and skip local setup. - `--tasks put_in_container`: select a task family. - `env.episode_length_s=10`: ordinary task configuration overrides. Reports go to a new timestamped directory under `logs/pi05`; `--output PATH` selects one explicitly. The action contract is seven absolute arm joint positions and gripper closure in [0, 1]. The standard velocity-action DROID checkpoint is incompatible. ## Validation - Started with an empty OpenPI checkout/environment cache: automatic fetch of revision `215abfb217dbac7d5f1273282331b9b1866c0479` and locked dependency installation succeeded. - Real pi0.5 inference completed both task families in two worlds with three-second episodes: two timeouts, 45 shared control steps, 90 trial steps and six standard policy requests. This checks integration, not policy performance. - That run used the published robot and scene configuration with no local asset overrides. Existing checkpoint and asset caches were reused; the full 12.4 GB model was not downloaded again. - Separately verified anonymous download of checkpoint normalization assets into a fresh cache, including recursive directory download and cache reuse. - Verified cached environment startup, interruption cleanup and propagation of server startup failure for a missing checkpoint. No inference process remains after exit. - Scheduler checks cover global family scheduling, fresh instructions, one-step episodes, completion within a chunk, idle holds, row ordering, gripper signs and exact step accounting. Reply guards reject short chunks, wrong width/rank, NaNs and server errors. - CLI help, full repository formatting/lint and changelog checks pass. No new simulation tests were added. ## Type of change - New example scripts ## Checklist - [x] Follow contribution guidelines - [x] Run formatting and lint checks - [x] Document setup and usage in the scripts - [x] Validate real inference, lifecycle and scheduling locally - [x] No source-package changes requiring a changelog fragment --------- Co-authored-by: Octi Zhang <[email protected]> (cherry picked from commit 92ecbee)
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Design and architecture (1), Scope and over-engineering (3), API (1), Compatibility and deprecation (1), Implementation (2), Style consistency (6). Other reviewed categories look good.
- PR description: Specify MuJoCo-only contact tuning; title, scope, and validation limits match the diff, but serial inference and per-step transfers need baseline/candidate throughput measurements with revisions, command, hardware, backend, environment count, and warmup.
- Design and architecture: Letterboxing belongs in utils.images; move the evaluator's image transformation there to preserve the prescribed ownership boundary.
- Scope and over-engineering: Minimal implementation: Extend play_rlinf.py and cli_args_rlinf.py for checkpoint identity and Hydra normalization, and utils.images for letterboxing; keep pi05_evaluate.py for scheduling/reports and pi05_serve.py for its isolated OpenPI contract; remove duplicate trial history, redundant dtype copies, and separate full-batch termination transfers. Suggested PR breakdown: (1) RLinf fixes, guide, and entrypoint regression, validated at CLI composition; (2) tabletop contact tuning and evaluation/server scripts, validated with GPU trials and throughput measurements.
- API: The new --tasks option consumes trailing Hydra overrides as family names; preserve override forwarding or require and document a separator.
- Compatibility and deprecation: Breaking changes: resolve_config_dir now canonicalizes explicit paths instead of returning them unchanged; preserve that documented return contract and normalize at configure_rlinf_environment before Hydra initialization.
- Implementation: Missing action-space metadata permits unverified external-server outputs to become absolute joint targets; require explicit absolute-action semantics or deliberate user opt-in.
- Style consistency: Evaluator status prints bypass repository logging and verbosity controls; configure console logging first and route setup, report-path, and trial-progress messages through a module logger.
- Test quality: Test quality looks good.
Significant concerns. Posted 14 inline findings.
Automated review; human maintainers own approval decisions.
| try: | ||
| with policy_connection() as socket: | ||
| metadata = msgpack.unpackb(socket.recv(timeout=180), object_hook=unpack_array) | ||
| if metadata.get("action_space") not in (None, "absolute_joint_position"): |
There was a problem hiding this comment.
🔴 Critical · Implementation — Require declared absolute actions
A standard external server without action_space metadata passes this check, so velocity actions can be applied as absolute joint positions. Require explicit absolute-action metadata or an explicit user opt-in.
| parser.add_argument("--num_envs", type=int, default=8) | ||
| parser.add_argument("--policy", metavar="HOST:PORT", help="Existing standard OpenPI server; default: start locally.") | ||
| parser.add_argument("--checkpoint", default="gs://openpi-assets-simeval/pi05_droid_jointpos", help="Checkpoint.") | ||
| parser.add_argument("--policy-cache", type=Path, default=Path.home() / ".cache/isaaclab/pi05") |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Use snake_case CLI names
--policy-cache and --policy-device violate the required snake_case convention used by --num_envs and --max_steps. Rename the options with underscores and update their documentation.
| parser.add_argument( | ||
| "--output", type=Path, default=Path("logs/pi05") / datetime.now().strftime("%Y%m%d_%H%M%S"), help="Reports." | ||
| ) | ||
| parser.add_argument("--tasks", nargs="+", metavar="FAMILY", help="Task families; default: all declared families.") |
There was a problem hiding this comment.
🟡 Warning · Api — Keep overrides after task selection
With --tasks FAMILY env.episode_length_s=10, argparse's nargs='+' consumes the override as another family. Parse family selections without swallowing trailing overrides, or require and document a separator.
|
|
||
|
|
||
| @contextmanager | ||
| def policy_connection(): |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Mark script helpers private
The connection, resizing, serialization, query, and evaluation helpers are used only in this script but have public names. Prefix these file-local helpers with underscores.
| git = ["git", "-C", str(checkout)] | ||
| revision = subprocess.run(git + ["rev-parse", "HEAD"], env=environment, capture_output=True, text=True) | ||
| if revision.returncode or revision.stdout.strip() != OPENPI_REVISION: | ||
| print(f"Fetching OpenPI {OPENPI_REVISION} into {checkout}", flush=True) |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Log entry-point status
Setup, report-path, and trial-progress prints bypass verbosity controls and log handlers. Configure console logging first and emit these status messages through a module logger.
| report["simulation_seconds"] += time.perf_counter() - before_step | ||
| report["control_steps"] += 1 | ||
| report["trial_steps"] += len(running) | ||
| success = env.termination_manager.get_term("success").tolist() |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Transfer only active termination flags
Two full-batch .tolist() calls synchronize the device on every control step, including idle worlds. Select active worlds and transfer success and timeout flags together.
| if not (success[slot] or timeout[slot]): | ||
| continue | ||
| trial.update(success=bool(success[slot]), timeout=bool(timeout[slot])) | ||
| report["episodes"].append(trial) |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Keep one trial history
Each trial is retained in result.json and written to episodes.jsonl, so periodic saves repeatedly serialize growing history. Keep aggregate counts in memory and detailed trials in JSONL.
|
|
||
|
|
||
| def main() -> None: | ||
| """Resolve the registered scene, prepare inference, then evaluate and save results.""" |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Remove narrated main docstrings
This docstring merely lists the operations immediately below it; pi05_serve.main does the same. Remove both narrations and retain the module-level usage documentation.
| if explicit_path is not None: | ||
| return explicit_path | ||
| # Hydra's initialize_config_dir() rejects relative directories | ||
| return str(Path(explicit_path).expanduser().resolve()) |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Preserve explicit config path returns
resolve_config_dir previously returned an explicit path unchanged; it now changes relative and symlink paths. Preserve that return contract and normalize in configure_rlinf_environment before passing the path to Hydra.
| backend.run(args) | ||
| GlobalHydra.instance().clear() | ||
|
|
||
| def launch(backend, checkpoint: str): |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Annotate the new test helper
The new launch helper leaves its backend and returned configuration unannotated despite the repository's signature-typing rule. Annotate the module argument and resolved configuration.
[Medium impact] The PR appears safe to merge; no actionable issues were found. SummaryBackports RLinf playback fixes and adds pi0.5 tabletop evaluation.
Review used source checks; GPU inference and simulation were not run. DiagramsequenceDiagram
participant Evaluator as pi05_evaluate.py
participant Policy as OpenPI server
participant Worlds as Isaac Lab worlds
Evaluator->>Policy: Start locally or connect remotely
Policy-->>Evaluator: Policy metadata
Evaluator->>Worlds: Assign task families and reset
loop Until all trials finish
Worlds-->>Evaluator: Images and joint positions
Evaluator->>Policy: Request action chunks
Policy-->>Evaluator: Absolute joint-position actions
Evaluator->>Worlds: Apply actions
Worlds-->>Evaluator: Success or timeout
Evaluator->>Evaluator: Save completed trials
end
Reviews (1) · Last reviewed commit: "Evaluate pi0.5 on sampled tabletop tasks..." · Reviewed by Greptile |
|
run-ci |
…9217) ## Summary Support installed external tasks in RLinf training and playback while keeping task and service implementations downstream. These shared changes are separate from isaac-sim#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](isaac-sim/isaaclab_demos#14) and [Trocar Cosmos demo](isaac-sim/isaaclab_demos#13). Only the latter also requires the task changes in isaac-sim#9148. ## Release backport - [x] <!-- backport-active-release --> Backport this pull request to the active release branch after it merges into `main` ## 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`](KumoLiu@a3ff0b5). Candidate: combined snapshot [`806b6f1fa`](KumoLiu@806b6f1), including the task-owned crop processor from isaac-sim#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. <details> <summary>Reproduce the preprocessing measurement</summary> Run from the tested combined snapshot with its task dependencies installed and the baseline commit available locally: ```bash 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 ``` </details> Based on main `c1afcee17`, including isaac-sim#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 --------- Co-authored-by: Fanxing-LI <[email protected]> (cherry picked from commit 05e3a7d)
|
run-ci |
Description
Backport #9155, #9184, and #9217 to
release/3.1.0:Cherry-picked with
-xfromc1afcee17283aacaebd5ccdbb4e823827752ffd6,92ecbeeb428fb50b242651d747be0fe3bcef6d4e, and05e3a7dc46dce08a2e61511cf5ef358a5ffd4c2d. All three applied without conflicts or manual edits; stable patch IDs match the original commits. The prerequisite tabletop task from #9165 is already on the release branch. Original changelog fragments are included for every touched package.Type of change
Validation
ISAACLAB_CHANGELOG_BASE_REF=upstream/release/3.1.0.git diff --check upstream/release/3.1.0passes; all three stable patch IDs match their source commits.run-ciand completed on final headeae44aca5037347a7bd95cb2a5fdc5447c29eb25: 54 passed, 7 skipped/neutral, no failures or pending checks.run-cicommand.Checklist