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
5 changes: 5 additions & 0 deletions motrix_env_core/src/motrix_env_core/direct/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ def __init__(
from motrix_env_core.sim.registry import create_sim_backend, default_sim_backend_name

factory = create_sim_backend(backend or default_sim_backend_name())
if not factory.capabilities.env_creation:
raise ValueError(
f"Backend {factory.name!r} cannot create a DirectEnv or ManagerEnv. "
f"{factory.capabilities.env_creation_unavailable_reason}"
)
# Construction compiles the scene inside the backend: no compiled
# artifact crosses the boundary.
render = RenderConfig(headless=headless, record=record)
Expand Down
5 changes: 5 additions & 0 deletions motrix_env_core/src/motrix_env_core/manager/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,11 @@ def __init__(
from motrix_env_core.sim.registry import create_sim_backend, default_sim_backend_name

factory = create_sim_backend(backend or cfg.backend or default_sim_backend_name())
if not factory.capabilities.env_creation:
raise ValueError(
f"Backend {factory.name!r} cannot create a DirectEnv or ManagerEnv. "
f"{factory.capabilities.env_creation_unavailable_reason}"
)
# Construction compiles the scene inside the backend: no compiled
# artifact crosses the boundary.
render = RenderConfig(headless=headless, record=record)
Expand Down
10 changes: 10 additions & 0 deletions motrix_env_core/src/motrix_env_core/sim/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from collections.abc import Mapping
from dataclasses import dataclass
from pathlib import Path
from typing import ClassVar

import torch

Expand All @@ -25,6 +26,14 @@
from motrix_env_core.sim.write import SimWrite, SimWriteCompiler, WriteProgram


@dataclass(frozen=True)
class SimBackendCapabilities:
"""Capabilities exposed by a simulator backend to environment frontends."""

env_creation: bool = True
env_creation_unavailable_reason: str = ""


@dataclass(frozen=True)
class RenderConfig:
"""Runtime rendering settings, independent of scene and video encoding.
Expand Down Expand Up @@ -104,6 +113,7 @@ class SimBackend(abc.ABC):
"""

name: str
capabilities: ClassVar[SimBackendCapabilities] = SimBackendCapabilities()

def __init__(self, scene: SceneCfg, sim: SimCfg, num_envs: int, *, render: RenderConfig | None = None) -> None:
"""Compile ``scene`` and allocate ``num_envs`` batched data rows.
Expand Down
64 changes: 58 additions & 6 deletions motrix_env_core/tests/test_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
from motrix_env_core.manager.env import ManagerBasedEnvCfg, ManagerEnv
from motrix_env_core.observations import ObservationGroupSpec, ObservationSpec
from motrix_env_core.sim import ModelQuery
from motrix_env_core.sim.backend import RecordConfig, RenderConfig, SimBackend
from motrix_env_core.sim.backend import RecordConfig, RenderConfig, SimBackend, SimBackendCapabilities
from motrix_env_core.sim.model import SimModel
from motrix_env_core.sim.read import PhysicsReadProgram
from motrix_env_core.sim.registry import register_sim_backend
Expand Down Expand Up @@ -251,18 +251,70 @@ class BackendConstructionReached(Exception):
cfg_type = DirectEnvCfg if workflow == "direct" else ManagerBasedEnvCfg
cfg = cfg_type(scene=SceneCfg())

def factory(scene, sim, num_envs, *, render: RenderConfig):
assert render == RenderConfig(headless=headless, record=record)
assert render.record is record
assert scene is cfg.scene
raise BackendConstructionReached
class RenderBackend(_FakeRegistryBackend):
def __init__(self, scene, sim, num_envs, *, render: RenderConfig):
assert render == RenderConfig(headless=headless, record=record)
assert render.record is record
assert scene is cfg.scene
raise BackendConstructionReached

factory = RenderBackend

monkeypatch.setattr(sim_registry, "create_sim_backend", lambda name: factory)
env_type = DirectRenderEnv if workflow == "direct" else ManagerEnv
with pytest.raises(BackendConstructionReached):
env_type(cfg, backend="render-test", headless=headless, record=record)


@pytest.mark.parametrize("workflow", ["direct", "manager"])
@pytest.mark.parametrize("headless", [False, True])
@pytest.mark.parametrize("use_spec", [False, True], ids=["registry", "build-spec"])
def test_environment_creation_rejects_compile_only_backends(workflow, headless, use_spec, monkeypatch):
"""Reject unsupported runtime selection before constructing or compiling a backend."""
from motrix_env_core.sim import registry as sim_registry

class CompileOnlyBackend(_FakeRegistryBackend):
name = "compile-only"
capabilities = SimBackendCapabilities(
env_creation=False,
env_creation_unavailable_reason="This backend only supports scene compilation.",
)

def __init__(self, scene: SceneCfg, sim, num_envs: int) -> None:
pytest.fail("Compile-only backend must not be constructed by an environment")

monkeypatch.setitem(sim_registry._sim_backends, "compile-only", lambda: CompileOnlyBackend)
env_name = "core-test-compile-only-env"
cfg_type = DirectEnvCfg if workflow == "direct" else ManagerBasedEnvCfg
env_base = DirectEnv if workflow == "direct" else ManagerEnv

@registry.envcfg(env_name)
@configclass
class RuntimeEnvCfg(cfg_type):
scene: SceneCfg = SceneCfg()

@registry.env(env_name)
class RuntimeEnv(env_base):
observation_spec = property(lambda self: None)
action_space = property(lambda self: None)

def apply_action(self, actions, state):
pass

def compute_transition(self, state):
pass

def reset(self, env_ids):
pass

with pytest.raises(ValueError, match="Backend 'compile-only'.*cannot create a DirectEnv or ManagerEnv") as exc_info:
if use_spec:
registry.resolve(env_name, sim="compile-only").make(headless=headless)
else:
registry.make(env_name, sim="compile-only", headless=headless)
assert CompileOnlyBackend.capabilities.env_creation_unavailable_reason in str(exc_info.value)


def test_custom_environment_can_be_registered_and_created_without_builtins():
env_name = "core-test-custom-env"

Expand Down
3 changes: 2 additions & 1 deletion motrix_env_mujoco/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
`motrix-env-mujoco` binds the declarative `SceneCfg` of
[`motrix-env-core`](../motrix_env_core) to MuJoCo: it compiles scenes into
`mujoco.MjModel` for sim2sim deployment, preview, and conversion tools. It
provides no live simulation.
provides no live simulation and cannot be selected to create runtime environments
with `registry.make(..., sim="mujoco")`. Use `MuJoCoSceneCompiler` directly for scene compilation.

Installing the package registers the backend under the name `"mujoco"` through the
`motrix_env.sim_backends` entry-point group. Importing `motrix_env_mujoco` is cheap; the native
Expand Down
9 changes: 8 additions & 1 deletion motrix_env_mujoco/src/motrix_env_mujoco/backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import torch

from motrix_env_core.config.sim import SimCfg
from motrix_env_core.sim.backend import SimBackend
from motrix_env_core.sim.backend import SimBackend, SimBackendCapabilities
from motrix_env_core.sim.model import SimModelCompiler
from motrix_env_core.sim.read import PhysicsReadProgram
from motrix_env_mujoco.compiler import MuJoCoSceneCompiler
Expand All @@ -23,6 +23,13 @@ class MuJoCoSimBackend(SimBackend):
"""

name = "mujoco"
capabilities = SimBackendCapabilities(
env_creation=False,
env_creation_unavailable_reason=(
"MuJoCo is currently used for sim2sim deployment and does not yet support "
"creating environments for training."
),
)

_GAP = "MuJoCo only compiles scene models; it provides no live simulation."

Expand Down
1 change: 1 addition & 0 deletions motrix_env_mujoco/tests/test_mujoco_scene_compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def test_mujoco_backend_is_registered_and_loaded_lazily():
assert isinstance(MuJoCoSceneCompiler().compile(SceneCfg(), SimCfg()), mj.MjModel)

# Compile-only backend: construction compiles the scene, behavior gaps loudly.
assert not MuJoCoSimBackend.capabilities.env_creation
backend = MuJoCoSimBackend(SceneCfg(), SimCfg(), 1)
with pytest.raises(NotImplementedError, match="no live simulation"):
backend.compile_reads({})
Expand Down