Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions .agents/skills/motrixlab-code-style/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
---
name: motrixlab-code-style
description: 编写、重构或审查 MotrixLab Python 代码时使用的仓库通用编程风格。强调显式且类型化的接口、清晰的依赖和所有权、最小必要抽象;避免无必要的 getattr/hasattr、object.__setattr__、防御式分支和兼容层。同一 PR 内跨 commit 的内部迁移直接更新全部调用方,不为中间实现保留前向或后向兼容。不规定具体业务逻辑或算法实现。
---

# MotrixLab Code Style

目标:让当前需求的实现直接、可读、可追踪,而不是让代码适配所有假设中的对象、版本和未来场景。

本 skill 描述整个仓库通用的编程与评审风格,不规定特定业务、算法或第三方框架的实现方式。先读仓库根目录和修改目录适用的 `AGENTS.md`,领域契约以相应代码和规范为准,不在这里重复维护。

## 工作步骤

1. 阅读目标实现、构造流程、实际调用方和相关测试,确认必需字段与真实可选能力。
2. 确认当前需求、公共边界,以及对象、资源和状态的所有权。
3. 优先直接访问、准确类型和简单组合;仅在真实边界需要时引入适配、校验或抽象。
4. 修改内部契约时,同步迁移实现、调用方、配置和测试。
5. 运行受影响范围的低成本行为测试与现有静态检查;提交前遵循仓库 pre-commit 要求。
6. 报告实际变更、验证结果及未验证部分,不将静态检查描述为运行时验证。

下文代码均为独立的虚构教学示例,不对应仓库当前实现。

## 1. 显式属性优先,反射不是内部契约

对于已知类型及其必需字段,直接访问。缺少必需字段是实现错误,不应静默降级。

```python
from dataclasses import dataclass


@dataclass
class PageOptions:
width: int


# 不推荐:类型已经声明 width,fallback 隐藏了内部契约。
def page_width(options: PageOptions) -> int:
return getattr(options, "width", 640)


# 推荐:初始化与调用方共同遵守明确的类型契约。
def page_width(options: PageOptions) -> int:
return options.width
```

- 不用 `getattr`、`hasattr` 或 `try/except AttributeError` 模拟已知对象的必需接口。
- 不通过字符串字段列表循环赋值来节省几行明确的依赖声明。
- 不把无必要的 `getattr` 改写成 `hasattr + if`,也不包 helper 掩盖同一个 fallback。
- 真正的可选值用显式字段和 `T | None` 表达;默认值在配置构造或边界组装处确定,不在执行路径层层补齐。
- 真正动态的接口解析、插件发现、用户选择的字段或第三方适配可以使用反射,但应限制在解析与适配边界。
- 不仅凭语法判断问题;保留动态访问需要真实契约依据,删除时也应确认不会破坏已确立的扩展能力。

## 2. 参数和结果类型化

- 新增或实质修改的函数、构造函数和方法,为参数及返回值提供有意义的类型注解;构造函数返回 `None`。
- 优先已有具体类型,不用 `object`、`Any` 或过宽基类掩盖实际依赖的方法与字段。
- 仅在真实的多实现需求或公共扩展契约需要时引入 `Protocol`,不要为单个具体调用方投机性增加接口层。
- 固定字段的内部数据优先用具名类型或普通 `@dataclass`,不靠 `dict[str, Any]`、`SimpleNamespace` 和运行时补属性传递契约。项目声明式配置遵循已有配置体系,不机械改成 dataclass。
- 可选值、分支结果和容器元素的类型应明确;不要依靠调用方猜测结构或解释位置不明的返回值。
- 类型与数据结构服务于真实接口,不为追求包装形式破坏底层库要求或增加无意义转换。
- 为单位、顺序、生命周期等非显然语义补充必要说明;类型注解不等于重复运行时校验。
- 避免用 `cast`、`# type: ignore` 或虚假的过宽注解掩盖未建立的契约。确需使用时说明原因。
- 只有存在真实循环导入或可选依赖需求时,才引入 `TYPE_CHECKING` 等处理,不机械增加模板代码。

## 3. 依赖与所有权显式,避免底层绕过

- 优先正常构造、普通赋值和显式依赖注入,避免把 `object.__setattr__`、手工修改 `__dict__` 或框架私有字段作为默认设计工具。
- 配置类不得在 `__post_init__` 中通过 `object.__setattr__`、直接调用 `__setattr__`、修改 `__dict__` 等方式绕过正常配置机制、隐式修改字段。派生值优先使用 `property`;配置补全与跨字段组装放在显式构造流程中,不通过底层写入规避 frozen 或配置约束。确需底层写入的配置装饰器等框架基础设施实现不适用此禁令,但须局部说明必要性;不能以 frozen dataclass 为由默认放行普通配置或数据对象的绕写。
- 构造函数明确表达必需依赖,不通过事后补属性完成正常初始化。
- 只传组件需要的依赖;不为读取少量字段而传入整个应用对象或大型上下文。
- 区分自有对象和借用依赖,明确谁负责创建、修改、清理和持久化,不让多个组件隐式承担同一职责。
- 通过组合或普通类型化数据对象表达真实的依赖分组;不要仅为绕开一种语法添加容器或通用依赖框架。
- 使用具有特殊属性赋值、注册或生命周期机制的框架时,优先其公开 API,并明确普通属性与框架管理对象的区别。
- 特殊底层机制确实不可替代时,局部保留并解释必要性、不变量和验证方式,而不是机械禁用或在各处扩散。

## 4. 校验放在边界,不重复防御

必要校验放在用户输入、配置加载、文件、网络、第三方接口或明确的公共契约入口。边界建立契约后,内部代码信任它。

```python
from dataclasses import dataclass


@dataclass
class TextBlock:
lines: list[str]


# 不推荐:对必需字段静默返回默认值,掩盖上游错误。
def line_count(block: TextBlock) -> int:
if not hasattr(block, "lines") or block.lines is None:
return 0
return len(block.lines)


# 推荐:边界负责解析外部数据,内部直接使用类型化字段。
def line_count(block: TextBlock) -> int:
return len(block.lines)
```

- 不反复检查内部对象的类型、字段、形状、有限性或取值范围。
- 不捕获宽泛异常并返回默认结果,不为假设性错误增加辅助函数和分支。
- 不用 `assert` 替换本来就不需要的防御分支。
- 保留有真实依据的安全约束、数值稳定性措施、资源清理和公共错误诊断;它们不因包含检查就属于过度防御。
- 能在初始化或解析阶段确定的选项,不在每次执行时重复探测。
- 错误信息应说明实际失败的契约,不静默吞掉实现错误。
- 不要对无效配置、不可用设备、越界索引、缺失能力或不兼容输入做静默降级;应在配置/边界处明确报错。只有公共契约明确规定的默认值或可选能力,才可以显式返回默认分支,并让该可选性体现在类型或接口中。

## 5. 同一 PR 内直接迁移,不兼容中间版本

同一 PR 的不同 commit 是实现演进,不是需要彼此兼容的已发布版本。默认最终分支中的内部实现、配置和调用方共同遵守新契约。

- 字段或函数改名时同步更新调用方,不保留旧名 alias、双字段读取、旧签名 wrapper 或新旧格式自动探测。
- 不因为本 PR 的早期 commit 曾采用另一种结构,就添加兼容分支、迁移器或版本号。
- 测试 double 和 fixture 应迁移到新契约,不为简化测试对象削弱生产接口。
- 各 commit 可以组织为可验证的完整步骤,但不要求新旧内部实现混用,也不通过长期兼容层实现逐 commit 可运行。
- 已发布公共 API、持久化数据格式、独立发布的插件及明确支持的第三方版本属于另一类契约。先确认支持范围,不能以“同一 PR 无需兼容”为由破坏这些边界。
- 真实兼容需求应注明消费者、格式或版本及支持范围;无证据的假设不构成保留兼容层的理由。

## 6. 模块化服从当前需求

- 优先小而直接的函数、明确的对象职责和最少依赖,不以类或文件数量衡量模块化程度。
- 相同规则只维护一处;共享逻辑与外部适配分离,但不为表面相似强行统一不同契约。
- 提取边界应有真实职责或复用价值,不把每一段计算都包装成类。
- 不为消除两行重复新增 registry、通用 resolver 或一组只有一个实现的接口。
- 默认值在明确的组装位置集中确定,避免多层覆盖与隐藏优先级。
- 从符号定义模块导入,保持 initializer 精简;保留有依据的公共 API 和注册副作用,不增加仅为内部便利服务的聚合门面。
- 命名反映职责和数据语义;注释解释原因、约束及非显然取舍,不复述显而易见的代码,也不记录临时调试历史。
- 改动限于当前需求及其必要调用链,不顺手扩展为无关的全仓库清理。

## 7. 验证与评审清单

修改后逐项确认:

- [ ] 必需字段直接访问;保留的动态访问有真实边界理由。
- [ ] 接口类型表达实际输入和输出,没有用弱类型容器代替契约。
- [ ] 依赖、状态和资源的所有权明确,没有无必要的底层绕过。
- [ ] 配置类的 `__post_init__` 未通过底层属性写入隐式修改字段;派生值与配置组装采用 property 或显式构造。
- [ ] 新增校验位于合理边界,没有静默 fallback 和重复内部检查。
- [ ] 实现、调用方、配置和测试同步迁移,没有只服务于中间 commit 的兼容代码。
- [ ] 抽象由当前需求驱动,没有扩大任务范围。
- [ ] 测试保护输入输出、状态转换或关键不变量,不绑定无关内部结构或易变配置值。
- [ ] 旧路径引用扫描等一次性迁移验收未固化为长期负向测试。
- [ ] 明确记录实际执行的检查及未验证部分。

评审反馈指出具体位置、真实契约和风险,并给出最小改进方向。不要只罗列禁用语法,也不要把某个业务模块的实现偏好推广为全仓库规则。
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ MotrixLab 是构建在 MotrixSim 仿真后端之上的强化学习框架,提
- `motrix_robots`:可复用机器人配置、默认姿态与模型资产;仅依赖 core。框架代码从定义模块导入模型类,例如 `motrix_robots.unitree`
- `motrix_envs`:内置环境与任务资产
- `motrix_rl`:RL 控制平面、训练编排与稳定 contracts(runner、run/checkpoint、backend 选择、`motrix_rl.frameworks` discovery、provider/trainer 接口)
- `motrix_rl_builtin`:内置 Motrix FastSAC provider 插件
- `motrix_rl_builtin`:内置 Motrix 算法集成插件,统一注册 FastSAC 与 SuperMimic provider
- `motrix_rl_supermimic`:独立的 SuperMimic world-model MBRL 实现与 provider,由 builtin 集成注册
- `motrix_rl_skrl`:SKRL PPO provider 插件(Torch 必需,额外 JAX runtime 可选)
- `motrix_rl_rslrl`:RSLRL PPO provider 插件(Torch)
- `motrix_deploy`:框架无关的 artifact、运行时契约与部署 CLI
Expand Down
7 changes: 7 additions & 0 deletions motrix_rl/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ extras. The workspace root requires `motrix-rl-builtin` and `motrix-rl-skrl`, en
for the built-in demos. The root `skrl-jax` extra adds the JAX backend; `rslrl` adds the optional RSLRL plugin.
Runtime installation does not force other optional workspace packages.

## Asynchronous transition transport

`motrix_rl.transport` provides bounded host and CUDA-IPC rings for provider collectors. Transition schemas distinguish
per-environment fields (the default) from `scope="global"` fields, which carry one native-shaped value per slot.
CUDA IPC stores the two scopes in separate shared GPU allocations and publishes them together; task-global state does
not need to be repeated across environments. Consumers must finish reads before acknowledging slots for reuse.

## GPU installation profiles

`motrix-rl[cuda]` and `motrix-rl[rocm]` define the tested NVIDIA and AMD Torch dependency profiles. Without either extra,
Expand Down
2 changes: 1 addition & 1 deletion motrix_rl/src/motrix_rl/transport/ring.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ def __init__(
num_envs: int,
cursors: RingCursors | None = None,
payload_store: SlotPayloadStore | None = None,
):
) -> None:
if capacity < 1:
raise ValueError(f"ring_capacity must be >= 1, got {capacity}")
self.schema = schema
Expand Down
13 changes: 9 additions & 4 deletions motrix_rl_builtin/README.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
# Motrix RL Builtin

`motrix-rl-builtin` owns MotrixLab's built-in reinforcement-learning integrations, currently FastSAC. Its Python namespace
is `motrix_rl_builtin`; FastSAC configuration and implementation live under `motrix_rl_builtin.fastsac`.
`motrix-rl-builtin` integrates MotrixLab's built-in reinforcement-learning algorithms under the `motrix` framework:
`motrix.fastsac` and `motrix.supermimic`, both using the Torch training backend. Its Python namespace is `motrix_rl_builtin`;
FastSAC configuration and implementation live under `motrix_rl_builtin.fastsac`.

The plugin owns FastSAC models, replay buffers, environment wrappers, synchronous/asynchronous trainers and policy-export
implementation. The method remains `motrix.fastsac`, with the Torch training backend; `algo.asynchronous` selects the
execution topology rather than a separate method.

It depends only on `motrix-rl` for control-plane services and provider/trainer contracts, plus its
Torch runtime dependencies. It registers via the `motrix_rl.frameworks` entry-point group:
SuperMimic configuration, provider and training implementation remain in the independently packaged
[`motrix-rl-supermimic`](../motrix_rl_supermimic/README.md). Builtin depends on that package and owns its registration under
`motrix`, including the `motrix.supermimic` algorithm defaults. SuperMimic does not depend on builtin.

Control-plane services and provider/trainer contracts come from `motrix-rl`. Builtin registers via the
`motrix_rl.frameworks` entry-point group:
`builtin = "motrix_rl_builtin.plugin:register"`. Consumers query `motrix_rl.frameworks` rather than importing plugin
internals to trigger registration.
3 changes: 2 additions & 1 deletion motrix_rl_builtin/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@ readme = "README.md"
license = "Apache-2.0"
dependencies = [
"motrix-rl==0.5.0",
"motrix-rl-supermimic==0.5.0",
"gymnasium==1.1.1",
"numpy>=1.26",
"torch>=2.7,<3",
"torch>=2.9,<3",
"motrix-bench==0.5.0",
]

Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
# Copyright Motphys Technology Co., Ltd. 2025, 2026
# SPDX-License-Identifier: Apache-2.0

from motrix_rl import frameworks
from motrix_rl.contracts import AgentProvider, RlFramework, TrainerBase, TrainerContext
from motrix_rl.contracts import AgentProvider, TrainerBase, TrainerContext
from motrix_rl.deploy.api import OnnxPolicyExporter
from motrix_rl_builtin.fastsac.config import FastSacCfg

Expand Down Expand Up @@ -37,16 +36,3 @@ def create_policy_exporter(self) -> OnnxPolicyExporter:
from motrix_rl_builtin.fastsac.export import FastSacOnnxExporter

return FastSacOnnxExporter()


class MotrixFramework(RlFramework):
def __init__(self) -> None:
super().__init__((FastSacProvider(),))

@property
def name(self) -> str:
return "motrix"


def register_framework() -> None:
frameworks.register_framework(MotrixFramework())
18 changes: 18 additions & 0 deletions motrix_rl_builtin/src/motrix_rl_builtin/framework.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Copyright Motphys Technology Co., Ltd. 2025, 2026
# SPDX-License-Identifier: Apache-2.0

"""Assemble Motrix-owned algorithm providers under one framework namespace."""

from motrix_rl_supermimic.provider import SuperMimicProvider

from motrix_rl.contracts import RlFramework
from motrix_rl_builtin.fastsac.provider import FastSacProvider


class MotrixFramework(RlFramework):
def __init__(self) -> None:
super().__init__((FastSacProvider(), SuperMimicProvider()))

@property
def name(self) -> str:
return "motrix"
7 changes: 6 additions & 1 deletion motrix_rl_builtin/src/motrix_rl_builtin/plugin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
# Copyright Motphys Technology Co., Ltd. 2025, 2026
# SPDX-License-Identifier: Apache-2.0

from hydra.core.config_store import ConfigStore
from motrix_rl_supermimic.config import SuperMimicCfg

from motrix_rl import frameworks
from motrix_rl_builtin.fastsac.framework import MotrixFramework
from motrix_rl_builtin.framework import MotrixFramework


def register() -> None:
frameworks.register_framework(MotrixFramework())
# The implementation package owns the defaults; builtin owns their public name.
ConfigStore.instance().store(group="algo_base", name="motrix.supermimic", node=SuperMimicCfg())
26 changes: 23 additions & 3 deletions motrix_rl_builtin/tests/test_builtin_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,36 @@

import pytest
from motrix_rl_builtin.fastsac.config import FastSacCfg
from motrix_rl_builtin.fastsac.framework import FastSacProvider
from motrix_rl_builtin.fastsac.provider import FastSacProvider
from motrix_rl_supermimic.config import SuperMimicCfg
from motrix_rl_supermimic.provider import SuperMimicProvider

from motrix_rl import frameworks


def test_builtin_plugin_registers_fastsac():
assert frameworks.supported_agents("motrix") == ("fastsac",)
@pytest.mark.integration
def test_builtin_plugin_registers_algorithms():
assert frameworks.supported_agents("motrix") == ("fastsac", "supermimic")
assert frameworks.get_config_type("motrix", "fastsac") is FastSacCfg
assert frameworks.supported_train_backends("motrix", "fastsac") == ("torch",)
assert isinstance(frameworks.get_agent_provider("motrix", "fastsac", "torch"), FastSacProvider)
assert frameworks.get_config_type("motrix", "supermimic") is SuperMimicCfg
assert frameworks.supported_train_backends("motrix", "supermimic") == ("torch",)
assert isinstance(frameworks.get_agent_provider("motrix", "supermimic", "torch"), SuperMimicProvider)


@pytest.mark.integration
def test_supermimic_defaults_compose_to_provider_config():
from hydra import compose, initialize_config_module
from omegaconf import OmegaConf

from motrix_rl.plugins import load_plugins

load_plugins()
with initialize_config_module(version_base=None, config_module="motrix_rl.configs"):
cfg = compose(config_name=None, overrides=["+algo_base@algo=motrix.supermimic"])

assert isinstance(OmegaConf.to_object(cfg.algo), SuperMimicCfg)


@pytest.mark.parametrize(("iterations", "num_envs", "expected"), [(1, 1, 1), (100, 64, 6400), (0, 8, 0)])
Expand Down
2 changes: 1 addition & 1 deletion motrix_rl_rslrl/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ readme = "README.md"
license = "Apache-2.0"
dependencies = [
"motrix-rl==0.5.0",
"torch>=2.7,<3",
"torch>=2.9,<3",
"rsl-rl-lib>=4.0,<5.0",
]

Expand Down
2 changes: 1 addition & 1 deletion motrix_rl_skrl/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ license = "Apache-2.0"
dependencies = [
"motrix-rl==0.5.0",
"skrl>=2.1,<2.2",
"torch>=2.7,<3",
"torch>=2.9,<3",
]

[project.optional-dependencies]
Expand Down
Loading