From 820eac7f584fb17e8ba18b88656176b0b8eca2ff Mon Sep 17 00:00:00 2001 From: TATP-233 Date: Wed, 2 Dec 2026 15:47:18 +0800 Subject: [PATCH] docs: refresh current user and developer guides --- CONTRIBUTING.md | 10 +- README_zh.md | 17 +- docs/README.md | 13 +- docs/flashsac_dp.md | 9 +- docs/sphinx/README.md | 72 +++++---- docs/sphinx/source/adr/ADR-0000-index.md | 10 +- ...p-collector-cuda-graph-integration-only.md | 4 + docs/sphinx/source/adr/ADR-TEMPLATE.md | 2 +- docs/sphinx/source/adr/README.md | 50 +----- .../sphinx/source/api_reference/base/index.md | 11 +- docs/sphinx/source/api_reference/index.md | 7 +- docs/sphinx/source/changelog.md | 14 ++ docs/sphinx/source/conf.py | 3 + docs/sphinx/source/en/0-index.md | 6 +- .../source/en/1-getting_started/0-index.md | 2 +- .../en/1-getting_started/2-installation.md | 43 ++--- .../3-evaluation_and_playback.md | 10 +- .../1-getting_started/4-project_structure.md | 7 +- .../source/en/1-getting_started/5-faq.md | 14 +- .../en/2-user_guide/1-training/0-index.md | 4 +- .../1-training/1-cli_reference.md | 36 +++-- .../2-user_guide/1-training/2-hydra_config.md | 2 +- .../en/2-user_guide/1-training/3-logging.md | 33 ++-- .../1-training/4-tensor_runtime.md | 22 +-- .../1-training/5-resume_and_checkpoints.md | 31 ++-- .../1-training/7-tensor_runtime_production.md | 36 +++-- .../1-training/8-sync_free_autoreset.md | 4 +- .../en/2-user_guide/2-algorithms/1-ppo.md | 6 +- .../en/2-user_guide/2-algorithms/2-appo.md | 7 +- .../en/2-user_guide/2-algorithms/3-sac.md | 65 +++++--- .../2-user_guide/2-algorithms/4-flash_sac.md | 43 ++++- .../en/2-user_guide/3-backends/0-index.md | 33 ++-- .../en/2-user_guide/3-backends/1-mujoco.md | 5 +- .../en/2-user_guide/3-backends/2-motrix.md | 11 +- .../en/2-user_guide/3-backends/3-isaacgym.md | 19 +-- .../en/2-user_guide/3-backends/4-isaacsim.md | 26 ++-- .../en/2-user_guide/3-backends/5-genesis.md | 33 ++-- .../en/2-user_guide/3-backends/6-drake.md | 10 +- .../en/2-user_guide/3-backends/7-newton.md | 15 +- .../en/2-user_guide/3-backends/8-superdex.md | 38 ++--- .../2-user_guide/4-tasks/2-motion_tracking.md | 27 ++-- .../5-domain_randomization/0-index.md | 44 +++--- .../5-domain_randomization/1-configuration.md | 15 +- .../2-field_reference.md | 38 +++-- .../en/2-user_guide/6-terrain/0-index.md | 6 +- .../en/2-user_guide/6-terrain/1-procedural.md | 32 ++-- .../6-terrain/2-heightfield_import.md | 11 +- .../2-user_guide/7-tooling/1-onnx_export.md | 9 +- .../en/2-user_guide/7-tooling/2-wandb.md | 3 +- .../7-tooling/3-nan_visualizer.md | 14 +- .../2-user_guide/7-tooling/5-robot_import.md | 5 +- docs/sphinx/source/en/3-deployment/0-index.md | 27 +++- .../3-deployment/1-sim_to_real/1-overview.md | 18 ++- .../1-sim_to_real/2-g1_whole_body.md | 147 +++++++++--------- .../1-sim_to_real/3-go2_locomotion.md | 54 ++++--- .../1-sim_to_real/5-onnx_runtime.md | 40 +++-- .../1-sim_to_real/6-domain_randomization.md | 18 ++- .../1-sim_to_real/7-safety_layers.md | 69 ++++---- .../1-sim_to_real/8-latency_budget.md | 54 ++++--- .../1-sim_to_real/9-troubleshooting.md | 57 +++---- .../en/3-deployment/2-sim_to_sim/0-index.md | 8 +- .../2-sim_to_sim/1-backend_swap.md | 69 ++++---- .../2-sim_to_sim/2-owner_yaml_swap.md | 125 +++++++++------ .../3-contact_and_friction_alignment.md | 65 +++++--- .../2-sim_to_sim/4-reward_parity.md | 78 ++++++---- .../5-playback_and_snapshot_differences.md | 85 ++++++---- .../2-sim_to_sim/6-capability_gaps.md | 87 +++++++---- .../2-sim_to_sim/7-config_guard.md | 131 +++++++++++----- .../3-framework_migration/0-index.md | 4 +- .../3-framework_migration/1-from_isaac_lab.md | 109 ++++++------- .../2-from_legged_gym.md | 76 +++++---- .../3-framework_migration/3-from_rsl_rl.md | 93 +++++++---- .../3-framework_migration/4-from_skrl.md | 57 ++++--- .../5-task_config_translation.md | 65 ++++---- .../3-framework_migration/7-from_unilab_rl.md | 18 ++- .../source/en/4-developer_guide/0-index.md | 7 + .../1-architecture/1-overview.md | 21 +-- .../1-architecture/2-runtime_model.md | 20 ++- .../1-architecture/3-layer_boundaries.md | 14 +- .../1-architecture/4-scene_composition.md | 30 ++-- .../1-architecture/5-registry.md | 6 +- .../1-architecture/6-manager_based_api.md | 16 +- .../2-contracts/1-env_contract.md | 28 ++-- .../2-contracts/3-task_owner.md | 11 +- .../4-developer_guide/3-extending/0-index.md | 2 +- .../3-extending/1-new_task.md | 52 ++++--- .../3-extending/2-new_backend.md | 66 +++++--- .../3-extending/3-new_algorithm.md | 63 +++++--- .../3-extending/4-new_terrain.md | 14 +- .../en/4-developer_guide/4-contributing.md | 27 ++-- .../5-contributing_workflow.md | 8 +- .../6-agent_quick_reference.md | 5 +- .../en/4-developer_guide/7-motion_assets.md | 20 ++- .../8-tensor_runtime_production.md | 2 +- .../9-sim2sim_contract_status.md | 58 +++++++ .../source/en/6-how_to/1-onboard_new_robot.md | 45 ++++-- .../source/en/6-how_to/2-custom_reward.md | 54 +++++-- .../en/6-how_to/3-training_diagnostics.md | 106 ++++++++++--- docs/sphinx/source/en/why_unilab.md | 4 +- docs/sphinx/source/zh_CN/0-index.md | 6 +- .../source/zh_CN/1-getting_started/0-index.md | 2 +- .../zh_CN/1-getting_started/1-quick_demo.md | 4 +- .../zh_CN/1-getting_started/2-installation.md | 44 +++--- .../3-evaluation_and_playback.md | 11 +- .../1-getting_started/4-project_structure.md | 7 +- .../source/zh_CN/1-getting_started/5-faq.md | 14 +- .../zh_CN/2-user_guide/1-training/0-index.md | 4 +- .../1-training/1-cli_reference.md | 28 ++-- .../2-user_guide/1-training/2-hydra_config.md | 2 +- .../2-user_guide/1-training/3-logging.md | 33 ++-- .../1-training/4-tensor_runtime.md | 19 +-- .../1-training/5-resume_and_checkpoints.md | 19 ++- .../1-training/7-tensor_runtime_production.md | 31 ++-- .../zh_CN/2-user_guide/2-algorithms/1-ppo.md | 4 +- .../zh_CN/2-user_guide/2-algorithms/2-appo.md | 6 +- .../zh_CN/2-user_guide/2-algorithms/3-sac.md | 37 ++--- .../2-user_guide/2-algorithms/4-flash_sac.md | 35 ++++- .../zh_CN/2-user_guide/3-backends/0-index.md | 33 ++-- .../zh_CN/2-user_guide/3-backends/1-mujoco.md | 3 +- .../zh_CN/2-user_guide/3-backends/2-motrix.md | 10 +- .../2-user_guide/3-backends/3-isaacgym.md | 14 +- .../2-user_guide/3-backends/4-isaacsim.md | 21 +-- .../2-user_guide/3-backends/5-genesis.md | 24 +-- .../zh_CN/2-user_guide/3-backends/6-drake.md | 8 +- .../zh_CN/2-user_guide/3-backends/7-newton.md | 19 +-- .../2-user_guide/3-backends/8-superdex.md | 33 ++-- .../2-user_guide/4-tasks/2-motion_tracking.md | 23 +-- .../5-domain_randomization/0-index.md | 50 +++--- .../5-domain_randomization/1-configuration.md | 12 +- .../2-field_reference.md | 33 ++-- .../zh_CN/2-user_guide/6-terrain/0-index.md | 4 +- .../2-user_guide/6-terrain/1-procedural.md | 29 ++-- .../6-terrain/2-heightfield_import.md | 8 +- .../2-user_guide/7-tooling/1-onnx_export.md | 8 +- .../zh_CN/2-user_guide/7-tooling/2-wandb.md | 2 +- .../7-tooling/3-nan_visualizer.md | 11 +- .../2-user_guide/7-tooling/5-robot_import.md | 3 +- .../source/zh_CN/3-deployment/0-index.md | 26 +++- .../3-deployment/1-sim_to_real/1-overview.md | 17 +- .../1-sim_to_real/2-g1_whole_body.md | 120 +++++++------- .../1-sim_to_real/3-go2_locomotion.md | 52 ++++--- .../1-sim_to_real/5-onnx_runtime.md | 29 ++-- .../1-sim_to_real/6-domain_randomization.md | 15 +- .../1-sim_to_real/7-safety_layers.md | 57 +++---- .../1-sim_to_real/8-latency_budget.md | 41 +++-- .../1-sim_to_real/9-troubleshooting.md | 51 +++--- .../3-deployment/2-sim_to_sim/0-index.md | 6 +- .../2-sim_to_sim/1-backend_swap.md | 62 ++++---- .../2-sim_to_sim/2-owner_yaml_swap.md | 101 +++++++----- .../3-contact_and_friction_alignment.md | 54 ++++--- .../2-sim_to_sim/4-reward_parity.md | 60 ++++--- .../5-playback_and_snapshot_differences.md | 58 ++++--- .../2-sim_to_sim/6-capability_gaps.md | 79 ++++++---- .../2-sim_to_sim/7-config_guard.md | 91 +++++++---- .../3-framework_migration/0-index.md | 4 +- .../3-framework_migration/1-from_isaac_lab.md | 97 ++++++------ .../2-from_legged_gym.md | 59 ++++--- .../3-framework_migration/3-from_rsl_rl.md | 70 +++++---- .../3-framework_migration/4-from_skrl.md | 47 +++--- .../5-task_config_translation.md | 62 ++++---- .../3-framework_migration/7-from_unilab_rl.md | 13 +- .../source/zh_CN/4-developer_guide/0-index.md | 6 + .../1-architecture/1-overview.md | 11 +- .../1-architecture/3-layer_boundaries.md | 12 +- .../1-architecture/4-scene_composition.md | 29 ++-- .../1-architecture/5-registry.md | 4 +- .../1-architecture/6-manager_based_api.md | 11 +- .../2-contracts/1-env_contract.md | 25 +-- .../2-contracts/3-task_owner.md | 12 +- .../4-developer_guide/3-extending/0-index.md | 8 +- .../3-extending/1-new_task.md | 49 +++--- .../3-extending/2-new_backend.md | 54 ++++--- .../3-extending/3-new_algorithm.md | 52 ++++--- .../3-extending/4-new_terrain.md | 12 +- .../zh_CN/4-developer_guide/4-contributing.md | 22 ++- .../5-contributing_workflow.md | 5 +- .../6-agent_quick_reference.md | 5 +- .../4-developer_guide/7-motion_assets.md | 17 +- .../8-tensor_runtime_production.md | 2 +- .../9-sim2sim_contract_status.md | 145 ++++++++--------- .../zh_CN/6-how_to/1-onboard_new_robot.md | 40 +++-- .../source/zh_CN/6-how_to/2-custom_reward.md | 49 ++++-- .../zh_CN/6-how_to/3-training_diagnostics.md | 95 ++++++++--- docs/sphinx/source/zh_CN/why_unilab.md | 3 +- scripts/motion/README.md | 43 +++++ 185 files changed, 3571 insertions(+), 2285 deletions(-) create mode 100644 docs/sphinx/source/en/4-developer_guide/9-sim2sim_contract_status.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index da62457b4..fb9896b83 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,13 +6,13 @@ Languages: English | [简体中文](docs/sphinx/source/zh_CN/4-developer_guide/4 1. Fork and clone the repository. 2. Install dependencies for your platform: - - macOS (MPS, installs PyPI torch wheels): `make setup-motrix` (or `make setup-mujoco`) + - macOS (MPS, installs PyPI torch wheels): `uv sync --extra motrix` (or `uv sync --extra mujoco`) - Linux default (installs PyTorch cu130 wheels; requires an NVIDIA GPU/driver supported by current PyTorch cu130 wheels): `make setup` - Linux AMD / ROCm workstation: `make sync-rocm`, then run commands with `uv run --no-sync ...` - For direct uv setup, use `uv sync --extra mujoco --extra motrix`; replace it with `--extra mujoco` or `--extra motrix` for a single backend - - Physics adapters are supplied by the production PyPI package - `unisim-core>=0.1.14` (import namespace `unisim`). + - Physics adapters are supplied by the pinned production PyPI package + `unisim-core` (import namespace `unisim`). 3. Create a branch such as `git checkout -b docs/improve-readme` or `git checkout -b fix/backend-bug`. ## Development Rules @@ -34,7 +34,7 @@ Languages: English | [简体中文](docs/sphinx/source/zh_CN/4-developer_guide/4 ```bash make format # ruff format + ruff check --fix -make sync-rocm # Linux AMD / ROCm >= 7.1: sync deps and install torch==2.11.0+rocm7.2 +make sync-rocm # Linux AMD / ROCm: sync the ROCm dependency track make type # mypy src/unilab + pyright make check # format + type (required before code-related commits) make test # non-slow tests @@ -64,7 +64,7 @@ under the bilingual subsections `### Added / 新增`, `### Changed / 变更`, or `### Fixed / 修复` (create the subsection when it is missing). Entries follow the released-version style below: English prose first, then the Chinese translation, with the driving GitHub issue or PR linked (for example -`([#706](https://github.com/Motphys/UniLab/issues/706))`). Purely internal +`([#706](https://github.com/unilabsim/UniLab/issues/706))`). Purely internal changes (refactors, test-only, or CI plumbing) may skip the changelog. Release maintainers rename `## Unreleased` to the version number and PyPI upload date at release time. diff --git a/README_zh.md b/README_zh.md index 53aaa7cac..63729dd9d 100644 --- a/README_zh.md +++ b/README_zh.md @@ -100,19 +100,29 @@ uv run --extra genesis eval --algo flashsac --task g1_motion_tracking --sim gene ``` 使用 MPS 时,先为每张选中的 GPU 手动启动服务,在训练命令后追加 -`training.cuda_process_sharing=mps`,训练结束后再手动关闭。例如 GPU 0、1: +`training.cuda_process_sharing=mps`,训练结束后再手动关闭。 +`uv run uni-cumps status` 可随时列出可见 GPU 和所有已登记服务。例如 GPU 0、1: ```bash +uv run uni-cumps status # 可见 GPU + 已登记服务 uv run uni-cumps start --gpus 0 --name train-gpu0 --daemon uv run uni-cumps start --gpus 1 --name train-gpu1 --daemon CUDA_VISIBLE_DEVICES=0,1 \ uv run --extra mjwarp train --algo flashsac --task g1_motion_tracking --sim mjwarp \ training.cuda_process_sharing=mps # 执行训练,等训练进程退出后,仅关闭上述服务。 -uv run uni-cumps stop --name train-gpu0 -uv run uni-cumps stop --name train-gpu1 +uv run uni-cumps stop --name train-gpu0 # 或:stop --gpus 0 +uv run uni-cumps stop --name train-gpu1 # 或:stop --gpus 1 ``` +`stop` 可按 `--name`、`--gpus` 选择,或在恰好有一个存活服务时隐式选择; +`stop --all` 会停止当前用户在这台主机上的所有已登记服务。启动时若不指定 +`--name`,服务名为 `gpu-`;`status` 会打印每个已登记名称及其 GPU。 +UniLab 只停止自己登记的服务(记录位于 `~/.cache/unilab/cuda-mps/`)。如果控制 +daemon 比其记录存活更久,请手动退出,例如 +`echo quit | CUDA_MPS_PIPE_DIRECTORY=/tmp/uni-cumps//pipe CUDA_MPS_LOG_DIRECTORY=/tmp/uni-cumps//log nvidia-cuda-mps-control`, +然后删除对应的 `/tmp/uni-cumps/` 目录。 + 请求 `mps` 后,每个 rank 会自动绑定本 GPU 已登记的服务(索引形式的 `CUDA_VISIBLE_DEVICES` 会在 CUDA 初始化前被规范为 per-GPU MPS 服务要求的 GPU UUID);`uni-cumps env` 仅供外部启动器使用——训练前不要 `eval` 它,它会把可见性 @@ -134,6 +144,7 @@ recipe,同时消费同一套 task、backend 和 RL contract。目前的下游 - [Sharpa](https://github.com/unilabsim/sharpa_rl_unilab) - [MicroDuck RL](https://github.com/unilabsim/microduck_rl_unilab) - [EngineAI RL](https://github.com/unilabsim/engineai_rl_unilab) +- [Unitree RL](https://github.com/unilabsim/unitree_rl_unilab) - [Wuji](https://github.com/unilabsim/wuji_unilab) - [Legged Manipulation](https://github.com/unilabsim/legged-manipulation_unilab) - [Cricket-Gym](https://github.com/kishanpb/Cricket-Gym-Unilab) diff --git a/docs/README.md b/docs/README.md index 28b01e168..2cc06e8a6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,8 +1,8 @@ # UniLab Documentation -UniLab 的全部文档源码统一在 [`docs/sphinx/`](sphinx/) 下,通过 Sphinx 构建,部署到 -。站点按版本子路径发布(当前仅 `main/`, -如 `/UniLab-doc/main/en/0-index.html`),根路径自动重定向到 `main/`。 +UniLab 的 Sphinx 站点文档源码统一在 [`docs/sphinx/`](sphinx/) 下,通过 Sphinx 构建,部署到 +。站点按版本子路径发布 +(如 `/UniLab-doc/main/en/0-index.html`),根路径自动重定向到 `main/`。 发布入口: @@ -32,9 +32,10 @@ UniLab 的全部文档源码统一在 [`docs/sphinx/`](sphinx/) 下,通过 Sphin ```bash cd docs/sphinx -uv pip install -r requirements.txt -make html # 一次性构建 -make live # sphinx-autobuild,自动 reload +# 跳过 autodoc 的散文页构建 +UNILAB_DOCS_SKIP_AUTODOC=1 uv run --no-project --with-requirements requirements.txt sphinx-build -b html -n source build/html +# sphinx-autobuild,自动 reload +UNILAB_DOCS_SKIP_AUTODOC=1 uv run --no-project --with-requirements requirements.txt sphinx-autobuild --watch ../../src source build/html -n ``` 详细构建与部署流程见 [`docs/sphinx/README.md`](sphinx/README.md)。 diff --git a/docs/flashsac_dp.md b/docs/flashsac_dp.md index e21e3c57e..ebdfa9960 100644 --- a/docs/flashsac_dp.md +++ b/docs/flashsac_dp.md @@ -6,8 +6,9 @@ This change ports the measured FlashMimic multi-GPU optimization to UniLab 1.5.0 (`03b75353`) with UniSim 2.1.0 (`6994cd1`). The intended PR base is `main`. The requested scope is default DP graph execution and optional BF16 gradient communication; the existing runner owns process lifecycle and synchronization. -No new runner or backend protocol is introduced. Communication remains FP32; -DP graphs default on, with explicit opt-out. The actor/temperature fusion experiment is excluded because +No new runner or backend protocol is introduced. Communication defaults to FP32, +with an explicit BF16 wire-precision option; DP graphs default on, with explicit +opt-out. The actor/temperature fusion experiment is excluded because it did not provide a stable throughput improvement. The proposed contract is recorded in @@ -70,5 +71,5 @@ normalizes index-form visibility entries to GPU UUIDs before CUDA initializes After training clients exit, stop each service with `uv run uni-cumps stop --name train-gpu0`. The default `null` uses independent CUDA contexts. Training does not start or stop services. README documents the -complete examples and optional env, batch, iteration, and transport overrides. -Full repository and current-head remote CI gates remain required before merge. +complete launch and MPS examples. Full repository and current-head remote CI +gates remain required before merge. diff --git a/docs/sphinx/README.md b/docs/sphinx/README.md index 616e1e194..a3774c5a3 100644 --- a/docs/sphinx/README.md +++ b/docs/sphinx/README.md @@ -1,7 +1,8 @@ # UniLab Sphinx Documentation -UniLab 的文档源码全部在这里,**双语平行结构**——`source/en/` 是英文版,`source/zh_CN/` -是中文版,`adr/`、`api_reference/`、`glossary.md`、`changelog.md`、`_static/` 共享。 +UniLab 的文档源码全部在这里,采用**双语平行结构**——`source/en/` 是英文版, +`source/zh_CN/` 是中文版,`adr/`、`api_reference/`、`glossary.md`、`changelog.md`、 +`_static/` 共享。两语言使用相同的编号顶层结构,但不要求每个页面路径严格 1:1 镜像。 CI 在 push to `main` 时用 sphinx-multiversion 构建 Sphinx,通过 deploy key 推到独立仓 [`unilabsim/UniLab-doc`](https://github.com/unilabsim/UniLab-doc) 的 `gh-pages` 分支, @@ -18,33 +19,38 @@ docs/sphinx/ ├── requirements.txt ← Sphinx + 扩展依赖,不含 unilab 本身 └── source/ ├── conf.py ← Sphinx 配置 - ├── index.md ← 根 landing(语言 picker) + ├── index.md ← 根 redirect → en/0-index.html │ ├── _static/ ← 共享:CSS / 图片 / 视频 / teaser - ├── _templates/ ← 共享:autosummary 模板 + ├── _templates/ ← 共享:侧栏与 autosummary 模板 ├── adr/ ← 共享:ADR(中英共用,中文为主) ├── api_reference/ ← 共享:autodoc 驱动(英文,从 src/ docstring 拉) ├── glossary.md ← 共享:术语表 ├── changelog.md ← 共享 │ ├── en/ ← 英文版 - │ ├── index.md ← 英文站根 - │ ├── user_guide/ ← getting_started / backends / algorithms / tasks / DR / terrain / manipulation / tooling - │ ├── developer_guide/ ← architecture / contracts / extending / contributing - │ ├── transfer/ ← sim_to_real / sim_to_sim / framework_migration - │ └── agents/ ← 占位,待写 + │ ├── 0-index.md ← 英文站根 + │ ├── 1-getting_started/ + │ ├── 2-user_guide/ + │ ├── 3-deployment/ + │ ├── 4-developer_guide/ + │ ├── 5-reference/ ← 共享资源的语言本地 wrapper + │ └── 6-how_to/ │ └── zh_CN/ ← 中文版 - ├── index.md ← 中文站根 - ├── user_guide/ ← 01-getting-started / 02-simulation-backends / ... / A-E 速查 - ├── developer_guide/ ← development-standard / collaboration / domain-randomization-contract / ... - ├── transfer/ ← 占位,待写 - └── agents/ ← Agent 速查(中文,01-agent-quick-reference.md) + ├── 0-index.md ← 中文站根 + ├── 1-getting_started/ + ├── 2-user_guide/ + ├── 3-deployment/ + ├── 4-developer_guide/ + ├── 5-reference/ ← 共享资源的语言本地 wrapper + └── 6-how_to/ ``` -URL 模式:`/`(重定向到 `main/en/0-index.html`)、`/main/en/...`、`/main/zh_CN/...`; -历史大版本在 `//en/...`(如 `/v1.5.11/en/...`)。站点按 -版本目录发布,版本目录内两种语言路径 1:1 镜像。 +URL 模式:`/`(重定向到 `main/en/0-index.html`)、`/main/en/...`、 +`/main/zh_CN/...`;历史版本在 `//en/...`(如 `/v1.5.0/en/...`)。 +站点按版本目录发布。语言切换器优先使用同路径页面;路径不镜像时使用 `conf.py` +的 `_LANGUAGE_PATH_FORWARD` 映射,未映射页面回退到目标语言首页。 ## 本地构建 @@ -167,20 +173,18 @@ git push origin gh-pages 详细规则见 [`AGENTS.md`](AGENTS.md)。要点: -1. **双语平行**:英文进 `source/en/
/`,中文进 `source/zh_CN/
/`,**路径 1:1 镜像**(同名文件) -2. **共享内容**:ADR、API reference、glossary、changelog、`_static` 都在根目录共享,不写双语 -3. **跨语言引用**:跨语言时用绝对路径 `//
/`,如 `{doc}`/zh_CN/user_guide/index`` -4. **API 文档 = autodoc**:`api_reference/` 下页面只放 `automodule` / `autosummary`,不写手写表格 -5. **图片放 `_static/`**:Sphinx 下用 `_static/assets/foo.png` 这种路径 -6. **ADR 命名**:`ADR-NNNN-kebab-title.md`,挂到 `adr/README.md` 索引和各语言 developer_guide 的 ADR toctree - -## 已知不全(框架已搭,内容待填) - -- `source/en/user_guide/` 个别页面(中文等价物在 `zh_CN/user_guide/`) -- `source/en/developer_guide/architecture/`、`contracts/`、`extending/` 各页(中文等价物在 `zh_CN/developer_guide/`) -- `source/en/transfer/sim_to_real/` 个别页面 -- `source/zh_CN/transfer/` 全部(等英文稳定后再翻) -- `source/en/agents/` 全部 -- `source/en/agents/` 全部(中文版在 `source/zh_CN/agents/01-agent-quick-reference.md`) - -中文版多数已有完整内容,可作为英文翻译底稿;反过来,英文 transfer 一节内容完整,可作为中文翻译底稿。 +1. **双语平行**:英文进 `source/en/
/`,中文进 `source/zh_CN/
/`; + 同主题优先保持同路径,但不要求两棵树严格 1:1 镜像。新增英文页面如有合适的中文 + 等价页,在 `conf.py` 的 `_LANGUAGE_PATH_FORWARD` 中登记映射。 +2. **共享内容**:ADR、API reference、glossary、changelog、`_static` 都在根目录共享, + 不写双语;语言侧栏通过 `5-reference/` 下的 wrapper 页面链接共享资源,不把共享 + 页面直接加入语言 toctree。 +3. **跨语言引用**:跨语言时用绝对路径 `//
/`,如 + `{doc}`/zh_CN/4-developer_guide/0-index``。 +4. **API 文档 = autodoc**:`api_reference/` 下页面使用 `automodule` / `autoclass` / + `autosummary` 等指令;公共 API 的详细散文写在源码 docstring 中。 +5. **图片放 `_static/`**:Sphinx 下用 `_static/assets/foo.png` 这种路径。 +6. **ADR 命名**:`ADR-NNNN-kebab-title.md`,加入 `adr/ADR-0000-index.md` 索引; + 中英文 `5-reference/4-adr.md` wrapper 只链接共享索引。 + +页面覆盖状态以各语言索引为准。 diff --git a/docs/sphinx/source/adr/ADR-0000-index.md b/docs/sphinx/source/adr/ADR-0000-index.md index cf5123864..e90c7b1a9 100644 --- a/docs/sphinx/source/adr/ADR-0000-index.md +++ b/docs/sphinx/source/adr/ADR-0000-index.md @@ -23,9 +23,11 @@ orphan: true | [ADR-0007 UniSim Extraction Boundary](ADR-0007-unisim-extraction-boundary.md) | Physics package extraction | Accepted | | [ADR-0008 Debug Overlay Primitive Contract And Playback Session](ADR-0008-debug-overlay-primitive-contract-and-playback-session.md) | Debug overlay / playback session | Accepted | | [ADR-0009 SuperDex Native C++ Scene Batch Executor](ADR-0009-superdex-persistent-cpu-workers.md) | Backend CPU scene execution | Accepted | -| [ADR-0010 Fixed Model Variant Ownership Boundary](ADR-0010-fixed-model-variant-ownership-boundary.md) | Fixed variants / cross-repository boundary | Proposed | -| [ADR-0011 Torch-Only Manager-Based Runtime](ADR-0011-torch-only-manager-based-runtime.md) | Manager runtime / tensor lifecycle | Accepted | +| [ADR-0010 Fixed Model Variant Ownership Boundary](ADR-0010-fixed-model-variant-ownership-boundary.md) | Fixed variants / cross-repository boundary | Accepted | +| [ADR-0011 Torch-Only Manager-Based Runtime](ADR-0011-torch-only-manager-based-runtime.md) | Manager runtime / tensor lifecycle | Superseded | | [ADR-0012 Sole Tensor Manager And Scoped Backends](ADR-0012-sole-tensor-manager-and-scoped-backends.md) | Manager runtime / backend scope | Proposed | +| [ADR-0013 CUDA MPS Single-Rank Execution Sharing](ADR-0013-cuda-mps-single-rank-execution-sharing.md) | Training runtime / execution sharing | Proposed | +| [ADR-0014 CUDA MPS CLI Lifecycle Owner](ADR-0014-cuda-mps-cli-lifecycle-owner.md) | Training runtime / host tooling | Proposed | | [ADR-0015 No Numba Runtime And Explicit NumPy Leaf Boundaries](ADR-0015-no-numba-and-explicit-numpy-leaf-boundaries.md) | Runtime dependency / NumPy boundary | Accepted | | [ADR-0016 RL Reintegration Into unilab.rl And Single Distribution](ADR-0016-rl-reintegration-into-unilab-rl.md) | RL packaging / layer ownership | Proposed | | [ADR-0017 FlashSAC Learner-Side Custom Actor Contract](ADR-0017-flashsac-learner-side-custom-actor-contract.md) | RL algorithm extension / checkpoint semantics | Proposed | @@ -57,7 +59,3 @@ orphan: true - 架构总览: {doc}`RL Infrastructure 开发标准 ` - 后端能力和支持矩阵: {doc}`仿真后端 ` - 协作流程与证据标准: {doc}`协作流程 ` - -## Navigation - -- Index: {doc}`Documentation ` diff --git a/docs/sphinx/source/adr/ADR-0231-k1-mjwarp-collector-cuda-graph-integration-only.md b/docs/sphinx/source/adr/ADR-0231-k1-mjwarp-collector-cuda-graph-integration-only.md index 94063d7c0..25135ce3c 100644 --- a/docs/sphinx/source/adr/ADR-0231-k1-mjwarp-collector-cuda-graph-integration-only.md +++ b/docs/sphinx/source/adr/ADR-0231-k1-mjwarp-collector-cuda-graph-integration-only.md @@ -1,3 +1,7 @@ +--- +orphan: true +--- + # ADR-0231 Integration-only K=1 MJWarp collector CUDA graph contract 语言: English diff --git a/docs/sphinx/source/adr/ADR-TEMPLATE.md b/docs/sphinx/source/adr/ADR-TEMPLATE.md index cb555830a..db40a614a 100644 --- a/docs/sphinx/source/adr/ADR-TEMPLATE.md +++ b/docs/sphinx/source/adr/ADR-TEMPLATE.md @@ -38,5 +38,5 @@ orphan: true ## Related Documents -- {doc}`ADR Index ` +- {doc}`ADR Index ` - {doc}`RL Infrastructure 开发标准 ` diff --git a/docs/sphinx/source/adr/README.md b/docs/sphinx/source/adr/README.md index 779d4129f..47b85e16b 100644 --- a/docs/sphinx/source/adr/README.md +++ b/docs/sphinx/source/adr/README.md @@ -6,51 +6,7 @@ orphan: true 语言: 简体中文 -本目录记录 UniLab 的稳定架构决策。这里不跟踪阶段性执行状态,只记录已经落地并作为评审基线的 contract。 +本页保留为旧链接入口。完整且持续维护的 ADR 列表与状态见 +{doc}`ADR 索引 `。 -新增 ADR 使用 [ADR Template](ADR-TEMPLATE.md)。ADR 只记录已经或即将作为 review 基线的结构性决策,不记录阶段性执行状态。 - -## ADR 列表 - -| ADR | Layer / Topic | Status | -|-----|---------------|--------| -| [ADR-0001 Runtime Model And Layer Boundaries](ADR-0001-runtime-model-and-layer-boundaries.md) | Runtime / layering | Accepted | -| [ADR-0002 Backend Capability Boundary For Play And Snapshot](ADR-0002-backend-capability-boundary-for-play-and-snapshot.md) | Backend capability | Accepted | -| [ADR-0003 Task Owner And Config Compose Contract](ADR-0003-task-owner-and-config-compose-contract.md) | Config owner | Accepted | -| [ADR-0004 Registry Bootstrap Contract](ADR-0004-registry-bootstrap-contract.md) | Registry bootstrap | Accepted | -| [ADR-0005 Unified Obs Critic Env And IPC Contract](ADR-0005-unified-obs-critic-env-and-ipc-contract.md) | Observation / IPC | Accepted | -| [ADR-0006 Community Manager API On NumPy Runtime](ADR-0006-community-manager-api-on-numpy-runtime.md) | Manager API / NumPy runtime | Superseded | -| [ADR-0007 UniSim Extraction Boundary](ADR-0007-unisim-extraction-boundary.md) | Physics package extraction | Accepted | -| [ADR-0008 Debug Overlay Primitive Contract And Playback Session](ADR-0008-debug-overlay-primitive-contract-and-playback-session.md) | Debug overlay / playback session | Accepted | -| [ADR-0009 SuperDex Native C++ Scene Batch Executor](ADR-0009-superdex-persistent-cpu-workers.md) | Backend CPU scene execution | Accepted | -| [ADR-0010 Fixed Model Variant Ownership Boundary](ADR-0010-fixed-model-variant-ownership-boundary.md) | Fixed variants / cross-repository boundary | Proposed | -| [ADR-0011 Torch-Only Manager-Based Runtime](ADR-0011-torch-only-manager-based-runtime.md) | Manager runtime / tensor lifecycle | Superseded | -| [ADR-0012 Sole Tensor Manager And Scoped Backends](ADR-0012-sole-tensor-manager-and-scoped-backends.md) | Manager runtime / backend scope | Proposed | -| [ADR-0013 CUDA MPS Single-Rank Execution Sharing](ADR-0013-cuda-mps-single-rank-execution-sharing.md) | Training runtime / execution sharing | Proposed | -| [ADR-0014 CUDA MPS CLI Lifecycle Owner](ADR-0014-cuda-mps-cli-lifecycle-owner.md) | Training runtime / host tooling | Proposed | -| [ADR-0015 No Numba Runtime And Explicit NumPy Leaf Boundaries](ADR-0015-no-numba-and-explicit-numpy-leaf-boundaries.md) | Runtime dependency / NumPy boundary | Accepted | -| [ADR-0238 State-Update-Only CUDA Graph Boundary](ADR-0238-state-update-only-cuda-graph-boundary.md) | Manager runtime / CUDA graph pre-registration | Rejected / no-go | - -## ADR Governance - -每篇 ADR 应包含: - -- `Status` -- `Date` -- `Owners` -- `Supersedes` -- `Superseded by` -- `Alternatives Considered` -- `Evidence In Repo` - -当新 ADR 改写旧决策时,不直接删除旧 ADR;在旧 ADR 的 `Superseded by` 中指向新 ADR,并在新 ADR 的 `Supersedes` 中反向链接。 - -## 与主文档的关系 - -- 架构总览: {doc}`RL Infrastructure 开发标准 ` -- 后端能力和支持矩阵: {doc}`仿真后端 ` -- 协作流程与证据标准: {doc}`协作流程 ` - -## Navigation - -- Index: {doc}`Documentation ` +新增 ADR 使用 {doc}`ADR Template `,并加入上述索引。 diff --git a/docs/sphinx/source/api_reference/base/index.md b/docs/sphinx/source/api_reference/base/index.md index 05f904c67..a77f099bf 100644 --- a/docs/sphinx/source/api_reference/base/index.md +++ b/docs/sphinx/source/api_reference/base/index.md @@ -7,9 +7,9 @@ in this reference, read this one. |---|---| | `TorchEnv` / `TorchEnvState` | The sole environment and state contract | | `SimBackend` | Abstract backend interface (MuJoCo / Motrix implement it) | -| `Registry` | Task / backend / algorithm registration and lookup | -| `Scene` | Cold-path scene materialization | -| `observations`, `final_observation` | Observation builders & terminal handling | +| `unilab.base.registry` | Environment / backend registration and lookup | +| `SceneCfg` | Cold-path scene declaration and materialization | +| `base.contracts.env` | Dictionary observations and terminal `final_observation` handling | | `curriculum` | Curriculum schedule primitives | ```{eval-rst} @@ -38,13 +38,12 @@ in this reference, read this one. ``` ```{eval-rst} -.. autoclass:: unilab.base.registry.Registry +.. automodule:: unilab.base.registry :members: - :show-inheritance: ``` ```{eval-rst} -.. autoclass:: unilab.base.scene.Scene +.. autoclass:: unilab.base.scene.SceneCfg :members: :show-inheritance: ``` diff --git a/docs/sphinx/source/api_reference/index.md b/docs/sphinx/source/api_reference/index.md index dd6b49500..8b464fc49 100644 --- a/docs/sphinx/source/api_reference/index.md +++ b/docs/sphinx/source/api_reference/index.md @@ -24,7 +24,7 @@ read this section on the live site. :link: base/index :link-type: doc The contracts everything else depends on: `TorchEnv`, `SimBackend`, -`Registry`, and `Scene`. +`registry`, and `SceneCfg`. ::: :::{grid-item-card} 🧪 `unilab.envs` @@ -65,10 +65,10 @@ Runtime helpers, reward bookkeeping, runner orchestration. Shared-memory rollout and replay primitives in `unilab.rl.runtime`. ::: -:::{grid-item-card} 🧮 `unilab.backend` +:::{grid-item-card} 🧮 `unisim.backend` :link: backend/index :link-type: doc -MuJoCo and Motrix adapters that implement `SimBackend`. +UniSim-owned simulation adapters that implement `SimBackend`. ::: :::: @@ -135,7 +135,6 @@ backend/index :hidden: :caption: Subsystems -dr/index terrains/index visualization/index utils/index diff --git a/docs/sphinx/source/changelog.md b/docs/sphinx/source/changelog.md index 8e0b07be8..ca6ca0f75 100644 --- a/docs/sphinx/source/changelog.md +++ b/docs/sphinx/source/changelog.md @@ -13,6 +13,20 @@ UniLab 遵循[语义化版本](https://semver.org/)。本共享页面以中英 PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完整提交历史请参阅 [UniLab 仓库](https://github.com/unilabsim/UniLab)。 +## Unreleased + +### Fixed / 修复 + +- Refreshed the bilingual documentation against the current CLI, owner configs, + backend support evidence, training/runtime behavior, Sim2Sim and Sim2Real + contracts, and extension workflows. Corrected stale commands, dependency + constraints, and support claims; repaired Sphinx navigation and API + references; and added verified motion preprocessing and playback guidance. + 按当前 CLI、owner 配置、后端支持证据、训练与运行时行为、Sim2Sim/Sim2Real + 契约及扩展流程更新双语文档。修正过时命令、依赖约束与支持声明,修复 Sphinx + 导航和 API 引用,并补充经过验证的运动数据预处理与回放指南 + ([#2671](https://github.com/Motphys/UniLab/issues/2671))。 + ## 1.6.4 (2026-11-28) ### Added / 新增 diff --git a/docs/sphinx/source/conf.py b/docs/sphinx/source/conf.py index a60245b86..d5f704c89 100644 --- a/docs/sphinx/source/conf.py +++ b/docs/sphinx/source/conf.py @@ -310,6 +310,9 @@ "en/4-developer_guide/8-tensor_runtime_production": ( "zh_CN/4-developer_guide/8-tensor_runtime_production" ), + "en/4-developer_guide/9-sim2sim_contract_status": ( + "zh_CN/4-developer_guide/9-sim2sim_contract_status" + ), "en/3-deployment/3-framework_migration/7-from_unilab_rl": ( "zh_CN/3-deployment/3-framework_migration/7-from_unilab_rl" ), diff --git a/docs/sphinx/source/en/0-index.md b/docs/sphinx/source/en/0-index.md index 537468113..c4ee313a7 100644 --- a/docs/sphinx/source/en/0-index.md +++ b/docs/sphinx/source/en/0-index.md @@ -182,7 +182,7 @@ flowchart LR env --> backend["SimBackend
unisim-core adapters"] env --> factory["EnvFactory contract"] factory --> runtime["Runner / IPC
unilab.rl async runtime"] - runtime --> learner["Learner
PPO / APPO / SAC"] + runtime --> learner["Learner
PPO / APPO / SAC / FlashSAC"] ``` The load-bearing contracts are documented in @@ -197,8 +197,8 @@ committed benchmark manifest or separate recommendation metadata. | Robot / task family | Algorithm paths with repo evidence | Backend evidence | | --- | --- | --- | -| Go2 joystick | PPO, FlashSAC | PPO has tested MuJoCo and Motrix rows. FlashSAC has MuJoCo owner YAMLs for `go2_joystick_flat`. | -| G1 reference locomotion / tracking | PPO, APPO, SAC | PPO, APPO, and SAC include committed MuJoCo and Motrix owner YAMLs for retained G1 tasks. | +| Go2 joystick | PPO, APPO, FlashSAC | PPO and APPO have tested MuJoCo and Motrix rows. FlashSAC has a tested MuJoCo row for `go2_joystick_flat`. | +| G1 reference locomotion / tracking | PPO, APPO, SAC, FlashSAC | All four algorithm paths include committed MuJoCo and Motrix owner YAMLs for retained G1 tasks. | Unitree production task families are maintained in `unitree_rl_unilab` and are not counted as core repository evidence. diff --git a/docs/sphinx/source/en/1-getting_started/0-index.md b/docs/sphinx/source/en/1-getting_started/0-index.md index 7c6faf609..c4936f9a7 100644 --- a/docs/sphinx/source/en/1-getting_started/0-index.md +++ b/docs/sphinx/source/en/1-getting_started/0-index.md @@ -9,7 +9,7 @@ shortest path to a first smoke run. :::{grid-item-card} Quick Demo :link: 1-quick_demo :link-type: doc -Clone the repo, sync Motrix dependencies, run PPO, then evaluate or demo. +Clone the repo, sync MuJoCo dependencies, run PPO, then evaluate or demo. ::: :::{grid-item-card} Installation diff --git a/docs/sphinx/source/en/1-getting_started/2-installation.md b/docs/sphinx/source/en/1-getting_started/2-installation.md index d5c4c6d27..96e6188b0 100644 --- a/docs/sphinx/source/en/1-getting_started/2-installation.md +++ b/docs/sphinx/source/en/1-getting_started/2-installation.md @@ -36,8 +36,7 @@ uv python install 3.13 ``` UniLab accepts Python `3.10` through `3.13`; `3.13` is the recommended main -environment. External-worker backends are not part of the scoped Manager runtime -during issue #1811. +environment. Choose one core setup path: @@ -106,7 +105,6 @@ cold paths (first use of the owning feature) from Hugging Face dataset repos: - [Robot meshes and textures](https://huggingface.co/datasets/unilabsim/unilab-robots) - [Motion clips](https://huggingface.co/datasets/unilabsim/unilab-motions) - [Scenes](https://huggingface.co/datasets/unilabsim/unilab-scenes) -- [Grasp caches](https://huggingface.co/datasets/unilabsim/unilab-caches) - [Demo checkpoints](https://huggingface.co/datasets/unilabsim/unilab-checkpoints) Pre-fetch robot assets with `uv run unilab-pull-assets`. For mainland China, @@ -115,46 +113,49 @@ is unreachable. ## Backend Extras -The tensor-only Manager runtime currently exposes five production backends -(`mujoco`, `mjwarp`, `genesis`, `newton`, and `motrix`) plus the scoped Drake -owner. Their simulator dependencies are optional. +The CLI currently routes ten backend names: `mujoco`, `mjwarp`, `genesis`, +`newton`, `motrix`, `mtxwarp`, `superdex`, `drake`, `isaacsim`, and `isaacgym`. +Their simulator dependencies are optional. A routable name is not a task support +claim; use the generated support matrix for the evidence grade of each +algorithm/task/backend combination. ```bash # Compatible MuJoCo 4.0-line backends: -uv sync --extra mujoco --extra mjwarp --extra genesis --extra motrix +uv sync --extra mujoco --extra mjwarp --extra genesis --extra motrix --extra mtxwarp -# Newton uses MuJoCo 3.11; sync it separately from the set above: +# Newton and SuperDex use MuJoCo 3.11; sync them separately from the set above: uv sync --extra newton +uv sync --extra superdex ``` | Backend | Install path | Important prerequisites | | --- | --- | --- | | MuJoCo | `make setup` or `uv sync --extra mujoco` | Python >=3.11; installs prebuilt `mjbatch-uni==0.3.3` wheels where available | | MJWarp | `uv sync --extra mujoco --extra mjwarp` | Python >=3.11 and NVIDIA CUDA; on a single-GPU host the current CUDA device is used by default, while multi-GPU topology remains explicit | -| Genesis | `uv sync --extra genesis` | The validated path uses Linux x86_64, an NVIDIA GPU, and the pinned torch/Genesis versions | +| Genesis | `uv sync --extra genesis` | Linux x86_64 with NVIDIA CUDA; Linux ROCm uses HIP Torch and exact `gs.amdgpu` (see the ROCm notes) | | Newton | `uv sync --extra newton` | Linux CUDA with the pinned newton / MuJoCo-Warp / Warp versions; use a separate environment from `mujoco` and `mjwarp` | | Motrix | `uv sync --extra motrix` | CPU-authoritative MotrixSim with packed Torch HOST_BRIDGE transfers | +| Motrix Warp | `uv sync --extra mtxwarp` | CUDA-resident MotrixSim on Linux x86_64 with NVIDIA CUDA | +| SuperDex | `uv sync --extra superdex` | Python 3.12 or 3.13 on Linux x86_64; scoped to the configured PPO `go2_joystick_flat` owner and separate from the MuJoCo 4.0-line extras | | Drake | `make setup-drake` | Local Drake C++ prefix plus the DrakeUni native batch extension; currently scoped to PPO `go2_joystick_flat` | +| IsaacGym | `bash scripts/tools/setup_isaacgym_env.sh` | Isolated external Python 3.8 IsaacGym Preview 4 worker on Linux CUDA | +| IsaacSim | `bash scripts/tools/setup_isaacsim_env.sh` | Isolated external Python 3.11 IsaacSim/IsaacLab worker on Linux CUDA | -The CUDA-resident MotrixSim runtime also has a package install path via -`uv sync --extra mtxwarp` (delegating to UniSim's CUDA MotrixSim extra; Linux -x86-64 with NVIDIA CUDA). The UniLab-side name is `mtxwarp` end to end; the +The UniLab-side name for CUDA-resident MotrixSim is `mtxwarp` end to end; the upstream extra rename is tracked at unilabsim/unisim#578. -The `isaacgym`, `isaacsim`, and `superdex` adapters remain temporarily shelved -by `unisim-core` during issue #1811. Their extras and historical backend pages -are not production support claims and the UniLab train/eval CLI rejects them -until new capability, parity, and support-matrix evidence is provided. - Read the scoped backend pages for runtime variables, renderer requirements, and verification commands: - {doc}`MuJoCo <../2-user_guide/3-backends/1-mujoco>` -- {doc}`MJWarp <../2-user_guide/3-backends/0-index>` +- {doc}`MJWarp and Motrix Warp <../2-user_guide/3-backends/0-index>` - {doc}`Genesis <../2-user_guide/3-backends/5-genesis>` - {doc}`Newton <../2-user_guide/3-backends/7-newton>` - {doc}`Motrix <../2-user_guide/3-backends/2-motrix>` +- {doc}`SuperDex <../2-user_guide/3-backends/8-superdex>` - {doc}`Drake <../2-user_guide/3-backends/6-drake>` +- {doc}`IsaacGym <../2-user_guide/3-backends/3-isaacgym>` +- {doc}`IsaacSim <../2-user_guide/3-backends/4-isaacsim>` ## Algorithm Extras @@ -238,8 +239,8 @@ installing the default torch package, then installs the XPU torch wheel through ROCm notes: -- `make sync-rocm` requires ROCm `>= 7.1` and installs the matching PyTorch wheel - from the repository's ROCm dependency files. +- `make sync-rocm` installs the pinned `torch==2.14.0` and + `triton-rocm==3.8.0` packages from the repository's `rocm7.2` index. - It swaps `pyproject.rocm.toml` / `uv.rocm.lock` in as the active `pyproject.toml` / `uv.lock`, so afterwards you can run bare `uv run ...`. - To return to the default CUDA / macOS profile, run @@ -268,7 +269,7 @@ ROCm notes: ```bash pip install torch==2.14.0 --index-url https://download.pytorch.org/whl/rocm7.2 - pip install unilab + pip install "unilab[unirl]" ``` Intel XPU notes: diff --git a/docs/sphinx/source/en/1-getting_started/3-evaluation_and_playback.md b/docs/sphinx/source/en/1-getting_started/3-evaluation_and_playback.md index ff905add3..4a6b05412 100644 --- a/docs/sphinx/source/en/1-getting_started/3-evaluation_and_playback.md +++ b/docs/sphinx/source/en/1-getting_started/3-evaluation_and_playback.md @@ -19,16 +19,16 @@ uv run demo dance Render modes: - `interactive` — open viewer window (default on macOS Motrix). -- `record` — write MP4 to `runs//playback/`. +- `record` — write `play_video.mp4` in the selected run directory. - `viser` — serve the rollout in a browser-based viser viewer (any backend with physics-state playback: `mujoco`, `mjwarp`, `newton`, `drake`, `superdex`). - `none` — skip rendering, just compute metrics. -For `--sim mujoco --render-mode interactive`, `uv run eval` launches the dedicated -`play_interactive.py` MuJoCo viewer directly. This mode rolls out one environment -so the viewer camera and controls remain interactive; `training.play_env_num` is -ignored. +For `--sim mujoco` or `--sim mjwarp` with `--render-mode interactive`, +`uv run eval` launches the dedicated `play_interactive.py` MuJoCo viewer +directly. This mode rolls out one environment so the viewer camera and controls +remain interactive; `training.play_env_num` is ignored. For `--sim mujoco` / `--sim mjwarp --render-mode viser`, `uv run eval` instead launches `play_viser.py`, serving the rollout at `http://localhost:8080` diff --git a/docs/sphinx/source/en/1-getting_started/4-project_structure.md b/docs/sphinx/source/en/1-getting_started/4-project_structure.md index 4b10b7e76..dc229267d 100644 --- a/docs/sphinx/source/en/1-getting_started/4-project_structure.md +++ b/docs/sphinx/source/en/1-getting_started/4-project_structure.md @@ -6,12 +6,13 @@ changing behavior. | Path | Owner Role | | --- | --- | -| `scripts/` | Thin training and tooling entrypoints. Scripts compose Hydra config and call owner-layer code. | +| `scripts/` | Repository-level developer, benchmark, and support-matrix tooling. | +| `src/unilab/scripts/` | Packaged training and playback entrypoints routed by the top-level CLI. | | `src/unilab/conf/` | Hydra roots and task owner YAMLs. The top-level CLI exposes backend selection as `--task` plus `--sim`, then composes the matching owner YAML. | | `src/unilab/base/` | Registry, env state, scene, and backend contracts. | | `src/unilab/envs/` | Task env implementations and task-specific reset, reward, observation, and DR logic. | | `src/unilab/rl/algos/` | APPO and off-policy algorithm code. | -| `src/unilab/rl/runtime/ipc/` | Shared-memory and async runner primitives. | +| `src/unilab/rl/runtime/` | Async runner, distributed launch, IPC, and off-policy runtime primitives. | | `src/unilab/rl/adapters/` | The direct RSL-RL PPO integration (VecEnv adapter and distributed helpers). | | `src/unilab/training/` | Shared training helpers for logging, playback, seed handling, and config guards. | | `src/unilab/visualization/` | Playback, rendering, NaN inspection, and scene/export utilities. | @@ -33,7 +34,7 @@ Task owner YAMLs are the backend identity. Examples: ```bash uv run train --algo ppo --task go2_joystick_flat --sim mujoco -uv run train --algo ppo --task go2_joystick_flat --sim mujoco +uv run train --algo appo --task go2_joystick_flat --sim mujoco uv run train --algo sac --task g1_walk_flat --sim mujoco ``` diff --git a/docs/sphinx/source/en/1-getting_started/5-faq.md b/docs/sphinx/source/en/1-getting_started/5-faq.md index 79f91e355..2017656d8 100644 --- a/docs/sphinx/source/en/1-getting_started/5-faq.md +++ b/docs/sphinx/source/en/1-getting_started/5-faq.md @@ -40,8 +40,8 @@ watchdog, is in the "Install Error Signatures" section of Python `>=3.10,<3.14` (`pyproject.toml`), with resolved dependency profiles for Linux x86_64, Linux aarch64, and Apple Silicon macOS; `3.13` is the -recommended interpreter. On Windows the `mjbatch` engine ships no wheels, so -the MuJoCo physics backend stays Linux/macOS-only there. ROCm and Intel XPU +recommended interpreter. `mjbatch-uni` ships Windows wheels, but the MuJoCo +physics backend is not a validated Windows support lane. ROCm and Intel XPU use the dedicated `make sync-rocm` / `make sync-xpu` profiles. Details: {doc}`2-installation`. @@ -260,12 +260,14 @@ Moved out of UniLab in 1.2.0: Go2 arm manipulation and HIM-PPO live in Sharpa in-hand and HORA in `sharpa_rl_unilab`; their configs, assets, and scripts were removed from this repository. Release notes: {doc}`/changelog`. -### `import uni_rl` fails / the `unirl` extra is gone +### `import uni_rl` fails / the `uni_rl` extra is gone The unilab-rl package is merged back into this repository as `unilab.rl` -({doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`); the RL stack -ships in the base install and the legacy `uni_rl` extra was removed — do not -pass it to `uv sync` or `pip install`. Import mapping: +({doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`). The RL code ships in the +package, while published-package training dependencies require the `unirl` +extra. Source checkouts install them through uv's default `rl` dependency +group. The legacy `uni_rl` extra was removed — do not pass it to `uv sync` or +`pip install`. Import mapping: {doc}`../3-deployment/3-framework_migration/7-from_unilab_rl`. ### v1.4 reset code raises `TypeError` on `reset_mask` diff --git a/docs/sphinx/source/en/2-user_guide/1-training/0-index.md b/docs/sphinx/source/en/2-user_guide/1-training/0-index.md index 7c6a248fd..b7f83aac0 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/0-index.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/0-index.md @@ -58,10 +58,10 @@ Opt-in fixed-shape autoreset, reset CUDA graph, and `ResetSelection` terms. :::: -## When to Drop to `scripts/train_*.py` +## When to Drop to `src/unilab/scripts/train_*.py` Day-to-day runs should use the unified CLI. Reach for the low-level -`scripts/train_*.py` entrypoints only when you are: +`src/unilab/scripts/train_*.py` entrypoints only when you are: - debugging a specific training stack, - observing Hydra compose behavior directly, or diff --git a/docs/sphinx/source/en/2-user_guide/1-training/1-cli_reference.md b/docs/sphinx/source/en/2-user_guide/1-training/1-cli_reference.md index 5dcc6739a..bbb0aeb9b 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/1-cli_reference.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/1-cli_reference.md @@ -54,7 +54,7 @@ uv run uni-cumps doctor --gpus uv run uni-cumps start --gpus --name uv run uni-cumps env --name uv run uni-cumps stop --name # or: stop --gpus -uv run uni-cumps stop --all # stop every recorded daemon +uv run uni-cumps stop --all # stop every current-user/current-host record ``` See the tensor runtime production guide for ownership, concurrency, and topology @@ -80,8 +80,8 @@ completion: make setup ``` -`make setup` syncs the default environment (`uv sync --extra mujoco --extra -unirl`, with the built-in RL stack) followed by +`make setup` syncs the default environment (`uv sync --extra mujoco`, including +the RL dependency group enabled by default) followed by `uv run --no-sync unilab-complete install`. Choose one setup path for an environment. The install command picks Bash or Zsh from `$SHELL` / platform and only writes user-level rc files. The current shell @@ -125,15 +125,17 @@ uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 \ Supported render modes are `auto`, `interactive`, `record`, `viser`, and `none`. -The MuJoCo interactive mode (`--sim mujoco --render-mode interactive`) routes -directly to `play_interactive.py` and always rolls out one environment. - -For backends with physics-state playback (`mujoco`, `mjwarp`, `newton`, -`drake`, `superdex`), `--render-mode viser` serves the rollout through the -browser-based viser viewer: no local display is required, and macOS runs it -without `mjpython`. Eval routes to the standalone `play_viser.py` viewer; -train runs the same viewer as its post-training playback. viser is a required -dependency; the `viser.*` config group (`viser.port`, `viser.max_envs`, +For MuJoCo and MJWarp (`--sim mujoco` or `--sim mjwarp` with +`--render-mode interactive`), eval routes directly to `play_interactive.py` +and always rolls out one environment. + +For backends that declare physics-state playback, `--render-mode viser` serves +the rollout through the browser-based viser viewer: no local display is +required, and macOS runs it without `mjpython`. The CLI rejects Genesis for +this mode; other backends are checked against the runtime playback capability. +Eval routes to the standalone `play_viser.py` viewer; train runs the same +viewer as its post-training playback. viser is a required dependency; the +`viser.*` config group (`viser.port`, `viser.max_envs`, `viser.display_mode`, `viser.env_idx`) tunes the server and the scene. ## Demo @@ -143,11 +145,11 @@ uv run demo dance uv run demo dance --refresh --device cpu ``` -Available demos: `teaser`, `dance`. -Each demo fetches a pre-trained checkpoint from the -`unilabsim/unilab-checkpoints` Hugging Face dataset on first run and caches it -under `src/unilab/assets/checkpoints//model_0.pt`. Pass `--refresh` to -re-download. +Available demos: `teaser`, `dance`. The `dance` demo fetches a pre-trained +checkpoint from the `unilabsim/unilab-checkpoints` Hugging Face dataset on +first run and caches it under +`src/unilab/assets/checkpoints/dance/model_0.pt`; pass `--refresh` to +re-download. `teaser` is renderer-only and does not use a trained checkpoint. Mainland China users: when `huggingface.co` is unreachable, switch to the community mirror before running the demo: diff --git a/docs/sphinx/source/en/2-user_guide/1-training/2-hydra_config.md b/docs/sphinx/source/en/2-user_guide/1-training/2-hydra_config.md index 67f6a1751..0f16bdf16 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/2-hydra_config.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/2-hydra_config.md @@ -15,7 +15,7 @@ Examples: ```bash uv run train --algo ppo --task go2_joystick_flat --sim mujoco -uv run train --algo ppo --task go2_joystick_flat --sim mujoco +uv run train --algo appo --task go2_joystick_flat --sim mujoco uv run train --algo sac --task g1_walk_flat --sim mujoco ``` diff --git a/docs/sphinx/source/en/2-user_guide/1-training/3-logging.md b/docs/sphinx/source/en/2-user_guide/1-training/3-logging.md index 68e89e472..38e42cfe4 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/3-logging.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/3-logging.md @@ -34,8 +34,9 @@ Run directories default to `logs///`, where | SAC | `logs/sac//` | `src/unilab/conf/sac/config.yaml` | | FlashSAC | `logs/flash_sac//` | `src/unilab/conf/flashsac/config.yaml` | -A run directory is named `YYYY-MM-DD_HH-MM-SS_`, for example -`2026-03-09_18-30-00_mujoco`. Common artifacts include `run_config.json`, +A single-rank run directory is named `YYYY-MM-DD_HH-MM-SS_`, for +example `2026-03-09_18-30-00_mujoco`; automatically named multi-rank runs append +`_gpuxN`. Common artifacts include `run_config.json`, `run_summary.json`, checkpoints, and `play_video.mp4` when that run produced one. Enable W&B with: @@ -47,24 +48,24 @@ uv run train --algo ppo --task go2_joystick_flat --sim mujoco \ ``` Shared fields include `training.wandb_project`, `training.wandb_entity`, -`training.wandb_group`, `training.wandb_name`, `training.wandb_tags`, -`training.wandb_notes`, and `training.wandb_mode`. `ExperimentTracker` writes +`training.wandb_group`, `training.wandb_job_type`, `training.wandb_name`, +`training.wandb_tags`, `training.wandb_notes`, and `training.wandb_mode`. `ExperimentTracker` writes `run_config.json` and `run_summary.json`; RSL-RL PPO also connects its writer in W&B mode. A MuJoCo `play_video.mp4` is uploaded when the run produces one. ## Manager-Based Reward Metrics Manager-Based environments place structured metrics in `info["log"]`. The reward -per-term path differs by training stack: off-policy runs (SAC / FlashSAC / APPO) -publish each term's value through `info["reward_components"]` and log it as -`reward/`; the RSL-RL PPO path does not emit per-term reward keys — its +per-term path differs by training stack: SAC/FlashSAC off-policy runs publish each +term's value through `info["reward_components"]` and log it as `reward/`. +RSL-RL PPO and current Manager-Based APPO do not emit per-term reward keys. PPO's TensorBoard output carries the native aggregate metrics (`Loss/*`, `Perf/*`, `Policy/*`, `Train/*`) plus episode-level UniLab keys. The reward-related keys have the following contract: | Key | Owner | Meaning | | --- | --- | --- | -| `reward/` | UniLab `RewardManager` via the off-policy logging stack | Per-term diagnostic for the current reward computation: the mean across environments of `raw_value * weight`, before `dt` scaling. Emitted by SAC / FlashSAC / APPO runs; not emitted on the PPO (rsl-rl) path | +| `reward/` | UniLab `RewardManager` via the off-policy logging stack | Per-term diagnostic for the current reward computation: the mean across environments of `raw_value * weight`, before `dt` scaling. Emitted by SAC / FlashSAC runs; not emitted by PPO or current Manager-Based APPO | | `Train/mean_reward` | Native RSL-RL PPO logger | Aggregate mean completed-episode return; use this for overall training progress | | `Train/mean_episode_length` | Native RSL-RL PPO logger | Aggregate mean completed-episode length | | `Episode_Termination/` | UniLab `TerminationManager` | Count of reset environments for which that termination term fired; this is a distinct diagnostic and is not a reward | @@ -156,10 +157,10 @@ copy / gather interval instead of treating submit wall time as extra iteration s ### Tags in Existing Runs -Historical TensorBoard event files are not rewritten. Runs made with unilab-rl 1.4.1 -or later use the canonical tags below (source of truth: -`unilab.rl.logging.metric_schema`, with the full migration table in the former -unilab_rl repo's `docs/metrics.md`), while an older run continues to show its retired names: +Historical TensorBoard event files are not rewritten. Runs originally made with +unilab-rl 1.4.1 or later use the canonical tags below (current source of truth: +`unilab.rl.logging.metric_schema`), while an older run continues to show its +retired names: | Old tag | New tag | Note | | --- | --- | --- | @@ -197,15 +198,15 @@ source of truth is `unilab.rl.logging.metric_schema` and | Namespace | Current value | Storage | | --- | ---: | --- | | TensorBoard / W&B metric schema | `metric_schema_version = 1` | top level of `run_summary.json` | -| Runtime process/device/IPC manifest | `runtime_manifest.schema_version = 1` | embedded runtime manifest | +| Runtime process/device/IPC manifest | `runtime_manifest.schema_version = 2` | embedded runtime manifest | | Long-soak monitor artifact | `schema_version = "0.3.0"` | soak JSON artifact | The three values are intentionally independent: bumping the soak monitor artifact does not change metric semantics, and a metric-schema change does not invalidate every runtime-manifest field. The current soak monitor accepts only metric schema 1, -runtime-manifest schema 1, and soak artifact `0.3.0`. +runtime-manifest schema 2, and soak artifact `0.3.0`. -Runtime-manifest v1 freezes the public configuration and lifecycle fields already +Runtime-manifest v2 freezes the public configuration and lifecycle fields already consumed by UniLab: inference ring capacity, collector metric interval, `collector_backend_device`, inference-flight counters, replay-ingress counters/timing, and the CUDA inference IPC event count when that budget exists. `collector_backend_device` @@ -236,7 +237,7 @@ the monitor classification (for example `timeout/stale_tick` or `runtime_manifest.shutdown` mapping when available; it is `null` when teardown could not produce diagnostics. Producer shutdown snapshots are best-effort: they are appended to, and never replace, the original soak failure reason. The -runtime-manifest v1 `shutdown` mapping remains opaque so that this soak +runtime-manifest v2 `shutdown` mapping remains opaque so that this soak artifact contract does not make producer-owned diagnostic extensions stable. Within a major schema version, producers may add optional fields with schema, test, and diff --git a/docs/sphinx/source/en/2-user_guide/1-training/4-tensor_runtime.md b/docs/sphinx/source/en/2-user_guide/1-training/4-tensor_runtime.md index 4228aac35..b4de1abf5 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/4-tensor_runtime.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/4-tensor_runtime.md @@ -6,26 +6,28 @@ are collected into one bounded `RuntimeSettings` object and passed to the off-policy runner. Invalid values, unsupported bounds, and impossible memory combinations therefore fail before collector or learner processes are launched. -This contract covers the scoped single-GPU off-policy runtime. It is not an -autotuner and does not add multi-GPU scaling. +These bounded settings are resolved per rank. The scoped memory-budget and +production evidence is single-GPU; SAC/FlashSAC data-parallel placement is +documented on the algorithm pages. -## Owner defaults and bounds +## Resolver defaults and bounds -| Setting | Default | Valid range or constraint | +| Setting | Default when omitted | Valid range or constraint | | --- | ---: | --- | | `training.inference_slot_capacity` | `1` | Positive integer, at most `16` | | `training.collector_metrics_interval` | `1` | Positive integer, at most `10000` | | `training.replay_ingress_depth` | `2` | Positive integer, at most `16` | | `training.replay_ingress_slot_rows` | `null` | `1` through `algo.num_envs`; `null` means `algo.num_envs` | -| `training.cuda_process_sharing` | `null` | `null` or explicit `mps` for single-rank device-resident CUDA backends (`mjwarp`, `mtxwarp`) | +| `training.cuda_process_sharing` | `null` | `null` or explicit per-rank `mps` for device-resident CUDA backends (`mjwarp`, `mtxwarp`) | | Learner rows per synchronization | `algo.batch_size * algo.updates_per_step` | Constrained by the CUDA memory budget | Values other than `training.cuda_process_sharing` must be exact positive integers. Booleans, strings, floating-point numbers, zero, and negative values fail closed. `training.cuda_process_sharing` accepts only `null` or the explicit -string `mps`. The G1 Motion Tracking / MJWarp owner intentionally overrides only -`collector_metrics_interval` to `100`; all other tensor-runtime defaults remain -as listed above. +string `mps`. The checked-in SAC and FlashSAC owner configs set +`collector_metrics_interval: 32`, overriding the resolver fallback of `1`; the +G1 Motion Tracking / MJWarp owner sets it to `100`. The other resolver defaults +remain as listed above. ## Device semantics and resolution @@ -143,7 +145,9 @@ The runtime manifest records the effective evidence needed to audit a run: - `tensor_memory_budget` records the combined CUDA inference, replay storage, replay ingress, learner batch, and workspace budget calculation. - `cuda_process_sharing` records validated execution-sharing evidence when the - owner explicitly requests `mps`; it is absent for the default `null` mode. + owner explicitly requests `mps`. The default `null` mode still records + best-effort ambient host state, including any transparent environment-level + daemon; see {doc}`7-tensor_runtime_production`. The manifest is written before spawn when a budget decision is made. If an unsafe combination is rejected, the error identifies the offending setting and diff --git a/docs/sphinx/source/en/2-user_guide/1-training/5-resume_and_checkpoints.md b/docs/sphinx/source/en/2-user_guide/1-training/5-resume_and_checkpoints.md index 5d8f9d19b..df39c763c 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/5-resume_and_checkpoints.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/5-resume_and_checkpoints.md @@ -5,16 +5,24 @@ Checkpoint selection is controlled by algorithm-level fields. Use ## Resume Training -PPO/APPO resume from `algo.load_run` directly. Use a run id or `-1` for the -latest run in the relevant log directory: +PPO and APPO resume only when `algo.load_run` makes an explicit selection other +than `-1` (normally a run id). Their default `algo.load_run=-1` means no +training resume; it does not mean "resume the latest run." For example: ```bash uv run train --algo ppo --task go2_joystick_flat --sim mujoco \ - algo.load_run=-1 \ + algo.load_run=2026-10-05_14-28-04_mujoco \ training.no_play=true ``` -Off-policy algorithms (SAC/FlashSAC/WarpSAC) keep resume opt-in so that the +PPO restores its RSL-RL runner state, including logger progress and any +supported environment training state described below. APPO restores the actor, +critic, and optimizer from its own checkpoint format, then synchronizes the +target actor from the restored actor instead of restoring the previous target +actor state. It starts a new run at iteration 1 with new logging progress and +does not restore the rollout ring, environment state, or RNG state. + +Off-policy algorithms (SAC/FlashSAC) keep resume opt-in so that the `algo.load_run=-1` default can never turn a fresh launch into an accidental resume. Set `algo.resume=true` and select the checkpoint with `algo.load_run` (run id or `-1` for the latest run) plus optional `algo.checkpoint` @@ -22,7 +30,6 @@ resume. Set `algo.resume=true` and select the checkpoint with `algo.load_run` ```bash uv run train --algo flashsac --task g1_motion_tracking --sim mjwarp \ - --profile \ algo.resume=true \ algo.load_run=2026-10-05_14-28-04_mjwarp \ training.no_play=true @@ -38,12 +45,14 @@ is not restored. ## Checkpoint Format Support Boundary -PPO/APPO resume loads UniLab-patched rsl-rl checkpoints. A supported -checkpoint carries `unilab_logger_state` (the logger `tot_time` / -`tot_timesteps` counters, required) and, when the task environment publishes -versioned training state, a matching `unilab_env_training_state`. UniLab has -written both keys since the resume-state patch (issue #441, shipped since -v1.0.0), and new checkpoints keep writing them unchanged. +PPO resume loads UniLab-patched RSL-RL checkpoints. A supported PPO checkpoint +carries `unilab_logger_state` (the logger `tot_time` / `tot_timesteps` +counters, required) and, when the task environment publishes versioned +training state, a matching `unilab_env_training_state`. UniLab has written +both keys since the resume-state patch (issue #441, shipped since v1.0.0), +and new checkpoints keep writing them unchanged. These keys and the +fail-closed rules below are specific to PPO, not APPO's native checkpoint +format. Starting with the first UniLab release after 1.3.5 that includes issue #2416, loading fails closed: diff --git a/docs/sphinx/source/en/2-user_guide/1-training/7-tensor_runtime_production.md b/docs/sphinx/source/en/2-user_guide/1-training/7-tensor_runtime_production.md index 244cc922a..a902e1063 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/7-tensor_runtime_production.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/7-tensor_runtime_production.md @@ -31,7 +31,8 @@ For the canonical combination: uv run train --algo flashsac --task g1_motion_tracking --sim mjwarp ``` -the MJWarp owner inherits the MuJoCo FlashSAC owner and resolves to: +the MJWarp and MuJoCo leaves each inherit the same-directory `base.yaml`. +The MJWarp leaf then declares its backend identity and metric interval, resolving to: | Effective setting | Value | | --- | --- | @@ -46,13 +47,13 @@ the MJWarp owner inherits the MuJoCo FlashSAC owner and resolves to: | Scene | `src/unilab/assets/robots/g1/scene_flat.xml` | | Motion | `motions/g1/dance1_subject2_part.npz` | -The MuJoCo owner uses the same 2048-environment training budget, but publishes -collector metrics every step. The MJWarp owner inherits the same canonical DR -(reset-mode model-field randomization plus the linear-velocity interval push) -and only zeroes the angular-velocity kicks, because its selected-row tensor -reset does not negotiate the interval angular root-velocity capability. The -Newton owner does not support reset randomization and sets the canonical DR -terms to `null` explicitly. +The MuJoCo owner uses the same 2048-environment training budget and the root +default `collector_metrics_interval: 32`. Both leaves inherit reset-mode +model-field randomization from the shared base. MuJoCo also keeps the six-axis +interval `push_robot` term, while MJWarp sets it to `null` because its +selected-row tensor reset does not negotiate the interval root-velocity +capability. The Newton owner does not support reset randomization and sets the +canonical DR terms to `null` explicitly. At the current generated evidence grade, FlashSAC / `g1_motion_tracking` / MJWarp is `Configured`. A successful local soak does not @@ -94,8 +95,9 @@ already-required rank-local topology. It is not a backend switch and does not replace `--sim mjwarp` or owner YAML selection. The default remains `null`: learner and collector keep independent CUDA contexts. -The supported initial topology is Linux, NVIDIA CUDA, one physical GPU, MJWarp, -SAC/FlashSAC, and `world_size=1`. Request shared GPU execution with: +This guide's canonical topology is Linux, NVIDIA CUDA, one physical GPU, MJWarp, +SAC/FlashSAC, and `world_size=1`. Validation is performed per rank and also +accepts MJWarp/MTXWarp DP ranks. Request shared GPU execution with: ```bash training.cuda_process_sharing=mps @@ -209,13 +211,15 @@ kind, the answering server PID, and best-effort learner/collector GPU UUIDs — with `ambient_server=true` when an environment-level daemon answered at the effective control pipe, so a transparent-MPS run is identifiable from its own manifest. Ambient observation never fails closed; unresolvable facts record -`null`. The section is a runtime-manifest v1 producer diagnostic, not a +`null`. The section is a runtime-manifest v2 producer diagnostic, not a stable scalar contract. MPS changes only GPU execution sharing. It does not change -`env_steps_per_sync`, learner/collector placement, or training semantics. -Multi-GPU DP remains unsupported until its separate gate and daemon topology -decision are completed. CUDA MPS remains host- and deployment-dependent: in +`env_steps_per_sync`, learner/collector placement, or training semantics. For +multi-GPU DP, each rank requires an existing daemon covering its own GPU; +`uni-cumps` accepts only one GPU selector per invocation and does not provision +a DP daemon topology in one command. This guide does not provide a multi-GPU +MPS production recipe. CUDA MPS remains host- and deployment-dependent: in shared containers, multi-user hosts, or restricted runners, control may be unavailable, and an explicit request fails closed rather than silently degrading. @@ -275,7 +279,7 @@ unavailable marker, never a bare `null`: ``` Like `runtime_manifest.cuda_process_sharing`, this section is a -runtime-manifest v1 producer diagnostic, not a stable scalar contract; the +runtime-manifest v2 producer diagnostic, not a stable scalar contract; the runtime manifest schema (`unilab.rl.logging.runtime_manifest_schema`) validates the section fail-closed when it is present. The diagnostics are observability only: they do not change CUDA graph @@ -365,7 +369,7 @@ The run directory must contain: - progress files consumed by the soak monitor. `run_summary.json` must carry metric schema `1` and an embedded runtime-manifest -schema `1`. The manifest records effective runtime limits, inference and tensor +schema `2`. The manifest records effective runtime limits, inference and tensor memory budgets when a budget decision is made, the collector/backend device, inference-flight state, replay-ingress state, shutdown diagnostics, and the backend tensor runtime diagnostics (`runtime_manifest.backend_diagnostics`; PPO diff --git a/docs/sphinx/source/en/2-user_guide/1-training/8-sync_free_autoreset.md b/docs/sphinx/source/en/2-user_guide/1-training/8-sync_free_autoreset.md index f55b3d6c0..f8ae396fd 100644 --- a/docs/sphinx/source/en/2-user_guide/1-training/8-sync_free_autoreset.md +++ b/docs/sphinx/source/en/2-user_guide/1-training/8-sync_free_autoreset.md @@ -24,8 +24,8 @@ Implementation: `src/unilab/base/torch_env.py`, motion body rewards and the anchor/body height terminations) already opt in. - For the CUDA graph: a CUDA env device, and a backend that declares the `external_graph_capture` capability and implements - `torch_graph_capture_scope`. MJWarp does both from `unisim-core` 2.7.2, the - pinned version. + `torch_graph_capture_scope`. MJWarp provides both in the pinned + `unisim-core` 2.9.0 release. ## Configuration flags diff --git a/docs/sphinx/source/en/2-user_guide/2-algorithms/1-ppo.md b/docs/sphinx/source/en/2-user_guide/2-algorithms/1-ppo.md index ff5ba1574..0a1ac06c4 100644 --- a/docs/sphinx/source/en/2-user_guide/2-algorithms/1-ppo.md +++ b/docs/sphinx/source/en/2-user_guide/2-algorithms/1-ppo.md @@ -87,9 +87,9 @@ This is the upstream RSL-RL distributed semantic, not global-rollout PPO. The integrated launcher is single-node only. The repository has two-GPU MuJoCo smoke coverage for `go2_joystick_flat` and `g1_motion_tracking`; this does not -claim multi-node or Motrix multi-GPU support. On the currently validated RTX -6000D host, the launcher inherits the production NCCL compatibility defaults -`NCCL_P2P_DISABLE=1` and `NCCL_SHM_DISABLE=1`; explicit environment values win. +claim multi-node or Motrix multi-GPU support. The launcher sets the NCCL +compatibility defaults `NCCL_P2P_DISABLE=1` and `NCCL_SHM_DISABLE=1`; explicit +environment values win. ## Configuration reference diff --git a/docs/sphinx/source/en/2-user_guide/2-algorithms/2-appo.md b/docs/sphinx/source/en/2-user_guide/2-algorithms/2-appo.md index 910a52a47..539e0ffcb 100644 --- a/docs/sphinx/source/en/2-user_guide/2-algorithms/2-appo.md +++ b/docs/sphinx/source/en/2-user_guide/2-algorithms/2-appo.md @@ -30,7 +30,10 @@ uv run eval --algo appo --task go2_joystick_flat --sim mujoco --load-run -1 ## Runtime Model -- The collector runs CPU simulation while the learner runs GPU training. +- A collector subprocess steps the selected backend and runs actor/critic + inference on `training.collector_device`; `null` follows the learner device. + Backend and Manager tensor placement are resolved separately rather than + being fixed to CPU simulation. - Rollouts are published into a replay queue that the learner consumes. - APPO applies a V-trace importance-sampling correction, so its update semantics differ from synchronous PPO. @@ -100,7 +103,7 @@ uv run train --algo appo --task go2_joystick_flat --sim mujoco \ | `algo.algorithm.enable_compile` | bool | true | torch.compile on the learner update; the built-in `src/unilab/conf/appo/config.yaml` ships `false` | | `algo.seed` | int | 1 | Random seed | | `training.collector_device` | str / null | null | Collector device; null follows the learner | -| `training.replay_queue_size` | int / null | null | Learner-side replay cache depth | +| `training.replay_queue_size` | int / null | null | Learner-side staging depth; null uses the runner default of 3 (the shared rollout ring separately has 4 slots) | | `training.log_interval` | int | 1 | TensorBoard/W&B scalar reporting interval in iterations | ### Policy performance diff --git a/docs/sphinx/source/en/2-user_guide/2-algorithms/3-sac.md b/docs/sphinx/source/en/2-user_guide/2-algorithms/3-sac.md index 5b05f5aac..2d0b5c56e 100644 --- a/docs/sphinx/source/en/2-user_guide/2-algorithms/3-sac.md +++ b/docs/sphinx/source/en/2-user_guide/2-algorithms/3-sac.md @@ -44,20 +44,46 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ training.no_play=true ``` -## Single-node multi-GPU device placement +## Single-node multi-GPU data parallelism -`CUDA_VISIBLE_DEVICES` is the sole GPU topology source. Each parent entry maps to one -rank, and within that rank the learner, collector, inference ring, replay ingress, and -backend payload all use the same physical GPU as local `cuda:0`. Off-policy collectors -never consume another rank's device or a parent-global CUDA ordinal. +`CUDA_VISIBLE_DEVICES` is the sole GPU topology source. Each parent entry maps to +one rank; rank 0 spawns the other ranks, and every rank uses its local `cuda:0`: -IsaacGym, IsaacSim, and Genesis receive the rank-local simulator ordinal through the -environment override. Genesis binds its process-wide session before initialization. +```bash +export CUDA_VISIBLE_DEVICES=, +uv run train --algo sac --task g1_walk_flat --sim mujoco \ + training.no_play=true +``` -MuJoCo has a committed multi-GPU scaling benchmark. The mjwarp per-rank placement contract is -covered by `tests/base/backend/test_process_device.py` and the off-policy runner/worker unit -tests; the repository does not currently contain an mjwarp multi-GPU throughput or convergence -benchmark. +Each rank owns one learner and one collector. Rank 0 broadcasts the actor, +critics, target critics, and temperature once at startup. Before each actual +optimizer step, the corresponding flat gradients are synchronously averaged +with `all_reduce(SUM) / world_size`; replay data is not exchanged. `algo.num_envs`, +`algo.batch_size`, and `algo.updates_per_step` are per-rank values. + +The learner, collector, probe environment, replay, inference ring, and backend +payload in one rank share the same physical GPU. Rank 0 alone owns the terminal, +TensorBoard/W&B output, checkpoints, and run metadata. Automatically named +multi-rank run directories append `_gpuxN`. Collector CPU affinity is partitioned +per rank by default; `training.dp_collector_cpu_ids` supplies explicit per-rank +CPU ids. + +Current limits and implementation details: + +- The integrated launcher is single-node and uses a run-directory FileStore. + For NCCL compatibility it defaults `NCCL_P2P_DISABLE=1` and + `NCCL_SHM_DISABLE=1`; explicit environment values win. These flags do not + select a particular network interface. +- Attaching DP gradient synchronization makes SAC leave its learner-owned + whole-cycle CUDA graph path. DP gradient averaging remains in the per-update + path; `algo.algo_params.use_compile=true` does not imply SAC DP whole-cycle + capture. +- IsaacGym, IsaacSim, and Genesis receive the rank-local simulator ordinal. + Genesis binds its process-wide session before `gs.init`. +- MuJoCo has a committed multi-GPU scaling benchmark. MJWarp per-rank placement + is covered by `tests/base/backend/test_process_device.py` and off-policy + runner/worker unit tests, but the repository has no MJWarp multi-GPU + throughput or convergence benchmark. ## Configuration reference @@ -75,17 +101,17 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ | Override key | Type | Default | Practical effect | | --- | --- | --- | --- | -| `algo.num_envs` | int | 4096 | Parallel collector environments | -| `algo.batch_size` | int | 8192 | Learner batch per update | +| `algo.num_envs` | int | 4096 | Parallel collector environments per rank | +| `algo.batch_size` | int | 8192 | Learner batch per update per rank | | `algo.replay_buffer_n` | int | 512 | Replay capacity in env-vector sweeps (rows = n × num_envs) | -| `algo.updates_per_step` | int | 4 | Learner updates per env step | +| `algo.updates_per_step` | int | 4 | Learner updates per env step per rank | | `algo.learning_starts` | int | 1 | Env-vector sweeps to collect before learner updates start | -| `algo.policy_frequency` | int | 4 | One actor/target update every N learner updates | +| `algo.policy_frequency` | int | 4 | One actor/temperature update every N learner updates; the target critic updates every learner update by default | | `algo.max_iterations` | int | 500 | Number of training iterations | | `algo.save_interval` | int | 500 | Checkpoint save interval in iterations | -| `algo.algo_params.use_compile` | bool | true | torch.compile on the learner update | +| `algo.algo_params.use_compile` | bool | true | torch.compile on the learner update; NVIDIA CUDA always uses the validated compiled path, while `false` is an opt-out only on compatibility tiers | | `algo.seed` | int | 1 | Random seed | -| `training.use_amp` | bool | true | bf16 autocast on the learner update path | +| `training.use_amp` | bool | true | Enable device-supported AMP; the dtype and device gates are controlled by `algo.algo_params.amp_dtype` | | `training.log_interval` | int | 1 | TensorBoard/W&B scalar reporting interval in iterations | ### Policy performance @@ -105,7 +131,7 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.alpha_init` | float | 0.01 | Initial entropy temperature | | `algo.algo_params.target_entropy_ratio` | float | 0.0 | Target entropy = −action_dim × ratio (0.0 → target 0) | | `algo.algo_params.max_grad_norm` | float | 0.0 | Gradient norm clip; 0 disables clipping | -| `algo.algo_params.amp_dtype` | str | auto | AMP dtype under `training.use_amp` | +| `algo.algo_params.amp_dtype` | str | auto | AMP dtype: `auto` selects bf16 on CUDA; Apple MPS requires explicit `bf16` plus a runtime capability probe (auto disables AMP there). CUDA `fp16` uses GradScaler and is incompatible with the whole-cycle graph | ### Training runtime (`training:` section) @@ -115,7 +141,8 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ | `training.play_only` | bool | false | Skip training and only play a checkpoint | | `training.export_onnx` | bool | true | Export `policy.onnx` during playback | | `training.cuda_process_sharing` | str / null | null | null = independent CUDA contexts; `mps` requests CUDA MPS (user-managed daemon via `uni-cumps`) | -| `training.dp_gradient_wire_dtype` | str | float32 | Gradient wire dtype for multi-GPU averaging; `bfloat16` compresses | +| `training.dp_gradient_wire_dtype` | str | float32 | Multi-GPU gradient wire dtype; `bfloat16` compresses only FP32 groups with at least 1024 elements, restores FP32 before averaging, and changes precision independently of AMP | +| `training.replay_storage_dtype` | str | float16 | Device replay storage: `float16` quantizes obs/action/critic columns while keeping rewards/dones/truncated in FP32 and up-casting sampled batches to FP32; `float32` keeps the full-FP32 ring | | `training.nan_guard.enabled` | bool | true | Detect non-finite tensors and dump diagnostics | | `training.nan_guard.check_interval` | int | 32 | Env steps between NaN checks | | `env.finite_validation_interval` | int | 32 | Steps per batched finite-check poll cycle (env-owned validation strictness) | diff --git a/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md b/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md index a407087ce..0d69e2a65 100644 --- a/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md +++ b/docs/sphinx/source/en/2-user_guide/2-algorithms/4-flash_sac.md @@ -45,6 +45,10 @@ remain separate configuration choices: whole-cycle CUDA Graph capture. Set only this field to `false` to retain Inductor compilation without whole-cycle capture. +Custom actors injected through `algo.algo_params.actor_config` do not support +whole-cycle capture; set `use_whole_cycle_cuda_graph=false` for that actor +configuration. + For example, run the eager debugging path with: ```bash @@ -74,6 +78,32 @@ recovery path is to retrain the policy with a current release. The supported baseline starts with the first release after 1.3.5 that carries this change; it is not backported to any 1.3.5 patch release. +## Single-node multi-GPU data parallelism + +FlashSAC uses the same per-rank learner/collector topology and gradient averaging +as SAC. See {doc}`/en/2-user_guide/2-algorithms/3-sac` for launch, logging, +checkpoint, CPU-affinity, and backend-placement details. + +```bash +export CUDA_VISIBLE_DEVICES=, +uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ + training.no_play=true +``` + +Unlike SAC, the FlashSAC owner YAML enables DP whole-cycle CUDA graphs by +default. `algo.algo_params.dp_whole_cycle_cuda_graph=false` disables capture +only on DP ranks; `algo.algo_params.use_whole_cycle_cuda_graph=false` disables +it for every rank. With DP capture enabled, a capture failure raises instead of +allowing a rank-local eager fallback that could desynchronize collectives. The +runner releases captured graphs before closing the process group. + +Before the first capture, the DP synchronizer performs an eager all-reduce and +device synchronization to initialize NCCL collectives. The historical issue +#978 validation used PyTorch 2.7.0+cu128, CUDA 12.8, NCCL 2.26.2, and two RTX +6000D GPUs; the bounded reproducer is +`scripts/benchmark/rl/reproduce_nccl_cuda_graph_capture.py`. This is historical +validation evidence, not a current-host throughput claim. + ## Configuration reference Defaults come from the typed configs in `src/unilab/structured_configs.py` @@ -90,10 +120,10 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | Override key | Type | Default | Practical effect | | --- | --- | --- | --- | -| `algo.num_envs` | int | 1024 | Parallel collector environments | -| `algo.batch_size` | int | 2048 | Learner batch per update | +| `algo.num_envs` | int | 1024 | Parallel collector environments per rank | +| `algo.batch_size` | int | 2048 | Learner batch per update per rank | | `algo.replay_buffer_n` | int | 512 | Replay capacity in env-vector sweeps (rows = n × num_envs) | -| `algo.updates_per_step` | int | 2 | Learner updates per env step | +| `algo.updates_per_step` | int | 2 | Learner updates per env step per rank | | `algo.learning_starts` | int | 98 | Env-vector sweeps to collect before learner updates start | | `algo.policy_frequency` | int | 2 | One actor/temperature update every N learner updates | | `algo.max_iterations` | int | 5000 | Number of training iterations | @@ -103,7 +133,7 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.use_whole_cycle_cuda_graph` | bool | true | Learner-owned whole-cycle CUDA Graph capture | | `algo.algo_params.dp_whole_cycle_cuda_graph` | bool | true | Whole-cycle capture on the data-parallel path; `false` disables DP capture only (field set in `config.yaml`) | | `algo.seed` | int | 1 | Random seed | -| `training.use_amp` | bool | true | bf16 autocast on the learner update path | +| `training.use_amp` | bool | true | Enable device-supported AMP; the dtype and device gates are controlled by `algo.algo_params.amp_dtype` | | `training.log_interval` | int | 1 | TensorBoard/W&B scalar reporting interval in iterations | ### Policy performance @@ -138,7 +168,7 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.learning_rate_warmup_steps` | int | 0 | Warmup steps from init to peak | | `algo.algo_params.learning_rate_decay_steps` | int | 500000 | Decay steps from peak to end | | `algo.algo_params.n_step` | int | 1 | N-step return length; only 1 is supported | -| `algo.algo_params.amp_dtype` | str | auto | AMP dtype under `training.use_amp` | +| `algo.algo_params.amp_dtype` | str | auto | AMP dtype: `auto` selects bf16 on CUDA; Apple MPS requires explicit `bf16` plus a runtime capability probe (auto disables AMP there). CUDA `fp16` uses GradScaler and is incompatible with the whole-cycle graph | ### Training runtime (`training:` section) @@ -148,7 +178,8 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `training.play_only` | bool | false | Skip training and only play a checkpoint | | `training.export_onnx` | bool | true | Export `policy.onnx` during playback | | `training.cuda_process_sharing` | str / null | null | null = independent CUDA contexts; `mps` requests CUDA MPS (user-managed daemon via `uni-cumps`) | -| `training.dp_gradient_wire_dtype` | str | float32 | Gradient wire dtype for multi-GPU averaging; `bfloat16` compresses | +| `training.dp_gradient_wire_dtype` | str | float32 | Multi-GPU gradient wire dtype; `bfloat16` compresses only FP32 groups with at least 1024 elements, restores FP32 before averaging, and changes precision independently of AMP | +| `training.replay_storage_dtype` | str | float16 | Device replay storage: `float16` quantizes obs/action/critic columns while keeping rewards/dones/truncated in FP32 and up-casting sampled batches to FP32; `float32` keeps the full-FP32 ring | | `training.nan_guard.enabled` | bool | true | Detect non-finite tensors and dump diagnostics | | `training.nan_guard.check_interval` | int | 32 | Env steps between NaN checks | | `env.finite_validation_interval` | int | 32 | Steps per batched finite-check poll cycle (env-owned validation strictness) | diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/0-index.md b/docs/sphinx/source/en/2-user_guide/3-backends/0-index.md index efdc7f063..2c4d67d91 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/0-index.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/0-index.md @@ -9,16 +9,19 @@ to the matching task owner YAML; do not switch a run by overriding ## Runtime Prerequisites - Any run using `--sim mujoco`, MuJoCo playback, or a MuJoCo-only debugging - tool requires the `mujoco` extra and its pinned `mjbatch` runtime. -- MJWarp requires the `mjwarp` extra, NVIDIA CUDA, and on multi-GPU hosts an - explicit process-device topology. -- Genesis requires the `genesis` extra and the validated Linux x86_64 GPU path. + tool requires Python 3.11–3.13, the `mujoco` extra, and its pinned `mjbatch` + runtime. The extra is empty on Python 3.10 and the backend fails closed. +- MJWarp requires Python 3.11–3.13, the `mjwarp` extra, NVIDIA CUDA, and on + multi-GPU hosts an explicit process-device topology. +- Genesis requires the `genesis` extra and a supported Linux GPU runtime: + NVIDIA CUDA with `gs.cuda`, or ROCm/HIP with `gs.amdgpu`. - Newton requires the `newton` extra and an NVIDIA CUDA device; the current tensor-native support scope is SAC `g1_walk_flat` and FlashSAC `g1_motion_tracking`. - Motrix requires the `motrix` extra and provides a CPU-authoritative packed - HOST_BRIDGE; the current canonical support scope is SAC `g1_walk_flat` and - FlashSAC `g1_motion_tracking`. + HOST_BRIDGE. Configured owners cover `go2_joystick_flat` (PPO/APPO), + `g1_walk_flat` (PPO/SAC/FlashSAC), and `g1_motion_tracking` + (PPO/APPO/SAC/FlashSAC). - Motrix Warp requires the `mtxwarp` extra and runs physics and Manager tensors on NVIDIA CUDA; the current canonical support scope is FlashSAC `g1_motion_tracking`. @@ -37,9 +40,9 @@ to the matching task owner YAML; do not switch a run by overriding | Backend | Operating system | GPU | | --- | --- | --- | -| MuJoCo | Linux / macOS / Windows | Not required: CPU physics; offline playback can render on CPU | +| MuJoCo | Linux / macOS / Windows (Windows is not CI-validated) | Not required: CPU physics; offline playback can render on CPU | | MJWarp | Linux (validated path) | Required: NVIDIA CUDA; a single-GPU host uses the current CUDA device by default | -| Genesis | Linux x86_64 | Required: NVIDIA GPU and driver; only the `gs.gpu` channel is validated | +| Genesis | Linux | Required: NVIDIA CUDA with `gs.cuda`, or ROCm/HIP with `gs.amdgpu`; CPU, MPS, and Metal are unsupported | | Newton | Linux | Required: NVIDIA CUDA; the selected-reset lane is device-resident | | Motrix | Linux / macOS / Windows | CPU-authoritative physics; Torch CUDA buffers are optional | | Motrix Warp | Linux x86_64 | Required: NVIDIA CUDA; device-resident state and reset | @@ -117,18 +120,20 @@ uv sync --extra mujoco uv run python -c "import unisim; print(unisim.ADAPTER_SPECS)" ``` -`unisim` has no dependency on UniLab, Hydra, or training components. The scoped -MuJoCo, MJWarp, Genesis, Newton, Motrix, and SuperDex adapters and the temporarily -shelved adapters use one public contract. Missing proprietary SDKs or GPU -workers produce an explicit cold-path diagnostic; no backend silently falls -back to another engine. +`unisim` has no dependency on UniLab, Hydra, or training components. All UniSim +adapters use one public contract. Missing proprietary SDKs or GPU workers +produce an explicit cold-path diagnostic; no backend silently falls back to +another engine. ```{toctree} :hidden: 1-mujoco +2-motrix +3-isaacgym +4-isaacsim 5-genesis +6-drake 7-newton -2-motrix 8-superdex ``` diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/1-mujoco.md b/docs/sphinx/source/en/2-user_guide/3-backends/1-mujoco.md index 682692cb0..4993fa0fb 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/1-mujoco.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/1-mujoco.md @@ -3,8 +3,9 @@ MuJoCo is the default backend path in the committed owner configs. On Python 3.11 and newer, the `mujoco` extra installs the official `mujoco` package (`~=4.0.1`) plus the published `mjbatch-uni==0.3.3` native batch engine, with -exact versions pinned by the committed `uv.lock`. The adapter lives under -`unisim.backend.mujoco`. +exact versions pinned by the committed `uv.lock`. Python 3.10 is not a supported +backend lane: dependency markers leave the extra empty and the runtime fails +closed. The adapter lives under `unisim.backend.mujoco`. ## When To Use It diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/2-motrix.md b/docs/sphinx/source/en/2-user_guide/3-backends/2-motrix.md index 7a74c6dee..da360a33d 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/2-motrix.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/2-motrix.md @@ -31,8 +31,9 @@ Motrix is an optional backend installed through the `motrix` extra, which delegates to `unisim-core[motrix]`: the runtime pin lives in UniSim's `pyproject.toml`, and the adapter lives under `unisim.backend.motrix`. -Motrix is a CPU-authoritative packed HOST_BRIDGE backend. Issue #2054 restored -it to the tensor-only Manager runtime with these canonical training workloads: +Motrix is a CPU-authoritative packed HOST_BRIDGE backend. Configured owners cover +`go2_joystick_flat` (PPO/APPO), `g1_walk_flat` (PPO/SAC/FlashSAC), and +`g1_motion_tracking` (PPO/APPO/SAC/FlashSAC). Examples include: ```bash uv run --extra motrix train --algo appo --task go2_joystick_flat --sim motrix @@ -40,9 +41,9 @@ uv run --extra motrix train --algo sac --task g1_walk_flat --sim motrix uv run --extra motrix train --algo flashsac --task g1_motion_tracking --sim motrix ``` -Other Motrix owners remain out of scope and do not constitute production -support claims. The Go2 APPO owner is restored as a configured training path; -its current evidence is bounded smoke training, not a performance benchmark. +Use the generated support matrix for the evidence grade of each algorithm/task +pair. The Go2 APPO owner's current evidence is bounded smoke training, not a +performance benchmark. The public tensor lifecycle exposes: diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/3-isaacgym.md b/docs/sphinx/source/en/2-user_guide/3-backends/3-isaacgym.md index c60e09796..1c8bdcf76 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/3-isaacgym.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/3-isaacgym.md @@ -120,14 +120,9 @@ uv run --no-project "$UNILAB_BENCHMARK_HSGYM_PYTHON" \ Once the external environment is installed, training works out of the box. The worker runtime is discovered automatically from `~/.cache/unisim/isaacgym`; when using a custom install root, export `UNISIM_ISAACGYM_HOME` before -training. `g1_walk_flat` currently ships isaacgym owner configs for PPO and -SAC: +training. `g1_walk_flat` currently ships an isaacgym owner config for SAC only: ```bash -# SAC -uv run train --algo sac --task g1_walk_flat --sim isaacgym - -# PPO uv run train --algo sac --task g1_walk_flat --sim isaacgym ``` @@ -135,14 +130,14 @@ Playback rendering is provided natively by IsaacGym: the interactive mode opens the gym viewer inside the worker process, and the record mode renders offscreen with a camera sensor and writes `play_video.mp4` (the camera tracks env 0's root; the view is adjustable via `training.cam_distance` / -`cam_elevation` / `cam_azimuth`). `play_render_mode=auto` (the default) -selects the interactive viewer when a display is reachable -(`DISPLAY`/`WAYLAND_DISPLAY`) and falls back to recording on headless hosts; -recording requires a finite `training.play_steps` (the default configs -provide one). +`cam_elevation` / `cam_azimuth`). The owner selects +`training.play_render_mode: record`; an explicit `auto` selects the interactive +viewer when a display is reachable (`DISPLAY`/`WAYLAND_DISPLAY`) and falls back +to recording on headless hosts. Recording requires a finite +`training.play_steps` (the default configs provide one). ```bash -# Training enters playback automatically (auto); headless servers record video +# Training enters playback automatically; the owner records video uv run train --algo sac --task g1_walk_flat --sim isaacgym # Evaluate a trained checkpoint in the interactive viewer diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/4-isaacsim.md b/docs/sphinx/source/en/2-user_guide/3-backends/4-isaacsim.md index e3d9e8061..fc725d279 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/4-isaacsim.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/4-isaacsim.md @@ -9,8 +9,9 @@ UniLab's `isaacsim` backend runs IsaacSim 5.1.0 and IsaacLab v2.3.0 in a dedicated Python 3.11 worker process. Pipe messages carry lifecycle metadata while canonical qpos/qvel/control/reset arenas cross same-GPU CUDA IPC. The current restored boundary is headless SAC `g1_walk_flat` training with a mapped -entity scene. Native interactive/record playback remains a separate runtime -follow-up and is not part of the training support claim. +entity scene. Native interactive/record render protocols exist, but the documented +real-host playback attempts are blocked before renderer initialization and are +not part of the training support claim. ## Runtime boundary @@ -57,10 +58,12 @@ half-width so adjacent clones cannot overlap. IsaacSim reports the effective spacing and environment origins back to the host, which rejects a mismatch. The current worker supports MJCF materialization, batched articulation state, -position-target stepping, masked root/joint resets, a native Kit viewer, and -headless IsaacLab RGB camera capture. Contact-force sensors, reset or interval -domain randomization, and host pre-step callbacks remain unsupported and fail -closed. +position-target stepping, masked root/joint resets, mapped-scene contact sensors, +a native Kit viewer, and headless IsaacLab RGB camera capture. Mapped scenes +also declare subsets of reset domain randomization and interval body-force and +body-torque randomization. The current G1 owner still disables PD-gain reset +randomization, and host pre-step callbacks remain unsupported; unsupported +terms fail closed. Use the top-level CLI to select the backend and owner: @@ -73,10 +76,11 @@ uv run eval --algo sac --task g1_walk_flat --sim isaacsim \ --load-run --render-mode interactive training.play_env_num=1 ``` -Record mode writes `play_video.mp4` in the selected run directory. These -commands require the external runtime and an NVIDIA CUDA device. The repository -has a headless SAC training completion record below, while native playback -remains a separate validation and is not claimed as stable. +The record protocol targets `play_video.mp4` in the selected run directory. +These commands require the external runtime and an NVIDIA CUDA device. The +repository has a headless SAC training completion record below; the documented +real-host playback attempts fail before renderer initialization, so playback is +not claimed as stable. ## Training Validation @@ -137,7 +141,7 @@ runtime; it is not a training or playback validation. | Rendering startup | `AppLauncher` cold mode selection | Mock worker verifies none/record/interactive mode, dimensions, and graphics handshake | Mode cannot change after env materialization | | Offline RGB | IsaacLab `Camera` + `CameraCfg` | Protocol tests verify video writing and reject bad shape, dtype, or uniform frames; current real host crashes before camera creation | Require finite steps and keep renderer/playback claims unpromoted until real playback succeeds | | Interactive viewer | non-headless Kit + `SimulationContext.set_camera_view` | Protocol tests drive a frame and map window close to `RenderClosedError`; current host has no successful bounded GUI evidence | Explicit interactive requires a display; `auto` falls back to record without one | -| Domain randomization | IsaacLab manager/event APIs | Not exercised | Non-empty unsupported plans must fail closed | +| Domain randomization | Mapped-scene property and wrench writes | Host tests cover declared reset subsets and interval body force/torque; the G1 owner disables PD-gain reset DR | Shared friction materials disable geom-friction DR; host pre-step callbacks and unsupported terms fail closed | The importer returns a different joint/body ordering (for example, left/right branches are interleaved). The worker builds name-to-index maps and reorders diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/5-genesis.md b/docs/sphinx/source/en/2-user_guide/3-backends/5-genesis.md index a5b3795e1..3b44f32f0 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/5-genesis.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/5-genesis.md @@ -6,21 +6,22 @@ contract on top of it, so physics shares the training process with the learner — no worker subprocess, no IPC. -Current status: `GenesisBackend` is implemented and registered; `g1_walk_flat` -ships PPO and SAC owner configs -(`src/unilab/conf/{ppo,sac}/task/g1_walk_flat/genesis.yaml`), and the cross-backend -contract audit (`scripts/audit_sim2sim_contracts.py`) covers the -mujoco/genesis pair in both algo trees (verdict TRANSFERABLE). Support level -is **experimental**. Evidence: registry + owner YAML + compose/contract -coverage, plus a real-machine slow-lane env smoke +Current status: `GenesisBackend` is implemented and registered. `g1_walk_flat` +ships PPO and SAC owners, and `g1_motion_tracking` ships SAC and FlashSAC owners +(`src/unilab/conf/{ppo,sac}/task/g1_walk_flat/genesis.yaml`, +`src/unilab/conf/{sac,flashsac}/task/g1_motion_tracking/genesis.yaml`). The +cross-backend contract audit (`scripts/audit_sim2sim_contracts.py`) covers the +mujoco/genesis pair for both `g1_walk_flat` algo trees (verdict TRANSFERABLE). +Support level is **experimental**. Evidence: registry + owner YAML + +compose/contract coverage, plus a real-machine slow-lane env smoke (`tests/envs/locomotion/g1/test_g1_owner_contract.py`: compose -> env construction -> keyframe reset -> 12 finite steps -> cleanup, run for both -the ppo and sac trees). The SAC cell is marked `Tested` after a full -real-machine training validation (5000/5000 iterations on 2026-08-31, RTX +the ppo and sac trees). The SAC `g1_walk_flat` cell is marked `Tested` after a +full real-machine training validation (5000/5000 iterations on 2026-08-31, RTX 4090 / torch 2.8.0+cu128 / genesis-world 1.3.3: reward/mean 6.5 -> 244.8, episode length -> 987/1000, 10.26M env steps in 224 s wall time) plus record -playback validation on the final checkpoint; the PPO cell stays `Configured` -(no training validation yet). +playback validation on the final checkpoint. The PPO walk and SAC/FlashSAC +motion owners stay `Configured` without equivalent full-training evidence. Env-construction lifecycle (fixed in #1383): entity validation during `ManagerBasedRlEnv` construction reads state getters before the env's @@ -71,9 +72,6 @@ compensates on the materialize cold path — hot paths never parse XML: Genesis adapter tensor lifecycle. On ROCm, `gs.cuda` is rejected as a runtime mismatch; on non-HIP CUDA, `gs.amdgpu` is likewise rejected. CPU, portable Genesis, Metal, MPS, and substitute backends are never silent fallbacks. -- The repository's pinned torch window (torch 2.8 on x86_64): the - IMUSensor + contact-force sensor combination crashed under torch 2.7 in - the probe (REPORT §3.4/§8). - Install the optional extra (pins `genesis-world==1.3.3` exactly): ```bash @@ -82,9 +80,10 @@ uv sync --extra genesis ## Training and Evaluation -Training selects the genesis owner through the canonical CLI (owner YAML -compose, registry routing, and env construction are covered by the -real-machine slow-lane smoke; there is no training-convergence evidence yet): +Training selects the genesis owner through the canonical CLI. Owner YAML +compose, registry routing, and env construction are covered by the real-machine +slow-lane smoke. Only SAC `g1_walk_flat` has the full-run validation described +above; the other configured owners do not have equivalent convergence evidence: ```bash # PPO diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/6-drake.md b/docs/sphinx/source/en/2-user_guide/3-backends/6-drake.md index 6430630cc..cc81d919f 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/6-drake.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/6-drake.md @@ -1,8 +1,7 @@ # Drake Backend > **Scoped runtime support.** Drake currently has one Manager-runtime owner: -> PPO `go2_joystick_flat`. The page is not a broader production support claim. -> Task support remains governed by the generated support matrix. +> PPO `go2_joystick_flat`. Task support remains governed by the generated support matrix. Drake is an experimental CPU batch backend. UniLab still owns the task, @@ -51,9 +50,10 @@ To use an existing Drake installation instead: make setup-drake DRAKE_HOME=/path/to/drake ``` -The prefix must contain `include/drake/`, `include/pybind11/`, and -`lib/libdrake.so`. On macOS, the setup script also discovers Homebrew `fmt` -and adds the required `gcc` library directory to `DYLD_LIBRARY_PATH`. +The prefix must contain `include/drake/`, `include/pybind11/`, and either +`lib/libdrake.so` (Linux) or `lib/libdrake.dylib` (macOS). On macOS, the setup +script also discovers Homebrew `fmt` and adds the required `gcc` library +directory to `DYLD_LIBRARY_PATH`. The setup script prints the environment exports needed by later shells. On macOS they are normally: diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/7-newton.md b/docs/sphinx/source/en/2-user_guide/3-backends/7-newton.md index 73849b044..c1067cf6d 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/7-newton.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/7-newton.md @@ -18,7 +18,7 @@ uv run train --algo flashsac --task g1_motion_tracking --sim newton The owner configurations are `src/unilab/conf/sac/task/g1_walk_flat/newton.yaml` and `src/unilab/conf/flashsac/task/g1_motion_tracking/newton.yaml`. Other Newton -owners remain out of scope and do not constitute production support claims. +owners remain out of scope. The public tensor lane exposes device-resident state views, frame/contact sensors, state widths, tensor stepping, and authoritative selected-reset publication. Newton is also the validated backend for Manager batched @@ -36,8 +36,8 @@ collector process binding is injection-based; UniLab injects ## Installation -The Newton runtime is an optional extra, pinning Newton 1.5.1 with the -MuJoCo-Warp 3.11 / Warp 1.16 line: +The Newton runtime is an optional extra, pinning Newton 1.5.1 with +MuJoCo-Warp 3.11 and Warp >=1.16 (1.17.0 in the lockfile): ```bash # In a source checkout: @@ -47,9 +47,10 @@ uv sync --extra newton pip install "unilab[newton]" ``` -The extra pins `newton==1.5.1`, `mujoco-warp==3.11.0`, `mujoco==3.11.0`, and -`warp-lang==1.16.0` exactly and includes the native ViewerGL dependencies -(`pyglet>=2.1.6,<3`, `imgui-bundle>=1.92.0`). The `mujoco` and `mjwarp` extras +The extra pins `newton==1.5.1`, `mujoco-warp==3.11.0`, and `mujoco==3.11.0` +exactly, requires `warp-lang>=1.16.0` (resolved to 1.17.0 in `uv.lock`), and +includes the native ViewerGL dependencies (`pyglet>=2.1.6,<3`, +`imgui-bundle>=1.92.0`). The `mujoco` and `mjwarp` extras now use the MuJoCo 4.0.1 line, so their dependency resolver declarations are explicitly mutually exclusive with `newton`. Install Newton in a separate environment; do not combine it with the `mujoco` or `mjwarp` extra. @@ -63,7 +64,7 @@ Prerequisites: - Python `>=3.10` (the repository supports 3.10–3.13). After installation, the unisim repository provides -`scripts/check_newton_runtime.py` as a metadata-only probe (pass `--import` +`scripts/diagnostics/check_newton_runtime.py` as a metadata-only probe (pass `--import` to import the native runtime explicitly). On the UniLab side a missing Newton runtime is not silent: the top-level CLI checks the `newton` module before training and fails closed with an install hint diff --git a/docs/sphinx/source/en/2-user_guide/3-backends/8-superdex.md b/docs/sphinx/source/en/2-user_guide/3-backends/8-superdex.md index aed809fac..26f30256c 100644 --- a/docs/sphinx/source/en/2-user_guide/3-backends/8-superdex.md +++ b/docs/sphinx/source/en/2-user_guide/3-backends/8-superdex.md @@ -1,8 +1,7 @@ # SuperDex Backend > SuperDex participates in the tensor-only Manager runtime as a packed CPU -> `HOST_BRIDGE` backend. Its Go2 owner remains a **Configured** research -> profiles, not full-training or cross-platform production claims. +> `HOST_BRIDGE` backend. Its Go2 owner remains a **Configured** research profile. SuperDex is an optional CPU physics adapter owned by `unisim.backend.superdex`. @@ -12,7 +11,7 @@ full-training performance or platform support. ## Installation -SuperDex Physics/Robotics 1.0.0 is published as Python wheels and is an +SuperDex Physics/Robotics 1.3.0 is published as Python wheels and is an optional UniLab extra; no native source build is required. The wheels carry the native batch executor and support CPython 3.12/3.13 on Linux x86_64 only; on other platforms the extra is empty and the CLI reports a targeted runtime @@ -75,8 +74,9 @@ uv run eval --algo ppo --task go2_joystick_flat --sim superdex \ ``` For the native SuperDex (Polyscope) viewer instead of a video, add -`--render-mode interactive`; the CLI forces `training.play_env_num=1` and the -owner layer switches the env to the serial executor for that run. +`--render-mode interactive`; the CLI defaults `training.play_env_num=1` unless +explicitly overridden, and the owner layer switches the env to the serial +executor for that run. A checkpoint trained on MuJoCo can be evaluated on SuperDex directly (sim2sim): pass its run directory to `--load-run`. The play entrypoint @@ -95,7 +95,7 @@ not change the PPO/APPO collector, learner or policy contracts. The decision is recorded in {doc}`/adr/ADR-0009-superdex-persistent-cpu-workers` and [unisim#41](https://github.com/unilabsim/unisim/issues/41). -Both task owners select automatic workers by default: +The task owner selects automatic workers by default: | Owner option | Meaning | | --- | --- | @@ -114,7 +114,7 @@ debugging profile, not a performance configuration. `eval --sim superdex --render-mode interactive` renders through the native SuperDex (Polyscope) viewer instead of the MuJoCo viewer path. The owner layer automatically switches the env to `superdex_execution_mode=serial`, and the CLI -forces `training.play_env_num=1` because the viewer draws exactly one scene; +defaults `training.play_env_num=1` because the viewer draws exactly one scene; an explicit `training.play_env_num=...` override is preserved. With 1024 environments on a 16-core/32-thread host, automatic selection yields @@ -139,11 +139,12 @@ control steps, not physics substeps. Existing contact approximations are unchang The fixed root still has a named entity and readable body state. Reset terms write joint state; they do not request a floating-root layout. The task does not require contact sensors, cameras, site Jacobians or runtime material DR. -SuperDex has no native renderer. Its default record playback uses the offline -MuJoCo renderer with the authored MJCF visual model while SuperDex remains the -physics backend. `.superdex_bot` scenes must provide `visual_model_file` for -this path. Selecting playback mode `none` skips playback entirely; it is not -evidence that a checkpoint has executed a rollout. +SuperDex does not provide the offline record renderer. Default record playback +uses MuJoCo with the authored MJCF visual model while SuperDex remains the +physics backend; native interactive playback instead uses Polyscope as described +above. `.superdex_bot` scenes must provide `visual_model_file` for the record +path. Selecting playback mode `none` skips playback entirely; it is not evidence +that a checkpoint has executed a rollout. `superdex_allow_contact_approximation` defaults to `false`. It is reserved for explicitly audited MJCF conversion profiles: enabling it accepts a warning about @@ -155,15 +156,16 @@ has completed. Kinematic body/joint getters are refreshed immediately at reset. ## Validation and Ownership -The `go2_joystick_flat/superdex` PPO owner is a research sim2sim profile. It -inherits the MuJoCo owner, preserving 49 actor observations, 52 critic -observations, 12 position-target actions, normalization, network dimensions and -control timing. It disables runtime PD gain randomization and explicitly opts +The `go2_joystick_flat/superdex` PPO owner is a research sim2sim profile. Through +the shared base owner, it preserves the MuJoCo owner's policy I/O: 49 actor +observations, 52 critic observations, 12 position-target actions, normalization, +network dimensions and control timing. It disables runtime PD gain randomization and explicitly opts into contact approximation. The adapter's cold-path MJCF conversion is restricted; this owner does not imply arbitrary scene support or equivalent walking behavior. -Create a small source checkpoint with the MuJoCo owner, then pass its path to the -optional checkpoint test: +Create a small source checkpoint with the MuJoCo owner in a separate environment +(the `mujoco` and `superdex` extras conflict), then pass its path to the optional +checkpoint test in the SuperDex environment: ```bash uv run --no-sync train --algo ppo --task go2_joystick_flat --sim mujoco \ diff --git a/docs/sphinx/source/en/2-user_guide/4-tasks/2-motion_tracking.md b/docs/sphinx/source/en/2-user_guide/4-tasks/2-motion_tracking.md index 1b5197920..cac49a4c8 100644 --- a/docs/sphinx/source/en/2-user_guide/4-tasks/2-motion_tracking.md +++ b/docs/sphinx/source/en/2-user_guide/4-tasks/2-motion_tracking.md @@ -4,10 +4,10 @@ G1 motion tracking tasks live under `src/unilab/tasks/motion_tracking/` and are selected through task owner YAMLs in `src/unilab/conf/ppo/`, `src/unilab/conf/appo/`, and selected off-policy paths. -> **Motion assets moved to Hugging Face.** The `.npz` clips are no longer shipped -> in the repository. On first use `MotionLoader` -> (`src/unilab/tasks/motion_tracking/common/motion_loader.py`) downloads them on demand -> from [unilabsim/unilab-motions](https://huggingface.co/datasets/unilabsim/unilab-motions) +> **Motion assets use Hugging Face on demand.** When a referenced `.npz` clip is +> not present locally, `MotionLoader` +> (`src/unilab/tasks/motion_tracking/common/motion_loader.py`) downloads it from +> [unilabsim/unilab-motions](https://huggingface.co/datasets/unilabsim/unilab-motions) > via `src/unilab/assets/hub.py` (`_HF_MOTIONS_REPO_ID`). `uv sync` already installs > the required `huggingface_hub` dependency. @@ -19,7 +19,7 @@ configuration entry point; the selected owner is materialized into the shared | CLI Task | Registered Env | Default Motion | Owner Evidence | | --- | --- | --- | --- | -| `g1_motion_tracking` | `G1MotionTracking` | `dance1_subject2_part.npz` | `src/unilab/conf/ppo/task/g1_motion_tracking/`, `src/unilab/conf/appo/task/g1_motion_tracking/` | +| `g1_motion_tracking` | `G1MotionTracking` | `dance1_subject2_part.npz` | `src/unilab/conf/{ppo,appo,sac,flashsac}/task/g1_motion_tracking/` | Profile differences remain in Hydra: PPO/APPO, SAC, and FlashSAC all compose the registered `G1MotionTracking` identity, while algorithm-specific @@ -34,7 +34,6 @@ PPO owner iteration budget (the `--sim mujoco` owner YAML): ```bash uv run train --algo ppo --task g1_motion_tracking --sim mujoco -uv run train --algo ppo --task g1_motion_tracking --sim mujoco uv run train --algo appo --task g1_motion_tracking --sim mujoco training.no_play=true uv run train --algo ppo --task g1_motion_tracking --sim mujoco \ algo.num_envs=128 algo.max_iterations=5 training.no_play=true @@ -51,11 +50,13 @@ uv run train --algo sac --task g1_motion_tracking --sim mujoco training.use_amp= The `g1_motion_tracking` owner is the deploy-aligned off-policy observation profile. When a Motrix sim2sim replay needs a checkpoint from another log root, -pass the absolute path through `uv run eval`: +set `training.log_root` and pass the run directory name through `--load-run` +(the flag does not accept an arbitrary path): ```bash -uv run eval --algo sac --task g1_motion_tracking --sim mujoco \ - algo.load_run=/abs/path/to/logs/sac/G1MotionTracking/2026-04-23_14-06-57_mujoco +uv run eval --algo sac --task g1_motion_tracking --sim motrix \ + --load-run 2026-04-23_14-06-57_mujoco \ + training.log_root=/abs/path/to/logs/sac ``` ## Motion Files @@ -80,12 +81,12 @@ Conversion and inspection helpers are in `scripts/motion/`: ```bash uv run scripts/motion/csv_to_npz.py \ - --input_file src/unilab/assets/motions/g1/dance1_subject2.csv \ - --output_file src/unilab/assets/motions/g1/dance1_subject2_from_csv.npz \ + --input_file /path/to/dance1_subject2.csv \ + --output_file /tmp/dance1_subject2_from_csv.npz \ --input_fps 30 --output_fps 50 uv run scripts/motion/csv_to_npz.py \ - --input_file src/unilab/assets/motions/g1/dance1_subject2.csv \ - --output_file src/unilab/assets/motions/g1/dance1_subject2_clip.npz \ + --input_file /path/to/dance1_subject2.csv \ + --output_file /tmp/dance1_subject2_clip.npz \ --input_fps 30 --output_fps 50 --start_time 4.0 --end_time 9.0 uv run scripts/motion/replay_npz.py \ --npz_file src/unilab/assets/motions/g1/dance1_subject2_part.npz --loop diff --git a/docs/sphinx/source/en/2-user_guide/5-domain_randomization/0-index.md b/docs/sphinx/source/en/2-user_guide/5-domain_randomization/0-index.md index 0c55c1b76..6bbdd2ebb 100644 --- a/docs/sphinx/source/en/2-user_guide/5-domain_randomization/0-index.md +++ b/docs/sphinx/source/en/2-user_guide/5-domain_randomization/0-index.md @@ -24,24 +24,19 @@ These three paths correspond to three lifecycle classes: 1. Reset/interval randomization consists of `events:` manager terms in the owner YAML, executed uniformly by the manager lifecycle. 2. Manager-Based owners declare reset behavior through Hydra command/event terms. G1 motion reset perturbations belong to the device-resident `MotionCommandCfg`, while task owners add `EventTermCfg` reset and interval terms. 3. `TensorResetRandomizationPayload` (the torch-first reset payload) expresses curated reset terms; a backend must advertise every requested term in its unified capability set and own its derived-quantity and device-execution obligations. -4. `MotrixBackend` currently supports `base_mass_delta`, `base_com_offset`, `kp`, `kd`, and interval push; and it requires all model actuators to be position actuators during initialization. +4. Backend capabilities are conditional on the realized model and runtime APIs. Current Motrix tests cover `base_mass_delta`, `base_com_offset`, `gravity`, `kp`, `kd`, and interval push; kp/kd gain overrides additionally require an all-position-actuator model. This is not a requirement for every Motrix capability. 5. Fixed mesh/tool identity is declared by `env.fixed_model_variants`; reset-time geometry fields remain behind backend capability declarations and never change that identity. -## Uniformity Assessment Table +## Owner Inventory -| Task | Declaration path | Structured form? | reset form | interval form | Code | -| --- | --- | --- | --- | --- | --- | -| `Go2JoystickFlat` | Hydra `events:` terms | Yes: owner YAML declares reset events | root-state reset + `pd_gains` kp/kd | none | `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` | -| `G1WalkFlat` | Hydra `events:` terms | Yes: Hydra `EventTermCfg` + Manager-Based reset terms | root-state reset + kp/kd via `pd_gains` | none | `g1/manager_terms.py` | -| `G1MotionTracking` | Hydra command term | Yes: Hydra device-resident `MotionCommandCfg` + Manager-Based command reset | motion frame, root pose/velocity, and joint-position sampling | none | `motion_tracking/common/manager_terms.py` | +A task name does not uniquely determine DR: shared base owners and algo/backend leaves differ. These rows describe the named owners rather than claiming one matrix for every algorithm. -## Per-task Domain Randomization List - -| Task | Currently implemented reset domain randomization | Currently implemented interval domain randomization | Default state | +| Owner | Reset/startup randomization | Interval randomization | Evidence | | --- | --- | --- | --- | -| `Go2JoystickFlat` | base xy/yaw and base qvel via `reset_root_state_uniform`; command sampling; kp/kd via `pd_gains` | none | event terms declared and enabled by default in `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` | -| `G1WalkFlat` | base xy/yaw and base qvel via `reset_root_state_uniform`; command sampling with a planar dead zone; `gait_phase` sampling; kp/kd randomization via `pd_gains` | none | kp/kd enabled on the mujoco, genesis, and motrix owners by default; disabled on the mjwarp owner | -| `G1MotionTracking` | Motion-command frame sampling; root pose perturbation `x/y/z/roll/pitch/yaw`; root velocity perturbation `x/y/z/roll/pitch/yaw`; joint-position noise clipped through the public entity soft limits; action-manager state reset | none | `pose_range`, `velocity_range`, and `joint_position_range` have non-zero perturbations in the base owner | +| Go2 shared base | Root-state reset, command sampling, and kp/kd through `pd_gains` | None | `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` | +| Go2 FlashSAC MuJoCo leaf | Inherited base terms plus base mass, COM, and a zero-width gravity term | Linear root-velocity push every 15 s | `src/unilab/conf/flashsac/task/go2_joystick_flat/mujoco.yaml` | +| G1 walk shared base | Root-state reset, command and gait-phase sampling, and kp/kd through `pd_gains`; the PPO MJWarp leaf disables `pd_gains` | None | `src/unilab/conf/ppo/task/g1_walk_flat/base.yaml`, `src/unilab/conf/ppo/task/g1_walk_flat/mjwarp.yaml` | +| G1 motion SAC/FlashSAC shared base | Motion-command pose/velocity sampling plus COM, encoder-bias, and foot-friction event terms | Six-axis velocity push; Motrix leaves disable it | `src/unilab/conf/sac/task/g1_motion_tracking/base.yaml`, `src/unilab/conf/flashsac/task/g1_motion_tracking/base.yaml` | ## Current DR Capabilities and Boundaries @@ -57,7 +52,7 @@ filtering or silent fallback. ## Reset gravity Usage -`gravity` is a reset-lifecycle DR: on each reset, a full MuJoCo gravity vector +`gravity` is a reset-lifecycle DR: on each reset, a full 3D gravity vector `(gx, gy, gz)` is sampled per selected environment and dispatched through `TensorResetRandomizationPayload.gravity`. Configure it with a reset `EventTermCfg` that calls `randomize_physics_scene_gravity`; unsupported backends fail closed. @@ -66,9 +61,10 @@ early task unlearnable. ## Interval push Usage -Manager-Based tasks configure interval push through the `env.events.push_robot` -term using `push_by_setting_velocity` with an interval and per-axis velocity -ranges. +Manager-Based tasks configure interval push through an interval event term that +calls `push_by_setting_velocity` with per-axis velocity ranges. The G1 motion +owners name it `env.events.push_robot`; the Go2 FlashSAC MuJoCo owner names the +same operation `env.events.push_by_setting_velocity`. ## Fixed Model/Tool Variant Boundary @@ -85,20 +81,24 @@ env: - name: tool_b source_model_file: tools/tool_b.xml # Omit explicit_variant_names for deterministic round-robin assignment. + # Otherwise provide exactly num_envs entries (this example assumes two). explicit_variant_names: [tool_a, tool_b] ``` The Manager factory turns the declaration into a read-only `int32` assignment -with shape `(num_envs,)`; an empty explicit list selects round-robin. +with shape `(num_envs,)`; an empty explicit list selects round-robin. A +non-empty list whose length differs from `num_envs` is rejected. The assignment is task identity: it is fixed after backend construction and is not resampled by reset events. UniLab does not open, parse, or compile `source_model_file`, and does not hold `MjSpec`, `MjModel`, mjbatch, or Warp objects. UniSim adapters own source -realization and must declare `supports_fixed_variants`. Until that -contract lands, a task configured with fixed variants fails closed before env -construction. Heterogeneous variants that cannot expose one public -state/action/sensor layout also fail closed. +realization and must advertise both `supports_fixed_variants` and the plan's +`same_layout` layout. An unsupported backend or layout fails closed before the +Manager-Based environment is constructed; `tests/base/test_fixed_model_variants.py` +covers plan construction, layout negotiation, and cleanup on this failure path. +Heterogeneous variants that cannot expose one public state/action/sensor layout +also fail closed. Reset-time model-field DR stays inside the selected identity. Its canonical or per-env baselines come from the backend's declared diff --git a/docs/sphinx/source/en/2-user_guide/5-domain_randomization/1-configuration.md b/docs/sphinx/source/en/2-user_guide/5-domain_randomization/1-configuration.md index ad42c39a0..9fb2aec9e 100644 --- a/docs/sphinx/source/en/2-user_guide/5-domain_randomization/1-configuration.md +++ b/docs/sphinx/source/en/2-user_guide/5-domain_randomization/1-configuration.md @@ -17,15 +17,18 @@ the selected backend does not advertise fails closed. ## Reset Gravity -Use `--sim mujoco` when enabling gravity reset randomization; Motrix does not -advertise the gravity reset capability. Configure gravity through a reset event -term that calls `randomize_physics_scene_gravity`. +Configure gravity through a reset event term that calls +`randomize_physics_scene_gravity`, and enable it only when the selected backend +advertises `gravity`. Current tests cover gravity reset on MuJoCo, MJWarp, and +Motrix; Genesis rejects this term. Support is therefore not MuJoCo-only, but it +is not universal either. ## Interval Push -Manager-Based tasks configure interval push through the `env.events.push_robot` -term using `push_by_setting_velocity` with an interval and per-axis velocity -ranges. +Manager-Based tasks configure interval push through an interval event term that +calls `push_by_setting_velocity` with per-axis velocity ranges. The G1 motion +owners name it `env.events.push_robot`; the Go2 FlashSAC MuJoCo owner names the +same operation `env.events.push_by_setting_velocity`. ## Owner-Local Defaults diff --git a/docs/sphinx/source/en/2-user_guide/5-domain_randomization/2-field_reference.md b/docs/sphinx/source/en/2-user_guide/5-domain_randomization/2-field_reference.md index cc1d645aa..4a1ecc4cd 100644 --- a/docs/sphinx/source/en/2-user_guide/5-domain_randomization/2-field_reference.md +++ b/docs/sphinx/source/en/2-user_guide/5-domain_randomization/2-field_reference.md @@ -23,11 +23,15 @@ DR terms run under three lifecycle classes (see the lifecycle overview in ## Backend Applicability -The exact field-by-backend matrix is owned by the external `unisim-core` +The runtime field-by-backend matrix is owned by the external `unisim-core` package (`DomainRandomizationCapabilities.supported_reset_terms` / -`supported_interval_terms`) and cannot be confirmed field by field from this -repository, so this page deliberately does not print one. Two rules always -hold: +`supported_interval_terms`). It can depend on the realized model and available +runtime APIs, so this page does not present a static matrix as universal. +In-repo tests provide concrete examples: Motrix gravity and interval push are +covered by `tests/base/test_sim_backend_smoke.py`, its conditional capability +declarations by `tests/base/test_motrix_backend_options.py`, Genesis's lack of +gravity reset by `tests/base/test_genesis_backend.py`, and MJWarp gravity by +`tests/base/test_mjwarp_dr.py`. Two rules always hold: 1. A requested term that the selected backend does not advertise fails closed at construction; there is no filtering or silent fallback. @@ -128,8 +132,9 @@ The center of mass and the principal frame are left untouched. Additive center-of-mass randomization (`unilab.envs.mdp.randomize_rigid_body_com`). Supports `mode: reset` and -`mode: startup`. The live `com_range` is re-read on every apply, so a -curriculum can widen the range between resets. +`mode: startup`. In reset mode, the live `com_range` is re-read on every apply, +so a curriculum can widen the range between resets. Startup mode samples one +full-width table and freezes it; later range changes do not alter those values. | Field | Type | Default / required | When it applies | Semantics and value hints | | --- | --- | --- | --- | --- | @@ -190,7 +195,7 @@ physics model field, and requires the Torch control plane. | Field | Type | Default / required | When it applies | Semantics and value hints | | --- | --- | --- | --- | --- | -| `bias_range` | `[lo, hi]` | required | sampled each reset | Uniform bias in radians (joint position units). The SAC G1 MuJoCo owner uses `[-0.01, 0.01]` on all joints. | +| `bias_range` | `[lo, hi]` | required | sampled each reset | Uniform bias in the model's joint-position units. The SAC G1 MuJoCo owner uses `[-0.01, 0.01]` on all joints. | | `asset_cfg` | `SceneEntityCfg` | required | bound at construction | `joint_names`/`joint_ids` select the joints; at least one joint must be selected. | ## Reset-State Terms @@ -336,16 +341,15 @@ Genesis owner scales `pelvis`/`torso_link` by `[0.9, 1.1]`), and `abs` sets absolute kilograms. The result is clamped below at `min_mass` (default `1e-6`). -**How do I keep one task runnable on Motrix and MuJoCo when Motrix has no gravity reset?** -Per {doc}`1-configuration`, gravity reset randomization is MuJoCo-only today; -`MotrixBackend` advertises `base_mass_delta`, `base_com_offset`, `kp`, `kd`, -and interval push only (see {doc}`0-index`). Keep shared terms in the task -`base.yaml`, declare `randomize_physics_scene_gravity` only in `mujoco.yaml`, -and if the shared base declares it, set `randomize_physics_scene_gravity: null` -in `motrix.yaml` — the same pattern as `pd_gains: null` in -`src/unilab/conf/ppo/task/g1_walk_flat/mjwarp.yaml`. -Leaving the term enabled for Motrix would fail closed at construction instead -of being skipped. +**How do I keep one task runnable when a backend has no gravity reset?** +Gravity reset is not MuJoCo-only: current tests cover MuJoCo, MJWarp, and +Motrix, while Genesis rejects it (see {doc}`1-configuration`). Keep shared +terms in the task `base.yaml`, declare `randomize_physics_scene_gravity` only +in owners whose backends advertise it, and set +`randomize_physics_scene_gravity: null` in an unsupported backend's owner if +the shared base declares it — the same pattern as `pd_gains: null` in +`src/unilab/conf/ppo/task/g1_walk_flat/mjwarp.yaml`. Leaving the term enabled +on an unsupported backend fails closed at construction instead of skipping it. For the payload-level contract behind these terms, see {doc}`Domain Randomization Contract `. diff --git a/docs/sphinx/source/en/2-user_guide/6-terrain/0-index.md b/docs/sphinx/source/en/2-user_guide/6-terrain/0-index.md index a3c5b8a57..96b0c13db 100644 --- a/docs/sphinx/source/en/2-user_guide/6-terrain/0-index.md +++ b/docs/sphinx/source/en/2-user_guide/6-terrain/0-index.md @@ -1,7 +1,9 @@ # Terrain -Terrain support is currently documented through the Go2 rough-terrain owner -path and the shared terrain generator. +Terrain support is provided by the shared generator, scene configuration, and +backend materialization contracts. No registered owner under `src/unilab/conf` +currently declares `env.scene.terrain`; the examples below are integration +patterns backed by generator, materialization, and Manager runtime tests. ::::{grid} 1 1 2 2 :gutter: 3 diff --git a/docs/sphinx/source/en/2-user_guide/6-terrain/1-procedural.md b/docs/sphinx/source/en/2-user_guide/6-terrain/1-procedural.md index df2c2d037..72f239a58 100644 --- a/docs/sphinx/source/en/2-user_guide/6-terrain/1-procedural.md +++ b/docs/sphinx/source/en/2-user_guide/6-terrain/1-procedural.md @@ -13,7 +13,8 @@ The core reusable pieces are: - `unilab.terrains` sub-terrain factories for generator composition. For example, an owner can declare a generated terrain without putting terrain -knowledge in the backend: +knowledge in the backend. `size` and at least one entry in `sub_terrains` are +required by `TerrainGeneratorCfg`: ```yaml env: @@ -23,12 +24,21 @@ env: geom_name: floor generator: _target_: unilab.terrains.TerrainGeneratorCfg + size: [2.0, 2.0] + num_rows: 2 + curriculum: true seed: 42 + sub_terrains: + flat: + _target_: unilab.terrains.HfFlatTerrainCfg + proportion: 1.0 ``` UniLab owns the runtime terrain spawn state in `src/unilab/base/terrain.py`; -UniSim owns generator composition and backend materialization. Task owners that -enable the capability carry their own training evidence. +UniSim owns generator composition and backend materialization. This declaration +is an integration pattern, not a registered owner shipped under +`src/unilab/conf`; `tests/base/test_terrain.py` constructs the equivalent typed +configuration directly. ## Materialization boundary @@ -37,12 +47,15 @@ During `registry.make(...)`: 1. Hydra materializes the selected owner into `ManagerBasedRlEnvCfg`. 2. `create_backend` resolves required robot assets and passes `SceneCfg` to the selected UniSim backend. -3. The backend's public scene materializer generates the terrain matrix, - origins, hfield, and merged scene model. +3. A backend that implements the public scene materializer generates the + terrain matrix, origins, hfield, and merged scene model. Current tests cover + MuJoCo and Motrix materialization. 4. Task owners retain their own scanner bindings and cached IDs. Step and reset never parse robot XML or inspect asset metadata. They consume -cached IDs and public backend capabilities. +cached IDs and public backend capabilities. A backend that declares generated +terrain but returns no `SimBackend.get_terrain_spawn_data()` metadata fails +closed in `src/unilab/base/terrain.py`. ## Owner integration @@ -81,8 +94,9 @@ robot at the selected origin. ## Core validation ```bash -uv run pytest tests/terrains tests/utils/test_xml_utils.py -q +uv run pytest tests/terrains tests/base/test_terrain.py tests/utils/test_xml_utils.py -q ``` -Core validation also covers the terrain generator and backend materialization -boundary; ecosystem packages own evidence for additional task families. +These tests cover the generator, runtime curriculum, and backend +materialization boundary. Optional simulator dependencies may skip their +corresponding materialization cases. diff --git a/docs/sphinx/source/en/2-user_guide/6-terrain/2-heightfield_import.md b/docs/sphinx/source/en/2-user_guide/6-terrain/2-heightfield_import.md index e4c50942d..b047a146f 100644 --- a/docs/sphinx/source/en/2-user_guide/6-terrain/2-heightfield_import.md +++ b/docs/sphinx/source/en/2-user_guide/6-terrain/2-heightfield_import.md @@ -1,8 +1,10 @@ # Heightfield Import Heightfield terrain is configured through `SceneCfg` and the terrain generator, -then materialized by the backend on the init path. Core tests exercise the -contract with a generated heightfield scene. +then materialized by the backend on the init path. The covered path generates a +merged heightfield PNG from procedural sub-terrains; it is not a general +importer for user-supplied heightfield images. Current materialization tests +cover MuJoCo and Motrix. ## Files To Read @@ -16,8 +18,11 @@ contract with a generated heightfield scene. ```bash uv run pytest tests/utils/test_xml_utils.py \ - -k mujoco_materialize_hfield_attached_scene + -k materialize_hfield_attached_scene ``` +This selects both MuJoCo and Motrix materialization tests; Motrix cases skip +when its optional simulator dependency is unavailable. + Height scan IDs and offsets are cached during env initialization; hot paths call the backend height-scanner contract instead of parsing XML or asset metadata. diff --git a/docs/sphinx/source/en/2-user_guide/7-tooling/1-onnx_export.md b/docs/sphinx/source/en/2-user_guide/7-tooling/1-onnx_export.md index b18077987..2968bedce 100644 --- a/docs/sphinx/source/en/2-user_guide/7-tooling/1-onnx_export.md +++ b/docs/sphinx/source/en/2-user_guide/7-tooling/1-onnx_export.md @@ -13,5 +13,12 @@ uv run eval --algo sac --task g1_walk_flat --sim mujoco --load-run -1 ``` Use the same `--algo`, `--task`, and `--sim` values that produced the -checkpoint. For deployment context, see +checkpoint. The artifact is `policy.onnx` in the selected checkpoint run +directory. SAC and FlashSAC export by default and accept +`training.export_onnx=false` to skip it. APPO attempts export whenever playback +resolves a checkpoint run directory and has no `training.export_onnx` switch. +APPO, SAC, and FlashSAC compare ONNX Runtime output with PyTorch after export, +while the PPO path delegates export to the RSL-RL runner. + +For deployment context, see {doc}`../../3-deployment/1-sim_to_real/5-onnx_runtime`. diff --git a/docs/sphinx/source/en/2-user_guide/7-tooling/2-wandb.md b/docs/sphinx/source/en/2-user_guide/7-tooling/2-wandb.md index 1c4f037d6..a9d6ea8d4 100644 --- a/docs/sphinx/source/en/2-user_guide/7-tooling/2-wandb.md +++ b/docs/sphinx/source/en/2-user_guide/7-tooling/2-wandb.md @@ -3,7 +3,8 @@ Training configs default to TensorBoard through `training.logger=tensorboard`. Set `training.logger=wandb` to use Weights & Biases. The shared W&B fields live in the training config blocks, including `wandb_project`, `wandb_entity`, -`wandb_group`, `wandb_name`, `wandb_tags`, `wandb_notes`, and `wandb_mode`. +`wandb_group`, `wandb_job_type`, `wandb_name`, `wandb_tags`, `wandb_notes`, and +`wandb_mode`. ## Examples diff --git a/docs/sphinx/source/en/2-user_guide/7-tooling/3-nan_visualizer.md b/docs/sphinx/source/en/2-user_guide/7-tooling/3-nan_visualizer.md index 1a4c19214..9b8ea76e0 100644 --- a/docs/sphinx/source/en/2-user_guide/7-tooling/3-nan_visualizer.md +++ b/docs/sphinx/source/en/2-user_guide/7-tooling/3-nan_visualizer.md @@ -13,6 +13,14 @@ uv run train --algo ppo --task go2_joystick_flat --sim mujoco \ ``` The viewer implementation is `src/unilab/utils/nan_viz.py`, registered as the -`unilab-viz-nan` console entry. It replays a dump path and lets you select the -environment index. Dump format and round-trip loading are covered by -`tests/training/test_tensor_diagnostics.py`. +`unilab-viz-nan` console entry: + +```bash +uv run unilab-viz-nan /tmp/unilab/nan_dumps/dump.npz --env-index 0 +``` + +It replays recorded MuJoCo physics states and needs the model file recorded in +the dump metadata or a sibling `*_model.*` artifact. If the backend did not +provide state playback, the dump contains no physics states and the command +prints the metadata instead of opening a viewer. Dump format and round-trip +loading are covered by `tests/training/test_tensor_diagnostics.py`. diff --git a/docs/sphinx/source/en/2-user_guide/7-tooling/5-robot_import.md b/docs/sphinx/source/en/2-user_guide/7-tooling/5-robot_import.md index 142f8489d..3bd5756d1 100644 --- a/docs/sphinx/source/en/2-user_guide/7-tooling/5-robot_import.md +++ b/docs/sphinx/source/en/2-user_guide/7-tooling/5-robot_import.md @@ -17,8 +17,9 @@ repository format: - `assets/`: only `.stl` / `.obj` meshes. - `.xml`: robot-only MJCF containing body / joint / actuator / sensor descriptions. -- task/scene fragment: for example `scene.xml`, containing the scene, ground, - task sensors, and keyframes. +- task/scene fragment: for example `scene.xml`, containing task keyframes and, + when the task needs them, scene elements, ground, and task sensors. The + importer-generated `scene.xml` contains only the initial `home` keyframe. Do not copy the full external package. `` belongs in the task/scene fragment, not in the robot XML. diff --git a/docs/sphinx/source/en/3-deployment/0-index.md b/docs/sphinx/source/en/3-deployment/0-index.md index 869075cab..dfb8e9258 100644 --- a/docs/sphinx/source/en/3-deployment/0-index.md +++ b/docs/sphinx/source/en/3-deployment/0-index.md @@ -26,7 +26,8 @@ deploy-side contract checks. :link-type: doc :class-card: sd-shadow-md -Switch the same task between MuJoCo and Motrix without retraining from scratch. +Move between supported backends through owner YAMLs, then validate policy I/O, +physics, rewards, and playback separately. ::: :::{grid-item-card} 🔁 Framework Migration @@ -34,7 +35,7 @@ Switch the same task between MuJoCo and Motrix without retraining from scratch. :link-type: doc :class-card: sd-shadow-md -Bring tasks over from Isaac Lab / Legged Gym / rsl_rl / skrl. +Bring tasks over from Isaac Lab / Legged Gym / rsl_rl / skrl / unilab-rl. ::: :::: @@ -98,7 +99,7 @@ Symptom → cause → fix cookbook. --- -## 🔀 Sim → Sim (MuJoCo ↔ Motrix) +## 🔀 Sim → Sim ::::{grid} 1 1 2 3 :gutter: 3 @@ -106,11 +107,13 @@ Symptom → cause → fix cookbook. :::{grid-item-card} 🤔 Backend swap :link: 2-sim_to_sim/1-backend_swap :link-type: doc +Select an owner with `--algo`, `--task`, and `--sim`. ::: :::{grid-item-card} 📝 Owner YAML swap :link: 2-sim_to_sim/2-owner_yaml_swap :link-type: doc +Add a backend leaf without cross-backend inheritance. ::: :::{grid-item-card} 🔬 Contact & friction alignment @@ -123,7 +126,7 @@ Symptom → cause → fix cookbook. :link-type: doc ::: -:::{grid-item-card} 🎞 Playback differences +:::{grid-item-card} 🎞 Playback & snapshots :link: 2-sim_to_sim/5-playback_and_snapshot_differences :link-type: doc ::: @@ -133,6 +136,12 @@ Symptom → cause → fix cookbook. :link-type: doc ::: +:::{grid-item-card} 🛡 Cross-backend config guard +:link: 2-sim_to_sim/7-config_guard +:link-type: doc +Validate the training-time policy contract before checkpoint playback. +::: + :::: --- @@ -145,7 +154,7 @@ Symptom → cause → fix cookbook. :::{grid-item-card} From **Isaac Lab** :link: 3-framework_migration/1-from_isaac_lab :link-type: doc -GPU-resident → CPU + shared-mem. +Manager-Based terms → Torch runtime and Hydra owners. ::: :::{grid-item-card} From **Legged Gym** @@ -157,7 +166,7 @@ Class-based env → Manager-Based TorchEnv. :::{grid-item-card} From **rsl_rl** :link: 3-framework_migration/3-from_rsl_rl :link-type: doc -Trainer split: collector + learner. +Direct upstream `OnPolicyRunner` integration; APPO is a separate algorithm. ::: :::{grid-item-card} From **skrl** @@ -178,6 +187,12 @@ Side-by-side field map. Common reward terms in UniLab style. ::: +:::{grid-item-card} From **unilab-rl** +:link: 3-framework_migration/7-from_unilab_rl +:link-type: doc +Move `uni_rl` imports and installations to `unilab.rl` and the `unirl` extra. +::: + :::: ```{toctree} diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/1-overview.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/1-overview.md index 6d8d7167e..e9bc25a2d 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/1-overview.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/1-overview.md @@ -50,15 +50,15 @@ flowchart LR 1. A **converged training run** with stable reward AND a stable success criterion (motion tracking error, drop count, etc.). 2. The same policy passes evaluation in **both** MuJoCo and Motrix when both - support the task — if not, you have a backend-dependent reward leak; see - {doc}`../2-sim_to_sim/4-reward_parity`. + support the task. If not, investigate backend-dependent contracts or dynamics + rather than assuming a reward leak; see {doc}`../2-sim_to_sim/4-reward_parity`. 3. **Domain randomization** ranges large enough that reward varies smoothly when you sweep DR strength — a brittle policy in sim is a brittle policy on hardware. 4. **No backend feature leakage** in the env — verify via the developer guide's {doc}`../../4-developer_guide/2-contracts/2-backend_contract`. 5. An **observation spec** you can implement on hardware. If your policy - reads `body_lin_vel`, you need a deploy-side estimator or a task owner + reads `base_lin_vel`, you need a deploy-side estimator or a task owner variant that removes that signal from the actor input. :::: @@ -69,15 +69,17 @@ flowchart LR runtime (units, frame, filter cutoffs). Log the first deploy-side observation window and compare it with a sim rollout built from the same owner YAML. -- **Action latency.** Some task owners expose one-step delayed action execution - through a control config or Manager-Based action term. Measure the deploy loop - and make the training owner match that contract before a hardware run. See +- **Action latency.** Manager-Based action terms can delay a processed target by + physics substeps; the G1 motion term can instead select the previous raw + action for one control tick. Measure the deploy loop and match the correct + mechanism and units in training before a hardware run. See {doc}`8-latency_budget`. - **Friction / damping mismatch.** Especially for in-hand manipulation. Sweep friction in DR; cross-check via {doc}`../2-sim_to_sim/3-contact_and_friction_alignment`. - **Reset transients.** Sim resets to a stable pose; deployment starts from a - controller state. The safety layer must reject malformed observations and - unsafe actions before they reach the motor driver. + controller state. The deploy-side safety design should reject malformed + observations and unsafe actions before they reach the motor driver; UniLab + does not supply that hardware safety loop. ## Per-robot quick links diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/2-g1_whole_body.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/2-g1_whole_body.md index ee5b9f333..eb74cd09a 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/2-g1_whole_body.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/2-g1_whole_body.md @@ -37,32 +37,17 @@ owner that produced the checkpoint: uv run eval --algo ppo --task g1_motion_tracking --sim mujoco --load-run -1 ``` -Every field your hardware loop needs is declared in that owner's YAML. Widths -differ per owner: - -```{list-table} -:header-rows: 1 -:widths: 34 22 44 - -* - Owner - - Actor obs width - - Notes -``` - -::::{admonition} Read the width off the composed config, not off this table -:class: warning -Actor obs width is the sum of `dim * history_length` over the terms declared -under `env.observations.actor.terms`, plus the motion command. A term set to -`null` is dropped. If the ONNX input width disagrees with what your hardware -loop assembles, that is a contract bug, not a hardware tuning problem. -:::: +The current 29-DoF G1 motion-tracking owners have a 160-dimensional actor +input. Read the width from the composed config and ONNX graph rather than +treating this number as a permanent constant. For a flat group, each term +contributes its current dimension, multiplied by `history_length` only when +flattened history is configured; a term set to `null` is dropped. The current +G1 motion owners declare no observation history. ## 2. Observation contract -Term order and per-term history come from your own owner's -`env.observations.actor.terms`. Terms carrying a `history_length` are -flattened **oldest-first** within the term, and terms are concatenated in -declaration order: +For the retained owners, `env.policy_observation_group` is `actor`, and +`env.observations.actor.terms` declares this order: ```{list-table} :header-rows: 1 @@ -71,81 +56,103 @@ declaration order: * - Term - Dim - Source on hardware +* - `command` + - 58 + - current reference joint positions (29, rad), then velocities (29, rad/s) +* - `motion_anchor_pos_b` + - 3 + - motion-anchor relative position term, m * - `motion_anchor_ori_b` - 6 - - anchor orientation term from the reference and robot torso frames + - six-component relative orientation of the motion anchor +* - `base_lin_vel` + - 3 + - pelvis-frame linear velocity estimate, m/s * - `base_ang_vel` - - 3 per history step - - IMU gyro (`params.sensor_name: pelvis_gyro`) + - 3 + - IMU gyro (`params.sensor_name: torso_gyro`), rad/s * - `joint_pos` - - 29 per history step - - measured joint position minus the `stand` keyframe joint angles + - 29 + - measured position relative to the scene default and `joint_default_bias`, rad; SAC/FlashSAC also add encoder bias * - `joint_vel` - - 29 per history step - - joint velocity term + - 29 + - measured joint velocity, rad/s * - `actions` - - 29 per history step + - 29 - previous raw actor output ``` -The motion command contributes the reference joint position and velocity ahead -of the observation terms when declared. Per-term oldest-first ordering is -guaranteed by the `ObservationManager` per-term history buffers -(`tests/managers/test_observation_buffers_noise.py`); mirror that ordering -on hardware or the policy reads a permuted vector. +These are single-frame terms in the current owners. If a custom owner adds +per-term history, `ObservationManager` flattens each term **oldest-first** and +concatenates terms in declaration order +(`tests/managers/test_observation_buffers_noise.py`). Reproduce any scaling and +history exactly; the critic-only body terms are not actor inputs. ## 3. Actuator interface -Map actor output as `action * scale + default_angles`, then clamp to the -scene's joint range before the target reaches the motor driver. - -- `scale` is `env.actions.joint_pos.scale`. It may be a **scalar** or a - **regex → value map** resolved per actuator. Unitree's deploy owners map - joint-name patterns to distinct values. - Reproduce the owner's resolved per-actuator vector exactly — do not average a - map, take one entry, or broadcast a scalar over a map owner. -- `default_angles` follows from `use_default_offset: true`, i.e. the `stand` - keyframe joint block of the owner's scene. -- Joint limits and gains come from the same scene XML (`jnt_range`, position - actuator `gainprm` / `biasprm`). - -Training applies the target directly with no smoothing. If hardware jitter -forces you to add smoothing, verify the sim2sim impact first — every step of lag -pushes observations out of the training distribution. +The base mapping is `action * scale + default_joint_pos`. For +`MotionJointPositionAction`, the applied target also adds the motion command's +`joint_default_bias` and subtracts encoder bias. Clamp the resulting target to +validated joint limits in the deploy controller before it reaches the motor +driver; UniLab does not perform that hardware-side clamp. + +- `scale` is `env.actions.joint_pos.scale`. Current PPO/APPO motion owners use + `0.25`; current SAC/FlashSAC motion owners use `2.0`. Other action terms may + use a regex → value map resolved per actuator, so always reproduce the + selected owner's resolved vector. +- `default_joint_pos` comes from `use_default_offset: true` and the `stand` + keyframe. Do not drop the motion/encoder bias terms when the selected owner + uses them. +- Joint limits and nominal position-actuator `kp` / `kv` come from the composed + scene, including its robot XML includes. An enabled `env.events.pd_gains` + term can change gains at reset. + +Unless an action-delay setting is enabled, training applies the target directly +with no smoothing. Adding deploy-only smoothing or filtering changes the +closed-loop contract; reproduce it in simulation and revalidate before hardware +use. ## 4. Reference motion sync -The phase variable lets the policy track an externally-supplied motion -clip. On hardware you need a wall-clock → phase mapping that is: - -- **Monotonic** — no skipping back. -- **Restartable** — survives a comms hiccup without producing a step - discontinuity in `(sin φ, cos φ)`. -- **Bounded rate** — clip dφ/dt to the value the policy was trained with - (the motion loader records this; load `reference_motion.npz`). +`MotionCommand` reads the NPZ selected by +`env.commands.motion.params.motion_file` (currently +`motions/g1/dance1_subject2_part.npz` for the retained owners). +`unilab.tasks.motion_tracking.common.motion_loader` requires `fps`, +`joint_pos`, `joint_vel`, and body trajectory arrays. The command advances a +reference **frame index**, and its 58 values are that frame's joint positions +and velocities; there is no `(sin φ, cos φ)` motion-command input in this task. -See `unilab.tasks.motion_tracking.common.motion_loader` for the sim-side -loader you should mirror on hardware. +The current owners use `env.ctrl_dt: 0.02` (20 ms, 50 Hz). A hardware runtime +must reproduce the selected reference-frame sequence and anchor observations +at the trained control timing. UniLab does not provide a deploy-side wall-clock +synchronizer, communications-recovery policy, or half-rate motion mapping; +those require a deploy-specific implementation and simulation revalidation. ## 5. Safety layer -Hardware-side: see {doc}`7-safety_layers` for the standard structure. The G1 +Hardware-side: see {doc}`7-safety_layers` for the recommended checklist. The G1 specifics: - Reject non-finite actions and shape mismatches before applying the action scale. -- Clamp generated targets with the joint range from the owner's scene XML. +- Clamp generated targets to validated limits derived from the composed scene + and the robot's hardware constraints. - Keep watchdog, pose monitor, and operator-stop thresholds in the deploy controller and test them independently of the policy. ## 6. Closed-loop bring-up sequence -1. **Stand-on-stand**. Robot held by a gantry. Policy runs but actuators are - torque-disabled. Confirm observation pipeline. -2. **Torque-enable, hand-held**. Operator catches the robot. Policy - commands actuators. Confirm action mapping. -3. **Gantry-supported gait**. Track motion at half time-rate (dφ/dt halved). -4. **Free-stand**. Full rate, then remove gantry. +The following is a suggested deploy-side sequence, not a hardware-validated +UniLab safety procedure: + +1. **Observation-only, supported robot**. Policy runs but actuators are + torque-disabled. Confirm the observation pipeline. +2. **Torque-enable with physical support**. Apply commands only within the + robot/controller operating limits and confirm action mapping. +3. **Supported closed-loop motion**. Keep the reference-frame timing consistent + with training. +4. **Reduce support only after independent safety checks pass**. Stay within + the validated operating envelope. Do not skip the observation-only stage: it is where axis-order, joint-order, and `actions` wiring mistakes are easiest to catch. diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/3-go2_locomotion.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/3-go2_locomotion.md index 4aaa92b85..eee964832 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/3-go2_locomotion.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/3-go2_locomotion.md @@ -1,48 +1,52 @@ # Go2 Locomotion Deployment -This page describes the retained `go2_joystick_flat` reference owner. Unitree -production deployment variants are documented by their ecosystem package. +This page describes the retained `go2_joystick_flat` reference owner. UniLab +does not ship a Go2 hardware runtime or hardware validation results for this +page. ## Observation contract +The current PPO/APPO/SAC/FlashSAC owners declare these terms, in this order, +under `env.observations.policy.terms`. The flat actor input is 49-dimensional +for the 12-DoF robot; confirm it against the selected composed owner and ONNX +input rather than treating that total as a permanent constant. + ```{list-table} :header-rows: 1 :widths: 30 15 55 -* - Group +* - Term - Dim - Source on hardware -* - Base linear velocity - - 3 - - state estimator (KF over IMU + leg odometry); NOT raw integration -* - Base angular velocity +* - `base_ang_vel` - 3 - - IMU gyro -* - Projected gravity + - IMU gyro, rad/s +* - `projected_gravity` - 3 - - IMU orientation -* - Joystick command (vx, vy, ωz) - - 3 - - operator input -* - Joint positions + - gravity projected into the base frame from IMU orientation +* - `joint_pos` - 12 - - encoder -* - Joint velocities + - encoder position relative to the `home` keyframe, rad +* - `joint_vel` - 12 - - encoder velocity after the deploy controller's filtering path -* - Previous action + - encoder velocity, rad/s +* - `actions` - 12 - - last policy output -* - Foot contact + - previous raw policy output +* - `command` + - 3 + - operator command `(vx, vy, ωz)`, in m/s, m/s, rad/s +* - `gait_phase` - 4 - - contact sensor or estimated from foot height + - four foot-phase values generated at the configured frequency ``` -::::{admonition} State estimator caveat +::::{admonition} Actor and critic inputs differ :class: warning -The policy is trained against the observation terms emitted by the selected env -owner. If deployment cannot provide the same base-velocity signal, train a -variant whose actor observation matches the estimator you can run on the robot. +`base_lin_vel` is critic-only in these owners, and foot contact is used by reward +terms rather than the actor observation. Do not append either to the deploy actor +input. If a task variant changes the terms, reproduce that variant's selected +policy group instead. :::: ## See also diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/5-onnx_runtime.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/5-onnx_runtime.md index 088e9b3c3..9a49aec40 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/5-onnx_runtime.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/5-onnx_runtime.md @@ -1,17 +1,16 @@ # ONNX Runtime UniLab exports ONNX policies from the existing training playback paths. Use the -same algorithm family and task owner that produced the checkpoint; the playback -code loads the checkpoint, exports `policy.onnx`, and verifies the exported -graph when that path implements ONNX Runtime checking. +same algorithm family and task owner that produced the checkpoint. Export and +verification behavior differs by algorithm path. ## Export Paths | Algorithm path | Entry script | Export behavior in repo | | --- | --- | --- | -| PPO (torch) | `src/unilab/scripts/train_rsl_rl.py` | `EXPORT_POLICY=True` in the script entrypoint; playback calls `runner.export_policy_to_onnx(...)` and `runner.export_policy_to_jit(...)`. | -| APPO | `src/unilab/scripts/train_appo.py` | Playback writes `policy.onnx` and verifies ONNX Runtime output against PyTorch. | -| SAC / FlashSAC | `src/unilab/scripts/train_sac.py` / `src/unilab/scripts/train_flashsac.py` | Playback writes `policy.onnx`; SAC and FlashSAC use `actor.as_export_module()` before export. | +| PPO (torch) | `src/unilab/scripts/train_rsl_rl.py` | When run as a script, the entrypoint sets `EXPORT_POLICY=True`; playback calls `runner.export_policy_to_onnx(...)` and `runner.export_policy_to_jit(...)`. This path does not call UniLab's ONNX Runtime verification helper. | +| APPO | `src/unilab/scripts/train_appo.py` | Playback writes `policy.onnx`, then compares ONNX Runtime output with PyTorch on one random input. | +| SAC / FlashSAC | `src/unilab/scripts/train_sac.py` / `src/unilab/scripts/train_flashsac.py` | Shared playback in `src/unilab/scripts/train_offpolicy.py` writes `policy.onnx` when `training.export_onnx=true` (the default), uses `actor.as_export_module()`, and runs the same comparison. | ## Commands @@ -25,22 +24,31 @@ uv run eval --algo sac --task g1_walk_flat --sim mujoco --load-run -1 `uv run eval` sets playback mode and maps `--load-run` to the checkpoint selector used by the routed training script. The exported file is written into -the selected run directory. For deployment, keep the exported `policy.onnx` -together with the task owner YAML it was trained from — that YAML is the -authority on the observation and action contract the runtime must reproduce. +the selected run directory. For deployment, keep `policy.onnx` together with +that run's `run_config.json` and the task owner YAML path. The composed run +configuration records the observation, action, and algorithm settings that the +runtime must reproduce. ## Verifying the Exported Graph -The playback path validates the exported graph against PyTorch before writing -it, so a successful export already establishes numerical parity. What it does -**not** establish is that your hardware-side loop assembles the same input -vector. Before hardware bring-up: +Do not infer numerical parity from the existence of `policy.onnx`. Export and +verification run inside a non-fatal playback guard. For APPO/SAC/FlashSAC, the +helper uses ONNX Runtime's `CPUExecutionProvider` on one random input and prints +`ONNX export verified OK.` when maximum absolute difference is at most `1e-4`; +a larger difference only prints a warning. PPO playback does not perform this +UniLab check. + +This sample comparison does **not** establish parity for every input or prove +that your hardware loop assembles the same input vector. When SAC/FlashSAC +playback has an observation normalizer, it applies that normalizer before +calling the exported actor and before verification, so raw-observation +preprocessing remains part of the deployment contract. Before hardware bring-up: - Read the actor obs width off the composed config (not off a doc table) and confirm it matches the ONNX input width. -- Confirm your term order and per-term history ordering against the owner's - `env.observations.actor.terms`. For G1 whole-body tracking, see - {doc}`2-g1_whole_body`. +- Confirm term order, scaling, normalization, and any per-term history against + the group named by `env.policy_observation_group`. For G1 whole-body tracking, + see {doc}`2-g1_whole_body`. ## See Also diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/6-domain_randomization.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/6-domain_randomization.md index 732f7b58d..350baf76e 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/6-domain_randomization.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/6-domain_randomization.md @@ -21,7 +21,7 @@ This page is the deployment checklist for domain randomization. For the - Affects balance and tracking margins. * - Friction - Foot ↔ ground μ, hand ↔ object μ - - In-hand cube tasks fail without this. + - Changes contact, locomotion, and grasp behavior. * - Observation noise - IMU noise, joint encoder bias, deploy-side observation history - Keeps actor inputs close to deploy-side sensor behavior. @@ -49,11 +49,11 @@ The legacy task-level provider protocol has been removed. The capability boundary is described in {doc}`../../4-developer_guide/2-contracts/4-dr_contract`. -## Recipe: starting ranges +## Example from a retained owner -Use the selected owner YAML as the source of truth. This excerpt shows a -PD-gain term; evaluate absolute gain ranges together with the robot's control -settings. +Use the selected owner YAML as the source of truth. This is the absolute PD-gain +reset term in `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml`, not a +recommended hardware range or a hardware-validated safe envelope: ```yaml env: @@ -62,11 +62,15 @@ env: func: unilab.envs.mdp.pd_gains mode: reset params: - kp_range: [17.5, 70.0] - kd_range: [0.25, 1.0] + kp_range: [31.5, 38.5] + kd_range: [0.45, 0.55] operation: abs ``` +Here `operation: abs` samples absolute gains rather than multipliers of the +nominal gains. Other owners may use `operation: scale` or disable the term on a +backend that does not support it. + ## Curriculum: ramp DR with skill DR that's too aggressive at step 0 stalls learning. UniLab curriculum diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/7-safety_layers.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/7-safety_layers.md index cfdfdb809..0af952567 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/7-safety_layers.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/7-safety_layers.md @@ -1,10 +1,12 @@ # Hardware Safety Layers The policy produces actions under the training contract. A deploy-side safety -layer must live **between the policy output and the motor driver** and reject -contract violations before they become actuator commands. +layer should live **between the policy output and the motor driver** and reject +contract violations before they become actuator commands. The following is a +design checklist, not a set of safety guarantees implemented or hardware-tested +by UniLab. -## Required components +## Recommended deploy-side components ```{list-table} :header-rows: 1 @@ -13,63 +15,70 @@ contract violations before they become actuator commands. * - Layer - Responsibility * - Schema check - - Action has correct dtype, shape, finite values. Reject NaN / Inf. + - Check action dtype, shape, and finite values; reject NaN / Inf. * - Range clamp - - Clamp each joint target to deploy-configured joint limits. + - Clamp each joint target to validated deploy-side joint limits. * - Δ clamp - Reject or clamp per-step action deltas using a threshold owned by the deploy controller. * - Rate limit - - Slew-rate limit applied AFTER clamp. + - Apply a validated slew-rate limit after clamping. * - Watchdog - - If no fresh action arrives within the controller-owned timeout, hold the - last known safe target or enter the controller's safe state. + - On stale actions, enter a controller-defined state that has been verified + safe for the robot; do not assume that holding the last target is safe. * - Pose monitor - - Roll / pitch outside operating envelope → triggered fault. + - Trigger a fault when roll / pitch leaves the validated operating envelope. * - Operator stop - - Big red button → instant torque-disable, regardless of state. + - Provide an independent stop path and verify its torque-removal behavior + according to the robot/controller safety design. ``` ## Where the safety layer lives ```{mermaid} flowchart LR - P[Policy ONNX] --> S[Safety layer
C++ on robot computer] - S -->|safe target| D[Motor driver] + P[Policy ONNX] --> S[Deploy-side safety layer] + S -->|checked target| D[Motor driver] D -->|encoder + IMU| Pre[Observation builder] Pre --> P S -.->|fault| OP[Operator UI] - OP -.->|E-stop| D + OP -.->|stop path| D ``` -Keep the hard real-time safety checks in the deploy controller, not in the -training script. The repository does not implement a production motor-driver -safety loop — that boundary is yours to build and test. +Keep hard real-time safety checks in the deploy controller, not in the training +script. The repository does not implement a production motor-driver safety +loop, watchdog, pose monitor, or emergency stop. Software clamps and policy +checks are not substitutes for an independently designed safety function. -## What the policy assumes you've configured +Training-side `BaseAction` does check action tensor shape, dtype, and device and +records finite-value verdicts. Its affine output clamp runs only when `clip` is +configured; the retained G1/Go2 owners do not configure that key. These checks +do not provide a hardware safety guarantee. -The policy expects the action mapping and limits its training owner declared: +## Action mapping inputs + +Derive the deploy-side mapping from the selected owner and composed scene: | Quantity | Authority | | --- | --- | -| action scale | `env.actions.joint_pos.scale` (scalar `2.0` for this owner; other owners declare a regex → value map resolved per actuator) | -| default angles | `use_default_offset: true`, i.e. the `stand` keyframe joint block of the owner's scene XML | -| joint limits | `jnt_range` in the scene XML | -| `kp` / `kd` | position actuator `gainprm` / `biasprm` in the scene XML | +| action scale | `env.actions.joint_pos.scale`, as a scalar or a regex → value map resolved per actuator | +| default angles | `use_default_offset: true` and the scene's `default_keyframe_name` (`stand` for current G1 owners, `home` for Go2) | +| joint limits | joint ranges in the composed scene; these are not automatically a deploy-side action clamp | +| nominal `kp` / `kd` | position-actuator `kp` / `kv` in the composed robot XML, plus any enabled `env.events.pd_gains` reset randomization | -Derive these from the owner YAML and its scene, and reproduce the owner's -resolved per-actuator scale exactly — a scalar owner and a regex-map owner are -not interchangeable. Do not hand-copy joint ranges or gains into a second place -that can silently drift from the asset. +Reproduce the owner's resolved per-actuator scale exactly — scalar and regex-map +owners are not interchangeable. For G1 motion tracking, also account for motion +and encoder bias terms. Avoid hand-copying values into a second place that can +silently drift from the selected assets and run configuration. ## Hand-off testing -Before integrating policy → safety → motor, test the safety layer in -isolation: +Before integrating policy → safety → motor, test the safety layer in isolation. +These are recommended deploy-side tests, not tests UniLab has run on hardware: 1. Inject a NaN action and verify the command is rejected. -2. Inject an out-of-range joint target and verify clamping uses the joint range - from the owner's scene XML. +2. Inject an out-of-range joint target and verify clamping uses the validated + joint limits. 3. Cut the policy feed mid-run and verify the controller enters its configured safe state. diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/8-latency_budget.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/8-latency_budget.md index 93b21d858..90509dedb 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/8-latency_budget.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/8-latency_budget.md @@ -1,38 +1,54 @@ # Latency Budget -This page documents the latency controls that are visible in the repository and -the deploy-side measurements you need before hardware bring-up. Treat numeric -budgets as robot-specific measurements, not UniLab defaults. +This page documents the latency controls visible in the repository and the +deploy-side measurements needed before hardware bring-up. Treat numeric budgets +as robot-specific measurements, not UniLab defaults or hardware results. ## Latency Surfaces In Repo -| Surface | Repo evidence | What it covers | +| Surface | Configuration and units | Behavior | | --- | --- | --- | -| One-step action delay | Manager action term `simulate_action_latency` declarations in task owners | Executes the previous action instead of the current action. | -| Observation history | Per-term `history_length` declarations in task owners | Per-term history for selected observation terms. | -| Obs history ordering | `ObservationManager` per-term history buffers (`tests/managers/test_observation_buffers_noise.py`) | Per-term oldest-first flatten for actor observations. | +| Joint-position target delay | `env.actions.joint_pos.delay_min_lag` / `delay_max_lag`, integer **physics substeps** | `JointPositionAction` delays the processed position target. | +| G1 motion one-tick action delay | `simulate_action_latency` on `MotionJointPositionActionCfg`, one **control tick** | Uses the previous raw action instead of the current raw action. | +| Observation delay | Per-term `delay_min_lag` / `delay_max_lag`, integer **control steps** | `ObservationManager` samples lag in the inclusive range; set min=max for fixed delay. | +| Observation history | Per-term `history_length`, a number of frames including the current frame | Stores and optionally flattens history; history alone is not an added delay. | + +The retained G1 motion and Go2 owners leave these delays at zero and declare no +observation history. Their `env.ctrl_dt` is `0.02` s (20 ms, 50 Hz), but action +`delay_*_lag` uses `env.sim_dt`, not `ctrl_dt`: Go2 uses 10 ms physics substeps +and the G1 motion owners use 6.666… ms substeps. Convert observation or +one-tick action latency with `lag * ctrl_dt`, and joint-target delay with +`lag * sim_dt`. ## Action Latency -For Manager-Based tasks that enable action latency, the action manager applies -the previous action when the flag is enabled. Keep this in the selected task -owner YAML instead of adding deploy-only behavior later. +For a fixed 2-substep joint-position target delay: ```yaml env: actions: joint_pos: - simulate_action_latency: true + delay_min_lag: 2 + delay_max_lag: 2 ``` +For G1 motion tracking, `simulate_action_latency: true` instead selects the +previous raw action once per control tick. These are different mechanisms and +units; do not combine their lag counts as if both were milliseconds. Keep the +chosen settings in the selected task owner and retrain rather than adding +deploy-only delay later. + ## Observation Lag And History -Observation width is the sum of `dim * history_length` over the declared actor -terms, not something a hardware runtime may guess. Terms carrying -`history_length` are flattened oldest-first within each term while other terms -stay single-step. +Set observation `delay_min_lag` and `delay_max_lag` on the specific term in the +selected policy group. Do not lag command/reference terms unless the training +owner did so. -Do not lag command/reference terms unless the training owner did so. +For a concatenated flat group with `flatten_history_dim=true`, a term without +history contributes its base dimension; a term with history contributes +`base_dim * history_length`. History frames are flattened oldest-first within +each term, while terms remain in declaration order +(`tests/managers/test_observation_buffers_noise.py`). ## Deploy-Side Measurements @@ -47,7 +63,8 @@ Record these per policy tick in the hardware runtime: Compare the observation vector against a sim rollout built from the same task owner YAML. If the measured pipeline needs filtering or buffering, encode the matching behavior in the task owner and retrain, rather than adding it only on -the deploy side. +the deploy side. Synthetic MLP benchmarks under `scripts/benchmark/compute/` +do not measure this end-to-end sensor-to-actuator path. ## Symptoms Of Mismatch @@ -60,4 +77,5 @@ the deploy side. - {doc}`6-domain_randomization` - {doc}`7-safety_layers` -- `src/unilab/managers/event_manager.py` +- `src/unilab/envs/mdp/actions/actions.py` +- `src/unilab/managers/observation_manager.py` diff --git a/docs/sphinx/source/en/3-deployment/1-sim_to_real/9-troubleshooting.md b/docs/sphinx/source/en/3-deployment/1-sim_to_real/9-troubleshooting.md index 8bdbaaa8a..1f7954592 100644 --- a/docs/sphinx/source/en/3-deployment/1-sim_to_real/9-troubleshooting.md +++ b/docs/sphinx/source/en/3-deployment/1-sim_to_real/9-troubleshooting.md @@ -1,38 +1,36 @@ # Sim-to-Real Troubleshooting -A cookbook of symptoms → likely causes → fixes. When a deployment goes -sideways, start here. +A cookbook of symptoms → possible causes → checks. ## High-frequency joint oscillation / "buzz" -| Likely cause | Check | Fix | +| Possible cause | Check | Next step | |---|---|---| -| State estimator velocity bias | Log `base_lin_vel` vs ground truth (motion capture) | Tune the state estimator | -| PD gains too high vs trained | Compare driver Kp/Kd against owner YAML | Match training values; or retrain with realistic Kp/Kd DR | -| Action latency too low in training | Sweep `torque_delay_ms` in DR | Retrain with measured-latency × 1.5 | -| Velocity noise too low | Compare encoder σ in sim vs hardware | Increase `joint_vel_noise_std` in DR | +| State estimator velocity bias | If the actor uses `base_lin_vel`, compare it with an independent measurement | Tune the estimator or train against the observation the deploy estimator can provide | +| PD gains differ from training | Compare driver Kp/Kd with nominal scene gains and the owner's `env.events.pd_gains` range | Match the trained values or retrain with measured gain variation | +| Action latency differs from training | Compare measured target delay with `delay_min_lag` / `delay_max_lag` (physics substeps) or G1 motion `simulate_action_latency` (one control tick) | Match the measured delay with the correct units and retrain | +| Velocity noise differs from training | Compare encoder noise with `env.observations..terms.joint_vel.noise` | Adjust the selected owner's noise model; `UniformNoiseCfg` uses `n_min` / `n_max`, not `joint_vel_noise_std` | ## Drift while standing / walking -| Likely cause | Check | Fix | +| Possible cause | Check | Next step | |---|---|---| -| IMU bias not calibrated | Robot static, check `gyro_bias` | Run 30-second calibration before policy start | -| Foot contact misclassified | Check contact event timestamps | Hysteresis on contact force threshold | +| IMU bias not calibrated | Record gyro output while the robot is stationary | Follow the robot/SDK calibration procedure; UniLab does not define a universal 30-second calibration | +| Foot contact misclassified | Check contact event timestamps where the selected task uses contact | Validate the deploy contact source and any threshold hysteresis | ## Policy succeeds in sim, falls on hardware immediately -Almost always one of: - -1. **Joint order swapped.** Inspect `policy.onnx` input width and the joint - order in your motor driver against the training scene XML - (`src/unilab/assets/robots//scene_flat.xml`). -2. **Action scale unit mismatch.** Policy outputs unscaled values; the - driver expects rad, but you fed it normalized [-1, 1]. Apply the - `env.actions.joint_pos.scale` / default-angle convention from the training - owner YAML before sending targets to the driver, reproducing the owner's - resolved per-actuator scale exactly. -3. **Observation layout mismatch.** Compare what your hardware loop assembles - against the owner's `env.observations.actor.terms` — term order first, then +First check these contract errors: + +1. **Joint order swapped.** Inspect the `policy.onnx` input/output widths and + compare motor-driver order with `env.scene.entities.robot.joint_names`, + `actuator_names`, and the selected `env.scene.model_file`. +2. **Action scale or unit mismatch.** Raw actor output is not necessarily + normalized to [-1, 1]. Apply the selected owner's + `env.actions.joint_pos.scale`, default-offset, and any motion/encoder-bias + convention before sending joint-position targets in radians to the driver. +3. **Observation layout mismatch.** Compare the hardware vector with the group + named by `env.policy_observation_group` — term order, scaling, and then any per-term history ordering. ## Policy succeeds in MuJoCo but fails in Motrix (or vice versa) @@ -43,14 +41,17 @@ That's a **sim-to-sim** problem, not sim-to-real. See ## What to capture before opening a bug report -When the lab WhatsApp blows up at 11 pm, save the following so the -investigation tomorrow takes 30 minutes instead of 4 hours: - - Full hardware trace (`obs / action / wall_clock` for the entire run). -- Sim-side YAML used to train: `runs//config.yaml`. +- The selected run's `run_config.json`; by default runs live under + `logs////`. - `policy.onnx` and the exact task owner YAML path it was trained from. -- One sim rollout video using **the same** seed: `eval --seed - --render-mode record`. +- A sim rollout video from that checkpoint with an explicitly recorded seed: + + ```bash + uv run eval --algo --task --sim \ + --load-run -1 --render-mode record algo.seed= + ``` + - A `git diff` between the run's commit and `main` if any. ## See also diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/0-index.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/0-index.md index 09fbc9c19..961b15c2b 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/0-index.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/0-index.md @@ -1,7 +1,7 @@ # Sim-to-Sim -Move the same task between MuJoCo and Motrix through owner YAMLs and backend -contracts. +Move a task between supported physics backends through owner YAMLs and +capability contracts. Check policy I/O, physics, rewards, and playback separately. ::::{grid} 1 1 2 2 :gutter: 3 @@ -30,10 +30,10 @@ Align contact-related assumptions across simulators. Check reward terms near backend boundaries. ::: -:::{grid-item-card} Playback differences +:::{grid-item-card} Playback and snapshots :link: 5-playback_and_snapshot_differences :link-type: doc -Understand renderer and snapshot capability differences. +Distinguish renderer routes, physics-state snapshots, and training config snapshots. ::: :::{grid-item-card} Capability gaps diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/1-backend_swap.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/1-backend_swap.md index a7c9d7e4e..fa1e9a4bc 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/1-backend_swap.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/1-backend_swap.md @@ -1,47 +1,62 @@ # Backend Swap -UniLab supports two CPU physics backends: **MuJoCo** (via the official `mujoco` -package plus the `mjbatch` batch engine) and -**Motrix** (via `motrixsim-core`). Both implement the same `SimBackend` -contract and the same env contract. Backend-specific behavior is exposed -through explicit methods and capability records. +UniLab's registry and CLI currently recognize `mujoco`, `mjwarp`, `genesis`, +`newton`, `motrix`, `mtxwarp`, `superdex`, `drake`, `isaacsim`, and `isaacgym`. +Support is the combination of an algorithm/task/backend owner YAML, a registered +environment factory, and the capabilities required by that task. -| Axis | MuJoCo | Motrix | -|---|---|---| -| Backend class | `unisim.backend.mujoco.backend` | `unisim.backend.motrix.backend` | -| Playback capabilities | Physics-state playback in `get_play_capabilities()` | Native interactive renderer and native video capture in `get_play_capabilities()` | -| Height-field scan | Implements `bind_height_scanner(...)` | Implements `bind_height_scanner(...)` | -| DR capability reporting | `get_dr_capabilities()` | `get_dr_capabilities()` | +Backend-specific behavior belongs behind `unisim.backend.base.SimBackend` and +in owner configuration. Do not add backend branches to environment hot paths. -**The right reason to switch** is one of: +For example, the two CPU host-bridge backends expose these capabilities through +their current UniSim adapters: -1. The target task has an owner YAML for the other backend. -2. The backend exposes the capability the workflow needs. -3. You want a sim-to-sim parity check before deployment or a backend change. +| Axis | MuJoCo | Motrix | +|---|---|---| +| Adapter module | `unisim.backend.mujoco.backend` | `unisim.backend.motrix.backend` | +| Physics-state playback | Yes | Yes | +| Native interactive renderer / video capture | No | Yes, except in whole-model-variant mode | +| Height-field scanner | `bind_height_scanner(...)` | `bind_height_scanner(...)` | +| DR support | Runtime `get_dr_capabilities()` | Runtime `get_dr_capabilities()` | -Switching is still a task-owner change, not an ad hoc runtime tweak. +These capability values are not interchangeable with task support or physical +parity. Other backends have different playback profiles; see +{doc}`5-playback_and_snapshot_differences` and {doc}`6-capability_gaps`. ## How to switch -UniLab does **not** support backend choice via passthrough Hydra overrides. The -backend is part of the *task owner identity* selected by `--task` and `--sim`: +Select the algorithm, task, and backend with CLI flags: ```bash -# wrong — backend is not an override -uv run train --algo ppo --task go2_joystick_flat --sim mujoco training.sim_backend=mujoco - -# right — choose the backend with --sim -uv run train --algo ppo --task go2_joystick_flat --sim mujoco uv run train --algo ppo --task go2_joystick_flat --sim mujoco +uv run train --algo ppo --task go2_joystick_flat --sim motrix +``` + +`--task` and `--sim` select the owner identity. The CLI rejects passthrough +`task` and `training.sim_backend` overrides as backend-selection mechanisms. +For these commands, the corresponding owners are +`src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml` and +`src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml`. + +Training requires the selected owner YAML to exist. Evaluation has a narrow +fallback for a missing target owner: it can reuse a sibling owner and then run +the same contract preflight. That fallback is not evidence that the target +backend supports the task, and it is not a general backend switch; see +{doc}`7-config_guard`. + +Before reusing a checkpoint, audit the composed policy-I/O contract and then +run task-specific physics and reward checks: + +```bash +uv run scripts/audit_sim2sim_contracts.py --trees ppo ``` -The CLI resolves `--algo`, `--task`, and `--sim` to an owner YAML such as -`src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml`. If that file doesn't exist, the -task **does not support** the backend — see -{doc}`../../4-developer_guide/2-contracts/3-task_owner`. +A `TRANSFERABLE` audit verdict covers only the fields compared by that script. +It does not prove contact, reward, convergence, or renderer parity. ## See also - {doc}`2-owner_yaml_swap` - {doc}`4-reward_parity` - {doc}`6-capability_gaps` +- {doc}`7-config_guard` diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md index fe6863a1b..3756d4979 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md @@ -1,57 +1,90 @@ # Adding a Backend YAML to an Existing Task -You have a task that runs on, say, Motrix. You want it on MuJoCo too. This -page is the recipe. - -## What you DON'T do - -- Add backend branching in Python. Backend-specific behaviour lives in the - backend adapter and the owner YAML, never in env code. This is the - ironclad rule of {doc}`../../4-developer_guide/2-contracts/2-backend_contract`. -- Set `training.sim_backend` as an override. That field is an **identity - echo** of the owner YAML, not a switch. - -## What you DO - -1. Copy the existing owner YAML: - ```bash - cp src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml \ - src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml - ``` -2. Inside the new file, set `training.sim_backend: mujoco`. -3. Adjust the **physical parameters** the new backend needs: - - Contact friction / damping — MuJoCo uses solver parameters per - contact pair; Motrix uses material props. Make sure your task asset - file under `src/unilab/assets/robots//` declares the values the - backend needs. - - Solver settings and timestep — keep them in the owner YAML or backend - adapter that owns the behavior. -4. Re-resolve any backend-conditional DR ranges. Some randomizations are - meaningful on one backend but no-ops on the other (e.g. friction - damping coefficient). -5. Verify the env/backend pair is registered and importable through the - registry bootstrap (see - {doc}`../../4-developer_guide/1-architecture/5-registry`). +Use this recipe when a task already has a canonical owner contract and you want +to add another backend. The shared contract lives in `base.yaml`; each backend +leaf owns only backend identity, tuning, rendering/placement, and explicit +capability adaptations. + +## What not to do + +- Do not branch on backend names in environment or training code. Required + behavior must be exposed through `SimBackend` and negotiated through its + capabilities. See + {doc}`../../4-developer_guide/2-contracts/2-backend_contract`. +- Do not use `training.sim_backend` as a standalone CLI override. Inside a + backend leaf it is an identity declaration; the public selector is `--sim`. +- Do not inherit one backend leaf from another. Cross-backend inheritance hides + changes to the composed task contract. + +## Owner layout + +For `src/unilab/conf//task//`: + +1. Keep the complete shared scene, observations, actions, commands, rewards, + terminations, canonical events, and shared training budget in `base.yaml`. + The base file is not a trainable owner and has no `training.sim_backend`. +2. Add `.yaml` with exactly the same-directory base and `_self_` in + `defaults:`. Declare `training.task_name` and `training.sim_backend` in the + leaf itself. +3. Put only real backend differences in the leaf: timestep/solver/capacity + fields, render settings, algorithm tuning, and event terms that are narrowed + or explicitly disabled with `null`. + +A minimal leaf has this shape: + +```yaml +# @package _global_ +defaults: + - /task/go2_joystick_flat/base + - _self_ + +training: + task_name: Go2JoystickFlat + sim_backend: motrix + +# Add only backend-owned tuning or explicit event adaptations here. +``` + +Do not copy another backend's command ranges, reward weights, or observation +normalization merely to make replay pass. Those values define task behavior, +not renderer settings. The composition rule and its tests are recorded in +{doc}`/adr/ADR-0023-task-sim-owner-inherits-same-directory-base-only`. + +## Physics and capability review + +- Keep `env.sim_dt` and `env.ctrl_dt` explicit and verify that their ratio gives + the intended control decimation. Use owner fields such as + `env.motrix_max_iterations`, `env.genesis_integrator`, + `env.genesis_solver_iterations`, `env.mjwarp_nconmax`, or + `env.mjwarp_njmax` only for the backend that owns them. +- Review friction, contact solver settings, sensors, actuator models, and reset + defaults in the task/robot XML. A shared MJCF does not imply identical + physics after import. +- Check every requested DR term against `get_dr_capabilities()`. If the target + cannot implement it, either extend the public backend contract or explicitly + disable/narrow that event in the target leaf and record the training + difference. Unsupported capabilities must not become silent no-ops. +- Register the task's generic Manager-Based factory for the new backend. If a + required capability is missing, fail during cold-path binding rather than + probing backend-private objects. ## Validation gate -Before claiming the backend is supported, you need (at minimum): +Compose the new owner and run a real registered-backend reset followed by +several tensor steps. Then compare nominal contacts and reward components using +{doc}`3-contact_and_friction_alignment` and {doc}`4-reward_parity`. -- One training run that reaches the same success threshold as the - reference backend, *or* a documented reason it doesn't (e.g. capability - gap). -- Reward parity check: see {doc}`4-reward_parity`. -- A test added under `tests/` that imports the env in the new backend and - runs `reset` + `step(10)` without error. +Audit all applicable owner trees, not just the new file: -::::{admonition} Evidence grades -:class: note -After validation, refresh the generated support data if the support status -changed: +```bash +uv run scripts/audit_sim2sim_contracts.py --trees ppo appo sac flashsac +``` + +The audit has a fixed set of compared backend pairs. `N/A` means that no pair +was audited, not that transfer is supported. A `TRANSFERABLE` result is only a +policy-contract result; support claims still need runtime and task evidence. +When support status changes, refresh the generated support data: ```bash uv run scripts/generate_support_matrix.py --write ``` - -See {doc}`/glossary` for the evidence-grade definitions. -:::: diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md index 8d75eb85a..11da8f9e5 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md @@ -1,36 +1,61 @@ # Aligning Contact and Friction Between Backends -Contact handling is a common source of MuJoCo-vs-Motrix drift. This page shows -you how to identify and close the gap. +Contact import, solver behavior, and sensor semantics are common sources of +cross-backend drift. Align them before interpreting reward or policy-return +curves. -## Diagnostic: probe contact early +## Diagnostic protocol -Run the same owner YAML, reset seed, and deterministic action sequence in both -backends. Log contact-dependent reward terms from `info["log"]` and any -backend-owned contact signals the env already uses. If the nominal contact -response differs before policy learning is involved, fix the friction / damping -/ restitution declarations before debugging reward parity. +Compose each backend's own owner; do not reuse the source backend's leaf as a +Hydra override. Fix the owner seed and, where exact initial-state comparison is +required, set the same explicit reset state. Replay the same deterministic +action tensor sequence. -## Common pitfalls +At each step, record the contact sensors used by the task and +`state.info["reward_components"]` when available. The latter is the full-width +weighted reward tensor before environment-`dt` scaling. `env.publish_reward_log()` +returns the corresponding per-term means as `reward/`. Do not assume that +`info["log"]` contains per-term rewards on every training path: native RSL-RL +PPO logging does not emit those TensorBoard keys. -| Pitfall | Symptom | Fix | +Inspect the first divergent transition rather than only the final episode +return. Once trajectories diverge, later differences no longer isolate a +contact parameter. + +## Alignment checklist + +| Area | What to verify | Current owner boundary | |---|---|---| -| Friction declared on geom in MuJoCo but on material in Motrix | One backend has μ=0 | Declare on both; verify in scene export | -| Solver iterations too low | MuJoCo sinks into floor | Increase the backend-owned solver setting in the owner YAML | -| Contact-pair specific overrides | Inconsistent slip | Make pair-level overrides explicit in both backend YAMLs | -| Restitution mismatch | Bouncy vs sticky landing | Set explicitly; defaults differ | +| Geom friction | All three friction coefficients, selected geoms, collision masks, and contact-pair behavior | Task/robot XML plus the backend's imported values | +| Solver and integration | Timestep, integrator, iterations, contact capacity, and constraint behavior | `env.sim_dt`, `env.ctrl_dt`, and backend-owned fields such as `env.motrix_max_iterations`, `env.genesis_solver_iterations`, `env.mjwarp_nconmax`, and `env.mjwarp_njmax` | +| Compliance and restitution | Solver reference/impedance and restitution behavior, not just nominal friction | Asset declarations and backend import/materialization evidence | +| Contact observations and rewards | Sensor type, force/contact threshold, coordinate frame, and update timing | Named public sensor bindings and the terms in `env.observations` / `reward` | + +There is no universal translation for every engine's contact parameters. Keep +any approximation explicit in the target owner; for example, the SuperDex Go2 +owner sets `env.superdex_allow_contact_approximation: true` rather than +claiming MuJoCo-equivalent contact. ## Aligning DR ranges -Once contact is aligned for the **nominal** parameters, audit DR: +Current Manager-Based friction DR uses an `env.events.` term with +`func: unilab.envs.mdp.geom_friction`. Its `params` include `ranges`, +`operation`, optional `axes`, and `shared_random`; it does not use fields named +`friction_static_mu` or `friction_dynamic_mu`. + +Check the actual randomization stream, selected geom IDs, default values, and +backend capabilities. Unsupported terms fail closed during capability binding; +they are not warning-only no-ops. A backend leaf may explicitly disable an +unsupported event, but that changes the training distribution and must be +reviewed as such. For example, current SAC/FlashSAC G1 motion owners disable +`foot_friction` on Genesis, while the Motrix owner disables `push_robot`. -- `friction_static_mu` and `friction_dynamic_mu` should be sampled - identically in both backends. -- If a DR field is a no-op in one backend, log a warning at episode init. - Silent ignorance leads to silent reward drift. +After nominal contact and DR are aligned, run the reward-parity protocol in +{doc}`4-reward_parity`. A passing config guard does not perform any of these +physical checks. ## See also +- {doc}`2-owner_yaml_swap` - {doc}`4-reward_parity` -- {doc}`../1-sim_to_real/6-domain_randomization` - {doc}`6-capability_gaps` diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/4-reward_parity.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/4-reward_parity.md index 0a9624b2c..71c4541a2 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/4-reward_parity.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/4-reward_parity.md @@ -1,48 +1,64 @@ # Reward Parity Across Backends -Two backends with "the same" reward function rarely produce **numerically -identical** rewards — and that's fine. What you want is **trajectory-level -parity**: the same policy, applied to the same initial state, produces a -similar reward curve. +A shared reward declaration does not guarantee numerically identical rewards. +Physics, sensor timing, and contact behavior can diverge. The useful check is a +fixed-transition comparison followed by a trajectory-level evaluation with +explicit, task-defined tolerances. ## The protocol -1. Freeze a **fixed seed**, fixed initial state, fixed action sequence. - The action sequence can be a sinusoidal sweep over joints, or a replay - from a real rollout — anything deterministic. -2. Replay it in both backends. Log per-step reward components from - `info["log"]`; locomotion reward dispatch writes `reward/` entries - there when reward logging is enabled. -3. For each reward term, compare the two time series and inspect the first - frame where they diverge. +1. Compose both target owners. Fix the seed, initial/reset state, action + sequence, observation inputs, and command inputs. Use a recorded rollout or + another deterministic action tensor sequence. +2. Replay the sequence in both backends and inspect the first divergent + transition. Record total reward and every reward component before comparing + long-episode returns. +3. Check units, coordinate frames, contact timing, termination/truncation + masks, and final observations at that transition. Then compare complete + trajectories and define acceptable tolerances for the task. -## What good parity looks like +Manager-Based environments expose full-width weighted components in +`state.info["reward_components"]`. `env.publish_reward_log()` exposes their +per-term means as `reward/`, before environment-`dt` scaling. With the +default `env.scale_rewards_by_dt: true`, total `state.reward` includes the +additional `env.ctrl_dt` multiplier. Account for that difference instead of +comparing a pre-`dt` component directly with total reward. -| Term type | What to inspect | +SAC/FlashSAC off-policy logging publishes these per-term metrics. RSL-RL PPO +and current Manager-Based APPO do not emit per-term reward keys, so use a +direct environment probe for their parity checks rather than searching their +training logs. + +## Interpretation + +| Observation | What to inspect first | |---|---| -| Smooth penalties | Same units, frames, and command inputs. | -| Contact-conditional terms | Contact timing and sensor availability in both backends. | -| Termination penalties | The termination mask and final-observation path. | +| A smooth penalty differs immediately | Units, action scaling, command values, observation frame, and `ctrl_dt` | +| A contact-conditional term differs | Sensor availability, thresholds, contact timing, and update order | +| A termination penalty differs | Non-timeout termination versus timeout masks and final-observation handling | +| Terms agree initially but diverge later | The first physics/contact divergence; later returns are not an isolated reward test | +| A term is zero or missing | Whether the owner disabled it and whether the required backend capability exists | -## What's a red flag +Do not treat late trajectory divergence alone as proof of a reward bug, and do +not infer backend capability from a zero value without checking the owner and +sensor bindings. -- **Diverging reward late in episode.** Usually means the policy explores - different state distributions in each backend, which usually means - contact / friction mismatch. See - {doc}`3-contact_and_friction_alignment`. -- **One reward term zero in one backend.** Capability gap: the term reads - a feature one backend doesn't expose. See - {doc}`6-capability_gaps`. +## Automation and guard boundaries -## Automating it +There is no standalone reward-parity script. Put deterministic comparisons near +the task/backend boundary in `tests/`, and assert on explicitly chosen +components and tolerances. -The repository does not currently include a standalone reward-parity helper in -`scripts/`. When adding parity coverage, keep the test close to the -backend/task-owner boundary: compose both owner YAMLs, reset with a fixed seed, -replay a deterministic action sequence, and assert on the logged reward -components under `tests/`. +`uv run scripts/audit_sim2sim_contracts.py` is a config audit, not this reward +check. Its `WARNING_LIST` contains only `reward.scales`, +`reward.base_height_target`, `reward.max_tilt_deg`, +`reward.min_base_height`, and the legacy action-latency field. The complete +current Manager-Based `reward` mapping, including `reward..weight`, is +not captured wholesale by the sim2sim snapshot. Reward parity therefore remains +necessary even when the config guard passes. ## See also - {doc}`3-contact_and_friction_alignment` +- {doc}`7-config_guard` - {doc}`../../4-developer_guide/2-contracts/2-backend_contract` diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md index d303671c3..49dc28abd 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md @@ -1,38 +1,61 @@ # Playback and Snapshot Differences -Beyond the physics step itself, the two backends differ in **how they let -you replay** a run. This page captures the practical implications. - -## Playback - -| Backend | Mechanism | Best for | -|---|---|---| -| MuJoCo | Physics-state playback path reported by `supports_physics_state_playback` | Record-mode playback and offline video export | -| Motrix | Native interactive renderer and native video capture reported by `get_play_capabilities()` | Interactive playback and record-mode capture | - -Both backends resolve `training.play_render_mode` through -`SimBackend.resolve_play_render_plan(...)`; unsupported modes should fail at -the backend boundary instead of branching in training scripts. - -## Snapshot - -MuJoCo currently reports `supports_physics_state_playback=True`. Motrix reports -native interactive rendering and native video capture instead. Treat these as -different backend capabilities rather than feature parity. - -The capability-boundary contract -({doc}`../../4-developer_guide/2-contracts/2-backend_contract`) requires that -*neither* env code nor algorithm code call snapshot-only paths directly — -it must be routed through a capability-aware abstraction. ADR-0002 -codifies this. - -## What to put in your task owner - -If a task starts to require a playback or snapshot capability, add that need to -the backend contract first, then validate it at the env/backend boundary. Do not -hide the requirement in a training script branch. +Playback has two independent choices: which backend advances physics, and +which renderer presents the resulting state. Do not infer one from the other. +`--sim` selects the physics owner; `--render-mode` selects the play route. + +## Current playback profiles + +| Backend | Physics-state playback | Native interactive renderer / video | UniLab playback route | +|---|---|---|---| +| MuJoCo | Yes | No / No | Shared MuJoCo interactive and offline rendering | +| MJWarp | Yes | No / No | MJWarp physics with the shared MuJoCo renderer; owners normally use explicit `record` | +| Motrix | Yes | Yes / Yes, except in whole-model-variant mode | Native `interactive` / `record`, or a physics-state frontend when supported | +| Genesis | Yes in the UniSim adapter | Yes / Yes | Native `interactive` / `record`; top-level `eval --render-mode viser` currently rejects Genesis explicitly | + +For native backend playback, `training.play_render_mode` is resolved through +`SimBackend.resolve_play_render_plan(...)`. Unsupported modes fail at that +boundary. Viser is a UniLab-level exception: it uses the physics-state playback +contract and per-environment MuJoCo playback models, bypasses the backend's +native render-plan resolver, and does not record a video. + +Use the top-level CLI so owner composition, play-only injection, and contract +preflight all run: + +```bash +# Record a G1 rollout with MJWarp physics through the shared MuJoCo renderer. +uv run eval --algo ppo --task g1_walk_flat --sim mjwarp --load-run -1 --render-mode record + +# Browser playback with MuJoCo physics; this requires a supporting checkpoint/run. +uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 --render-mode viser +``` + +`scripts/play_viser.py` is the source-checkout wrapper around the packaged +viewer. The packaged implementation is `src/unilab/scripts/play_viser.py`, and +its session setup shares `src/unilab/visualization/interactive_playback.py`. +These are implementation references, not replacements for the canonical +`uv run eval` commands above. + +## Two meanings of “snapshot” + +A **physics-state snapshot** is the backend's detached +`[time, qpos, qvel, ...]` representation used by interactive/Viser rendering. +It is a render/diagnostic host boundary. Availability is reported by +`get_play_capabilities().supports_physics_state_playback`; the viewer also +checks the state layout and playback model before applying it. + +A **training config snapshot** is `run_config.json` beside a run's checkpoints. +`ExperimentTracker` writes its `contract_snapshot` mapping at training start. +It is used for policy-I/O validation, not for restoring or rendering physics +state. See {doc}`7-config_guard`. + +Neither env nor algorithm code should call backend-private snapshot or renderer +methods. New requirements belong in the public backend capability contract; +unsupported combinations fail instead of silently changing renderer or physics +backend. ## See also - {doc}`6-capability_gaps` +- {doc}`7-config_guard` - {doc}`/adr/ADR-0002-backend-capability-boundary-for-play-and-snapshot` diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/6-capability_gaps.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/6-capability_gaps.md index 68f4de8dd..e765a47f9 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/6-capability_gaps.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/6-capability_gaps.md @@ -1,61 +1,86 @@ # Capability Gaps -A living table of backend capabilities that are surfaced through -`SimBackend` and the current backend implementations. Update this page when a -capability is added to or removed from the backend contract. +This page records selected, test-backed gaps in the current playback and +terrain/DR contracts. Task support still requires an owner YAML, registration, +and runtime evidence. + +## Playback and height scanning ```{list-table} :header-rows: 1 -:widths: 30 15 15 40 +:widths: 30 14 14 18 24 * - Capability - MuJoCo + - MJWarp - Motrix - - Notes + - Genesis * - `supports_physics_state_playback` - Yes - - No - - Reported by `get_play_capabilities()`. + - Yes + - Yes + - Yes * - `supports_native_interactive_renderer` - No + - No + - Conditional - Yes - - Reported by `get_play_capabilities()`. * - `supports_native_video_capture` - No + - No + - Conditional - Yes - - Reported by `get_play_capabilities()`. * - `bind_height_scanner(...)` - Yes + - No - Yes - - Backend-owned height-field scanner for rough-terrain observations. -* - `apply_interval_randomization(...)` - - Yes - - Yes - - Supported fields still depend on each backend's `get_dr_capabilities()`. -* - Position-actuator gain DR - - Yes - - Conditional - - Motrix reports support from runtime capability detection. -* - Geom-friction DR - - Yes - - Conditional - - Motrix reports support from runtime capability detection. + - No ``` -Use `unisim.backend.base` as the contract source and backend tests -under `tests/base/` as evidence for support claims. +Motrix disables its two native-renderer flags in whole-model-variant mode. +Although the Genesis adapter declares physics-state playback, the top-level CLI +currently rejects `eval --render-mode viser` for Genesis and directs users to +its native renderer. These distinctions are implemented in the UniSim adapters, +`src/unilab/cli.py`, and tests including `tests/base/test_mjwarp_playback.py`, +`tests/base/test_mjwarp_capabilities.py`, `tests/base/test_genesis_backend.py`, +and `tests/base/test_motrix_backend_options.py`. + +## DR is a runtime capability set + +`apply_interval_randomization(...)` existing on the base interface does not mean +that every DR field is implemented. Inspect `get_dr_capabilities()` for the +concrete backend and bind every requested term on the cold path. Missing +capabilities fail closed; they are not warning-only no-ops. + +Current owner examples make the remaining gaps explicit: + +- SAC/FlashSAC G1 motion owners disable `foot_friction` on Genesis because the + required per-environment geom-friction operation is unavailable. +- The Motrix G1 motion owner disables `push_robot`; the MJWarp owner narrows + angular push components to zero because that capability is absent. +- Position-actuator gain and geom-friction support on Motrix depends on runtime + capability detection, rather than being universally available in every mode. + +Disabling or narrowing an event can preserve a valid training configuration, +but it changes the training distribution. It is not physics or reward parity. +Record that difference with the owner and re-run the nominal and randomized +parity checks. -## How to update this page +## Contract and config-audit limits -When you add or remove a capability: +The config guard covers selected policy-I/O fields, not every backend feature. +Likewise, `scripts/audit_sim2sim_contracts.py` compares only its configured +backend pairs and reports `N/A` when none applies. Neither result proves that a +task's sensors, terrain, DR, contacts, renderer, or convergence are supported. -1. Update the table above. -2. If the change is a new contract, add or update the relevant ADR under - {doc}`/adr/ADR-0000-index`. -3. Add or update backend tests under `tests/base/`. -4. Mention user-visible changes in the changelog (see {doc}`/changelog`). +Use `unisim.backend.base` as the interface source, concrete UniSim adapters and +`tests/base/` as implementation evidence, and the generated support matrix for +support claims. When a capability changes, update its adapter/tests and the +relevant support evidence rather than treating this page as the source of truth. ## See also - {doc}`1-backend_swap` +- {doc}`5-playback_and_snapshot_differences` +- {doc}`7-config_guard` - {doc}`../../4-developer_guide/2-contracts/2-backend_contract` diff --git a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/7-config_guard.md b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/7-config_guard.md index 9ca0ddc0b..9deec3a78 100644 --- a/docs/sphinx/source/en/3-deployment/2-sim_to_sim/7-config_guard.md +++ b/docs/sphinx/source/en/3-deployment/2-sim_to_sim/7-config_guard.md @@ -1,53 +1,108 @@ # Cross-Backend Config Guard -When replaying across backends (train on one backend, `eval` on another), UniLab automatically checks whether the target backend config is compatible with the policy contract captured at training time, so a mismatched config can't silently load a broken policy. This happens with no manual steps. +When replaying a checkpoint with another owner, UniLab compares the target +config with the policy contract captured at training time. The check runs +before environment construction; checkpoint loading has a second dimension +check. Neither check proves physics or reward parity. -## An example that replays successfully +## A repository-tested example -For `go2_joystick_flat`, the MuJoCo and Motrix owners agree on every guarded field, so a cross-backend replay passes directly: +The `g1_walk_flat` MuJoCo and Genesis owners agree on the guarded fields. This +pair is covered by `tests/training/test_sim2sim_resolver.py` and by the read-only +owner audit: ```bash -# 1) Train in MuJoCo, producing a checkpoint -uv run train --algo ppo --task go2_joystick_flat --sim mujoco +# Train with MuJoCo, then replay the resulting run with Genesis. +uv run train --algo ppo --task g1_walk_flat --sim mujoco +uv run eval --algo ppo --task g1_walk_flat --sim genesis --load-run -1 -# 2) Replay the same checkpoint across backends in Motrix — the guard passes, playback runs -uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 +# Audit composed PPO owners without creating an environment. +uv run scripts/audit_sim2sim_contracts.py --trees ppo ``` -## How the guard chain works - -1. **At train time**: `ExperimentTracker` snapshots the contract fields that define policy I/O into `contract_snapshot` in `run_config.json` (the checkpoint format is untouched, so historical checkpoints stay compatible). -2. **At replay time**: `eval` loads the **target backend** owner config selected by `--sim` (e.g. `src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml`) and injects `training.play_only=true`. If the task has no owner config for the requested backend, `eval` falls back to a sibling backend owner of the same task and re-applies the requested backend through the allowlisted `training.sim_backend` override (`train` still requires the owner config to exist); the guard chain below is unaffected. -3. **Before env creation**: the play entrypoints (rsl_rl / appo / sac / flashsac) call `resolve_sim2sim_config`, comparing the target config against the source run's contract snapshot field by field. -4. **At weight load**: `policy_load_dim_guard` wraps checkpoint loading, re-raising cryptic tensor shape-mismatch errors as a clear sim2sim diagnostic. - -## What the guard covers - -Fields are classified by dotted path into three tiers (see `src/unilab/utils/sim2sim.py`): - -| Tier | Behavior | Fields | +The audit currently prints `TRANSFERABLE` for the MuJoCo/Genesis pair. This is +a statement about its compared config fields only. Use an explicit run ID +instead of `-1` when the latest run is not the intended source run. + +## Guard chain + +1. **Training:** `ExperimentTracker.start()` writes `run_config.json` beside the + run's checkpoints, including a `contract_snapshot` extracted by + `extract_contract_snapshot`. The checkpoint tensors are not rewritten. For + PPO, the default location is + `logs/rsl_rl_ppo///run_config.json`. +2. **Owner selection:** `eval` composes the target selected by `--algo`, + `--task`, and `--sim`, then injects `training.play_only=true`. On the normal + training-script eval route, a missing target owner can fall back to a + sibling owner with the requested backend reapplied internally; training has + no such fallback. The preflight still runs, and this fallback is not a + task-support claim or a guarantee for every dedicated viewer route. +3. **Before environment creation:** PPO/APPO/SAC/FlashSAC playback calls + `resolve_sim2sim_config` with the source run directory and target config. +4. **Weight loading:** `policy_load_dim_guard` translates checkpoint tensor + size-mismatch errors into a sim2sim diagnostic. Unrelated load errors pass + through unchanged. + +## Guarded fields + +The authoritative lists are in `src/unilab/utils/sim2sim.py`. + +| Tier | Behavior | Current fields | |---|---|---| -| **DENYLIST** | Mismatch → `CrossBackendIncompatibleError`, aborts | `algo.obs_groups`, Manager-Based `env.observations` / `env.actions` / policy and critic group mapping, `algo.actor.hidden_dims` / `algo.critic.hidden_dims`, `algo.actor.obs_normalization` / `algo.critic.obs_normalization` / `algo.obs_normalization`, `env.commands.motion.params.sampling_mode`, plus the historical snapshot key `env.control_config.action_scale` (retired from current owner configs) | -| **WARNING_LIST** | Prints a warning, continues | `reward.*`, `env.control_config.simulate_action_latency` | -| **ALLOWLIST** | Free to override, not checked | `training.sim_backend`, `env.scene`, `training.play_steps`, `env.noise_config` | - -## When DENYLIST fields differ - -If the target backend's DENYLIST fields differ from training (e.g. a task whose two owners use different `action_scale` values), the guard aborts before env creation and lists the diverging fields. Two ways to resolve: - -- **Align the contract** (recommended): make the target owner's DENYLIST fields match the training backend, then replay. -- **Force through** (at your own risk): `uv run eval ... training.sim2sim_strict=false` downgrades DENYLIST mismatches to warnings. It does **not** bypass the snapshot-integrity checks below. - -> Minimum supported snapshot format: the guard fails closed (raises `CrossBackendIncompatibleError`) when the source run's `run_config.json` is missing, is not valid JSON, has no `contract_snapshot` mapping, or contains keys outside the current contract schema — including the retired legacy keys `env.sampling_mode`, `algo.policy.actor_hidden_dims`, `algo.policy.critic_hidden_dims`, and `algo.empirical_normalization`, which are no longer aliased. Starting from the first release that ships this change, only canonical `contract_snapshot` mappings written by training runs on the 1.3.5 baseline schema are supported, and the breaking change is not backported to 1.3.5 patch releases. There is no offline migration tool: to reuse an older run, retrain the policy with the current version (checkpoint weights are unchanged) and replay from the new run. - -Manager-Based snapshots store the complete typed observation and action declarations from -Hydra. A snapshot from before those fields existed cannot prove that its policy I/O is -equivalent to a Manager-Based target, so asymmetric presence fails closed. Set -`training.sim2sim_strict=false` only as an explicit user override; the load-time dimension -guard still remains active. +| **DENYLIST** | A value mismatch raises `CrossBackendIncompatibleError` in strict mode | `algo.obs_groups`; `env.observations`; `env.actions`; `env.policy_observation_group`; `env.critic_observation_group`; `env.control_config.action_scale`; `env.ctrl_dt`; `env.commands.vel_limit`; `env.commands.motion.params.sampling_mode`; `algo.actor.hidden_dims`; `algo.critic.hidden_dims`; `algo.actor.obs_normalization`; `algo.critic.obs_normalization`; `algo.obs_normalization` | +| **WARNING_LIST** | Prints a warning and continues | `reward.scales`, `reward.base_height_target`, `reward.max_tilt_deg`, `reward.min_base_height`, `env.control_config.simulate_action_latency` | +| **ALLOWLIST** | Excluded from the snapshot | `training.sim_backend`, `env.scene`, `training.play_steps`, `env.noise_config` | + +`env.control_config.action_scale` is retained for historical snapshots; current +Manager-Based owners normally express action scaling inside `env.actions`. +Asymmetric presence of an `env.*` DENYLIST field also fails closed because the +guard cannot prove that an omitted side's runtime default is equivalent. + +Two narrow normalizations avoid false denials: `log_goal` and `show_rays` are +removed from `env.actions` comparisons because they only affect playback debug +visualization, and the ray-caster identity `uni_ray` is normalized to `uniray`. +Other observation/action changes remain guarded. + +The whole current Manager-Based `reward` mapping is **not** snapshotted. In +particular, `reward..weight` is not covered by `reward.scales`. Run +{doc}`4-reward_parity` separately. + +## Mismatches and snapshot integrity + +To resolve a DENYLIST mismatch, align the target owner's policy-I/O contract +with the training contract. An explicit +`uv run eval ... training.sim2sim_strict=false` downgrades contract mismatches +to warnings, including structural-presence mismatches. It does not bypass +snapshot-integrity validation or the checkpoint dimension guard. + +Replay fails closed, regardless of `sim2sim_strict`, when the source +`run_config.json` is missing, invalid JSON, not a JSON object, lacks a mapping +`contract_snapshot`, or contains keys outside the current schema. Retired keys +such as `env.sampling_mode`, `algo.policy.actor_hidden_dims`, +`algo.policy.critic_hidden_dims`, and `algo.empirical_normalization` are not +aliased. There is no offline migration tool: create a new training run with a +supported snapshot, or explicitly use a source-less external-checkpoint path. +Historical weight files are not modified, but weights alone do not satisfy the +preflight. + +The direct PPO interactive viewers have an explicit +`interactive.sim2sim=false` escape for external checkpoints that have no +UniLab run snapshot. Use it only when accepting that the policy-I/O provenance +is unverified; it does not make a malformed normal eval snapshot valid, and it +is not a shared APPO/SAC/FlashSAC bypass. + +## Audit scope + +`uv run scripts/audit_sim2sim_contracts.py --trees ppo appo sac flashsac` +composes owners and compares DENYLIST/WARNING_LIST values without constructing +an environment. It currently audits MuJoCo/MJWarp/Genesis pairs and +MuJoCo/Isaac pairs where present. Motrix, Newton, SuperDex, Drake, and +`mtxwarp` are not automatically covered by those pairs. `N/A` means no audited pair, not +support or incompatibility; inspect compose errors separately. ## See also - {doc}`1-backend_swap` - {doc}`4-reward_parity` -- {doc}`/zh_CN/4-developer_guide/9-sim2sim_contract_status` +- {doc}`5-playback_and_snapshot_differences` +- {doc}`../../4-developer_guide/9-sim2sim_contract_status` diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/0-index.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/0-index.md index 0d1db0eae..401a9d22b 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/0-index.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/0-index.md @@ -9,7 +9,7 @@ contract-driven layout. :::{grid-item-card} From Isaac Lab :link: 1-from_isaac_lab :link-type: doc -Keep Manager-Based terms while adapting Hydra config, NumPy execution, and scene access. +Keep Manager-Based terms while adapting Hydra config, Torch execution, and scene access. ::: :::{grid-item-card} From Legged Gym @@ -21,7 +21,7 @@ Move class-based environments into the Manager-Based `TorchEnv` contract. :::{grid-item-card} From RSL-RL :link: 3-from_rsl_rl :link-type: doc -Separate trainer assumptions from UniLab runner assembly. +Use upstream `OnPolicyRunner` through UniLab's adapter; treat APPO separately. ::: :::{grid-item-card} From skrl diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/1-from_isaac_lab.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/1-from_isaac_lab.md index d7bc9b277..62c6c3a3d 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/1-from_isaac_lab.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/1-from_isaac_lab.md @@ -1,11 +1,11 @@ # Migrating from Isaac Lab -Port an Isaac Lab Manager-Based task to UniLab by keeping its manager and term -structure, then adapting configuration, numeric execution, and scene access at -their owner boundaries. Do not rewrite it as a monolithic environment subclass. +Port an Isaac Lab Manager-Based task by preserving its manager and term +structure, then adapting configuration, tensor access, and scene capabilities +at their owner boundaries. Do not rewrite it as a monolithic environment +subclass or convert its terms to NumPy. -This is source-compatible migration, not a promise that an arbitrary Isaac Lab -task runs unchanged. The target path is: +This is source-level migration. The current target path is: ```text Hydra owner YAML @@ -33,13 +33,13 @@ Hydra owner YAML - Change imports to `unilab.managers`; keep term boundaries and partial `reset(env_ids)` semantics. * - `ManagerBasedRLEnv` / `ManagerBasedRLEnvCfg` - - Compatible spelling aliases + - Available aliases - The canonical UniLab names are `ManagerBasedRlEnv` and - `ManagerBasedRlEnvCfg`; the aliases point to the same implementation. + `ManagerBasedRlEnvCfg`; the aliases refer to the same implementation. * - Tensor values and operations - Adapted - - Replace `torch.Tensor` with `np.ndarray` and use vectorized NumPy. There is - no manager-facing device API. + - Keep `torch.Tensor` and Torch operations. Adapt reads/writes to UniLab's + packed entity views, manager contracts, dtypes, and `env.device`. * - Nested `@configclass` task configuration - Adapted - Move the complete task declaration to one Hydra owner YAML. `_target_` @@ -47,17 +47,24 @@ Hydra owner YAML * - `InteractiveSceneCfg`, USD, and PhysX views - Adapted or unsupported - Declare a task-owned `SceneCfg` and `EntityCfg`; access state and control - only through `SceneEntityCfg` and the public entity facade. Unsupported - capabilities raise during cold-path binding. -* - Omniverse, Isaac renderer, and Torch/PhysX mutation - - Unsupported - - UniLab does not install or silently emulate these runtimes. + only through `SceneEntityCfg` and the public entity/backend contracts. +* - Omniverse, Isaac renderer, and direct PhysX mutation + - Not a portable Manager-term API + - Do not emulate these calls in terms. Use them only behind a declared backend + capability; unsupported requests fail during cold-path binding. ``` -The normative boundary is -{doc}`ADR-0006 `. Only -surfaces backed by registration, configuration, and tests should be described -as compatible. +The current tensor-runtime boundary is +{doc}`ADR-0012 `. +ADR-0006's NumPy design is superseded historical context, not the migration +target. + +UniLab also has explicit `isaacsim` and `isaacgym` backend selections using +external workers (Python 3.11 and Python 3.8 respectively). That integration is +separate from porting an Isaac Lab task: it still requires the corresponding +owner YAML and registered task support, and does not make USD/PhysX-specific +terms portable. The CLI points to `scripts/tools/setup_isaacsim_env.sh` and +`scripts/tools/setup_isaacgym_env.sh` for those external runtimes. ## Migration procedure @@ -68,35 +75,37 @@ order, parameters, observation dimensions, action dimensions, reset behavior, and episode timing. Classify each dependency before writing code: - reuse an existing `unilab.managers` config or `unilab.envs.mdp` term; -- adapt a task-specific term from Torch to NumPy; +- adapt a task-specific Torch term to the public entity/manager views; - stop if the term requires a capability absent from the public entity or `SimBackend` contract. -Do not probe backend objects with `getattr`/`hasattr`, return zeros, or route the -task back to a legacy environment. +Do not probe backend objects with `getattr`/`hasattr`, return zeros, or route +the task back to a legacy environment. ### 2. Port scene and assets on the cold path -Replace Isaac Lab's USD/`InteractiveSceneCfg` declaration with a task-owned -`SceneCfg`. Declare every entity and selector needed by terms. The -`SceneEntityCfg` selector resolves names and regular expressions once during -materialization; reset and step reuse cached IDs and NumPy views. +Replace the source task's USD/`InteractiveSceneCfg` declaration with a +task-owned `SceneCfg`. Declare every entity and selector needed by terms. +`SceneEntityCfg` resolves names and regular expressions once during +materialization; reset and step reuse cached IDs and Torch views. The Cartpole fixture uses a minimal task-owned MJCF asset. More complex assets must follow {doc}`scene composition <../../4-developer_guide/1-architecture/4-scene_composition>` -and the selected backend's formal capabilities. +and the selected backend's formal capabilities. Choosing the external IsaacSim +backend is not a substitute for this declaration. ### 3. Port term code, not the manager structure -Keep each function/class term and its parameters. Replace Torch types and -operators mechanically with NumPy, preserve batch shapes, and return one value -per environment where the source term does. Stateful terms resolve selectors -and allocate buffers in their constructor, then update only NumPy buffers on -the hot path. +Keep each function/class term and its parameters. Preserve Torch batch shapes +and return one value per environment where the source term does. Check the +manager's required dtype and device; for example, rewards are float32 tensors +of shape `(num_envs,)` on `env.device`. -Python owns term implementations and reusable config dataclasses. It must not -hold a second task-specific list of enabled terms or default weights. +Stateful terms resolve selectors and allocate Torch buffers in their +constructor, then reuse those buffers on the hot path. Python owns term +implementations and reusable config dataclasses. It must not hold a second +task-specific list of enabled terms or default weights. ### 4. Make Hydra the only task configuration owner @@ -168,9 +177,8 @@ env: delay_max_lag: 2 ``` -The Manager samples delay independently per environment and physical substep, -and selected resets clear only the selected histories. The first target after -initialization or reset backfills the history. These fields cover command +Selected resets clear only the selected delay histories, and the first target +after initialization or reset backfills the history. These fields cover command delay, not a DC motor's torque-speed saturation curve. ### 5. Register one generic runtime path @@ -187,11 +195,11 @@ uv run train --algo ppo --task --sim mujoco Do not add a task-specific training-script branch, environment factory, runner, or IPC path. -One maintainer-approved factory wrapper is the only registered exception to +One maintainer-approved factory wrapper is the current registered exception to the generic-factory rule: `make_g1_walk_env` (`src/unilab/tasks/locomotion/g1/manager_terms.py`) constructs the -`G1WalkManagerBasedEnv` subclass that owns the G1 walk manager-based runtime, -Every other Compatible task registers `make_manager_based_rl_env` directly. +`G1WalkManagerBasedEnv` subclass for the G1 walk runtime. Other Compatible +production tasks register `make_manager_based_rl_env` directly. ### 6. Validate near each adaptation @@ -202,26 +210,23 @@ benchmark only after semantic migration is complete. ## Final task status -The task migration status is maintained in the registry and migration matrix. -The fail-closed source of truth is -`src/unilab/tasks/migration_matrix.py`: `migration_record()` raises `KeyError` -for a production task name with no entry, so adding a production registration -requires an explicit migration decision. - -- 36 tasks are **Compatible** (`target=complete`): the Hydra owner YAML - materializes the canonical tensor-only Manager-Based runtime. +The fail-closed migration source is `src/unilab/tasks/migration_matrix.py`: +`migration_record()` raises `KeyError` for a production task with no entry. +The current matrix contains three production tasks, all marked **Compatible** +with `target=complete`: `Go2JoystickFlat`, `G1WalkFlat`, and +`G1MotionTracking`. This count describes the matrix, not the number of Isaac +Lab tasks that can be ported without adaptation. ## Repository evidence `tests/fixtures/isaac_lab_cartpole/` ports the Manager-Based Cartpole task from Isaac Lab commit `b0542fe2d45bf91c4e1d9ef6952b9c709c80b4e8`. It preserves all -12 source term names and their order while adapting Torch to NumPy, nested -config objects to Hydra YAML, and the scene/action/reset boundaries to a -fixture-local MJCF implementation. It is test-only evidence, not a production -task or a blanket Isaac Lab support claim. +12 source term names and their order while adapting nested config objects to +Hydra YAML and scene/action/reset access to the fixture-local MJCF/entity +boundary. Its current terms return Torch tensors. This is test-only evidence. ## See also - {doc}`Manager-Based API <../../4-developer_guide/1-architecture/6-manager_based_api>` - {doc}`Environment contract <../../4-developer_guide/2-contracts/1-env_contract>` -- {doc}`ADR-0006 ` +- {doc}`ADR-0012 ` diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/2-from_legged_gym.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/2-from_legged_gym.md index 9ff096df7..3df442ec3 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/2-from_legged_gym.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/2-from_legged_gym.md @@ -1,9 +1,9 @@ # Migrating from Legged Gym -Legged Gym was the GPU-resident PPO template that taught the field how to -train quadrupeds. Its core ideas — joystick command spaces, terrain -curricula, RSL-RL PPO — live on inside UniLab. Migration is therefore -mostly mechanical. +Legged Gym's joystick commands, terrain curricula, and RSL-RL PPO concepts map +well to UniLab, but the environment implementation is not a drop-in subclass. +Move the task into the Manager-Based owner/term structure and validate the +result against the pinned source revision. ## Direct equivalences @@ -11,41 +11,59 @@ mostly mechanical. |---|---| | `LeggedRobot` env class | `unilab.envs.manager_based_rl_env.ManagerBasedRlEnv` | | `compute_observations()` | owner `env.observations` terms + `unilab.managers.observation_manager` | -| `_reward_*` methods | owner `reward` terms + `unilab.managers.reward_manager` | +| `_reward_*` methods | top-level owner `reward` terms + `unilab.managers.reward_manager` | | `command_ranges` | task owner YAML's `env.commands` block | -| Terrain curriculum | {doc}`../../2-user_guide/6-terrain/1-procedural` | -| RSL-RL PPO | upstream `rsl_rl.algorithms:PPO` via `unilab.rl` | +| Terrain curriculum | `env.scene.terrain` plus `env.curriculum` terms; see {doc}`../../2-user_guide/6-terrain/1-procedural` | +| RSL-RL PPO | upstream `rsl_rl.algorithms:PPO` through `unilab.rl.adapters.rsl_rl` | -## What's new +## Architectural differences -- **Two backends.** Legged Gym is Isaac Gym only; UniLab gives you MuJoCo - + Motrix. Pick one (or both) before porting; see +- **Backend selection is per owner.** UniLab supports multiple in-process and + external-worker backends, not only MuJoCo and Motrix. Select one with + `--sim` and verify the corresponding owner and capabilities; see {doc}`../2-sim_to_sim/1-backend_swap`. -- **Async collection.** Legged Gym collects on-GPU synchronously; UniLab's - APPO (`unilab.rl.algos.appo`) decouples collectors from - learner. If wall-clock matters, port to APPO once your reward parity is - established. -- **Hardware deployment.** Legged Gym → real-world deployment is a - hand-rolled story per lab. UniLab gives you the - {doc}`../1-sim_to_real/1-overview` pipeline as a first-class artifact. +- **The public lifecycle is Torch-based.** Port observations, actions, rewards, + resets, and termination values to the Manager's tensor contracts rather than + keeping Legged Gym's class-local buffers and implicit device assumptions. +- **APPO is a separate algorithm.** `unilab.rl.algos.appo` decouples collectors + from the learner and applies V-trace off-policy correction. It is not a + wrapper that makes an existing PPO run asynchronous with identical update + semantics. +- **Deployment uses explicit contracts.** Use the + {doc}`../1-sim_to_real/1-overview` pipeline after policy-I/O and sim-to-sim + validation rather than carrying over lab-specific deployment glue. ## Migration checklist -1. Copy your URDF / MJCF assets under `src/unilab/assets/robots//`. -2. Create a task module under `src/unilab/tasks/locomotion//`. -3. Mirror your reward terms; keep the same names so reward parity is - diff-able. -4. Translate command sampling — configure `UniformVelocityCommandCfg` under - the owner YAML's `env.commands` (see the `go2_joystick_flat` owner). -5. Translate terrain — Legged Gym's heightfield generator has a UniLab - counterpart at `unilab.terrains.heightfield_terrains`. +1. Pin the source Legged Gym revision and inventory assets, term order, + observation/action dimensions, commands, resets, timing, and DR. +2. Register robot assets through the asset hub and create a task module under + `src/unilab/tasks/locomotion//`. +3. Declare the shared contract in + `src/unilab/conf/ppo/task//base.yaml`, then add backend leaves under + the same directory. Do not inherit one backend leaf from another. +4. Port reward terms with the same names and explicit float32 Torch outputs. + Configure `UniformVelocityCommandCfg` under `env.commands`; the + `go2_joystick_flat` base owner is a current example. +5. Translate terrain to `env.scene.terrain` and curriculum terms under + `env.curriculum`. Heightfield factories live in + `unilab.terrains.heightfield_terrains`. +6. Register the generic Manager-Based factory and run the standard command: + + ```bash + uv run train --algo ppo --task --sim + ``` ## Validation gate -Before deleting your Legged Gym checkout, train a Go2-equivalent task in -UniLab on flat ground and compare the reward-term traces against the source -implementation. If the traces diverge before the policy learns, there is a -reward, command, reset, or DR mismatch; see {doc}`../2-sim_to_sim/4-reward_parity`. +Before comparing learning curves, replay a fixed reset and deterministic action +sequence in both implementations. Compare observations, total reward, reward +components, termination/truncation masks, and final observations. Early +divergence indicates a reward, command, reset, timing, or DR mismatch; see +{doc}`../2-sim_to_sim/4-reward_parity`. + +Only after that fixed-transition check should you train the Go2-equivalent task +on flat ground and compare reward curves with the source baseline. ## See also diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/3-from_rsl_rl.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/3-from_rsl_rl.md index b89e91aae..0b9a0439e 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/3-from_rsl_rl.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/3-from_rsl_rl.md @@ -1,41 +1,66 @@ # Migrating from RSL-RL -You're already using RSL-RL standalone? Good news: UniLab drives upstream -RSL-RL PPO directly (`unilab.rl` adapts the env to -`rsl_rl.runners.OnPolicyRunner`) and it's nearly drop-in. - -## What you gain by moving inside UniLab - -1. **Env contract.** RSL-RL leaves env structure to you. UniLab's - `unilab.base.torch_env.TorchEnv` standardizes obs/info/reset - signatures, makes parallelism and resets less error-prone. -2. **Task owners.** Hydra-based config compose, plus the registry-driven - backend / task / algo selection. No more bespoke train scripts per - robot. -3. **Async runner.** Wrap RSL-RL PPO inside - `unilab.rl.algos.appo` for higher throughput on machines - with many CPU cores. -4. **Deployment story.** ONNX export with the right wrapper, safety - layer documentation, and the - {doc}`../1-sim_to_real/1-overview` pipeline. - -## What you don't lose - -- Same PPO algorithm and hyperparameters — RSL-RL is wrapped, not - reimplemented. -- Checkpoint compatibility: `runs//model_*.pt` files from UniLab can - be loaded by stock RSL-RL given a matching policy architecture. +UniLab's PPO path drives the upstream `rsl_rl.runners.OnPolicyRunner` directly. +`unilab.rl.adapters.rsl_rl.RslRlVecEnvAdapter` converts the UniLab `TorchEnv` +contract to RSL-RL's current TensorDict-based `VecEnv` interface; PPO itself is +not reimplemented in `unilab.rl.algos`. + +## What changes + +1. **Environment contract.** `TorchEnv.reset()` returns `(obs_dict, info_dict)`; + `step()` returns a state whose observations, rewards, and done flags are + tensors. The adapter maps actor/critic groups and timeout information for + RSL-RL. +2. **Configuration ownership.** Task, backend, and algorithm selection comes + from Hydra owner YAML and the top-level CLI rather than a bespoke training + script per robot. +3. **Checkpoint/run layout.** UniLab PPO runs normally live under + `logs/rsl_rl_ppo///`, with `model_*.pt` and + `run_config.json` in the same run directory. Resume uses `algo.load_run` + and `algo.checkpoint`. +4. **Other algorithms are not transparent wrappers.** APPO uses asynchronous + collection and V-trace correction; SAC and FlashSAC are off-policy. Moving + from PPO to APPO changes update semantics and configuration. ## Migration steps -1. Move your env into `unilab.envs../`. -2. Convert your training config to a Hydra group under `src/unilab/conf/ppo//`. -3. Run `uv run train --algo ppo --task --sim `. -4. Compare reward curves against your standalone RSL-RL baseline. +1. Port the environment into the generic Manager-Based task structure under + `src/unilab/tasks/`, keeping observation/action dimensions and termination + semantics explicit. +2. Translate training values into `src/unilab/conf/ppo/config.yaml` and the + task owners under `src/unilab/conf/ppo/task//`. Backend leaves inherit + only that directory's `base.yaml` and `_self_`. +3. Install the backend requirements plus the current RL extra. Published + package users need `pip install "unilab[unirl]"`; the legacy `uni_rl` extra + is removed. +4. Run the canonical command: + + ```bash + uv run train --algo ppo --task --sim + ``` + +5. Compare fixed-transition observations/rewards first, then compare learning + curves against the standalone RSL-RL baseline. + +The composed `cfg.algo` subtree is passed to the upstream runner, but migration +still requires checking RSL-RL version-specific class names, observation +groups, normalization, and hyperparameter semantics. Do not assume that +similarly named YAML fields produce identical training. + +## Checkpoint compatibility boundary + +UniLab saves upstream actor/critic state through `OnPolicyRunner`, with +additional UniLab resume metadata. Matching architecture and observation/action +layouts are necessary for any external reuse; they are not a guarantee that a +stock standalone RSL-RL setup can resume a UniLab run unchanged. + +Playback also validates the source run's `contract_snapshot` before creating +the environment. An external checkpoint without `run_config.json` needs an +explicit source-less viewer exception and has unverified policy-I/O provenance. +See {doc}`../2-sim_to_sim/7-config_guard`. -## When NOT to migrate +## When not to migrate -If you have an existing pipeline that works, no real-hardware target, and -you mostly need RSL-RL for the algorithm — UniLab is overkill. Use it -when you need any of: multi-backend, async collection, ONNX deployment, -or task registration. +If an existing standalone pipeline only needs the RSL-RL algorithm and none of +UniLab's task ownership, backend capability checks, deployment tooling, or +other algorithms, keeping that pipeline is reasonable. diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/4-from_skrl.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/4-from_skrl.md index 8e6020139..1a6dfb878 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/4-from_skrl.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/4-from_skrl.md @@ -1,32 +1,51 @@ # Migrating from skrl -skrl's strength is algorithm breadth. UniLab focuses on a curated set -(PPO, SAC with several optimized variants) but adds a real-hardware -deployment path. +skrl offers a broad algorithm catalog. UniLab currently exposes PPO, APPO, +SAC, and FlashSAC through its built-in CLI, with task ownership, backend +capability checks, and deployment tooling around them. Algorithm names alone do +not imply matching update semantics or checkpoint compatibility. ## Mapping skrl concepts to UniLab | skrl | UniLab | |---|---| -| `Agent` (PPO, SAC, …) | `unilab.rl.algos.*` | -| `RolloutMemory` | `unilab.rl.runtime.ipc.tensor_rollout_ring_buffer` | -| `ReplayMemory` | `unilab.rl.runtime.ipc.replay_buffer` | -| `Trainer` | `unilab.training.run` | -| `Wrapper` for env | `TorchEnv` subclassing | +| `Agent` (PPO, SAC, …) | Upstream RSL-RL PPO or `unilab.rl.algos.{appo,sac,flash_sac}` | +| `RolloutMemory` | APPO's `unilab.rl.runtime.ipc.tensor_rollout_ring_buffer` | +| `ReplayMemory` | Off-policy `unilab.rl.runtime.ipc.replay_buffer` | +| `Trainer` | Algorithm-specific runner assembled by `src/unilab/scripts/train_*.py`; PPO uses upstream `OnPolicyRunner` | +| Environment `Wrapper` | A `TorchEnv` task plus the algorithm adapter, such as `RslRlVecEnvAdapter` for PPO | +| Hyperparameter config | `src/unilab/conf//task//.yaml` and its same-directory `base.yaml` | ## What to expect -- **No algorithm parity** for niche algos (CQL, IQL, etc.) — UniLab - intentionally focuses on a few highly optimized actor-critic variants. -- **Different runner lifecycle.** skrl's monolithic trainer becomes a - collector + learner pair connected by shared memory. See - {doc}`../../4-developer_guide/2-contracts/5-runner_lifecycle`. -- **Different env interface.** skrl tolerates many env styles. UniLab - insists on `TorchEnv` + tensor dict obs. +- **No blanket algorithm parity.** Algorithms such as CQL and IQL are not + built-in UniLab algorithms. APPO also differs from ordinary synchronous PPO + through asynchronous collection and V-trace correction. +- **The runner lifecycle is algorithm-specific.** PPO remains the upstream + on-policy runner. APPO and off-policy training use collector/learner + execution with IPC and shared-memory data structures; do not apply that model + to every algorithm. +- **The env interface is tensor-native.** Port task code to `TorchEnv` and the + Manager-Based term contracts. Observations are a dict of tensors, not an + arbitrary skrl-supported environment format. +- **Config and checkpoints are not drop-in.** Map network shape, observation + groups, action scaling, normalization, and algorithm parameters explicitly, + then validate loading and inference. ## Migration checklist -1. Decide which UniLab algorithm best matches your skrl agent. -2. Port the env into `TorchEnv` form. -3. Convert hyperparameter YAML into Hydra groups under `src/unilab/conf///`. -4. Validate reward parity. +1. Choose the algorithm whose objective and data lifecycle match the source + agent, rather than selecting only by name. +2. Port the env into the generic Manager-Based `TorchEnv` structure. +3. Put shared task declarations in + `src/unilab/conf//task//base.yaml` and backend identity/tuning + in `.yaml`. Do not use `src/unilab/conf///`, which is + not the current owner layout. +4. Run the standard command and validate fixed-transition reward parity before + comparing training curves: + + ```bash + uv run train --algo --task --sim + ``` + +See {doc}`3-from_rsl_rl` for PPO and {doc}`6-reward_porting` for term migration. diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/5-task_config_translation.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/5-task_config_translation.md index d26dc5664..c83cd7999 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/5-task_config_translation.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/5-task_config_translation.md @@ -1,7 +1,8 @@ # Task Config Translation Cheatsheet -A side-by-side map of common config fields across Isaac Lab / Legged Gym -/ skrl and UniLab task owner YAMLs. +A side-by-side map of common Isaac Lab / Legged Gym concepts and their current +UniLab owner declarations. The UniLab column shows canonical paths, not legacy +compatibility aliases. ## Env-level @@ -14,28 +15,28 @@ A side-by-side map of common config fields across Isaac Lab / Legged Gym - Legged Gym - UniLab * - Action scale - - `action_scale` on env cfg + - `action_scale` on env/action cfg - `action_scale` in env class - - `env.action.scale` in owner YAML -* - Decimation - - `decimation` on env cfg - - `cfg.control.decimation` - - `env.decimation` + - `env.actions..scale` +* - Control decimation + - `decimation` and simulation dt + - `cfg.control.decimation` and sim dt + - `env.ctrl_dt / env.sim_dt` (the runtime requires an integer ratio) * - Episode length (s) - `episode_length_s` - `cfg.env.episode_length_s` - - `env.episode_length_s` -* - Default joint pos + - `env.max_episode_seconds` +* - Default joint state - `init_state.joint_pos` - `default_joint_angles` - - `env.default_joint_pos` (or asset-side) + - Task/robot keyframe selected by `env.scene.default_keyframe_name`, or asset-side defaults * - Observation noise - - `noise.obs.*` + - Observation term noise cfg - `cfg.noise.add_noise` - - `env.observations...noise` + - `env.observations..terms..noise` ``` -## Reward +## Reward and termination ```{list-table} :header-rows: 1 @@ -48,17 +49,22 @@ A side-by-side map of common config fields across Isaac Lab / Legged Gym * - Reward term registration - `RewardManager` cfg - `_reward_*` methods - - reward registry + env's `compute_reward` + - Top-level `reward.` mapping injected into the Manager reward config * - Reward weight - `RewTerm(weight=…)` - `reward_scales.` - `reward..weight` * - Termination penalty - - `Termination` cfg + - Reward and termination cfgs - `_reward_termination` - - reward registry term + termination signal + - `reward.` using `unilab.envs.mdp.is_terminated`, with termination signals under `env.terminations` ``` +Manager-Based rewards return float32 Torch tensors of shape `(num_envs,)`. +The top-level `reward` mapping is distinct from the typed `env.rewards` config +created during materialization; owner YAML authors should use `reward` as in the +current task owners. + ## DR ```{list-table} @@ -70,19 +76,23 @@ A side-by-side map of common config fields across Isaac Lab / Legged Gym - Legged Gym - UniLab * - Randomize friction - - `EventTerm(...friction)` + - Friction `EventTerm` - `cfg.domain_rand.friction_range` - - `env.events.` using `geom_friction` + - `env.events.` with `func: unilab.envs.mdp.geom_friction` * - Push robot - - `EventTerm(...push)` + - Push `EventTerm` - `cfg.domain_rand.push_robots` - - `env.events.push_robot` + - `env.events.` with `func: unilab.envs.mdp.push_by_setting_velocity` * - PD gain DR - - `EventTerm(...stiffness)` + - Gain randomization `EventTerm` - `cfg.domain_rand.randomize_motor_strength` - - `env.events.pd_gains` + - `env.events.` with `func: unilab.envs.mdp.pd_gains` ``` +Every requested event must be supported by the selected backend's +`get_dr_capabilities()`. Disable or narrow it explicitly in that backend leaf +when necessary; do not assume a shared event declaration works unchanged. + ## Curriculum ```{list-table} @@ -94,16 +104,17 @@ A side-by-side map of common config fields across Isaac Lab / Legged Gym - Legged Gym - UniLab * - Terrain curriculum - - `TerrainCfg.curriculum` + - Terrain curriculum cfg - `cfg.terrain.curriculum` - - `terrain.curriculum.*` + - `env.scene.terrain.generator.curriculum` plus an `env.curriculum` term such as `unilab.envs.mdp.terrain_levels_by_progress` * - Command range curriculum - - bespoke + - Command curriculum cfg or bespoke term - `update_command_curriculum` - - `unilab.base.curriculum` + - `env.curriculum` with `unilab.envs.mdp.command_curriculum` ``` ## See also - {doc}`6-reward_porting` +- {doc}`../2-sim_to_sim/2-owner_yaml_swap` - {doc}`../../4-developer_guide/2-contracts/3-task_owner` diff --git a/docs/sphinx/source/en/3-deployment/3-framework_migration/7-from_unilab_rl.md b/docs/sphinx/source/en/3-deployment/3-framework_migration/7-from_unilab_rl.md index fcbc30be7..770e7dea7 100644 --- a/docs/sphinx/source/en/3-deployment/3-framework_migration/7-from_unilab_rl.md +++ b/docs/sphinx/source/en/3-deployment/3-framework_migration/7-from_unilab_rl.md @@ -7,20 +7,24 @@ The former `unilab-rl` distribution (import namespace `uni_rl`, repository [unilabsim/unilab_rl](https://github.com/unilabsim/unilab_rl)) is merged into this repository under `unilab.rl` (issue #2372, decision in {doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`). There is a single -`unilab` distribution: the APPO / SAC / FlashSAC runners, the async IPC -runtime, and the RL logging stack ship in the base install. +`unilab` distribution containing the APPO / SAC / FlashSAC runners, async IPC +runtime, and RL logging stack. Their third-party training dependencies are +still packaged separately in the current `unirl` extra. ## Install changes -- Drop `--extra uni_rl` from `uv sync` commands and `unilab[uni_rl]` from - pip installs; the RL stack needs no extra. -- The empty transitional `uni_rl` extra has been removed, so the old commands - now fail with an unknown-extra error. Remove the extra from scripts and CI. +- Remove `--extra uni_rl` from `uv sync` commands and `unilab[uni_rl]` from + pip installs. The legacy extra has been removed and fails with an + unknown-extra error. +- For a published-package installation, install `unilab[unirl]` to pull in + `rsl-rl-lib`, `tensordict`, `tensorboard`, and `wandb`. In a source checkout, + the default `rl` dependency group already installs `unilab[unirl]`, so the + usual backend-specific `uv sync --extra ` is sufficient. - Remove any standalone `unilab-rl` install from your environment (`pip uninstall unilab-rl`) so no stale copy of the old implementation lingers next to `unilab.rl`. - CLI algorithm names, log paths, checkpoint fields, and metric schemas are - unchanged. + unchanged by the namespace merge. ## Import path mapping diff --git a/docs/sphinx/source/en/4-developer_guide/0-index.md b/docs/sphinx/source/en/4-developer_guide/0-index.md index 8e8273c27..ff3d9e0c3 100644 --- a/docs/sphinx/source/en/4-developer_guide/0-index.md +++ b/docs/sphinx/source/en/4-developer_guide/0-index.md @@ -48,6 +48,12 @@ Manager-Based construction, reset, interval, and backend capability boundaries. Contract ownership, schema policy, benchmark acceptance, and release transition. ::: +:::{grid-item-card} Sim2Sim contract status +:link: 9-sim2sim_contract_status +:link-type: doc +Cross-backend snapshots, play validation, and current owner audit results. +::: + :::: ## Extending @@ -100,4 +106,5 @@ Extend terrain generation while keeping asset access on cold paths. 6-agent_quick_reference 7-motion_assets 8-tensor_runtime_production +9-sim2sim_contract_status ``` diff --git a/docs/sphinx/source/en/4-developer_guide/1-architecture/1-overview.md b/docs/sphinx/source/en/4-developer_guide/1-architecture/1-overview.md index 861a1ce0b..f853e5ac9 100644 --- a/docs/sphinx/source/en/4-developer_guide/1-architecture/1-overview.md +++ b/docs/sphinx/source/en/4-developer_guide/1-architecture/1-overview.md @@ -5,17 +5,19 @@ rule is to fix behavior at the owner layer that owns the contract. ## Runtime Model -The async paths use a CPU simulation to accelerator learner pipeline: +The async paths use a simulation-to-learner pipeline; transport follows the +backend's declared data plane: ```text -CPU physics backend -> collector / IPC -> learner -MuJoCo or Motrix shared memory torch +Physics backend -> collector / IPC -> learner +HOST_BRIDGE or DEVICE_RESIDENT declared tensor transport torch ``` -PPO is a synchronous single-process path. APPO and off-policy -algorithms use the async runner, shared buffers, and weight synchronization -primitives under `unilab.rl.runtime` (merged from the former `unilab-rl` -package; see +PPO is synchronous: it defaults to one process and can run RSL-RL data parallel +with one process per GPU on a single host. Each rank owns its env and rollout; +RSL-RL averages gradients after each mini-batch. APPO and off-policy algorithms +use the async runner, shared buffers, and weight synchronization primitives +under `unilab.rl.runtime` (merged from the former `unilab-rl` package; see {doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`). ## Layer Boundaries @@ -25,8 +27,9 @@ package; see | Backend | `unisim.backend` | `SimBackend`, physics state, optional capabilities | | Env | `src/unilab/envs/`, `src/unilab/base/torch_env.py` | MDP semantics, observation, reward, reset | | Config and registry | `src/unilab/conf/`, `src/unilab/base/registry.py`, `src/unilab/structured_configs.py` | Schema, owner YAMLs, env/backend registration | -| Algorithms and IPC | `src/unilab/rl/algos/`, `src/unilab/rl/runtime/ipc/` | Learners, runners, buffers, weight sync | -| Scripts | `scripts/`, `src/unilab/cli.py` | Thin assembly and CLI routing | +| RL algorithms, adapters, and runtime | `src/unilab/rl/` | RSL-RL adaptation, learners, runners, buffers, IPC, and distributed primitives | +| Training assembly | `src/unilab/training/` | Experiment metadata, `run_config.json` snapshots, and log/checkpoint/playback helpers | +| Scripts and CLI | `src/unilab/scripts/`, `scripts/`, `src/unilab/cli.py` | Thin assembly and CLI routing | ## Design Rules diff --git a/docs/sphinx/source/en/4-developer_guide/1-architecture/2-runtime_model.md b/docs/sphinx/source/en/4-developer_guide/1-architecture/2-runtime_model.md index 547b353f0..d68cd1477 100644 --- a/docs/sphinx/source/en/4-developer_guide/1-architecture/2-runtime_model.md +++ b/docs/sphinx/source/en/4-developer_guide/1-architecture/2-runtime_model.md @@ -9,10 +9,20 @@ summary close to the code paths. ### Synchronous PPO Paths -`src/unilab/scripts/train_rsl_rl.py` composes Hydra config, -calls registry bootstrap, constructs the strict `TorchEnv` through -`registry.make(...)`, and runs the learner in the same process. The RSL-RL path -adapts that tensor boundary through `src/unilab/rl/`. +`src/unilab/scripts/train_rsl_rl.py` composes Hydra config, calls registry +bootstrap, constructs the strict `TorchEnv` through `registry.make(...)`, and +runs the learner in the same process. The default is single-process. When +`CUDA_VISIBLE_DEVICES` selects multiple GPUs, the parent starts local workers +through the PyTorch elastic launcher and each worker enters the same script. +The RSL-RL path adapts the tensor boundary through `src/unilab/rl/`. + +Every rank creates the configured `algo.num_envs`, a policy copy, and rollout +storage; data and GAE are not exchanged across ranks. RSL-RL owns startup model +broadcast, adaptive-KL scalar synchronization, and gradient averaging for each +PPO mini-batch. UniLab's launcher owns only device/rank setup, the shared log +directory, seed offsets, and process-failure propagation. Only rank 0 writes +logs and checkpoints; normalizer buffers, curriculum, and episode statistics +remain rank-local. ### Async APPO And Off-Policy Paths @@ -40,6 +50,8 @@ Environment tensor loop -> shared IPC carrier -> learner learner code, not env code. - Collector/learner protocols must reuse the existing IPC primitives instead of creating ad-hoc parallel protocols in scripts. +- Multi-GPU PPO follows RSL-RL's distributed contract. `algo.num_envs` is a + per-rank value and is never silently divided by world size in scripts. ## Evidence In Repo diff --git a/docs/sphinx/source/en/4-developer_guide/1-architecture/3-layer_boundaries.md b/docs/sphinx/source/en/4-developer_guide/1-architecture/3-layer_boundaries.md index 2ca55bfad..e3b4362e6 100644 --- a/docs/sphinx/source/en/4-developer_guide/1-architecture/3-layer_boundaries.md +++ b/docs/sphinx/source/en/4-developer_guide/1-architecture/3-layer_boundaries.md @@ -10,10 +10,22 @@ standard is {doc}`/zh_CN/4-developer_guide/0-index`. | --- | --- | --- | | L0 Backend | `unisim.backend` | Physics backend abstraction, backend-owned scene materialization, backend capabilities. | | L1 Env | `src/unilab/envs/`, `src/unilab/base/torch_env.py` | MDP semantics, observations, rewards, reset logic, backend-to-task adaptation. | -| L2 Config and Registry | `src/unilab/conf/`, `src/unilab/structured_configs.py`, `src/unilab/base/registry.py`, `src/unilab/training/reward.py` | Hydra composition, owner YAML identity, env/reward registration. | +| L2 Config and Registry | `src/unilab/conf/`, `src/unilab/structured_configs.py`, `src/unilab/base/registry.py` | Hydra composition, owner YAML identity, env/reward registration. | | L3 Algo and IPC | `src/unilab/rl/algos/`, `src/unilab/rl/runtime/ipc/` | Learners, runners, collectors, replay and rollout buffers, weight sync. | | L4 Scripts | `scripts/` | Entrypoint assembly only. | +## RL Internal Dependencies + +`src/unilab/base/contracts/` is the only `unilab.base` leaf that the RL core may +depend on. It contains type/tensor contracts and imports no registry, Manager, +backend, or algorithm. `rl.runtime` must not depend on `rl.algos`, `training`, +or env-construction layers; `rl.algos` and `rl.adapters` must not construct +concrete environments. The `unilab.rl`, `rl.runtime`, and +`rl.runtime.distributed` package initializers stay lightweight and do not +eagerly import Torch or algorithm stacks. `tests/test_library_import_boundary.py` +guards these rules with AST checks and isolated-process import probes; see +{doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`. + ## Rules - Fix behavior at the owner layer. A training script should not carry long-term diff --git a/docs/sphinx/source/en/4-developer_guide/1-architecture/4-scene_composition.md b/docs/sphinx/source/en/4-developer_guide/1-architecture/4-scene_composition.md index 03f0b7dab..0fcebdcae 100644 --- a/docs/sphinx/source/en/4-developer_guide/1-architecture/4-scene_composition.md +++ b/docs/sphinx/source/en/4-developer_guide/1-architecture/4-scene_composition.md @@ -6,21 +6,13 @@ native model during initialization. ## Contract -`SceneCfg` and `TerrainSceneCfg` live in `src/unilab/base/scene.py`: - -```python -@dataclass -class TerrainSceneCfg: - generator: TerrainGeneratorCfg | None = None - hfield_name: str = "terrain_hfield" - geom_name: str | None = None - -@dataclass -class SceneCfg: - model_file: str - fragment_files: list[str] = field(default_factory=list) - terrain: TerrainSceneCfg | None = None -``` +`TerrainSceneCfg` is defined by `unisim.scene` and re-exported from +`src/unilab/base/scene.py`. UniLab's `SceneCfg` subclasses the UniSim config, +retaining `model_file`, `fragment_files`, and `terrain` while adding task fields +including `entities`, `entity_assets`, `entity_variant`, `primary_entity`, and +`tracked_body_names`. UniSim owns physics-scene fields and backend-facing +behavior; UniLab only materializes Hydra/OmegaConf entity mappings into typed +facade configs on the cold path. `EnvCfg.scene` is the single scene source. Static scenes use `SceneCfg(model_file=...)`. Procedural terrain scenes combine a robot model, @@ -73,8 +65,9 @@ For procedural terrain, the MuJoCo backend calls with `terrain_origins` (and an optional surface sampler). The procedural path returns a precompiled `MjModel`; it does not expose a final -`scene.xml` path as a contract. Scene context such as `terrain_origins` is -handed back to the env through backend attributes. +`scene.xml` path as a contract. Terrain context is returned on the cold path +through the public `SimBackend.get_terrain_spawn_data()` interface; UniLab does +not read backend-private scene attributes. ## Layer Ownership @@ -109,6 +102,7 @@ but it does not own a production rough-terrain task: - Terrain generator: `unisim.terrain.generator` - MuJoCo materializer: `unisim.backend.mujoco.xml` - Motrix materializer: `unisim.backend.motrix.scene` -- Contract coverage: `tests/utils/test_xml_utils.py` +- Contract coverage: `tests/base/test_terrain.py`, + `tests/terrains/test_terrain_generator.py`, `tests/utils/test_xml_utils.py` User instructions are in {doc}`../../2-user_guide/6-terrain/1-procedural`. diff --git a/docs/sphinx/source/en/4-developer_guide/1-architecture/5-registry.md b/docs/sphinx/source/en/4-developer_guide/1-architecture/5-registry.md index 643781a7c..05f7ebb77 100644 --- a/docs/sphinx/source/en/4-developer_guide/1-architecture/5-registry.md +++ b/docs/sphinx/source/en/4-developer_guide/1-architecture/5-registry.md @@ -18,9 +18,9 @@ defined by {doc}`/adr/ADR-0004-registry-bootstrap-contract` and implemented in 5. Imported modules register configs with `@registry.envcfg(...)` and env implementations with `@registry.env(..., sim_backend=...)` or `registry.register_env(...)`. -6. Runtime construction goes through `registry.make(...)`, which applies env - config overrides, validates the env config, selects the requested backend, - and instantiates the registered env class. +6. Runtime construction goes through `registry.make(...)`, which applies and + validates env config overrides, selects the requested backend, calls the + registered env factory, and requires it to return a `TorchEnv`. ## Extension Rules diff --git a/docs/sphinx/source/en/4-developer_guide/1-architecture/6-manager_based_api.md b/docs/sphinx/source/en/4-developer_guide/1-architecture/6-manager_based_api.md index c7fc8fc78..b22e8a642 100644 --- a/docs/sphinx/source/en/4-developer_guide/1-architecture/6-manager_based_api.md +++ b/docs/sphinx/source/en/4-developer_guide/1-architecture/6-manager_based_api.md @@ -5,8 +5,10 @@ term configs, function/class terms, lifecycle ordering, and reset semantics foll pinned mjlab 1.6.0 source. Numeric execution uses Torch tensors while preserving UniLab's `TorchEnvState`, Hydra owner YAML, `SimBackend`, registry, and IPC contracts. -The current tensor-runtime decision is {doc}`ADR-0011 `. -The superseded compatibility matrix and mechanical migration example remain in +The current tensor-runtime structural baseline is +{doc}`ADR-0012 `, which +supersedes {doc}`ADR-0011 `. +The older compatibility matrix and mechanical migration example remain in {doc}`ADR-0006 ` as historical context. @@ -14,6 +16,16 @@ historical context. - Community manager semantics and a general structure take priority over local optimizations that would create a UniLab-only term API. +- Manager-Based is the sole production task runtime. + `make_manager_based_rl_env()` provides the shared construction path; + task-owned factories and subclasses, such as `G1WalkManagerBasedEnv`, must + retain `ManagerBasedRlEnv` and its Manager lifecycle. A second direct runtime + that bypasses the Manager must not be registered. +- Production tasks are configured only from Hydra owner YAML. YAML fully + declares managers, groups, terms, concrete cfg `_target_` values, dotted + callables, params, weights, and observation mappings. The Registry + materializes plain typed configs on the cold path; Python does not mirror + task-specific config declarations. - Manager carriers, term returns, environment IDs, and entity views use Torch tensors. Production `managers` and `envs` source rejects NumPy imports and Torch↔NumPy conversions. The cold NPZ MotionLoader is the only task-runtime diff --git a/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md b/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md index eaad1d8cc..dcc56e1e5 100644 --- a/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md +++ b/docs/sphinx/source/en/4-developer_guide/2-contracts/1-env_contract.md @@ -1,9 +1,13 @@ # Env Contract -The environment contract is code-owned by `src/unilab/base/base.py` and -`src/unilab/base/torch_env.py`. Observation semantics are recorded in -{doc}`/adr/ADR-0005-unified-obs-critic-env-and-ipc-contract` and superseded by -{doc}`/adr/ADR-0011-torch-only-manager-based-runtime`. +The environment lifecycle is owned by `src/unilab/base/base.py` and +`src/unilab/base/torch_env.py`; the structural contract injected into RL +runners and collectors lives in `src/unilab/base/contracts/`. Observation-group +semantics are recorded in +{doc}`/adr/ADR-0005-unified-obs-critic-env-and-ipc-contract`. +{doc}`/adr/ADR-0011-torch-only-manager-based-runtime` and +{doc}`/adr/ADR-0012-sole-tensor-manager-and-scoped-backends` update the tensor +carrier; they do not replace the `obs` plus optional `critic` semantics. ## Required Shape @@ -12,8 +16,10 @@ The environment contract is code-owned by `src/unilab/base/base.py` and - The only optional critic-only observation key is `critic`. - `obs_groups_spec` maps each observation group name to its flat dimension. Wrappers and learners use this map to size actor and critic paths. -- `reset(env_indices)` accepts a one-dimensional Torch integer tensor (or - `None`) and returns `(obs_dict, info_dict)` for the reset rows. +- `reset(env_ids)` accepts a one-dimensional Torch integer tensor (or `None`) + and returns `(obs_dict, info_dict)`. Observation tensors remain full-width + `(num_envs, dim)`; only selected rows are reset and updated, while unselected + rows retain their previous observations. - `step(actions)` on `TorchEnv` accepts a contiguous float32 Torch tensor and returns `TorchEnvState`; external adapters may transfer tensors to a trainer device only at the adapter boundary. @@ -53,9 +59,9 @@ The environment contract is code-owned by `src/unilab/base/base.py` and ## Evidence In Repo - Env base contract: `src/unilab/base/base.py` +- RL injection contract: `src/unilab/base/contracts/env.py` - Torch env lifecycle: `src/unilab/base/torch_env.py` -- RSL-RL adapter boundary: `src/unilab/rl/vec_env.py` -- Final observation helper: `src/unilab/base/final_observation.py` -- Tests: `tests/base/test_torch_env.py`, - `tests/envs/test_manager_based_rl_env.py`, - `tests/utils/test_final_observation.py`, `tests/ipc/` +- RSL-RL adapter boundary: `src/unilab/rl/adapters/rsl_rl/vec_env.py` +- Final-observation lifecycle: `src/unilab/base/torch_env.py` +- Tests: `tests/base/test_torch_env.py`, `tests/base/contracts/test_env.py`, + `tests/envs/test_manager_based_rl_env.py`, `tests/rl/runtime/ipc/` diff --git a/docs/sphinx/source/en/4-developer_guide/2-contracts/3-task_owner.md b/docs/sphinx/source/en/4-developer_guide/2-contracts/3-task_owner.md index 5f72fb1dd..89c5bc0d0 100644 --- a/docs/sphinx/source/en/4-developer_guide/2-contracts/3-task_owner.md +++ b/docs/sphinx/source/en/4-developer_guide/2-contracts/3-task_owner.md @@ -2,7 +2,9 @@ Task owner YAML is the identity of a composed task/backend/algorithm path. The contract is recorded in -{doc}`/adr/ADR-0003-task-owner-and-config-compose-contract`. +{doc}`/adr/ADR-0003-task-owner-and-config-compose-contract`; composition from a +same-directory `base.yaml` and backend leaf is defined by +{doc}`/adr/ADR-0023-task-sim-owner-inherits-same-directory-base-only`. ## Owner Paths @@ -15,9 +17,14 @@ contract is recorded in - Use public CLI flags to switch backend, for example `uv run train --algo ppo --task go2_joystick_flat --sim mujoco` or - `uv run train --algo ppo --task go2_joystick_flat --sim mujoco`. + `uv run train --algo sac --task g1_walk_flat --sim mjwarp`. - For off-policy entrypoints, `--algo ` selects the per-algorithm config tree; the owner YAML path is `src/unilab/conf//task//.yaml`. +- Every task directory has a `base.yaml` holding the shared task contract. Each + backend leaf lists only `/task//base` and `_self_` in `defaults`; it must + not inherit another backend leaf. The base is not a trainable entrypoint. The + leaf directly owns `training.task_name`, `training.sim_backend`, and explicit + backend-specific differences. - `training.sim_backend` is an identity field inside the selected owner YAML. It is not an independent backend switch. - Backend-specific reward, env, scene, and algorithm differences belong in the diff --git a/docs/sphinx/source/en/4-developer_guide/3-extending/0-index.md b/docs/sphinx/source/en/4-developer_guide/3-extending/0-index.md index cb37ae4e4..9f459f6b3 100644 --- a/docs/sphinx/source/en/4-developer_guide/3-extending/0-index.md +++ b/docs/sphinx/source/en/4-developer_guide/3-extending/0-index.md @@ -21,7 +21,7 @@ Add a `SimBackend` implementation and declared capabilities. :::{grid-item-card} New algorithm :link: 3-new_algorithm :link-type: doc -Add configs, runner code, and script-level assembly. +Add owner configs, `unilab.rl` code, and thin entrypoint assembly. ::: :::{grid-item-card} New terrain diff --git a/docs/sphinx/source/en/4-developer_guide/3-extending/1-new_task.md b/docs/sphinx/source/en/4-developer_guide/3-extending/1-new_task.md index 636e3833c..ac5175136 100644 --- a/docs/sphinx/source/en/4-developer_guide/3-extending/1-new_task.md +++ b/docs/sphinx/source/en/4-developer_guide/3-extending/1-new_task.md @@ -6,45 +6,59 @@ Start from the contracts: {doc}`../2-contracts/1-env_contract`, ## Implementation Checklist -1. Pick the closest owner package under `src/unilab/envs/`. -2. Define or extend an env config dataclass and register it with - `@registry.envcfg("EnvName")`. -3. Register each supported backend implementation with - `@registry.env("EnvName", sim_backend="mujoco")` or - `@registry.env("EnvName", sim_backend="motrix")`. +1. Pick the closest task owner package under `src/unilab/tasks/`. Keep the + shared Manager-Based runtime under `src/unilab/envs/`; do not add a per-task + env class or a legacy class-config factory. +2. Register `ManagerBasedRlEnvCfg` (or another existing Manager-Based config + owner) with `registry.register_env_config("EnvName", ...)`. +3. Register the generic `make_manager_based_rl_env` factory for each supported + backend with `registry.register_env("EnvName", ..., sim_backend=...)`. + Backend selection does not require separate task-specific env implementations. 4. If the task lives in a new module, add that module to the package `__unilab_registry_modules__` tuple so `ensure_registries()` imports it. Third-party packages outside this repo additionally declare `[project.entry-points."unilab.tasks"]` in their `pyproject.toml` (see {doc}`../1-architecture/5-registry`). -5. Keep `obs_groups_spec` accurate. It must include `obs` and may include - `critic`; wrappers and learners trust these dimensions. +5. Declare observations, actions, rewards, events, and other task terms in the + owner YAML. Set `policy_observation_group` and, when needed, + `critic_observation_group`; the Manager maps these to the required `obs` and + optional `critic` entries in `obs_groups_spec`, whose dimensions wrappers and + learners trust. 6. Keep reset and step semantics at the env owner layer: - `reset(env_indices)` returns `(obs_dict, info_dict)`, and `step(actions)` + `reset(env_ids)` returns `(obs_dict, info_dict)`, and `step(actions)` returns `TorchEnvState`. -7. Add owner YAMLs under the relevant config root, such as - `src/unilab/conf/ppo/task//.yaml` or, for an off-policy algorithm, - `src/unilab/conf//task//.yaml`. -8. Put task or scene keyframes in task/scene XML fragments referenced through +7. Put shared task behavior in `src/unilab/conf//task//base.yaml` + and backend/algo-specific selections in `.yaml` leaves that inherit + it. Each runnable leaf selects `training.task_name` and + `training.sim_backend`; user-facing commands use + `--task --sim ` rather than a standalone + `training.sim_backend` override. +8. Implement domain randomization only as Manager-Based event terms negotiated + through declared `SimBackend` capabilities. Unsupported capabilities fail + closed; do not add a DR manager/provider protocol. +9. Put task or scene keyframes in task/scene XML fragments referenced through `SceneCfg.fragment_files`; do not put task-level keyframes in `robot.xml`. + Asset and XML inspection belongs to initialization, materialization, or + caching, never `step()`, `reset()`, or randomization hot paths. ## Validation Near Risk - Registry and config shape: `tests/base/test_registry.py`, `tests/config/test_config_system.py` - Env observation/reset behavior: `tests/base/test_torch_env.py` and the nearest - task-specific tests under `tests/envs/` + task-specific tests under `tests/envs/` and `tests/tasks/` - Script composition: `tests/scripts/test_train_script_configs.py` ## Evidence In Repo -- Registry API: `src/unilab/base/registry.py` +- Registry API and backend allowlist: `src/unilab/base/registry.py` - Env state contract: `src/unilab/base/torch_env.py` - Scene config: `src/unilab/base/scene.py` - Task declaration is owner YAML plus registry bootstrap — no per-task Python env class: `src/unilab/tasks/locomotion/go2/__init__.py` registers - `Go2JoystickFlat` with `ManagerBasedRlEnvCfg` and `make_manager_based_rl_env` - per backend, and the owner YAMLs live under - `src/unilab/conf/ppo/task/go2_joystick_flat/`. Task-owned term library - example: `src/unilab/tasks/motion_tracking/g1/manager_terms.py`. End-to-end + `Go2JoystickFlat` with `ManagerBasedRlEnvCfg` and + `make_manager_based_rl_env` per backend. Shared task terms live in + `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml`, with backend leaves + beside it. Task-owned term library example: + `src/unilab/tasks/motion_tracking/g1/manager_terms.py`. End-to-end walkthrough: {doc}`../../6-how_to/1-onboard_new_robot`. diff --git a/docs/sphinx/source/en/4-developer_guide/3-extending/2-new_backend.md b/docs/sphinx/source/en/4-developer_guide/3-extending/2-new_backend.md index 480b657a7..ed3f30c79 100644 --- a/docs/sphinx/source/en/4-developer_guide/3-extending/2-new_backend.md +++ b/docs/sphinx/source/en/4-developer_guide/3-extending/2-new_backend.md @@ -6,28 +6,41 @@ adding backend code. ## Current Backend Shape -The repository currently recognizes `mujoco` and `motrix` in two important -places: +Concrete adapters and their public contracts live in `unisim-core`. UniLab's +`create_backend(...)` resolves hosted assets and translates owner options, then +delegates construction to `unisim.create_backend(...)`. The backend names +accepted by task registration and the top-level CLI are declared separately in +`_SUPPORTED_SIM_BACKENDS` (`src/unilab/base/registry.py`) and `SUPPORTED_SIMS` +(`src/unilab/cli.py`). -- `registry.register_env(...)` in `src/unilab/base/registry.py` -- `create_backend(...)` in `src/unilab/base/backend_factory.py` - -A third backend is therefore an architecture change, not just a new package. +Adding a backend therefore crosses the upstream adapter contract and UniLab's +registry, config, dependency, and device-routing owners; it is not just a new +task package. ## Implementation Checklist -1. Implement a `SimBackend` subclass under `unisim.backend/`. -2. Add backend construction to `create_backend(...)`. -3. Update registry validation if the new backend should be accepted by - `@registry.env(..., sim_backend=...)`. -4. Expose backend-specific optional capabilities through `SimBackend` methods, - `PlayCapabilities`, domain-randomization capability methods, or a new - explicit abstract method. -5. Add task owner YAMLs for supported task/backend pairs. Route user-facing - examples through `--task --sim ` and do not rely on - `training.sim_backend=` as an override. -6. Keep XML, asset, and model inspection in backend init or materialization code. - Hot env paths should receive cached IDs, arrays, or declared backend methods. +1. Implement a `SimBackend` subclass under `unisim.backend./` in + UniSim, and add its adapter declaration and lazy factory dispatch there. +2. Add the UniLab backend name to the registry and CLI allowlists. If the + UniLab and UniSim names differ, translate them in + `src/unilab/base/process_device.py`; add only the required runtime + dependency checks, owner options, and device routing in their existing + owner modules. +3. Expose optional behavior through the declared `SimBackend` capability + surface, including `get_tensor_capabilities()`, `get_dr_capabilities()`, + `get_play_capabilities()`, and `get_capabilities()` as applicable. Extend + the public interface before an env consumes a new capability; never probe + backend-private methods from env or training code. +4. Register `make_manager_based_rl_env` for each supported task/backend pair + and add the corresponding owner YAML leaves. Route user-facing examples + through `--task --sim ` and do not rely on + `training.sim_backend=` as a standalone override. +5. Keep XML, asset, and model inspection in backend init or materialization + code. Hot env paths should receive cached IDs, arrays, or declared backend + methods. +6. After changing registered or configured support, regenerate the support + matrix with `uv run scripts/generate_support_matrix.py --write`; do not + hand-edit its generated block. ## Validation Near Risk @@ -35,12 +48,17 @@ A third backend is therefore an architecture change, not just a new package. `tests/base/test_backend_conformance.py`, `tests/base/test_sim_backend_smoke.py` - Backend-specific behavior tests near the feature boundary, such as - `tests/base/test_motrix_backend_options.py` -- Task/backend config composition: `tests/config/test_config_system.py` + `tests/base/test_motrix_backend_options.py` and + `tests/base/backend/test_process_device.py` +- CLI runtime requirements and naming: `tests/test_cli_runtime_requirements.py` +- Task/backend config composition and generated support data: + `tests/config/test_config_system.py`, `tests/scripts/test_support_matrix.py` ## Evidence In Repo -- Backend interface: `unisim.backend.base` -- Backend factory: `src/unilab/base/backend_factory.py` -- MuJoCo backend package: `unisim.backend.mujoco` -- Motrix backend package: `unisim.backend.motrix` +- Backend interface and adapter factory: `unisim.backend.base`, + `unisim.create_backend` +- UniLab asset/option adapter: `src/unilab/base/backend_factory.py` +- Backend name and device mapping: `src/unilab/base/process_device.py` +- Registry and CLI allowlists: `src/unilab/base/registry.py`, + `src/unilab/cli.py` diff --git a/docs/sphinx/source/en/4-developer_guide/3-extending/3-new_algorithm.md b/docs/sphinx/source/en/4-developer_guide/3-extending/3-new_algorithm.md index 64512f4c6..a827b3499 100644 --- a/docs/sphinx/source/en/4-developer_guide/3-extending/3-new_algorithm.md +++ b/docs/sphinx/source/en/4-developer_guide/3-extending/3-new_algorithm.md @@ -27,42 +27,49 @@ Change no code — only adjust the Hydra config under `src/unilab/conf//`: ### 2. `runtime_resolver`: Algorithm Code In Your Own Repository A researcher imports `unilab.rl` as a library in their own repository and -implements the runner / learner / play logic there — **no fork of UniLab -needed**. The owner YAML declares a dotted path -(`module:attr`) via `algo.runtime_resolver`: +implements family-specific runtime customizations there — **no fork of UniLab +needed**. The owner YAML declares a dotted path (`module:attr`) via +`algo.runtime_resolver`: ```yaml algo: runtime_resolver: my_pkg.my_module:resolve_my_runtime ``` -Contract: - -- Signature is `(rl_cfg: dict) -> Runtime | None`; returning `None` falls back - to the algorithm's default runtime; -- The returned object must carry `runner_cls`; depending on the algorithm - family it may optionally carry `play_fn` (APPO style); -- Resolution happens on the RL runtime side (`unilab.rl.algos.appo.resolution`); - the dotted path may point at any importable module. The PPO path no longer - uses `runtime_resolver` — it drives upstream RSL-RL directly through - `unilab.rl`, so PPO customization goes through the `class_name` - config keys (tier 1). - -### 3. Modify `unilab/rl/algos/` In UniLab - -Only when you need to change the shared runner / learner / collector -implementation (for example a new IPC lifecycle) should you modify -`src/unilab/rl/algos/` in this repository. Async algorithms should reuse -`AsyncRunner`, `ReplayBuffer` / -`TensorRolloutRingBuffer`, and `SharedWeightSync` instead of creating a new IPC -lifecycle. +The resolver receives the resolved algorithm dictionary as +`(rl_cfg: dict)`. Its return contract depends on the algorithm family: + +- APPO uses `unilab.rl.algos.appo.resolution`. The returned object must carry + `runner_cls`; `play_fn` is optional and falls back to the generic APPO play + entrypoint. +- SAC-family off-policy customization uses + `unilab.rl.runtime.offpolicy.resolution` and must return an + `OffPolicyRuntime`. Its optional fields override the learner class, algorithm + type, actor kwargs/adapter modules, and learner preparation hook while the + shared off-policy runner and IPC lifecycle remain in place. +- Omitting `runtime_resolver` selects the default runtime. If a configured + resolver returns `None`, both APPO and off-policy resolution fail closed; + `None` is not a fallback signal. +- PPO does not use `runtime_resolver`: it drives upstream RSL-RL through + `unilab.rl.adapters.rsl_rl`, so PPO customization goes through the + `class_name` config keys (tier 1). + +### 3. Modify `unilab.rl` Owner Layers In UniLab + +Add algorithm-specific learners and runners under `src/unilab/rl/algos/`. +Change shared collector, IPC, off-policy, or distributed behavior only in +`src/unilab/rl/runtime/`, and keep upstream RSL-RL integration in +`src/unilab/rl/adapters/rsl_rl/`. Async algorithms should reuse `AsyncRunner`, +`ReplayBuffer` / `TensorRolloutRingBuffer`, and `SharedWeightSync` instead of +creating a new IPC lifecycle. Algorithms receive a pickleable `EnvFactory`; +they must not construct concrete envs themselves. ## Footprint Of A CLI-Routable Algorithm `uv run train --algo ` / `uv run eval --algo ` use convention-based routing (`available_algos` and `build_route` in -`src/unilab/cli.py`): an algo name `` is routable if and only if both of -the following exist — **no cli.py change required**: +`src/unilab/cli.py`). A non-built-in algo name `` is routable if and only +if both of the following exist — **no cli.py change required**: 1. `src/unilab/conf//config.yaml` — the Hydra config root with the algorithm hyperparameters inlined; @@ -101,12 +108,18 @@ Notes: - CLI routing and convention discovery: `tests/test_cli.py` - Script/config tests: `tests/scripts/test_train_script_configs.py`, `tests/scripts/test_train_scripts.py` +- Runtime resolution and lifecycle: `tests/rl/runtime/offpolicy/test_resolution.py`, + `tests/rl/runtime/test_async_runner.py` +- RL import ownership boundaries: `tests/test_library_import_boundary.py` ## Evidence In Repo - Structured config dataclasses: `src/unilab/structured_configs.py` - Training helpers: `src/unilab/training/common.py`, `src/unilab/training/run.py` +- Runtime resolvers: `src/unilab/rl/algos/appo/resolution.py`, + `src/unilab/rl/runtime/offpolicy/resolution.py` +- Pickleable env injection: `src/unilab/base/env_factory.py` - Existing algorithm packages: `unilab.rl.algos` in this repository (merged from the former [unilabsim/unilab_rl](https://github.com/unilabsim/unilab_rl); see diff --git a/docs/sphinx/source/en/4-developer_guide/3-extending/4-new_terrain.md b/docs/sphinx/source/en/4-developer_guide/3-extending/4-new_terrain.md index 348eb7e29..f53daf910 100644 --- a/docs/sphinx/source/en/4-developer_guide/3-extending/4-new_terrain.md +++ b/docs/sphinx/source/en/4-developer_guide/3-extending/4-new_terrain.md @@ -14,9 +14,12 @@ materialization out of `step()`, `reset()`, and hot domain-randomization loops. set such as `ROUGH_TERRAINS_CFG` or through an owner YAML under `src/unilab/conf/`. 4. Expose terrain to scenes through `SceneCfg.terrain` and `TerrainSceneCfg` in `src/unilab/base/scene.py`. -5. If an env needs height observations, create the backend scanner on init via - `bind_height_scanner(...)`; read samples through the returned - `HeightScanner`. +5. If an env needs ray/height observations, declare an `mdp.RayScan` + observation term with a `RayPatternCfg`. The Manager binds the configured + caster through UniSim during read-phase initialization; do not construct or + bind scanners in `step()` or `reset()`. Code that directly consumes the + lower-level `SimBackend.bind_height_scanner(...)` contract must likewise + bind it on a cold path. 6. Keep terrain spawn, curriculum, and observation dimensions reflected in the owning env config and `obs_groups_spec`. @@ -24,8 +27,11 @@ materialization out of `step()`, `reset()`, and hot domain-randomization loops. - Terrain generator shape and numerical behavior: `tests/terrains/test_terrain_generator.py` +- Scene terrain origins and curriculum: `tests/base/test_terrain.py` - Backend terrain materialization contract: `tests/base/test_backend_conformance.py` +- Ray observation configuration and binding: + `tests/envs/mdp/test_ray_observation.py` - Backend materialization boundaries: `tests/utils/test_xml_utils.py` ## Evidence In Repo @@ -33,3 +39,5 @@ materialization out of `step()`, `reset()`, and hot domain-randomization loops. - Terrain configs and presets: `src/unilab/terrains/config.py` - Terrain generator: `unisim.terrain.generator` - Heightfield terrain types: `src/unilab/terrains/heightfield_terrains.py` +- Manager terrain state: `src/unilab/base/terrain.py` +- Ray observation owner: `src/unilab/envs/mdp/ray_observation.py` diff --git a/docs/sphinx/source/en/4-developer_guide/4-contributing.md b/docs/sphinx/source/en/4-developer_guide/4-contributing.md index 4fd71cc7d..9970b3ef1 100644 --- a/docs/sphinx/source/en/4-developer_guide/4-contributing.md +++ b/docs/sphinx/source/en/4-developer_guide/4-contributing.md @@ -84,10 +84,11 @@ UNILAB_DOCS_SKIP_AUTODOC=1 uv run --no-project --with-requirements requirements. The `Docs` GitHub Actions workflow runs the same prose-only build for matching PRs whose base is `main` and for pushes to `main`. It can also be started from -the GitHub Actions web UI via `workflow_dispatch`. It does not install UniLab -with `pip install -e .`, does -not generate API reference pages, and does not publish the external docs -repository. +the GitHub Actions web UI via `workflow_dispatch`. The PR build does not install +UniLab or generate API reference pages. After that build succeeds on `main`, the +separate deploy job runs `sphinx-multiversion` and publishes the external +`UniLab-doc` repository; a failed UniLab installation there falls back to a +prose-only deployment. For a final local refresh of the full site, including API reference pages for the `UniLab-doc` publication flow, use a parallel Sphinx build from a synced @@ -107,6 +108,10 @@ branches, PR evidence, local and remote gates, ADRs, and releases are in {doc}`5-contributing_workflow`. Run focused checks for the changed contract and `make test-all` on the final head before creating or updating a PR. +Every PR with user-visible changes must add an entry to the `Unreleased` +section of `docs/sphinx/source/changelog.md` as described in `CONTRIBUTING.md`. +Purely internal refactors, test-only changes, and CI plumbing may skip it. + ## Testing Tests are grouped by owner area under `tests/`: @@ -116,13 +121,16 @@ tests/ ├── base/ # registry, backend selection, env contract ├── config/ # Hydra / dataclass / reward injection ├── envs/ # environment configuration and instantiation -├── dr/ # domain-randomization types and managers +├── managers/ # Manager-Based terms and observation/reset behavior +├── tasks/ # task-owned terms, registration, and package boundaries ├── terrains/ # terrain generators and scene materialization -├── ipc/ # shared-memory and async-runner primitives +├── rl/ # algorithms, adapters, distributed/IPC/off-policy runtime +├── algos/ # training-runner integration +├── assets/ # hosted asset resolvers ├── scripts/ # training-script configs and entrypoint tooling -├── algos/ # runner integration, RSL-RL PPO -├── integration/ # cross-module reward / config integration ├── training/ # training-run helpers +├── architecture/ # cross-owner architecture boundaries +├── benchmark/ # benchmark contracts and smoke coverage └── utils/ # helpers and experiment tracking ``` @@ -162,7 +170,8 @@ Notes for `make test-slow`: - Do not describe `training.sim_backend=` as a standalone backend switch. Use `--sim ` in user-facing commands and select the owner YAML path internally. -- Keep English pages free of manual navigation blocks. +- Keep English and Chinese pages free of manual navigation blocks and per-page + language-picker lines. ## Configuration Changes diff --git a/docs/sphinx/source/en/4-developer_guide/5-contributing_workflow.md b/docs/sphinx/source/en/4-developer_guide/5-contributing_workflow.md index 3256c4ca4..4fc33a4de 100644 --- a/docs/sphinx/source/en/4-developer_guide/5-contributing_workflow.md +++ b/docs/sphinx/source/en/4-developer_guide/5-contributing_workflow.md @@ -80,10 +80,10 @@ another backend, macOS, Linux, or training behavior. A documentation-only change uses its focused docs checks as well as the repository gate required for its PR. Dependency maintenance is dual-track: a change to `pyproject.toml` dependency -pins must apply the same bump to `pyproject.rocm.toml` and `uv.rocm.lock` in -the same PR. For a published-dependency transition the upstream release must -exist on PyPI before the bump lands; see the tensor-runtime transition -subsection below. +pins must apply the same bump to `pyproject.rocm.toml` and regenerate both +`uv.lock` and `uv.rocm.lock` in the same PR. For a published-dependency +transition the upstream release must exist on PyPI before the bump lands; see +the tensor-runtime transition subsection below. ## Architecture Decisions diff --git a/docs/sphinx/source/en/4-developer_guide/6-agent_quick_reference.md b/docs/sphinx/source/en/4-developer_guide/6-agent_quick_reference.md index 3772e3fb7..fcd72d55a 100644 --- a/docs/sphinx/source/en/4-developer_guide/6-agent_quick_reference.md +++ b/docs/sphinx/source/en/4-developer_guide/6-agent_quick_reference.md @@ -16,8 +16,11 @@ repo facts. ## Contracts To Keep In Mind -- Env contract: `src/unilab/base/torch_env.py` +- Env lifecycle: `src/unilab/base/torch_env.py`; RL injection contract: + `src/unilab/base/contracts/env.py` - Backend contract: `unisim.backend.base` +- RL internal layering guard: `tests/test_library_import_boundary.py` +- Sim2Sim snapshot/validation: `src/unilab/utils/sim2sim.py` - Training helpers: `src/unilab/training/run.py` - Config schema: `src/unilab/structured_configs.py` - Developer standard: {doc}`1-architecture/1-overview` diff --git a/docs/sphinx/source/en/4-developer_guide/7-motion_assets.md b/docs/sphinx/source/en/4-developer_guide/7-motion_assets.md index bde100e9f..9334eb80d 100644 --- a/docs/sphinx/source/en/4-developer_guide/7-motion_assets.md +++ b/docs/sphinx/source/en/4-developer_guide/7-motion_assets.md @@ -48,7 +48,7 @@ The resolver then only looks up local files and raises if a file is missing. To pre-download every asset in an environment that does have network access: ```bash -huggingface-cli download unilabsim/unilab-motions \ +uv run hf download unilabsim/unilab-motions \ --repo-type dataset \ --local-dir src/unilab/assets ``` @@ -57,17 +57,17 @@ After this completes the assets are available for offline use. ## CI Caching -In CI, point `HF_HOME` at a persistent cache directory to avoid repeated -downloads: +The resolvers download with `local_dir=ASSETS_ROOT_PATH`, so CI should persist +`src/unilab/assets/motions/` and the registered robot asset directories for +direct reuse at the paths checked by the resolver. These downloaded contents +are excluded by `.gitignore`. `HF_HOME` can additionally point at a persistent +Hugging Face cache: ```yaml env: HF_HOME: /cache/huggingface ``` -Alternatively, pre-download into the in-repo directory with `--local-dir` -(already excluded by `.gitignore`). - ## Adding New Motion Files 1. Generate the `.npz` with the existing pipeline (see @@ -75,7 +75,7 @@ Alternatively, pre-download into the in-repo directory with `--local-dir` 2. Upload to the HF repo, keeping the directory layout identical: ```bash - huggingface-cli upload unilabsim/unilab-motions \ + uv run hf upload unilabsim/unilab-motions \ src/unilab/assets/motions motions \ --repo-type dataset ``` @@ -143,3 +143,9 @@ To add a new robot's binary assets: - Robot binary assets use the same directory resolver (`resolve_robot_asset_dir`). The resolver is also exposed through the `unilab-pull-assets` CLI. + +## Validation Near Risk + +- Motion, scene, and robot resolver behavior: `tests/assets/test_hub.py` +- Robot prefetch CLI: `tests/test_pull_assets.py` +- Motion CSV conversion: `tests/scripts/test_csv_to_npz.py` diff --git a/docs/sphinx/source/en/4-developer_guide/8-tensor_runtime_production.md b/docs/sphinx/source/en/4-developer_guide/8-tensor_runtime_production.md index 0467cf634..fc69d87a8 100644 --- a/docs/sphinx/source/en/4-developer_guide/8-tensor_runtime_production.md +++ b/docs/sphinx/source/en/4-developer_guide/8-tensor_runtime_production.md @@ -26,7 +26,7 @@ The current namespaces are independent: | Namespace | Version | Producer owner | | --- | ---: | --- | | TensorBoard / W&B metric schema | `1` | `unilab.rl.logging.metric_schema` | -| Runtime process/device/IPC manifest | `1` | `unilab.rl.logging.runtime_manifest_schema` | +| Runtime process/device/IPC manifest | `2` | `unilab.rl.logging.runtime_manifest_schema` | | UniLab long-soak monitor artifact | `0.3.0` | `unilab.training.soak` | Within a major version, producers may add optional fields with schema, tests, diff --git a/docs/sphinx/source/en/4-developer_guide/9-sim2sim_contract_status.md b/docs/sphinx/source/en/4-developer_guide/9-sim2sim_contract_status.md new file mode 100644 index 000000000..2eb6b7c45 --- /dev/null +++ b/docs/sphinx/source/en/4-developer_guide/9-sim2sim_contract_status.md @@ -0,0 +1,58 @@ +# Sim2Sim Contract Status + +`src/unilab/utils/sim2sim.py` is the runtime source of truth for policy-I/O and +network-shape compatibility. The full current owner table and field guidance are +maintained in the {doc}`Chinese contract status page +`. A transferable verdict is +a config-contract result, not a claim of dynamics equivalence, convergence, or +deployment performance. + +## Runtime Contract + +- Training writes present DENYLIST and WARNING_LIST fields to + `run_config.json.contract_snapshot`; ALLOWLIST fields are excluded. +- On playback routes with preflight enabled, the source snapshot is validated + against the target composed Hydra config before environment construction. + Preflight is skipped for an explicit source-less run and for the direct PPO + interactive viewer with `interactive.sim2sim=false`. When preflight runs, + missing, malformed, unknown, or retired snapshot keys fail closed even with + `strict=False`. +- DENYLIST mismatches raise by default and become warnings only in non-strict + mode. WARNING_LIST differences are reported; ALLOWLIST fields may vary. + Asymmetric presence of `env.` structural fields is included in these mismatches. +- Checkpoint dimension guards translate only tensor `size mismatch` errors into + Sim2Sim diagnostics. Other load errors propagate unchanged. + +Implementation evidence: `src/unilab/utils/sim2sim.py`, +`src/unilab/training/experiment.py`, +`src/unilab/visualization/interactive_playback.py`, and +`tests/training/test_sim2sim_resolver.py`. + +## Current Audit + +Reproduce the read-only audit with: + +```bash +uv run scripts/audit_sim2sim_contracts.py --trees ppo appo sac flashsac +``` + +The audited pairs are MuJoCo↔Genesis, MuJoCo↔MJWarp, MJWarp↔Genesis, +MuJoCo↔IsaacGym, and MuJoCo↔IsaacSim. The current workspace run reports five +`TRANSFERABLE` task rows and no `BLOCKED` rows: + +| Config tree | Task | Audited result | +| --- | --- | --- | +| PPO | `g1_walk_flat` | All three MuJoCo/MJWarp/Genesis pairs pass | +| SAC | `g1_motion_tracking` | All three MuJoCo/MJWarp/Genesis pairs pass | +| SAC | `g1_walk_flat` | All five audited pairs pass | +| FlashSAC | `g1_motion_tracking` | All three MuJoCo/MJWarp/Genesis pairs pass | +| FlashSAC | `g1_walk_flat` | MuJoCo↔MJWarp passes | + +Every other discovered task row is `N/A` because it has no audited pair. N/A is +not evidence of either compatibility or incompatibility. In particular, Motrix, +Newton, SuperDex, Drake, and Motrix Warp are not currently in `CONTRACT_PAIRS`. +See the Chinese page for the complete table and update it after rerunning the +audit; never substitute this static summary for play-time validation. + +Audit evidence: `scripts/audit_sim2sim_contracts.py` and +`tests/scripts/test_audit_sim2sim_contracts.py`. diff --git a/docs/sphinx/source/en/6-how_to/1-onboard_new_robot.md b/docs/sphinx/source/en/6-how_to/1-onboard_new_robot.md index 44d0eb365..52c906815 100644 --- a/docs/sphinx/source/en/6-how_to/1-onboard_new_robot.md +++ b/docs/sphinx/source/en/6-how_to/1-onboard_new_robot.md @@ -10,9 +10,10 @@ registry entry (checklist view: {doc}`../4-developer_guide/3-extending/1-new_tas Steps that need a simulator install, a display, or a GPU are marked. The compose-only checks (`--cfg job`) still pass through the CLI's backend preflight, so `--sim mujoco` requires the `mujoco` extra; the routed PPO -entrypoint also imports the built-in RL stack, so install the `unirl` extra -as well (`uv sync --extra mujoco` in a source checkout — the -same sync `make setup` runs). +entrypoint also imports the built-in RL stack. In a source checkout, run +`uv sync --extra mujoco` (the default `rl` dependency group supplies `unirl`; +this is the same sync `make setup` runs). For a pip installation, use +`pip install 'unilab[mujoco,unirl]'`. ## 0. Pick Names @@ -25,6 +26,13 @@ Three names, used consistently everywhere: (`_check_task_name` in `src/unilab/cli.py`). - `` — PascalCase registry key, e.g. `Go2JoystickFlat`. +Verify the CLI task name with the same pattern used by `src/unilab/cli.py`: + +```bash +uv run python -c 'from unilab.cli import TASK_NAME_PATTERN; assert TASK_NAME_PATTERN.fullmatch(""); print("task name accepted")' +# Expected: task name accepted +``` + ## 1. Prepare the Assets Follow {doc}`../2-user_guide/7-tooling/5-robot_import`. For a URDF source: @@ -35,10 +43,11 @@ uv run scripts/tools/import_robot.py [robot_name] The script converts URDF through `urdf-to-mjcf`, organizes the meshes, and opens a `mujoco.viewer` for keyframe tuning (implementation: -`scripts/tools/import_robot.py`). It writes the scene fragment as -`scene.xml`; the fragment name is yours to keep or rename — the Go2 -reference uses `scene_flat.xml`. If the source is already MJCF, lay out the -same directory contract by hand: +`scripts/tools/import_robot.py`). It writes `scene.xml` with only the `home` +keyframe. Before training, complete that fragment with an `` of the +robot XML, the ground, and any task sensors; keep the name `scene.xml` or +rename it (the Go2 reference uses `scene_flat.xml`). If the source is already +MJCF, lay out the same directory contract by hand: - `src/unilab/assets/robots//assets/` — only `.stl` / `.obj` meshes. - `src/unilab/assets/robots//.xml` — robot-only MJCF: bodies, @@ -94,8 +103,10 @@ Verify: ```bash grep -n '/.xml -# Expected: 0 — keyframes stay out of the robot XML. +! grep -n '/.xml +# Expected: no output and a successful exit — keyframes stay out of the robot XML. +uv run python -c 'import mujoco; mujoco.MjModel.from_xml_path("src/unilab/assets/robots//scene_flat.xml")' +# Expected: no output; the scene, robot include, meshes, and keyframe compile. ``` ## 3. Write the Owner YAMLs @@ -208,9 +219,9 @@ Notes on the minimal set: `track_angular_velocity`) read root state instead of named sensors, so they work on any robot whose command is named `twist`; parameters and semantics are in {doc}`../5-reference/6-manager_terms/1-rewards`. -- Add a `critic` observation group plus `env.critic_observation_group: critic` - when the algorithm should consume privileged observations (the Go2 owner - does both). +- When the algorithm should consume privileged observations, add a `critic` + observation group, set `env.critic_observation_group: critic`, and add + `critic: [critic]` under `algo.obs_groups` (the Go2 owner does all three). The backend owner (`src/unilab/conf/ppo/task//mujoco.yaml`), following `src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml`: @@ -283,15 +294,15 @@ Start with `mujoco` (the default backend). Each additional backend needs: {doc}`../2-user_guide/5-domain_randomization/2-field_reference`. Unsupported capabilities fail closed at construction; set a term the backend cannot serve to `null` in that backend's owner (pattern: - `pd_gains: null` in `src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml`). + `pd_gains: null` in `src/unilab/conf/ppo/task/go2_joystick_flat/drake.yaml`). Verify per added backend: repeat the `--cfg job` compose check with `--sim `. ## 6. First Training Run -Needs the backend's Python extra plus the `unirl` RL-stack extra (`uv sync ---extra mujoco --extra unirl`); a GPU for any meaningful run. Start small: +Needs the backend's Python extra plus the RL stack (installation above); a GPU +for any meaningful run. Start small: ```bash uv run train --algo ppo --task --sim mujoco \ @@ -348,5 +359,5 @@ uv run eval --algo ppo --task --sim mujoco --load-run -1 - Add or tune reward terms: {doc}`2-custom_reward`. - Built-in term tables: {doc}`../5-reference/6-manager_terms/0-index`. - Checklist view of the same contract: {doc}`../4-developer_guide/3-extending/1-new_task`. -- Interactive visual smoke check of the spawned scene (needs a display): - `uv run scripts/visualize_task_env.py --task --backend mujoco --num_envs 4`. +- Interactive visual smoke check of the trained policy (needs a display): + `uv run eval --algo ppo --task --sim mujoco --load-run -1 --render-mode interactive`. diff --git a/docs/sphinx/source/en/6-how_to/2-custom_reward.md b/docs/sphinx/source/en/6-how_to/2-custom_reward.md index 13018c41a..73b8e4b91 100644 --- a/docs/sphinx/source/en/6-how_to/2-custom_reward.md +++ b/docs/sphinx/source/en/6-how_to/2-custom_reward.md @@ -1,9 +1,9 @@ # Walkthrough: Add a Custom Reward Term -This walkthrough adds a reward term from zero to the point where it runs in -a real training session and its per-term value is visible in the training -logs. The runtime is Torch-only (since 1.3.4; see the changelog and -ADR-0011) — terms return `torch.Tensor`, and there is no NumPy path. +This walkthrough adds a reward term from zero to a real training session and +shows how to expose its per-term value in SAC/FlashSAC training logs. The +runtime is Torch-only (since 1.3.4; see the changelog and ADR-0011) — terms +return `torch.Tensor`, and there is no NumPy path. ## 1. Define the Term @@ -31,6 +31,14 @@ def action_magnitude_l1(env: ManagerBasedRlEnv) -> torch.Tensor: return torch.sum(torch.abs(env.action_manager.action), dim=1) ``` +Verify that the new function is importable at the exact path you will put in +YAML: + +```bash +uv run python -c 'from unilab.tasks.locomotion.common.sensor_reward_terms import action_magnitude_l1; print(action_magnitude_l1.__name__)' +# Expected: action_magnitude_l1 +``` + Return contract, enforced by `RewardManager._compute_term` (`src/unilab/managers/reward_manager.py`): a `torch.Tensor` of shape `(num_envs,)`, dtype `float32`, on the env device. Wrong type, dtype, device, @@ -67,8 +75,9 @@ the pre-dt weighted value). Use a negative weight for penalties — the framewor penalty terms return non-negative costs, so do not negate them a second time. Verify composition (still passes the CLI's backend preflight; `--sim mujoco` -needs the `mujoco` extra, and the routed training script imports the RL stack, -so the `unirl` extra is required as well): +needs the `mujoco` extra, and the routed training script imports the RL stack. +In a source checkout, `uv sync --extra mujoco` installs the default `rl` +dependency group as well): ```bash uv run train --algo ppo --task --sim mujoco --cfg job \ @@ -86,25 +95,41 @@ uv run train --algo ppo --task --sim mujoco \ algo.num_envs=64 algo.max_iterations=5 training.no_play=true ``` +Successful completion verifies the term's construction and return contract. The Manager-Based environment tracks per-term weighted reward means on device (`RewardManager.step_reward_means` in `src/unilab/managers/reward_manager.py` — mean across environments of `raw_value * weight`, before `dt` scaling). How much of that reaches the training log depends on the algorithm route: -- **PPO (rsl_rl)**: since 1.5.8 the per-term `reward/` scalars are no - longer copied into `info["log"]`; they travel as the fixed-width - `info["reward_components"]` tensor, which only the off-policy runtimes - consume. The console and TensorBoard +- **PPO (rsl_rl)**: the environment publishes a fixed-width + `info["reward_components"]` tensor, but the PPO adapter does not forward it; + per-term rewards are also absent from the `info["log"]` mapping it does + forward. The console and TensorBoard (`uv run tensorboard --logdir logs/rsl_rl_ppo/` — the directory level is the `training.task_name` registry name, not the snake_case CLI task) show the aggregate `Train/mean_reward`, and `Episode_Termination/` counters appear once episodes complete. -- **SAC / FlashSAC / APPO**: the off-policy runtimes consume - `reward_components` and emit the `reward/` metric family (schema: +- **APPO**: its worker reads per-term rewards from `info["log"]`, but the + Manager-Based environment does not publish them there, so this route does + not emit `reward/` either. +- **SAC / FlashSAC**: the off-policy runtimes consume `reward_components` and + emit the `reward/` metric family (schema: `src/unilab/rl/logging/metric_schema.py`), on the console and in TensorBoard / W&B ({doc}`../2-user_guide/1-training/3-logging`). +To verify the new term's own value end-to-end, add the same reward block to +`src/unilab/conf/sac/task//base.yaml` (or its backend sibling), then run +that SAC owner and inspect its log: + +```bash +uv run train --algo sac --task --sim mujoco \ + algo.num_envs=64 algo.max_iterations=5 training.no_play=true +uv run tensorboard --logdir logs/sac/ +# Expected: an action magnitude row in the console reward table and a +# reward/action_magnitude TensorBoard tag after collector metrics flush. +``` + Verified on 1.5.9 (MuJoCo backend, single RTX 4090). PPO (`go2_joystick_flat`, `algo.num_envs=16 algo.max_iterations=1`) console excerpt — the aggregate only: @@ -139,10 +164,11 @@ and a NaN/Inf return raises `RewardManager term '' returned NaN/Inf` ## 4. Tune the Weight -Retune a declared term from the command line — no YAML edit needed: +Retune a declared term from the command line — no YAML edit needed. Select the +algorithm whose owner contains the term: ```bash -uv run train --algo ppo --task --sim mujoco \ +uv run train --algo --task --sim mujoco \ reward.action_magnitude.weight=-0.01 ``` diff --git a/docs/sphinx/source/en/6-how_to/3-training_diagnostics.md b/docs/sphinx/source/en/6-how_to/3-training_diagnostics.md index 6ca052f36..ee70579e8 100644 --- a/docs/sphinx/source/en/6-how_to/3-training_diagnostics.md +++ b/docs/sphinx/source/en/6-how_to/3-training_diagnostics.md @@ -32,9 +32,19 @@ on-device and writes one state dump at an explicit host boundary. The chain: `check_interval` is the poll period in deferred mode. The defer mode itself is not a guard field: it follows the env's single validation strictness (`env.finite_validation_mode`, issue #2618) when the guard is attached. -2. The training entrypoint attaches the guard to the env - (`apply_env_nan_guard` in `src/unilab/training/run.py`), and - `TorchEnv.step` calls `NanGuard.check(...)` each step. On detection, + + Verify the composed guard and validation settings: + + ```bash + uv run train --algo ppo --task go2_joystick_flat --sim mujoco --cfg job \ + | grep -E 'nan_guard|check_interval|capture_interval|finite_validation_interval' + # Expected: nan_guard plus both intervals, and finite_validation_interval: 32. + ``` + +2. The PPO entrypoint attaches the guard with `apply_env_nan_guard` + (`src/unilab/training/run.py`); the off-policy collector attaches the same + guard from `training.nan_guard`. `TorchEnv.step` calls + `NanGuard.check(...)` each step. On detection, `NanGuard.dump(...)` writes `nan_dump__step.npz` (state ring buffer plus `meta_*` fields such as `detection_step` and `nan_env_ids`), copies the model file next to it, and updates the `nan_dump_latest.npz` @@ -50,24 +60,43 @@ on-device and writes one state dump at an explicit host boundary. The chain: (`pyproject.toml`); it prints the detection step and NaN env ids, then replays the buffered states. Backends without physics-state playback ship no states in the dump — the viewer prints the metadata only. + `--env-index` selects a row within `meta_dumped_env_ids`, not necessarily + the original environment id. + + Without a display, verify the dump metadata on the host: + + ```bash + uv run python -c 'import numpy as np; d = np.load("/tmp/unilab/nan_dumps/nan_dump_latest.npz"); print(d["meta_detection_step"], d["meta_nan_env_ids"], d["states"].shape)' + # Expected: detection step, bad environment ids, and the saved state shape. + ``` Details and the viewer walkthrough: {doc}`../2-user_guide/7-tooling/3-nan_visualizer`. Round-trip coverage: `tests/training/test_tensor_diagnostics.py`. -## Reading `info["log"]` +## Reading Training Metrics -Manager-Based environments place structured metrics in `info["log"]`; the -training logger forwards slash-prefixed entries to TensorBoard / W&B. The full -semantics table is in {doc}`../2-user_guide/1-training/3-logging`; the key families and their producers: +Manager-Based environments place structured episode metrics in `info["log"]`; +training loggers forward slash-prefixed entries to TensorBoard / W&B. Per-term +rewards use the separate `info["reward_components"]` tensor channel, and only +the SAC/FlashSAC runtimes currently turn it into persisted `reward/` +metrics. The full semantics table is in +{doc}`../2-user_guide/1-training/3-logging`; the key families and their producers are: | Key | Producer | Meaning | | --- | --- | --- | -| `reward/` | `RewardManager.step_reward_extras()` (`src/unilab/managers/reward_manager.py`) | Per-term mean of `raw_value * weight` across envs, before `dt` scaling | +| `reward/` | `CollectorMetrics` and `OffPolicyLogger` (`src/unilab/rl/runtime/offpolicy/metrics.py`, `src/unilab/rl/logging/offpolicy.py`) | SAC/FlashSAC per-term mean of `raw_value * weight` across envs, before `dt` scaling; not emitted by PPO or current Manager-Based APPO | | `Episode_Termination/` | `TerminationManager.reset()` (`src/unilab/managers/termination_manager.py`) | Count of reset env rows for which that termination term fired | | `Episode_Metrics/` | `MetricsManager` (`src/unilab/managers/metrics_manager.py`) | Completed-episode metric aggregates | -Use `Train/mean_reward` and `Train/mean_episode_length` for overall progress -and `reward/` to attribute it; see {doc}`../2-user_guide/1-training/3-logging` for the distinction. +Use `Train/mean_reward` and `Train/mean_episode_length` for overall progress. +On SAC/FlashSAC, use `reward/` to attribute it; PPO and APPO require the +aggregate and episode-level metrics instead. Verify the available keys in the +run directory printed by training: + +```bash +uv run tensorboard --logdir +# Expected: Train/* and episode metrics; reward/ only on SAC/FlashSAC. +``` ## Common Failure Modes @@ -76,17 +105,19 @@ and `reward/` to attribute it; see {doc}`../2-user_guide/1-training/3-logg - Symptom: training aborts with `RewardManager term '' returned NaN/Inf for environments ...` (`src/unilab/managers/reward_manager.py`), or the NaN guard writes a dump. -- Check: the per-term `reward/` curves — the diverging term usually - separates first. Compare its raw magnitude against its `weight` in the owner - YAML's `reward:` block. +- Check: on SAC/FlashSAC, inspect the per-term `reward/` curves — the + diverging term usually separates first. On PPO/APPO those curves are absent; + use the exception's term name and compare the term's raw magnitude against + its `weight` in the owner YAML's `reward:` block. - Fix: retune the weight from the CLI, e.g. `uv run train --algo ppo --task --sim mujoco reward..weight=-0.01` (override mechanics: the "Reward term weights" - section of {doc}`../2-user_guide/2-algorithms/1-ppo`). Keep the smoothness/regularization - terms (`action_rate`-style penalties) enabled; dropping them commonly - destabilizes the action stream. + section of {doc}`../2-user_guide/2-algorithms/1-ppo`). Verify the new value + before a longer run by appending `--cfg job | grep -A2 ''` to that + command. Keep the smoothness/regularization terms (`action_rate`-style + penalties) enabled; dropping them commonly destabilizes the action stream. -### Policy does not learn +### PPO policy does not learn - Symptom: `Train/mean_reward` stays flat while iterations advance. - Check the hyperparameters against the per-algorithm reference tables @@ -96,9 +127,19 @@ and `reward/` to attribute it; see {doc}`../2-user_guide/1-training/3-logg gradient estimate. Check observation conditioning: `algo.actor.obs_normalization` (the Go2 owner enables it) and whether any observation term emits values with unexpected scale. -- Check the reward mix: if a tracking term (`reward/tracking_*`) stays near - zero while penalties dominate the `reward/` curves, the weights are - misbalanced, not the optimizer. +- Check the reward mix: on SAC/FlashSAC, compare `reward/tracking_*` with the + penalty curves; on PPO, compare the tracking and penalty weights in the owner + YAML against the aggregate return. A tracking term staying near zero while + penalties dominate indicates a reward-weight problem rather than an + optimizer problem. + + Verify the PPO values actually composed: + + ```bash + uv run train --algo ppo --task --sim mujoco --cfg job \ + | grep -E 'num_envs|learning_rate|entropy_coef|lam:|obs_normalization' + # Expected: the intended environment count, optimizer values, and normalization flags. + ``` ### Two backends behave differently @@ -112,6 +153,14 @@ and `reward/` to attribute it; see {doc}`../2-user_guide/1-training/3-logg `training.sim2sim_strict: true` a mismatch raises `CrossBackendIncompatibleError`; WARNING_LIST fields only print a warning. Audit the shipped pairs with `uv run scripts/audit_sim2sim_contracts.py`. + For your own checkpoint, run the real preflight with the source run directory + name (not a path): + + ```bash + uv run eval --algo ppo --task --sim --load-run + # Expected: a DENYLIST mismatch raises before env construction; otherwise playback starts. + ``` + - Check capability differences per backend: {doc}`../3-deployment/2-sim_to_sim/6-capability_gaps`; exact support grades: {doc}`../5-reference/5-support_matrix`. @@ -122,8 +171,9 @@ and `reward/` to attribute it; see {doc}`../2-user_guide/1-training/3-logg `meta_nan_env_ids` narrow the window, and the replayed states show whether the pose diverged (asset/keyframe problem) or the controls blew up (reward/action scaling problem). -- Cross-check the `reward/` curves just before the detection step to - find the first diverging term. +- On SAC/FlashSAC, cross-check the `reward/` curves just before the + detection step to find the first diverging term; on PPO/APPO, use the + exception's term name and the dump metadata instead. ### Performance and trace analysis @@ -132,14 +182,20 @@ and `reward/` to attribute it; see {doc}`../2-user_guide/1-training/3-logg `training.trace_cuda_events` (`src/unilab/conf/sac/config.yaml`), plus `training.nvtx_profile_ranges` for NVTX annotations on CUDA. Traces are Perfetto JSON; scalar timing keys are documented in {doc}`../2-user_guide/1-training/3-logging`. -- Analyze a captured trace host-side (no GPU needed): +- Capture a short SAC trace, then analyze it host-side (capture needs the + backend and RL stack; analysis needs no GPU): ```bash - uv run scripts/analyze_offpolicy_trace.py --training-e2e \ + uv run train --algo sac --task --sim mujoco \ + algo.num_envs=64 algo.max_iterations=5 training.no_play=true \ + training.trace_enabled=true training.trace_output_dir= + uv run scripts/analyze_offpolicy_trace.py \ + /perfetto_offpolicy_timeline.json --training-e2e \ --event collector/env_step --gap-event learner/training_e2e ``` The script reports mean/median/p90/p95/p99 durations per event name; - `--steps-per-cycle` and `--drop-first` adjust the throughput summary. + `--steps-per-cycle` and `--drop-first` adjust the throughput summary. Check + that `training_e2e` and `collector/env_step` have non-zero sample counts. - For the production long-soak setup and its failure classification fields, see {doc}`../2-user_guide/1-training/7-tensor_runtime_production`. diff --git a/docs/sphinx/source/en/why_unilab.md b/docs/sphinx/source/en/why_unilab.md index 8d5bf0e72..c832653c4 100644 --- a/docs/sphinx/source/en/why_unilab.md +++ b/docs/sphinx/source/en/why_unilab.md @@ -59,9 +59,7 @@ prerequisite for robot training. UniLab is the RL infrastructure/runtime layer above that physics-engine evolution. It can connect MuJoCo, Motrix, Newton, or another registered adapter when the -repository has the corresponding configuration and validation evidence. It -does not claim that every solver or task combination is already production -ready. +repository has the corresponding configuration and validation evidence. ## Scope diff --git a/docs/sphinx/source/zh_CN/0-index.md b/docs/sphinx/source/zh_CN/0-index.md index 5e856d1f4..4de2d907e 100644 --- a/docs/sphinx/source/zh_CN/0-index.md +++ b/docs/sphinx/source/zh_CN/0-index.md @@ -174,7 +174,7 @@ flowchart LR env --> backend["SimBackend
unisim-core adapters"] env --> factory["EnvFactory contract"] factory --> runtime["Runner / IPC
unilab.rl async runtime"] - runtime --> learner["Learner
PPO / APPO / SAC"] + runtime --> learner["Learner
PPO / APPO / SAC / FlashSAC"] ``` 承载核心的 contract 记录在 @@ -189,8 +189,8 @@ recommendation 元数据。 | 机器人 / 任务族 | 有仓库证据的算法路径 | 后端证据 | | --- | --- | --- | -| Go2 joystick | PPO、FlashSAC | PPO 有已测试的 MuJoCo 与 Motrix 行。FlashSAC 有 `go2_joystick_flat` 的 MuJoCo owner YAML。 | -| G1 reference locomotion / tracking | PPO、APPO、SAC | PPO、APPO、SAC 都为保留的 G1 任务提供了已提交的 MuJoCo 与 Motrix owner YAML。 | +| Go2 joystick | PPO、APPO、FlashSAC | PPO 和 APPO 有已测试的 MuJoCo 与 Motrix 行。FlashSAC 有 `go2_joystick_flat` 的已测试 MuJoCo 行。 | +| G1 reference locomotion / tracking | PPO、APPO、SAC、FlashSAC | 四条算法路径都为保留的 G1 任务提供了已提交的 MuJoCo 与 Motrix owner YAML。 | Unitree production 任务族由 `unitree_rl_unilab` 维护,不计入核心仓库证据。 diff --git a/docs/sphinx/source/zh_CN/1-getting_started/0-index.md b/docs/sphinx/source/zh_CN/1-getting_started/0-index.md index b3504aa33..c20f72c4c 100644 --- a/docs/sphinx/source/zh_CN/1-getting_started/0-index.md +++ b/docs/sphinx/source/zh_CN/1-getting_started/0-index.md @@ -8,7 +8,7 @@ :::{grid-item-card} 快速演示 :link: 1-quick_demo :link-type: doc -克隆仓库、同步 Motrix 依赖、运行 PPO,然后进行评估或演示。 +克隆仓库、同步 MuJoCo 依赖、运行 PPO,然后进行评估或演示。 ::: :::{grid-item-card} 安装 diff --git a/docs/sphinx/source/zh_CN/1-getting_started/1-quick_demo.md b/docs/sphinx/source/zh_CN/1-getting_started/1-quick_demo.md index 2dbfd9848..56bd832c2 100644 --- a/docs/sphinx/source/zh_CN/1-getting_started/1-quick_demo.md +++ b/docs/sphinx/source/zh_CN/1-getting_started/1-quick_demo.md @@ -58,12 +58,12 @@ uv run train --algo ppo --task go2_joystick_flat --sim mujoco uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 -# 面向 Linux/服务器运行的 Motrix 无头(headless)视频导出 +# 面向 Linux/服务器运行的无头(headless)视频导出 uv run eval --algo ppo --task go2_joystick_flat --sim mujoco \ --load-run -1 --render-mode record ``` -该命令会路由到已注册的 `go2_joystick_flat` 任务,并使用 Motrix 后端。CLI 通过 +该命令会路由到已注册的 `go2_joystick_flat` 任务,并使用 MuJoCo 后端。CLI 通过 `--algo`、`--task` 和 `--sim` 让算法、任务和后端的选择保持显式;其内部会组合(compose)出匹配的 owner YAML。 在 macOS 上,CLI 会在需要时通过 `mxpython` 路由 Motrix 的交互式回放。使用 diff --git a/docs/sphinx/source/zh_CN/1-getting_started/2-installation.md b/docs/sphinx/source/zh_CN/1-getting_started/2-installation.md index ea6abb874..4ad295ee7 100644 --- a/docs/sphinx/source/zh_CN/1-getting_started/2-installation.md +++ b/docs/sphinx/source/zh_CN/1-getting_started/2-installation.md @@ -33,8 +33,7 @@ cd UniLab uv python install 3.13 ``` -UniLab 支持 Python `3.10` 到 `3.13`;主环境推荐使用 `3.13`。issue #1811 -期间,外部 worker 后端不属于 scoped Manager runtime。 +UniLab 支持 Python `3.10` 到 `3.13`;主环境推荐使用 `3.13`。 选择一条核心安装路径: @@ -96,7 +95,6 @@ ROCm / XPU profile 请优先使用上面的 uv 路径。机器人 mesh 和纹理 - [机器人网格与纹理](https://huggingface.co/datasets/unilabsim/unilab-robots) - [动作片段](https://huggingface.co/datasets/unilabsim/unilab-motions) - [场景](https://huggingface.co/datasets/unilabsim/unilab-scenes) -- [抓取缓存](https://huggingface.co/datasets/unilabsim/unilab-caches) - [Demo checkpoint](https://huggingface.co/datasets/unilabsim/unilab-checkpoints) 机器人 asset 可通过 `uv run unilab-pull-assets` 预拉取。中国大陆用户在默认 @@ -104,45 +102,47 @@ Hugging Face endpoint 无法访问时,可设置 `HF_ENDPOINT=https://hf-mirror ## 后端 Extras -当前 tensor-only Manager runtime 暴露五个生产后端(`mujoco`、`mjwarp`、 -`genesis`、`newton`、`motrix`),另有一个 scoped Drake owner。各自的仿真依赖 -均为可选。 +当前 CLI 可路由十个后端名称:`mujoco`、`mjwarp`、`genesis`、`newton`、 +`motrix`、`mtxwarp`、`superdex`、`drake`、`isaacsim` 和 `isaacgym`。各自的 +仿真依赖均为可选。名称可路由并不代表任务受支持;每个算法/任务/后端组合的 +证据等级请查看生成的支持矩阵。 ```bash # 可组合的 MuJoCo 4.0 版本线后端: -uv sync --extra mujoco --extra mjwarp --extra genesis --extra motrix +uv sync --extra mujoco --extra mjwarp --extra genesis --extra motrix --extra mtxwarp -# Newton 使用 MuJoCo 3.11,需与上面一组分开同步: +# Newton 和 SuperDex 使用 MuJoCo 3.11,需与上面一组分开同步: uv sync --extra newton +uv sync --extra superdex ``` | 后端 | 安装路径 | 重要前置条件 | | --- | --- | --- | | MuJoCo | `make setup` 或 `uv sync --extra mujoco` | Python >=3.11;在可用平台上安装预编译 `mjbatch-uni==0.3.3` wheel | | MJWarp | `uv sync --extra mujoco --extra mjwarp` | Python >=3.11 与 NVIDIA CUDA;单 GPU 主机默认使用当前 CUDA 设备,多卡拓扑仍需显式配置 | -| Genesis | `uv sync --extra genesis` | 已验证路径使用 Linux x86_64、NVIDIA GPU 及固定版本 torch/Genesis | +| Genesis | `uv sync --extra genesis` | Linux x86_64 + NVIDIA CUDA;Linux ROCm 使用 HIP Torch 和 exact `gs.amdgpu`(见下方 ROCm 说明) | | Newton | `uv sync --extra newton` | Linux CUDA,并钉定 newton / MuJoCo-Warp / Warp 版本;需与 `mujoco`、`mjwarp` 使用独立环境 | | Motrix | `uv sync --extra motrix` | CPU-authoritative MotrixSim 与 packed Torch HOST_BRIDGE 传输 | +| Motrix Warp | `uv sync --extra mtxwarp` | Linux x86_64 + NVIDIA CUDA 上的 CUDA-resident MotrixSim | +| SuperDex | `uv sync --extra superdex` | Linux x86_64 上的 Python 3.12 或 3.13;当前 scoped 到已配置的 PPO `go2_joystick_flat` owner,并与 MuJoCo 4.0 版本线 extras 分开安装 | | Drake | `make setup-drake` | 本地 Drake C++ 前缀与 DrakeUni native batch extension;当前 scoped 到 PPO `go2_joystick_flat` | +| IsaacGym | `bash scripts/tools/setup_isaacgym_env.sh` | Linux CUDA 上隔离的外部 Python 3.8 IsaacGym Preview 4 worker | +| IsaacSim | `bash scripts/tools/setup_isaacsim_env.sh` | Linux CUDA 上隔离的外部 Python 3.11 IsaacSim/IsaacLab worker | -CUDA-resident MotrixSim 运行时另有安装包路径:`uv sync --extra -mtxwarp`(委托 UniSim 的 CUDA MotrixSim extra;Linux x86-64 + NVIDIA -CUDA)。UniLab 侧统一使用 `mtxwarp` 命名;上游 extra 改名对齐见 -unilabsim/unisim#578。 - -`isaacgym`、`isaacsim` 与 `superdex` 适配器在 issue #1811 期间由 -`unisim-core` 暂时搁置。它们的 extras 和历史后端页面不构成生产支持声明; -在提供新的 capability、parity 与支持矩阵证据之前,UniLab train/eval CLI -会直接拒绝这些后端。 +UniLab 侧统一使用 `mtxwarp` 命名 CUDA-resident MotrixSim;上游 extra 改名 +对齐见 unilabsim/unisim#578。 runtime 变量、渲染器要求和验证命令见 scoped 后端页面: - {doc}`MuJoCo <../2-user_guide/3-backends/1-mujoco>` -- {doc}`MJWarp <../2-user_guide/3-backends/0-index>` +- {doc}`MJWarp 与 Motrix Warp <../2-user_guide/3-backends/0-index>` - {doc}`Genesis <../2-user_guide/3-backends/5-genesis>` - {doc}`Newton <../2-user_guide/3-backends/7-newton>` - {doc}`Motrix <../2-user_guide/3-backends/2-motrix>` +- {doc}`SuperDex <../2-user_guide/3-backends/8-superdex>` - {doc}`Drake <../2-user_guide/3-backends/6-drake>` +- {doc}`IsaacGym <../2-user_guide/3-backends/3-isaacgym>` +- {doc}`IsaacSim <../2-user_guide/3-backends/4-isaacsim>` ## 算法 Extras @@ -216,8 +216,8 @@ ROCm 配置档。`make sync-xpu` 会同步 scoped 后端依赖但不安装默认 ROCm 说明: -- `make sync-rocm` 要求 ROCm `>= 7.1`,并按仓库的 ROCm 依赖文件安装对应的 PyTorch - wheel。 +- `make sync-rocm` 从仓库配置的 `rocm7.2` 索引安装钉定的 `torch==2.14.0` + 和 `triton-rocm==3.8.0`。 - 它会把 `pyproject.rocm.toml` / `uv.rocm.lock` 激活为当前的 `pyproject.toml` / `uv.lock`,因此之后可以直接运行裸 `uv run ...`。 - 切回默认 CUDA / macOS 配置档时,运行 `git restore -- pyproject.toml uv.lock`,然 @@ -242,7 +242,7 @@ ROCm 说明: ```bash pip install torch==2.14.0 --index-url https://download.pytorch.org/whl/rocm7.2 - pip install unilab + pip install "unilab[unirl]" ``` Intel XPU 说明: diff --git a/docs/sphinx/source/zh_CN/1-getting_started/3-evaluation_and_playback.md b/docs/sphinx/source/zh_CN/1-getting_started/3-evaluation_and_playback.md index 2125ae388..d1c3a4e06 100644 --- a/docs/sphinx/source/zh_CN/1-getting_started/3-evaluation_and_playback.md +++ b/docs/sphinx/source/zh_CN/1-getting_started/3-evaluation_and_playback.md @@ -19,14 +19,14 @@ uv run demo dance 渲染模式: - `interactive` — 打开查看器窗口(macOS Motrix 上的默认值)。 -- `record` — 将 MP4 写入 `runs//playback/`。 +- `record` — 在所选 run 目录中写入 `play_video.mp4`。 - `viser` — 在基于浏览器的 viser viewer 中展示回放 (支持所有具备 physics-state playback 的后端:`mujoco`、`mjwarp`、`newton`、`drake`、`superdex`)。 - `none` — 跳过渲染,仅计算指标。 -当使用 `--sim mujoco --render-mode interactive` 时,`uv run eval` 会直接启动 -`play_interactive.py` MuJoCo viewer。该模式只 rollout 一个环境以保持相机和交互控制; -`training.play_env_num` 在此模式下会被忽略。 +当使用 `--sim mujoco` 或 `--sim mjwarp` 并指定 `--render-mode interactive` 时, +`uv run eval` 会直接启动 `play_interactive.py` MuJoCo viewer。该模式只 rollout +一个环境以保持相机和交互控制;`training.play_env_num` 在此模式下会被忽略。 当使用 `--sim mujoco` / `--sim mjwarp --render-mode viser` 时,`uv run eval` 改为启动 `play_viser.py`,在 `http://localhost:8080` 提供浏览器回放(可通过 `viser.*` @@ -44,8 +44,7 @@ uv run demo dance `src/unilab/scripts/play_interactive.py` 是通用 MuJoCo viewer 入口,适合 PPO、APPO、 SAC 和 FlashSAC 的策略可视化。它使用 `--algo / --task / --sim` -选择算法和 owner config;无论 `--sim` 选择 MuJoCo 还是 Motrix,窗口都使用 -`mujoco.viewer` 可视化,`--sim` 只决定读取哪份配置。 +选择算法和 owner config;窗口始终使用 `mujoco.viewer`,`--sim` 只决定读取哪份配置。 ```bash # 使用 owner config 中的 interactive.action_mode;全局默认是 zero action diff --git a/docs/sphinx/source/zh_CN/1-getting_started/4-project_structure.md b/docs/sphinx/source/zh_CN/1-getting_started/4-project_structure.md index 33c492cae..b61a77ab6 100644 --- a/docs/sphinx/source/zh_CN/1-getting_started/4-project_structure.md +++ b/docs/sphinx/source/zh_CN/1-getting_started/4-project_structure.md @@ -4,12 +4,13 @@ UniLab 将运行时 contract、配置、训练脚本和文档分置于不同的 | 路径 | Owner 角色 | | --- | --- | -| `scripts/` | 轻量的训练与工具入口。脚本负责组合 Hydra 配置并调用 owner 层代码。 | +| `scripts/` | 仓库级开发者、benchmark 与支持矩阵工具。 | +| `src/unilab/scripts/` | 由顶层 CLI 路由的随包训练与回放入口。 | | `src/unilab/conf/` | Hydra 根配置和任务 owner YAML。顶层 CLI 将后端选择暴露为 `--task` 加 `--sim`,然后组合出匹配的 owner YAML。 | | `src/unilab/base/` | Registry、env state、scene 以及 backend contract。 | | `src/unilab/envs/` | 任务 env 实现,以及任务专属的 reset、reward、observation 和 DR 逻辑。 | | `src/unilab/rl/algos/` | APPO 和 off-policy 算法代码。 | -| `src/unilab/rl/runtime/ipc/` | 共享内存与异步 runner 原语。 | +| `src/unilab/rl/runtime/` | 异步 runner、分布式启动、IPC 与 off-policy runtime 原语。 | | `src/unilab/rl/adapters/` | 直接集成 RSL-RL PPO 的适配层(VecEnv adapter 与分布式辅助)。 | | `src/unilab/training/` | 共享的训练辅助工具,用于日志、回放、种子处理和配置守卫(config guard)。 | | `src/unilab/visualization/` | 回放、渲染、NaN 检查以及 scene/export 工具。 | @@ -30,7 +31,7 @@ UniLab 将运行时 contract、配置、训练脚本和文档分置于不同的 ```bash uv run train --algo ppo --task go2_joystick_flat --sim mujoco -uv run train --algo ppo --task go2_joystick_flat --sim mujoco +uv run train --algo appo --task go2_joystick_flat --sim mujoco uv run train --algo sac --task g1_walk_flat --sim mujoco ``` diff --git a/docs/sphinx/source/zh_CN/1-getting_started/5-faq.md b/docs/sphinx/source/zh_CN/1-getting_started/5-faq.md index 7744883c9..3ef8c3113 100644 --- a/docs/sphinx/source/zh_CN/1-getting_started/5-faq.md +++ b/docs/sphinx/source/zh_CN/1-getting_started/5-faq.md @@ -34,9 +34,9 @@ C++17 工具链或 Python 开发头文件。uv 管理的 Python(`uv python ins ### 支持哪些平台和 Python 版本? Python `>=3.10,<3.14`(`pyproject.toml`),依赖解析覆盖 Linux x86_64、Linux -aarch64 与 Apple Silicon macOS;推荐解释器为 `3.13`。Windows 上 `mjbatch` -引擎没有 wheel,因此 MuJoCo 物理后端仅限 Linux/macOS。ROCm 与 Intel XPU 使用 -专用的 `make sync-rocm` / `make sync-xpu` profile。详见 {doc}`2-installation`。 +aarch64 与 Apple Silicon macOS;推荐解释器为 `3.13`。`mjbatch-uni` 提供 Windows +wheel,但 MuJoCo 物理后端尚未形成经过验证的 Windows 支持通道。ROCm 与 Intel XPU +使用专用的 `make sync-rocm` / `make sync-xpu` profile。详见 {doc}`2-installation`。 ### 资产或 checkpoint 下载失败 / Hugging Face 不可达 @@ -240,11 +240,13 @@ UniLab 的数据并行启动默认设置 `NCCL_P2P_DISABLE=1` 与 `NCCL_SHM_DISA Sharpa 灵巧手与 HORA 迁至 `sharpa_rl_unilab`;相关配置、资产与脚本已从本仓库 移除。版本说明见 {doc}`/changelog`。 -### `import uni_rl` 失败 / `unirl` extra 没有了 +### `import uni_rl` 失败 / `uni_rl` extra 没有了 unilab-rl 包已合并回本仓库的 `unilab.rl` -({doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`);RL 栈随基础安装提供, -旧 `uni_rl` extra 已移除——不要再传给 `uv sync` 或 `pip install`。导入映射见 +({doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`)。RL 代码随 package 提供, +但通过发布包训练仍需 `unirl` extra 中的依赖;源码 checkout 会通过 uv 默认的 +`rl` 依赖组安装这些依赖。旧 `uni_rl` extra 已移除——不要再传给 `uv sync` 或 +`pip install`。导入映射见 {doc}`../3-deployment/3-framework_migration/7-from_unilab_rl`。 ### v1.4 的 reset 代码在 `reset_mask` 上抛 `TypeError` diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/0-index.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/0-index.md index c6c2f2078..88aff631f 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/0-index.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/0-index.md @@ -51,10 +51,10 @@ TensorBoard、W&B、运行元数据以及 trace 选项。 :::: -## 什么时候下沉到 `scripts/train_*.py` +## 什么时候下沉到 `src/unilab/scripts/train_*.py` 日常运行应使用统一 CLI。只有在下面几种场景才直接使用底层 -`scripts/train_*.py` 入口: +`src/unilab/scripts/train_*.py` 入口: - 需要调试特定训练栈, - 需要直接观察 Hydra compose 行为,或 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/1-cli_reference.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/1-cli_reference.md index 47e2a9807..ebe86596a 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/1-cli_reference.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/1-cli_reference.md @@ -49,7 +49,7 @@ uv run uni-cumps doctor --gpus uv run uni-cumps start --gpus --name uv run uni-cumps env --name uv run uni-cumps stop --name # 或:stop --gpus -uv run uni-cumps stop --all # 停止当前用户所有已记录 daemon +uv run uni-cumps stop --all # 停止当前用户、当前主机的所有已记录 daemon ``` ownership、并发和拓扑限制见 tensor runtime 生产指南。训练仍必须显式设置 @@ -114,15 +114,17 @@ uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 \ --render-mode record ``` -支持的渲染模式为 `auto`、`interactive`、`record`、`viser` 和 `none`。其中 MuJoCo 交互模式 -(`--sim mujoco --render-mode interactive`)直接路由到 `play_interactive.py`,并始终只 -rollout 一个环境。 +支持的渲染模式为 `auto`、`interactive`、`record`、`viser` 和 `none`。MuJoCo 与 +MJWarp 的交互模式(`--sim mujoco` 或 `--sim mjwarp` 搭配 +`--render-mode interactive`)会直接路由到 `play_interactive.py`,并始终只 rollout +一个环境。 -具备 physics-state playback 的后端(`mujoco`、`mjwarp`、`newton`、`drake`、`superdex`) -还支持 `--render-mode viser`:通过基于浏览器的 viser viewer 展示回放,不需要本地显示, -在 macOS 上也不需要 `mjpython`。eval 会路由到独立的 `play_viser.py` viewer;train 则在 -训练后回放阶段运行同一 viewer。viser 是必选依赖;`viser.*` 配置组 -(`viser.port`、`viser.max_envs`、`viser.display_mode`、`viser.env_idx`)用于调整服务器与场景。 +对于声明 physics-state playback 能力的后端,`--render-mode viser` 通过基于浏览器的 +viser viewer 展示回放,不需要本地显示,在 macOS 上也不需要 `mjpython`。CLI 会拒绝 +Genesis 的该模式请求;其他后端仍须在运行时通过 playback 能力检查。eval 会路由到独立的 +`play_viser.py` viewer;train 则在训练后回放阶段运行同一 viewer。viser 是必选依赖; +`viser.*` 配置组(`viser.port`、`viser.max_envs`、`viser.display_mode`、 +`viser.env_idx`)用于调整服务器与场景。 ## 演示 @@ -131,10 +133,10 @@ uv run demo dance uv run demo dance --refresh --device cpu ``` -可用的 demo:`teaser`、`dance`。 -每个 demo 在首次运行时会从 `unilabsim/unilab-checkpoints` 这个 Hugging Face -数据集拉取预训练检查点,并缓存到 `src/unilab/assets/checkpoints//model_0.pt`。 -传入 `--refresh` 可重新下载。 +可用的 demo:`teaser`、`dance`。`dance` 在首次运行时会从 +`unilabsim/unilab-checkpoints` 这个 Hugging Face 数据集拉取预训练检查点,并缓存到 +`src/unilab/assets/checkpoints/dance/model_0.pt`;传入 `--refresh` 可重新下载。 +`teaser` 仅执行渲染,不使用预训练检查点。 中国大陆用户:当 `huggingface.co` 无法访问时,请在运行 demo 前切到社区镜像: diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/2-hydra_config.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/2-hydra_config.md index b38e460fa..ea4791fd4 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/2-hydra_config.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/2-hydra_config.md @@ -15,7 +15,7 @@ reward、scene 以及 task 专属运行时字段的身份标识。 ```bash uv run train --algo ppo --task go2_joystick_flat --sim mujoco -uv run train --algo ppo --task go2_joystick_flat --sim mujoco +uv run train --algo appo --task go2_joystick_flat --sim mujoco uv run train --algo sac --task g1_walk_flat --sim mujoco ``` diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/3-logging.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/3-logging.md index f97cd2413..dad819714 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/3-logging.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/3-logging.md @@ -31,8 +31,9 @@ uv run train --algo ppo --task go2_joystick_flat --sim mujoco | SAC | `logs/sac//` | `src/unilab/conf/sac/config.yaml` | | FlashSAC | `logs/flash_sac//` | `src/unilab/conf/flashsac/config.yaml` | -单个 run 目录名为 `YYYY-MM-DD_HH-MM-SS_`,例如 -`2026-03-09_18-30-00_mujoco`。常见产物包括 `run_config.json`、 +单 rank run 目录名为 `YYYY-MM-DD_HH-MM-SS_`,例如 +`2026-03-09_18-30-00_mujoco`;自动命名的多 rank run 还会追加 `_gpuxN`。 +常见产物包括 `run_config.json`、 `run_summary.json`、checkpoint,以及该 run 产生时的 `play_video.mp4`。 启用 W&B: @@ -44,22 +45,22 @@ uv run train --algo ppo --task go2_joystick_flat --sim mujoco \ ``` 共享配置字段包括 `training.wandb_project`、`training.wandb_entity`、 -`training.wandb_group`、`training.wandb_name`、`training.wandb_tags`、 -`training.wandb_notes` 和 `training.wandb_mode`。`ExperimentTracker` 会写 +`training.wandb_group`、`training.wandb_job_type`、`training.wandb_name`、 +`training.wandb_tags`、`training.wandb_notes` 和 `training.wandb_mode`。`ExperimentTracker` 会写 `run_config.json` 与 `run_summary.json`;RSL-RL PPO 在 W&B 模式下还会接管 RSL-RL writer。MuJoCo run 若产生 `play_video.mp4`,该视频会上传至 W&B。 ## Manager-Based reward 指标 Manager-Based 环境把结构化指标放在 `info["log"]` 中。reward 分项的路径因训练 -技术栈而异:off-policy run(SAC / FlashSAC / APPO)通过 `info["reward_components"]` -发布每个 term 的值并记录为 `reward/`;RSL-RL PPO 路径不发出分项 reward -key——其 TensorBoard 输出是原生聚合指标(`Loss/*`、`Perf/*`、`Policy/*`、 -`Train/*`)加 episode 级 UniLab key。reward 相关 key 的契约如下: +技术栈而异:SAC/FlashSAC off-policy run 通过 `info["reward_components"]` 发布每个 +term 的值并记录为 `reward/`;RSL-RL PPO 与当前 Manager-Based APPO 不发出 +分项 reward key。PPO 的 TensorBoard 输出是原生聚合指标(`Loss/*`、`Perf/*`、 +`Policy/*`、`Train/*`)加 episode 级 UniLab key。reward 相关 key 的契约如下: | Key | 归属 | 含义 | | --- | --- | --- | -| `reward/` | UniLab `RewardManager`,经 off-policy 日志栈 | 当前 reward 计算的分项诊断:`raw_value * weight` 在所有 env 上的平均值,不经过 `dt` 缩放。由 SAC / FlashSAC / APPO run 发出;PPO(rsl-rl)路径不发出 | +| `reward/` | UniLab `RewardManager`,经 off-policy 日志栈 | 当前 reward 计算的分项诊断:`raw_value * weight` 在所有 env 上的平均值,不经过 `dt` 缩放。由 SAC / FlashSAC run 发出;PPO 与当前 Manager-Based APPO 不发出 | | `Train/mean_reward` | RSL-RL PPO 原生 logger | 已完成 episode return 的聚合平均值;查看整体训练进度使用它 | | `Train/mean_episode_length` | RSL-RL PPO 原生 logger | 已完成 episode 长度的聚合平均值 | | `Episode_Termination/` | UniLab `TerminationManager` | 本次 reset 的 env 中触发该 termination term 的数量;这是独立诊断,不是 reward | @@ -140,9 +141,9 @@ APPO 出现。 ### 旧 run 的 tag 对照 -历史 TensorBoard event 不会被重写。unilab-rl 1.4.1 及以后的 run 使用下列 -canonical tag(权威定义:`unilab.rl.logging.metric_schema`,完整迁移表见原 unilab_rl -仓库的 `docs/metrics.md`);打开旧 run 时仍会看到已退役的旧名: +历史 TensorBoard event 不会被重写。最初由 unilab-rl 1.4.1 及以后版本生成的 run +使用下列 canonical tag(当前权威定义:`unilab.rl.logging.metric_schema`);打开旧 +run 时仍会看到已退役的旧名: | 旧 tag | 新 tag | 说明 | | --- | --- | --- | @@ -177,14 +178,14 @@ Metric 元数据与 runtime manifest 是两个独立版本命名空间。生产 | 命名空间 | 当前值 | 存储位置 | | --- | ---: | --- | | TensorBoard / W&B metric schema | `metric_schema_version = 1` | `run_summary.json` 顶层 | -| Runtime 进程 / 设备 / IPC manifest | `runtime_manifest.schema_version = 1` | 内嵌 runtime manifest | +| Runtime 进程 / 设备 / IPC manifest | `runtime_manifest.schema_version = 2` | 内嵌 runtime manifest | | 长时间 soak 监控 artifact | `schema_version = "0.3.0"` | soak JSON artifact | 三个值刻意相互独立:soak 监控 artifact 升级不代表 metric 语义变化,metric schema 升级也不会让所有 runtime-manifest 字段失效。当前 soak monitor 只接受 metric schema 1、 -runtime-manifest schema 1 与 soak artifact `0.3.0`。 +runtime-manifest schema 2 与 soak artifact `0.3.0`。 -Runtime-manifest v1 冻结 UniLab 已经消费的公开配置与生命周期字段:inference ring +Runtime-manifest v2 冻结 UniLab 已经消费的公开配置与生命周期字段:inference ring 容量、collector metric interval、`collector_backend_device`、inference-flight 计数、 replay-ingress 计数/耗时,以及存在该预算时的 CUDA inference IPC event 数。 `collector_backend_device` 在 completed manifest 中必填;只有 backend 本身不需要加速器 @@ -210,7 +211,7 @@ Soak artifact `0.3.0` 顶层新增两个异常 shutdown 字段。通过时 `shutdown` 在 producer 可用时保存原始 host-only `runtime_manifest.shutdown` mapping;teardown 无法生成诊断时为 `null`。 Producer shutdown snapshot 是 best-effort:它只追加到原始 soak failure -reason 之后,绝不替换原始错误。runtime-manifest v1 的 `shutdown` mapping +reason 之后,绝不替换原始错误。runtime-manifest v2 的 `shutdown` mapping 仍保持 opaque,因此该 soak artifact 契约不会把 producer 自有诊断扩展变成 稳定字段。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/4-tensor_runtime.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/4-tensor_runtime.md index d7940c6b6..d1041dd04 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/4-tensor_runtime.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/4-tensor_runtime.md @@ -6,25 +6,25 @@ SAC 与 FlashSAC 会在探测环境或构造 learner 之前解析所有面向进 边界的数据以及显存预算不可能满足的组合,都会在 collector 或 learner 进程 启动前失败。 -该契约只覆盖当前 scoped 单 GPU off-policy runtime;它不是自动调参器,也不 -提供多 GPU scaling。 +这些有边界的设置按 rank 解析。当前 scoped 显存预算与生产证据仅覆盖单 GPU; +SAC/FlashSAC 的数据并行设备放置见各算法页。 -## Owner 默认值与边界 +## 解析器默认值与边界 -| 设置 | 默认值 | 有效范围或约束 | +| 设置 | 未配置时的默认值 | 有效范围或约束 | | --- | ---: | --- | | `training.inference_slot_capacity` | `1` | 正整数,最大 `16` | | `training.collector_metrics_interval` | `1` | 正整数,最大 `10000` | | `training.replay_ingress_depth` | `2` | 正整数,最大 `16` | | `training.replay_ingress_slot_rows` | `null` | `1` 到 `algo.num_envs`;`null` 表示 `algo.num_envs` | -| `training.cuda_process_sharing` | `null` | `null` 或 device-resident CUDA 后端(`mjwarp`、`mtxwarp`)单 rank 显式 `mps` | +| `training.cuda_process_sharing` | `null` | `null` 或 device-resident CUDA 后端(`mjwarp`、`mtxwarp`)按 rank 显式 `mps` | | Learner 每次同步的行数 | `algo.batch_size * algo.updates_per_step` | 受 CUDA 显存预算约束 | 除 `training.cuda_process_sharing` 外,所有值必须是精确的正整数。布尔值、字符串、 浮点数、零和负数都会 fail closed。`training.cuda_process_sharing` 只接受 `null` -或显式字符串 `mps`。G1 Motion Tracking / MJWarp owner 仅有意将 -`collector_metrics_interval` 覆盖为 `100`;其他 tensor-runtime 默认值仍保持 -上表所示。 +或显式字符串 `mps`。仓库内置的 SAC 与 FlashSAC owner config 将 +`collector_metrics_interval` 设为 `32`,覆盖解析器回退值 `1`;G1 Motion Tracking / +MJWarp owner 将其设为 `100`。其他解析器默认值仍保持上表所示。 ## 设备语义与解析 @@ -133,7 +133,8 @@ Runtime manifest 记录审计 run 所需的有效证据: - `tensor_memory_budget` 记录 CUDA inference、replay storage、replay ingress、 learner batch 与 workspace 的组合预算计算。 - owner 显式请求 `mps` 时,`cuda_process_sharing` 记录已验证的 - execution-sharing 证据;默认 `null` 模式下该字段不存在。 + execution-sharing 证据。默认 `null` 模式仍会记录 best-effort 的环境级 host 状态, + 包括透明运行的环境级 daemon;详见 {doc}`7-tensor_runtime_production`。 预算决策在 spawn 前写入 manifest。如果不安全的组合被拒绝,错误会指出具体 设置,且相关进程不会被启动。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/5-resume_and_checkpoints.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/5-resume_and_checkpoints.md index ca4c22d05..e6a444155 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/5-resume_and_checkpoints.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/5-resume_and_checkpoints.md @@ -5,22 +5,28 @@ ## 续训 -PPO/APPO 直接通过 `algo.load_run` 续训。使用 run id,或用 `-1` 表示相关日志目录中最新的一次运行: +PPO 与 APPO 只有在 `algo.load_run` 显式选择非 `-1` 的值(通常是 run id)时才续训。 +默认的 `algo.load_run=-1` 表示不续训,而不是“从最新 run 续训”。例如: ```bash uv run train --algo ppo --task go2_joystick_flat --sim mujoco \ - algo.load_run=-1 \ + algo.load_run=2026-10-05_14-28-04_mujoco \ training.no_play=true ``` -off-policy 算法(SAC/FlashSAC/WarpSAC)的续训是显式开启的,以避免 +PPO 恢复 RSL-RL runner 状态,包括 logger 进度以及下文所述、受支持的环境 +training state。APPO 从自己的 checkpoint 格式恢复 actor、critic 与 optimizer, +随后用恢复后的 actor 重新同步 target actor,而不是恢复此前的 target actor +状态。它会从迭代 1 开始一个带全新日志进度的 run,不恢复 rollout ring、环境状态 +或 RNG 状态。 + +off-policy 算法(SAC/FlashSAC)的续训是显式开启的,以避免 `algo.load_run=-1` 的默认值把全新启动意外变成续训。设置 `algo.resume=true`,并用 `algo.load_run`(run id 或 `-1` 表示最新 run)与可选的 `algo.checkpoint` (迭代号或文件名;`-1` 表示最新 checkpoint)选择检查点: ```bash uv run train --algo flashsac --task g1_motion_tracking --sim mjwarp \ - --profile \ algo.resume=true \ algo.load_run=2026-10-05_14-28-04_mjwarp \ training.no_play=true @@ -33,11 +39,12 @@ off-policy checkpoint 恢复完整的 learner 状态(网络、优化器、调 ## 检查点格式支持边界 -PPO/APPO 续训加载的是 UniLab patch 过的 rsl-rl checkpoint。受支持的 checkpoint 必须 +PPO 续训加载的是 UniLab patch 过的 RSL-RL checkpoint。受支持的 PPO checkpoint 必须 携带 `unilab_logger_state`(logger 的 `tot_time` / `tot_timesteps` 计数器,必需), 并且当任务环境发布版本化 training state 时,还需携带对应的 `unilab_env_training_state`。自 resume-state patch(issue #441,v1.0.0 起发布)以来 -UniLab 一直写入这两个键,新保存的 checkpoint 保持不变。 +UniLab 一直写入这两个键,新保存的 checkpoint 保持不变。这些键及下面的 fail-closed +规则仅适用于 PPO,不适用于 APPO 的原生 checkpoint 格式。 从包含 issue #2416 的 1.3.5 之后的第一个 UniLab 版本起,加载改为 fail closed: diff --git a/docs/sphinx/source/zh_CN/2-user_guide/1-training/7-tensor_runtime_production.md b/docs/sphinx/source/zh_CN/2-user_guide/1-training/7-tensor_runtime_production.md index 886efeccf..01e50b451 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/1-training/7-tensor_runtime_production.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/1-training/7-tensor_runtime_production.md @@ -30,7 +30,8 @@ canonical 组合使用: uv run train --algo flashsac --task g1_motion_tracking --sim mjwarp ``` -MJWarp owner 继承 FlashSAC MuJoCo owner,并解析为: +MJWarp 与 MuJoCo 叶子分别继承同目录的 `base.yaml`;MJWarp 叶子再声明自身的 +backend 身份与指标间隔,并解析为: | 有效设置 | 值 | | --- | --- | @@ -45,11 +46,11 @@ MJWarp owner 继承 FlashSAC MuJoCo owner,并解析为: | Scene | `src/unilab/assets/robots/g1/scene_flat.xml` | | Motion | `motions/g1/dance1_subject2_part.npz` | -MuJoCo owner 使用同样的 2048 环境训练预算,但每步发布 collector metric。 -MJWarp owner 继承同样的 canonical DR(reset 模式模型字段随机化 + 线速度 -interval push),仅将角速度推扰收窄为零,因为其 selected-row tensor reset -不协商 interval angular root-velocity。Newton owner 不支持 reset 随机化, -将 canonical DR 显式置 `null`。 +MuJoCo owner 使用同样的 2048 环境训练预算,并采用根配置的默认 +`collector_metrics_interval: 32`。两个叶子都继承共享 base 的 reset 模式模型字段 +随机化。MuJoCo 保留六轴 interval `push_robot`,MJWarp 则将其置为 `null`,因为其 +selected-row tensor reset 不协商 interval root-velocity 能力。Newton owner 不支持 +reset 随机化,将 canonical DR 显式置 `null`。 在当前生成证据等级中,FlashSAC / `g1_motion_tracking` / MJWarp 是 `Configured`。本地 soak 成功不会自动把它提升为 `Benchmarked` 或 @@ -87,9 +88,9 @@ trainer 进程内所有 CUDA ordinal 都相对于该 mask。不要添加更多 execution-sharing 模式。它不是 backend 开关,也不替代 `--sim mjwarp` 或 owner YAML 选择。 -默认 `null` 表示 learner 与 collector 保持独立 CUDA context。初始支持拓扑为 -Linux、NVIDIA CUDA、单物理 GPU、MJWarp、SAC/FlashSAC 且 `world_size=1`。使用以下 -设置请求共享 GPU 执行: +默认 `null` 表示 learner 与 collector 保持独立 CUDA context。本指南的 canonical +拓扑为 Linux、NVIDIA CUDA、单物理 GPU、MJWarp、SAC/FlashSAC 且 `world_size=1`。 +校验按 rank 执行,也接受 MJWarp/MTXWarp 的 DP rank。使用以下设置请求共享 GPU 执行: ```bash training.cuda_process_sharing=mps @@ -194,11 +195,13 @@ selector 会解析成 canonical 物理 GPU UUID。MIG UUID 显式拒绝。逗号 server PID,以及 best-effort 的 learner/collector GPU UUID——当环境级 daemon 在 生效 control pipe 上应答时 `ambient_server=true`,使透明走 MPS 的 run 可以从自身 manifest 自证。ambient 观测永不 fail closed;无法解析的事实记录为 `null`。 -该 section 是 runtime-manifest v1 的 producer diagnostic,不是稳定标量契约。 +该 section 是 runtime-manifest v2 的 producer diagnostic,不是稳定标量契约。 MPS 只改变 GPU execution sharing,不改变 `env_steps_per_sync`、 -learner/collector placement 或训练语义。多 GPU DP 在独立的 gate 与 daemon 拓扑 -决策完成前保持不支持。CUDA MPS 仍依赖 host 与部署方式:在共享容器、多用户主机或 +learner/collector placement 或训练语义。多 GPU DP 中,每个 rank 都需要一个覆盖其 +GPU 的既有 daemon;`uni-cumps` 每次调用只接受一个 GPU selector,不会用一条命令 +provision DP daemon 拓扑。本指南不提供多 GPU MPS 生产配方。CUDA MPS 仍依赖 host 与 +部署方式:在共享容器、多用户主机或 受限 runner 中 control 可能不可用,显式请求会 fail closed 而不是静默降级。 无法使用 UniLab CLI 的受限部署仍可以用 `nvidia-cuda-mps-control` 手动运行既有 @@ -250,7 +253,7 @@ payload 形状: ``` 与 `runtime_manifest.cuda_process_sharing` 一样,该 section 是 -runtime-manifest v1 的 producer diagnostic,不是稳定标量契约;runtime +runtime-manifest v2 的 producer diagnostic,不是稳定标量契约;runtime manifest schema(`unilab.rl.logging.runtime_manifest_schema`) 在该 section 存在时会 fail-closed 校验。这些诊断 仅用于 observability:不改变 CUDA graph 启用策略,也不是验收 gate。它们是 @@ -332,7 +335,7 @@ run 目录必须包含: - soak monitor 消费的进度文件。 `run_summary.json` 必须携带 metric schema `1` 与内嵌 runtime-manifest -schema `1`。manifest 记录有效 runtime limits、发生预算决策时的 inference / +schema `2`。manifest 记录有效 runtime limits、发生预算决策时的 inference / tensor memory budget、collector/backend device、inference-flight 状态、 replay-ingress 状态、shutdown diagnostics,以及 backend tensor runtime 诊断 (`runtime_manifest.backend_diagnostics`;PPO run 以顶层 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/1-ppo.md b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/1-ppo.md index 14d4c1f7e..24683f119 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/1-ppo.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/1-ppo.md @@ -80,8 +80,8 @@ RSL-RL 启动后不会同步 observation normalizer buffer 或环境 curriculum 集成 launcher 只覆盖单机。仓库已有 `go2_joystick_flat` 与 `g1_motion_tracking` 的双卡 MuJoCo smoke;这不构成多机或 Motrix 多卡 support -声明。当前验证的 RTX 6000D 主机沿用 production NCCL 兼容默认值 -`NCCL_P2P_DISABLE=1`、`NCCL_SHM_DISABLE=1`,用户显式环境变量优先。 +声明。launcher 设置 NCCL 兼容默认值 `NCCL_P2P_DISABLE=1`、 +`NCCL_SHM_DISABLE=1`,用户显式环境变量优先。 ## 配置参考 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/2-appo.md b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/2-appo.md index f9f8f3959..d19499e57 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/2-appo.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/2-appo.md @@ -29,7 +29,9 @@ uv run eval --algo appo --task go2_joystick_flat --sim mujoco --load-run -1 ## 运行模型 -- collector 负责 CPU 仿真,learner 负责 GPU 训练。 +- collector 子进程推进所选 backend,并在 `training.collector_device` 上执行 + actor/critic 推理;`null` 跟随 learner device。backend 与 Manager tensor 的放置 + 单独解析,并不固定为 CPU 仿真。 - rollout 会先进入 replay queue,再由 learner 消费。 - APPO 内部带 V-trace importance-sampling 修正,更新语义不同于同步 PPO。 - collector / learner 流水线由一个 4 槽 ring buffer 支撑。 @@ -98,7 +100,7 @@ uv run train --algo appo --task go2_joystick_flat --sim mujoco \ | `algo.algorithm.enable_compile` | bool | true | learner 更新的 torch.compile;内置 `src/unilab/conf/appo/config.yaml` 出货为 `false` | | `algo.seed` | int | 1 | 随机种子 | | `training.collector_device` | str / null | null | collector 设备;null 跟随 learner | -| `training.replay_queue_size` | int / null | null | learner 侧 replay 缓存深度 | +| `training.replay_queue_size` | int / null | null | learner 侧 staging 深度;null 使用 runner 默认值 3(共享 rollout ring 另有 4 槽) | | `training.log_interval` | int | 1 | TensorBoard/W&B 标量上报间隔(迭代数) | ### 策略性能 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/3-sac.md b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/3-sac.md index 0f7050cf9..f48dd2b8d 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/3-sac.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/3-sac.md @@ -50,9 +50,10 @@ rank 子进程。启动时 rank 0 一次性广播 actor、critic、target critic 执行阻塞式 flat-gradient `all_reduce(SUM) / world_size`。各 rank 不交换 replay 数据, 在相同初值、平均梯度和更新顺序下各自维护一致的 optimizer 状态。 -每个 rank 当前只创建一个 collector。每个 rank 都是单卡可见,因此 probe env、 -collector 正式 env、replay、inference ring 与 learner 都落在同一张物理卡上。runtime manifest 的 `collector_backend_device` 记录本 rank 的 -实际绑定。 +每个 rank 当前只创建一个 collector。`algo.num_envs`、`algo.batch_size` 与 +`algo.updates_per_step` 都是每 rank 取值。每个 rank 都是单卡可见,因此 probe env、 +collector 正式 env、replay、inference ring 与 learner 都落在同一张物理卡上。 +runtime manifest 的 `collector_backend_device` 记录本 rank 的实际绑定。 off-policy 不再有设备字段,GPU 由进程可见性决定。单 rank 只需导出单卡可见; 多 rank 由父进程导出与 rank 数相同的 opaque 条目: @@ -80,16 +81,9 @@ MuJoCo worker 线程逐核绑定外,collector 进程及其已启动的本地 当前限制: -- 多卡 actor/critic optimizer CUDA Graph 支持捕获 NCCL gradient all-reduce。首次 capture - 前,DP owner 会先执行一次 eager all-reduce 并同步设备,完成 NCCL collective lazy - initialization;flat-gradient buffer 在 graph 生命周期内保持固定地址。runtime manifest - 记录 `dp_sync.cuda_graph_optimizer_capture=enabled_after_collective_warmup` 和 - `cuda_graph_collective_warmup=true`。销毁 process group 前会先释放 graph 中的 NCCL 节点。 - Issue #978 的验证环境为 PyTorch 2.7.0+cu128、CUDA 12.8、NCCL 2.26.2、2 × RTX - 6000D;TCP loopback 下同步 all-reduce 和 `async_op=True` + `Work.wait()` 均可 capture/replay, - 默认 stream 与 side stream 均通过;跳过 warmup 时首个 all-reduce 会在 capture 中报 - `operation not permitted when stream is capturing`。有限超时的最小复现见 - `scripts/benchmark/rl/reproduce_nccl_cuda_graph_capture.py`。 +- SAC 附加 DP 梯度同步时会离开 learner 自有的 whole-cycle CUDA Graph 路径; + DP 梯度平均仍在逐 update 路径执行。`algo.algo_params.use_compile=true` 不表示 + SAC DP 支持 whole-cycle 捕获。 - MuJoCo 有已提交的多卡 scaling benchmark;mjwarp 的 per-rank device placement 有 `tests/base/backend/test_process_device.py` 与 off-policy runner/worker 单测覆盖,但仓库中 尚无 mjwarp 多卡吞吐或收敛 benchmark。 @@ -119,17 +113,17 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ | Override key | 类型 | 默认值 | 实际影响 | | --- | --- | --- | --- | -| `algo.num_envs` | int | 4096 | 并行采集环境数 | -| `algo.batch_size` | int | 8192 | 每次 learner 更新的 batch | +| `algo.num_envs` | int | 4096 | 每 rank 的并行采集环境数 | +| `algo.batch_size` | int | 8192 | 每 rank 每次 learner 更新的 batch | | `algo.replay_buffer_n` | int | 512 | replay 容量(以整轮 env 向量为单位;行数 = n × num_envs) | -| `algo.updates_per_step` | int | 4 | 每个 env step 的 learner 更新数 | +| `algo.updates_per_step` | int | 4 | 每 rank 每个 env step 的 learner 更新数 | | `algo.learning_starts` | int | 1 | learner 开始更新前需采集的整轮 env 向量数 | -| `algo.policy_frequency` | int | 4 | 每 N 次 learner 更新做一次 actor/target 更新 | +| `algo.policy_frequency` | int | 4 | 每 N 次 learner 更新做一次 actor/温度更新;target critic 默认每次 learner 更新都更新 | | `algo.max_iterations` | int | 500 | 训练迭代数 | | `algo.save_interval` | int | 500 | checkpoint 保存间隔(迭代数) | -| `algo.algo_params.use_compile` | bool | true | learner 更新的 torch.compile | +| `algo.algo_params.use_compile` | bool | true | learner 更新的 torch.compile;NVIDIA CUDA 始终使用已验证的编译路径,`false` 仅在兼容层提供退出选项 | | `algo.seed` | int | 1 | 随机种子 | -| `training.use_amp` | bool | true | learner 更新路径上的 bf16 autocast | +| `training.use_amp` | bool | true | 启用设备支持的 AMP;dtype 与设备门控由 `algo.algo_params.amp_dtype` 决定 | | `training.log_interval` | int | 1 | TensorBoard/W&B 标量上报间隔(迭代数) | ### 策略性能 @@ -149,7 +143,7 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.alpha_init` | float | 0.01 | 初始熵温度 | | `algo.algo_params.target_entropy_ratio` | float | 0.0 | 目标熵 = −action_dim × 该比例(0.0 → 目标为 0) | | `algo.algo_params.max_grad_norm` | float | 0.0 | 梯度范数裁剪;0 表示不裁剪 | -| `algo.algo_params.amp_dtype` | str | auto | `training.use_amp` 下的 AMP dtype | +| `algo.algo_params.amp_dtype` | str | auto | AMP dtype:`auto` 在 CUDA 上选择 bf16;Apple MPS 必须显式选择 `bf16` 并通过运行时能力探测(auto 在 MPS 上关闭 AMP)。CUDA `fp16` 使用 GradScaler,与 whole-cycle graph 不兼容 | ### 训练运行(`training:` 段) @@ -159,7 +153,8 @@ uv run train --algo sac --task g1_walk_flat --sim mujoco \ | `training.play_only` | bool | false | 跳过训练,只回放已有 checkpoint | | `training.export_onnx` | bool | true | 回放时导出 `policy.onnx` | | `training.cuda_process_sharing` | str / null | null | null = 独立 CUDA context;`mps` 请求 CUDA MPS(守护进程由用户经 `uni-cumps` 管理) | -| `training.dp_gradient_wire_dtype` | str | float32 | 多卡梯度平均的传输 dtype;`bfloat16` 会压缩 | +| `training.dp_gradient_wire_dtype` | str | float32 | 多卡梯度传输 dtype;`bfloat16` 仅压缩至少含 1024 个元素的 FP32 组,平均前恢复 FP32,且独立于 AMP 改变数值精度 | +| `training.replay_storage_dtype` | str | float16 | 设备 replay 存储:`float16` 量化 obs/action/critic 列,rewards/dones/truncated 保持 FP32,采样 batch 上转 FP32;`float32` 保留完整 FP32 ring | | `training.nan_guard.enabled` | bool | true | 检测非有限张量并转储诊断信息 | | `training.nan_guard.check_interval` | int | 32 | NaN 检查之间的 env step 数 | | `env.finite_validation_interval` | int | 32 | 每个批量有限性检查轮询周期的步数(env 持有的校验严格度) | diff --git a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md index 0ec1e2519..88f67a7da 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/2-algorithms/4-flash_sac.md @@ -39,6 +39,9 @@ uv run train --algo flashsac --task go2_joystick_flat --sim mujoco training.no_p - `algo.algo_params.use_whole_cycle_cuda_graph` 控制 learner 自己捕获并回放整轮 CUDA Graph。只把此字段设为 `false`,可以保留 Inductor 编译而关闭整轮捕获。 +通过 `algo.algo_params.actor_config` 注入的自定义 actor 不支持 whole-cycle 捕获; +使用该配置时必须设置 `use_whole_cycle_cuda_graph=false`。 + 例如,使用 eager 调试路径: ```bash @@ -69,8 +72,9 @@ actor 一律不再支持,包括内置 actor:加载会 fail closed,错误 FlashSAC 与 SAC 共用同一套多卡数据并行机制:`CUDA_VISIBLE_DEVICES` 下每个 rank 各跑一 套独立的 learner+collector;启动时广播完整模型状态,稳态在每个实际 optimizer step -前分别平均 actor / critic / temperature 梯度。仅 rank 0 保存 checkpoint。用法与限制见 -{doc}`/zh_CN/2-user_guide/2-algorithms/3-sac` 的"多卡数据并行"小节。 +前分别平均 actor / critic / temperature 梯度。仅 rank 0 保存 checkpoint。启动、日志、 +checkpoint、CPU 亲和与 backend 放置见 +{doc}`/zh_CN/2-user_guide/2-algorithms/3-sac` 的“多卡数据并行”小节。 ```bash export CUDA_VISIBLE_DEVICES=, @@ -78,6 +82,20 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ training.no_play=true ``` +与 SAC 不同,FlashSAC owner YAML 默认启用 DP whole-cycle CUDA Graph。 +`algo.algo_params.dp_whole_cycle_cuda_graph=false` 只关闭 DP rank 的捕获; +`algo.algo_params.use_whole_cycle_cuda_graph=false` 则关闭所有 rank 的捕获。 +启用 DP 捕获时,capture failure 会直接抛出,不允许各 rank 分别回退 eager 而导致 +collective 失步。runner 会在关闭 process group 前释放已捕获的 graph。 + +首次 capture 前,DP synchronizer 会执行一次 eager all-reduce 并同步设备,以完成 +NCCL collective 初始化。issue #978 的历史验证环境为 PyTorch 2.7.0+cu128、CUDA 12.8、 +NCCL 2.26.2、2 × RTX 6000D;TCP loopback 下同步 all-reduce 和 `async_op=True` + +`Work.wait()` 均可 capture/replay,默认 stream 与 side stream 均通过;跳过 warmup 时 +首个 all-reduce 会在 capture 中报 `operation not permitted when stream is capturing`。 +有限超时的最小复现见 `scripts/benchmark/rl/reproduce_nccl_cuda_graph_capture.py`。 +这些是历史验证证据,不是当前主机的吞吐声明。 + ## 配置参考 默认值以 `src/unilab/structured_configs.py` 中的类型化配置(`FlashSACConfig`)为准; @@ -94,10 +112,10 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | Override key | 类型 | 默认值 | 实际影响 | | --- | --- | --- | --- | -| `algo.num_envs` | int | 1024 | 并行采集环境数 | -| `algo.batch_size` | int | 2048 | 每次 learner 更新的 batch | +| `algo.num_envs` | int | 1024 | 每 rank 的并行采集环境数 | +| `algo.batch_size` | int | 2048 | 每 rank 每次 learner 更新的 batch | | `algo.replay_buffer_n` | int | 512 | replay 容量(以整轮 env 向量为单位;行数 = n × num_envs) | -| `algo.updates_per_step` | int | 2 | 每个 env step 的 learner 更新数 | +| `algo.updates_per_step` | int | 2 | 每 rank 每个 env step 的 learner 更新数 | | `algo.learning_starts` | int | 98 | learner 开始更新前需采集的整轮 env 向量数 | | `algo.policy_frequency` | int | 2 | 每 N 次 learner 更新做一次 actor/温度更新 | | `algo.max_iterations` | int | 5000 | 训练迭代数 | @@ -107,7 +125,7 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.use_whole_cycle_cuda_graph` | bool | true | learner 侧整轮 CUDA Graph 捕获 | | `algo.algo_params.dp_whole_cycle_cuda_graph` | bool | true | 数据并行路径上的整轮捕获;`false` 只关闭 DP 捕获(该字段设于 `config.yaml`) | | `algo.seed` | int | 1 | 随机种子 | -| `training.use_amp` | bool | true | learner 更新路径上的 bf16 autocast | +| `training.use_amp` | bool | true | 启用设备支持的 AMP;dtype 与设备门控由 `algo.algo_params.amp_dtype` 决定 | | `training.log_interval` | int | 1 | TensorBoard/W&B 标量上报间隔(迭代数) | ### 策略性能 @@ -142,7 +160,7 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `algo.algo_params.learning_rate_warmup_steps` | int | 0 | 从起始值到峰值的 warmup 步数 | | `algo.algo_params.learning_rate_decay_steps` | int | 500000 | 从峰值到结束值的衰减步数 | | `algo.algo_params.n_step` | int | 1 | N-step 回报长度;当前仅支持 1 | -| `algo.algo_params.amp_dtype` | str | auto | `training.use_amp` 下的 AMP dtype | +| `algo.algo_params.amp_dtype` | str | auto | AMP dtype:`auto` 在 CUDA 上选择 bf16;Apple MPS 必须显式选择 `bf16` 并通过运行时能力探测(auto 在 MPS 上关闭 AMP)。CUDA `fp16` 使用 GradScaler,与 whole-cycle graph 不兼容 | ### 训练运行(`training:` 段) @@ -152,7 +170,8 @@ uv run train --algo flashsac --task g1_walk_flat --sim mujoco \ | `training.play_only` | bool | false | 跳过训练,只回放已有 checkpoint | | `training.export_onnx` | bool | true | 回放时导出 `policy.onnx` | | `training.cuda_process_sharing` | str / null | null | null = 独立 CUDA context;`mps` 请求 CUDA MPS(守护进程由用户经 `uni-cumps` 管理) | -| `training.dp_gradient_wire_dtype` | str | float32 | 多卡梯度平均的传输 dtype;`bfloat16` 会压缩 | +| `training.dp_gradient_wire_dtype` | str | float32 | 多卡梯度传输 dtype;`bfloat16` 仅压缩至少含 1024 个元素的 FP32 组,平均前恢复 FP32,且独立于 AMP 改变数值精度 | +| `training.replay_storage_dtype` | str | float16 | 设备 replay 存储:`float16` 量化 obs/action/critic 列,rewards/dones/truncated 保持 FP32,采样 batch 上转 FP32;`float32` 保留完整 FP32 ring | | `training.nan_guard.enabled` | bool | true | 检测非有限张量并转储诊断信息 | | `training.nan_guard.check_interval` | int | 32 | NaN 检查之间的 env step 数 | | `env.finite_validation_interval` | int | 32 | 每个批量有限性检查轮询周期的步数(env 持有的校验严格度) | diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/0-index.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/0-index.md index 99f778eec..a1f661e4b 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/0-index.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/0-index.md @@ -8,14 +8,17 @@ task owner YAML;不要单独覆盖 `training.sim_backend`。 ## Runtime 前置条件 - 任何使用 `--sim mujoco`、MuJoCo 回放或 MuJoCo 专属调试工具的运行,都需要 - `mujoco` extra 及其钉住的 `mjbatch` runtime。 -- MJWarp 需要 `mjwarp` extra、NVIDIA CUDA;多 GPU 主机必须显式配置 - process-device topology。 -- Genesis 需要 `genesis` extra 以及已验证的 Linux x86_64 GPU 路径。 + Python 3.11–3.13、`mujoco` extra 及其钉住的 `mjbatch` runtime。该 extra 在 + Python 3.10 上为空,后端会 fail closed。 +- MJWarp 需要 Python 3.11–3.13、`mjwarp` extra 和 NVIDIA CUDA;多 GPU 主机必须 + 显式配置 process-device topology。 +- Genesis 需要 `genesis` extra 和受支持的 Linux GPU runtime:NVIDIA CUDA 搭配 + `gs.cuda`,或 ROCm/HIP 搭配 `gs.amdgpu`。 - Newton 需要 `newton` extra 与 NVIDIA CUDA 设备;当前 tensor-native 支持范围 为 SAC `g1_walk_flat` 和 FlashSAC `g1_motion_tracking`。 -- Motrix 需要 `motrix` extra,提供 CPU-authoritative packed HOST_BRIDGE;当前 - canonical 支持范围为 SAC `g1_walk_flat` 和 FlashSAC `g1_motion_tracking`。 +- Motrix 需要 `motrix` extra,提供 CPU-authoritative packed HOST_BRIDGE。已配置的 + owner 包括 `go2_joystick_flat`(PPO/APPO)、`g1_walk_flat` + (PPO/SAC/FlashSAC)和 `g1_motion_tracking`(PPO/APPO/SAC/FlashSAC)。 - Motrix Warp 需要 `mtxwarp` extra,在 NVIDIA CUDA 上运行物理仿真和 Manager 张量;当前 canonical 支持范围为 FlashSAC `g1_motion_tracking`。 - SuperDex 在 CPython 3.12/3.13 Linux x86_64 上需要 `superdex` extra,提供 @@ -31,9 +34,9 @@ task owner YAML;不要单独覆盖 `training.sim_backend`。 | 后端 | 操作系统 | GPU | | --- | --- | --- | -| MuJoCo | Linux / macOS / Windows | 不要求:CPU physics;离线回放可在 CPU 渲染 | +| MuJoCo | Linux / macOS / Windows(Windows 未经 CI 验证) | 不要求:CPU physics;离线回放可在 CPU 渲染 | | MJWarp | Linux(已验证路径) | 要求:NVIDIA CUDA;单 GPU 主机默认使用当前 CUDA 设备 | -| Genesis | Linux x86_64 | 要求:NVIDIA GPU 与 driver;仅验证 `gs.gpu` channel | +| Genesis | Linux | 要求:NVIDIA CUDA 搭配 `gs.cuda`,或 ROCm/HIP 搭配 `gs.amdgpu`;不支持 CPU、MPS、Metal | | Newton | Linux | 要求:NVIDIA CUDA;selected-reset 通道为 device-resident | | Motrix | Linux / macOS / Windows | CPU-authoritative physics;Torch CUDA buffer 可选 | | Motrix Warp | Linux x86_64 | 要求 NVIDIA CUDA,状态和重置张量驻留设备 | @@ -56,7 +59,7 @@ UniLab 通过 task owner config 选择仿真后端。常规用法通过 `--task` | --- | --- | | 默认路径或 owner 覆盖最广 | MuJoCo | | `scripts/play_viser.py` 等 MuJoCo 专属工具 | MuJoCo | -| Device-resident tensor owner | MJWarp、Genesis 或 Newton,且支持矩阵标记该组合为 supported | +| Device-resident tensor owner | MJWarp、Genesis、Newton 或 Motrix Warp,具体组合以任务支持矩阵为准 | | CPU-authoritative packed HOST_BRIDGE | Motrix;SuperDex 或 scoped Drake 的 configured research owner | 支持矩阵由 registry、owner YAML 与测试生成;当前证据源见 @@ -108,17 +111,19 @@ uv sync --extra mujoco uv run python -c "import unisim; print(unisim.ADAPTER_SPECS)" ``` -`unisim` 不依赖 UniLab、Hydra 或训练组件。scoped -MuJoCo/MJWarp/Genesis/Newton/Motrix/SuperDex 适配器与暂时搁置的适配器使用同一个 -public contract。缺失 proprietary SDK 或 GPU worker 时会产生明确的 -cold-path diagnostic;不会静默切换到另一个引擎。 +`unisim` 不依赖 UniLab、Hydra 或训练组件。所有 UniSim 适配器使用同一个 public +contract。缺失 proprietary SDK 或 GPU worker 时会产生明确的 cold-path diagnostic; +不会静默切换到另一个引擎。 ```{toctree} :hidden: 1-mujoco +2-motrix +3-isaacgym +4-isaacsim 5-genesis +6-drake 7-newton -2-motrix 8-superdex ``` diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/1-mujoco.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/1-mujoco.md index 0001dde64..e3d0ca064 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/1-mujoco.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/1-mujoco.md @@ -3,7 +3,8 @@ MuJoCo 是已提交 owner 配置中的默认后端路径。在 Python 3.11 及更高版本上, `mujoco` extra 安装官方 `mujoco` 包(`~=4.0.1`)和发布版 `mjbatch-uni==0.3.3` 原生 batch 引擎,精确版本由已提交的 `uv.lock` 钉住。 -适配层位于 `unisim.backend.mujoco` 下。 +Python 3.10 不是受支持的后端路径:依赖 marker 会使 extra 为空,运行时会 fail +closed。适配层位于 `unisim.backend.mujoco` 下。 ## 何时使用 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/2-motrix.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/2-motrix.md index dba0d6304..86adb2f59 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/2-motrix.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/2-motrix.md @@ -28,8 +28,9 @@ Motrix 是一个可选后端,通过 `motrix` extra 安装。该 extra 委托 `unisim-core[motrix]`,runtime 版本固定在 UniSim 的 `pyproject.toml` 中,适配层位于 `unisim.backend.motrix` 下。 -Motrix 是 CPU-authoritative packed HOST_BRIDGE 后端。issue #2054 将其恢复 -进 tensor-only Manager runtime,当前包含这些 canonical workload: +Motrix 是 CPU-authoritative packed HOST_BRIDGE 后端。已配置的 owner 包括 +`go2_joystick_flat`(PPO/APPO)、`g1_walk_flat`(PPO/SAC/FlashSAC)和 +`g1_motion_tracking`(PPO/APPO/SAC/FlashSAC)。示例命令: ```bash uv run --extra motrix train --algo appo --task go2_joystick_flat --sim motrix @@ -37,9 +38,8 @@ uv run --extra motrix train --algo sac --task g1_walk_flat --sim motrix uv run --extra motrix train --algo flashsac --task g1_motion_tracking --sim motrix ``` -其他 Motrix owner 仍不在支持范围内,也不构成生产支持声明。 -Go2 APPO owner 是已恢复的 configured 训练路径;当前证据仅限 bounded smoke -training,不构成性能 benchmark。 +各 algorithm/task 组合的证据等级以生成的支持矩阵为准。Go2 APPO owner 的当前证据 +仅限 bounded smoke training,不构成性能 benchmark。 public tensor lifecycle 提供: diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/3-isaacgym.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/3-isaacgym.md index f593f1601..2d893dae6 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/3-isaacgym.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/3-isaacgym.md @@ -102,25 +102,21 @@ uv run --no-project "$UNILAB_BENCHMARK_HSGYM_PYTHON" \ 安装好外部环境后即可训练。worker 运行时默认从 `~/.cache/unisim/isaacgym` 自动 发现;自定义安装根时在训练前导出 `UNISIM_ISAACGYM_HOME` 即可。当前 -`g1_walk_flat` 提供 PPO 与 SAC 的 isaacgym owner 配置: +`g1_walk_flat` 仅提供 SAC 的 isaacgym owner 配置: ```bash -# SAC -uv run train --algo sac --task g1_walk_flat --sim isaacgym - -# PPO uv run train --algo sac --task g1_walk_flat --sim isaacgym ``` 回放渲染由 IsaacGym 原生提供:交互模式在 worker 进程里打开 gym viewer, 录制模式用 camera sensor 离屏渲染并写出 `play_video.mp4`(相机跟踪 env 0 的 root,视角可用 `training.cam_distance` / `cam_elevation` / -`cam_azimuth` 调整)。`play_render_mode=auto`(默认)在有显示器 -(`DISPLAY`/`WAYLAND_DISPLAY`)时进入交互模式,无显示器的机器自动降级为 -录制模式;录制需要有限的 `training.play_steps`(默认配置已给出)。 +`cam_azimuth` 调整)。owner 设置 `training.play_render_mode: record`;显式选择 +`auto` 时,有显示器(`DISPLAY`/`WAYLAND_DISPLAY`)则进入交互模式,无显示器则 +回退到录制模式。录制需要有限的 `training.play_steps`(默认配置已给出)。 ```bash -# 训练后自动进入回放(auto);无显示器的服务器自动录视频 +# 训练后自动进入回放;owner 默认录制视频 uv run train --algo sac --task g1_walk_flat --sim isaacgym # 对已训练的 checkpoint 做评估:交互 viewer diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/4-isaacsim.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/4-isaacsim.md index c5c420a39..418d2b39a 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/4-isaacsim.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/4-isaacsim.md @@ -9,7 +9,8 @@ UniLab 的 `isaacsim` 后端在独立的 Python 3.11 worker 进程中运行 Isaa 5.1.0 和 IsaacLab v2.3.0。管道传输生命周期 metadata,canonical qpos/qvel/control/reset arena 通过同 GPU CUDA IPC 传输。当前恢复边界是使用 mapped entity scene 的 headless SAC `g1_walk_flat` training。原生 -interactive/record playback 仍是独立后续项,不属于本次训练支持声明。 +interactive/record 渲染协议已经实现,但已记录的真机 playback 尝试都在 renderer +初始化前受阻,不属于本次训练支持声明。 ## 运行时边界 @@ -48,10 +49,12 @@ mapped scene 使用 backend 默认 2 m 的网格克隆间距。可在 env 创建 两倍的间距,避免相邻 clone 重叠。IsaacSim 会把生效间距和 environment origin 回报给 host,host 检测到不一致时拒绝启动。 -当前 worker 支持 MJCF 材质化、批量 articulation 状态、位置 target 步进和 -masked root/joint reset,以及 Kit 原生 viewer 和 headless IsaacLab RGB camera。 -contact-force sensor、reset/interval domain randomization 和 host pre-step -callback 仍不支持,并会 fail closed。 +当前 worker 支持 MJCF 材质化、批量 articulation 状态、位置 target 步进、 +masked root/joint reset、mapped-scene 接触传感器,以及 Kit 原生 viewer 和 +headless IsaacLab RGB camera。mapped scene 还声明了部分 reset domain +randomization 与 interval body-force/body-torque randomization。当前 G1 owner +仍禁用 PD-gain reset randomization,host pre-step callback 仍不支持;未支持的 +term 会 fail closed。 使用顶层 CLI 选择 backend 和 owner: @@ -64,9 +67,9 @@ uv run eval --algo sac --task g1_walk_flat --sim isaacsim \ --load-run --render-mode interactive training.play_env_num=1 ``` -`record` 会在所选 run 目录写入 `play_video.mp4`。这些命令需要外部运行时和 -NVIDIA CUDA 设备。仓库已有上方的 headless SAC training 完整运行记录;原生 -playback 仍是独立验证,当前不声称稳定可用。 +`record` 协议的目标是在所选 run 目录写入 `play_video.mp4`。这些命令需要外部 +运行时和 NVIDIA CUDA 设备。仓库已有上方的 headless SAC training 完整运行记录; +已记录的真机 playback 尝试在 renderer 初始化前失败,当前不声称稳定可用。 ## Training Validation @@ -133,7 +136,7 @@ uv run --active --no-project \ | 渲染启动 | `AppLauncher` 冷路径模式选择 | mock worker 验证 none/record/interactive mode、尺寸和 graphics 握手 | env 材质化后不能切换 mode | | 离线 RGB | IsaacLab `Camera` + `CameraCfg` | 协议测试验证视频写入,并拒绝错误 shape、dtype 或均匀帧;当前真实主机在 camera 创建前崩溃 | 要求有限步数;真实 playback 成功前 renderer/playback 声明不提升 | | 交互窗口 | 非 headless Kit + `SimulationContext.set_camera_view` | 协议测试驱动一帧并将关闭窗口映射为 `RenderClosedError`;当前主机没有成功的有界 GUI 证据 | 显式 interactive 需要 display;无 display 时 `auto` 回退到 record | -| Domain randomization | IsaacLab manager/event API | 未探测 | 非空不支持 plan 必须 fail-closed | +| Domain randomization | mapped-scene 属性与 wrench 写入 | host 测试覆盖已声明的 reset 子集和 interval body force/torque;G1 owner 禁用 PD-gain reset DR | shared friction material 禁用 geom-friction DR;host pre-step callback 与未支持 term 会 fail closed | Importer 返回的 joint/body 顺序与 MJCF 文档顺序不同(例如左右分支交错)。 worker 建立 name-to-index 映射并重排所有状态和控制数组;按位置假设顺序会 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/5-genesis.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/5-genesis.md index ccceff3a8..b0958a6dc 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/5-genesis.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/5-genesis.md @@ -6,19 +6,21 @@ NumPy contract,物理与 learner 同进程运行——没有 worker 子进程,也没有 IPC。 -当前状态:`GenesisBackend` 已实现并注册到 registry;`g1_walk_flat` 提供 -PPO 与 SAC owner 配置(`src/unilab/conf/{ppo,sac}/task/g1_walk_flat/genesis.yaml`), -跨后端契约审计(`scripts/audit_sim2sim_contracts.py`)在两棵 algo 树上 +当前状态:`GenesisBackend` 已实现并注册到 registry。`g1_walk_flat` 提供 PPO +与 SAC owner,`g1_motion_tracking` 提供 SAC 与 FlashSAC owner +(`src/unilab/conf/{ppo,sac}/task/g1_walk_flat/genesis.yaml`、 +`src/unilab/conf/{sac,flashsac}/task/g1_motion_tracking/genesis.yaml`)。跨后端 +契约审计(`scripts/audit_sim2sim_contracts.py`)在两棵 `g1_walk_flat` algo 树上 覆盖 mujoco↔genesis(结论 TRANSFERABLE)。支持等级为 **experimental**。 现有证据:registry + owner YAML + compose/contract 覆盖,以及真机 slow-lane env smoke (`tests/envs/locomotion/g1/test_g1_owner_contract.py`:compose → env 构造 → keyframe reset → 12 步有限稳定 → cleanup,覆盖 ppo 与 sac -两棵树)。SAC cell 标记为 `Tested`——真机完整训练验证(2026-08-31, -RTX 4090 / torch 2.8.0+cu128 / genesis-world 1.3.3:5000/5000 +两棵树)。SAC `g1_walk_flat` cell 标记为 `Tested`——真机完整训练验证 +(2026-08-31,RTX 4090 / torch 2.8.0+cu128 / genesis-world 1.3.3:5000/5000 iterations,reward/mean 6.5 → 244.8,episode length → 987/1000, -10.26M env steps / 224s wall time)加最终 checkpoint 的 record -playback 验证;PPO cell 保持 `Configured`(尚无训练验证)。 +10.26M env steps / 224s wall time)加最终 checkpoint 的 record playback 验证。 +PPO walk 与 SAC/FlashSAC motion owner 保持 `Configured`,没有同等的完整训练证据。 env 构造生命周期(#1383 已修复):`ManagerBasedRlEnv` 构造期的 entity 校验在 env 的 `materialize()` 钩子之前读取状态 getter,因此 adapter 的 @@ -66,9 +68,6 @@ materialize 冷路径补偿——热路径从不解析 XML: UniSim Genesis adapter tensor 生命周期之外。ROCm 上的 `gs.cuda` 与非 HIP CUDA 上的 `gs.amdgpu` 都因 runtime 不匹配而被拒绝;CPU、portable Genesis、 Metal、MPS 或替代后端不会成为静默 fallback。 -- 仓库钉定的 torch 窗口(x86_64 上为 torch 2.8):探针中 - IMUSensor + contact-force 传感器组合在 torch 2.7 下崩溃(REPORT - §3.4/§8)。 - 安装可选 extra(精确钉定 `genesis-world==1.3.3`): ```bash @@ -77,8 +76,9 @@ uv sync --extra genesis ## 训练与评估 -训练通过标准 CLI 选择 genesis owner(owner YAML compose、registry -路由与 env 构造链路已在真机 slow-lane smoke 覆盖;尚无训练收敛证据): +训练通过标准 CLI 选择 genesis owner。owner YAML compose、registry 路由与 env +构造链路已在真机 slow-lane smoke 覆盖。只有 SAC `g1_walk_flat` 具有上述完整 +运行验证;其他 configured owner 没有同等的收敛证据: ```bash # PPO diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/6-drake.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/6-drake.md index f1ddda201..b3059e78c 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/6-drake.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/6-drake.md @@ -1,8 +1,7 @@ # Drake 后端 > **Scoped runtime 支持。** Drake 当前只有一个 Manager-runtime owner:PPO -> `go2_joystick_flat`。本页不构成更广泛的生产支持声明;任务支持范围以生成的 -> 支持矩阵为准。 +> `go2_joystick_flat`。任务支持范围以生成的支持矩阵为准。 Drake 是实验性的 CPU 批量物理后端;task、reward、observation 和训练循环仍由 @@ -48,8 +47,9 @@ make setup-drake make setup-drake DRAKE_HOME=/path/to/drake ``` -前缀必须包含 `include/drake/`、`include/pybind11/` 和 `lib/libdrake.so`。macOS -下脚本会自动发现 Homebrew `fmt`,并把 gcc 库目录加入 `DYLD_LIBRARY_PATH`。 +前缀必须包含 `include/drake/`、`include/pybind11/`,以及 Linux 的 +`lib/libdrake.so` 或 macOS 的 `lib/libdrake.dylib`。macOS 下脚本会自动发现 +Homebrew `fmt`,并把 gcc 库目录加入 `DYLD_LIBRARY_PATH`。 脚本结束时会打印后续 shell 需要的环境变量。Apple Silicon macOS 通常为: diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/7-newton.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/7-newton.md index a1d6ee0a6..46963fea8 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/7-newton.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/7-newton.md @@ -17,7 +17,7 @@ uv run train --algo flashsac --task g1_motion_tracking --sim newton owner 配置为 `src/unilab/conf/sac/task/g1_walk_flat/newton.yaml` 与 `src/unilab/conf/flashsac/task/g1_motion_tracking/newton.yaml`。其他 -Newton owner 仍不在支持范围内,也不构成生产支持声明。public tensor lane +Newton owner 仍不在支持范围内。public tensor lane 提供 device-resident state views、frame/contact sensors、state widths、 tensor stepping 与 authoritative selected-reset publication。Newton 也是 Manager 批量 body-pair contact 读取的数值验收 backend:scene read plan 冷绑定 @@ -33,8 +33,8 @@ Newton。 ## 安装 -Newton 运行时是 optional extra,钉定 Newton 1.5.1 与 -MuJoCo-Warp 3.11 / Warp 1.16 系列: +Newton 运行时是 optional extra,钉定 Newton 1.5.1 与 MuJoCo-Warp 3.11,并要求 +Warp >=1.16(lockfile 中为 1.17.0): ```bash # 源码 checkout: @@ -44,9 +44,10 @@ uv sync --extra newton pip install "unilab[newton]" ``` -该 extra 精确钉定 `newton==1.5.1`、`mujoco-warp==3.11.0`、 -`mujoco==3.11.0`、`warp-lang==1.16.0`,并包含原生 ViewerGL 依赖 -(`pyglet>=2.1.6,<3`、`imgui-bundle>=1.92.0`)。`mujoco` 和 `mjwarp` extra +该 extra 精确钉定 `newton==1.5.1`、`mujoco-warp==3.11.0` 和 +`mujoco==3.11.0`,要求 `warp-lang>=1.16.0`(`uv.lock` 解析为 1.17.0),并包含 +原生 ViewerGL 依赖(`pyglet>=2.1.6,<3`、`imgui-bundle>=1.92.0`)。`mujoco` 和 +`mjwarp` extra 现使用 MuJoCo 4.0.1 版本线,依赖解析声明与 `newton` 明确互斥。请在独立环境 中安装 Newton,不要与 `mujoco` 或 `mjwarp` extra 组合安装。 @@ -58,10 +59,10 @@ pip install "unilab[newton]" 支持通道。 - Python `>=3.10`(仓库支持范围为 3.10–3.13)。 -安装后可运行 unisim 仓库的 `scripts/check_newton_runtime.py` 做 +安装后可运行 unisim 仓库的 `scripts/diagnostics/check_newton_runtime.py` 做 metadata 级探针(加 `--import` 显式导入原生运行时)。在 UniLab 侧,缺少 -Newton 运行时不是静默失败:顶层 CLI 在训练前检查 `newton` / -`newton` 模块,缺失时 fail-closed 并给出安装提示(`src/unilab/cli.py` +Newton 运行时不是静默失败:顶层 CLI 在训练前检查 `newton` 模块,缺失时 +fail-closed 并给出安装提示(`src/unilab/cli.py` 的 `_check_runtime_requirements`)。 ## 训练与评估 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/8-superdex.md b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/8-superdex.md index d65878b49..54fed0dfd 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/3-backends/8-superdex.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/3-backends/8-superdex.md @@ -1,8 +1,7 @@ # SuperDex 后端 > SuperDex 已作为 packed CPU `HOST_BRIDGE` 后端加入 tensor-only Manager -> runtime。Go2 owner 仍是 **Configured** 研究配置,不构成完整训练或 -> 跨平台生产支持声明。 +> runtime。Go2 owner 仍是 **Configured** 研究配置。 SuperDex 是由 `unisim.backend.superdex` 拥有的可选 CPU 物理后端。当前签入的 @@ -11,7 +10,7 @@ owner 为 `go2_joystick_flat/superdex`。当前支持等级为 **Configured**; ## 安装 -SuperDex Physics/Robotics 1.0.0 已发布 Python wheel,是 UniLab 的 optional +SuperDex Physics/Robotics 1.3.0 已发布 Python wheel,是 UniLab 的 optional extra,不再需要源码编译 native extension。wheel 携带 native batch executor, 仅支持 CPython 3.12/3.13 的 Linux x86_64;其他平台上该 extra 为空,CLI 会给出 针对性的运行时诊断。CPU 物理不需要 CUDA。 @@ -66,8 +65,8 @@ uv run eval --algo ppo --task go2_joystick_flat --sim superdex \ ``` 如需 native SuperDex(Polyscope)viewer 而不是视频,加 -`--render-mode interactive`;CLI 会强制 `training.play_env_num=1`,owner 层同时 -把该次运行的 env 切到 serial executor。 +`--render-mode interactive`;CLI 默认设置 `training.play_env_num=1`(显式覆盖时 +保留用户值),owner 层同时把该次运行的 env 切到 serial executor。 在 MuJoCo 上训练的 checkpoint 可以直接在 SuperDex 上评估(sim2sim):把它的 run 目录传给 `--load-run`。play 入口会在构造环境前按 sim2sim contract 验证来源 @@ -83,7 +82,7 @@ PPO/APPO collector、learner 或 policy contract。决策见 {doc}`/adr/ADR-0009-superdex-persistent-cpu-workers` 和 [unisim#41](https://github.com/unilabsim/unisim/issues/41)。 -两个 task owner 默认选择自动 worker: +该 task owner 默认选择自动 worker: | Owner 选项 | 含义 | | --- | --- | @@ -101,8 +100,8 @@ scene,完全不创建 native worker pool `eval --sim superdex --render-mode interactive` 走 native SuperDex(Polyscope) viewer 渲染,而不是 MuJoCo viewer 路径。owner 层会自动把 env 切到 -`superdex_execution_mode=serial`,CLI 同时强制 `training.play_env_num=1`(viewer -只绘制一个 scene);显式传入的 `training.play_env_num=...` 会被保留。 +`superdex_execution_mode=serial`,CLI 同时默认设置 `training.play_env_num=1` +(viewer 只绘制一个 scene);显式传入的 `training.play_env_num=...` 会被保留。 1024 个环境、16 核 32 线程主机上,自动解析为 16 workers。多 rank 并发 collector 按完整物理核心分配,并将同一核心的 logical sibling 放在同一 rank,避免拆分 SMT 核心。 @@ -119,10 +118,11 @@ backend/env 时间、startup、RSS、CPU 使用和实际 worker 数。吞吐按 不能把 physics 子步重复计入样本。已有接触近似的物理边界保持不变。 固定根具有名称和可读的 body state,但 reset 只写 joint state,不要求 free-root -layout。该任务不需要接触 sensor、相机、site Jacobian 或材料 DR。SuperDex 没有 native -renderer;默认 record 回放使用离线 MuJoCo renderer,物理仍由 SuperDex 执行。 -`.superdex_bot` 场景需要提供 `visual_model_file`。`play_render_mode=none` 会完全跳过 -回放,不能作为 checkpoint rollout 已执行的证据。 +layout。该任务不需要接触 sensor、相机、site Jacobian 或材料 DR。SuperDex 不提供 +离线 record renderer;默认 record 回放使用 MuJoCo,物理仍由 SuperDex 执行,原生 +interactive 回放则使用上文所述的 Polyscope。`.superdex_bot` 场景的 record 路径需要 +提供 `visual_model_file`。`play_render_mode=none` 会完全跳过回放,不能作为 +checkpoint rollout 已执行的证据。 `superdex_allow_contact_approximation` 默认 `false`,只供经过审核的 MJCF 转换配置 显式启用。启用后会警告 contact/material 近似,包括 torsional/rolling friction @@ -133,12 +133,13 @@ getter 则在 reset 后立即刷新。 ## 验证与归属 -`go2_joystick_flat/superdex` PPO owner 是研究性质的 sim2sim 配置。它继承 MuJoCo -owner,保留 49 维 actor 观测、52 维 critic 观测、12 维位置目标动作、归一化、网络 -维度和控制时序;关闭 runtime PD gain DR,并显式接受接触近似。adapter 的冷路径 +`go2_joystick_flat/superdex` PPO owner 是研究性质的 sim2sim 配置。它通过共享 +base owner 保留与 MuJoCo owner 相同的 policy I/O:49 维 actor 观测、52 维 critic +观测、12 维位置目标动作、归一化、网络维度和控制时序;关闭 runtime PD gain DR,并显式接受接触近似。adapter 的冷路径 MJCF 转换有明确限制,该 owner 不代表任意场景或行走效果等价。 -先用 MuJoCo owner 创建一个小型来源 checkpoint,再把路径传给可选 checkpoint 测试: +先在独立环境中用 MuJoCo owner 创建一个小型来源 checkpoint(`mujoco` 与 +`superdex` extra 相互冲突),再在 SuperDex 环境中把路径传给可选 checkpoint 测试: ```bash uv run --no-sync train --algo ppo --task go2_joystick_flat --sim mujoco \ diff --git a/docs/sphinx/source/zh_CN/2-user_guide/4-tasks/2-motion_tracking.md b/docs/sphinx/source/zh_CN/2-user_guide/4-tasks/2-motion_tracking.md index 26a650a1b..dd50a4dc0 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/4-tasks/2-motion_tracking.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/4-tasks/2-motion_tracking.md @@ -3,8 +3,8 @@ G1 动作追踪任务位于 `src/unilab/tasks/motion_tracking/` 下,并通过 `src/unilab/conf/ppo/`、`src/unilab/conf/appo/` 以及选定的 off-policy 路径中的 task owner YAML 选择。 -> **Motion 资产已迁移到 Hugging Face。** `.npz` 片段不再随仓库分发,首次使用时由 -> `MotionLoader`(`src/unilab/tasks/motion_tracking/common/motion_loader.py`)按需从 +> **Motion 资产通过 Hugging Face 按需获取。** 当引用的 `.npz` 片段不在本地时, +> `MotionLoader`(`src/unilab/tasks/motion_tracking/common/motion_loader.py`)会从 > [unilabsim/unilab-motions](https://huggingface.co/datasets/unilabsim/unilab-motions) > 下载,下载逻辑在 `src/unilab/assets/hub.py`(`_HF_MOTIONS_REPO_ID`)。`uv sync` > 已自动安装所需的 `huggingface_hub` 依赖。 @@ -17,7 +17,7 @@ Manager-Based runtime 执行。 | CLI Task | Registered Env | 默认 motion | Owner Evidence | | --- | --- | --- | --- | -| `g1_motion_tracking` | `G1MotionTracking` | `dance1_subject2_part.npz` | `src/unilab/conf/ppo/task/g1_motion_tracking/`, `src/unilab/conf/appo/task/g1_motion_tracking/` | +| `g1_motion_tracking` | `G1MotionTracking` | `dance1_subject2_part.npz` | `src/unilab/conf/{ppo,appo,sac,flashsac}/task/g1_motion_tracking/` | profile 差异留在 Hydra 中:PPO/APPO、SAC 与 FlashSAC 都组合注册的 `G1MotionTracking` identity,而算法专属的 observation、DR 与 tensor runtime @@ -32,7 +32,6 @@ PPO owner 迭代预算(`--sim mujoco` owner YAML):`g1_motion_tracking` 为 ```bash uv run train --algo ppo --task g1_motion_tracking --sim mujoco -uv run train --algo ppo --task g1_motion_tracking --sim mujoco uv run train --algo appo --task g1_motion_tracking --sim mujoco training.no_play=true uv run train --algo ppo --task g1_motion_tracking --sim mujoco \ algo.num_envs=128 algo.max_iterations=5 training.no_play=true @@ -48,11 +47,13 @@ uv run train --algo sac --task g1_motion_tracking --sim mujoco training.use_amp= ``` `g1_motion_tracking` owner 是与部署对齐的 off-policy 观测配置。当 Motrix sim2sim -回放需要引用其他日志根目录下的 checkpoint 时,用 `uv run eval` 透传绝对路径: +回放需要引用其他日志根目录下的 checkpoint 时,设置 `training.log_root`,并通过 +`--load-run` 传入 run 目录名(该参数不接受任意路径): ```bash -uv run eval --algo sac --task g1_motion_tracking --sim mujoco \ - algo.load_run=/abs/path/to/logs/sac/G1MotionTracking/2026-04-23_14-06-57_mujoco +uv run eval --algo sac --task g1_motion_tracking --sim motrix \ + --load-run 2026-04-23_14-06-57_mujoco \ + training.log_root=/abs/path/to/logs/sac ``` ## 动作文件 @@ -76,12 +77,12 @@ env: ```bash uv run scripts/motion/csv_to_npz.py \ - --input_file src/unilab/assets/motions/g1/dance1_subject2.csv \ - --output_file src/unilab/assets/motions/g1/dance1_subject2_from_csv.npz \ + --input_file /path/to/dance1_subject2.csv \ + --output_file /tmp/dance1_subject2_from_csv.npz \ --input_fps 30 --output_fps 50 uv run scripts/motion/csv_to_npz.py \ - --input_file src/unilab/assets/motions/g1/dance1_subject2.csv \ - --output_file src/unilab/assets/motions/g1/dance1_subject2_clip.npz \ + --input_file /path/to/dance1_subject2.csv \ + --output_file /tmp/dance1_subject2_clip.npz \ --input_fps 30 --output_fps 50 --start_time 4.0 --end_time 9.0 uv run scripts/motion/replay_npz.py \ --npz_file src/unilab/assets/motions/g1/dance1_subject2_part.npz --loop diff --git a/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/0-index.md b/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/0-index.md index 50b88e4ae..d99106696 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/0-index.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/0-index.md @@ -7,7 +7,11 @@ Manager-Based event term 是唯一 DR 声明路径: - **Manager-Based(Compatible)任务**:reset / interval 随机化通过 owner YAML 中的 Hydra `events:` manager term 声明;reset 生命周期的 event 在 reset 时采样,interval 生命周期的 event 在 step 之间施加扰动。例如 `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` 的 `events:` 段。 +Manager-Based 生命周期如下: +- construction 路径:固定 model/tool identity 在 backend 构造前附加到 `SceneCfg`。 +- reset 路径:event term 在 `ResetStateTransaction` 中组合写入,经 backend 持有的 packed reset transaction(`SimBackend.bind_packed_reset()`)一次提交。 +- interval 路径:event term 通过公开契约提交 backend 持有的 interval plan。 这三条路径对应三个生命周期类别: @@ -18,26 +22,21 @@ Manager-Based event term 是唯一 DR 声明路径: ## 状态结论 1. reset/interval 随机化由 owner YAML 中的 `events:` manager term 声明,并由 manager 生命周期统一执行。 -2. Manager-Based owner 通过 Hydra command/event term 声明 reset 行为。G1 motion reset 扰动归 device-resident `MotionCommandCfg` 所有,WBT 另加 `EventTermCfg` reset 与 interval term。 -3. `TensorResetRandomizationPayload`(torch-first 的 reset payload)表达 curated reset terms;backend 必须在对应的 host/device 平面上声明每个请求 term,并拥有其派生量重算义务。 -4. `MotrixBackend` 目前支持 `base_mass_delta`、`base_com_offset`、`kp`、`kd` 和 interval push;并且它要求在初始化期间所有模型 actuator 都是 position actuator。 +2. Manager-Based owner 通过 Hydra command/event term 声明 reset 行为。G1 motion reset 扰动归 device-resident `MotionCommandCfg` 所有,task owner 另加 `EventTermCfg` reset 与 interval term。 +3. `TensorResetRandomizationPayload`(torch-first 的 reset payload)表达 curated reset terms;backend 必须在统一能力集中声明每个请求 term,并拥有派生量与设备执行义务。 +4. backend 能力取决于实际模型和运行时 API。当前 Motrix 测试覆盖 `base_mass_delta`、`base_com_offset`、`gravity`、`kp`、`kd` 和 interval push;kp/kd 增益覆盖还要求模型全部使用 position actuator。这不是所有 Motrix 能力的共同前提。 5. 固定 mesh/tool identity 由 `env.fixed_model_variants` 声明;reset-time geometry 字段仍位于 backend capability 声明之后,且不会改变该 identity。 -## 统一性评估表 +## Owner 清单 -| Task | 声明路径 | 结构化形式? | reset 形式 | interval 形式 | Code | -| --- | --- | --- | --- | --- | --- | -| `Go2JoystickFlat` | Hydra `events:` term | 是:owner YAML 声明 reset event | root-state reset + `pd_gains` kp/kd | 无 | `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` | -| `G1WalkFlat` | Hydra `events:` term | 是:Hydra `EventTermCfg` + Manager-Based reset term | root-state reset + 经 `pd_gains` 的 kp/kd | 无 | `g1/manager_terms.py` | -| `G1MotionTracking` | Hydra command term | 是:Hydra device-resident `MotionCommandCfg` + Manager-Based command reset | motion frame、root pose/velocity 与 joint-position 采样 | 无 | `motion_tracking/common/manager_terms.py` | +任务名本身不能唯一确定 DR:共享 base owner 与 algo/backend 叶子配置可能不同。下表只描述指定 owner,不把它当作所有算法通用的矩阵。 -## 各任务域随机化清单 - -| Task | 当前已实现的 reset 域随机化 | 当前已实现的 interval 域随机化 | 默认状态 | +| Owner | Reset/startup 随机化 | Interval 随机化 | 证据 | | --- | --- | --- | --- | -| `Go2JoystickFlat` | 经 `reset_root_state_uniform` 的 base xy/yaw 与 base qvel;command 采样;经 `pd_gains` 的 kp/kd | 无 | event term 在 `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` 中默认声明并启用 | -| `G1WalkFlat` | 经 `reset_root_state_uniform` 的 base xy/yaw 与 base qvel;带平面死区的 command 采样;`gait_phase` 采样;经 `pd_gains` 的 kp/kd 随机化 | 无 | mujoco、genesis 与 motrix owner 默认启用 kp/kd;mjwarp owner 默认禁用 | -| `G1MotionTracking` | Motion-command frame 采样;root 位姿扰动 `x/y/z/roll/pitch/yaw`;root 速度扰动 `x/y/z/roll/pitch/yaw`;通过 public entity soft limit clip 的关节位置噪声;action-manager 状态 reset | 无 | base owner 中 `pose_range`、`velocity_range` 与 `joint_position_range` 默认有非零扰动 | +| Go2 共享 base | root-state reset、command 采样,以及经 `pd_gains` 的 kp/kd | 无 | `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` | +| Go2 FlashSAC MuJoCo 叶子 | 继承 base 项,并增加 base 质量、质心和零宽度 gravity 项 | 每 15 s 一次线速度 push | `src/unilab/conf/flashsac/task/go2_joystick_flat/mujoco.yaml` | +| G1 walk 共享 base | root-state reset、command 与 gait-phase 采样,以及经 `pd_gains` 的 kp/kd;PPO MJWarp 叶子禁用 `pd_gains` | 无 | `src/unilab/conf/ppo/task/g1_walk_flat/base.yaml`、`src/unilab/conf/ppo/task/g1_walk_flat/mjwarp.yaml` | +| G1 motion SAC/FlashSAC 共享 base | motion-command 位姿/速度采样,以及质心、encoder bias、足部摩擦 event term | 六轴速度 push;Motrix 叶子禁用 | `src/unilab/conf/sac/task/g1_motion_tracking/base.yaml`、`src/unilab/conf/flashsac/task/g1_motion_tracking/base.yaml` | ## 当前 DR 的能力与边界 @@ -52,15 +51,17 @@ command/event term 拥有: ## Reset gravity 用法 -`gravity` 是 reset 生命周期 DR:每次 reset 按选中环境采样完整的 MuJoCo gravity +`gravity` 是 reset 生命周期 DR:每次 reset 按选中环境采样完整的三维 gravity 向量 `(gx, gy, gz)`,并通过 `TensorResetRandomizationPayload.gravity` 提交。请通过调用 `randomize_physics_scene_gravity` 的 reset `EventTermCfg` 配置;不支持的后端 fail closed。建议从较小倾斜范围开始,避免早期训练任务不可学习。 ## Interval push 用法 -Manager-Based 任务通过 `env.events.push_robot` term 配置周期推扰,使用 -`push_by_setting_velocity`,并按轴声明速度范围。 +Manager-Based 任务通过调用 `push_by_setting_velocity` 的 interval event term +配置周期推扰,并按轴声明速度范围。G1 motion owner 将其命名为 +`env.events.push_robot`;Go2 FlashSAC MuJoCo owner 对同一操作使用 +`env.events.push_by_setting_velocity`。 ## 固定 Model/Tool Variant 边界 @@ -76,18 +77,21 @@ env: - name: tool_b source_model_file: tools/tool_b.xml # 省略 explicit_variant_names 时使用确定性 round-robin assignment。 + # 否则必须恰好提供 num_envs 项(本例假设有两个环境)。 explicit_variant_names: [tool_a, tool_b] ``` Manager factory 会把它物化为形状 `(num_envs,)`、只读的 `int32` assignment; -空 explicit list 选择 round-robin。Assignment 是 +空 explicit list 选择 round-robin。非空列表长度与 `num_envs` 不一致时会被拒绝。Assignment 是 task identity:backend construction 后固定,reset event 不会重新采样。 UniLab 不打开、解析或编译 `source_model_file`,也不持有 `MjSpec`、`MjModel`、 -mjbatch 或 Warp object。UniSim adapter 负责 source realization,并必须声明 -`supports_fixed_variants`。在该 contract 落地前,配置 fixed variants 的 -task 会在 env 构造前 fail closed。无法投影到统一 public -state/action/sensor layout 的 heterogeneous variants 同样 fail closed。 +mjbatch 或 Warp object。UniSim adapter 负责 source realization,并必须同时声明 +`supports_fixed_variants` 和该 plan 的 `same_layout` layout。不支持的 backend 或 +layout 会在 Manager-Based 环境构造前 fail closed; +`tests/base/test_fixed_model_variants.py` 覆盖 plan 构造、layout 协商以及失败路径的 +资源清理。无法投影到统一 public state/action/sensor layout 的 heterogeneous +variants 同样 fail closed。 Reset-time model-field DR 保持在已选 identity 内。其 canonical 或 per-env 基线来自 backend 声明的 `get_reset_term_default(term)` contract;Manager term diff --git a/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/1-configuration.md b/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/1-configuration.md index 71f25ece1..59448e366 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/1-configuration.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/1-configuration.md @@ -16,13 +16,17 @@ Backend 支持通过 `unisim.backend.base` 显式声明。所选 backend 未声 ## Reset Gravity -启用 gravity reset 随机化时使用 `--sim mujoco`;Motrix 未声明 gravity reset -能力。请通过调用 `randomize_physics_scene_gravity` 的 reset event term 配置。 +请通过调用 `randomize_physics_scene_gravity` 的 reset event term 配置 gravity, +并且只在所选 backend 声明支持 `gravity` 时启用。当前测试覆盖 MuJoCo、MJWarp +和 Motrix 的 gravity reset;Genesis 会拒绝该 term。因此,该能力并非 +MuJoCo 独占,也不是所有 backend 都支持。 ## Interval Push -Manager-Based 任务通过 `env.events.push_robot` term 配置周期推扰,使用 -`push_by_setting_velocity`,并按轴声明速度范围。 +Manager-Based 任务通过调用 `push_by_setting_velocity` 的 interval event term +配置周期推扰,并按轴声明速度范围。G1 motion owner 将其命名为 +`env.events.push_robot`;Go2 FlashSAC MuJoCo owner 对同一操作使用 +`env.events.push_by_setting_velocity`。 ## Owner 本地默认值 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/2-field_reference.md b/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/2-field_reference.md index 0ddb4ccee..5f92c53c6 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/2-field_reference.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/5-domain_randomization/2-field_reference.md @@ -18,10 +18,14 @@ DR term 运行在三个生命周期类别下(见 {doc}`0-index` 的生命周 ## Backend 适用性 -字段 × backend 的精确矩阵由外部包 `unisim-core` 持有 +运行时字段 × backend 矩阵由外部包 `unisim-core` 持有 (`DomainRandomizationCapabilities.supported_reset_terms` / -`supported_interval_terms`),无法从本仓库逐字段确认,因此本页刻意不给出 -该矩阵。有两条规则始终成立: +`supported_interval_terms`)。它可能取决于实际模型和可用的运行时 API,因此本页 +不把静态矩阵当作通用结论。仓库测试提供了具体例证: +`tests/base/test_sim_backend_smoke.py` 覆盖 Motrix gravity 与 interval push, +`tests/base/test_motrix_backend_options.py` 覆盖其条件能力声明, +`tests/base/test_genesis_backend.py` 证明 Genesis 不支持 gravity reset, +`tests/base/test_mjwarp_dr.py` 覆盖 MJWarp gravity。有两条规则始终成立: 1. 所选 backend 未声明支持的 term 在构造期 fail closed;不存在过滤或静默 回退。 @@ -114,8 +118,9 @@ DR term 运行在三个生命周期类别下(见 {doc}`0-index` 的生命周 ### `randomize_rigid_body_com` 加性质心随机化(`unilab.envs.mdp.randomize_rigid_body_com`)。支持 -`mode: reset` 与 `mode: startup`。每次应用都会重新读取实时的 -`com_range`,因此 curriculum 可以在两次 reset 之间放宽范围。 +`mode: reset` 与 `mode: startup`。reset 模式下,每次应用都会重新读取实时的 +`com_range`,因此 curriculum 可以在两次 reset 之间放宽范围。startup 模式采样 +一张全宽表并冻结,之后的范围变更不会改变这些取值。 | 字段 | 类型 | 默认值/必填 | 生效时机 | 语义与合理取值线索 | | --- | --- | --- | --- | --- | @@ -174,7 +179,7 @@ DR term 运行在三个生命周期类别下(见 {doc}`0-index` 的生命周 | 字段 | 类型 | 默认值/必填 | 生效时机 | 语义与合理取值线索 | | --- | --- | --- | --- | --- | -| `bias_range` | `[lo, hi]` | 必填 | 每次 reset 采样 | 均匀偏置,单位为弧度(关节位置单位)。SAC G1 MuJoCo owner 在全部关节上用 `[-0.01, 0.01]`。 | +| `bias_range` | `[lo, hi]` | 必填 | 每次 reset 采样 | 均匀偏置,使用模型的关节位置单位。SAC G1 MuJoCo owner 在全部关节上用 `[-0.01, 0.01]`。 | | `asset_cfg` | `SceneEntityCfg` | 必填 | 构造期绑定 | 用 `joint_names`/`joint_ids` 选择 joint;至少选中一个关节。 | ## Reset 状态 Term @@ -313,16 +318,14 @@ owner 给 `base` 加 ±1.5 kg),`scale` 乘无量纲因子(SAC G1 Genesis o 把 `pelvis`/`torso_link` 缩放 `[0.9, 1.1]`),`abs` 直接设绝对千克数。 结果按 `min_mass`(默认 `1e-6`)做下限截断。 -**Motrix 不支持 gravity 时,如何写一份 Motrix 与 MuJoCo 都能跑的 owner YAML?** -按 {doc}`1-configuration`,gravity reset 随机化目前仅 MuJoCo 可用; -`MotrixBackend` 只声明支持 `base_mass_delta`、`base_com_offset`、`kp`、 -`kd` 与 interval push(见 {doc}`0-index`)。共享 term 留在任务的 -`base.yaml`,只在 `mujoco.yaml` 声明 -`randomize_physics_scene_gravity`;如果共享 base 已声明它,就在 -`motrix.yaml` 中设置 `randomize_physics_scene_gravity: null` —— 与 +**某个 backend 不支持 gravity 时,如何写一份跨 backend 可运行的 owner YAML?** +gravity reset 并非 MuJoCo 独占:当前测试覆盖 MuJoCo、MJWarp 和 Motrix,而 +Genesis 会拒绝该能力(见 {doc}`1-configuration`)。共享 term 留在任务的 +`base.yaml`,只在 backend 声明支持该能力的 owner 中声明 +`randomize_physics_scene_gravity`;如果共享 base 已声明它,就在不支持的 +backend owner 中设置 `randomize_physics_scene_gravity: null` —— 与 `src/unilab/conf/ppo/task/g1_walk_flat/mjwarp.yaml` 中 `pd_gains: null` -的模式相同。若让 Motrix 保留该 term,构造期会 fail -closed 而不是被跳过。 +的模式相同。若在不支持的 backend 上保留该 term,构造期会 fail closed 而不是被跳过。 这些 term 背后的 payload 级契约见 {doc}`Domain Randomization Contract `。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/0-index.md b/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/0-index.md index 33c5b933c..5287ac84c 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/0-index.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/0-index.md @@ -1,6 +1,8 @@ # 地形 -地形支持目前通过 Go2 崎岖地形 owner 路径以及共享地形生成器进行说明。 +地形支持由共享生成器、scene 配置和 backend 物化契约提供。当前 +`src/unilab/conf` 下没有已注册 owner 声明 `env.scene.terrain`;以下示例是有 +生成器、物化和 Manager 运行时测试支撑的集成方式,不是现成任务 owner 的用法。 ::::{grid} 1 1 2 2 :gutter: 3 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/1-procedural.md b/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/1-procedural.md index 790ec884d..637649f04 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/1-procedural.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/1-procedural.md @@ -11,7 +11,8 @@ adapter 只在环境构建阶段物化地形。 - `unilab.base.scene.SceneCfg`:`terrain` 与 scene 文件。 - `unilab.terrains` sub-terrain factory:generator 组合。 -例如,owner 可以声明生成式 terrain,而不让 backend 感知任务语义: +例如,owner 可以声明生成式 terrain,而不让 backend 感知任务语义。 +`TerrainGeneratorCfg` 要求提供 `size`,且 `sub_terrains` 至少有一项: ```yaml env: @@ -21,12 +22,20 @@ env: geom_name: floor generator: _target_: unilab.terrains.TerrainGeneratorCfg + size: [2.0, 2.0] + num_rows: 2 + curriculum: true seed: 42 + sub_terrains: + flat: + _target_: unilab.terrains.HfFlatTerrainCfg + proportion: 1.0 ``` UniLab 在 `src/unilab/base/terrain.py` 中持有运行时地形 spawn 状态;UniSim -持有 generator 组合与 backend materialization。启用该能力的 task owner 需要自行 -持有训练证据。 +持有 generator 组合与 backend materialization。该声明是集成示例,不是 +`src/unilab/conf` 中现成的注册 owner;`tests/base/test_terrain.py` 直接构造了 +等价的类型化配置。 ## 物化边界 @@ -35,12 +44,14 @@ UniLab 在 `src/unilab/base/terrain.py` 中持有运行时地形 spawn 状态; 1. Hydra 将选中的 owner 物化为 `ManagerBasedRlEnvCfg`。 2. `create_backend` 解析所需机器人资产,并将 `SceneCfg` 传给选中的 UniSim backend。 -3. backend 的公开 scene materializer 生成 terrain matrix、origins、hfield - 与合并后的 scene model。 +3. 实现公开 scene materializer 的 backend 生成 terrain matrix、origins、hfield + 与合并后的 scene model。当前测试覆盖 MuJoCo 和 Motrix 的物化。 4. task owner 自行持有 scanner binding 与缓存 ID。 step 和 reset 不解析机器人 XML,也不检查 asset metadata;它们只消费缓存 -ID 和公开 backend capability。 +ID 和公开 backend capability。如果 backend 声明了生成式 terrain,却未返回 +`SimBackend.get_terrain_spawn_data()` 元数据,`src/unilab/base/terrain.py` 会 +fail closed。 ## Owner 集成 @@ -77,8 +88,8 @@ curriculum: ## 核心验证 ```bash -uv run pytest tests/terrains tests/utils/test_xml_utils.py -q +uv run pytest tests/terrains tests/base/test_terrain.py tests/utils/test_xml_utils.py -q ``` -核心验证同时覆盖 terrain generator 与 backend materialization 边界; -额外任务族的证据由 ecosystem 包持有。 +这些测试覆盖 terrain generator、运行时课程和 backend materialization 边界;缺少可选 +仿真依赖时,对应的物化用例可能跳过。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/2-heightfield_import.md b/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/2-heightfield_import.md index 9c335f081..e29ae1a98 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/2-heightfield_import.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/6-terrain/2-heightfield_import.md @@ -1,6 +1,8 @@ # 高度场导入 -高度场地形通过 `SceneCfg` 和地形生成器进行配置,然后在 init 路径上由后端实例化。核心测试使用生成式 heightfield 场景覆盖该契约。 +高度场地形通过 `SceneCfg` 和地形生成器进行配置,然后在 init 路径上由后端实例化。 +当前覆盖的路径从程序化子地形生成合并的 heightfield PNG,并不是用户自备高度图的 +通用导入器。当前物化测试覆盖 MuJoCo 和 Motrix。 ## 需要阅读的文件 @@ -14,7 +16,9 @@ ```bash uv run pytest tests/utils/test_xml_utils.py \ - -k mujoco_materialize_hfield_attached_scene + -k materialize_hfield_attached_scene ``` +该命令同时选择 MuJoCo 和 Motrix 物化测试;缺少 Motrix 可选仿真依赖时,对应用例会跳过。 + 高度扫描的 ID 和偏移在 env 初始化期间缓存;热路径调用后端高度 scanner contract,而不是解析 XML 或 asset 元数据。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/1-onnx_export.md b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/1-onnx_export.md index cd9cc9eca..eae987c92 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/1-onnx_export.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/1-onnx_export.md @@ -10,4 +10,10 @@ uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 uv run eval --algo sac --task g1_walk_flat --sim mujoco --load-run -1 ``` -使用与生成 checkpoint 时相同的 `--algo`、`--task` 和 `--sim` 值。关于部署上下文,参见 {doc}`../../3-deployment/1-sim_to_real/5-onnx_runtime`。 +使用与生成 checkpoint 时相同的 `--algo`、`--task` 和 `--sim` 值。产物是所选 +checkpoint 运行目录中的 `policy.onnx`。SAC 和 FlashSAC 默认导出,可通过 +`training.export_onnx=false` 跳过。APPO 在回放解析到 checkpoint 运行目录时会尝试 +导出,且没有 `training.export_onnx` 开关。APPO、SAC 和 FlashSAC 导出后会比较 +ONNX Runtime 与 PyTorch 输出,PPO 路径则委托 RSL-RL runner 导出。 + +关于部署上下文,参见 {doc}`../../3-deployment/1-sim_to_real/5-onnx_runtime`。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/2-wandb.md b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/2-wandb.md index 148399a36..5e891d79c 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/2-wandb.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/2-wandb.md @@ -1,6 +1,6 @@ # W&B 与 TensorBoard -训练配置默认通过 `training.logger=tensorboard` 使用 TensorBoard。设置 `training.logger=wandb` 以使用 Weights & Biases。共享的 W&B 字段位于训练配置块中,包括 `wandb_project`、`wandb_entity`、`wandb_group`、`wandb_name`、`wandb_tags`、`wandb_notes` 和 `wandb_mode`。 +训练配置默认通过 `training.logger=tensorboard` 使用 TensorBoard。设置 `training.logger=wandb` 以使用 Weights & Biases。共享的 W&B 字段位于训练配置块中,包括 `wandb_project`、`wandb_entity`、`wandb_group`、`wandb_job_type`、`wandb_name`、`wandb_tags`、`wandb_notes` 和 `wandb_mode`。 ## 示例 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/3-nan_visualizer.md b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/3-nan_visualizer.md index 531f92904..5449767d0 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/3-nan_visualizer.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/3-nan_visualizer.md @@ -8,4 +8,13 @@ uv run train --algo ppo --task go2_joystick_flat --sim mujoco \ training.nan_guard.output_dir=/tmp/unilab/nan_dumps ``` -viewer 的实现是 `src/unilab/utils/nan_viz.py`,注册为 `unilab-viz-nan` 控制台入口。它会回放一个 dump 路径,并让你选择环境索引。dump 格式和往返加载由 `tests/training/test_tensor_diagnostics.py` 覆盖。 +viewer 的实现是 `src/unilab/utils/nan_viz.py`,注册为 `unilab-viz-nan` 控制台入口: + +```bash +uv run unilab-viz-nan /tmp/unilab/nan_dumps/dump.npz --env-index 0 +``` + +它回放 dump 中的 MuJoCo 物理状态,需要 dump 元数据记录的模型文件,或同目录下的 +`*_model.*` 产物。如果 backend 未提供状态回放,dump 不包含物理状态,命令会打印 +元数据而不会打开 viewer。dump 格式和往返加载由 +`tests/training/test_tensor_diagnostics.py` 覆盖。 diff --git a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/5-robot_import.md b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/5-robot_import.md index d922ab81a..5ce4c3ede 100644 --- a/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/5-robot_import.md +++ b/docs/sphinx/source/zh_CN/2-user_guide/7-tooling/5-robot_import.md @@ -14,7 +14,8 @@ task/reward/env 语义。 - `assets/`:只放 `.stl` / `.obj` mesh。 - `.xml`:纯机器人 MJCF,只包含 body / joint / actuator / sensor 等机器人描述。 -- task/scene fragment:例如 `scene.xml`,放场景、地面、任务传感器和 keyframe。 +- task/scene fragment:例如 `scene.xml`,放任务 keyframe,并按任务需要放场景、地面和 + 任务传感器。导入器生成的 `scene.xml` 只包含初始 `home` keyframe。 不要复制完整外部资源包。`` 属于 task/scene fragment,不能放进机器人 XML。 diff --git a/docs/sphinx/source/zh_CN/3-deployment/0-index.md b/docs/sphinx/source/zh_CN/3-deployment/0-index.md index 0e71ef338..c2e91f611 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/0-index.md +++ b/docs/sphinx/source/zh_CN/3-deployment/0-index.md @@ -25,7 +25,7 @@ :link-type: doc :class-card: sd-shadow-md -在 MuJoCo 与 Motrix 之间切换同一任务,无需从头重新训练。 +通过 owner YAML 在受支持的后端之间迁移,并分别验证策略 I/O、物理、reward 和回放。 ::: :::{grid-item-card} 🔁 框架迁移 @@ -33,7 +33,7 @@ :link-type: doc :class-card: sd-shadow-md -从 Isaac Lab / Legged Gym / rsl_rl / skrl 迁移任务。 +从 Isaac Lab / Legged Gym / rsl_rl / skrl / unilab-rl 迁移任务。 ::: :::: @@ -97,7 +97,7 @@ Go2 joystick-flat 部署。 --- -## 🔀 仿真 → 仿真(MuJoCo ↔ Motrix) +## 🔀 仿真 → 仿真 ::::{grid} 1 1 2 3 :gutter: 3 @@ -105,11 +105,13 @@ Go2 joystick-flat 部署。 :::{grid-item-card} 🤔 后端切换 :link: 2-sim_to_sim/1-backend_swap :link-type: doc +用 `--algo`、`--task` 和 `--sim` 选择 owner。 ::: :::{grid-item-card} 📝 Owner YAML 切换 :link: 2-sim_to_sim/2-owner_yaml_swap :link-type: doc +新增后端 leaf,避免跨后端继承。 ::: :::{grid-item-card} 🔬 接触与摩擦对齐 @@ -122,7 +124,7 @@ Go2 joystick-flat 部署。 :link-type: doc ::: -:::{grid-item-card} 🎞 回放差异 +:::{grid-item-card} 🎞 回放与快照 :link: 2-sim_to_sim/5-playback_and_snapshot_differences :link-type: doc ::: @@ -132,6 +134,12 @@ Go2 joystick-flat 部署。 :link-type: doc ::: +:::{grid-item-card} 🛡 跨后端配置守卫 +:link: 2-sim_to_sim/7-config_guard +:link-type: doc +在 checkpoint 回放前验证训练时的策略契约。 +::: + :::: --- @@ -144,7 +152,7 @@ Go2 joystick-flat 部署。 :::{grid-item-card} 来自 **Isaac Lab** :link: 3-framework_migration/1-from_isaac_lab :link-type: doc -GPU 常驻 → CPU + 共享内存。 +Manager-Based term → Torch runtime 与 Hydra owner。 ::: :::{grid-item-card} 来自 **Legged Gym** @@ -156,7 +164,7 @@ GPU 常驻 → CPU + 共享内存。 :::{grid-item-card} 来自 **rsl_rl** :link: 3-framework_migration/3-from_rsl_rl :link-type: doc -训练器拆分:collector + learner。 +直接集成上游 `OnPolicyRunner`;APPO 是独立算法。 ::: :::{grid-item-card} 来自 **skrl** @@ -177,6 +185,12 @@ GPU 常驻 → CPU + 共享内存。 以 UniLab 风格表达常见奖励项。 ::: +:::{grid-item-card} 来自 **unilab-rl** +:link: 3-framework_migration/7-from_unilab_rl +:link-type: doc +将 `uni_rl` import 和安装方式迁移到 `unilab.rl` 与 `unirl` extra。 +::: + :::: ```{toctree} diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/1-overview.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/1-overview.md index 66376a014..e94ff8a97 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/1-overview.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/1-overview.md @@ -44,13 +44,14 @@ flowchart LR :class: note 1. 一次**收敛的训练运行**,奖励稳定,且成功判据也稳定(运动跟踪误差、跌落次数等)。 -2. 当 MuJoCo 与 Motrix **都**支持该任务时,同一策略在两者中都能通过评估 —— 否则 - 你存在一个依赖后端的奖励泄漏;见 {doc}`../2-sim_to_sim/4-reward_parity`。 +2. 当 MuJoCo 与 Motrix **都**支持该任务时,同一策略在两者中都能通过评估。如果不能, + 应排查依赖后端的契约或动力学,而不是直接假定为奖励泄漏;见 + {doc}`../2-sim_to_sim/4-reward_parity`。 3. **域随机化**范围足够大,使得在扫动 DR 强度时奖励平滑变化 —— 在仿真里脆弱的策略 在硬件上同样脆弱。 4. 环境中**没有后端功能泄漏** —— 通过开发者指南的 {doc}`../../4-developer_guide/2-contracts/2-backend_contract` 验证。 -5. 一份你能在硬件上实现的**观测规格**。如果你的策略读取 `body_lin_vel`,你需要一个 +5. 一份你能在硬件上实现的**观测规格**。如果你的策略读取 `base_lin_vel`,你需要一个 部署侧的估计器,或者一个把该信号从 actor 输入中移除的任务 owner 变体。 :::: @@ -59,13 +60,13 @@ flowchart LR - **观测漂移。** 仿真与部署运行时之间的传感器预处理不同(单位、坐标系、滤波截止频率)。 记录第一段部署侧观测窗口,并与用同一份 owner YAML 构建的仿真回合作对比。 -- **动作延迟。** 一些 task owner 通过 control config 或 Manager-Based action term - 暴露单步延迟的动作执行。测量部署回路,并在硬件运行前让训练 owner 匹配该契约。 - 见 {doc}`8-latency_budget`。 +- **动作延迟。** Manager-Based 动作项可以按物理子步延迟处理后的目标;G1 运动项也可以 + 选择一个控制 tick 前的原始动作。测量部署回路,并在硬件运行前用正确机制和单位匹配 + 训练契约。见 {doc}`8-latency_budget`。 - **摩擦 / 阻尼不匹配。** 尤其对于手内操作。在 DR 中扫动摩擦;通过 {doc}`../2-sim_to_sim/3-contact_and_friction_alignment` 交叉核对。 -- **复位瞬态。** 仿真复位到一个稳定姿态;部署则从一个控制器状态开始。安全层必须在 - 畸形观测与不安全动作到达电机驱动器之前将其拒绝。 +- **复位瞬态。** 仿真复位到一个稳定姿态;部署则从一个控制器状态开始。部署侧安全设计 + 应在畸形观测与不安全动作到达电机驱动器之前将其拒绝;UniLab 不提供该硬件安全回路。 ## 各机器人快速链接 diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/2-g1_whole_body.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/2-g1_whole_body.md index e756e301b..deefc73bd 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/2-g1_whole_body.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/2-g1_whole_body.md @@ -34,105 +34,101 @@ uv run eval --algo ppo --task g1_motion_tracking --sim mujoco --load-run -1 \ uv run eval --algo ppo --task g1_motion_tracking --sim mujoco --load-run -1 ``` -硬件回路需要的每个字段都在该 owner 的 YAML 中声明。宽度随 owner 而异: - -```{list-table} -:header-rows: 1 -:widths: 34 22 44 - -* - Owner - - Actor 观测宽度 - - 说明 -``` - -::::{admonition} 观测宽度应从 composed config 读取,而不是照抄本表 -:class: warning -Actor 观测宽度是 `env.observations.actor.terms` 下各项 `dim * history_length` -之和,再加上 motion command。置为 `null` 的项被丢弃。如果 ONNX 输入宽度与硬件回路 -装配出的宽度不一致,那是契约 bug,而不是硬件调参问题。 -:::: +当前 29 自由度 G1 运动跟踪 owner 的 actor 输入为 160 维。应从 composed config 和 +ONNX 计算图读取宽度,而不要把这个数字当作永久常量。对于展平的 group,每个观测项 +贡献其当前维度;只有配置了展平历史时才乘以 `history_length`,置为 `null` 的项会被 +丢弃。当前 G1 运动 owner 未声明观测历史。 ## 2. 观测契约 -分项顺序与逐项历史来自你所用 owner 自己的 `env.observations.actor.terms`。带 -`history_length` 的项在项内按**最旧优先**展平,各项再按声明顺序拼接: +保留的 owner 中,`env.policy_observation_group` 为 `actor`, +`env.observations.actor.terms` 按以下顺序声明观测项: ```{list-table} :header-rows: 1 :widths: 30 15 55 -* - 项 +* - 观测项 - 维度 - 硬件上的来源 +* - `command` + - 58 + - 当前参考帧的关节位置(29,rad),随后是关节速度(29,rad/s) +* - `motion_anchor_pos_b` + - 3 + - 运动锚点相对位置项,m * - `motion_anchor_ori_b` - 6 - - 来自参考帧与机器人躯干帧的锚点朝向项 + - 运动锚点的六分量相对朝向 +* - `base_lin_vel` + - 3 + - 骨盆坐标系线速度估计,m/s * - `base_ang_vel` - - 每个历史步 3 - - IMU 陀螺仪(`params.sensor_name: pelvis_gyro`) + - 3 + - IMU 陀螺仪(`params.sensor_name: torso_gyro`),rad/s * - `joint_pos` - - 每个历史步 29 - - 测量到的关节位置减去 `stand` keyframe 的关节角 + - 29 + - 相对场景默认值与 `joint_default_bias` 的测量位置,rad;SAC/FlashSAC 还会加上编码器偏置 * - `joint_vel` - - 每个历史步 29 - - 关节速度项 + - 29 + - 测量的关节速度,rad/s * - `actions` - - 每个历史步 29 - - 上一步的原始 actor 输出 + - 29 + - 上一步原始 actor 输出 ``` -声明时,motion command 在观测项之前贡献参考关节位置与速度。逐项的最旧优先 -顺序由 `ObservationManager` 的逐项历史缓冲实现保证 -(`tests/managers/test_observation_buffers_noise.py`);硬件侧必须镜像该顺序, -否则策略读到的是被置换过的向量。 +当前 owner 中这些项都只有单帧。如果自定义 owner 添加逐项历史,`ObservationManager` +会在每项内按**最旧优先**展平,再按声明顺序拼接各项 +(`tests/managers/test_observation_buffers_noise.py`)。必须原样复现缩放和历史; +仅供 critic 的 body 项不属于 actor 输入。 ## 3. 执行器接口 -将 actor 输出映射为 `action * scale + default_angles`,然后在目标到达电机驱动器 -之前钳制到场景的关节范围内。 +基础映射为 `action * scale + default_joint_pos`。对于 +`MotionJointPositionAction`,实际施加的目标还会加上 motion command 的 +`joint_default_bias` 并减去编码器偏置。部署控制器应在目标到达电机驱动器之前,将其 +钳制到经过验证的关节限位;UniLab 不执行这种硬件侧钳制。 -- `scale` 即 `env.actions.joint_pos.scale`。它可能是**标量**,也可能是按 - actuator 解析的**正则 → 数值映射**(Unitree deploy owner - 把关节名模式映射到不同数值)。必须原样复现 owner - 解析后的逐 actuator 向量——不要对映射取平均、取其中一项,也不要把标量广播到 - 映射型 owner 上。 -- `default_angles` 由 `use_default_offset: true` 决定,即 owner 场景中 `stand` - keyframe 的关节段。 -- 关节限位与增益同样来自该场景 XML(`jnt_range`、position actuator 的 - `gainprm` / `biasprm`)。 +- `scale` 即 `env.actions.joint_pos.scale`。当前 PPO/APPO 运动 owner 使用 `0.25`, + 当前 SAC/FlashSAC 运动 owner 使用 `2.0`。其他动作项可能使用按 actuator 解析的 + 正则 → 数值映射,因此必须复现所选 owner 解析后的向量。 +- `default_joint_pos` 来自 `use_default_offset: true` 和 `stand` keyframe。所选 owner + 使用运动/编码器偏置项时,不得省略这些项。 +- 关节限位和 position actuator 的标称 `kp` / `kv` 来自 composed 场景及其包含的 + 机器人 XML。启用 `env.events.pd_gains` 时,增益可在 reset 时改变。 -训练侧直接施加目标,不做平滑。如果硬件抖动迫使你加入平滑,请先验证其 sim2sim -影响——每一步滞后都会把观测推离训练分布。 +除非启用动作延迟设置,训练侧直接施加目标,不做平滑。仅在部署侧增加平滑或滤波会改变 +闭环契约;必须在仿真中复现并重新验证,然后再用于硬件。 ## 4. 参考运动同步 -相位变量让策略能够跟踪一个外部提供的运动片段。在硬件上你需要一个墙钟 → 相位的映射, -它必须: +`MotionCommand` 读取 `env.commands.motion.params.motion_file` 选择的 NPZ(保留的 +owner 当前为 `motions/g1/dance1_subject2_part.npz`)。 +`unilab.tasks.motion_tracking.common.motion_loader` 要求提供 `fps`、`joint_pos`、 +`joint_vel` 和 body 轨迹数组。command 推进的是参考**帧索引**,其 58 个数值是该帧的 +关节位置与速度;该任务没有 `(sin φ, cos φ)` 形式的 motion command 输入。 -- **单调** —— 不向后跳跃。 -- **可重启** —— 在通信抖动后仍能存活,不会在 `(sin φ, cos φ)` 中产生阶跃式 - 不连续。 -- **速率有界** —— 将 dφ/dt 钳制到策略训练时所用的值(运动加载器会记录这个值;加载 - `reference_motion.npz`)。 - -参见 `unilab.tasks.motion_tracking.common.motion_loader`,这是你应当在硬件上镜像的 -仿真侧加载器。 +当前 owner 使用 `env.ctrl_dt: 0.02`(20 ms,50 Hz)。硬件运行时必须按训练时的控制 +时序复现所选参考帧序列和锚点观测。UniLab 不提供部署侧墙钟同步器、通信恢复策略或半速 +运动映射;这些都需要部署侧自行实现,并在仿真中重新验证。 ## 5. 安全层 -硬件侧:标准结构见 {doc}`7-safety_layers`。G1 的具体事项: +硬件侧:建议检查清单见 {doc}`7-safety_layers`。G1 的具体事项: - 在应用动作缩放之前拒绝非有限动作与形状不匹配。 -- 用 owner 场景 XML 中的关节范围钳制生成的目标。 +- 根据 composed 场景和机器人硬件约束得到经过验证的限位,并据此钳制生成的目标。 - 把看门狗、姿态监控以及操作员停止阈值保留在部署控制器中,并独立于策略对它们进行 测试。 ## 6. 闭环上机序列 -1. **支架上站立**。机器人由龙门架吊挂。策略运行,但执行器关闭力矩。确认观测管线。 -2. **使能力矩、手扶**。操作员护着机器人。策略指挥执行器。确认动作映射。 -3. **龙门架支撑步态**。以半时间速率跟踪运动(dφ/dt 减半)。 -4. **自由站立**。全速率,然后移除龙门架。 +以下是部署侧建议流程,不是 UniLab 已在硬件上验证的安全规程: + +1. **仅观测,机器人有支撑**。策略运行,但执行器关闭力矩。确认观测管线。 +2. **在物理支撑下使能力矩**。仅在机器人/控制器运行限值内施加指令,确认动作映射。 +3. **有支撑的闭环运动**。保持参考帧时序与训练一致。 +4. **仅在独立安全检查通过后减少支撑**。始终处于经过验证的运行包络内。 不要跳过仅观测阶段:轴顺序、关节顺序以及 `actions` 接线错误在这一阶段最容易被 抓出来。 diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/3-go2_locomotion.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/3-go2_locomotion.md index 618f10d2a..7bc8b5415 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/3-go2_locomotion.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/3-go2_locomotion.md @@ -1,47 +1,49 @@ # Go2 运动部署 -本页描述保留的 `go2_joystick_flat` reference owner。Unitree production 部署 -变体由对应 ecosystem 包文档维护。 +本页描述保留的 `go2_joystick_flat` reference owner。UniLab 不为本页提供 Go2 +硬件运行时或硬件验证结果。 ## 观测契约 +当前 PPO/APPO/SAC/FlashSAC owner 在 `env.observations.policy.terms` 中按以下顺序 +声明观测项。对于 12 自由度机器人,展平后的 actor 输入为 49 维;仍应对照所选 +composed owner 和 ONNX 输入确认,而不要把这个总数当作永久常量。 + ```{list-table} :header-rows: 1 :widths: 30 15 55 -* - Group - - Dim +* - 观测项 + - 维度 - 硬件来源 -* - Base linear velocity - - 3 - - 状态估计器(IMU + 足端里程计 KF);不要使用原始积分 -* - Base angular velocity +* - `base_ang_vel` - 3 - - IMU 陀螺仪 -* - Projected gravity + - IMU 陀螺仪,rad/s +* - `projected_gravity` - 3 - - IMU 姿态 -* - Joystick command (vx, vy, ωz) - - 3 - - 操作者输入 -* - Joint positions + - 根据 IMU 姿态投影到基座坐标系的重力向量 +* - `joint_pos` - 12 - - 编码器 -* - Joint velocities + - 相对 `home` keyframe 的编码器位置,rad +* - `joint_vel` - 12 - - 部署控制器滤波后的编码器速度 -* - Previous action + - 编码器速度,rad/s +* - `actions` - 12 - - 上一步策略输出 -* - Foot contact + - 上一步原始策略输出 +* - `command` + - 3 + - 操作者指令 `(vx, vy, ωz)`,单位依次为 m/s、m/s、rad/s +* - `gait_phase` - 4 - - 接触传感器或由足端高度估计 + - 按配置频率生成的四个足端相位值 ``` -::::{admonition} 状态估计器注意事项 +::::{admonition} actor 与 critic 输入不同 :class: warning -策略训练时使用所选 env owner 声明的观测 term。如果部署侧无法提供相同的 -base-velocity 信号,请训练 actor 观测与机器人可用估计器匹配的变体。 +这些 owner 中的 `base_lin_vel` 仅供 critic 使用,足端接触则用于奖励项,而非 actor +观测。不要把它们追加到部署侧 actor 输入。如果任务变体修改了观测项,应改为复现该变体 +所选的 policy group。 :::: ## 另请参阅 diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/5-onnx_runtime.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/5-onnx_runtime.md index dec117d1a..7e85de1eb 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/5-onnx_runtime.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/5-onnx_runtime.md @@ -1,16 +1,15 @@ # ONNX 运行时 UniLab 从既有的训练回放路径导出 ONNX 策略。使用产出该检查点的同一算法家族与任务 -owner;回放代码加载检查点、导出 `policy.onnx`,并在该路径实现了 ONNX Runtime 检查时 -校验所导出的计算图。 +owner。不同算法路径的导出和校验行为并不相同。 ## 导出路径 | 算法路径 | 入口脚本 | 仓库中的导出行为 | | --- | --- | --- | -| PPO(torch) | `src/unilab/scripts/train_rsl_rl.py` | 脚本入口处 `EXPORT_POLICY=True`;回放调用 `runner.export_policy_to_onnx(...)` 与 `runner.export_policy_to_jit(...)`。 | -| APPO | `src/unilab/scripts/train_appo.py` | 回放写出 `policy.onnx` 并将 ONNX Runtime 输出与 PyTorch 比对校验。 | -| SAC / FlashSAC | `src/unilab/scripts/train_sac.py` / `src/unilab/scripts/train_flashsac.py` | 回放写出 `policy.onnx`;SAC 与 FlashSAC 在导出前使用 `actor.as_export_module()`。 | +| PPO(torch) | `src/unilab/scripts/train_rsl_rl.py` | 作为脚本运行时,入口设置 `EXPORT_POLICY=True`;回放调用 `runner.export_policy_to_onnx(...)` 与 `runner.export_policy_to_jit(...)`。该路径不调用 UniLab 的 ONNX Runtime 校验辅助函数。 | +| APPO | `src/unilab/scripts/train_appo.py` | 回放写出 `policy.onnx`,随后在一个随机输入上比对 ONNX Runtime 与 PyTorch 输出。 | +| SAC / FlashSAC | `src/unilab/scripts/train_sac.py` / `src/unilab/scripts/train_flashsac.py` | `src/unilab/scripts/train_offpolicy.py` 中的共享回放在 `training.export_onnx=true`(默认值)时写出 `policy.onnx`,使用 `actor.as_export_module()`,并执行同样的比对。 | ## 命令 @@ -23,19 +22,25 @@ uv run eval --algo sac --task g1_walk_flat --sim mujoco --load-run -1 ``` `uv run eval` 设置回放模式,并把 `--load-run` 映射到所路由训练脚本使用的检查点 -选择器。导出的文件会写入所选的运行目录。用于部署时,请把导出的 `policy.onnx` 与训练 -它所用的任务 owner YAML 放在一起——该 YAML 是运行时必须复现的观测与动作契约的权威 -来源。 +选择器。导出的文件会写入所选的运行目录。用于部署时,请把 `policy.onnx` 与该运行的 +`run_config.json` 及任务 owner YAML 路径放在一起。composed 运行配置记录了运行时必须 +复现的观测、动作和算法设置。 ## 校验导出的计算图 -回放路径在写出之前会把导出的计算图与 PyTorch 比对,因此导出成功本身已经建立了数值 -一致性。它**没有**建立的是:你的硬件侧回路装配出的输入向量是否相同。在硬件上机前: +不要仅凭 `policy.onnx` 文件存在就推断数值一致。导出与校验都位于非致命回放保护块中。 +对于 APPO/SAC/FlashSAC,辅助函数使用 ONNX Runtime 的 `CPUExecutionProvider` 在一个 +随机输入上比对;最大绝对误差不超过 `1e-4` 时打印 `ONNX export verified OK.`,超出时 +也只打印警告。PPO 回放不执行这项 UniLab 校验。 + +这种单样本比对**不能**证明所有输入都一致,也不能证明硬件回路装配了相同的输入向量。 +SAC/FlashSAC 回放存在观测归一化器时,会在调用导出的 actor 和校验之前应用它,因此 +原始观测的预处理仍属于部署契约。硬件上机前: - 从 composed config 读取 actor 观测宽度(而不是照抄文档表格),确认它与 ONNX 输入宽度一致。 -- 对照 owner 的 `env.observations.actor.terms` 确认分项顺序与逐项历史顺序。G1 - 全身跟踪见 {doc}`2-g1_whole_body`。 +- 对照 `env.policy_observation_group` 指定的 group,确认分项顺序、缩放、归一化和任何 + 逐项历史。G1 全身跟踪见 {doc}`2-g1_whole_body`。 ## 另请参阅 diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/6-domain_randomization.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/6-domain_randomization.md index 954b48069..936c2b554 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/6-domain_randomization.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/6-domain_randomization.md @@ -20,7 +20,7 @@ - 影响平衡与跟踪裕度。 * - 摩擦 - 足 ↔ 地面 μ、手 ↔ 物体 μ - - 手内方块任务没有它就会失败。 + - 改变接触、运动与抓握行为。 * - 观测噪声 - IMU 噪声、关节编码器偏置、部署侧观测历史 - 让 actor 输入贴近部署侧传感器行为。 @@ -46,10 +46,10 @@ Manager-Based 任务在 owner YAML 的 `env.events` 中声明 reset 与 interval legacy 任务级 provider 协议已移除。能力边界见 {doc}`../../4-developer_guide/2-contracts/4-dr_contract`。 -## 配方:起始范围 +## 保留 owner 中的示例 -以所选 owner YAML 为准。以下是一个 PD 增益片段;绝对增益范围应与机器人的 -控制参数一起评估。 +以所选 owner YAML 为准。以下是 `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml` +中的绝对 PD 增益 reset 项,不是建议的硬件范围,也不是经过硬件验证的安全包络: ```yaml env: @@ -58,11 +58,14 @@ env: func: unilab.envs.mdp.pd_gains mode: reset params: - kp_range: [17.5, 70.0] - kd_range: [0.25, 1.0] + kp_range: [31.5, 38.5] + kd_range: [0.45, 0.55] operation: abs ``` +这里 `operation: abs` 采样的是绝对增益,而非标称增益的倍率。其他 owner 可能使用 +`operation: scale`,或在不支持该能力的 backend 上禁用此项。 + ## 课程:随技能逐步加大 DR 在第 0 步就过于激进的 DR 会让学习停滞。UniLab 的课程辅助工具由任务自身拥有;把它们的 diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/7-safety_layers.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/7-safety_layers.md index bfda2341d..20e69cc7b 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/7-safety_layers.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/7-safety_layers.md @@ -1,9 +1,10 @@ # 硬件安全层 -策略在训练契约下产生动作。一个部署侧的安全层必须位于**策略输出与电机驱动器之间**, -并在契约违例成为执行器指令之前将其拒绝。 +策略在训练契约下产生动作。部署侧安全层应位于**策略输出与电机驱动器之间**,在契约 +违例成为执行器指令之前将其拒绝。以下是设计检查清单,不是 UniLab 已实现或已在硬件上 +验证的安全保证。 -## 必备组件 +## 建议的部署侧组件 ```{list-table} :header-rows: 1 @@ -12,58 +13,62 @@ * - 层 - 职责 * - 模式检查 - - 动作具有正确的 dtype、形状、有限值。拒绝 NaN / Inf。 + - 检查动作的 dtype、形状和有限值,拒绝 NaN / Inf。 * - 范围钳制 - - 将每个关节目标钳制到部署配置的关节限位。 + - 将每个关节目标钳制到经过验证的部署侧关节限位。 * - Δ 钳制 - 使用部署控制器拥有的阈值,拒绝或钳制逐步的动作增量。 * - 速率限制 - - 在钳制之后施加变化率限制。 + - 在钳制后施加经过验证的变化率限制。 * - 看门狗 - - 若在控制器拥有的超时内没有新的动作到达,则保持最后一个已知的安全目标,或进入 - 控制器的安全状态。 + - 动作过期时进入控制器定义且已验证对机器人安全的状态;不要假定保持最后目标必然安全。 * - 姿态监控 - - 横滚 / 俯仰超出工作包络 → 触发故障。 + - 横滚 / 俯仰超出经过验证的运行包络时触发故障。 * - 操作员停止 - - 大红按钮 → 立即关闭力矩,无论处于何种状态。 + - 提供独立的停止通路,并依据机器人/控制器安全设计验证其切断力矩的行为。 ``` ## 安全层位于何处 ```{mermaid} flowchart LR - P[Policy ONNX] --> S[Safety layer
C++ on robot computer] - S -->|safe target| D[Motor driver] + P[Policy ONNX] --> S[Deploy-side safety layer] + S -->|checked target| D[Motor driver] D -->|encoder + IMU| Pre[Observation builder] Pre --> P S -.->|fault| OP[Operator UI] - OP -.->|E-stop| D + OP -.->|stop path| D ``` -把硬实时的安全检查放在部署控制器中,而不是训练脚本里。仓库不实现生产级的电机驱动器 -安全回路——该边界由你构建并测试。 +把硬实时的安全检查放在部署控制器中,而不是训练脚本里。仓库不实现生产级电机驱动器 +安全回路、看门狗、姿态监控或急停。软件钳制和策略检查不能替代独立设计的安全功能。 -## 策略假定你已配置的内容 +训练侧 `BaseAction` 会检查动作张量的形状、dtype 和设备,并记录有限值判定。只有配置 +`clip` 时才对仿射输出钳制;保留的 G1/Go2 owner 未配置该键。这些检查不构成硬件安全 +保证。 -策略期望的是其训练 owner 所声明的动作映射与限位: +## 动作映射的输入 + +从所选 owner 和 composed 场景派生部署侧映射: | 量 | 权威来源 | | --- | --- | -| 动作缩放 | `env.actions.joint_pos.scale`(该 owner 为标量 `2.0`;其他 owner 声明按 actuator 解析的正则 → 数值映射) | -| 默认关节角 | `use_default_offset: true`,即 owner 场景 XML 中 `stand` keyframe 的关节段 | -| 关节限位 | 场景 XML 中的 `jnt_range` | -| `kp` / `kd` | 场景 XML 中 position actuator 的 `gainprm` / `biasprm` | +| 动作缩放 | `env.actions.joint_pos.scale`,可以是标量或按 actuator 解析的正则 → 数值映射 | +| 默认关节角 | `use_default_offset: true` 和场景的 `default_keyframe_name`(当前 G1 owner 为 `stand`,Go2 为 `home`) | +| 关节限位 | composed 场景中的关节范围;它们不会自动成为部署侧动作钳制 | +| 标称 `kp` / `kd` | composed 机器人 XML 中 position actuator 的 `kp` / `kv`,以及任何已启用的 `env.events.pd_gains` reset 随机化 | -请从 owner YAML 及其场景派生这些量,并原样复现 owner 解析后的逐 actuator 缩放—— -标量 owner 与正则映射型 owner 不可互换。不要把关节范围或增益手工复制到第二处,那会 -与资产静默漂移。 +必须原样复现 owner 解析后的逐 actuator 缩放,标量与正则映射型 owner 不可互换。对于 +G1 运动跟踪,还要处理运动和编码器偏置项。避免把数值手工复制到另一处,使其与所选资产 +和运行配置静默漂移。 ## 交接测试 -在把 策略 → 安全层 → 电机 集成起来之前,先隔离测试安全层: +在把 策略 → 安全层 → 电机 集成起来之前,先隔离测试安全层。以下是建议的部署侧测试, +不是 UniLab 已在硬件上运行的测试: 1. 注入一个 NaN 动作,验证该指令被拒绝。 -2. 注入一个超范围的关节目标,验证钳制使用了 owner 场景 XML 中的关节范围。 +2. 注入一个超范围的关节目标,验证钳制使用经过验证的关节限位。 3. 在运行途中切断策略输入,验证控制器进入其配置的安全状态。 ## 另请参阅 diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/8-latency_budget.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/8-latency_budget.md index 538216990..ca352da4e 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/8-latency_budget.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/8-latency_budget.md @@ -1,34 +1,46 @@ # 延迟预算 -本页记录仓库中可见的延迟控制项,以及硬件上机前你需要做的部署侧测量。把数值预算当作 -机器人专属的测量结果,而不是 UniLab 的默认值。 +本页记录仓库中可见的延迟控制项,以及硬件上机前需要做的部署侧测量。数值预算应视为 +机器人专属的测量结果,而不是 UniLab 默认值或硬件验证结果。 ## 仓库中的延迟面 -| 面 | 仓库证据 | 它覆盖什么 | +| 延迟面 | 配置与单位 | 行为 | | --- | --- | --- | -| 单步动作延迟 | task owner 中 Manager action term 的 `simulate_action_latency` 声明 | 执行上一步动作而非当前动作。 | -| 观测历史 | task owner 中逐 term 的 `history_length` 声明 | 为选定观测项提供逐项历史。 | -| 观测历史顺序 | `ObservationManager` 逐项历史缓冲(`tests/managers/test_observation_buffers_noise.py`) | actor 观测按逐项最旧优先展平。 | +| 关节位置目标延迟 | `env.actions.joint_pos.delay_min_lag` / `delay_max_lag`,整数个**物理子步** | `JointPositionAction` 延迟处理后的位置目标。 | +| G1 运动单 tick 动作延迟 | `MotionJointPositionActionCfg` 的 `simulate_action_latency`,一个**控制 tick** | 使用上一步原始动作,而非当前原始动作。 | +| 观测延迟 | 逐项 `delay_min_lag` / `delay_max_lag`,整数个**控制步** | `ObservationManager` 在闭区间内采样延迟;min=max 时为固定延迟。 | +| 观测历史 | 逐项 `history_length`,包含当前帧在内的帧数 | 存储并可选展平历史;历史本身不等于额外延迟。 | + +保留的 G1 运动和 Go2 owner 将这些延迟保持为零,且未声明观测历史。它们的 +`env.ctrl_dt` 为 `0.02` s(20 ms,50 Hz),但动作 `delay_*_lag` 使用 `env.sim_dt` +而非 `ctrl_dt`:Go2 的物理子步为 10 ms,G1 运动 owner 为 6.666… ms。观测或单 tick +动作延迟用 `lag * ctrl_dt` 换算,关节目标延迟用 `lag * sim_dt` 换算。 ## 动作延迟 -对于启用 action latency 的 Manager-Based 任务,action manager 会在该开关开启时应用 -上一步 action。把它保留在所选的 task owner YAML 中,而不要事后添加仅部署的行为。 +固定延迟 2 个物理子步的关节位置目标配置为: ```yaml env: actions: joint_pos: - simulate_action_latency: true + delay_min_lag: 2 + delay_max_lag: 2 ``` +对于 G1 运动跟踪,`simulate_action_latency: true` 则每个控制 tick 选择上一步原始 +动作。这是不同的机制和单位,不能把两者的 lag 计数都当作毫秒相加。把所选设置保留在 +任务 owner 中并重新训练,不要事后添加仅部署侧延迟。 + ## 观测滞后与历史 -观测宽度是所声明 actor 各项 `dim * history_length` 之和,硬件运行时不允许猜测。 -带 `history_length` 的项在项内按最旧优先展平,其他项保持单步。 +在所选 policy group 的具体观测项上设置 `delay_min_lag` 和 `delay_max_lag`。除非训练 +owner 这样配置,否则不要让指令/参考项滞后。 -除非训练 owner 这样做了,否则不要让指令/参考项滞后。 +对于 `flatten_history_dim=true` 的拼接展平 group,无历史的项贡献其基础维度,有历史的 +项贡献 `base_dim * history_length`。每项的历史帧按最旧优先展平,各项仍按声明顺序排列 +(`tests/managers/test_observation_buffers_noise.py`)。 ## 部署侧测量 @@ -42,6 +54,8 @@ env: 将观测向量与用同一份任务 owner YAML 构建的仿真回合作对比。如果实测管线需要滤波或 缓冲,请把相匹配的行为编码到任务 owner 中并重新训练,而不是只在部署侧添加。 +`scripts/benchmark/compute/` 下的合成 MLP benchmark 并不测量这条端到端 +传感器到执行器通路。 ## 不匹配的症状 @@ -53,4 +67,5 @@ env: - {doc}`6-domain_randomization` - {doc}`7-safety_layers` -- `src/unilab/managers/event_manager.py` +- `src/unilab/envs/mdp/actions/actions.py` +- `src/unilab/managers/observation_manager.py` diff --git a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/9-troubleshooting.md b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/9-troubleshooting.md index 01c86f5a2..f549df129 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/9-troubleshooting.md +++ b/docs/sphinx/source/zh_CN/3-deployment/1-sim_to_real/9-troubleshooting.md @@ -1,35 +1,35 @@ # 仿真到真机故障排查 -一本 症状 → 可能原因 → 修复 的手册。当部署出岔子时,从这里开始。 +一本 症状 → 可能原因 → 检查 的手册。 ## 高频关节振荡 / "嗡鸣" -| 可能原因 | 检查 | 修复 | +| 可能原因 | 检查 | 下一步 | |---|---|---| -| 状态估计器速度偏置 | 记录 `base_lin_vel` 与真值(动作捕捉) | 调整状态估计器 | -| PD 增益相对训练值过高 | 将驱动器 Kp/Kd 与 owner YAML 比较 | 匹配训练值;或用真实的 Kp/Kd DR 重新训练 | -| 训练中动作延迟过低 | 在 DR 中扫动 `torque_delay_ms` | 用 实测延迟 × 1.5 重新训练 | -| 速度噪声过低 | 比较仿真与硬件中的编码器 σ | 在 DR 中增大 `joint_vel_noise_std` | +| 状态估计器速度偏置 | 如果 actor 使用 `base_lin_vel`,将其与独立测量比较 | 调整估计器,或按部署估计器可提供的观测重新训练 | +| PD 增益与训练不同 | 将驱动器 Kp/Kd 与场景标称增益及 owner 的 `env.events.pd_gains` 范围比较 | 匹配训练值,或按实测增益变化重新训练 | +| 动作延迟与训练不同 | 将实测目标延迟与 `delay_min_lag` / `delay_max_lag`(物理子步)或 G1 运动的 `simulate_action_latency`(一个控制 tick)比较 | 用正确单位匹配实测延迟并重新训练 | +| 速度噪声与训练不同 | 将编码器噪声与 `env.observations..terms.joint_vel.noise` 比较 | 调整所选 owner 的噪声模型;`UniformNoiseCfg` 使用 `n_min` / `n_max`,不存在 `joint_vel_noise_std` 配置键 | ## 站立 / 行走时漂移 -| 可能原因 | 检查 | 修复 | +| 可能原因 | 检查 | 下一步 | |---|---|---| -| IMU 偏置未标定 | 机器人静止,检查 `gyro_bias` | 在策略启动前运行 30 秒标定 | -| 足端接触分类错误 | 检查接触事件时间戳 | 对接触力阈值加滞回 | +| IMU 偏置未标定 | 在机器人静止时记录陀螺仪输出 | 按机器人/SDK 的标定流程操作;UniLab 不定义通用的 30 秒标定 | +| 足端接触分类错误 | 在所选任务使用接触时检查接触事件时间戳 | 验证部署侧接触来源及任何阈值滞回 | ## 策略在仿真中成功,在硬件上立即跌倒 -几乎总是以下之一: +首先检查以下契约错误: -1. **关节顺序被调换。** 检查 `policy.onnx` 的输入宽度,并将你电机驱动器中的关节顺序 - 与训练场景 XML(`src/unilab/assets/robots//scene_flat.xml`)对照。 -2. **动作缩放单位不匹配。** 策略输出未缩放的值;驱动器期望的是弧度,而你喂给它的 - 是归一化的 [-1, 1]。在把目标发送给驱动器之前,应用训练 owner YAML 中的 - `env.actions.joint_pos.scale` / 默认角度约定,并原样复现该 owner 解析后的 - 逐 actuator 缩放。 -3. **观测布局不匹配。** 将硬件回路装配出的内容与 owner 的 - `env.observations.actor.terms` 比较——先比分项顺序,再比逐项历史顺序。 +1. **关节顺序被调换。** 检查 `policy.onnx` 的输入/输出宽度,并将电机驱动器顺序与 + `env.scene.entities.robot.joint_names`、`actuator_names` 及所选的 + `env.scene.model_file` 对照。 +2. **动作缩放或单位不匹配。** 原始 actor 输出不一定归一化到 [-1, 1]。向驱动器发送 + 以弧度为单位的关节位置目标之前,应用所选 owner 的 `env.actions.joint_pos.scale`、 + 默认偏移以及任何运动/编码器偏置约定。 +3. **观测布局不匹配。** 将硬件向量与 `env.policy_observation_group` 指定的 group + 比较——依次检查分项顺序、缩放和任何逐项历史顺序。 ## 策略在 MuJoCo 中成功但在 Motrix 中失败(或反之) @@ -39,14 +39,17 @@ ## 提交 bug 报告前应捕获什么 -当实验室微信群在晚上 11 点炸开时,保存以下内容,好让明天的排查只花 30 分钟而不是 -4 小时: - - 完整的硬件轨迹(整段运行的 `obs / action / wall_clock`)。 -- 用于训练的仿真侧 YAML:`runs//config.yaml`。 +- 所选运行的 `run_config.json`;默认运行目录位于 + `logs////`。 - `policy.onnx`,以及训练它所用的确切任务 owner YAML 路径。 -- 一段使用**同一**种子的仿真回合视频:`eval --seed - --render-mode record`。 +- 从该检查点生成、显式记录种子的仿真回合视频: + + ```bash + uv run eval --algo --task --sim \ + --load-run -1 --render-mode record algo.seed= + ``` + - 如果有的话,该运行所在 commit 与 `main` 之间的 `git diff`。 ## 另请参阅 diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/0-index.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/0-index.md index 43c65be22..47dd21cd4 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/0-index.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/0-index.md @@ -1,6 +1,6 @@ # Sim-to-Sim -通过 owner YAML 和 backend contract,在 MuJoCo 与 Motrix 之间迁移同一个任务。 +通过 owner YAML 和 capability contract 在受支持的物理后端之间迁移任务,并分别检查策略 I/O、物理、reward 和回放。 ::::{grid} 1 1 2 2 :gutter: 3 @@ -29,10 +29,10 @@ 检查后端边界附近的 reward 项。 ::: -:::{grid-item-card} 回放差异 +:::{grid-item-card} 回放与快照 :link: 5-playback_and_snapshot_differences :link-type: doc -理解渲染器与快照能力上的差异。 +区分渲染路径、物理状态快照和训练配置快照。 ::: :::{grid-item-card} 能力缺口 diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/1-backend_swap.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/1-backend_swap.md index bef54cb34..7454c1c99 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/1-backend_swap.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/1-backend_swap.md @@ -1,47 +1,55 @@ # 切换后端 -UniLab 支持两个 CPU 物理后端:**MuJoCo**(通过官方 `mujoco` 包加 -`mjbatch` batch 引擎)和 -**Motrix**(通过 `motrixsim-core`)。两者实现了相同的 `SimBackend` -contract 和相同的 env contract。后端特有的行为通过显式方法和能力记录 -(capability records)暴露出来。 +UniLab 的 registry 和 CLI 当前识别 `mujoco`、`mjwarp`、`genesis`、`newton`、 +`motrix`、`mtxwarp`、`superdex`、`drake`、`isaacsim` 和 `isaacgym`。实际支持由 +算法/任务/后端 owner YAML、已注册的环境工厂以及任务所需能力共同决定。 -| 维度 | MuJoCo | Motrix | -|---|---|---| -| 后端类 | `unisim.backend.mujoco.backend` | `unisim.backend.motrix.backend` | -| 回放能力 | `get_play_capabilities()` 中的物理状态回放 | `get_play_capabilities()` 中的原生交互式渲染器与原生视频采集 | -| 高度场扫描 | 实现 `bind_height_scanner(...)` | 实现 `bind_height_scanner(...)` | -| DR 能力上报 | `get_dr_capabilities()` | `get_dr_capabilities()` | +后端特有行为必须放在 `unisim.backend.base.SimBackend` 和 owner 配置之后,不能在环境热 +路径中新增后端分支。 -**切换后端的正当理由**是以下之一: +例如,两个 CPU host-bridge 后端在当前 UniSim 适配器中暴露以下能力: -1. 目标任务已经有针对另一个后端的 owner YAML。 -2. 该后端暴露了工作流所需的能力。 -3. 你想在部署或更换后端之前做一次 sim-to-sim 一致性检查。 +| 维度 | MuJoCo | Motrix | +|---|---|---| +| 适配器模块 | `unisim.backend.mujoco.backend` | `unisim.backend.motrix.backend` | +| 物理状态回放 | 支持 | 支持 | +| 原生交互渲染器 / 视频采集 | 不支持 | 支持,whole-model-variant 模式除外 | +| 高度场扫描 | `bind_height_scanner(...)` | `bind_height_scanner(...)` | +| DR 支持 | 运行时 `get_dr_capabilities()` | 运行时 `get_dr_capabilities()` | -切换始终是一次任务 owner 的变更,而不是临时的运行时调整。 +这些能力值不等同于任务支持或物理一致性。其他后端具有不同的回放配置;参见 +{doc}`5-playback_and_snapshot_differences` 和 {doc}`6-capability_gaps`。 ## 如何切换 -UniLab **不**支持通过透传式(passthrough)Hydra override 来选择后端。后端是由 -`--task` 和 `--sim` 选定的 *任务 owner 身份* 的一部分: +使用 CLI 标志选择算法、任务和后端: ```bash -# wrong — backend is not an override -uv run train --algo ppo --task go2_joystick_flat --sim mujoco training.sim_backend=mujoco - -# right — choose the backend with --sim -uv run train --algo ppo --task go2_joystick_flat --sim mujoco uv run train --algo ppo --task go2_joystick_flat --sim mujoco +uv run train --algo ppo --task go2_joystick_flat --sim motrix +``` + +`--task` 与 `--sim` 共同选择 owner 身份。CLI 会拒绝把透传的 `task` 和 +`training.sim_backend` override 用作后端选择机制。上述命令对应的 owner 分别是 +`src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml` 和 +`src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml`。 + +训练要求所选 owner YAML 必须存在。评估在目标 owner 缺失时有一条有限的回退路径:可以 +复用同任务的兄弟 owner,随后仍执行相同的契约预检。该回退不能证明目标后端支持此任务, +也不是通用的后端开关;参见 {doc}`7-config_guard`。 + +复用 checkpoint 前,先审计组合后的策略 I/O 契约,再执行任务特定的物理和 reward 检查: + +```bash +uv run scripts/audit_sim2sim_contracts.py --trees ppo ``` -CLI 会把 `--algo`、`--task` 和 `--sim` 解析为一个 owner YAML,例如 -`src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml`。如果该文件不存在,则说明该任务 -**不支持**这个后端 —— 参见 -{doc}`../../4-developer_guide/2-contracts/3-task_owner`。 +审计的 `TRANSFERABLE` 结论只覆盖脚本实际比较的字段,不能证明接触、reward、收敛或渲染器 +一致性。 ## 另请参阅 - {doc}`2-owner_yaml_swap` - {doc}`4-reward_parity` - {doc}`6-capability_gaps` +- {doc}`7-config_guard` diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md index cdc825d8a..c49ca346b 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/2-owner_yaml_swap.md @@ -1,51 +1,78 @@ # 为已有任务添加后端 YAML -假设你有一个跑在 Motrix 上的任务,现在想让它也能跑在 MuJoCo 上。本页 -就是操作配方。 +当任务已经有 canonical owner 契约、需要新增另一个后端时,使用本流程。共享契约放在 +`base.yaml`;每个后端 leaf 只拥有后端身份、调参、渲染/设备放置以及显式能力适配。 ## 不应该做的事 -- 在 Python 中添加后端分支。后端特有的行为属于后端适配层和 owner YAML, - 绝不能写进 env 代码。这是 - {doc}`../../4-developer_guide/2-contracts/2-backend_contract` 的铁律。 -- 把 `training.sim_backend` 当作 override 来设置。该字段是 owner YAML 的 - **身份回显(identity echo)**,不是切换开关。 - -## 应该做的事 - -1. 复制已有的 owner YAML: - ```bash - cp src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml \ - src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml - ``` -2. 在新文件里,设置 `training.sim_backend: mujoco`。 -3. 调整新后端所需的**物理参数**: - - 接触摩擦 / 阻尼 —— MuJoCo 对每个接触对使用 solver 参数;Motrix 使用材质 - 属性(material props)。确保你位于 - `src/unilab/assets/robots//` 下的任务资源文件声明了该后端所需的值。 - - Solver 设置与 timestep —— 把它们放在拥有该行为的 owner YAML 或后端适配层中。 -4. 重新核定任何依赖后端的 DR 范围。某些随机化在一个后端上有意义,但在另一个后端上 - 是空操作(no-op)(例如摩擦阻尼系数)。 -5. 验证该 env/backend 组合已经注册,并且可以通过 registry bootstrap 导入(参见 - {doc}`../../4-developer_guide/1-architecture/5-registry`)。 +- 不要在环境或训练代码中按后端名称分支。所需行为必须通过 `SimBackend` 暴露,并通过其 + capability 协商。参见 + {doc}`../../4-developer_guide/2-contracts/2-backend_contract`。 +- 不要把 `training.sim_backend` 当作独立的 CLI override。它在后端 leaf 内是身份声明, + 公共选择器是 `--sim`。 +- 不要让一个后端 leaf 继承另一个后端 leaf。跨后端继承会隐藏组合任务契约的变化。 + +## Owner 布局 + +对于 `src/unilab/conf//task//`: + +1. 在 `base.yaml` 中保存完整的共享 scene、observation、action、command、reward、 + termination、canonical event 和共享训练预算。base 文件不是可训练 owner,不包含 + `training.sim_backend`。 +2. 新增 `.yaml`,其 `defaults:` 只包含同目录 base 和 `_self_`。在 leaf 自身 + 声明 `training.task_name` 与 `training.sim_backend`。 +3. leaf 只写真正的后端差异:timestep/solver/容量字段、渲染设置、算法调参,以及需要收窄 + 或用 `null` 显式禁用的 event term。 + +最小 leaf 的结构如下: + +```yaml +# @package _global_ +defaults: + - /task/go2_joystick_flat/base + - _self_ + +training: + task_name: Go2JoystickFlat + sim_backend: motrix + +# 此处只添加后端拥有的调参或显式 event 适配。 +``` + +不要为了让回放通过而复制另一个后端的 command range、reward weight 或 observation +normalization。这些值定义任务行为,而不是渲染设置。组合规则及其测试见 +{doc}`/adr/ADR-0023-task-sim-owner-inherits-same-directory-base-only`。 + +## 物理与能力审查 + +- 显式检查 `env.sim_dt` 和 `env.ctrl_dt`,确认两者比值给出预期的控制 decimation。 + `env.motrix_max_iterations`、`env.genesis_integrator`、 + `env.genesis_solver_iterations`、`env.mjwarp_nconmax`、`env.mjwarp_njmax` + 等字段只用于拥有它们的后端。 +- 审查任务/机器人 XML 中的摩擦、接触 solver、传感器、执行器模型和 reset 默认值。共享 + MJCF 不表示导入后的物理行为一致。 +- 用 `get_dr_capabilities()` 检查每个请求的 DR term。如果目标后端无法实现,要么扩展公共 + backend contract,要么在目标 leaf 中显式禁用/收窄该 event 并记录训练差异。不支持的 + capability 不得静默变成 no-op。 +- 为新后端注册任务的通用 Manager-Based 工厂。缺少所需 capability 时,应在冷路径绑定阶段 + 失败,不能探测 backend 私有对象。 ## 验证闸门 -在声称该后端受支持之前,你(至少)需要: +组合新 owner,在真实已注册后端上执行 reset,再进行多次张量 step。随后按 +{doc}`3-contact_and_friction_alignment` 和 {doc}`4-reward_parity` 比较名义接触和 reward +分量。 -- 一次达到与参考后端相同成功阈值的训练运行,*或者*一份说明它为何达不到的文档 - (例如能力缺口)。 -- Reward 一致性检查:参见 {doc}`4-reward_parity`。 -- 在 `tests/` 下新增一个测试:用新后端导入该 env,并无错误地运行 - `reset` + `step(10)`。 +审计所有相关 owner 树,而不只是新文件: -::::{admonition} 证据等级 -:class: note -验证之后,如果支持状态发生了变化,刷新生成的支持数据: +```bash +uv run scripts/audit_sim2sim_contracts.py --trees ppo appo sac flashsac +``` + +审计只比较固定的后端对。`N/A` 表示没有可审计的后端对,不表示支持迁移; +`TRANSFERABLE` 也只是策略契约结论。支持声明仍需要运行时和任务证据。支持状态变化时, +刷新生成的支持数据: ```bash uv run scripts/generate_support_matrix.py --write ``` - -证据等级的定义参见 {doc}`/glossary`。 -:::: diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md index 1a0834118..796029104 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/3-contact_and_friction_alignment.md @@ -1,35 +1,51 @@ # 在后端之间对齐接触与摩擦 -接触处理是 MuJoCo 与 Motrix 之间产生漂移的常见来源。本页教你如何识别并消除 -这一差距。 +接触导入、solver 行为和传感器语义是跨后端漂移的常见来源。应先对齐这些内容,再解释 +reward 或策略回报曲线。 -## 诊断:尽早探测接触 +## 诊断协议 -在两个后端中运行同一份 owner YAML、相同的复位种子(reset seed)以及确定性的 -动作序列。从 `info["log"]` 记录依赖接触的 reward 项,以及 env 已经使用的任何 -后端拥有的接触信号。如果在策略学习介入之前,名义接触响应就已经不同,那么先修正 -摩擦 / 阻尼 / 恢复系数(restitution)的声明,再去调试 reward 一致性。 +分别组合各后端自己的 owner,不要把源后端 leaf 当作 Hydra override 复用。固定 owner +seed;需要精确比较初始状态时,还要设置相同的显式 reset state。随后回放相同的确定性 +动作张量序列。 -## 常见陷阱 +逐步记录任务使用的接触传感器,以及可用时的 `state.info["reward_components"]`。后者是 +环境 `dt` 缩放前的全宽度加权 reward 张量。`env.publish_reward_log()` 返回对应的逐项均值, +键名为 `reward/`。不能假设每条训练路径的 `info["log"]` 都包含逐项 reward:原生 +RSL-RL PPO 日志不会输出这些 TensorBoard 键。 -| 陷阱 | 表现 | 修复 | +应检查首个发生分歧的 transition,而不是只比较最终 episode return。轨迹一旦分叉,后续 +差异就无法再单独定位某个接触参数。 + +## 对齐清单 + +| 方面 | 核对内容 | 当前 owner 边界 | |---|---|---| -| 在 MuJoCo 中摩擦声明在 geom 上,而在 Motrix 中声明在 material 上 | 某个后端出现 μ=0 | 两边都声明;在场景导出中核对 | -| Solver 迭代次数过低 | MuJoCo 陷入地面 | 在 owner YAML 中调高后端拥有的 solver 设置 | -| 接触对特定的 override | 打滑不一致 | 在两个后端 YAML 中都显式写出接触对级别的 override | -| 恢复系数不匹配 | 落地一边弹跳、一边粘滞 | 显式设置;默认值不同 | +| Geom 摩擦 | 三个摩擦系数、所选 geom、碰撞掩码和接触对行为 | 任务/机器人 XML 及后端导入值 | +| Solver 与积分 | Timestep、积分器、迭代次数、接触容量和约束行为 | `env.sim_dt`、`env.ctrl_dt`,以及 `env.motrix_max_iterations`、`env.genesis_solver_iterations`、`env.mjwarp_nconmax`、`env.mjwarp_njmax` 等后端字段 | +| 柔性与恢复 | Solver reference/impedance 和 restitution 行为,而不只是名义摩擦 | 资产声明和后端导入/物化证据 | +| 接触观测与 reward | 传感器类型、力/接触阈值、坐标系和更新时序 | 公共具名传感器绑定及 `env.observations` / `reward` 中的 term | + +不存在适用于所有引擎接触参数的通用换算。任何近似都必须显式写入目标 owner;例如, +SuperDex Go2 owner 设置 `env.superdex_allow_contact_approximation: true`,而不是声称与 +MuJoCo 接触等价。 ## 对齐 DR 范围 -一旦**名义**参数的接触已经对齐,就审查 DR: +当前 Manager-Based 摩擦 DR 使用 `env.events.` term,并设置 +`func: unilab.envs.mdp.geom_friction`。其 `params` 包括 `ranges`、`operation`、可选的 +`axes` 和 `shared_random`;不使用 `friction_static_mu` 或 `friction_dynamic_mu` 字段。 + +检查实际随机流、所选 geom ID、默认值和后端 capability。不支持的 term 会在 capability +绑定时 fail closed,不会成为只发警告的 no-op。后端 leaf 可以显式禁用不支持的 event,但 +这会改变训练分布,必须据此审查。例如,当前 SAC/FlashSAC G1 motion owner 在 Genesis 上 +禁用 `foot_friction`,Motrix owner 则禁用 `push_robot`。 -- `friction_static_mu` 和 `friction_dynamic_mu` 在两个后端中应当以相同方式 - 采样。 -- 如果某个 DR 字段在一个后端中是空操作(no-op),就在 episode 初始化时记录一条 - 警告。无声的忽略会导致无声的 reward 漂移。 +名义接触和 DR 对齐后,执行 {doc}`4-reward_parity` 中的协议。配置守卫通过并不执行上述 +任何物理检查。 ## 另请参阅 +- {doc}`2-owner_yaml_swap` - {doc}`4-reward_parity` -- {doc}`../1-sim_to_real/6-domain_randomization` - {doc}`6-capability_gaps` diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/4-reward_parity.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/4-reward_parity.md index 58ade07d9..bb5bcb98c 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/4-reward_parity.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/4-reward_parity.md @@ -1,42 +1,52 @@ # 跨后端的 Reward 一致性 -两个拥有"相同" reward 函数的后端,很少会产生**数值上完全相同**的 reward —— -这没关系。你想要的是**轨迹级别的一致性(trajectory-level parity)**:同一个策略, -施加到相同的初始状态上,会产生相似的 reward 曲线。 +共享 reward 声明并不保证数值完全一致。物理、传感器时序和接触行为都可能分叉。有效的 +检查是先做固定 transition 对比,再按任务显式定义的容差做轨迹级评估。 ## 协议 -1. 冻结一个**固定种子**、固定的初始状态、固定的动作序列。 - 动作序列可以是对各关节的正弦扫频,也可以是来自真实 rollout 的回放 —— - 只要是确定性的即可。 -2. 在两个后端中回放它。从 `info["log"]` 记录每一步的 reward 分量;当 reward - 日志开启时,locomotion 的 reward 分发会在那里写入 `reward/` 条目。 -3. 对每个 reward 项,比较两条时间序列,并检查它们开始分叉的第一帧。 +1. 分别组合两个目标 owner。固定 seed、初始/reset state、动作序列、观测输入和 command + 输入。使用已记录的 rollout 或其他确定性动作张量序列。 +2. 在两个后端回放,并检查首个分叉的 transition。记录总 reward 和每个 reward 分量, + 再比较长 episode return。 +3. 在该 transition 核对单位、坐标系、接触时序、termination/truncation mask 和最终观测。 + 随后比较完整轨迹,并为任务定义可接受的容差。 -## 良好的一致性是什么样的 +Manager-Based 环境在 `state.info["reward_components"]` 中暴露全宽度加权分量。 +`env.publish_reward_log()` 以 `reward/` 暴露逐项均值,这些值位于环境 `dt` 缩放 +之前。默认 `env.scale_rewards_by_dt: true` 时,总 `state.reward` 还包含额外的 +`env.ctrl_dt` 乘数。比较时必须考虑这一差异,不能把 `dt` 前分量直接与总 reward 对比。 -| 项的类型 | 检查什么 | +SAC/FlashSAC off-policy 日志会发布这些逐项指标。RSL-RL PPO 与当前 Manager-Based +APPO 不输出逐项 reward 键,因此这两条路径的一致性检查应直接探测环境,而不是在 +训练日志中查找这些键。 + +## 结果解释 + +| 观察到的现象 | 优先检查 | |---|---| -| 平滑惩罚项 | 单位、帧以及命令输入是否相同。 | -| 接触条件项 | 两个后端中的接触时序与传感器可用性。 | -| 终止惩罚项 | 终止掩码(termination mask)与最终观测(final-observation)路径。 | +| 平滑惩罚立即不同 | 单位、动作缩放、command 值、观测坐标系和 `ctrl_dt` | +| 接触条件项不同 | 传感器可用性、阈值、接触时序和更新顺序 | +| 终止惩罚不同 | 非 timeout 的 termination 与 timeout mask、最终观测处理 | +| 起初一致、随后分叉 | 首个物理/接触分叉;后续 return 不是独立的 reward 检查 | +| 某项为零或缺失 | owner 是否禁用,以及所需后端 capability 是否存在 | -## 哪些是危险信号 +不能仅凭轨迹后段分叉就断定 reward 实现有误,也不能不检查 owner 和传感器绑定就把零值 +解释为 capability 缺失。 -- **reward 在 episode 后期出现分叉。** 通常意味着策略在每个后端中探索了不同的 - 状态分布,而这通常又意味着接触 / 摩擦不匹配。参见 - {doc}`3-contact_and_friction_alignment`。 -- **某个 reward 项在某个后端中恒为零。** 能力缺口:该项读取了某个后端不暴露的 - 特性。参见 - {doc}`6-capability_gaps`。 +## 自动化与守卫边界 -## 自动化 +仓库没有独立的 reward 一致性脚本。应在 `tests/` 中把确定性比较放在 task/backend +边界附近,并对显式选择的分量和容差做断言。 -仓库目前没有在 `scripts/` 中提供独立的 reward 一致性辅助工具。在新增一致性覆盖时, -让测试贴近 backend/task-owner 边界:组合两份 owner YAML,用固定种子复位,回放一段 -确定性的动作序列,并在 `tests/` 下对记录下来的 reward 分量做断言。 +`uv run scripts/audit_sim2sim_contracts.py` 是配置审计,不执行上述 reward 检查。其 +`WARNING_LIST` 只包含 `reward.scales`、`reward.base_height_target`、 +`reward.max_tilt_deg`、`reward.min_base_height` 和历史动作延迟字段。当前完整的 +Manager-Based `reward` mapping(包括 `reward..weight`)不会整体写入 sim2sim +快照。因此,即使配置守卫通过,reward 一致性检查仍然必要。 ## 另请参阅 - {doc}`3-contact_and_friction_alignment` +- {doc}`7-config_guard` - {doc}`../../4-developer_guide/2-contracts/2-backend_contract` diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md index 01ca06e55..96bf80f0d 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/5-playback_and_snapshot_differences.md @@ -1,35 +1,53 @@ # 回放与快照差异 -除了物理步进本身之外,两个后端在**如何让你回放**一次运行这件事上也有所不同。 -本页记录其中的实际影响。 +回放包含两个相互独立的选择:哪个后端推进物理,以及哪个渲染器呈现状态。不能由其中一个 +推断另一个。`--sim` 选择物理 owner;`--render-mode` 选择回放路径。 -## 回放 +## 当前回放配置 -| 后端 | 机制 | 最适合 | -|---|---|---| -| MuJoCo | 由 `supports_physics_state_playback` 上报的物理状态回放路径 | 录制模式回放与离线视频导出 | -| Motrix | 由 `get_play_capabilities()` 上报的原生交互式渲染器与原生视频采集 | 交互式回放与录制模式采集 | +| 后端 | 物理状态回放 | 原生交互渲染 / 视频 | UniLab 回放路径 | +|---|---|---|---| +| MuJoCo | 支持 | 否 / 否 | 共享 MuJoCo 交互和离线渲染 | +| MJWarp | 支持 | 否 / 否 | MJWarp 物理加共享 MuJoCo 渲染;owner 通常显式使用 `record` | +| Motrix | 支持 | 支持 / 支持,whole-model-variant 模式除外 | 原生 `interactive` / `record`,或受支持时的物理状态前端 | +| Genesis | UniSim 适配器支持 | 支持 / 支持 | 原生 `interactive` / `record`;顶层 `eval --render-mode viser` 当前显式拒绝 Genesis | -两个后端都通过 `SimBackend.resolve_play_render_plan(...)` 解析 -`training.play_render_mode`;不受支持的模式应当在后端边界处失败,而不是在训练 -脚本里分支。 +原生后端回放通过 `SimBackend.resolve_play_render_plan(...)` 解析 +`training.play_render_mode`,不支持的模式在该边界失败。Viser 是 UniLab 层的例外:它使用 +物理状态回放契约和逐环境 MuJoCo 回放模型,绕过后端原生 render-plan resolver,并且不录制 +视频。 -## 快照 +使用顶层 CLI,以确保 owner 组合、play-only 注入和契约预检全部执行: -MuJoCo 目前上报 `supports_physics_state_playback=True`。而 Motrix 上报的是 -原生交互式渲染与原生视频采集。请把它们当作不同的后端能力,而不是特性对等。 +```bash +# 用 MJWarp 物理和共享 MuJoCo 渲染器录制 G1 rollout。 +uv run eval --algo ppo --task g1_walk_flat --sim mjwarp --load-run -1 --render-mode record -能力边界 contract -({doc}`../../4-developer_guide/2-contracts/2-backend_contract`)要求 *env 代码* -和算法代码**都不得**直接调用仅快照可用的路径 —— 必须通过一个能力感知 -(capability-aware)的抽象来路由。ADR-0002 将此固化为规范。 +# 用 MuJoCo 物理进行浏览器回放;需要支持的 checkpoint/run。 +uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 --render-mode viser +``` -## 应该在任务 owner 里放什么 +`scripts/play_viser.py` 是源码检出中指向 packaged viewer 的包装器。打包实现位于 +`src/unilab/scripts/play_viser.py`,其 session 组装共享 +`src/unilab/visualization/interactive_playback.py`。这些是实现证据,不能替代上面的标准 +`uv run eval` 命令。 -如果某个任务开始需要某种回放或快照能力,先把这一需求加入 backend contract, -然后在 env/backend 边界处验证它。不要把该需求藏在训练脚本的某个分支里。 +## “快照”的两种含义 + +**物理状态快照**是后端分离的 `[time, qpos, qvel, ...]` 表示,供交互/Viser 渲染使用。 +它属于渲染/诊断 host 边界。可用性由 +`get_play_capabilities().supports_physics_state_playback` 上报;viewer 在应用快照前还会 +检查状态布局和回放模型。 + +**训练配置快照**是 run 的 checkpoint 旁的 `run_config.json`。`ExperimentTracker` 在训练 +开始时写入其中的 `contract_snapshot` mapping。它用于策略 I/O 校验,不能用于恢复或渲染 +物理状态。参见 {doc}`7-config_guard`。 + +环境和算法代码都不能调用后端私有的 snapshot 或 renderer 方法。新需求必须进入公共后端 +能力契约;不支持的组合应直接失败,不能静默更换渲染器或物理后端。 ## 另请参阅 - {doc}`6-capability_gaps` +- {doc}`7-config_guard` - {doc}`/adr/ADR-0002-backend-capability-boundary-for-play-and-snapshot` diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/6-capability_gaps.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/6-capability_gaps.md index 0888467c1..60ae734da 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/6-capability_gaps.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/6-capability_gaps.md @@ -1,60 +1,79 @@ # 能力缺口 -一张持续维护的表格,记录通过 `SimBackend` 及当前后端实现暴露出来的后端能力。 -当某项能力被加入或从 backend contract 中移除时,请更新本页。 +本页记录当前回放、地形和 DR 契约中一组有测试证据的缺口。任务支持仍需要 +owner YAML、注册信息和运行时证据。 + +## 回放与高度扫描 ```{list-table} :header-rows: 1 -:widths: 30 15 15 40 +:widths: 30 14 14 18 24 * - 能力 - MuJoCo + - MJWarp - Motrix - - 备注 + - Genesis * - `supports_physics_state_playback` - 是 - - 否 - - 由 `get_play_capabilities()` 上报。 + - 是 + - 是 + - 是 * - `supports_native_interactive_renderer` - 否 + - 否 + - 有条件 - 是 - - 由 `get_play_capabilities()` 上报。 * - `supports_native_video_capture` - 否 + - 否 + - 有条件 - 是 - - 由 `get_play_capabilities()` 上报。 * - `bind_height_scanner(...)` - 是 + - 否 - 是 - - 后端拥有的高度场扫描器,用于崎岖地形观测。 -* - `apply_interval_randomization(...)` - - 是 - - 是 - - 受支持的字段仍取决于各后端的 `get_dr_capabilities()`。 -* - 位置执行器增益 DR - - 是 - - 有条件 - - Motrix 通过运行时能力检测上报支持情况。 -* - Geom 摩擦 DR - - 是 - - 有条件 - - Motrix 通过运行时能力检测上报支持情况。 + - 否 ``` -把 `unisim.backend.base` 作为 contract 的来源,把 `tests/base/` -下的后端测试作为支持声明的证据。 +Motrix 在 whole-model-variant 模式下关闭两个原生渲染标志。虽然 Genesis 适配器声明支持 +物理状态回放,顶层 CLI 当前仍拒绝 Genesis 的 `eval --render-mode viser`,并指引用户使用 +原生渲染器。这些差异由 UniSim 适配器、`src/unilab/cli.py` 以及 +`tests/base/test_mjwarp_playback.py`、`tests/base/test_mjwarp_capabilities.py`、 +`tests/base/test_genesis_backend.py`、`tests/base/test_motrix_backend_options.py` +等测试共同定义。 + +## DR 是运行时能力集合 + +基础接口存在 `apply_interval_randomization(...)`,不表示每个 DR 字段都已实现。必须检查 +具体后端的 `get_dr_capabilities()`,并在冷路径绑定每个请求的 term。缺少 capability 时 +会 fail closed,不会成为只发警告的 no-op。 + +当前 owner 示例显式记录了这些缺口: + +- SAC/FlashSAC G1 motion owner 在 Genesis 上禁用 `foot_friction`,因为缺少所需的逐环境 + geom 摩擦操作。 +- Motrix G1 motion owner 禁用 `push_robot`;MJWarp owner 把角速度 push 分量收窄为零, + 因为缺少该能力。 +- Motrix 的位置执行器增益和 geom 摩擦支持取决于运行时 capability 检测,并非所有模式下 + 都普遍可用。 + +禁用或收窄 event 可以形成有效的训练配置,但会改变训练分布,不等同于物理或 reward +一致性。应在 owner 中记录该差异,并重新执行名义和随机化条件下的一致性检查。 -## 如何更新本页 +## 契约与配置审计的边界 -当你添加或移除某项能力时: +配置守卫只覆盖选定的策略 I/O 字段,不覆盖所有后端特性。 +`scripts/audit_sim2sim_contracts.py` 同样只比较其配置的后端对,没有适用后端对时报告 +`N/A`。这些结果都不能证明任务的传感器、地形、DR、接触、渲染器或收敛得到支持。 -1. 更新上面的表格。 -2. 如果该变更引入了新的 contract,则在 {doc}`/adr/ADR-0000-index` 下添加或更新 - 相关的 ADR。 -3. 在 `tests/base/` 下添加或更新后端测试。 -4. 在 changelog 中提及对用户可见的变更(参见 {doc}`/changelog`)。 +接口以 `unisim.backend.base` 为准,实现证据以具体 UniSim 适配器和 `tests/base/` 为准, +支持声明以生成的支持矩阵为准。capability 变化时,应更新适配器、测试和相关支持证据, +不能把本页当作唯一事实来源。 ## 另请参阅 - {doc}`1-backend_swap` +- {doc}`5-playback_and_snapshot_differences` +- {doc}`7-config_guard` - {doc}`../../4-developer_guide/2-contracts/2-backend_contract` diff --git a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/7-config_guard.md b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/7-config_guard.md index 7a74b17e1..64d3afdfb 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/7-config_guard.md +++ b/docs/sphinx/source/zh_CN/3-deployment/2-sim_to_sim/7-config_guard.md @@ -1,51 +1,90 @@ # 跨后端配置守卫 -跨后端回放(在一个后端训练、到另一个后端 `eval`)时,UniLab 会自动校验目标后端配置与训练时的策略契约是否兼容,避免用错配置静默加载出行为异常的策略。整个过程无需手动干预。 +使用另一个 owner 回放 checkpoint 时,UniLab 会把目标配置与训练时捕获的策略契约进行比较。 +检查在创建环境前执行;checkpoint 加载时还有第二层维度检查。两项检查都不能证明物理或 +reward 一致性。 -## 一个可成功回放的例子 +## 仓库测试覆盖的示例 -`go2_joystick_flat` 的 MuJoCo 与 Motrix owner 在守卫字段上完全一致,因此跨后端回放可以直接通过: +`g1_walk_flat` 的 MuJoCo 和 Genesis owner 在受守卫字段上保持一致。该组合由 +`tests/training/test_sim2sim_resolver.py` 和只读 owner 审计共同覆盖: ```bash -# 1) MuJoCo 训练,产生 checkpoint -uv run train --algo ppo --task go2_joystick_flat --sim mujoco +# 先用 MuJoCo 训练,再用 Genesis 回放生成的 run。 +uv run train --algo ppo --task g1_walk_flat --sim mujoco +uv run eval --algo ppo --task g1_walk_flat --sim genesis --load-run -1 -# 2) Motrix 跨后端回放同一个 checkpoint —— 守卫校验通过,正常播放 -uv run eval --algo ppo --task go2_joystick_flat --sim mujoco --load-run -1 +# 不创建环境,审计组合后的 PPO owner。 +uv run scripts/audit_sim2sim_contracts.py --trees ppo ``` -## 生效链路 +审计当前会对 MuJoCo/Genesis 组合输出 `TRANSFERABLE`。这只表示脚本比较的字段一致。如果 +最新 run 不是预期的源 run,应使用显式 run ID,而不是 `-1`。 -1. **训练时**:`ExperimentTracker` 把决定策略 I/O 的契约字段快照进 `run_config.json` 的 `contract_snapshot`(不改动 checkpoint 格式,历史 checkpoint 天然兼容)。 -2. **回放时**:`eval` 读取 `--sim` 指定的**目标后端** owner 配置(如 `src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml`),并注入 `training.play_only=true`。若该任务没有所请求后端的 owner 配置,`eval` 会回退到同任务的兄弟后端 owner,并通过 ALLOWLIST 中的 `training.sim_backend` override 重新指定目标后端(`train` 仍要求 owner 配置必须存在);下面的守卫链路不受影响。 -3. **建 env 前**:各 play 入口(rsl_rl / appo / sac / flashsac)调用 `resolve_sim2sim_config`,把目标配置与源 run 的契约快照逐字段比对。 -4. **加载权重时**:`policy_load_dim_guard` 包裹 checkpoint 加载,把底层 tensor 维度不匹配的晦涩报错重抛为清晰的 sim2sim 诊断。 +## 守卫链路 -## 守卫的字段 +1. **训练:** `ExperimentTracker.start()` 在 run 的 checkpoint 旁写入 + `run_config.json`,其中包含由 `extract_contract_snapshot` 提取的 + `contract_snapshot`。checkpoint 张量不会被改写。PPO 的默认位置是 + `logs/rsl_rl_ppo///run_config.json`。 +2. **Owner 选择:** `eval` 组合 `--algo`、`--task` 和 `--sim` 选定的目标,并注入 + `training.play_only=true`。在普通训练脚本的 eval 路由上,目标 owner 缺失时可以回退到 + 兄弟 owner,并在内部重新应用请求的后端;训练没有这种回退。契约预检仍会执行,该回退 + 不构成任务支持声明,也不保证适用于每个专用 viewer 路由。 +3. **创建环境前:** PPO/APPO/SAC/FlashSAC 回放调用 `resolve_sim2sim_config`,传入源 run + 目录和目标配置。 +4. **加载权重:** `policy_load_dim_guard` 把 checkpoint 张量大小不匹配转换为 sim2sim + 诊断;无关的加载错误保持原样抛出。 -守卫按 dotted path 分三档(定义见 `src/unilab/utils/sim2sim.py`): +## 受守卫字段 -| 档位 | 行为 | 字段 | +权威列表位于 `src/unilab/utils/sim2sim.py`。 + +| 档位 | 行为 | 当前字段 | |---|---|---| -| **DENYLIST** | 差异即 `CrossBackendIncompatibleError`,中断 | `algo.obs_groups`、Manager-Based `env.observations` / `env.actions` / policy 与 critic group mapping、`algo.actor.hidden_dims` / `algo.critic.hidden_dims`、`algo.actor.obs_normalization` / `algo.critic.obs_normalization` / `algo.obs_normalization`、`env.commands.motion.params.sampling_mode`,以及历史快照键 `env.control_config.action_scale`(当前 owner 配置已不声明) | -| **WARNING_LIST** | 仅打印 warning,继续 | `reward.*`、`env.control_config.simulate_action_latency` | -| **ALLOWLIST** | 自由覆盖,不检查 | `training.sim_backend`、`env.scene`、`training.play_steps`、`env.noise_config` | +| **DENYLIST** | 严格模式下,值不匹配会抛出 `CrossBackendIncompatibleError` | `algo.obs_groups`;`env.observations`;`env.actions`;`env.policy_observation_group`;`env.critic_observation_group`;`env.control_config.action_scale`;`env.ctrl_dt`;`env.commands.vel_limit`;`env.commands.motion.params.sampling_mode`;`algo.actor.hidden_dims`;`algo.critic.hidden_dims`;`algo.actor.obs_normalization`;`algo.critic.obs_normalization`;`algo.obs_normalization` | +| **WARNING_LIST** | 打印 warning 后继续 | `reward.scales`、`reward.base_height_target`、`reward.max_tilt_deg`、`reward.min_base_height`、`env.control_config.simulate_action_latency` | +| **ALLOWLIST** | 不写入快照 | `training.sim_backend`、`env.scene`、`training.play_steps`、`env.noise_config` | + +`env.control_config.action_scale` 为历史快照保留;当前 Manager-Based owner 通常在 +`env.actions` 内表达动作缩放。`env.*` DENYLIST 字段只在一侧存在时也会 fail closed,因为 +守卫无法证明省略一侧的运行时默认值等价。 + +有两项窄范围的规范化用于避免误拒绝:`log_goal` 和 `show_rays` 只影响回放调试可视化, +比较 `env.actions` 时会移除;ray-caster 身份 `uni_ray` 会规范化为 `uniray`。其他 +observation/action 变化仍受守卫约束。 + +当前完整的 Manager-Based `reward` mapping **不会**写入快照。特别是, +`reward..weight` 不在 `reward.scales` 的覆盖范围内。必须另行执行 +{doc}`4-reward_parity`。 + +## 不匹配与快照完整性 -## 当 DENYLIST 字段不一致时 +出现 DENYLIST 不匹配时,应让目标 owner 的策略 I/O 契约与训练契约对齐。显式执行 +`uv run eval ... training.sim2sim_strict=false` 会把契约不匹配(包括字段只在一侧存在) +降级为 warning,但不会绕过快照完整性验证或 checkpoint 维度守卫。 -若目标后端的 DENYLIST 字段与训练时不同(例如某 task 的两端 owner 在 `action_scale` 上取值不同),守卫会在建 env 前中断并列出差异字段。处理方式二选一: +当源 `run_config.json` 缺失、不是合法 JSON、顶层不是 JSON object、缺少 mapping 形式的 +`contract_snapshot`,或包含当前 schema 之外的键时,无论 `sim2sim_strict` 如何设置都会 +fail closed。`env.sampling_mode`、`algo.policy.actor_hidden_dims`、 +`algo.policy.critic_hidden_dims` 和 `algo.empirical_normalization` 等退役键不会再做 +别名解析。仓库没有离线迁移工具:需要创建带有受支持快照的新训练 run,或显式使用无源 run +的外部 checkpoint 路径。历史权重文件不会被修改,但仅有权重不能满足预检。 -- **对齐契约**(推荐):让目标后端 owner 的 DENYLIST 字段与训练后端一致,再回放。 -- **强制放行**(自担风险):`uv run eval ... training.sim2sim_strict=false`,把 DENYLIST 差异降级为 warning。它**不会**绕过下面的快照完整性检查。 +直接 PPO 交互 viewer 为没有 UniLab run 快照的外部 checkpoint 提供显式 +`interactive.sim2sim=false` 开关。只有接受策略 I/O 来源未经验证时才应使用;它不能让正常 +eval 中损坏的快照变为有效,也不是 APPO/SAC/FlashSAC 共用的绕过开关。 -> 最低支持快照格式:当源 run 的 `run_config.json` 缺失、不是合法 JSON、缺少 `contract_snapshot` mapping、或含有当前契约 schema 之外的键(包括已退役的 legacy 键 `env.sampling_mode`、`algo.policy.actor_hidden_dims`、`algo.policy.critic_hidden_dims`、`algo.empirical_normalization`,这些键不再做别名解析)时,守卫一律 fail-closed(抛 `CrossBackendIncompatibleError`)。自合入本变更后的首个发布版本起,仅支持 1.3.5 基线 schema 的训练 run 写出的 canonical `contract_snapshot`;该破坏性变更不会回 port 到 1.3.5 patch release。没有离线迁移工具:要复用旧 run,需用当前版本重新训练(checkpoint 权重本身不变),再从新 run 回放。 +## 审计范围 -Manager-Based snapshot 会保存 Hydra 中完整的 typed observation/action 声明。缺少这些字段的旧 -snapshot 无法证明其 policy I/O 与 Manager-Based 目标等价,因此不对称出现时会 fail-closed。 -只有用户显式设置 `training.sim2sim_strict=false` 才会继续;加载权重时的维度守卫仍然生效。 +`uv run scripts/audit_sim2sim_contracts.py --trees ppo appo sac flashsac` 组合 owner 并比较 +DENYLIST/WARNING_LIST 值,不创建环境。当前会审计存在的 MuJoCo/MJWarp/Genesis 组合和 +MuJoCo/Isaac 组合。Motrix、Newton、SuperDex、Drake 和 `mtxwarp` 不会自动包含在这些 +后端对中。`N/A` 表示没有受审计的组合,不表示支持或不兼容;组合错误需要单独检查。 ## 另请参阅 - {doc}`1-backend_swap` - {doc}`4-reward_parity` +- {doc}`5-playback_and_snapshot_differences` - {doc}`../../4-developer_guide/9-sim2sim_contract_status` diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/0-index.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/0-index.md index 5963056c2..92e128957 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/0-index.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/0-index.md @@ -8,7 +8,7 @@ :::{grid-item-card} 从 Isaac Lab 迁移 :link: 1-from_isaac_lab :link-type: doc -保留 Manager-Based term 结构,适配 Hydra 配置、NumPy 执行和场景访问。 +保留 Manager-Based term 结构,适配 Hydra 配置、Torch 执行和场景访问。 ::: :::{grid-item-card} 从 Legged Gym 迁移 @@ -20,7 +20,7 @@ :::{grid-item-card} 从 RSL-RL 迁移 :link: 3-from_rsl_rl :link-type: doc -把 trainer 的假设与 UniLab 的 runner 组装分离开。 +通过 UniLab 适配器使用上游 `OnPolicyRunner`,并单独理解 APPO。 ::: :::{grid-item-card} 从 skrl 迁移 diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/1-from_isaac_lab.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/1-from_isaac_lab.md index 80def1772..4a300ee28 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/1-from_isaac_lab.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/1-from_isaac_lab.md @@ -1,15 +1,16 @@ # 从 Isaac Lab 迁移 -把 Isaac Lab Manager-Based task 迁入 UniLab 时,应保留 manager 与 term 结构,只在各自 -owner 边界适配配置、数值执行和场景访问;不要把 task 重写成单体 environment 子类。 +迁移 Isaac Lab Manager-Based 任务时,应保留 manager 与 term 结构,只在各自的 owner +边界适配配置、张量访问和场景 capability;不要把任务重写成单体 environment 子类,也不要 +把 term 转换为 NumPy。 -这是基于源码的兼容迁移,不代表任意 Isaac Lab task 都能不修改直接运行。目标路径是: +这是源码级迁移。当前目标路径是: ```text Hydra owner YAML -> plain ManagerBasedRlEnvCfg -> Registry + make_manager_based_rl_env - -> NumPy/SimBackend runtime 上的 ManagerBasedRlEnv + -> Torch/SimBackend runtime 上的 ManagerBasedRlEnv -> 交给现有 training 和 IPC 路径的 TorchEnvState ``` @@ -31,13 +32,13 @@ Hydra owner YAML - 把 import 改为 `unilab.managers`;保留 term 边界和局部 `reset(env_ids)` 语义。 * - `ManagerBasedRLEnv` / `ManagerBasedRLEnvCfg` - - Compatible 拼写 alias - - UniLab canonical 名称是 `ManagerBasedRlEnv` 与 `ManagerBasedRlEnvCfg`;alias - 指向同一份实现。 -* - Tensor 数值与运算 + - 可用 alias + - UniLab canonical 名称是 `ManagerBasedRlEnv` 与 `ManagerBasedRlEnvCfg`; + alias 指向同一份实现。 +* - 张量数值与运算 - Adapted - - 把 `torch.Tensor` 换成 `np.ndarray` 并使用向量化 NumPy;manager-facing - API 没有 device 接口。 + - 保留 `torch.Tensor` 和 Torch 运算,把读写适配到 UniLab 的 packed entity + view、manager 契约、dtype 和 `env.device`。 * - 嵌套 `@configclass` task 配置 - Adapted - 把完整 task 声明迁入唯一 Hydra owner YAML;用 `_target_` 选择具体 config @@ -45,14 +46,22 @@ Hydra owner YAML * - `InteractiveSceneCfg`、USD 与 PhysX view - Adapted 或 Unsupported - 声明 task-owned `SceneCfg` 与 `EntityCfg`;状态和控制只通过 - `SceneEntityCfg` 与公共 entity facade 访问。不支持的能力在冷路径绑定时报错。 -* - Omniverse、Isaac renderer 与 Torch/PhysX mutation - - Unsupported - - UniLab 不安装这些 runtime,也不提供静默模拟或回退。 + `SceneEntityCfg` 及公共 entity/backend contract 访问。 +* - Omniverse、Isaac renderer 与直接 PhysX mutation + - 不是可移植的 Manager-term API + - 不要在 term 中模拟这些调用;只能通过已声明的后端 capability 使用,不支持 + 的请求在冷路径绑定时失败。 ``` -规范边界见 {doc}`ADR-0006 `。 -只有已经被 registry、配置和测试覆盖的表面才能声明为 Compatible。 +当前张量运行时边界见 +{doc}`ADR-0012 `。 +ADR-0006 的 NumPy 设计已被取代,只能作为历史背景,不是迁移目标。 + +UniLab 还提供使用外部 worker 的显式 `isaacsim` 和 `isaacgym` 后端选择(分别为 +Python 3.11 和 Python 3.8)。该集成与 Isaac Lab 任务源码迁移是两件事:仍需要对应的 +owner YAML 和已注册任务支持,也不会让 USD/PhysX 专用 term 变得可移植。外部运行时的安装 +入口由 CLI 指向 `scripts/tools/setup_isaacsim_env.sh` 和 +`scripts/tools/setup_isaacgym_env.sh`。 ## 迁移步骤 @@ -62,29 +71,30 @@ Hydra owner YAML 维度、action 维度、reset 行为和 episode timing。写代码前逐项分类: - 复用已有 `unilab.managers` config 或 `unilab.envs.mdp` term; -- 把 task-specific term 从 Torch 适配为 NumPy; +- 把 task-specific Torch term 适配到公共 entity/manager view; - 如果 term 依赖公共 entity 或 `SimBackend` contract 尚未提供的能力,立即停止。 -不能用 `getattr`/`hasattr` 探测 backend 对象、返回零,或把 task 路由回 legacy env。 +不能用 `getattr`/`hasattr` 探测 backend 对象、返回零,或把任务路由回 legacy env。 ### 2. 在冷路径迁移 scene 与 asset -用 task-owned `SceneCfg` 代替 Isaac Lab 的 USD/`InteractiveSceneCfg` 声明,显式声明 term +用 task-owned `SceneCfg` 代替源任务的 USD/`InteractiveSceneCfg` 声明,显式声明 term 需要的每个 entity 与 selector。`SceneEntityCfg` 在 materialization 时只解析一次名称和 -正则表达式;reset/step 复用缓存 ID 与 NumPy view。 +正则表达式;reset/step 复用缓存 ID 与 Torch view。 Cartpole fixture 使用最小 task-owned MJCF。更复杂的 asset 必须遵守 {doc}`场景组合 <../../4-developer_guide/1-architecture/4-scene_composition>`,并只使用所选 -backend 的正式能力。 +backend 的正式能力。选择外部 IsaacSim 后端不能替代这份声明。 ### 3. 迁移 term 代码,不改 manager 结构 -保留每个 function/class term 及其参数,机械地把 Torch 类型与运算改为 NumPy,保持 batch -shape,并在来源 term 返回每环境数值时继续返回每环境数值。Stateful term 在构造时解析 -selector、分配 buffer,热路径只更新 NumPy buffer。 +保留每个 function/class term 及其参数,保持 Torch batch shape,并在来源 term 返回每环境 +数值时继续返回每环境数值。核对 manager 要求的 dtype 和 device;例如,reward 是 +`env.device` 上形状为 `(num_envs,)` 的 float32 张量。 -Python 只拥有 term 实现和可复用 config dataclass,不能再保存一份 task-specific term -启停清单或默认 weight。 +Stateful term 在构造时解析 selector、分配 Torch buffer,热路径复用这些 buffer。Python +只拥有 term 实现和可复用 config dataclass,不能再保存一份 task-specific term 启停清单或 +默认 weight。 ### 4. 让 Hydra 成为唯一 task 配置 owner @@ -150,14 +160,13 @@ env: delay_max_lag: 2 ``` -Manager 按环境、按物理子步独立采样延迟,局部 reset 只清除所选环境的历史。 -初始化或 reset 后的首个目标会回填历史。这些字段覆盖指令延迟,不覆盖 DC -电机的转矩—转速饱和曲线。 +局部 reset 只清除所选环境的延迟历史,初始化或 reset 后的首个目标会回填历史。这些字段 +覆盖指令延迟,不覆盖 DC 电机的转矩—转速饱和曲线。 ### 5. 只注册一条通用 runtime 路径 Task module 为仓库已经实际支持的每个 backend 注册 `ManagerBasedRlEnvCfg` 与 -`make_manager_based_rl_env`。Backend owner YAML 只承载 backend 身份与 tuning。用户通过 +`make_manager_based_rl_env`。Backend owner YAML 承载 backend 身份与 tuning。用户通过 标准 CLI 选择 compose owner,例如: ```bash @@ -166,38 +175,34 @@ uv run train --algo ppo --task --sim mujoco 不要增加 task-specific 训练脚本分支、env factory、runner 或 IPC 路径。 -generic factory 规则只有一个 maintainer 批准的已注册例外: +当前 generic factory 规则有一个 maintainer 批准的已注册例外: `make_g1_walk_env`(`src/unilab/tasks/locomotion/g1/manager_terms.py`)构造 -`G1WalkManagerBasedEnv` 子类,承载 G1 walk 的 manager-based 生产 runtime。其余所有 -Compatible task 都直接注册 +`G1WalkManagerBasedEnv` 子类,承载 G1 walk runtime。其余 Compatible 生产任务直接注册 `make_manager_based_rl_env`。 ### 6. 在适配风险附近验证 测试 Hydra compose 与 typed materialization、term 顺序与数学、selector 失败、 -observation/action shape、局部 reset,以及至少一个真实已注册 backend 的 transition。行为 -应与固定来源 task 对比;完成语义迁移后再做性能 benchmark。 +observation/action shape、局部 reset,以及至少一个真实已注册 backend 的 transition。 +行为应与固定来源 task 对比;完成语义迁移后再做性能 benchmark。 ## 任务迁移最终状态 -任务迁移状态由 registry 与迁移矩阵维护。fail-closed 的 source of truth 是 -`src/unilab/tasks/migration_matrix.py`:`migration_record()` 对没有 -entry 的 production task 名称抛出 `KeyError`,因此新增 production 注册必须显式做出 -迁移决策。 - -- 36 个 task 为 **Compatible**(`target=complete`):Hydra owner YAML 物化 canonical - tensor-only Manager-Based runtime。 +fail-closed 的迁移事实来源是 `src/unilab/tasks/migration_matrix.py`: +`migration_record()` 对没有 entry 的 production task 抛出 `KeyError`。当前矩阵包含三个 +生产任务,均标记为 **Compatible** 且 `target=complete`:`Go2JoystickFlat`、`G1WalkFlat` +和 `G1MotionTracking`。该数量只描述矩阵,不表示有多少 Isaac Lab 任务可以免适配迁移。 ## 仓库证据 `tests/fixtures/isaac_lab_cartpole/` 迁移了 Isaac Lab commit `b0542fe2d45bf91c4e1d9ef6952b9c709c80b4e8` 的 Manager-Based Cartpole task。它保留 -全部 12 个来源 term 的名称和顺序,同时把 Torch 适配为 NumPy、嵌套 config object 适配 -为 Hydra YAML,并用 fixture-local MJCF 实现 scene/action/reset 边界。这只是 test-only -证据,不是 production task 或 Isaac Lab 全量支持声明。 +全部 12 个来源 term 的名称和顺序,同时把嵌套 config object 适配为 Hydra YAML,并用 +fixture-local MJCF/entity 边界实现 scene/action/reset 访问。其当前 term 返回 Torch 张量。 +这是 test-only 证据。 ## 另请参阅 - {doc}`Manager-Based API <../../4-developer_guide/1-architecture/6-manager_based_api>` - {doc}`Env contract <../../4-developer_guide/2-contracts/1-env_contract>` -- {doc}`ADR-0006 ` +- {doc}`ADR-0012 ` diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/2-from_legged_gym.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/2-from_legged_gym.md index 432698d3e..c0898ee4c 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/2-from_legged_gym.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/2-from_legged_gym.md @@ -1,8 +1,8 @@ # 从 Legged Gym 迁移 -Legged Gym 曾是那套 GPU 常驻的 PPO 模板,教会了整个领域如何训练四足机器人。它的 -核心思想 —— joystick 命令空间、地形课程(terrain curricula)、RSL-RL PPO —— -在 UniLab 中得以延续。因此迁移在很大程度上是机械性的。 +Legged Gym 的 joystick command、地形课程和 RSL-RL PPO 概念可以很好地映射到 UniLab,但 +环境实现不是即插即用的子类。应把任务迁入 Manager-Based owner/term 结构,并对照固定的 +源 revision 验证。 ## 直接对应关系 @@ -10,37 +10,48 @@ Legged Gym 曾是那套 GPU 常驻的 PPO 模板,教会了整个领域如何 |---|---| | `LeggedRobot` env 类 | `unilab.envs.manager_based_rl_env.ManagerBasedRlEnv` | | `compute_observations()` | owner 的 `env.observations` term + `unilab.managers.observation_manager` | -| `_reward_*` 方法 | owner 的 `reward` term + `unilab.managers.reward_manager` | +| `_reward_*` 方法 | owner 顶层 `reward` term + `unilab.managers.reward_manager` | | `command_ranges` | 任务 owner YAML 的 `env.commands` 块 | -| 地形课程 | {doc}`../../2-user_guide/6-terrain/1-procedural` | -| RSL-RL PPO | 上游 `rsl_rl.algorithms:PPO`,经由 `unilab.rl` | +| 地形课程 | `env.scene.terrain` 加 `env.curriculum` term;参见 {doc}`../../2-user_guide/6-terrain/1-procedural` | +| RSL-RL PPO | 上游 `rsl_rl.algorithms:PPO`,经由 `unilab.rl.adapters.rsl_rl` | -## 有哪些新东西 +## 架构差异 -- **两个后端。** Legged Gym 仅支持 Isaac Gym;UniLab 给你 MuJoCo + Motrix。 - 在移植之前先选一个(或两个都选);参见 +- **后端选择按 owner 决定。** UniLab 支持多个进程内和外部 worker 后端,不只有 MuJoCo + 和 Motrix。使用 `--sim` 选择,并核对对应 owner 与 capability;参见 {doc}`../2-sim_to_sim/1-backend_swap`。 -- **异步采集。** Legged Gym 在 GPU 上同步采集;UniLab 的 - APPO(`unilab.rl.algos.appo`)把 collector 与 learner 解耦。如果你在意 - wall-clock 时间,在建立起 reward 一致性之后,就移植到 APPO。 -- **硬件部署。** Legged Gym → 真实世界部署,是各实验室各自手工搭建的流程。UniLab - 把 {doc}`../1-sim_to_real/1-overview` 流水线作为一等公民产物提供给你。 +- **公共生命周期基于 Torch。** observation、action、reward、reset 和 termination 值必须 + 迁移到 Manager 的张量契约,不能保留 Legged Gym 类内的私有 buffer 和隐式 device 假设。 +- **APPO 是独立算法。** `unilab.rl.algos.appo` 将 collector 与 learner 解耦,并使用 + V-trace off-policy 修正。它不是把现有 PPO 运行异步化且保持更新语义完全相同的包装器。 +- **部署使用显式契约。** 完成策略 I/O 和 sim-to-sim 验证后,使用 + {doc}`../1-sim_to_real/1-overview` 流水线,不要直接搬移各实验室定制的部署胶水。 ## 迁移清单 -1. 把你的 URDF / MJCF asset 复制到 `src/unilab/assets/robots//` 下。 -2. 在 `src/unilab/tasks/locomotion//` 下创建一个任务模块。 -3. 镜像你的 reward 项;保持名称相同,以便 reward 一致性可被 diff。 -4. 翻译命令采样 —— 在 owner YAML 的 `env.commands` 下配置 - `UniformVelocityCommandCfg`,参考 `go2_joystick_flat` owner。 -5. 翻译地形 —— Legged Gym 的高度场生成器在 UniLab 中有一个对应物,位于 - `unilab.terrains.heightfield_terrains`。 +1. 固定源 Legged Gym revision,盘点 asset、term 顺序、observation/action 维度、command、 + reset、timing 和 DR。 +2. 通过 asset hub 注册机器人资产,并在 `src/unilab/tasks/locomotion//` 下创建任务 + 模块。 +3. 在 `src/unilab/conf/ppo/task//base.yaml` 中声明共享契约,再在同目录添加后端 + leaf。不要让一个后端 leaf 继承另一个。 +4. 使用相同名称移植 reward term,并显式返回 float32 Torch 输出。在 `env.commands` 下配置 + `UniformVelocityCommandCfg`;`go2_joystick_flat` base owner 是当前示例。 +5. 把地形迁移到 `env.scene.terrain`,把课程迁移到 `env.curriculum` 下的 term。高度场工厂 + 位于 `unilab.terrains.heightfield_terrains`。 +6. 注册通用 Manager-Based 工厂,并运行标准命令: + + ```bash + uv run train --algo ppo --task --sim + ``` ## 验证闸门 -在删除你的 Legged Gym 检出之前,先在 UniLab 中于平地上训练一个等价于 Go2 的任务, -并把 reward 项轨迹与源实现对比。如果在策略学习之前轨迹就已经分叉,那么存在 reward、 -命令、复位或 DR 的不匹配;参见 {doc}`../2-sim_to_sim/4-reward_parity`。 +比较学习曲线之前,先在两种实现中回放固定 reset 和确定性动作序列。比较 observation、 +总 reward、reward 分量、termination/truncation mask 和最终观测。早期分叉表示 reward、 +command、reset、timing 或 DR 不匹配;参见 {doc}`../2-sim_to_sim/4-reward_parity`。 + +完成固定 transition 检查后,再在平地上训练 Go2 等价任务,并与源基线比较 reward 曲线。 ## 另请参阅 diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/3-from_rsl_rl.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/3-from_rsl_rl.md index 2b86c181b..41e5b5b9a 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/3-from_rsl_rl.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/3-from_rsl_rl.md @@ -1,36 +1,54 @@ # 从 RSL-RL 迁移 -你已经在独立使用 RSL-RL 了?好消息:UniLab 直接驱动上游 RSL-RL PPO -(`unilab.rl` 把 env 适配给 `rsl_rl.runners.OnPolicyRunner`), -而且几乎是即插即用的。 +UniLab 的 PPO 路径直接驱动上游 `rsl_rl.runners.OnPolicyRunner`。 +`unilab.rl.adapters.rsl_rl.RslRlVecEnvAdapter` 把 UniLab `TorchEnv` 契约转换为 RSL-RL 当前 +基于 TensorDict 的 `VecEnv` 接口;PPO 本身没有在 `unilab.rl.algos` 中重新实现。 + +## 会发生什么变化 + +1. **环境契约。** `TorchEnv.reset()` 返回 `(obs_dict, info_dict)`;`step()` 返回的状态中, + observation、reward 和 done 标志都是张量。适配器为 RSL-RL 映射 actor/critic group 和 + timeout 信息。 +2. **配置归属。** 任务、后端和算法选择来自 Hydra owner YAML 与顶层 CLI,不再为每个机器人 + 编写定制训练脚本。 +3. **Checkpoint/run 布局。** UniLab PPO run 通常位于 + `logs/rsl_rl_ppo///`,`model_*.pt` 与 `run_config.json` 位于同一 run + 目录。resume 使用 `algo.load_run` 和 `algo.checkpoint`。 +4. **其他算法不是透明包装器。** APPO 使用异步采集和 V-trace 修正;SAC 与 FlashSAC 是 + off-policy。由 PPO 转向 APPO 会改变更新语义和配置。 -## 迁移进 UniLab 后你能获得什么 +## 迁移步骤 -1. **Env contract。** RSL-RL 把 env 结构留给你自己处理。UniLab 的 - `unilab.base.torch_env.TorchEnv` 标准化了 obs/info/reset 的签名,让并行与复位 - 更不容易出错。 -2. **任务 owner。** 基于 Hydra 的配置组合,外加 registry 驱动的 - backend / task / algo 选择。不再需要为每种机器人编写定制的训练脚本。 -3. **异步 runner。** 把 RSL-RL PPO 包进 `unilab.rl.algos.appo`,在拥有许多 - CPU 核心的机器上获得更高吞吐量。 -4. **部署流程。** 配合正确 wrapper 的 ONNX 导出、安全层文档,以及 - {doc}`../1-sim_to_real/1-overview` 流水线。 +1. 把环境移植到 `src/unilab/tasks/` 下的通用 Manager-Based 任务结构,显式保持 + observation/action 维度和 termination 语义。 +2. 把训练值翻译到 `src/unilab/conf/ppo/config.yaml` 和 + `src/unilab/conf/ppo/task//` 下的任务 owner。后端 leaf 只继承同目录的 + `base.yaml` 与 `_self_`。 +3. 安装后端依赖和当前 RL extra。使用发布包时需要 + `pip install "unilab[unirl]"`;旧 `uni_rl` extra 已移除。 +4. 运行标准命令: -## 你不会失去什么 + ```bash + uv run train --algo ppo --task --sim + ``` -- 相同的 PPO 算法与超参数 —— RSL-RL 是被包装,而非被重新实现。 -- Checkpoint 兼容性:在策略架构匹配的前提下,来自 UniLab 的 - `runs//model_*.pt` 文件可以被原生 RSL-RL 加载。 +5. 先比较固定 transition 的 observation/reward,再与独立 RSL-RL 基线比较学习曲线。 -## 迁移步骤 +组合后的 `cfg.algo` 子树会传给上游 runner,但迁移仍需检查 RSL-RL 版本相关的 class +name、observation group、normalization 和超参数语义。不能假设同名字段就会产生相同训练 +行为。 + +## Checkpoint 兼容边界 + +UniLab 通过 `OnPolicyRunner` 保存上游 actor/critic state,并附加 UniLab resume 元数据。 +任何外部复用都必须匹配网络结构和 observation/action 布局,但这不保证原生独立 RSL-RL +环境可以原样 resume UniLab run。 -1. 把你的 env 移到 `unilab.envs../`。 -2. 把你的训练配置转换为 `src/unilab/conf/ppo//` 下的一个 Hydra 组。 -3. 运行 `uv run train --algo ppo --task --sim `。 -4. 把 reward 曲线与你独立运行的 RSL-RL 基线对比。 +回放还会在创建环境前验证源 run 的 `contract_snapshot`。没有 `run_config.json` 的外部 +checkpoint 需要显式使用无源 viewer 例外,其策略 I/O 来源未经验证。参见 +{doc}`../2-sim_to_sim/7-config_guard`。 -## 何时不该迁移 +## 何时不必迁移 -如果你已经有一条能用的流水线、没有真实硬件目标,并且你主要只是需要 RSL-RL 提供 -算法 —— 那么 UniLab 就有点杀鸡用牛刀了。当你需要以下任意一项时再用它:多后端、 -异步采集、ONNX 部署,或任务注册。 +如果现有独立流水线只需要 RSL-RL 算法,不需要 UniLab 的任务 owner、后端 capability +检查、部署工具或其他算法,继续保留该流水线是合理选择。 diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/4-from_skrl.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/4-from_skrl.md index 978c405b1..d0957b459 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/4-from_skrl.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/4-from_skrl.md @@ -1,31 +1,42 @@ # 从 skrl 迁移 -skrl 的强项在于算法广度。UniLab 专注于一组精选算法(PPO、SAC,以及若干 -优化变体),但增加了一条真实硬件部署路径。 +skrl 提供广泛的算法目录。UniLab 当前通过内置 CLI 暴露 PPO、APPO、SAC 和 FlashSAC,并 +提供任务 owner、后端 capability 检查和部署工具。算法名称相同不表示更新语义或 checkpoint +兼容。 ## 把 skrl 概念映射到 UniLab | skrl | UniLab | |---|---| -| `Agent`(PPO、SAC……) | `unilab.rl.algos.*` | -| `RolloutMemory` | `unilab.rl.runtime.ipc.tensor_rollout_ring_buffer` | -| `ReplayMemory` | `unilab.rl.runtime.ipc.replay_buffer` | -| `Trainer` | `unilab.training.run` | -| 用于 env 的 `Wrapper` | 继承 `TorchEnv` | +| `Agent`(PPO、SAC……) | 上游 RSL-RL PPO 或 `unilab.rl.algos.{appo,sac,flash_sac}` | +| `RolloutMemory` | APPO 的 `unilab.rl.runtime.ipc.tensor_rollout_ring_buffer` | +| `ReplayMemory` | Off-policy 的 `unilab.rl.runtime.ipc.replay_buffer` | +| `Trainer` | 由 `src/unilab/scripts/train_*.py` 组装的算法专属 runner;PPO 使用上游 `OnPolicyRunner` | +| 环境 `Wrapper` | `TorchEnv` 任务加算法适配器,例如 PPO 的 `RslRlVecEnvAdapter` | +| 超参数配置 | `src/unilab/conf//task//.yaml` 及同目录 `base.yaml` | ## 应当预期什么 -- 对于小众算法(CQL、IQL 等)**没有算法对等** —— UniLab 有意专注于少数几个 - 高度优化的 actor-critic 变体。 -- **不同的 runner 生命周期。** skrl 那种单体式 trainer,变成了由共享内存连接的 - collector + learner 组合。参见 - {doc}`../../4-developer_guide/2-contracts/5-runner_lifecycle`。 -- **不同的 env 接口。** skrl 容忍多种 env 风格。UniLab 坚持要求 - `TorchEnv` + tensor dict obs。 +- **没有统一的算法对等。** CQL、IQL 等不是 UniLab 内置算法。APPO 还通过异步采集和 + V-trace 修正区别于普通同步 PPO。 +- **Runner 生命周期因算法而异。** PPO 仍使用上游 on-policy runner。APPO 和 off-policy + 训练使用 collector/learner 执行、IPC 和共享内存数据结构,不能把该模型套用到所有算法。 +- **环境接口是张量原生的。** 任务代码必须迁移到 `TorchEnv` 和 Manager-Based term 契约。 + observation 是张量字典,不是 skrl 支持的任意环境格式。 +- **配置和 checkpoint 不是即插即用。** 必须显式映射网络形状、observation group、动作 + 缩放、normalization 和算法参数,再验证加载与推理。 ## 迁移清单 -1. 决定哪个 UniLab 算法最匹配你的 skrl agent。 -2. 把 env 移植为 `TorchEnv` 形式。 -3. 把超参数 YAML 转换为 `src/unilab/conf///` 下的 Hydra 组。 -4. 验证 reward 一致性。 +1. 根据目标和数据生命周期选择算法,不要只按名称选择。 +2. 把环境移植到通用 Manager-Based `TorchEnv` 结构。 +3. 把共享任务声明放在 `src/unilab/conf//task//base.yaml`,把后端身份和调参 + 放在 `.yaml`。不要使用 `src/unilab/conf///`,那不是当前 owner + 布局。 +4. 运行标准命令,先验证固定 transition 的 reward 一致性,再比较训练曲线: + + ```bash + uv run train --algo --task --sim + ``` + +PPO 参见 {doc}`3-from_rsl_rl`,term 迁移参见 {doc}`6-reward_porting`。 diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/5-task_config_translation.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/5-task_config_translation.md index 790335cec..c48c9b0c6 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/5-task_config_translation.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/5-task_config_translation.md @@ -1,7 +1,7 @@ # 任务配置翻译速查表 -一张并排对照表,列出 Isaac Lab / Legged Gym / skrl 与 UniLab 任务 owner YAML -之间常见配置字段的对应关系。 +并排列出常见 Isaac Lab / Legged Gym 概念及其当前 UniLab owner 声明。UniLab 列展示 +canonical 路径,不展示历史兼容 alias。 ## Env 级别 @@ -14,28 +14,28 @@ - Legged Gym - UniLab * - Action scale - - env cfg 上的 `action_scale` + - env/action cfg 上的 `action_scale` - env 类中的 `action_scale` - - owner YAML 中的 `env.action.scale` -* - Decimation - - env cfg 上的 `decimation` - - `cfg.control.decimation` - - `env.decimation` + - `env.actions..scale` +* - 控制 decimation + - `decimation` 和仿真 dt + - `cfg.control.decimation` 和仿真 dt + - `env.ctrl_dt / env.sim_dt`(运行时要求整数比) * - Episode 长度(秒) - `episode_length_s` - `cfg.env.episode_length_s` - - `env.episode_length_s` -* - 默认关节位置 + - `env.max_episode_seconds` +* - 默认关节状态 - `init_state.joint_pos` - `default_joint_angles` - - `env.default_joint_pos`(或 asset 侧) + - 由 `env.scene.default_keyframe_name` 选择的任务/机器人 keyframe,或资产侧默认值 * - 观测噪声 - - `noise.obs.*` + - Observation term noise cfg - `cfg.noise.add_noise` - - `env.observations...noise` + - `env.observations..terms..noise` ``` -## Reward +## Reward 与 termination ```{list-table} :header-rows: 1 @@ -48,17 +48,21 @@ * - Reward 项注册 - `RewardManager` cfg - `_reward_*` 方法 - - reward registry + env 的 `compute_reward` + - 注入 Manager reward 配置的顶层 `reward.` mapping * - Reward 权重 - `RewTerm(weight=…)` - `reward_scales.` - `reward..weight` * - 终止惩罚 - - `Termination` cfg + - Reward 与 termination cfg - `_reward_termination` - - reward registry 项 + 终止信号 + - 使用 `unilab.envs.mdp.is_terminated` 的 `reward.`,终止信号位于 `env.terminations` ``` +Manager-Based reward 返回形状为 `(num_envs,)` 的 float32 Torch 张量。顶层 `reward` +mapping 与物化时创建的 typed `env.rewards` 配置不同;owner YAML 作者应按照当前任务 owner +使用 `reward`。 + ## DR ```{list-table} @@ -70,19 +74,22 @@ - Legged Gym - UniLab * - 随机化摩擦 - - `EventTerm(...friction)` + - 摩擦 `EventTerm` - `cfg.domain_rand.friction_range` - - 使用 `geom_friction` 的 `env.events.` + - `env.events.`,设置 `func: unilab.envs.mdp.geom_friction` * - 推搡机器人 - - `EventTerm(...push)` + - Push `EventTerm` - `cfg.domain_rand.push_robots` - - `env.events.push_robot` + - `env.events.`,设置 `func: unilab.envs.mdp.push_by_setting_velocity` * - PD 增益 DR - - `EventTerm(...stiffness)` + - 增益随机化 `EventTerm` - `cfg.domain_rand.randomize_motor_strength` - - `env.events.pd_gains` + - `env.events.`,设置 `func: unilab.envs.mdp.pd_gains` ``` +每个请求的 event 都必须受所选后端的 `get_dr_capabilities()` 支持。必要时在该后端 leaf +中显式禁用或收窄,不能假设共享 event 声明可以原样工作。 + ## Curriculum ```{list-table} @@ -94,16 +101,17 @@ - Legged Gym - UniLab * - 地形课程 - - `TerrainCfg.curriculum` + - Terrain curriculum cfg - `cfg.terrain.curriculum` - - `terrain.curriculum.*` + - `env.scene.terrain.generator.curriculum` 加 `env.curriculum` term,例如 `unilab.envs.mdp.terrain_levels_by_progress` * - 命令范围课程 - - 定制实现 + - Command curriculum cfg 或定制 term - `update_command_curriculum` - - `unilab.base.curriculum` + - `env.curriculum` 加 `unilab.envs.mdp.command_curriculum` ``` ## 另请参阅 - {doc}`6-reward_porting` +- {doc}`../2-sim_to_sim/2-owner_yaml_swap` - {doc}`../../4-developer_guide/2-contracts/3-task_owner` diff --git a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/7-from_unilab_rl.md b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/7-from_unilab_rl.md index 550a6f33a..638e9055d 100644 --- a/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/7-from_unilab_rl.md +++ b/docs/sphinx/source/zh_CN/3-deployment/3-framework_migration/7-from_unilab_rl.md @@ -7,18 +7,19 @@ [unilabsim/unilab_rl](https://github.com/unilabsim/unilab_rl))已并入本 仓库的 `unilab.rl`(issue #2372,决策见 {doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`)。发行面收敛为单一 -`unilab` distribution:APPO / SAC / FlashSAC runner、异步 IPC runtime -与 RL logging 栈均随基础安装提供。 +`unilab` distribution,其中包含 APPO / SAC / FlashSAC runner、异步 IPC runtime +与 RL logging 栈。其第三方训练依赖仍由当前 `unirl` extra 单独打包。 ## 安装变化 - 从 `uv sync` 命令中去掉 `--extra uni_rl`,pip 安装中去掉 - `unilab[uni_rl]`;RL 栈不需要任何 extra。 -- 空的过渡期 `uni_rl` extra 已移除,旧命令会因 unknown extra 报错。请从 - 脚本和 CI 中删除该 extra。 + `unilab[uni_rl]`。旧 extra 已移除,会因 unknown extra 报错。 +- 安装发布包时,使用 `unilab[unirl]` 拉取 `rsl-rl-lib`、`tensordict`、 + `tensorboard` 和 `wandb`。在源码检出中,默认 `rl` dependency group 已安装 + `unilab[unirl]`,因此通常只需按后端执行 `uv sync --extra `。 - 从环境中卸载独立的 `unilab-rl`(`pip uninstall unilab-rl`),避免旧 实现残留并与 `unilab.rl` 并存。 -- CLI 算法名、日志路径、checkpoint 字段与 metric schema 均不变。 +- CLI 算法名、日志路径、checkpoint 字段与 metric schema 不因 namespace 合并而改变。 ## Import 路径映射 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/0-index.md b/docs/sphinx/source/zh_CN/4-developer_guide/0-index.md index 5282a7519..e0196df92 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/0-index.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/0-index.md @@ -48,6 +48,12 @@ Manager-Based construction、reset、interval 与后端能力边界。 契约所有权、schema 策略、benchmark 验收与 release transition。 ::: +:::{grid-item-card} Sim2Sim 契约状态 +:link: 9-sim2sim_contract_status +:link-type: doc +跨后端 snapshot、play 校验与当前 owner 审计结果。 +::: + :::: ## 扩展 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/1-overview.md b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/1-overview.md index 55c32ecab..3cce41b74 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/1-overview.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/1-overview.md @@ -5,11 +5,11 @@ UniLab 是一个 contract 驱动的机器人学习基础设施仓库。其核心 ## 运行时模型 -异步路径采用从 CPU 仿真到加速器 learner 的流水线: +异步路径采用从仿真环境到 learner 的流水线;具体传输取决于 backend 声明的数据平面: ```text -CPU physics backend -> collector / IPC -> learner -MuJoCo or Motrix shared memory torch +Physics backend -> collector / IPC -> learner +HOST_BRIDGE or DEVICE_RESIDENT declared tensor transport torch ``` PPO 是同步路径:默认单进程,也可在单机上按一卡一进程运行 RSL-RL 数据并行; @@ -25,8 +25,9 @@ off-policy 算法则使用异步 runner、共享缓冲区,以及位于 `unilab | Backend | `unisim.backend` | `SimBackend`、物理状态、可选能力 | | Env | `src/unilab/envs/`、`src/unilab/base/torch_env.py` | MDP 语义、观测、奖励、reset | | Config 与 registry | `src/unilab/conf/`、`src/unilab/base/registry.py`、`src/unilab/structured_configs.py` | Schema、owner YAML、env/backend 注册 | -| 算法与 IPC | `src/unilab/rl/algos/`、`src/unilab/rl/runtime/ipc/` | Learner、runner、buffer、权重同步 | -| Scripts | `scripts/`、`src/unilab/cli.py` | 轻量装配与 CLI 路由 | +| RL 算法、适配器与 runtime | `src/unilab/rl/` | RSL-RL 适配、learner、runner、buffer、IPC 与分布式原语 | +| 训练装配 | `src/unilab/training/` | 实验元数据、`run_config.json` 快照、log/checkpoint/playback helper | +| Scripts 与 CLI | `src/unilab/scripts/`、`scripts/`、`src/unilab/cli.py` | 轻量装配与 CLI 路由 | ## 设计规则 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/3-layer_boundaries.md b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/3-layer_boundaries.md index daf4e4606..9bdfcac04 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/3-layer_boundaries.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/3-layer_boundaries.md @@ -11,10 +11,20 @@ | --- | --- | --- | | L0 Backend | `unisim.backend` | 物理 backend 抽象、由 backend 拥有的场景 materialization、backend 能力。 | | L1 Env | `src/unilab/envs/`、`src/unilab/base/torch_env.py` | MDP 语义、观测、奖励、reset 逻辑、backend 到任务的适配。 | -| L2 Config 与 Registry | `src/unilab/conf/`、`src/unilab/structured_configs.py`、`src/unilab/base/registry.py`、`src/unilab/training/reward.py` | Hydra compose、owner YAML 身份、env/reward 注册。 | +| L2 Config 与 Registry | `src/unilab/conf/`、`src/unilab/structured_configs.py`、`src/unilab/base/registry.py` | Hydra compose、owner YAML 身份、env/reward 注册。 | | L3 算法与 IPC | `src/unilab/rl/algos/`、`src/unilab/rl/runtime/ipc/` | Learner、runner、collector、replay 与 rollout buffer、权重同步。 | | L4 Scripts | `scripts/` | 仅做入口装配。 | +## RL 内部依赖 + +`src/unilab/base/contracts/` 是 RL 核心唯一允许依赖的 `unilab.base` 叶子,只包含 +类型/tensor 契约,不 import registry、Manager、backend 或算法。`rl.runtime` 不得依赖 +`rl.algos`、`training` 或 env 构造层;`rl.algos` 与 `rl.adapters` 不得构造具体环境。 +`unilab.rl`、`rl.runtime` 和 `rl.runtime.distributed` 的 package initializer 保持轻量, +不 eager import Torch 或算法栈。`tests/test_library_import_boundary.py` 同时以 AST 和隔离 +进程 import probe 守护这些规则,详见 +{doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`。 + ## 规则 - 在 owner 层修复行为。训练脚本不应承载长期的 env、backend、reward 或算法业务 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/4-scene_composition.md b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/4-scene_composition.md index 15c57e156..a087072cb 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/4-scene_composition.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/4-scene_composition.md @@ -5,21 +5,12 @@ materializer 在初始化期间将该声明转换为 backend 的原生模型。 ## 契约 -`SceneCfg` 与 `TerrainSceneCfg` 位于 `src/unilab/base/scene.py`: - -```python -@dataclass -class TerrainSceneCfg: - generator: TerrainGeneratorCfg | None = None - hfield_name: str = "terrain_hfield" - geom_name: str | None = None - -@dataclass -class SceneCfg: - model_file: str - fragment_files: list[str] = field(default_factory=list) - terrain: TerrainSceneCfg | None = None -``` +`TerrainSceneCfg` 由 `unisim.scene` 定义,并从 `src/unilab/base/scene.py` +re-export。UniLab 的 `SceneCfg` 继承 UniSim scene config,保留 `model_file`、 +`fragment_files` 与 `terrain`,并增加 `entities`、`entity_assets`、`entity_variant`、 +`primary_entity` 和 `tracked_body_names` 等任务字段。物理场景字段与 backend-facing +行为由 UniSim 拥有;UniLab 只在冷路径把 Hydra/OmegaConf entity mapping 物化为 typed +facade config。 `EnvCfg.scene` 是唯一的 scene source。静态场景使用 `SceneCfg(model_file=...)`。 程序化地形场景则将机器人模型、任务 fragment 与地形配置组合在一起: @@ -66,8 +57,9 @@ materializer。 5. `MjSpec.from_string(...).compile()` 返回编译好的 `MjModel`,连同 `terrain_origins`(以及可选的 surface sampler)。 -程序化路径返回预编译的 `MjModel`,不把最终 `scene.xml` path 作为契约暴露。诸如 -`terrain_origins` 这类场景上下文通过 backend 属性传回 env。 +程序化路径返回预编译的 `MjModel`,不把最终 `scene.xml` path 作为契约暴露。地形 +上下文通过公开 `SimBackend.get_terrain_spawn_data()` 在冷路径返回;UniLab 不读取 +backend 私有场景属性。 ## 分层所有权 @@ -102,6 +94,7 @@ production rough-terrain 任务: - 地形生成器:`unisim.terrain.generator` - MuJoCo materializer:`unisim.backend.mujoco.xml` - Motrix materializer:`unisim.backend.motrix.scene` -- 契约覆盖:`tests/utils/test_xml_utils.py` +- 契约覆盖:`tests/base/test_terrain.py`、`tests/terrains/test_terrain_generator.py`、 + `tests/utils/test_xml_utils.py` 用户使用说明见 {doc}`../../2-user_guide/6-terrain/1-procedural`。 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/5-registry.md b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/5-registry.md index 518ec6ce2..2a2d0c964 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/5-registry.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/5-registry.md @@ -17,8 +17,8 @@ Registry bootstrap 是一个针对环境的显式导入契约。它由 5. 被导入的模块通过 `@registry.envcfg(...)` 注册 config,并通过 `@registry.env(..., sim_backend=...)` 或 `registry.register_env(...)` 注册 env 实现。 -6. 运行时构造经由 `registry.make(...)`,它会应用 env config override、校验 - env config、选择所请求的 backend,并实例化已注册的 env 类。 +6. 运行时构造经由 `registry.make(...)`,它会应用并校验 env config override、选择 + 所请求的 backend、调用已注册的 env factory,并要求返回 `TorchEnv`。 ## 扩展规则 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/6-manager_based_api.md b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/6-manager_based_api.md index b3e26fa02..8562eb8ec 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/6-manager_based_api.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/1-architecture/6-manager_based_api.md @@ -4,14 +4,19 @@ UniLab 采用“社区兼容 API + UniLab Torch runtime”:manager-facing 模 function/class term、生命周期和顺序语义以固定的 mjlab 1.6.0 source 为基线;数值实现使用 Torch,并保留现有 `TorchEnvState`、Hydra owner YAML、`SimBackend`、registry 与 IPC contract。 -当前 tensor-runtime 决策见 -{doc}`/adr/ADR-0011-torch-only-manager-based-runtime`;已被取代的兼容矩阵和机械迁移 -示例仅作为历史背景保留在 +当前 tensor-runtime 结构基线见 +{doc}`/adr/ADR-0012-sole-tensor-manager-and-scoped-backends`; +{doc}`/adr/ADR-0011-torch-only-manager-based-runtime` 已被其取代。更早的兼容矩阵和 +机械迁移示例仅作为历史背景保留在 {doc}`/adr/ADR-0006-community-manager-api-on-numpy-runtime`。 ## 不变量 - 公共 manager 结构优先保持社区语义;不为局部性能制造 UniLab-only term API。 +- Manager-Based 是唯一生产 task runtime。`make_manager_based_rl_env()` 提供共享构造 + 路径;task-owned factory/subclass(例如 `G1WalkManagerBasedEnv`)必须继续复用 + `ManagerBasedRlEnv` 及其 Manager 生命周期,不得注册绕过 Manager 的第二套 direct + runtime。 - Production task 只从 Hydra owner YAML 配置:YAML 完整声明 manager/group/term、具体 cfg `_target_`、dotted callable、params、weight 与 observation mapping;Registry 冷路径将其 物化为 plain typed cfg,Python 不保留 task config mirror。 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md index 1becf0b0d..ab665d29c 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/1-env_contract.md @@ -1,9 +1,11 @@ # Env 契约 -Env 契约由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py` -在代码层拥有。观测语义 -记录在 {doc}`/adr/ADR-0005-unified-obs-critic-env-and-ipc-contract`,并被 -{doc}`/adr/ADR-0011-torch-only-manager-based-runtime` 取代。 +Env 生命周期由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py` +拥有,注入 RL runner/collector 的结构契约位于 `src/unilab/base/contracts/`。 +观测分组语义记录在 {doc}`/adr/ADR-0005-unified-obs-critic-env-and-ipc-contract`; +{doc}`/adr/ADR-0011-torch-only-manager-based-runtime` 与 +{doc}`/adr/ADR-0012-sole-tensor-manager-and-scoped-backends` 更新了 tensor carrier, +并未取代 `obs` 加可选 `critic` 的语义。 ## 必需形状 @@ -12,8 +14,9 @@ Env 契约由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py` - 唯一可选的、仅供 critic 使用的观测 key 是 `critic`。 - `obs_groups_spec` 将每个观测组名映射到其扁平维度。Wrapper 与 learner 利用该 映射来确定 actor 与 critic 路径的尺寸。 -- `reset(env_indices)` 接受一维 Torch integer tensor 或 `None`,并为被 reset - 的 env 行返回 `(obs_dict, info_dict)`。 +- `reset(env_ids)` 接受一维 Torch integer tensor 或 `None`,返回 + `(obs_dict, info_dict)`。observation tensor 保持全宽 `(num_envs, dim)`;只有选中行被 + reset 和更新,未选中行保留此前观测。 - 在 `TorchEnv` 上调用 `step(actions)` 接受 contiguous float32 Torch tensor, 并返回 `TorchEnvState`;外部适配器只能在适配边界做 trainer device transfer。 - 公共 `obs`、`reward`、`terminated` 与 `truncated` 输出逐步 fresh 且归调用方 @@ -50,9 +53,9 @@ Env 契约由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py` ## 仓库中的证据 - Env base 契约:`src/unilab/base/base.py` +- RL 注入结构契约:`src/unilab/base/contracts/env.py` - Torch env 生命周期:`src/unilab/base/torch_env.py` -- RSL-RL 适配边界:`src/unilab/rl/vec_env.py` -- Final observation helper:`src/unilab/base/final_observation.py` -- 测试:`tests/base/test_torch_env.py`、 - `tests/envs/test_manager_based_rl_env.py`、 - `tests/utils/test_final_observation.py`、`tests/ipc/` +- RSL-RL 适配边界:`src/unilab/rl/adapters/rsl_rl/vec_env.py` +- Final observation 生命周期:`src/unilab/base/torch_env.py` +- 测试:`tests/base/test_torch_env.py`、`tests/base/contracts/test_env.py`、 + `tests/envs/test_manager_based_rl_env.py`、`tests/rl/runtime/ipc/` diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/3-task_owner.md b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/3-task_owner.md index 6bdaab2c2..fdf083069 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/3-task_owner.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/2-contracts/3-task_owner.md @@ -1,7 +1,9 @@ # 任务 owner config 契约 -任务 owner YAML 是一条已 compose 的 任务/backend/算法 路径的身份。该契约记录在 -{doc}`/adr/ADR-0003-task-owner-and-config-compose-contract`。 +任务 owner YAML 是一条已 compose 的任务/backend/算法路径的身份。该契约记录在 +{doc}`/adr/ADR-0003-task-owner-and-config-compose-contract`;同目录 `base.yaml` 与 +backend leaf 的组合规则见 +{doc}`/adr/ADR-0023-task-sim-owner-inherits-same-directory-base-only`。 ## Owner 路径 @@ -14,9 +16,13 @@ - 使用对外的 CLI flag 切换 backend,例如 `uv run train --algo ppo --task go2_joystick_flat --sim mujoco` 或 - `uv run train --algo ppo --task go2_joystick_flat --sim mujoco`。 + `uv run train --algo sac --task g1_walk_flat --sim mjwarp`。 - 对于 off-policy 入口,`--algo ` 选择按算法划分的配置树;owner YAML 路径为 `src/unilab/conf//task//.yaml`。 +- 每个任务目录必须有 `base.yaml`,持有共享任务契约;每个 backend leaf 的 + `defaults` 只包含 `/task//base` 与 `_self_`,不得继承另一个 backend leaf。 + `base.yaml` 不是可训练入口,backend leaf 直接持有 `training.task_name` 与 + `training.sim_backend`,并显式声明后端差异。 - `training.sim_backend` 是所选 owner YAML 内部的身份字段,而不是一个独立的 backend 切换开关。 - 与 backend 相关的 reward、env、scene 与算法差异属于 owner YAML,而不是训练 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/0-index.md b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/0-index.md index 838e9213b..988547190 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/0-index.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/0-index.md @@ -21,7 +21,13 @@ :::{grid-item-card} 新算法 :link: 3-new_algorithm :link-type: doc -添加配置、runner 代码与脚本层组装。 +添加 owner 配置、`unilab.rl` 代码与入口薄层组装。 +::: + +:::{grid-item-card} 新地形 +:link: 4-new_terrain +:link-type: doc +在冷路径扩展地形生成。 ::: :::: diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/1-new_task.md b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/1-new_task.md index 20e9c80a3..2f49a12bb 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/1-new_task.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/1-new_task.md @@ -6,44 +6,55 @@ ## 实现清单 -1. 在 `src/unilab/envs/` 下选取最接近的 owner 包。 -2. 定义或扩展一个 env config dataclass,并用 - `@registry.envcfg("EnvName")` 注册它。 -3. 用 `@registry.env("EnvName", sim_backend="mujoco")` 或 - `@registry.env("EnvName", sim_backend="motrix")` 注册每个受支持的 - 后端实现。 +1. 在 `src/unilab/tasks/` 下选取最接近的任务 owner 包。共享 Manager-Based + runtime 留在 `src/unilab/envs/`;不要新增按任务划分的 env 类或 legacy + class-config factory。 +2. 用 `registry.register_env_config("EnvName", ...)` 注册 + `ManagerBasedRlEnvCfg`(或其他现有 Manager-Based config owner)。 +3. 对每个受支持的后端,用 `registry.register_env("EnvName", ..., + sim_backend=...)` 注册通用 `make_manager_based_rl_env` factory。选择后端 + 不需要不同的任务专用 env 实现。 4. 如果任务位于一个新模块中,请把该模块加入包的 `__unilab_registry_modules__` 元组,以便 `ensure_registries()` 导入它。 仓库外的第三方任务包还需在 `pyproject.toml` 声明 `[project.entry-points."unilab.tasks"]`(见 {doc}`../1-architecture/5-registry`)。 -5. 保持 `obs_groups_spec` 准确。它必须包含 `obs`,并且可以包含 - `critic`;wrapper 和 learner 都信任这些维度。 +5. 在 owner YAML 中声明 observation、action、reward、event 及其他任务 term。 + 设置 `policy_observation_group`,并按需设置 + `critic_observation_group`;Manager 把它们映射为 `obs_groups_spec` 中必需的 + `obs` 和可选的 `critic`,wrapper 与 learner 信任这些维度。 6. 把 reset 与 step 语义保留在 env owner 层: - `reset(env_indices)` 返回 `(obs_dict, info_dict)`,而 `step(actions)` + `reset(env_ids)` 返回 `(obs_dict, info_dict)`,而 `step(actions)` 返回 `TorchEnvState`。 -7. 在相关 config 根目录下添加 owner YAML,例如 - `src/unilab/conf/ppo/task//.yaml`,off-policy 算法则为 - `src/unilab/conf//task//.yaml`。 -8. 把任务或场景的 keyframe 放进通过 `SceneCfg.fragment_files` 引用的 +7. 把共享任务行为放进 `src/unilab/conf//task//base.yaml`,把 + 后端/算法特定选择放进继承它的 `.yaml` 叶子。每个可运行叶子选择 + `training.task_name` 与 `training.sim_backend`;面向用户的命令使用 + `--task --sim `,不要把 `training.sim_backend` 当作独立的后端 + override。 +8. 域随机化只能通过 Manager-Based event term 与已声明的 `SimBackend` + capability 协商实现。不支持的 capability 必须 fail closed;不要新增 DR + manager/provider 协议。 +9. 把任务或场景的 keyframe 放进通过 `SceneCfg.fragment_files` 引用的 任务/场景 XML fragment;不要把 task-level keyframe 放进 `robot.xml`。 + Asset 与 XML 检查只能位于初始化、materialization 或缓存冷路径,不得进入 + `step()`、`reset()` 或随机化热路径。 ## 在风险点附近验证 - Registry 与 config 形状:`tests/base/test_registry.py`、 `tests/config/test_config_system.py` - Env observation/reset 行为:`tests/base/test_torch_env.py` 以及 - `tests/envs/` 下最接近的特定任务测试 + `tests/envs/`、`tests/tasks/` 下最接近的特定任务测试 - 脚本组合:`tests/scripts/test_train_script_configs.py` ## 仓库内证据 -- Registry API:`src/unilab/base/registry.py` +- Registry API 与后端 allowlist:`src/unilab/base/registry.py` - Env 状态契约:`src/unilab/base/torch_env.py` - 场景配置:`src/unilab/base/scene.py` - 任务声明是 owner YAML 加 registry 引导,没有按任务划分的 Python env 类: `src/unilab/tasks/locomotion/go2/__init__.py` 用 `ManagerBasedRlEnvCfg` 与 - `make_manager_based_rl_env` 按后端注册 `Go2JoystickFlat`,owner YAML 位于 - `src/unilab/conf/ppo/task/go2_joystick_flat/`。任务自有 term 库示例: - `src/unilab/tasks/motion_tracking/g1/manager_terms.py`。端到端演练见 - {doc}`../../6-how_to/1-onboard_new_robot`。 + `make_manager_based_rl_env` 按后端注册 `Go2JoystickFlat`。共享任务 term 位于 + `src/unilab/conf/ppo/task/go2_joystick_flat/base.yaml`,后端叶子与其同目录。 + 任务自有 term 库示例:`src/unilab/tasks/motion_tracking/g1/manager_terms.py`。 + 端到端演练见 {doc}`../../6-how_to/1-onboard_new_robot`。 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/2-new_backend.md b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/2-new_backend.md index 606df03cd..7cb153883 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/2-new_backend.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/2-new_backend.md @@ -5,26 +5,35 @@ ## 当前后端形态 -仓库目前在两个重要位置识别 `mujoco` 与 `motrix`: +具体 adapter 及其公共契约位于 `unisim-core`。UniLab 的 +`create_backend(...)` 解析托管资产并转换 owner 选项,然后把构造委派给 +`unisim.create_backend(...)`。任务注册和顶层 CLI 接受的后端名称分别在 +`_SUPPORTED_SIM_BACKENDS`(`src/unilab/base/registry.py`)与 +`SUPPORTED_SIMS`(`src/unilab/cli.py`)中声明。 -- `src/unilab/base/registry.py` 中的 `registry.register_env(...)` -- `src/unilab/base/backend_factory.py` 中的 `create_backend(...)` - -因此,引入第三个后端是一项架构变更,而不仅仅是新增一个包。 +因此,新增后端会跨越上游 adapter 契约以及 UniLab 的 registry、config、依赖和 +设备路由 owner,而不只是新增一个任务包。 ## 实现清单 -1. 在 `unisim.backend/` 下实现一个 `SimBackend` 子类。 -2. 把后端构造逻辑加入 `create_backend(...)`。 -3. 如果新后端应当被 `@registry.env(..., sim_backend=...)` 接受, - 则更新 registry 校验逻辑。 -4. 通过 `SimBackend` 方法、`PlayCapabilities`、域随机化能力方法, - 或新的显式抽象方法,暴露后端特定的可选能力。 -5. 为受支持的 task/backend 组合添加任务 owner YAML。让面向用户的示例 - 走 `--task --sim `,不要依赖 - `training.sim_backend=` 作为 override。 -6. 把 XML、asset 与 model 检查保留在后端 init 或 materialization 代码中。 +1. 在 UniSim 的 `unisim.backend./` 下实现 `SimBackend` 子类,并在 + 上游添加 adapter 声明与惰性 factory 分派。 +2. 把 UniLab 后端名称加入 registry 与 CLI allowlist。如果 UniLab 与 UniSim + 名称不同,在 `src/unilab/base/process_device.py` 中转换;只在现有 owner + 模块中添加必需的运行时依赖检查、owner 选项与设备路由。 +3. 通过已声明的 `SimBackend` capability 表面暴露可选行为,按适用情况包括 + `get_tensor_capabilities()`、`get_dr_capabilities()`、 + `get_play_capabilities()` 与 `get_capabilities()`。env 消费新能力前先扩展 + 公共接口;不得从 env 或训练代码探测后端私有方法。 +4. 为每个受支持的 task/backend 组合注册 `make_manager_based_rl_env`,并添加 + 对应的 owner YAML 叶子。面向用户的示例走 + `--task --sim `,不要把 + `training.sim_backend=` 作为独立 override。 +5. 把 XML、asset 与 model 检查保留在后端 init 或 materialization 代码中。 热路径的 env 应当接收缓存好的 ID、数组或已声明的后端方法。 +6. 改动已注册或已配置的支持范围后,运行 + `uv run scripts/generate_support_matrix.py --write` 重新生成支持矩阵; + 不要手改生成块。 ## 在风险点附近验证 @@ -32,12 +41,15 @@ `tests/base/test_backend_conformance.py`、 `tests/base/test_sim_backend_smoke.py` - 特性边界附近的后端特定行为测试,例如 - `tests/base/test_motrix_backend_options.py` -- Task/backend config 组合:`tests/config/test_config_system.py` + `tests/base/test_motrix_backend_options.py` 与 + `tests/base/backend/test_process_device.py` +- CLI 运行时要求与命名:`tests/test_cli_runtime_requirements.py` +- Task/backend config 组合与生成的支持数据: + `tests/config/test_config_system.py`、`tests/scripts/test_support_matrix.py` ## 仓库内证据 -- 后端接口:`unisim.backend.base` -- 后端工厂:`src/unilab/base/backend_factory.py` -- MuJoCo 后端包:`unisim.backend.mujoco` -- Motrix 后端包:`unisim.backend.motrix` +- 后端接口与 adapter factory:`unisim.backend.base`、`unisim.create_backend` +- UniLab 资产/选项 adapter:`src/unilab/base/backend_factory.py` +- 后端名称与设备映射:`src/unilab/base/process_device.py` +- Registry 与 CLI allowlist:`src/unilab/base/registry.py`、`src/unilab/cli.py` diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/3-new_algorithm.md b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/3-new_algorithm.md index b328aff5e..61d67d67b 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/3-new_algorithm.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/3-new_algorithm.md @@ -23,36 +23,42 @@ ### 2. `runtime_resolver`:算法代码放在自己的仓库 -研究者在自己的仓库里 import `unilab.rl` 作为库, -实现 runner / learner / play 逻辑,**不需要 fork UniLab**。owner YAML -通过 `algo.runtime_resolver` 声明一个 dotted path(`module:attr`): +研究者在自己的仓库里 import `unilab.rl` 作为库,实现算法族特定的 runtime +定制,**不需要 fork UniLab**。owner YAML 通过 `algo.runtime_resolver` 声明一个 +dotted path(`module:attr`): ```yaml algo: runtime_resolver: my_pkg.my_module:resolve_my_runtime ``` -约定: - -- 签名为 `(rl_cfg: dict) -> Runtime | None`;返回 `None` 表示回落到该算法的 - 默认 runtime; -- 返回对象必须携带 `runner_cls`;按算法族可选携带 `play_fn`(APPO 风格); -- 解析发生在 RL runtime 侧(`unilab.rl.algos.appo.resolution`),dotted path 可以指向 - 任何可 import 的模块。PPO 路径不再使用 `runtime_resolver` —— 它通过 - `unilab.rl` 直接驱动上游 RSL-RL,因此 PPO 的定制化走 - `class_name` 配置键(第一档)。 - -### 3. 在 UniLab 中修改 `unilab/rl/algos/` - -只有当需要改动 runner / learner / collector 的共享实现(例如新的 IPC -生命周期)时,才在本仓库修改 -`src/unilab/rl/algos/`。异步算法应复用 `AsyncRunner`、`ReplayBuffer` / -`TensorRolloutRingBuffer` 与 `SharedWeightSync`,而不是新建一套 IPC 生命周期。 +resolver 以 `(rl_cfg: dict)` 接收解析后的算法字典,返回约定取决于算法族: + +- APPO 使用 `unilab.rl.algos.appo.resolution`。返回对象必须携带 + `runner_cls`;`play_fn` 可选,缺省时回落到通用 APPO play 入口。 +- SAC 家族的 off-policy 定制使用 + `unilab.rl.runtime.offpolicy.resolution`,并且必须返回 + `OffPolicyRuntime`。其可选字段覆盖 learner 类、算法类型、actor + kwargs/adapter 模块与 learner 准备 hook,共享 off-policy runner 和 IPC + 生命周期保持不变。 +- 未配置 `runtime_resolver` 时选择默认 runtime。如果已配置的 resolver 返回 + `None`,APPO 与 off-policy 解析都会 fail closed;`None` 不是回退信号。 +- PPO 不使用 `runtime_resolver`:它通过 `unilab.rl.adapters.rsl_rl` 驱动上游 + RSL-RL,因此 PPO 定制化走 `class_name` 配置键(第一档)。 + +### 3. 在 UniLab 中修改 `unilab.rl` owner 层 + +算法专用 learner 与 runner 放在 `src/unilab/rl/algos/`。共享 collector、 +IPC、off-policy 或分布式行为只能在 `src/unilab/rl/runtime/` 中修改,上游 +RSL-RL 集成保留在 `src/unilab/rl/adapters/rsl_rl/`。异步算法应复用 +`AsyncRunner`、`ReplayBuffer` / `TensorRolloutRingBuffer` 与 +`SharedWeightSync`,而不是新建一套 IPC 生命周期。算法接收可 pickle 的 +`EnvFactory`,不得自行构造具体 env。 ## CLI 可路由算法的 footprint `uv run train --algo ` / `uv run eval --algo ` 采用约定式路由 -(`src/unilab/cli.py` 的 `available_algos` 与 `build_route`):algo 名 +(`src/unilab/cli.py` 的 `available_algos` 与 `build_route`)。非内置 algo 名 `` 可路由,当且仅当以下两个文件同时存在,**不需要修改 cli.py**: 1. `src/unilab/conf//config.yaml` —— Hydra config 根,算法超参数内联; @@ -87,12 +93,18 @@ fail-closed,报错信息列出全部可用 algo(内置 + 约定发现的) - CLI 路由与约定式发现:`tests/test_cli.py` - 脚本/配置测试:`tests/scripts/test_train_script_configs.py`、 `tests/scripts/test_train_scripts.py` +- Runtime 解析与生命周期:`tests/rl/runtime/offpolicy/test_resolution.py`、 + `tests/rl/runtime/test_async_runner.py` +- RL import owner 边界:`tests/test_library_import_boundary.py` ## 仓库内证据 - 结构化 config dataclass:`src/unilab/structured_configs.py` - 训练辅助工具:`src/unilab/training/common.py`、 `src/unilab/training/run.py` +- Runtime resolver:`src/unilab/rl/algos/appo/resolution.py`、 + `src/unilab/rl/runtime/offpolicy/resolution.py` +- 可 pickle 的 env 注入:`src/unilab/base/env_factory.py` - 现有算法包:本仓库的 `unilab.rl.algos`(并自原 [unilabsim/unilab_rl](https://github.com/unilabsim/unilab_rl);见 {doc}`/adr/ADR-0016-rl-reintegration-into-unilab-rl`) diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/4-new_terrain.md b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/4-new_terrain.md index 7f100a883..7225dffa7 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/4-new_terrain.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/3-extending/4-new_terrain.md @@ -14,9 +14,11 @@ `ROUGH_TERRAINS_CFG`),也可以通过 `src/unilab/conf/` 下的 owner YAML。 4. 通过 `src/unilab/base/scene.py` 中的 `SceneCfg.terrain` 与 `TerrainSceneCfg` 把地形暴露给场景。 -5. 如果某个 env 需要高度 observation,在 init 时通过 - `bind_height_scanner(...)` 创建后端 scanner;通过返回的 - `HeightScanner` 读取采样。 +5. 如果 env 需要 ray/高度 observation,用 `RayPatternCfg` 声明 + `mdp.RayScan` observation term。Manager 在 read-phase 初始化期间通过 + UniSim 绑定配置的 caster;不要在 `step()` 或 `reset()` 中构造或绑定 + scanner。直接消费底层 `SimBackend.bind_height_scanner(...)` 契约的代码也 + 必须在冷路径完成绑定。 6. 让地形的 spawn、curriculum 与 observation 维度在归属的 env config 与 `obs_groups_spec` 中得到体现。 @@ -24,8 +26,10 @@ - 地形生成器形状与数值行为: `tests/terrains/test_terrain_generator.py` +- 场景地形原点与 curriculum:`tests/base/test_terrain.py` - Backend terrain materialization contract: `tests/base/test_backend_conformance.py` +- Ray observation 配置与绑定:`tests/envs/mdp/test_ray_observation.py` - 后端 materialization 边界:`tests/utils/test_xml_utils.py` ## 仓库内证据 @@ -33,3 +37,5 @@ - 地形配置与 preset:`src/unilab/terrains/config.py` - 地形生成器:`unisim.terrain.generator` - Heightfield 地形类型:`src/unilab/terrains/heightfield_terrains.py` +- Manager 地形状态:`src/unilab/base/terrain.py` +- Ray observation owner:`src/unilab/envs/mdp/ray_observation.py` diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/4-contributing.md b/docs/sphinx/source/zh_CN/4-developer_guide/4-contributing.md index 68f16b74b..57737f1de 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/4-contributing.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/4-contributing.md @@ -73,8 +73,9 @@ UNILAB_DOCS_SKIP_AUTODOC=1 uv run --no-project --with-requirements requirements. `Docs` GitHub Actions workflow 会在 base 为 `main` 的匹配 PR 和 `main` push 上运行 同样的 prose-only 构建,也可以在 GitHub Actions 网页界面通过 `workflow_dispatch` -手动触发。它不会用 -`pip install -e .` 安装 UniLab,不生成 API reference 页面,也不发布外部文档仓库。 +手动触发。PR 构建不安装 UniLab,也不生成 API reference 页面。`main` 上的检查构建 +成功后,独立的 deploy job 运行 `sphinx-multiversion` 并发布外部 `UniLab-doc` +仓库;其中 UniLab 安装失败时会回退为 prose-only 部署。 如果要在本地对完整站点(含面向 `UniLab-doc` 发布流程的 API reference 页面)做最终 刷新,请从已同步的开发环境用并行 Sphinx 构建: @@ -92,6 +93,10 @@ uv run --no-sync sphinx-build -j auto -b html -n source build/html 与发布的唯一规则来源是 {doc}`5-contributing_workflow`。创建或更新 PR 前,在最终 head 运行贴近改动契约的检查和 `make test-all`。 +每个包含用户可见改动的 PR 都必须按 `CONTRIBUTING.md` 的说明,在 +`docs/sphinx/source/changelog.md` 的 `Unreleased` 小节添加条目。纯内部重构、 +仅测试改动和 CI 设施改动可以不加。 + ## 测试 测试按 owner 区域分组,位于 `tests/`: @@ -101,13 +106,16 @@ tests/ ├── base/ # registry、backend 选择、env contract ├── config/ # Hydra / dataclass / reward 注入 ├── envs/ # 环境配置与实例化 -├── dr/ # domain-randomization 类型与 manager +├── managers/ # Manager-Based term 与 observation/reset 行为 +├── tasks/ # 任务自有 term、注册与包边界 ├── terrains/ # 地形生成器与场景 materialization -├── ipc/ # shared-memory 与 async-runner 原语 +├── rl/ # 算法、adapter、分布式/IPC/off-policy runtime +├── algos/ # 训练 runner 集成 +├── assets/ # 托管资产 resolver ├── scripts/ # 训练脚本配置与入口工具 -├── algos/ # runner 集成、RSL-RL PPO -├── integration/ # 跨模块 reward / config 集成 ├── training/ # 训练运行辅助 +├── architecture/ # 跨 owner 架构边界 +├── benchmark/ # benchmark 契约与 smoke 覆盖 └── utils/ # 辅助工具与实验跟踪 ``` @@ -140,7 +148,7 @@ tests/ `Registered`、`Configured`、`Tested`、`Benchmarked` 或 `Recommended`。 - 不要把 `training.sim_backend=` 描述为独立的后端切换方式。在 面向用户的命令中使用 `--sim `,并在内部选择 owner YAML 路径。 -- 让英文页面不含手写的导航块。 +- 中英文页面都不得包含手写导航块或页面级语言选择行。 ## 配置改动 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/5-contributing_workflow.md b/docs/sphinx/source/zh_CN/4-developer_guide/5-contributing_workflow.md index 2030d833c..0402d4817 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/5-contributing_workflow.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/5-contributing_workflow.md @@ -62,8 +62,9 @@ child branch 从最新集成分支创建,使用常规类型前缀,例如 训练行为。文档改动运行相应的 docs 检查,并遵守该 PR 所需的仓库 gate。 依赖维护是双轨的:修改 `pyproject.toml` 依赖钉版时,必须在同一 PR 中把相同的 -版本钉进 `pyproject.rocm.toml` 并重新生成 `uv.rocm.lock`。切换已发布依赖时, -上游版本必须已在 PyPI 发布后才能合入钉版变更;见下文 tensor-runtime 切换小节。 +版本钉进 `pyproject.rocm.toml`,并重新生成 `uv.lock` 与 `uv.rocm.lock`。切换已发布 +依赖时,上游版本必须已在 PyPI 发布后才能合入钉版变更;见下文 tensor-runtime +切换小节。 ## 架构决策 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/6-agent_quick_reference.md b/docs/sphinx/source/zh_CN/4-developer_guide/6-agent_quick_reference.md index 089f741ee..68e4fd67b 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/6-agent_quick_reference.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/6-agent_quick_reference.md @@ -15,8 +15,11 @@ ## 需要记住的契约 -- Env 契约:`src/unilab/base/torch_env.py` +- Env 生命周期:`src/unilab/base/torch_env.py`;RL 注入契约: + `src/unilab/base/contracts/env.py` - Backend 契约:`unisim.backend.base` +- RL 内部分层守卫:`tests/test_library_import_boundary.py` +- Sim2Sim snapshot/validation:`src/unilab/utils/sim2sim.py` - 训练辅助工具:`src/unilab/training/run.py` - Config schema:`src/unilab/structured_configs.py` - Developer 标准:{doc}`1-architecture/1-overview` diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/7-motion_assets.md b/docs/sphinx/source/zh_CN/4-developer_guide/7-motion_assets.md index 00d682946..3d494cc6e 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/7-motion_assets.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/7-motion_assets.md @@ -44,7 +44,7 @@ export HF_HUB_OFFLINE=1 在有网络的环境中提前下载全部资产: ```bash -huggingface-cli download unilabsim/unilab-motions \ +uv run hf download unilabsim/unilab-motions \ --repo-type dataset \ --local-dir src/unilab/assets ``` @@ -53,22 +53,23 @@ huggingface-cli download unilabsim/unilab-motions \ ## CI 缓存 -在 CI 中可通过设置 `HF_HOME` 指向持久化缓存目录来避免重复下载: +resolver 使用 `local_dir=ASSETS_ROOT_PATH` 下载,因此 CI 应持久化 +`src/unilab/assets/motions/` 与已注册的机器人资产目录,以便在 resolver 检查的 +原路径直接复用。这些下载内容已被 `.gitignore` 排除。此外,也可以让 `HF_HOME` +指向持久化的 Hugging Face 缓存: ```yaml env: HF_HOME: /cache/huggingface ``` -或使用 `--local-dir` 预下载到仓库内目录(已被 `.gitignore` 排除)。 - ## 新增 motion 文件 1. 按现有流程生成 `.npz`(见 `scripts/motion/README.md`)。 2. 上传到 HF 仓库,保持目录结构一致: ```bash - huggingface-cli upload unilabsim/unilab-motions \ + uv run hf upload unilabsim/unilab-motions \ src/unilab/assets/motions motions \ --repo-type dataset ``` @@ -126,3 +127,9 @@ uv run unilab-pull-assets --robot all # 所有已注册机器人 - `ASSETS_ROOT_PATH` 定义不变,下载落盘位置与原始本地路径完全一致。 - 机器人二进制资产使用同一目录 resolver(`resolve_robot_asset_dir`);同一 resolver 也通过 `unilab-pull-assets` CLI 暴露。 + +## 在风险点附近验证 + +- Motion、scene 与机器人 resolver 行为:`tests/assets/test_hub.py` +- 机器人预拉取 CLI:`tests/test_pull_assets.py` +- Motion CSV 转换:`tests/scripts/test_csv_to_npz.py` diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/8-tensor_runtime_production.md b/docs/sphinx/source/zh_CN/4-developer_guide/8-tensor_runtime_production.md index 1ba33ab4c..66d8924e9 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/8-tensor_runtime_production.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/8-tensor_runtime_production.md @@ -26,7 +26,7 @@ fail closed。 | Namespace | 版本 | Producer owner | | --- | ---: | --- | | TensorBoard / W&B metric schema | `1` | `unilab.rl.logging.metric_schema` | -| Runtime 进程 / 设备 / IPC manifest | `1` | `unilab.rl.logging.runtime_manifest_schema` | +| Runtime 进程 / 设备 / IPC manifest | `2` | `unilab.rl.logging.runtime_manifest_schema` | | UniLab 长 soak 监控 artifact | `0.3.0` | `unilab.training.soak` | 同一 major version 内,producer 可以伴随 schema、测试与文档增加可选字段。 diff --git a/docs/sphinx/source/zh_CN/4-developer_guide/9-sim2sim_contract_status.md b/docs/sphinx/source/zh_CN/4-developer_guide/9-sim2sim_contract_status.md index 74c5765cf..9f9fd2367 100644 --- a/docs/sphinx/source/zh_CN/4-developer_guide/9-sim2sim_contract_status.md +++ b/docs/sphinx/source/zh_CN/4-developer_guide/9-sim2sim_contract_status.md @@ -1,75 +1,78 @@ # Sim2Sim 跨后端任务契约状态 -本页给出每个 task 在两后端(MuJoCo / Motrix)上 DENYLIST 契约字段是否一致的当前状态, -回答「这个 task 当前能否 A 后端训练 → B 后端 play」。契约字段定义见 -`src/unilab/utils/sim2sim.py`,运行时守卫与机制概述见 AGENTS.md 的 Sim2Sim 章节。 - -## 复跑方式 - -``` -uv run scripts/audit_sim2sim_contracts.py +`src/unilab/utils/sim2sim.py` 是策略 I/O 与网络形状契约的运行时事实源。本页记录当前 +owner YAML 的静态审计结果;“可迁移”只表示受检配置字段一致,不构成动力学等价、 +训练收敛或部署性能保证。 + +## 运行时 snapshot 与 play 校验 + +- 训练由 `ExperimentTracker` 在 `run_config.json` 写入 `contract_snapshot`。snapshot + 包含实际存在的 DENYLIST 与 WARNING_LIST 字段,不包含 ALLOWLIST 字段。 +- 启用 preflight 的 play 路由在环境构造前用源 run 的 snapshot 校验目标 composed + Hydra config。显式无源 run,以及直接 PPO 交互 viewer 设置 + `interactive.sim2sim=false` 时,会跳过 preflight。preflight 执行时,缺失或损坏的 + snapshot、未知或已退役键即使 `strict=False` 也 fail closed。 +- DENYLIST value diff 默认抛出 `CrossBackendIncompatibleError`;`strict=False` 仅把 + 这类不匹配降级为 warning。WARNING_LIST 差异被报告,ALLOWLIST 字段可以不同。 +- `env.` 结构字段仅在一侧出现时也计入上述 DENYLIST mismatch;算法专属字段在目标 + 算法中不存在时按跨算法规则跳过。`env.actions` 比较排除仅影响可视化的 `log_goal`/`show_rays`, + ray-caster 的 `uni_ray`/`uniray` 改名会归一化,其它差异不被豁免。 +- checkpoint 加载时的 dimension guard 只转换 `size mismatch` 为 Sim2Sim 诊断;其它 + 加载错误原样传播。它是对配置校验的补充,而不是替代品。 + +权威实现与测试:`src/unilab/utils/sim2sim.py`、 +`src/unilab/training/experiment.py`、`src/unilab/visualization/interactive_playback.py`、 +`tests/training/test_sim2sim_resolver.py`。 + +## 复跑当前审计 + +```bash +uv run scripts/audit_sim2sim_contracts.py --trees ppo appo sac flashsac ``` -该脚本只读,对每个 task 用 hydra `compose` 得到有效配置(展开 `defaults` / -`# @package _global_`),再按守卫同一套归一化逐字段比对,输出本页相同的判定。 - -判定分三档: - -- ✅ **可迁移**:DENYLIST 在 composed config 上无分歧。 -- ❌ **阻断**:存在 value-diff,或 env 结构字段不对称出现;守卫会抛 `CrossBackendIncompatibleError`。 -- ⚪ **N/A**:缺少 mujoco↔motrix 配对。 - -> 一个口径细节:脚本比对的是 composed YAML,「某后端没写该字段」显示为 ``;运行时 -> env dataclass 会给该路径填默认值。对 env 结构字段(`action_scale` / `sampling_mode`) -> 守卫对不对称出现一律 fail-closed;`algo` 专属字段(`algo.actor.obs_normalization` / -> `algo.obs_normalization`)在目标缺省时按设计跳过(跨算法合法)。 - -## `src/unilab/conf/ppo/task/` - -| Task | 判定 | 分歧 | -|---|---|---| -| g1_motion_tracking · go2_handstand · go2_joystick_flat | ✅ | 无 | -| g1_walk_flat | ❌ | `env.actions.joint_pos.scale` 0.25↔0.5;`obs_normalization` false↔true;`obs_groups` | - -## `src/unilab/conf/appo/task/` - -| Task | 判定 | 分歧 | -|---|---|---| -| g1_motion_tracking · go2_joystick_flat | ✅ | 无 | -| g1_walk_flat | ⚪ | 仅 mujoco | - -已迁移的 Unitree owner 由 `unitree_rl_unilab` 自行维护 contract audit;核心状态表不再声称覆盖它们。 - -## 其它配置树 - -`src/unilab/conf/sac/task` 与 `src/unilab/conf/flashsac/task` -均无 mujoco↔motrix 配对,sim2sim 不适用。 - -## 字段语义速查 - -- **`env.control_config.action_scale`** —— 策略输出到关节目标的线性缩放系数; - 改动等价于动作幅值整体放缩,无法跨值迁移。 -- **`algo.actor.obs_normalization`** —— 是否在 actor 前插入 - running mean/std 归一化层。旧 run 快照中的 legacy 键 - `algo.empirical_normalization` 已退役:守卫不再做别名解析,含该键的快照直接 - fail-closed。 - 该层 buffer 烘进 checkpoint,ON / OFF 两类 checkpoint 不可互换;统一必须重训。 -- **`algo.obs_groups`** —— actor / critic 取哪几个 obs group 作为输入。 - 在多数 env 上 actor 实际输入由 `env.obs_groups_spec` 决定,YAML 中的差异常只影响 critic - 的训练侧,play 时不影响 actor。 -- **`env.commands.motion.params.sampling_mode`** —— motion-tracking task 的参考帧采样策略 - (旧快照键 `env.sampling_mode` 同样已退役并被拒绝)。 - -## 把 BLOCKED task 变为可迁移 - -| 字段 | 是否可仅改 YAML | 说明 | -|---|---|---| -| `obs_groups` | 可(多数情况) | 命名差异在两后端 owner 中统一,actor 部署不变 | -| `sampling_mode` | 可(取决于 task) | 两后端运行时已同值时只需补齐显式声明 | -| `action_scale` | **不可** | 改值即改训练动力学,必须 owner 决策 + 重训 | -| `obs_normalization` | **不可** | 改变网络结构,必须重训 | - -试点示例:`src/unilab/conf/ppo/task/g1_walk_flat/{base,mujoco,motrix}.yaml`。后端 owner 通过 Hydra -defaults 继承共享 base owner 的完整契约,`motrix.yaml` 为单后端调参 override -了若干契约字段——这种 override -即令该 task 在该后端不可 sim2sim 迁移,去掉 override 即可恢复。 +脚本只读:Hydra compose 每个 backend leaf(展开同目录 `base.yaml` 与 `_self_`), +按运行时归一化规则比较 DENYLIST/WARNING_LIST,不构造环境或 backend。当前审计对为: + +- `mujoco<->genesis` +- `mujoco<->mjwarp` +- `mjwarp<->genesis` +- `mujoco<->isaacgym` +- `mujoco<->isaacsim` + +判定分为 `TRANSFERABLE`(所有已审计对无 DENYLIST 分歧)、`BLOCKED`(至少一个已 +审计对有分歧)和 `N/A`(没有已审计对)。**N/A 不表示兼容,也不表示不兼容**; +Motrix、Newton、SuperDex、Drake 与 Motrix Warp 当前不在 `CONTRACT_PAIRS` 中。 + +## 当前工作区结果 + +本次复跑汇总为 `TRANSFERABLE: 5`、`BLOCKED: 0`,没有 guard-blind-spot 报告。 + +| 配置树 | Task | 判定 | 已审计对或 N/A 原因 | +| --- | --- | --- | --- | +| PPO | `g1_motion_tracking` | N/A | 仅有 MuJoCo/Motrix,无已审计对 | +| PPO | `g1_walk_flat` | TRANSFERABLE | MuJoCo↔Genesis、MuJoCo↔MJWarp、MJWarp↔Genesis | +| PPO | `go2_joystick_flat` | N/A | 现有 backend 未组成已审计对 | +| APPO | `g1_motion_tracking` | N/A | 仅有 MuJoCo/Motrix,无已审计对 | +| APPO | `g1_walk_flat` | N/A | 仅 MuJoCo | +| APPO | `go2_joystick_flat` | N/A | 仅有 MuJoCo/Motrix,无已审计对 | +| SAC | `g1_motion_tracking` | TRANSFERABLE | MuJoCo↔Genesis、MuJoCo↔MJWarp、MJWarp↔Genesis | +| SAC | `g1_walk_flat` | TRANSFERABLE | MuJoCo↔Genesis、MuJoCo↔MJWarp、MJWarp↔Genesis、MuJoCo↔IsaacGym、MuJoCo↔IsaacSim | +| FlashSAC | `g1_motion_tracking` | TRANSFERABLE | MuJoCo↔Genesis、MuJoCo↔MJWarp、MJWarp↔Genesis | +| FlashSAC | `g1_walk_flat` | TRANSFERABLE | MuJoCo↔MJWarp | +| FlashSAC | `go2_joystick_flat` | N/A | 仅 MuJoCo | + +## 字段与修正原则 + +- DENYLIST 覆盖 observation/action 结构、observation-group 映射、actor/critic + hidden dims 与 normalization、`env.ctrl_dt`、command limits 和 motion sampling 等 + 策略定义字段。网络形状或动作语义变化需要 owner 决策与重训,不能只改 play 配置。 +- WARNING_LIST 当前覆盖 reward 参数和 `simulate_action_latency`;差异会报告,但不 + 单独阻断。ALLOWLIST 当前包括 backend/scene identity、play steps 与 noise config。 +- 两侧 env 结构字段不对称时,应在目标 owner 中显式声明实际契约,而不是依赖 + dataclass 默认值让 guard 猜测。 +- 当前没有 `BLOCKED` 行。后续出现分歧时,以 `scripts/audit_sim2sim_contracts.py` + 输出的 pair/field/kind 定位;不要用本页的 `TRANSFERABLE` 结果覆盖新 run 的运行时 + 校验。 + +审计器与回归证据:`scripts/audit_sim2sim_contracts.py`、 +`tests/scripts/test_audit_sim2sim_contracts.py`。 diff --git a/docs/sphinx/source/zh_CN/6-how_to/1-onboard_new_robot.md b/docs/sphinx/source/zh_CN/6-how_to/1-onboard_new_robot.md index 6577f5c02..8e30e89c2 100644 --- a/docs/sphinx/source/zh_CN/6-how_to/1-onboard_new_robot.md +++ b/docs/sphinx/source/zh_CN/6-how_to/1-onboard_new_robot.md @@ -9,8 +9,9 @@ owner YAML({doc}`../2-user_guide/1-training/2-hydra_config`)以及 registry 需要安装仿真器、显示器或 GPU 的步骤都已标注。纯组合检查(`--cfg job`)仍会 经过 CLI 的后端预检,因此 `--sim mujoco` 需要 `mujoco` extra;被路由的 PPO -入口还会导入内置 RL 栈,所以还需要 `unirl` extra(源码检出中执行 -`uv sync --extra mujoco`——与 `make setup` 相同的同步命令)。 +入口还会导入内置 RL 栈。源码检出中执行 `uv sync --extra mujoco`(默认 `rl` +依赖组会提供 `unirl`;与 `make setup` 相同);使用 pip 安装时则执行 +`pip install 'unilab[mujoco,unirl]'`。 ## 0. 选定名称 @@ -22,6 +23,13 @@ owner YAML({doc}`../2-user_guide/1-training/2-hydra_config`)以及 registry (`src/unilab/cli.py` 中的 `_check_task_name`)。 - `` —— PascalCase 的 registry 键,例如 `Go2JoystickFlat`。 +用 `src/unilab/cli.py` 的同一正则验证 CLI 任务名: + +```bash +uv run python -c 'from unilab.cli import TASK_NAME_PATTERN; assert TASK_NAME_PATTERN.fullmatch(""); print("task name accepted")' +# 预期:task name accepted +``` + ## 1. 准备资产 按 {doc}`../2-user_guide/7-tooling/5-robot_import` 操作。URDF 源: @@ -31,9 +39,10 @@ uv run scripts/tools/import_robot.py [robot_name] ``` 脚本通过 `urdf-to-mjcf` 转换 URDF、整理 mesh,并打开 `mujoco.viewer` 供 -keyframe 调整(实现:`scripts/tools/import_robot.py`)。它把场景 fragment -写为 `scene.xml`;fragment 的名字可以保留或自行修改——Go2 的参考实现用的是 -`scene_flat.xml`。如果源已经是 MJCF,手工按同一目录契约摆放: +keyframe 调整(实现:`scripts/tools/import_robot.py`)。它写出的 `scene.xml` +只有 `home` keyframe。训练前必须在该 fragment 中补齐机器人 XML 的 +``、地面和所需任务传感器;文件名可保留 `scene.xml` 或自行修改(Go2 +参考实现使用 `scene_flat.xml`)。如果源已经是 MJCF,手工按同一目录契约摆放: - `src/unilab/assets/robots//assets/` —— 仅 `.stl` / `.obj` mesh。 - `src/unilab/assets/robots//.xml` —— 仅含机器人的 MJCF: @@ -84,8 +93,10 @@ ls src/unilab/assets/robots// ```bash grep -n '/.xml -# 预期:0 —— keyframe 不进入机器人 XML。 +! grep -n '/.xml +# 预期:无输出且命令成功——keyframe 不进入机器人 XML。 +uv run python -c 'import mujoco; mujoco.MjModel.from_xml_path("src/unilab/assets/robots//scene_flat.xml")' +# 预期:无输出;场景、机器人 include、mesh 与 keyframe 均可编译。 ``` ## 3. 编写 owner YAML @@ -198,8 +209,9 @@ reward: `track_angular_velocity`)读 root state 而不是具名传感器,只要 command 名为 `twist` 就能用于任意机器人;参数与语义见 {doc}`../5-reference/6-manager_terms/1-rewards`。 -- 当算法需要消费特权观测时,再加 `critic` 观测组和 - `env.critic_observation_group: critic`(Go2 owner 两者都有)。 +- 当算法需要消费特权观测时,添加 `critic` 观测组,设置 + `env.critic_observation_group: critic`,并在 `algo.obs_groups` 下添加 + `critic: [critic]`(Go2 owner 三者齐备)。 后端 owner(`src/unilab/conf/ppo/task//mujoco.yaml`),参照 `src/unilab/conf/ppo/task/go2_joystick_flat/mujoco.yaml`: @@ -270,15 +282,15 @@ print(registry.list_registered_envs()['']) {doc}`../5-reference/5-support_matrix`,DR term 另查 {doc}`../2-user_guide/5-domain_randomization/2-field_reference`。 不支持的能力在构造期 fail closed;后端无法服务的 term 在该后端 owner 里 - 置为 `null`(模式:`src/unilab/conf/ppo/task/go2_joystick_flat/motrix.yaml` + 置为 `null`(模式:`src/unilab/conf/ppo/task/go2_joystick_flat/drake.yaml` 中的 `pd_gains: null`)。 每加一个后端验证一次:用 `--sim ` 重跑 `--cfg job` 组合检查。 ## 6. 首次训练 -需要后端的 Python extra 以及 `unirl` RL 栈 extra -(`uv sync --extra mujoco`);有意义的运行需要 GPU。先小规模: +需要后端的 Python extra 以及 RL 栈(安装命令见上文);有意义的运行需要 GPU。 +先小规模: ```bash uv run train --algo ppo --task --sim mujoco \ @@ -332,5 +344,5 @@ uv run eval --algo ppo --task --sim mujoco --load-run -1 - 添加或调权 reward term:{doc}`2-custom_reward`。 - 内置 term 速查表:{doc}`../5-reference/6-manager_terms/0-index`。 - 同一契约的清单视角:{doc}`../4-developer_guide/3-extending/1-new_task`。 -- 对出生场景做交互式目视冒烟检查(需要显示器): - `uv run scripts/visualize_task_env.py --task --backend mujoco --num_envs 4`。 +- 对训练后的策略做交互式目视冒烟检查(需要显示器): + `uv run eval --algo ppo --task --sim mujoco --load-run -1 --render-mode interactive`。 diff --git a/docs/sphinx/source/zh_CN/6-how_to/2-custom_reward.md b/docs/sphinx/source/zh_CN/6-how_to/2-custom_reward.md index 5b2a9b3a4..5cc574625 100644 --- a/docs/sphinx/source/zh_CN/6-how_to/2-custom_reward.md +++ b/docs/sphinx/source/zh_CN/6-how_to/2-custom_reward.md @@ -1,8 +1,8 @@ # 演练:添加自定义 Reward Term -本演练从零开始添加一个 reward term,直到它在真实训练会话中运行、且其逐项 -数值在训练日志中可见。运行时是 Torch-only(1.3.4 起;见 changelog 与 -ADR-0011)——term 返回 `torch.Tensor`,没有 NumPy 路径。 +本演练从零开始添加一个 reward term,跑通真实训练会话,并说明如何在 +SAC/FlashSAC 训练日志中查看其逐项数值。运行时是 Torch-only(1.3.4 起;见 +changelog 与 ADR-0011)——term 返回 `torch.Tensor`,没有 NumPy 路径。 ## 1. 定义 term @@ -29,6 +29,13 @@ def action_magnitude_l1(env: ManagerBasedRlEnv) -> torch.Tensor: return torch.sum(torch.abs(env.action_manager.action), dim=1) ``` +验证新函数能从稍后将写入 YAML 的精确路径导入: + +```bash +uv run python -c 'from unilab.tasks.locomotion.common.sensor_reward_terms import action_magnitude_l1; print(action_magnitude_l1.__name__)' +# 预期:action_magnitude_l1 +``` + 返回契约由 `RewardManager._compute_term` 强制执行 (`src/unilab/managers/reward_manager.py`):形状为 `(num_envs,)` 的 `torch.Tensor`,dtype 为 `float32`,位于 env 设备上。类型、dtype、设备或 @@ -64,7 +71,8 @@ reward: 惩罚项用负权重——框架的惩罚 term 返回非负代价,不要再取负一次。 验证组合结果(仍会经过 CLI 的后端预检;`--sim mujoco` 需要 `mujoco` -extra,且被路由的训练脚本会导入 RL 栈,因此还需要 `unirl` extra): +extra,且被路由的训练脚本会导入 RL 栈。源码检出中执行 +`uv sync --extra mujoco` 也会安装默认 `rl` 依赖组): ```bash uv run train --algo ppo --task --sim mujoco --cfg job \ @@ -82,23 +90,37 @@ uv run train --algo ppo --task --sim mujoco \ algo.num_envs=64 algo.max_iterations=5 training.no_play=true ``` -Manager-Based 环境在设备侧维护逐项加权 reward 均值 -(`src/unilab/managers/reward_manager.py` 的 +短跑成功完成即验证了 term 的构造与返回契约。Manager-Based 环境在设备侧维护 +逐项加权 reward 均值(`src/unilab/managers/reward_manager.py` 的 `RewardManager.step_reward_means`——跨环境对 `raw_value * weight` 取均值, 未乘 `dt`)。其中有多少进入训练日志取决于算法路由: -- **PPO(rsl_rl)**:自 1.5.8 起,逐项 `reward/` 标量不再写入 - `info["log"]`,改以定长 `info["reward_components"]` 张量传递,只有 - off-policy 运行时消费它。控制台与 TensorBoard +- **PPO(rsl_rl)**:环境发布定长 `info["reward_components"]` 张量,但 PPO + adapter 不转发它;adapter 转发的 `info["log"]` 中也没有逐项 reward。 + 控制台与 TensorBoard (`uv run tensorboard --logdir logs/rsl_rl_ppo/`——该级目录 是 `training.task_name` 的 registry 名,不是 snake_case 的 CLI 任务名) 显示聚合的 `Train/mean_reward`;首个 episode 结束后出现 `Episode_Termination/` 计数器。 -- **SAC / FlashSAC / APPO**:off-policy 运行时消费 `reward_components` 并 - 输出 `reward/` 指标族(schema 见 +- **APPO**:worker 从 `info["log"]` 读取逐项 reward,但 Manager-Based 环境 + 不向该映射发布这些值,因此此路由同样不输出 `reward/`。 +- **SAC / FlashSAC**:off-policy 运行时消费 `reward_components` 并输出 + `reward/` 指标族(schema 见 `src/unilab/rl/logging/metric_schema.py`),同时出现在控制台与 TensorBoard / W&B({doc}`../2-user_guide/1-training/3-logging`)。 +要端到端验证新 term 的逐项数值,把同一个 reward 块加入 +`src/unilab/conf/sac/task//base.yaml`(或其 backend 兄弟文件),再运行 +对应的 SAC owner 并检查日志: + +```bash +uv run train --algo sac --task --sim mujoco \ + algo.num_envs=64 algo.max_iterations=5 training.no_play=true +uv run tensorboard --logdir logs/sac/ +# 预期:collector 指标刷新后,控制台 reward 表出现 action magnitude 行, +# TensorBoard 出现 reward/action_magnitude 标签。 +``` + 在 1.5.9(MuJoCo 后端,单卡 RTX 4090)上实测。PPO(`go2_joystick_flat`, `algo.num_envs=16 algo.max_iterations=1`)终端节选——只有聚合值: @@ -132,10 +154,11 @@ term 出错时在任一路由下失败都是显式的:构造错误会指出 te ## 4. 调整权重 -已声明的 term 可以在命令行直接调权,无需改 YAML: +已声明的 term 可以在命令行直接调权,无需改 YAML。请选择其 owner 包含该 +term 的算法: ```bash -uv run train --algo ppo --task --sim mujoco \ +uv run train --algo --task --sim mujoco \ reward.action_magnitude.weight=-0.01 ``` diff --git a/docs/sphinx/source/zh_CN/6-how_to/3-training_diagnostics.md b/docs/sphinx/source/zh_CN/6-how_to/3-training_diagnostics.md index ce96e4351..c34f2cf62 100644 --- a/docs/sphinx/source/zh_CN/6-how_to/3-training_diagnostics.md +++ b/docs/sphinx/source/zh_CN/6-how_to/3-training_diagnostics.md @@ -29,9 +29,20 @@ NaN guard 在设备侧检查观测、reward 与控制量中的非有限行,并 `check_interval` 是 deferred 模式下的轮询周期。defer 模式本身不是 guard 字段:guard 挂载时跟随 env 的单一校验严格度 (`env.finite_validation_mode`,issue #2618)。 -2. 训练入口把 guard 挂到 env 上(`src/unilab/training/run.py` 的 - `apply_env_nan_guard`),`TorchEnv.step` 每步调用 `NanGuard.check(...)`。 - 检出时 `NanGuard.dump(...)` 写出 `nan_dump_<时间戳>_step.npz` + + 验证组合后的 guard 与校验设置: + + ```bash + uv run train --algo ppo --task go2_joystick_flat --sim mujoco --cfg job \ + | grep -E 'nan_guard|check_interval|capture_interval|finite_validation_interval' + # 预期:nan_guard 与两个 interval,以及 finite_validation_interval: 32。 + ``` + +2. PPO 入口通过 `apply_env_nan_guard` 挂载 guard + (`src/unilab/training/run.py`);off-policy collector 也从 + `training.nan_guard` 挂载同一个 guard。`TorchEnv.step` 每步调用 + `NanGuard.check(...)`。检出时 `NanGuard.dump(...)` 写出 + `nan_dump_<时间戳>_step.npz` (状态环形缓冲加 `meta_*` 字段,如 `detection_step` 与 `nan_env_ids`), 把模型文件复制到旁边,并更新 `nan_dump_latest.npz` 软链。 3. 在 MuJoCo viewer 中回放 dump(需要 `mujoco` extra 与显示器): @@ -43,23 +54,40 @@ NaN guard 在设备侧检查观测、reward 与控制量中的非有限行,并 `unilab-viz-nan` 是 `src/unilab/utils/nan_viz.py` 注册的 console 入口 (`pyproject.toml`);它先打印检出步数与 NaN env id,再回放缓冲状态。 不支持物理状态回放的后端 dump 中没有状态——viewer 只打印元数据。 + `--env-index` 选择的是 `meta_dumped_env_ids` 内的行号,不一定是原始 env id。 + + 没有显示器时,在主机侧验证 dump 元数据: + + ```bash + uv run python -c 'import numpy as np; d = np.load("/tmp/unilab/nan_dumps/nan_dump_latest.npz"); print(d["meta_detection_step"], d["meta_nan_env_ids"], d["states"].shape)' + # 预期:检出步数、异常 env id 与已保存状态的形状。 + ``` 细节与 viewer 操作见 {doc}`../2-user_guide/7-tooling/3-nan_visualizer`。往返加载覆盖: `tests/training/test_tensor_diagnostics.py`。 -## 读懂 `info["log"]` +## 读懂训练指标 -Manager-Based 环境把结构化指标放进 `info["log"]`;训练 logger 把带斜杠前缀的 -条目转发到 TensorBoard / W&B。完整语义表见 {doc}`../2-user_guide/1-training/3-logging`;键族与生产者: +Manager-Based 环境把结构化 episode 指标放进 `info["log"]`;训练 logger 把带 +斜杠前缀的条目转发到 TensorBoard / W&B。逐项 reward 使用独立的 +`info["reward_components"]` 张量通道,目前只有 SAC/FlashSAC 运行时把它转成 +持久化的 `reward/` 指标。完整语义表见 +{doc}`../2-user_guide/1-training/3-logging`;键族与生产者如下: | 键 | 生产者 | 含义 | | --- | --- | --- | -| `reward/` | `RewardManager.step_reward_extras()`(`src/unilab/managers/reward_manager.py`) | 各 term 的 `raw_value * weight` 跨环境均值,未乘 `dt` | +| `reward/` | `CollectorMetrics` 与 `OffPolicyLogger`(`src/unilab/rl/runtime/offpolicy/metrics.py`、`src/unilab/rl/logging/offpolicy.py`) | SAC/FlashSAC 各 term 的 `raw_value * weight` 跨环境均值,未乘 `dt`;PPO 与当前 Manager-Based APPO 不输出 | | `Episode_Termination/` | `TerminationManager.reset()`(`src/unilab/managers/termination_manager.py`) | 因该终止 term 而 reset 的环境行数 | | `Episode_Metrics/` | `MetricsManager`(`src/unilab/managers/metrics_manager.py`) | 已完成 episode 的指标聚合 | -整体进展看 `Train/mean_reward` 与 `Train/mean_episode_length`,归因看 -`reward/`;两者区别见 {doc}`../2-user_guide/1-training/3-logging`。 +整体进展看 `Train/mean_reward` 与 `Train/mean_episode_length`。SAC/FlashSAC +可用 `reward/` 归因;PPO 与 APPO 则使用聚合值和 episode 级指标。用训练 +打印的运行目录验证实际可用的键: + +```bash +uv run tensorboard --logdir +# 预期:Train/* 与 episode 指标;reward/ 仅见于 SAC/FlashSAC。 +``` ## 常见失败模式 @@ -68,14 +96,16 @@ Manager-Based 环境把结构化指标放进 `info["log"]`;训练 logger 把 - 症状:训练以 `RewardManager term '' returned NaN/Inf for environments ...` 中止(`src/unilab/managers/reward_manager.py`),或 NaN guard 写出 dump。 -- 查:逐项的 `reward/` 曲线——发散的 term 通常最先分离。对照 owner - YAML `reward:` 块中它的原始量级与 `weight`。 +- 查:SAC/FlashSAC 下检查逐项 `reward/` 曲线——发散的 term 通常最先 + 分离。PPO/APPO 没有这些曲线;根据异常中的 term 名,对照 owner YAML + `reward:` 块中它的原始量级与 `weight`。 - 改:用 CLI 调权,例如 `uv run train --algo ppo --task --sim mujoco reward..weight=-0.01`(override 机制见 - {doc}`../2-user_guide/2-algorithms/1-ppo` 的 “Reward term weights” 小节)。保留 - 平滑/正则项(`action_rate` 类惩罚);删掉它们常常直接导致动作流不稳定。 + {doc}`../2-user_guide/2-algorithms/1-ppo` 的 “Reward term weights” 小节)。长训前 + 在该命令末尾添加 `--cfg job | grep -A2 ''` 验证新值。保留平滑/正则项 + (`action_rate` 类惩罚);删掉它们常常直接导致动作流不稳定。 -### 策略不收敛 +### PPO 策略不收敛 - 症状:`Train/mean_reward` 持平但迭代在推进。 - 对照算法参考表查超参(PPO 见 {doc}`../2-user_guide/2-algorithms/1-ppo`): @@ -83,8 +113,17 @@ Manager-Based 环境把结构化指标放进 `info["log"]`;训练 logger 把 `algo.algorithm.lam`。检查 `algo.num_envs`——它是按 rank 计的数量,过小会 让梯度估计失真。检查观测条件:`algo.actor.obs_normalization`(Go2 owner 开启了它),以及是否有观测 term 输出了异常量纲的值。 -- 检查 reward 配比:如果跟踪项(`reward/tracking_*`)一直接近零而惩罚项主导 - `reward/` 曲线,问题是权重失衡而不是优化器。 +- 检查 reward 配比:SAC/FlashSAC 下比较 `reward/tracking_*` 与惩罚项曲线; + PPO 下对照 owner YAML 中跟踪/惩罚权重与聚合回报。如果跟踪项一直接近零而 + 惩罚项占主导,问题是权重失衡而不是优化器。 + + 验证实际组合出的 PPO 数值: + + ```bash + uv run train --algo ppo --task --sim mujoco --cfg job \ + | grep -E 'num_envs|learning_rate|entropy_coef|lam:|obs_normalization' + # 预期:预期的环境数、优化器数值与归一化开关。 + ``` ### 两个后端行为不一致 @@ -94,7 +133,14 @@ Manager-Based 环境把结构化指标放进 `info["log"]`;训练 logger 把 `resolve_sim2sim_config`)。DENYLIST 字段(observations、actions、网络 形状、`ctrl_dt` 等)必须一致——默认 `training.sim2sim_strict: true` 下不一致 会抛 `CrossBackendIncompatibleError`;WARNING_LIST 字段只打印警告。审计已发布 - 的组合用 `uv run scripts/audit_sim2sim_contracts.py`。 + 的组合用 `uv run scripts/audit_sim2sim_contracts.py`。对自己的 checkpoint, + 用源运行目录名(不是路径)执行真实的预检: + + ```bash + uv run eval --algo ppo --task --sim --load-run + # 预期:DENYLIST 不一致会在构造 env 前抛错;否则开始回放。 + ``` + - 查后端能力差异:{doc}`../3-deployment/2-sim_to_sim/6-capability_gaps`; 精确支持等级:{doc}`../5-reference/5-support_matrix`。 @@ -103,7 +149,8 @@ Manager-Based 环境把结构化指标放进 `info["log"]`;训练 logger 把 - 走上面的 NaN 链:dump 中的 `meta_detection_step` 与 `meta_nan_env_ids` 缩小时间窗;回放状态可以看出是姿态发散(资产/keyframe 问题)还是控制量爆炸 (reward/动作尺度问题)。 -- 对照检出步之前的 `reward/` 曲线,找最先发散的 term。 +- SAC/FlashSAC 下对照检出步之前的 `reward/` 曲线,找最先发散的 term; + PPO/APPO 下改用异常中的 term 名与 dump 元数据定位。 ### 性能与 trace 分析 @@ -112,14 +159,20 @@ Manager-Based 环境把结构化指标放进 `info["log"]`;训练 logger 把 `training.trace_cuda_events`(`src/unilab/conf/sac/config.yaml`),另有 CUDA 上 NVTX 标注用的 `training.nvtx_profile_ranges`。trace 是 Perfetto JSON;标量计时键见 {doc}`../2-user_guide/1-training/3-logging`。 -- 在主机侧分析已捕获的 trace(不需要 GPU): +- 先采集一次短 SAC trace,再在主机侧分析(采集需要后端与 RL 栈;分析不需要 + GPU): ```bash - uv run scripts/analyze_offpolicy_trace.py --training-e2e \ + uv run train --algo sac --task --sim mujoco \ + algo.num_envs=64 algo.max_iterations=5 training.no_play=true \ + training.trace_enabled=true training.trace_output_dir= + uv run scripts/analyze_offpolicy_trace.py \ + /perfetto_offpolicy_timeline.json --training-e2e \ --event collector/env_step --gap-event learner/training_e2e ``` 脚本按事件名报告 mean/median/p90/p95/p99 时长;`--steps-per-cycle` 与 - `--drop-first` 调整吞吐量汇总。 + `--drop-first` 调整吞吐量汇总。检查 `training_e2e` 与 `collector/env_step` + 的样本数均非零。 - 生产环境长 soak 的设置与失败分类字段见 {doc}`../2-user_guide/1-training/7-tensor_runtime_production`。 diff --git a/docs/sphinx/source/zh_CN/why_unilab.md b/docs/sphinx/source/zh_CN/why_unilab.md index b79678c92..62d040877 100644 --- a/docs/sphinx/source/zh_CN/why_unilab.md +++ b/docs/sphinx/source/zh_CN/why_unilab.md @@ -45,8 +45,7 @@ Warp 与 VBD/MPM 耦合,用于接触丰富的任务。solver 选择越来越 的 solver 都必须先 CUDA 化,机器人训练才能使用。 UniLab 是位于 physics engine 演进之上的 RL 基础设施/runtime 层。当仓库具备对应配置和 -验证证据时,它可以连接 MuJoCo、Motrix、Newton 或其他注册 adapter。UniLab 不声称 -每个 solver 或 task 组合都已经达到生产就绪。 +验证证据时,它可以连接 MuJoCo、Motrix、Newton 或其他注册 adapter。 ## 范围 diff --git a/scripts/motion/README.md b/scripts/motion/README.md index 0ea6eadc7..efaaaad75 100644 --- a/scripts/motion/README.md +++ b/scripts/motion/README.md @@ -132,6 +132,8 @@ uv run scripts/motion/csv_to_npz.py \ - `--model_file`: MuJoCo model file (default: G1 flat scene) - `--line_range`: 1-based motion-frame range to process [start, end] (optional); the range is independent of an optional CSV header +- `--start_time` / `--end_time`: Optional time range in seconds; when either is + set, it takes precedence over `--line_range` ### Notes @@ -139,3 +141,44 @@ uv run scripts/motion/csv_to_npz.py \ - Velocities are computed using numerical differentiation - Forward kinematics is computed using MuJoCo for all bodies - The output FPS should match the control frequency of your training environment (typically 50 Hz) + +## Full-body NPZ Remapping + +The `remap_fullbody_npz.py` script converts an NPZ exported from a detailed +MuJoCo model to the training model's body layout. The source NPZ must contain +`body_names`; the script reindexes body arrays by name and removes the root +free-joint prefix from `joint_pos` (7 columns) and `joint_vel` (6 columns). + +```bash +uv run scripts/motion/remap_fullbody_npz.py \ + --input path/to/fullbody_motion.npz \ + --output path/to/training_motion.npz + +# Select another training model, or validate without writing output +uv run scripts/motion/remap_fullbody_npz.py \ + --input path/to/fullbody_motion.npz \ + --output path/to/training_motion.npz \ + --model_file path/to/scene_flat.xml \ + --dry-run +``` + +The default target model is the G1 flat scene. + +## NPZ Replay + +The `replay_npz.py` script replays a preprocessed NPZ in the MuJoCo viewer. If +the NPZ contains `joint_names`, replay uses that order; otherwise, the joint +array width must match the model's scalar joints in qpos order. + +```bash +uv run scripts/motion/replay_npz.py --npz_file path/to/motion.npz + +# Loop at half speed with a custom model +uv run scripts/motion/replay_npz.py \ + --npz_file path/to/motion.npz \ + --model_file path/to/scene.xml \ + --loop \ + --speed 0.5 +``` + +Press `Space` to pause or resume, and close the viewer or press `Esc` to quit.