ceca51b0d8
Default humanoid intake to command-following gait and support bounded Cartesian target dragging for arms. Carry model and actuator semantics through calibration, native verification and packaging. Document reusable intake decisions and cover them with regression tests.
950 lines
38 KiB
Python
950 lines
38 KiB
Python
"""Adapt an external actor from explicit extracted metadata to layout.json and ONNX.
|
||
|
||
The metadata describes meaning and order. Graph shapes only validate dimensions.
|
||
No tensor width is used to guess a joint order or an observation term.
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import json
|
||
import os
|
||
from collections.abc import Mapping
|
||
from dataclasses import dataclass
|
||
from pathlib import Path
|
||
from tempfile import TemporaryDirectory
|
||
|
||
import mujoco
|
||
import numpy as np
|
||
import yaml
|
||
|
||
from controller.controls import controller_contract, load_controls
|
||
|
||
from .controllers.bindings import velocity_controls, walking_controls
|
||
from .controllers.model import finite, joint_ids, vector
|
||
from .platform.graph import TORCHSCRIPT_SUFFIXES, read_embedded_onnx
|
||
from .platform.layout import COMMAND_ORDER, JOINT_TERMS, NATIVE_LAYOUT_SCHEMA, STANDARD_TERMS
|
||
|
||
SCHEMA = "mjrl-policy-adapter/1"
|
||
CANONICAL_TERMS = STANDARD_TERMS
|
||
_ALIASES = {
|
||
"velocity_commands": "commands",
|
||
"command": "commands",
|
||
"actuator_force": "joint_torque",
|
||
}
|
||
_FLOAT_MAX = np.finfo(np.float32).max
|
||
|
||
|
||
class _MetadataLoader(yaml.SafeLoader):
|
||
"""Reject an ambiguous declaration rather than taking its last value."""
|
||
|
||
def construct_mapping(self, node, deep=False):
|
||
self.flatten_mapping(node)
|
||
pairs = self.construct_pairs(node, deep=deep)
|
||
names = set()
|
||
for name, _ in pairs:
|
||
if not isinstance(name, str) or name in names:
|
||
raise ValueError(f"Expected a unique string metadata key, got {name!r}")
|
||
names.add(name)
|
||
return dict(pairs)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class AdaptedPolicy:
|
||
layout: Path
|
||
actor: Path
|
||
max_abs_error: float
|
||
config: Path
|
||
controls: Path | None
|
||
|
||
|
||
def _object(value, field: str) -> Mapping:
|
||
if not isinstance(value, Mapping):
|
||
raise ValueError(f"{field} must be an object")
|
||
return value
|
||
|
||
|
||
def _keys(doc: Mapping, allowed: set[str], field: str) -> None:
|
||
unknown = set(doc) - allowed
|
||
if unknown:
|
||
raise ValueError(f"Unknown {field} fields {sorted(map(str, unknown))}")
|
||
|
||
|
||
def _metadata(source: Mapping | Path) -> Mapping:
|
||
if isinstance(source, (Path, str)):
|
||
path = Path(source)
|
||
source = yaml.load(path.read_text("utf-8"), Loader=_MetadataLoader)
|
||
doc = _object(source, "policy metadata")
|
||
if doc.get("schema", SCHEMA) != SCHEMA:
|
||
raise ValueError(f"Expected {SCHEMA} metadata")
|
||
_keys(
|
||
doc,
|
||
{
|
||
"schema",
|
||
"wire_joint_order",
|
||
"obs_joint_order",
|
||
"action_joint_order",
|
||
"source_action_joint_order",
|
||
"default_joint_pos",
|
||
"default_joint_vel",
|
||
"passive_joints",
|
||
"joint_limits",
|
||
"action_scale",
|
||
"control",
|
||
"kp",
|
||
"kd",
|
||
"effort_limit",
|
||
"control_hz",
|
||
"observation",
|
||
"action",
|
||
"command_ranges",
|
||
"raw_action_clip",
|
||
"use_default_offset",
|
||
"controller",
|
||
"root_body",
|
||
"motor_model",
|
||
},
|
||
"policy metadata",
|
||
)
|
||
return doc
|
||
|
||
|
||
def _names(value, field: str, *, empty: bool = False) -> list[str]:
|
||
if (
|
||
not isinstance(value, (list, tuple))
|
||
or not all(isinstance(n, str) and n for n in value)
|
||
or len(set(value)) != len(value)
|
||
or (not value and not empty)
|
||
):
|
||
raise ValueError(f"{field} must list unique names")
|
||
return list(value)
|
||
|
||
|
||
def _permutation(source, target: list[str], field: str) -> np.ndarray:
|
||
source = _names(source, field)
|
||
if set(source) != set(target):
|
||
raise ValueError(f"{field} must contain exactly {target!r}")
|
||
return np.array([target.index(name) for name in source], dtype=np.int64)
|
||
|
||
|
||
def _integer(value, field: str) -> int:
|
||
if type(value) is not int or value < 1:
|
||
raise ValueError(f"{field} must be a positive integer")
|
||
return value
|
||
|
||
|
||
def _by_joint(value, names: list[str], field: str) -> Mapping:
|
||
value = _object(value, field)
|
||
if set(value) != set(names):
|
||
raise ValueError(f"{field} must cover exactly {names!r}")
|
||
return value
|
||
|
||
|
||
def _action(doc: Mapping, joints: list[str]) -> tuple[float, np.ndarray, np.ndarray]:
|
||
action = _object(doc.get("action", {}), "action")
|
||
_keys(action, {"dim", "targets"}, "action")
|
||
if _integer(action.get("dim", len(joints)), "action.dim") != len(joints):
|
||
raise ValueError("action.dim differs from action_joint_order")
|
||
source = doc.get("source_action_joint_order", joints)
|
||
to_source = _permutation(source, joints, "source_action_joint_order")
|
||
scale = doc.get("action_scale")
|
||
if isinstance(scale, Mapping):
|
||
values = _by_joint(scale, joints, "action_scale")
|
||
graph_scale = np.array(
|
||
[finite(values[name], "action_scale") for name in joints], dtype=np.float32
|
||
)
|
||
if not np.all(np.isfinite(graph_scale)):
|
||
raise ValueError("action_scale is out of float32 range")
|
||
layout_scale = 1.0
|
||
else:
|
||
layout_scale = finite(scale, "action_scale")
|
||
graph_scale = np.ones(len(joints), dtype=np.float32)
|
||
return layout_scale, graph_scale, to_source
|
||
|
||
|
||
def _control(doc: Mapping, wire: list[str]) -> dict:
|
||
nested = _object(doc.get("control", {}), "control")
|
||
fields = {"kp", "kd", "effort_limit", "control_hz"}
|
||
_keys(nested, fields, "control")
|
||
if fields & nested.keys() & doc.keys():
|
||
raise ValueError("Specify control metadata in one place")
|
||
gains = {}
|
||
for key in sorted(fields):
|
||
value = nested.get(key, doc.get(key))
|
||
positive = key in {"effort_limit", "control_hz"}
|
||
if isinstance(value, Mapping) and key != "control_hz":
|
||
values = _by_joint(value, wire, key)
|
||
gains[key] = {name: finite(values[name], key, positive=positive) for name in wire}
|
||
flat = gains[key].values()
|
||
else:
|
||
gains[key] = finite(value, key, positive=positive)
|
||
flat = (gains[key],)
|
||
if any(v < 0 or v > _FLOAT_MAX for v in flat):
|
||
raise ValueError(f"{key} must be nonnegative and fit in float32")
|
||
return gains
|
||
|
||
|
||
def _targets(doc: Mapping, action: list[str], home: dict) -> tuple[dict, set[str]]:
|
||
targets = {}
|
||
velocity = set()
|
||
raw = doc.get("action", {}).get("targets")
|
||
if raw is None:
|
||
return {name: {"kind": "position", "offset": home[name]} for name in action}, velocity
|
||
raw = _by_joint(raw, action, "action.targets")
|
||
for name in action:
|
||
target = _object(raw[name], f"action.targets.{name}")
|
||
_keys(target, {"kind", "offset", "clip"}, f"action.targets.{name}")
|
||
kind = target.get("kind")
|
||
if kind not in ("position", "velocity"):
|
||
raise ValueError(f"Unknown action target kind {kind!r} for {name!r}")
|
||
if kind == "velocity":
|
||
velocity.add(name)
|
||
offset = finite(target.get("offset"), f"action.targets.{name}.offset")
|
||
targets[name] = {"kind": kind, "offset": offset}
|
||
if "clip" in target:
|
||
lo, hi = vector(target["clip"], 2, f"action.targets.{name}.clip")
|
||
if lo >= hi:
|
||
raise ValueError(f"action.targets.{name}.clip must be increasing")
|
||
targets[name]["clip"] = [float(lo), float(hi)]
|
||
return targets, velocity
|
||
|
||
|
||
def _limits(doc: Mapping, model, wire: list[str], home: dict, required: set[str]) -> dict:
|
||
model_limits = {}
|
||
if model is not None:
|
||
for name, jid in zip(wire, joint_ids(model, wire), strict=True):
|
||
if model.jnt_limited[jid]:
|
||
model_limits[name] = model.jnt_range[jid].tolist()
|
||
lo, hi = model_limits[name]
|
||
if not lo - 1e-6 <= home[name] <= hi + 1e-6:
|
||
raise ValueError(f"default_joint_pos.{name} is outside the model limits")
|
||
if "joint_limits" not in doc:
|
||
return model_limits if required <= model_limits.keys() else {}
|
||
declared = _object(doc["joint_limits"], "joint_limits")
|
||
if not required <= declared.keys() or set(declared) - set(wire):
|
||
raise ValueError("joint_limits must cover every position joint")
|
||
limits = {}
|
||
for name in declared:
|
||
lo, hi = vector(declared[name], 2, f"joint_limits.{name}")
|
||
if not lo < hi or not lo <= home[name] <= hi:
|
||
raise ValueError(f"joint_limits.{name} must be ordered and include its home position")
|
||
if name in model_limits:
|
||
model_lo, model_hi = model_limits[name]
|
||
if lo < model_lo - 1e-6 or hi > model_hi + 1e-6:
|
||
raise ValueError(f"joint_limits.{name} exceeds the compiled model range")
|
||
limits[name] = [float(lo), float(hi)]
|
||
return limits
|
||
|
||
|
||
def _term_name(name: str) -> str:
|
||
if not isinstance(name, str):
|
||
raise ValueError("Observation term needs a name")
|
||
canonical = _ALIASES.get(name, name)
|
||
if canonical not in CANONICAL_TERMS:
|
||
raise ValueError(f"Unsupported observation term {name!r}")
|
||
return canonical
|
||
|
||
|
||
def _coefficients(value, width: int, field: str, default: float) -> np.ndarray:
|
||
if value is None:
|
||
return np.full(width, default, dtype=np.float32)
|
||
if isinstance(value, (int, float)):
|
||
return np.full(width, finite(value, field), dtype=np.float32)
|
||
return vector(value, width, field).astype(np.float32)
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class _Input:
|
||
name: str
|
||
width: int
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class _Transform:
|
||
obs_index: np.ndarray
|
||
inverse_action_scale: np.ndarray
|
||
low: np.ndarray
|
||
high: np.ndarray
|
||
obs_scale: np.ndarray
|
||
mean: np.ndarray
|
||
denominator: np.ndarray
|
||
action_index: np.ndarray
|
||
action_scale: np.ndarray
|
||
action_clip: np.ndarray | None
|
||
inputs: tuple[_Input, ...]
|
||
|
||
def source_inputs(self, obs: np.ndarray) -> tuple[np.ndarray, ...]:
|
||
obs = obs[:, self.obs_index] * self.inverse_action_scale
|
||
obs = (np.clip(obs, self.low, self.high) * self.obs_scale - self.mean) / self.denominator
|
||
return tuple(np.split(obs, np.cumsum([item.width for item in self.inputs])[:-1], axis=1))
|
||
|
||
def canonical_actions(self, raw: np.ndarray) -> np.ndarray:
|
||
raw = raw[:, self.action_index]
|
||
if self.action_clip is not None:
|
||
raw = np.clip(raw, *self.action_clip)
|
||
return raw * self.action_scale
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class _Term:
|
||
layout: dict
|
||
frames: np.ndarray
|
||
inverse_action_scale: np.ndarray
|
||
scale: np.ndarray
|
||
clip: np.ndarray
|
||
|
||
|
||
def _term(
|
||
term: Mapping,
|
||
history: int,
|
||
obs_joints: list[str],
|
||
command_order: list[str],
|
||
act_joints: list[str],
|
||
act_to_source: np.ndarray,
|
||
graph_scale: np.ndarray,
|
||
offset: int,
|
||
history_order: str,
|
||
action_clipped: bool,
|
||
) -> _Term:
|
||
_keys(
|
||
term,
|
||
{
|
||
"name",
|
||
"dim",
|
||
"history_length",
|
||
"history_stride",
|
||
"scale",
|
||
"clip",
|
||
"source_joint_order",
|
||
"source_command_order",
|
||
"joint_order",
|
||
},
|
||
"observation term",
|
||
)
|
||
name = _term_name(term.get("name"))
|
||
history = _integer(term.get("history_length", history), f"{name}.history_length")
|
||
stride = _integer(term.get("history_stride", 1), f"{name}.history_stride")
|
||
per_joint = name in JOINT_TERMS
|
||
per_command = name == "commands"
|
||
if {"source_joint_order", "joint_order"} & term.keys() and not per_joint:
|
||
raise ValueError(f"{name} cannot carry a joint order")
|
||
if "source_command_order" in term and not per_command:
|
||
raise ValueError(f"{name} cannot carry source_command_order")
|
||
if per_joint:
|
||
if "joint_order" in term:
|
||
obs_joints = _names(term["joint_order"], f"{name}.joint_order")
|
||
width = len(obs_joints)
|
||
index = _permutation(
|
||
term.get("source_joint_order", obs_joints), obs_joints, f"{name}.source_joint_order"
|
||
)
|
||
elif per_command:
|
||
width = len(command_order)
|
||
index = _permutation(
|
||
term.get("source_command_order", command_order),
|
||
command_order,
|
||
f"{name}.source_command_order",
|
||
)
|
||
elif name == "actions":
|
||
if action_clipped or np.any(graph_scale == 0):
|
||
raise ValueError(
|
||
"Previous actions cannot be reconstructed after clipping or zero scaling"
|
||
)
|
||
width, index = len(act_joints), act_to_source
|
||
else:
|
||
width, index = 3, np.arange(3)
|
||
if width < 1:
|
||
raise ValueError(f"{name} is empty")
|
||
dim = width * history
|
||
if _integer(term.get("dim", dim), f"{name}.dim") != dim:
|
||
raise ValueError(f"{name}.dim must be {dim} ({width} × {history} frames)")
|
||
order = np.arange(offset, offset + dim, dtype=np.int64).reshape(history, width)[:, index]
|
||
if history_order == "newest_first":
|
||
order = order[::-1]
|
||
inv = 1 / graph_scale[index] if name == "actions" else np.ones(width, dtype=np.float32)
|
||
scale = _coefficients(term.get("scale"), width, f"{name}.scale", 1)
|
||
clip = vector(term["clip"], 2, f"{name}.clip") if "clip" in term else [-_FLOAT_MAX, _FLOAT_MAX]
|
||
if clip[0] >= clip[1]:
|
||
raise ValueError(f"{name}.clip must be an increasing pair")
|
||
layout = {
|
||
"name": name,
|
||
"dim": dim,
|
||
"offset": offset,
|
||
"history_length": history,
|
||
"history_stride": stride,
|
||
}
|
||
if "joint_order" in term:
|
||
layout["joint_order"] = obs_joints
|
||
return _Term(layout, order, inv, scale, np.asarray(clip, dtype=np.float32))
|
||
|
||
|
||
def _observations(
|
||
doc: Mapping,
|
||
obs_joints: list[str],
|
||
act_joints: list[str],
|
||
act_to_source: np.ndarray,
|
||
graph_scale: np.ndarray,
|
||
action_clip: np.ndarray | None,
|
||
) -> tuple[dict, _Transform]:
|
||
_keys(
|
||
doc,
|
||
{
|
||
"terms",
|
||
"dim",
|
||
"history_length",
|
||
"source_term_order",
|
||
"source_order",
|
||
"source_history_order",
|
||
"normalization",
|
||
"inputs",
|
||
"command_order",
|
||
"frames",
|
||
},
|
||
"observation",
|
||
)
|
||
listed = doc.get("terms")
|
||
if not isinstance(listed, list) or not listed:
|
||
raise ValueError("observation.terms must describe the source observation quantities")
|
||
has_command = any(
|
||
_term_name(_object(term, "observation term").get("name")) == "commands" for term in listed
|
||
)
|
||
command_order = _names(
|
||
doc.get("command_order", COMMAND_ORDER if has_command else ()),
|
||
"observation.command_order",
|
||
empty=not has_command,
|
||
)
|
||
if command_order and not has_command:
|
||
raise ValueError("command_order requires a commands observation")
|
||
if set(command_order) - set(COMMAND_ORDER):
|
||
raise ValueError(f"Commands must use the supported channels {COMMAND_ORDER}")
|
||
history = _integer(doc.get("history_length", 1), "observation.history_length")
|
||
history_order = doc.get("source_history_order", "oldest_first")
|
||
if history_order not in {"oldest_first", "newest_first"}:
|
||
raise ValueError("source_history_order must be oldest_first or newest_first")
|
||
terms, offset = {}, 0
|
||
for term in listed:
|
||
entry = _term(
|
||
_object(term, "observation term"),
|
||
history,
|
||
obs_joints,
|
||
command_order,
|
||
act_joints,
|
||
act_to_source,
|
||
graph_scale,
|
||
offset,
|
||
history_order,
|
||
action_clip is not None,
|
||
)
|
||
name = entry.layout["name"]
|
||
if name in terms:
|
||
raise ValueError(f"Observation term {name!r} is listed twice")
|
||
terms[name] = entry
|
||
offset += entry.layout["dim"]
|
||
if _integer(doc.get("dim", offset), "observation.dim") != offset:
|
||
raise ValueError(f"observation.dim must be {offset}")
|
||
source = list(terms)
|
||
if "source_term_order" in doc:
|
||
source = [
|
||
_term_name(name) for name in _names(doc["source_term_order"], "source_term_order")
|
||
]
|
||
_permutation(source, list(terms), "source_term_order")
|
||
entries = [terms[name] for name in source]
|
||
order = doc.get("source_order", "term_major")
|
||
if order == "term_major":
|
||
rows = [(e, f) for e in entries for f in range(len(e.frames))]
|
||
elif order == "frame_major":
|
||
depths = {len(e.frames) for e in entries}
|
||
strides = {e.layout["history_stride"] for e in entries}
|
||
if len(depths) != 1 or len(strides) != 1:
|
||
raise ValueError(
|
||
"Frame-major source observations need equal history depths and strides"
|
||
)
|
||
rows = [(e, f) for f in range(len(entries[0].frames)) for e in entries]
|
||
else:
|
||
raise ValueError("source_order must be term_major or frame_major")
|
||
|
||
normalization = doc.get("normalization", "baked_into_onnx")
|
||
mean = np.zeros(offset, dtype=np.float32)
|
||
denominator = np.ones(offset, dtype=np.float32)
|
||
if isinstance(normalization, Mapping):
|
||
_keys(normalization, {"mean", "std", "epsilon"}, "observation.normalization")
|
||
mean = vector(normalization.get("mean"), offset, "normalization.mean").astype(np.float32)
|
||
std = vector(normalization.get("std"), offset, "normalization.std")
|
||
epsilon = finite(normalization.get("epsilon"), "normalization.epsilon", positive=True)
|
||
if np.any(std < 0):
|
||
raise ValueError("normalization.std must be nonnegative")
|
||
denominator = (std + epsilon).astype(np.float32)
|
||
elif normalization not in ("baked_into_onnx", "none"):
|
||
raise ValueError("Unknown observation.normalization")
|
||
frames = _object(doc.get("frames", {}), "observation.frames")
|
||
for name, frame in frames.items():
|
||
if name not in {"base_ang_vel", "base_lin_vel", "projected_gravity"} or name not in terms:
|
||
raise ValueError("Observation frames require a corresponding base vector term")
|
||
frame = _object(frame, f"observation.frames.{name}")
|
||
if set(frame) != {"kind", "name"} or frame["kind"] not in {"body", "site"}:
|
||
raise ValueError("Observation frames must name a body or site")
|
||
if not isinstance(frame["name"], str) or not frame["name"]:
|
||
raise ValueError("Observation frame name must be nonempty")
|
||
inputs = []
|
||
if "inputs" in doc:
|
||
for item in doc["inputs"]:
|
||
item = _object(item, "observation input")
|
||
_keys(item, {"name", "dim"}, "observation input")
|
||
width = _integer(item.get("dim"), "observation input dim")
|
||
inputs.append(_Input(item.get("name"), width))
|
||
_names([item.name for item in inputs], "observation.inputs names")
|
||
if sum(item.width for item in inputs) != offset:
|
||
raise ValueError("observation.inputs widths must sum to observation.dim")
|
||
transform = _Transform(
|
||
np.concatenate([e.frames[f] for e, f in rows]),
|
||
np.concatenate([e.inverse_action_scale for e, _ in rows]),
|
||
np.concatenate([np.full(len(e.scale), e.clip[0], dtype=np.float32) for e, _ in rows]),
|
||
np.concatenate([np.full(len(e.scale), e.clip[1], dtype=np.float32) for e, _ in rows]),
|
||
np.concatenate([e.scale for e, _ in rows]),
|
||
mean,
|
||
denominator,
|
||
np.argsort(act_to_source),
|
||
graph_scale,
|
||
action_clip,
|
||
tuple(inputs),
|
||
)
|
||
arrays = (
|
||
transform.inverse_action_scale,
|
||
transform.low,
|
||
transform.high,
|
||
transform.obs_scale,
|
||
transform.mean,
|
||
transform.denominator,
|
||
)
|
||
if any(not np.all(np.isfinite(a)) for a in arrays) or np.any(denominator <= 0):
|
||
raise ValueError("Observation transforms cannot be represented as finite float32")
|
||
return {
|
||
"dim": offset,
|
||
"terms": [t.layout for t in terms.values()],
|
||
"history_order": "oldest_first",
|
||
"normalization": "baked_into_onnx",
|
||
"command_order": command_order,
|
||
**({"frames": dict(frames)} if frames else {}),
|
||
}, transform
|
||
|
||
|
||
def _prepare(metadata: Mapping | Path, model=None) -> tuple[dict, _Transform]:
|
||
doc = _metadata(metadata)
|
||
default_offset = doc.get("use_default_offset", True)
|
||
if type(default_offset) is not bool:
|
||
raise ValueError("use_default_offset must be true or false")
|
||
if not default_offset and "targets" not in _object(doc.get("action", {}), "action"):
|
||
raise ValueError("Position actions must use default_joint_pos as their baseline")
|
||
wire = _names(doc.get("wire_joint_order"), "wire_joint_order")
|
||
observed = _names(doc.get("obs_joint_order"), "obs_joint_order", empty=True)
|
||
action = _names(doc.get("action_joint_order"), "action_joint_order")
|
||
for field, order in (("obs_joint_order", observed), ("action_joint_order", action)):
|
||
if set(order) - set(wire):
|
||
raise ValueError(f"{field} contains joints absent from wire_joint_order")
|
||
passive = _names(doc.get("passive_joints", []), "passive_joints", empty=True)
|
||
if set(passive) - set(wire) or set(passive) & set(action):
|
||
raise ValueError("passive_joints must be known wire joints outside the action order")
|
||
actuated = [name for name in wire if name not in passive]
|
||
home = _by_joint(doc.get("default_joint_pos"), wire, "default_joint_pos")
|
||
home = {n: finite(home[n], f"default_joint_pos.{n}") for n in wire}
|
||
default_vel = {}
|
||
if "default_joint_vel" in doc:
|
||
velocities = _by_joint(doc["default_joint_vel"], wire, "default_joint_vel")
|
||
default_vel = {n: finite(velocities[n], f"default_joint_vel.{n}") for n in wire}
|
||
layout_scale, graph_scale, to_source = _action(doc, action)
|
||
targets, velocity = _targets(doc, action, home)
|
||
control = _control(doc, actuated)
|
||
position = set(actuated) - velocity
|
||
for name in actuated:
|
||
kp = control["kp"][name] if isinstance(control["kp"], dict) else control["kp"]
|
||
kd = control["kd"][name] if isinstance(control["kd"], dict) else control["kd"]
|
||
if name in velocity and (kp != 0 or kd <= 0):
|
||
raise ValueError(f"Velocity joint {name!r} requires kp=0 and kd>0")
|
||
if name in position and kp <= 0:
|
||
raise ValueError(f"Position joint {name!r} requires kp>0")
|
||
clip = (
|
||
vector(doc["raw_action_clip"], 2, "raw_action_clip").astype(np.float32)
|
||
if ("raw_action_clip" in doc)
|
||
else None
|
||
)
|
||
if clip is not None and (not np.all(np.isfinite(clip)) or clip[0] >= clip[1]):
|
||
raise ValueError("raw_action_clip must be a finite increasing pair")
|
||
observation, transform = _observations(
|
||
_object(doc.get("observation"), "observation"),
|
||
observed,
|
||
action,
|
||
to_source,
|
||
graph_scale,
|
||
clip,
|
||
)
|
||
terms = observation["terms"]
|
||
for term in terms:
|
||
if set(term.get("joint_order", [])) - set(observed):
|
||
raise ValueError(f"{term['name']}.joint_order must be a subset of obs_joint_order")
|
||
names = {term["name"] for term in terms}
|
||
native = (
|
||
"motor_model" in doc
|
||
or bool(observation.get("frames"))
|
||
or "targets" in doc.get("action", {})
|
||
or bool(passive)
|
||
or any(default_vel.values())
|
||
or any(isinstance(gain, dict) for gain in control.values())
|
||
or any("joint_order" in term for term in terms)
|
||
or "base_lin_vel" in names
|
||
or ("commands" in names and observation["command_order"] != list(COMMAND_ORDER))
|
||
)
|
||
limits = _limits(doc, model, wire, home, position)
|
||
if native and not position <= limits.keys():
|
||
raise ValueError("Native policy needs model or explicit limits for every position joint")
|
||
action_layout = {"dim": len(action)}
|
||
if native:
|
||
action_layout["targets"] = targets
|
||
layout_scale = dict.fromkeys(action, layout_scale)
|
||
layout = {
|
||
"_schema": NATIVE_LAYOUT_SCHEMA if native else "isaac_layout v1",
|
||
"_source": SCHEMA,
|
||
"wire_joint_order": wire,
|
||
"obs_joint_order": observed,
|
||
"action_joint_order": action,
|
||
"default_joint_pos": home,
|
||
"unactuated_joints": {n: home[n] for n in actuated if n not in action},
|
||
"action_scale": layout_scale,
|
||
"control": control,
|
||
"observation": observation,
|
||
"action": action_layout,
|
||
}
|
||
if native:
|
||
if passive:
|
||
layout["passive_joints"] = passive
|
||
if default_vel:
|
||
layout["default_joint_vel"] = default_vel
|
||
else:
|
||
layout["use_default_offset"] = True
|
||
if limits:
|
||
layout["joint_limits"] = limits
|
||
ranges = _object(doc.get("command_ranges", {}), "command_ranges")
|
||
if ranges:
|
||
channels = observation["command_order"]
|
||
twist = _object(ranges.get("twist"), "command_ranges.twist")
|
||
if set(ranges) != {"twist"} or not channels or set(twist) != set(channels):
|
||
raise ValueError("command_ranges.twist must cover exactly the observed command axes")
|
||
layout["command_ranges"] = {"twist": {}}
|
||
for axis in channels:
|
||
lo, hi = vector(twist[axis], 2, f"command_ranges.twist.{axis}")
|
||
if not lo <= 0 <= hi:
|
||
raise ValueError(f"command_ranges.twist.{axis} must contain zero")
|
||
layout["command_ranges"]["twist"][axis] = [float(lo), float(hi)]
|
||
if "motor_model" in doc:
|
||
from .platform.motors import validate_motor_model
|
||
|
||
if velocity:
|
||
raise ValueError("BAM motor model requires position targets")
|
||
layout["motor_model"] = validate_motor_model(doc["motor_model"])
|
||
if model is not None:
|
||
for frame in observation.get("frames", {}).values():
|
||
kind = mujoco.mjtObj.mjOBJ_SITE if frame["kind"] == "site" else mujoco.mjtObj.mjOBJ_BODY
|
||
index = mujoco.mj_name2id(model, kind, frame["name"])
|
||
if index < 0 or (frame["kind"] == "body" and index == 0):
|
||
raise ValueError(f"Model has no observation frame {frame['name']!r}")
|
||
if "controller" in doc:
|
||
layout["controller"] = dict(_object(doc["controller"], "controller"))
|
||
return layout, transform
|
||
|
||
|
||
def build_layout(metadata: Mapping | Path, *, model: mujoco.MjModel | None = None) -> dict:
|
||
"""Validate explicit metadata and derive the adapted actor's deployment layout."""
|
||
return _prepare(metadata, model)[0]
|
||
|
||
|
||
def _session(actor: Path | bytes):
|
||
import onnxruntime as ort
|
||
|
||
options = ort.SessionOptions()
|
||
options.intra_op_num_threads = 1
|
||
options.inter_op_num_threads = 1
|
||
source = str(actor) if isinstance(actor, Path) else actor
|
||
return ort.InferenceSession(source, sess_options=options, providers=["CPUExecutionProvider"])
|
||
|
||
|
||
def _feature_shape(node, width: int, what: str) -> int:
|
||
shape = node.shape
|
||
if node.type != "tensor(float)" or not (
|
||
len(shape) in (1, 2)
|
||
and shape[-1] == width
|
||
and (len(shape) == 1 or shape[0] == 1 or not isinstance(shape[0], int))
|
||
):
|
||
raise ValueError(
|
||
f"{what} {node.name!r} must be float32 [{width}] or [1,{width}], "
|
||
f"got {node.type} {shape}"
|
||
)
|
||
return len(shape)
|
||
|
||
|
||
def _source_signature(session, transform: _Transform, obs: int, act: int):
|
||
model_inputs = {node.name: node for node in session.get_inputs()}
|
||
declared = transform.inputs
|
||
if not declared:
|
||
if len(model_inputs) != 1:
|
||
raise ValueError("A multi-input actor needs explicit observation.inputs")
|
||
declared = (_Input(next(iter(model_inputs)), obs),)
|
||
if set(model_inputs) != {item.name for item in declared}:
|
||
raise ValueError(f"observation.inputs differ from the graph inputs {list(model_inputs)}")
|
||
ranks = tuple(
|
||
_feature_shape(model_inputs[item.name], item.width, "Actor input") for item in declared
|
||
)
|
||
outputs = session.get_outputs()
|
||
if len(outputs) != 1:
|
||
raise ValueError("Actor must return exactly one action tensor")
|
||
output = outputs[0]
|
||
output_rank = _feature_shape(output, act, "Actor output")
|
||
return declared, ranks, output.name, output_rank
|
||
|
||
|
||
def _wrap_onnx(source: Path, output: Path, transform: _Transform, obs: int, act: int):
|
||
import onnx
|
||
from onnx import TensorProto, compose, helper, numpy_helper
|
||
|
||
data, actor = read_embedded_onnx(source)
|
||
onnx.checker.check_model(actor)
|
||
session = _session(data)
|
||
inputs, ranks, output_name, output_rank = _source_signature(session, transform, obs, act)
|
||
model = compose.add_prefix(actor, "source/")
|
||
graph = model.graph
|
||
del graph.input[:]
|
||
del graph.output[:]
|
||
graph.input.append(helper.make_tensor_value_info("obs", TensorProto.FLOAT, [1, obs]))
|
||
graph.output.append(helper.make_tensor_value_info("actions", TensorProto.FLOAT, [1, act]))
|
||
before, after = [], []
|
||
|
||
def constant(name, value):
|
||
graph.initializer.append(numpy_helper.from_array(np.asarray(value), name))
|
||
return name
|
||
|
||
def node(target, op, values, name, **attrs):
|
||
target.append(helper.make_node(op, values, [name], name=f"adapter/{name}", **attrs))
|
||
return name
|
||
|
||
prepared = node(
|
||
before, "Gather", ["obs", constant("obs_index", transform.obs_index)], "ordered", axis=1
|
||
)
|
||
prepared = node(
|
||
before,
|
||
"Mul",
|
||
[prepared, constant("previous_action_factor", transform.inverse_action_scale)],
|
||
"raw",
|
||
)
|
||
prepared = node(before, "Max", [prepared, constant("obs_min", transform.low)], "min_bounded")
|
||
prepared = node(before, "Min", [prepared, constant("obs_max", transform.high)], "clipped")
|
||
prepared = node(before, "Mul", [prepared, constant("obs_scale", transform.obs_scale)], "scaled")
|
||
prepared = node(before, "Sub", [prepared, constant("obs_mean", transform.mean)], "centered")
|
||
prepared = node(
|
||
before, "Div", [prepared, constant("obs_std", transform.denominator)], "prepared"
|
||
)
|
||
|
||
start = 0
|
||
for i, (item, rank) in enumerate(zip(inputs, ranks, strict=True)):
|
||
part = prepared
|
||
if len(inputs) > 1:
|
||
columns = constant(
|
||
f"input_{i}_index", np.arange(start, start + item.width, dtype=np.int64)
|
||
)
|
||
part = node(before, "Gather", [part, columns], f"input_{i}_values", axis=1)
|
||
if rank == 1:
|
||
shape = constant(f"input_{i}_shape", np.array([item.width], dtype=np.int64))
|
||
node(before, "Reshape", [part, shape], f"source/{item.name}")
|
||
else:
|
||
node(before, "Identity", [part], f"source/{item.name}")
|
||
start += item.width
|
||
|
||
raw = f"source/{output_name}"
|
||
if output_rank == 1:
|
||
shape = constant("action_shape", np.array([1, act], dtype=np.int64))
|
||
raw = node(after, "Reshape", [raw, shape], "batched_actions")
|
||
raw = node(
|
||
after,
|
||
"Gather",
|
||
[raw, constant("action_index", transform.action_index)],
|
||
"ordered_actions",
|
||
axis=1,
|
||
)
|
||
if transform.action_clip is not None:
|
||
lo, hi = transform.action_clip
|
||
raw = node(after, "Max", [raw, constant("action_min", lo)], "lower_actions")
|
||
raw = node(after, "Min", [raw, constant("action_max", hi)], "clipped_actions")
|
||
node(after, "Mul", [raw, constant("action_scale", transform.action_scale)], "actions")
|
||
source_nodes = list(graph.node)
|
||
del graph.node[:]
|
||
graph.node.extend([*before, *source_nodes, *after])
|
||
onnx.checker.check_model(model, full_check=True)
|
||
onnx.save(model, output)
|
||
return session, inputs, ranks
|
||
|
||
|
||
def _torch_to_onnx(source: Path, out: Path, transform: _Transform, obs: int, act: int):
|
||
import torch
|
||
|
||
actor = torch.jit.load(str(source), map_location="cpu").eval()
|
||
inputs = transform.inputs or (_Input("observations", obs),)
|
||
|
||
def run(arrays):
|
||
with torch.no_grad():
|
||
result = actor(*(torch.from_numpy(x) for x in arrays))
|
||
if not isinstance(result, torch.Tensor) or tuple(result.shape) != (1, act):
|
||
raise ValueError(f"TorchScript actor must return one [1,{act}] tensor")
|
||
if result.dtype != torch.float32:
|
||
raise ValueError("TorchScript actor must return float32")
|
||
return result.detach().cpu().numpy()
|
||
|
||
dummy = tuple(np.zeros((1, item.width), dtype=np.float32) for item in inputs)
|
||
run(dummy)
|
||
with torch.no_grad():
|
||
torch.onnx.export(
|
||
actor,
|
||
tuple(torch.from_numpy(x) for x in dummy),
|
||
str(out),
|
||
dynamo=False,
|
||
input_names=[item.name for item in inputs],
|
||
output_names=["source_actions"],
|
||
opset_version=17,
|
||
)
|
||
return run
|
||
|
||
|
||
def _check_parity(
|
||
source,
|
||
adapted: Path,
|
||
inputs: tuple[_Input, ...],
|
||
ranks: tuple[int, ...],
|
||
transform: _Transform,
|
||
obs: int,
|
||
act: int,
|
||
torch_source,
|
||
) -> float:
|
||
from dataclasses import replace
|
||
|
||
transform = replace(transform, inputs=inputs)
|
||
target = _session(adapted)
|
||
rng = np.random.default_rng(31071)
|
||
probes = [np.zeros((1, obs), dtype=np.float32)]
|
||
# Distinct columns catch order permutations that a uniform probe misses.
|
||
probes.append(np.linspace(-1, 1, obs, dtype=np.float32)[None, :])
|
||
probes.extend(
|
||
rng.standard_normal((1, obs), dtype=np.float32) * span
|
||
for span in (0.01, 0.1, 1, 1, 2, 5, 10, 30)
|
||
)
|
||
error = 0.0
|
||
for x in probes:
|
||
values = transform.source_inputs(x)
|
||
if torch_source is None:
|
||
feed = {
|
||
item.name: value if rank == 2 else value[0]
|
||
for item, rank, value in zip(inputs, ranks, values, strict=True)
|
||
}
|
||
raw = source.run(None, feed)[0].reshape(1, act)
|
||
else:
|
||
raw = torch_source(values)
|
||
expected = transform.canonical_actions(raw)
|
||
actual = target.run(["actions"], {"obs": x})[0]
|
||
if (
|
||
actual.shape != (1, act)
|
||
or not np.all(np.isfinite(actual))
|
||
or not np.all(np.isfinite(expected))
|
||
):
|
||
raise ValueError("Actor returned an invalid action tensor during parity checks")
|
||
error = max(error, float(np.max(np.abs(actual - expected))))
|
||
if not np.allclose(actual, expected, rtol=2e-5, atol=2e-6):
|
||
raise ValueError(f"Adapted actor disagrees with source, max absolute error {error:.3g}")
|
||
return error
|
||
|
||
|
||
def adapt_policy(
|
||
source: Path,
|
||
metadata: Mapping | Path,
|
||
out: Path,
|
||
*,
|
||
model: mujoco.MjModel | None = None,
|
||
) -> AdaptedPolicy:
|
||
"""Export and validate one actor. Only use TorchScript files from trusted sources."""
|
||
source = Path(source).resolve(strict=True)
|
||
out = Path(out).absolute()
|
||
filenames = ("actor.onnx", "layout.json", "controller.json", "controls.yaml")
|
||
actor, layout_path, config_path, controls_path = [out / name for name in filenames]
|
||
if any((out / name).exists() for name in filenames):
|
||
raise FileExistsError(f"Policy export would overwrite files in {out}")
|
||
doc = _metadata(metadata)
|
||
layout, transform = _prepare(doc, model)
|
||
config = {"kind": "rl_onnx", "policy": actor.name, "layout": layout_path.name}
|
||
root_body = doc.get("root_body")
|
||
if root_body is None and model is not None:
|
||
joints = joint_ids(model, layout["wire_joint_order"])
|
||
roots = set(model.body_rootid[model.jnt_bodyid[joints]])
|
||
if len(roots) == 1 and 0 not in roots:
|
||
root_body = model.body(int(roots.pop())).name or None
|
||
if root_body is not None:
|
||
if not isinstance(root_body, str) or not root_body:
|
||
raise ValueError("root_body must name a model body")
|
||
if model is not None and mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, root_body) <= 0:
|
||
raise ValueError(f"Model has no robot body {root_body!r}")
|
||
config["root_body"] = root_body
|
||
twist = layout.get("command_ranges", {}).get("twist", {})
|
||
active_axes = [axis for axis, (lo, hi) in twist.items() if lo < hi]
|
||
if not active_axes and "controller" in layout:
|
||
raise ValueError("controller metadata needs a nonzero trained command range")
|
||
obs, act = layout["observation"]["dim"], layout["action"]["dim"]
|
||
out.parent.mkdir(parents=True, exist_ok=True)
|
||
with TemporaryDirectory(prefix=".policy-", dir=out.parent) as staging:
|
||
temporary = Path(staging)
|
||
converted = source
|
||
torch_source = None
|
||
suffix = source.suffix.lower()
|
||
if suffix in TORCHSCRIPT_SUFFIXES:
|
||
converted = temporary / "converted.onnx"
|
||
torch_source = _torch_to_onnx(source, converted, transform, obs, act)
|
||
elif suffix != ".onnx":
|
||
raise ValueError("Expected an ONNX or TorchScript actor")
|
||
normalized = temporary / "actor.onnx"
|
||
session, inputs, ranks = _wrap_onnx(converted, normalized, transform, obs, act)
|
||
error = _check_parity(session, normalized, inputs, ranks, transform, obs, act, torch_source)
|
||
digest = hashlib.sha256()
|
||
with source.open("rb") as stream:
|
||
for block in iter(lambda: stream.read(1024 * 1024), b""):
|
||
digest.update(block)
|
||
layout["_checkpoint"] = {"path": str(source), "sha256": digest.hexdigest()}
|
||
layout["_adapter_validation"] = {"max_abs_error": error, "probes": 10}
|
||
if active_axes:
|
||
tmp_controls = temporary / controls_path.name
|
||
supplied = layout.get("controller")
|
||
# Prefer the walking layout for new exports. Existing actor metadata
|
||
# may explicitly contract the earlier, equally valid velocity keys.
|
||
for make_controls in (walking_controls, velocity_controls):
|
||
tmp_controls.write_text(
|
||
yaml.safe_dump(make_controls(active_axes), sort_keys=False), "utf-8"
|
||
)
|
||
generated = controller_contract(load_controls(tmp_controls), None)
|
||
if supplied is None or all(
|
||
supplied.get(key) == generated[key]
|
||
for key in ("schema", "command", "task", "devices")
|
||
):
|
||
layout["controller"] = generated
|
||
break
|
||
else:
|
||
raise ValueError("Supplied controller metadata differs from generated controls")
|
||
for path, value in ((layout_path, layout), (config_path, config)):
|
||
(temporary / path.name).write_text(
|
||
json.dumps(value, indent=2, allow_nan=False) + "\n", "utf-8"
|
||
)
|
||
out.mkdir(exist_ok=True)
|
||
published = []
|
||
try:
|
||
for path in (actor, layout_path, config_path, controls_path):
|
||
staged = temporary / path.name
|
||
if staged.exists():
|
||
os.link(staged, path)
|
||
published.append(path)
|
||
except OSError:
|
||
for path in published:
|
||
path.unlink()
|
||
raise
|
||
return AdaptedPolicy(
|
||
layout_path, actor, error, config_path, controls_path if active_axes else None
|
||
)
|