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
24 changes: 19 additions & 5 deletions docs/sphinx/source/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完
`SceneTensorReadPlan.site_tensor_view` returns the phase view, and Manager
environments publish every declared site automatically. Entities without
sites return empty tensors, and sites owned by the static world body keep a
constant pose with zero velocity. Declaring `site_names` keeps the full
named-body tracking request on MuJoCo and MJWarp; an explicit
`SceneCfg.tracked_body_names` that omits a site's owning body fails closed
constant pose with zero velocity. Declaring `site_names` tracks the resolved
dynamic owning bodies on MuJoCo and MJWarp when the authored model is
available; an explicit `SceneCfg.tracked_body_names` that omits a site's
owning body fails closed
at read-plan compilation
([#2673](https://github.com/Motphys/UniLab/issues/2673)).
`EntityData` 现在为声明了 `site_names` 的实体发布与 mjlab 对齐的 site 状态:
Expand All @@ -42,13 +43,26 @@ PyPI 版本变更与未发布变更;发布日期采用 PyPI 上传日期。完
`SceneTensorReadSpec.site_names` 发起该发布,`SceneTensorReadPlan.site_tensor_view`
返回 phase 视图,Manager 环境会自动发布所有已声明的 site。未声明 site 的实体
返回空张量;挂在静态 world body 上的 site 保持常量位姿和零速度。声明
`site_names` 会在 MuJoCo 与 MJWarp 上保留完整的命名 body 跟踪请求;显式的
`SceneCfg.tracked_body_names` 若漏掉某个 site 的所属 body,则在 read plan
`site_names` 时,MuJoCo 与 MJWarp 在 authored 模型可用的情况下只跟踪解析出的
动态所属 body;显式的 `SceneCfg.tracked_body_names` 若漏掉某个 site 的所属
body,则在 read plan
编译期 fail closed
([#2673](https://github.com/Motphys/UniLab/issues/2673))。

### Fixed / 修复

- Manager-based MuJoCo and MJWarp scenes now resolve declared sites from authored
models before backend construction, tracking only their dynamic parent bodies
instead of every named body when resolution is available. Scene and physical-entity
fixed variants whose site frames differ are rejected with the variant, site, and
changed fields identified instead of publishing one canonical pose to every
environment ([#2675](https://github.com/Motphys/UniLab/issues/2675)).
Manager-Based 的 MuJoCo 与 MJWarp 场景现在会在后端构造前从 authored 模型解析
声明的 site;解析可用时只跟踪其动态所属 body,不再跟踪全部命名 body。若 scene 或
physical entity 的 fixed variants 中任意 site 本地帧不同,则报错并指明 variant、
site 与变化字段,不再向所有环境发布同一个 canonical 位姿
([#2675](https://github.com/Motphys/UniLab/issues/2675))。

- 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,12 @@ carrier; they do not replace the `obs` plus optional `critic` semantics.
is compiled the carrier is zero-valued so Manager construction can probe term
shapes; afterwards an unrefreshed phase fails closed. Entities without sites
return empty tensors, and sites owned by the static world body keep a constant
pose with zero velocity.
pose with zero velocity. On MuJoCo and MJWarp, the Manager cold-compiles
authored model sources to track only dynamic site-owning bodies in addition to
the root and explicitly declared bodies; sources that cannot be resolved before
materialization retain full named-body tracking. Because the public local-frame
contract is canonical, scene and physical-entity fixed variants with different
site frames are rejected with the variant, site, and changed fields identified.

## Evidence In Repo

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,11 @@ Env 生命周期由 `src/unilab/base/base.py` 与 `src/unilab/base/torch_env.py`
`SceneTensorReadPlan.site_tensor_view` 返回 phase 视图。read plan 编译之前
carrier 为零值,供 Manager 构造期探测 term 形状;编译之后未刷新的 phase
会 fail closed。未声明 site 的 entity 返回空张量,挂在静态 world body 上的
site 保持常量位姿和零速度。
site 保持常量位姿和零速度。在 MuJoCo 与 MJWarp 上,Manager 在冷路径编译
authored 模型源,除 root 与显式声明的 body 外只跟踪动态 site 的所属 body;
无法在物化前解析的模型源仍保留完整命名 body 跟踪。由于公开的本地帧契约只有
canonical 值,scene 或 physical entity 的 fixed variants 中任意 site 本地帧不同时会
fail closed,错误信息指明 variant、site 与变化字段。

## 仓库中的证据

Expand Down
9 changes: 9 additions & 0 deletions src/unilab/base/backend_factory.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,7 +338,16 @@ def create_backend(
)
if scene.entity_variant is not None:
paths.extend(source.model_file for source in scene.entity_variant.plan.variants)
fixed_variant_plan = getattr(scene, "fixed_variant_plan", None)
if fixed_variant_plan is not None:
paths.extend(source.model_file for source in fixed_variant_plan.variants)
ensure_robot_assets_for_paths(list(dict.fromkeys(paths)))
if backend_type in SELECTIVE_TRACKED_BODY_BACKENDS and (
fixed_variant_plan is not None or scene.entity_variant is not None
):
from unilab.base.scene import validate_fixed_variant_site_frames

validate_fixed_variant_site_frames(scene)
# MotrixSim GPU owns its per-world contact storage; translate the owner
# capacities into the adapter's constructor names and drop them for every
# other backend so they never leak into an unrelated constructor.
Expand Down
150 changes: 146 additions & 4 deletions src/unilab/base/scene.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

from collections.abc import Mapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING

import numpy as np
from unisim.dr.types import FixedVariantLayout, FixedVariantPlan, ModelSourceDescriptor
Expand All @@ -17,7 +18,10 @@
resolve_scene_fragment_path,
)

from unilab.base.entity import EntityCfg
from unilab.base.entity import EntityCfg, NamesCfg

if TYPE_CHECKING:
from unisim.ray_query import RaySiteFrameDescription


@dataclass
Expand All @@ -32,9 +36,10 @@ class SceneCfg(_UniSimSceneCfg):
inject named body-state sensors. ``None`` preserves the backend's existing
full request; EntityCfg selectors remain the source of truth for Manager
body reads. Concrete (non-pattern) EntityCfg selectors may still derive the
default selection on MuJoCo and MJWarp for backward compatibility, unless an
entity declares ``site_names``: site owning bodies resolve only after
backend materialization, so the full request is kept.
default selection on MuJoCo and MJWarp for backward compatibility. Declared
sites contribute their dynamic owning bodies when the authored model can be
compiled before backend materialization; composed or unavailable sources
retain the full request.
"""

model_file: str = ""
Expand Down Expand Up @@ -111,9 +116,146 @@ def __post_init__(self) -> None:
super().__post_init__()


def _load_authored_site_frames(
model_file: str, site_names: tuple[str, ...]
) -> tuple["RaySiteFrameDescription", ...]:
import mujoco
from unisim.backend.ray_scene import ray_site_frames_from_mujoco_model

model_type = getattr(mujoco, "MjModel")
model = (
model_type.from_binary_path(model_file)
if model_file.lower().endswith(".mjb")
else model_type.from_xml_path(model_file)
)
frames: tuple[RaySiteFrameDescription, ...] = ray_site_frames_from_mujoco_model(
model, site_names
)
return frames


def _resolve_authored_site_frames(
sources: tuple[str, ...], names: tuple[str, ...]
) -> tuple["RaySiteFrameDescription", ...] | None:
resolved: list[tuple[RaySiteFrameDescription, ...]] = []
for source in sources:
try:
resolved.append(_load_authored_site_frames(source, names))
except (ImportError, OSError, ValueError):
return None

mismatches: list[str] = []
canonical = resolved[0]
for variant_index, frames in enumerate(resolved[1:], start=1):
for reference, candidate in zip(canonical, frames, strict=True):
fields = []
if reference.body_name != candidate.body_name:
fields.append("site_bodyid")
if not np.array_equal(reference.pos, candidate.pos):
fields.append("site_pos")
if not (
np.array_equal(reference.quat, candidate.quat)
or np.array_equal(reference.quat, -candidate.quat)
):
fields.append("site_quat")
if fields:
mismatches.append(
f"variant {variant_index} ({sources[variant_index]!r}) changes site "
f"{reference.site_name!r} ({', '.join(fields)})"
)
if mismatches:
raise ValueError(
"Fixed variants must keep site frames identical because "
"SimBackend.get_ray_site_frames exposes one canonical local frame: "
+ "; ".join(mismatches)
)
return canonical


def resolve_authored_site_frames(
scene: SceneCfg, site_names: NamesCfg
) -> tuple["RaySiteFrameDescription", ...] | None:
"""Resolve declared sites from authored models before backend construction.

The first fixed variant is the parent-layout reference. Site frames must be
identical across every variant because the public backend frame contract
exposes only one canonical local frame. ``None`` means that the source
cannot be compiled or does not contain the declared sites, so a caller must
retain its materialized-backend resolution path.
"""
if not site_names:
return ()
if isinstance(site_names, str):
return None
plan = scene.fixed_variant_plan
sources = (
tuple(variant.model_file for variant in plan.variants)
if plan is not None
else (scene.model_file,)
)
if any(not source for source in sources):
return None
return _resolve_authored_site_frames(sources, tuple(site_names))


def resolve_site_parent_body_names(scene: SceneCfg, site_names: NamesCfg) -> tuple[str, ...] | None:
"""Return dynamic site-owning bodies in declaration order, or ``None`` if unresolved."""
frames = resolve_authored_site_frames(scene, site_names)
if frames is None:
return None
return tuple(dict.fromkeys(frame.body_name for frame in frames if frame.body_name != "world"))


def validate_fixed_variant_site_frames(scene: SceneCfg) -> None:
"""Fail closed when declared site frames differ between fixed model variants."""
if scene.fixed_variant_plan is not None:
for entity_name, entity in scene.entities.items():
if not isinstance(entity, EntityCfg) or not entity.site_names:
continue
if resolve_authored_site_frames(scene, entity.site_names) is None:
raise NotImplementedError(
f"Entity '{entity_name}' fixed-variant site frames cannot be validated from "
"the authored model sources; declare sites in complete MJCF/MJB variant "
"sources so per-world poses cannot be published incorrectly"
)
return

binding = scene.entity_variant
if binding is None:
return
prefix = binding.target_entity + "/"
sources = tuple(variant.model_file for variant in binding.plan.variants)
for entity_name, entity in scene.entities.items():
if not isinstance(entity, EntityCfg) or not entity.site_names:
continue
physical_entity = entity.physical_entity
if physical_entity is None and entity.root_body_name and "/" in entity.root_body_name:
physical_entity = entity.root_body_name.split("/", 1)[0]
if physical_entity != binding.target_entity:
continue
if isinstance(entity.site_names, str):
resolved = None
else:
names = tuple(entity.site_names)
if any(not name.startswith(prefix) for name in names):
raise ValueError("mapped logical selectors must belong to their physical entity")
resolved = _resolve_authored_site_frames(
sources, tuple(name[len(prefix) :] for name in names)
)
if resolved is None:
raise NotImplementedError(
f"Entity '{entity_name}' fixed-variant site frames cannot be validated from "
"the authored model sources; declare sites in complete MJCF/MJB variant "
"sources so per-world poses cannot be published incorrectly"
)


__all__ = [
"SceneCfg",
"TerrainSceneCfg",
"resolve_authored_site_frames",
"resolve_scene_default_qpos",
"resolve_scene_fragment_path",
"resolve_site_parent_body_names",
"validate_fixed_variant_site_frames",
]
17 changes: 12 additions & 5 deletions src/unilab/envs/manager_based_rl_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@
from unilab.base.reset_selection import ResetSelection
from unilab.base.reset_selectors import ResetMaskBuffer, resolve_reset_env_ids
from unilab.base.reset_state import ResetStateTransaction
from unilab.base.scene import SceneCfg, resolve_scene_default_qpos
from unilab.base.scene import (
SceneCfg,
resolve_scene_default_qpos,
resolve_site_parent_body_names,
)
from unilab.base.torch_env import TorchEnv, TorchEnvState
from unilab.base.variants import (
build_fixed_variant_plan,
Expand Down Expand Up @@ -357,11 +361,14 @@ def _resolve_backend_entity_contract(
tracked_body_names = None
elif tracked_body_names is not None:
tracked_body_names.extend(selector_names)
if isinstance(entity_cfg, EntityCfg) and entity_cfg.site_names:
# Site owning bodies are resolved by the materialized backend, so a
# declared site namespace keeps the full named-body request.
if entity_cfg.site_names:
body_state_requested = True
tracked_body_names = None
if tracked_body_names is not None and backend_type in SELECTIVE_TRACKED_BODY_BACKENDS:
site_parents = resolve_site_parent_body_names(cfg.scene, entity_cfg.site_names)
if site_parents is None:
tracked_body_names = None
else:
tracked_body_names.extend(site_parents)

if not root_entities:
raise ValueError(
Expand Down
Loading
Loading