Initialize portable humanoid RL framework with licenses, locks and CI
Core and layout checks / core (push) Has been cancelled
Core and layout checks / core (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
"""CPU-only adapter/reward checks in the selected mjlab Python environment."""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
torch = pytest.importorskip("torch")
|
||||
pytest.importorskip("mjlab")
|
||||
|
||||
from universal_humanoid.config import Experiment # noqa: E402
|
||||
from universal_humanoid.rewards import planar_velocity_exp # noqa: E402
|
||||
from universal_humanoid.tasks import build_configs # noqa: E402
|
||||
|
||||
pytestmark = pytest.mark.integration
|
||||
|
||||
|
||||
@pytest.mark.parametrize("task", ["g1.flat", "t1.flat"])
|
||||
def test_factories_are_independent(task):
|
||||
a, _ = build_configs(Experiment(task=task, reward_weights={"track_linear_velocity": 7}))
|
||||
b, _ = build_configs(Experiment(task=task))
|
||||
assert a.rewards["track_linear_velocity"].weight == 7
|
||||
assert b.rewards["track_linear_velocity"].weight != 7
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"exp, match",
|
||||
[
|
||||
(Experiment(reward_weights={"typo": 1}), "Unknown reward weight"),
|
||||
(Experiment(reward_params={"track_linear_velocity": {"stdd": 1}}), "Unknown parameters"),
|
||||
(
|
||||
Experiment(extra_rewards={"bad": {"function": "os.system", "weight": 1}}),
|
||||
"Unknown local",
|
||||
),
|
||||
(
|
||||
Experiment(extra_rewards={"pose": {"function": "joint_speed_l2", "weight": 1}}),
|
||||
"shadows",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_reward_changes_fail_loudly(exp, match):
|
||||
with pytest.raises(ValueError, match=match):
|
||||
build_configs(exp)
|
||||
|
||||
|
||||
def test_evaluation_keeps_fall_terminations_and_finite_episodes():
|
||||
exp = Experiment(episode_seconds=5)
|
||||
cfg, _ = build_configs(exp, evaluation=True, command=(0.3, 0.1, 0.2))
|
||||
assert cfg.episode_length_s == 5
|
||||
assert "fell_over" in cfg.terminations and "time_out" in cfg.terminations
|
||||
assert not cfg.curriculum
|
||||
assert all(event.mode == "reset" for event in cfg.events.values())
|
||||
assert cfg.commands["twist"].ranges.lin_vel_x == (0.3, 0.3)
|
||||
assert cfg.commands["twist"].ranges.heading is None
|
||||
assert not cfg.commands["twist"].heading_command
|
||||
assert not cfg.observations["actor"].enable_corruption
|
||||
|
||||
|
||||
@pytest.mark.parametrize("task", ["g1.flat", "t1.flat"])
|
||||
@pytest.mark.parametrize("profile", ["nominal", "randomized", "stress"])
|
||||
def test_evaluation_randomization_profiles(task, profile):
|
||||
cfg, _ = build_configs(Experiment(task=task), evaluation=True, profile=profile)
|
||||
position = cfg.events["reset_robot_joints"].params["position_range"]
|
||||
assert position == ((0.0, 0.0) if profile == "nominal" else (-0.03, 0.03))
|
||||
assert ("evaluation_push" in cfg.events) == (profile == "stress")
|
||||
assert cfg.observations["actor"].enable_corruption == (profile == "stress")
|
||||
assert not cfg.observations["critic"].enable_corruption
|
||||
assert "fell_over" in cfg.terminations and "time_out" in cfg.terminations
|
||||
assert all(term.mode in ("reset", "interval") for term in cfg.events.values())
|
||||
|
||||
|
||||
def test_reward_shape_finiteness_and_direction():
|
||||
velocity = torch.tensor([[0.3, 0, 0], [0.9, 0, 0]], dtype=torch.float32)
|
||||
env = SimpleNamespace(
|
||||
scene={"robot": SimpleNamespace(data=SimpleNamespace(root_link_lin_vel_b=velocity))},
|
||||
command_manager=SimpleNamespace(get_command=lambda _: torch.tensor([[0.3, 0, 0]] * 2)),
|
||||
)
|
||||
reward = planar_velocity_exp(env, std=0.5)
|
||||
assert reward.shape == (2,)
|
||||
assert torch.isfinite(reward).all()
|
||||
assert reward[0] == 1 and reward[1] < reward[0]
|
||||
with pytest.raises(ValueError, match="positive"):
|
||||
planar_velocity_exp(env, std=0)
|
||||
@@ -0,0 +1,170 @@
|
||||
"""Pin silent contract failures without requiring a simulator or a GPU."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from universal_humanoid.artifacts import canonical_hash, digest, tree_hash, write_json
|
||||
from universal_humanoid.cli import parser, run
|
||||
from universal_humanoid.config import Experiment
|
||||
from universal_humanoid.deployment import verify_bundle
|
||||
from universal_humanoid.registry import TASKS
|
||||
|
||||
|
||||
def test_registry_is_lightweight():
|
||||
command = (
|
||||
"import sys; from universal_humanoid.cli import main; main(['list']); "
|
||||
"assert 'torch' not in sys.modules; assert 'mjlab' not in sys.modules"
|
||||
)
|
||||
env = {**os.environ, "PYTHONPATH": str(Path(__file__).parents[1] / "src")}
|
||||
subprocess.run([sys.executable, "-c", command], env=env, check=True, capture_output=True)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"patch",
|
||||
[
|
||||
{"iterations": 0},
|
||||
{"num_envs": True},
|
||||
{"steps_per_env": -1},
|
||||
{"device": "cpu"},
|
||||
{"device": "cuda:bad"},
|
||||
{"task": "imaginary.flat"},
|
||||
{"episode_seconds": float("nan")},
|
||||
{"reward_weights": {"a": float("inf")}},
|
||||
{"reward_params": {"a": [1]}},
|
||||
{"extra_rewards": {"a": {"function": "f", "weight": True}}},
|
||||
{"reward_params": {"a": {"std": float("nan")}}},
|
||||
{"seed": -1},
|
||||
],
|
||||
)
|
||||
def test_invalid_experiments_rejected(patch):
|
||||
with pytest.raises(ValueError):
|
||||
Experiment(**patch).validate()
|
||||
|
||||
|
||||
def test_unknown_json_keys_rejected(tmp_path):
|
||||
path = tmp_path / "config.json"
|
||||
path.write_text('{"num_env": 32}')
|
||||
with pytest.raises(ValueError, match="Unknown experiment keys"):
|
||||
Experiment.load(path)
|
||||
|
||||
|
||||
def test_json_roundtrip_and_defaults(tmp_path):
|
||||
exp = Experiment().validate()
|
||||
path = tmp_path / "config.json"
|
||||
write_json(path, exp.to_dict())
|
||||
assert Experiment.load(path) == exp
|
||||
assert len(TASKS) >= 2
|
||||
|
||||
|
||||
def test_fingerprint_detects_untracked_source(tmp_path):
|
||||
source = tmp_path / "reward.py"
|
||||
source.write_text("weight = 1\n")
|
||||
original = tree_hash(tmp_path)
|
||||
source.write_text("weight = 2\n")
|
||||
assert tree_hash(tmp_path) != original
|
||||
assert canonical_hash({"a": 1, "b": 2}) == canonical_hash({"b": 2, "a": 1})
|
||||
|
||||
|
||||
def minimal_bundle(path):
|
||||
path.mkdir()
|
||||
for name in (
|
||||
"policy.onnx",
|
||||
"evaluation.json",
|
||||
"reference.json",
|
||||
"experiment.json",
|
||||
"provenance.json",
|
||||
"agent.json",
|
||||
):
|
||||
(path / name).write_text("{}")
|
||||
write_json(
|
||||
path / "contract.json",
|
||||
{
|
||||
"schema_version": 1,
|
||||
"hardware_approved": False,
|
||||
"action": {
|
||||
"size": 2,
|
||||
"joint_names": ["left", "right"],
|
||||
"scale": [0.2, 0.2],
|
||||
"offset": [0, 0],
|
||||
},
|
||||
},
|
||||
)
|
||||
manifest = {
|
||||
"schema_version": 1,
|
||||
"hardware_approved": False,
|
||||
"files": {p.name: digest(p) for p in path.iterdir()},
|
||||
}
|
||||
write_json(path / "manifest.json", manifest)
|
||||
return manifest
|
||||
|
||||
|
||||
def test_bundle_tamper_rejected(tmp_path):
|
||||
bundle = tmp_path / "bundle"
|
||||
minimal_bundle(bundle)
|
||||
verify_bundle(bundle) # Positive control: an intact bundle passes.
|
||||
(bundle / "policy.onnx").write_text("changed")
|
||||
with pytest.raises(ValueError, match="integrity"):
|
||||
verify_bundle(bundle)
|
||||
|
||||
|
||||
def test_bundle_traversal_rejected(tmp_path):
|
||||
bundle = tmp_path / "bundle"
|
||||
manifest = minimal_bundle(bundle)
|
||||
manifest["files"]["../outside"] = "hash"
|
||||
write_json(bundle / "manifest.json", manifest)
|
||||
with pytest.raises(ValueError, match="non-local"):
|
||||
verify_bundle(bundle)
|
||||
|
||||
|
||||
def test_bundle_cannot_claim_hardware_approval(tmp_path):
|
||||
bundle = tmp_path / "bundle"
|
||||
manifest = minimal_bundle(bundle)
|
||||
manifest["hardware_approved"] = True
|
||||
write_json(bundle / "manifest.json", manifest)
|
||||
with pytest.raises(ValueError, match="unsafe"):
|
||||
verify_bundle(bundle)
|
||||
|
||||
|
||||
def test_comparison_requires_identical_protocol(tmp_path):
|
||||
report = {
|
||||
"task": "g1.flat",
|
||||
"status": "completed",
|
||||
"protocol": {"steps": 500},
|
||||
"metrics": {
|
||||
"tracking_xy_rmse_m_s": 0.1,
|
||||
"tracking_yaw_rmse_rad_s": 0.2,
|
||||
"failure_events": 0,
|
||||
},
|
||||
}
|
||||
a, b = tmp_path / "a.json", tmp_path / "b.json"
|
||||
write_json(a, report)
|
||||
write_json(b, report)
|
||||
args = parser().parse_args(["compare", str(a), str(b)])
|
||||
assert run(args)["candidate_minus_baseline"]["failure_events"] == 0
|
||||
report["protocol"]["steps"] = 50
|
||||
write_json(b, report)
|
||||
with pytest.raises(ValueError, match="identical"):
|
||||
run(args)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"command",
|
||||
[
|
||||
["smoke", "--config", "x", "--steps", "0"],
|
||||
["evaluate", "--checkpoint", "x", "--output", "y", "--command", "nan", "0", "0"],
|
||||
],
|
||||
)
|
||||
def test_invalid_cli_bounds_rejected(command):
|
||||
with pytest.raises(SystemExit):
|
||||
parser().parse_args(command)
|
||||
|
||||
|
||||
def test_all_experiment_examples_parse():
|
||||
for path in (Path(__file__).parents[1] / "experiments").glob("*.json"):
|
||||
data = json.loads(path.read_text())
|
||||
assert Experiment.load(path).task == data["task"]
|
||||
@@ -0,0 +1,221 @@
|
||||
"""Contracts for manuals, lock, vendor sources and package layout."""
|
||||
|
||||
import argparse
|
||||
import ast
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tomllib
|
||||
from pathlib import Path
|
||||
|
||||
from universal_humanoid import __version__
|
||||
from universal_humanoid.cli import parser
|
||||
from universal_humanoid.registry import TASKS
|
||||
from universal_humanoid.robot_check import CHECK_IDS, load_spec
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_vendored_layout_and_packaging():
|
||||
assert not (ROOT / "rl/__init__.py").exists()
|
||||
assert not any(p.is_symlink() for p in (ROOT / "rl").rglob("*")), (
|
||||
"Vendor real files, not workspace symlinks"
|
||||
)
|
||||
for package in ("mjlab", "rsl_rl"):
|
||||
assert (ROOT / "rl" / package / "__init__.py").is_file()
|
||||
assert (ROOT / "rl" / package / "LICENSE").is_file()
|
||||
assert not (ROOT / package).exists()
|
||||
project = tomllib.loads((ROOT / "pyproject.toml").read_text())
|
||||
assert project["tool"]["setuptools"]["packages"]["find"]["where"] == ["src", "rl"]
|
||||
# Upstream mjlab/scripts has no __init__.py; excluding namespaces drops real source from wheels.
|
||||
assert project["tool"]["setuptools"]["packages"]["find"]["namespaces"] is True
|
||||
assert __version__ == project["project"]["version"]
|
||||
deps = project["project"]["dependencies"]
|
||||
assert not any(re.match(r"(mjlab|rsl[-_]rl)", dep) for dep in deps)
|
||||
assert (
|
||||
"robot_specs/*.json" in project["tool"]["setuptools"]["package-data"]["universal_humanoid"]
|
||||
)
|
||||
assert set(project["tool"]["ruff"]["extend-exclude"]) == {
|
||||
"rl/mjlab",
|
||||
"rl/rsl_rl",
|
||||
"rl/upstream",
|
||||
}
|
||||
|
||||
|
||||
def test_vendor_inventory_and_explicit_modified_sources():
|
||||
result = subprocess.run(
|
||||
[sys.executable, str(ROOT / "tools/vendor_manifest.py")],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
assert json.loads(result.stdout)["files"] > 300
|
||||
manifest = json.loads((ROOT / "rl/VENDOR.json").read_text())
|
||||
expected = {
|
||||
"rl/mjlab/sim/sim.py",
|
||||
"rl/mjlab/tasks/velocity/mdp/velocity_command.py",
|
||||
"rl/mjlab/asset_zoo/robots/booster_t1/t1_constants.py",
|
||||
}
|
||||
assert set(manifest["changed_since_import"]) == expected
|
||||
vendor_doc = (ROOT / "docs/VENDOR.md").read_text()
|
||||
for name in expected:
|
||||
assert "[uh-vendor]" in (ROOT / name).read_text()
|
||||
assert name in vendor_doc
|
||||
|
||||
|
||||
def test_lock_contains_no_external_workspace_dependency():
|
||||
lock = tomllib.loads((ROOT / "uv.lock").read_text())
|
||||
names = {p["name"] for p in lock["package"]}
|
||||
assert {"torch", "mujoco", "mujoco-warp", "warp-lang"} <= names
|
||||
assert not {"mjlab", "rsl-rl-lib"} & names
|
||||
for package in lock["package"]:
|
||||
source = package["source"]
|
||||
if "editable" in source:
|
||||
assert source["editable"] == "."
|
||||
else:
|
||||
assert "registry" in source
|
||||
for wheel in package.get("wheels", []):
|
||||
assert wheel["hash"].startswith("sha256:")
|
||||
exported = (ROOT / "requirements-linux-cu130.lock").read_text()
|
||||
assert "torch==2.14.0+cu130" in exported
|
||||
assert "--hash=sha256:" in exported
|
||||
pins = set(re.findall(r"^([a-zA-Z0-9_.-]+)==([^\s;]+)", exported, re.M))
|
||||
expected = {
|
||||
(p["name"], p["version"]) for p in lock["package"] if p["name"] != "universal-humanoid"
|
||||
}
|
||||
assert pins == expected, "Regenerate the hashed pip export after changing uv.lock"
|
||||
|
||||
|
||||
def test_license_and_locked_ci_contract():
|
||||
project = tomllib.loads((ROOT / "pyproject.toml").read_text())
|
||||
license_text = (ROOT / "LICENSE").read_text()
|
||||
assert "Apache License" in license_text and "Version 2.0, January 2004" in license_text
|
||||
assert project["project"]["license"] == "Apache-2.0 AND BSD-3-Clause AND MIT"
|
||||
assert {"LICENSE", "NOTICE.md", "licenses/*.txt"} <= set(project["project"]["license-files"])
|
||||
assert project["dependency-groups"]["ci"] == project["project"]["optional-dependencies"]["dev"]
|
||||
ci_lock = (ROOT / "requirements-ci.lock").read_text()
|
||||
ci_pins = set(re.findall(r"^([a-zA-Z0-9_.-]+)==([^\s;]+)", ci_lock, re.M))
|
||||
full_pins = set(
|
||||
re.findall(
|
||||
r"^([a-zA-Z0-9_.-]+)==([^\s;]+)",
|
||||
(ROOT / "requirements-linux-cu130.lock").read_text(),
|
||||
re.M,
|
||||
)
|
||||
)
|
||||
assert ci_pins <= full_pins
|
||||
names = {name for name, _ in ci_pins}
|
||||
assert {"pytest", "ruff", "build", "setuptools"} <= names
|
||||
assert not {"torch", "mujoco", "mujoco-warp", "warp-lang"} & names
|
||||
assert "--hash=sha256:" in ci_lock
|
||||
workflow = (ROOT / ".github/workflows/check.yml").read_text()
|
||||
for command in (
|
||||
"uv lock --check",
|
||||
"--locked --only-group ci",
|
||||
"--no-build-isolation",
|
||||
"git diff --exit-code",
|
||||
"tools/vendor_manifest.py",
|
||||
"tools/check_wheel.py",
|
||||
"ruff check",
|
||||
"ruff format --check",
|
||||
"pytest -q",
|
||||
):
|
||||
assert command in workflow
|
||||
actions = re.findall(r"uses: ([^\s]+)", workflow)
|
||||
assert len(actions) >= 2
|
||||
assert all(re.fullmatch(r"[^@]+@[0-9a-f]{40}", action) for action in actions)
|
||||
assert "contents: read" in workflow and "workflow_dispatch:" in workflow
|
||||
|
||||
|
||||
def test_every_skill_indexed_and_has_real_stage_instructions():
|
||||
skills = sorted((ROOT / ".agents/skills").glob("*/SKILL.md"))
|
||||
names = {path.parent.name for path in skills}
|
||||
assert names == {"setup-env", "new-task", "train", "controls", "deploy", "rl-engineer"}
|
||||
agents = (ROOT / "AGENTS.md").read_text()
|
||||
indexed = set(re.findall(r"\]\(\.agents/skills/([^/]+)/SKILL\.md\)", agents))
|
||||
assert indexed == names
|
||||
for path in skills:
|
||||
text = path.read_text()
|
||||
assert f"name: {path.parent.name}\n" in text
|
||||
assert "description:" in text and "## " in text
|
||||
assert "uh " in text or "scripts/uh" in text
|
||||
for name in ("detect.py", "check.py"):
|
||||
script = ROOT / ".agents/skills/setup-env/scripts" / name
|
||||
assert script.is_file()
|
||||
assert name in (ROOT / ".agents/skills/setup-env/SKILL.md").read_text()
|
||||
|
||||
|
||||
def test_documentation_links_resolve():
|
||||
documents = [
|
||||
ROOT / name
|
||||
for name in (
|
||||
"README.md",
|
||||
"README.zh.md",
|
||||
"AGENTS.md",
|
||||
"CLAUDE.md",
|
||||
"NOTICE.md",
|
||||
"CONTRIBUTING.md",
|
||||
)
|
||||
]
|
||||
documents += list((ROOT / "docs").glob("*.md"))
|
||||
documents += list((ROOT / ".agents/skills").rglob("*.md"))
|
||||
for path in documents:
|
||||
for target in re.findall(r"\[[^\]]*\]\(([^)]+)\)", path.read_text()):
|
||||
if "://" in target or target.startswith(("#", "mailto:")):
|
||||
continue
|
||||
assert (path.parent / target.split("#")[0]).exists(), (path, target)
|
||||
|
||||
|
||||
def test_cli_reference_exactly_matches_parser():
|
||||
root = parser()
|
||||
commands = next(a for a in root._actions if isinstance(a, argparse._SubParsersAction)).choices
|
||||
documented = {}
|
||||
for line in (ROOT / "docs/CLI.md").read_text().splitlines():
|
||||
match = re.match(r"\| `([a-z-]+)` \| ([^|]*) \|", line)
|
||||
if match:
|
||||
documented[match[1]] = set(re.findall(r"--[a-z-]+", match[2]))
|
||||
assert set(documented) == set(commands)
|
||||
for name, cmd in commands.items():
|
||||
flags = {
|
||||
flag
|
||||
for action in cmd._actions
|
||||
for flag in action.option_strings
|
||||
if flag != "--help" and flag != "-h"
|
||||
}
|
||||
assert documented[name] == flags, name
|
||||
|
||||
|
||||
def test_robot_specs_and_check_ids_are_documented():
|
||||
for task in TASKS.values():
|
||||
spec = load_spec(task.id)
|
||||
assert len(spec["action_joint_order"]) == task.dof
|
||||
assert len(spec["motors"]) == task.dof
|
||||
documented = set(re.findall(r"\| `([a-z_]+)` \|", (ROOT / "docs/NEW_ROBOT.md").read_text()))
|
||||
assert documented == set(CHECK_IDS)
|
||||
|
||||
|
||||
def test_no_private_workspace_fallback_or_sys_path_rewriting():
|
||||
directories = [ROOT / "src", ROOT / "scripts", ROOT / "tools", ROOT / ".agents/skills"]
|
||||
paths = [
|
||||
p
|
||||
for directory in directories
|
||||
for p in directory.rglob("*")
|
||||
if p.is_file()
|
||||
and "__pycache__" not in p.parts
|
||||
and (p.suffix in (".py", ".sh") or p.parent.name == "scripts")
|
||||
]
|
||||
assert paths
|
||||
for path in paths:
|
||||
text = path.read_text()
|
||||
assert "Embodied_Workspace" not in text, path
|
||||
assert not re.search(r"[\"']/(home|Users)/", text), path
|
||||
if path.suffix == ".py":
|
||||
for node in ast.walk(ast.parse(text)):
|
||||
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
||||
assert ast.unparse(node.func) not in {
|
||||
"sys.path.insert",
|
||||
"sys.path.append",
|
||||
"sys.path.extend",
|
||||
}, path
|
||||
for path in (ROOT / "rl").rglob("*.py"):
|
||||
assert "Embodied_Workspace" not in path.read_text(), path
|
||||
@@ -0,0 +1,202 @@
|
||||
"""Statistics, CLI and process lifecycle checks without a GPU."""
|
||||
|
||||
import copy
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from universal_humanoid import artifacts, jobs
|
||||
from universal_humanoid.benchmark import (
|
||||
COMMANDS,
|
||||
METRICS,
|
||||
aggregate,
|
||||
compare_benchmarks,
|
||||
moments,
|
||||
select_checkpoint,
|
||||
)
|
||||
from universal_humanoid.cli import parser, run
|
||||
from universal_humanoid.curves import series_summary, write_svg
|
||||
from universal_humanoid.evaluation import profile_spec
|
||||
|
||||
|
||||
def record(seed=0, value=1, command="forward", profile="randomized", checkpoint="c000"):
|
||||
metrics = dict.fromkeys(METRICS, value)
|
||||
metrics.update(completed_episodes=4, failure_events=2, first_episode_censored_count=1)
|
||||
return {
|
||||
"checkpoint_id": checkpoint,
|
||||
"command_name": command,
|
||||
"profile": profile,
|
||||
"report": {
|
||||
"status": "completed",
|
||||
"task": "g1.flat",
|
||||
"metrics": metrics,
|
||||
"protocol": {
|
||||
"seed": seed,
|
||||
"command": list(COMMANDS[command]),
|
||||
"randomization": {"profile": profile},
|
||||
"steps": 500,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_aggregate_is_across_seeds_not_worlds():
|
||||
rows = aggregate([record(0, 1), record(1, 3)])
|
||||
stats = rows[0]["metrics"][METRICS[0]]
|
||||
assert stats == {"n": 2, "mean": 2, "variance": 2}
|
||||
assert rows[0]["first_episode_censored_count"] == 2
|
||||
assert moments([None, None]) == {"n": 0, "mean": None, "variance": None}
|
||||
assert moments([2])["variance"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mutation", ["duplicate", "protocol", "status"])
|
||||
def test_reject_invalid_aggregation(mutation):
|
||||
a, b = record(0), record(1)
|
||||
if mutation == "duplicate":
|
||||
b["report"]["protocol"]["seed"] = 0
|
||||
elif mutation == "protocol":
|
||||
b["report"]["protocol"]["steps"] = 3
|
||||
else:
|
||||
b["report"]["status"] = "failed"
|
||||
with pytest.raises(ValueError):
|
||||
aggregate([a, b])
|
||||
|
||||
|
||||
def matrix(tmp_path, name, value):
|
||||
directory = tmp_path / name
|
||||
directory.mkdir()
|
||||
records = [record(seed, value, command) for command in COMMANDS for seed in (0, 1)]
|
||||
filenames = []
|
||||
for i, item in enumerate(records):
|
||||
filename = f"report-{i}.json"
|
||||
artifacts.write_json(directory / filename, item["report"])
|
||||
filenames.append(filename)
|
||||
summary = {
|
||||
"status": "completed",
|
||||
"task": "g1.flat",
|
||||
"checkpoints": [{"id": "c000"}],
|
||||
"rows": aggregate(records),
|
||||
"reports": filenames,
|
||||
"protocol": {"profiles": ["randomized"], "seeds": [0, 1]},
|
||||
}
|
||||
path = directory / "summary.json"
|
||||
artifacts.write_json(path, summary)
|
||||
return path, summary
|
||||
|
||||
|
||||
def test_paired_comparison_and_selection(tmp_path):
|
||||
a, _ = matrix(tmp_path, "a", 3)
|
||||
b, _ = matrix(tmp_path, "b", 1)
|
||||
compared = compare_benchmarks(a, b)
|
||||
assert len(compared["paired_candidate_minus_baseline"]) == 4
|
||||
stats = compared["paired_candidate_minus_baseline"][0]["metrics"][METRICS[0]]
|
||||
assert stats == {"n": 2, "mean": -2, "variance": 0}
|
||||
selected = select_checkpoint(b, tmp_path / "selected.json")
|
||||
assert selected["selected"]["score"] == 1
|
||||
assert not selected["hardware_approved"]
|
||||
|
||||
|
||||
def test_selection_rejects_missing_seed_or_cell(tmp_path):
|
||||
path, summary = matrix(tmp_path, "a", 1)
|
||||
summary["rows"][0]["seeds"] = [0]
|
||||
artifacts.write_json(path, summary)
|
||||
with pytest.raises(ValueError, match="seed coverage"):
|
||||
select_checkpoint(path, tmp_path / "selection.json")
|
||||
summary["rows"].pop()
|
||||
artifacts.write_json(path, summary)
|
||||
with pytest.raises(ValueError, match="Incomplete"):
|
||||
select_checkpoint(path, tmp_path / "selection.json")
|
||||
|
||||
|
||||
def test_comparison_rejects_protocol_mismatch(tmp_path):
|
||||
a, _ = matrix(tmp_path, "a", 1)
|
||||
b, summary = matrix(tmp_path, "b", 1)
|
||||
summary["protocol"]["seeds"] = [10, 11]
|
||||
artifacts.write_json(b, summary)
|
||||
with pytest.raises(ValueError, match="identical protocol"):
|
||||
compare_benchmarks(a, b)
|
||||
|
||||
|
||||
def test_curve_summary_and_escaped_svg(tmp_path):
|
||||
points = [{"step": i, "value": 2 * i} for i in range(4)]
|
||||
summary = series_summary(points, 3)
|
||||
assert summary["tail_slope_per_iteration"] == 2
|
||||
assert summary["tail_points"] == 3
|
||||
assert series_summary(points[:1], 3)["tail_slope_per_iteration"] is None
|
||||
path = tmp_path / "curves.svg"
|
||||
write_svg(path, {"<bad&tag>": {"points": points}})
|
||||
assert "<bad&tag>" in path.read_text()
|
||||
|
||||
|
||||
def test_profile_specs_are_independent():
|
||||
a = profile_spec("stress")
|
||||
a["reset_pose_range"]["yaw"] = (10, 20)
|
||||
assert profile_spec("stress")["reset_pose_range"]["yaw"] == (-0.2, 0.2)
|
||||
assert not profile_spec("nominal")["actor_observation_noise"]
|
||||
with pytest.raises(ValueError):
|
||||
profile_spec("typo")
|
||||
|
||||
|
||||
def test_resume_requires_explicit_budget():
|
||||
args = parser().parse_args(["train", "--resume", "missing.pt", "--output", "unused"])
|
||||
with pytest.raises(ValueError, match="explicit --iterations"):
|
||||
run(args)
|
||||
|
||||
|
||||
def test_new_cli_arguments():
|
||||
args = parser().parse_args(
|
||||
[
|
||||
"benchmark",
|
||||
"--checkpoints",
|
||||
"a.pt",
|
||||
"b.pt",
|
||||
"--output",
|
||||
"result",
|
||||
"--seeds",
|
||||
"1",
|
||||
"2",
|
||||
"--profiles",
|
||||
"randomized",
|
||||
"stress",
|
||||
]
|
||||
)
|
||||
assert args.seeds == [1, 2] and len(args.checkpoints) == 2
|
||||
args = parser().parse_args(["play", "--checkpoint", "a.pt", "--measure", "joint.csv"])
|
||||
assert args.measure == Path("joint.csv")
|
||||
|
||||
|
||||
@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="Linux /proc lifecycle")
|
||||
def test_pid_identity_stop_and_lost_job(tmp_path):
|
||||
output = tmp_path / "run"
|
||||
job = jobs.job_directory(output)
|
||||
job.mkdir()
|
||||
child = subprocess.Popen(
|
||||
[sys.executable, "-c", "import time; time.sleep(60)"], start_new_session=True
|
||||
)
|
||||
try:
|
||||
identity = jobs.process_identity(child.pid)
|
||||
artifacts.write_json(job / "launch.json", {"identity": identity})
|
||||
artifacts.write_json(job / "state.json", {"status": "running"})
|
||||
assert jobs.status(output)["process_alive"]
|
||||
mismatched = copy.deepcopy(identity)
|
||||
mismatched["start_ticks"] = "wrong"
|
||||
artifacts.write_json(job / "launch.json", {"identity": mismatched})
|
||||
with pytest.raises(ValueError, match="PID identity"):
|
||||
jobs.stop(output)
|
||||
assert child.poll() is None
|
||||
artifacts.write_json(job / "launch.json", {"identity": identity})
|
||||
if hasattr(signal, "pidfd_send_signal"):
|
||||
assert jobs.stop(output)["status"] == "stop-requested"
|
||||
else:
|
||||
child.terminate()
|
||||
child.wait(timeout=5)
|
||||
assert jobs.status(output)["effective_status"] == "lost"
|
||||
finally:
|
||||
if child.poll() is None:
|
||||
child.kill()
|
||||
child.wait()
|
||||
assert jobs.process_identity(os.getpid()) is not None
|
||||
@@ -0,0 +1,107 @@
|
||||
"""Installed origin, bootstrap and explicit override regression checks."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from universal_humanoid import backend
|
||||
from universal_humanoid.inspection import asset_inventory
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def test_backend_shadowing_is_rejected(monkeypatch):
|
||||
monkeypatch.setattr(
|
||||
backend.importlib.util,
|
||||
"find_spec",
|
||||
lambda name: SimpleNamespace(origin=f"/tmp/wrong/{name}/__init__.py"),
|
||||
)
|
||||
with pytest.raises(RuntimeError, match="shadowing"):
|
||||
backend.require_vendored()
|
||||
|
||||
|
||||
def test_installed_imports_work_outside_repository(tmp_path):
|
||||
env = os.environ.copy()
|
||||
env.pop("PYTHONPATH", None)
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-c",
|
||||
"import json; from universal_humanoid.backend import require_vendored; "
|
||||
"print(json.dumps(require_vendored()))",
|
||||
],
|
||||
cwd=tmp_path,
|
||||
env=env,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
origins = json.loads(result.stdout)
|
||||
assert all(row["matches"] for row in origins.values())
|
||||
|
||||
|
||||
def test_external_assets_have_no_default_home_scan(tmp_path, monkeypatch):
|
||||
for name in ("BOOSTER_ASSETS_ROOT", "UNITREE_ROBOTS_ROOT"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
assert asset_inventory() == []
|
||||
model = tmp_path / "g1_description/g1_29dof.xml"
|
||||
model.parent.mkdir()
|
||||
model.write_text("<mujoco/>")
|
||||
monkeypatch.setenv("UNITREE_ROBOTS_ROOT", str(tmp_path))
|
||||
assert asset_inventory()[0]["path"] == str(model)
|
||||
|
||||
|
||||
def test_bootstrap_detector_needs_only_stdlib(tmp_path):
|
||||
output = tmp_path / "host.json"
|
||||
subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-I",
|
||||
str(ROOT / ".agents/skills/setup-env/scripts/detect.py"),
|
||||
"--output",
|
||||
str(output),
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=True,
|
||||
)
|
||||
assert json.loads(output.read_text())["python"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"variable,value,fragment",
|
||||
[
|
||||
("UH_PYTHON", "/nonexistent/python", "Invalid Python"),
|
||||
("MJLAB_ROOT", "/not/a/backend", "no longer supported"),
|
||||
],
|
||||
)
|
||||
def test_launcher_rejects_bad_explicit_overrides(variable, value, fragment):
|
||||
env = os.environ.copy()
|
||||
for key in ("UH_PYTHON", "MJLAB_ROOT", "UH_EXTRA_PYTHONPATH"):
|
||||
env.pop(key, None)
|
||||
env[variable] = value
|
||||
result = subprocess.run(
|
||||
[str(ROOT / "scripts/uh"), "list"], env=env, capture_output=True, text=True
|
||||
)
|
||||
assert result.returncode != 0 and fragment in result.stderr
|
||||
|
||||
|
||||
def test_t1_bundled_asset_and_bad_override(monkeypatch, tmp_path):
|
||||
pytest.importorskip("mujoco")
|
||||
pytest.importorskip("mjlab")
|
||||
from mjlab.asset_zoo.robots.booster_t1.t1_constants import get_spec, get_t1_xml
|
||||
|
||||
monkeypatch.delenv("BOOSTER_ASSETS_ROOT", raising=False)
|
||||
assert get_t1_xml().is_relative_to(ROOT / "rl")
|
||||
model = get_spec().compile()
|
||||
assert model.nv == 29 # free root + 23 joints
|
||||
assert model.site("left_foot").id >= 0
|
||||
assert model.sensor("imu_ang_vel").id >= 0
|
||||
monkeypatch.setenv("BOOSTER_ASSETS_ROOT", str(tmp_path))
|
||||
with pytest.raises(FileNotFoundError, match="T1 asset not found"):
|
||||
get_spec()
|
||||
@@ -0,0 +1,69 @@
|
||||
"""A valid checkpoint must not silently replay with changed experiment/code."""
|
||||
|
||||
import pytest
|
||||
|
||||
from universal_humanoid import artifacts
|
||||
|
||||
|
||||
def completed_run(tmp_path):
|
||||
checkpoint = tmp_path / "final.pt"
|
||||
checkpoint.write_bytes(b"trusted-test-checkpoint")
|
||||
experiment = {"task": "g1.flat"}
|
||||
run = {
|
||||
"status": "completed",
|
||||
"experiment": experiment,
|
||||
"experiment_sha256": artifacts.canonical_hash(experiment),
|
||||
"checkpoints": {"final.pt": artifacts.digest(checkpoint)},
|
||||
"provenance": {"identity_sha256": "original"},
|
||||
}
|
||||
artifacts.write_json(tmp_path / "run.json", run)
|
||||
return checkpoint, run
|
||||
|
||||
|
||||
def test_source_drift_is_rejected(tmp_path, monkeypatch):
|
||||
checkpoint, run = completed_run(tmp_path)
|
||||
monkeypatch.setattr(artifacts, "provenance", lambda _: {"identity_sha256": "original"})
|
||||
assert artifacts.load_run(checkpoint) == run
|
||||
monkeypatch.setattr(artifacts, "provenance", lambda _: {"identity_sha256": "changed"})
|
||||
with pytest.raises(ValueError, match="changed since training"):
|
||||
artifacts.load_run(checkpoint)
|
||||
|
||||
|
||||
def test_checkpoint_replacement_is_rejected(tmp_path):
|
||||
checkpoint, _ = completed_run(tmp_path)
|
||||
checkpoint.write_bytes(b"different weights")
|
||||
with pytest.raises(ValueError, match="Checkpoint hash"):
|
||||
artifacts.load_run(checkpoint)
|
||||
|
||||
|
||||
def test_experiment_mutation_is_rejected(tmp_path):
|
||||
checkpoint, run = completed_run(tmp_path)
|
||||
run["experiment"]["task"] = "t1.flat"
|
||||
artifacts.write_json(tmp_path / "run.json", run)
|
||||
with pytest.raises(ValueError, match="Experiment hash"):
|
||||
artifacts.load_run(checkpoint)
|
||||
|
||||
|
||||
def test_partial_training_is_not_completion(tmp_path):
|
||||
checkpoint, run = completed_run(tmp_path)
|
||||
run["status"] = "training"
|
||||
artifacts.write_json(tmp_path / "run.json", run)
|
||||
with pytest.raises(ValueError, match="Only completed"):
|
||||
artifacts.load_run(checkpoint)
|
||||
|
||||
|
||||
def test_only_sealed_intermediate_checkpoint_can_be_resumed(tmp_path, monkeypatch):
|
||||
checkpoint, run = completed_run(tmp_path)
|
||||
monkeypatch.setattr(artifacts, "provenance", lambda _: {"identity_sha256": "original"})
|
||||
run["status"] = "interrupted"
|
||||
artifacts.write_json(tmp_path / "run.json", run)
|
||||
with pytest.raises(ValueError, match="Only completed"):
|
||||
artifacts.load_run(checkpoint, allow_incomplete=True)
|
||||
run["checkpoint_metadata"] = {"final.pt": {"committed": True, "completed_iterations": 2}}
|
||||
artifacts.write_json(tmp_path / "run.json", run)
|
||||
assert artifacts.load_run(checkpoint, allow_incomplete=True)["status"] == "interrupted"
|
||||
with pytest.raises(ValueError, match="Only completed"):
|
||||
artifacts.load_run(checkpoint) # export still requires a completed run
|
||||
checkpoint.write_bytes(b"partial overwrite")
|
||||
with pytest.raises(ValueError, match="Checkpoint hash"):
|
||||
artifacts.load_run(checkpoint, allow_incomplete=True)
|
||||
@@ -0,0 +1,153 @@
|
||||
"""Negative conformance checks: plausible-looking adapters must not pass the wrong contract."""
|
||||
|
||||
import copy
|
||||
|
||||
import pytest
|
||||
|
||||
from universal_humanoid.robot_check import CHECK_IDS, assess, load_spec
|
||||
|
||||
|
||||
def valid_facts(spec):
|
||||
bodies = spec["contact_bodies"]
|
||||
return {
|
||||
"free_root_count": 1,
|
||||
"foot_sites": {
|
||||
n: {
|
||||
"body": b,
|
||||
"height_m": 0.02,
|
||||
"local_position_m": spec["foot_site_positions_m"][n],
|
||||
"local_quaternion": spec["foot_site_quaternions_wxyz"][n],
|
||||
}
|
||||
for n, b in spec["foot_sites"].items()
|
||||
},
|
||||
"imu": {
|
||||
n: {
|
||||
"type": kind,
|
||||
"dimension": 3,
|
||||
"site": spec["imu_site"],
|
||||
"body": spec["imu_body"],
|
||||
"site_position_m": spec["imu_site_position_m"],
|
||||
"site_quaternion": spec["imu_site_quaternion_wxyz"],
|
||||
}
|
||||
for n, kind in spec["imu_sensors"].items()
|
||||
},
|
||||
"action_joint_order": spec["action_joint_order"],
|
||||
"observation_joint_order": spec["observation_joint_order"],
|
||||
"motors": {
|
||||
m["joint"]: {
|
||||
**m,
|
||||
"count": 1,
|
||||
"joint_transmission": True,
|
||||
"force_limited": True,
|
||||
"joint_limited": True,
|
||||
"hinge_joint": True,
|
||||
}
|
||||
for m in spec["motors"]
|
||||
},
|
||||
"action_transform": {
|
||||
k: spec[k] for k in ("action_scale", "action_offset", "policy_dt", "physics_dt")
|
||||
},
|
||||
"initial_pose": {
|
||||
"default_joint_position": spec["default_joint_position_rad"],
|
||||
"actual_joint_position": spec["default_joint_position_rad"],
|
||||
"default_root_position": spec["default_root_position_m"],
|
||||
"default_root_quaternion": spec["default_root_quaternion_wxyz"],
|
||||
"actual_root_quaternion": spec["default_root_quaternion_wxyz"],
|
||||
"actual_root_position": [
|
||||
v + (0.02 if i == 2 else 0) for i, v in enumerate(spec["default_root_position_m"])
|
||||
],
|
||||
"actual_root_velocity": [0.0] * 6,
|
||||
"actual_joint_velocity": [0.0] * len(spec["observation_joint_order"]),
|
||||
"within_joint_limits": True,
|
||||
"upright_cosine": 1.0,
|
||||
},
|
||||
"initial_penetration_m": 0,
|
||||
"contacts": {
|
||||
"bodies": bodies,
|
||||
"terrain_filter": True,
|
||||
"has_force_and_found": True,
|
||||
"collision_enabled": dict.fromkeys(bodies, True),
|
||||
"observed": dict.fromkeys(bodies, True),
|
||||
"peak_force_n": dict.fromkeys(bodies, 100),
|
||||
},
|
||||
"probe": {"finite": True, "terminations": 0},
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("task", ["g1.flat", "t1.flat"])
|
||||
def test_declared_baseline_passes(task):
|
||||
spec = load_spec(task)
|
||||
checks = assess(spec, valid_facts(spec))
|
||||
assert {c["id"] for c in checks} == set(CHECK_IDS)
|
||||
assert all(c["passed"] for c in checks)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"case,check",
|
||||
[
|
||||
("site", "foot_sites"),
|
||||
("site_position", "foot_sites"),
|
||||
("reset_velocity", "initial_pose"),
|
||||
("imu_type", "imu"),
|
||||
("imu_body", "imu"),
|
||||
("imu_frame", "imu"),
|
||||
("order", "joint_order"),
|
||||
("kp", "pd_and_limits"),
|
||||
("limit", "pd_and_limits"),
|
||||
("pose", "initial_pose"),
|
||||
("penetration", "initial_penetration"),
|
||||
("collision", "contact_configuration"),
|
||||
("contact", "contact_response"),
|
||||
("force", "contact_response"),
|
||||
("finite", "finite_probe"),
|
||||
("termination", "finite_probe"),
|
||||
("timing", "action_transform"),
|
||||
("root", "free_root"),
|
||||
],
|
||||
)
|
||||
def test_corrupted_mechanics_fail(case, check):
|
||||
spec = load_spec("g1.flat")
|
||||
facts = copy.deepcopy(valid_facts(spec))
|
||||
foot = spec["contact_bodies"][0]
|
||||
joint = spec["action_joint_order"][0]
|
||||
sensor = next(iter(spec["imu_sensors"]))
|
||||
if case == "site":
|
||||
facts["foot_sites"].pop(next(iter(spec["foot_sites"])))
|
||||
elif case == "site_position":
|
||||
facts["foot_sites"][next(iter(spec["foot_sites"]))]["local_position_m"][0] = 1.0
|
||||
elif case == "reset_velocity":
|
||||
facts["initial_pose"]["actual_root_velocity"][0] = 2.0
|
||||
elif case.startswith("imu_"):
|
||||
key, value = {
|
||||
"imu_type": ("type", "accelerometer"),
|
||||
"imu_body": ("body", foot),
|
||||
"imu_frame": ("site_quaternion", [0, 1, 0, 0]),
|
||||
}[case]
|
||||
facts["imu"][sensor][key] = value
|
||||
elif case == "order":
|
||||
facts["action_joint_order"].reverse()
|
||||
elif case == "kp":
|
||||
facts["motors"][joint]["kp"] = -1
|
||||
elif case == "limit":
|
||||
facts["motors"][joint]["force_limited"] = False
|
||||
elif case == "pose":
|
||||
facts["initial_pose"]["upright_cosine"] = 0.5
|
||||
elif case == "penetration":
|
||||
facts["initial_penetration_m"] = 1
|
||||
elif case == "collision":
|
||||
facts["contacts"]["collision_enabled"][foot] = False
|
||||
elif case == "contact":
|
||||
facts["contacts"]["observed"][foot] = False
|
||||
elif case == "force":
|
||||
facts["contacts"]["peak_force_n"][foot] = 0
|
||||
elif case == "finite":
|
||||
facts["probe"]["finite"] = False
|
||||
elif case == "termination":
|
||||
facts["probe"]["terminations"] = 1
|
||||
elif case == "timing":
|
||||
facts["action_transform"]["policy_dt"] *= 2
|
||||
elif case == "root":
|
||||
facts["free_root_count"] = 0
|
||||
result = {c["id"]: c["passed"] for c in assess(spec, facts)}
|
||||
assert result[check] is False
|
||||
assert all(value for key, value in result.items() if key != check)
|
||||
@@ -0,0 +1,73 @@
|
||||
"""TensorBoard and measurement checks using CPU tensors, never a simulator."""
|
||||
|
||||
import csv
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
torch = pytest.importorskip("torch")
|
||||
pytest.importorskip("tensorboard")
|
||||
|
||||
from torch.utils.tensorboard import SummaryWriter # noqa: E402
|
||||
|
||||
from universal_humanoid.artifacts import read_json # noqa: E402
|
||||
from universal_humanoid.curves import export_curves, read_curves # noqa: E402
|
||||
from universal_humanoid.measurement import JointRecorder # noqa: E402
|
||||
|
||||
|
||||
def test_tensorboard_round_trip_and_missing_tags(tmp_path):
|
||||
log = tmp_path / "log"
|
||||
with SummaryWriter(str(log)) as writer:
|
||||
for i in range(3):
|
||||
writer.add_scalar("Episode_Reward/track_linear_velocity", i / 4, i)
|
||||
writer.add_scalar("Policy/mean_std", 1 - i / 10, i)
|
||||
writer.add_scalar("Train/mean_episode_length", 10 + i, i)
|
||||
writer.add_scalar("Train/mean_episode_length/time", 10, 1)
|
||||
writer.add_scalar("Train/mean_episode_length/time", 20, 2)
|
||||
writer.add_scalar("Loss/bad", float("nan"), 0)
|
||||
result = export_curves(log, tmp_path / "curves")
|
||||
assert "tracking" not in result["missing_categories"]
|
||||
assert result["curves"]["Train/mean_episode_length"]["last"] == 12
|
||||
assert (tmp_path / "curves/curves.svg").is_file()
|
||||
assert "Train/mean_episode_length/time" not in result["curves"]
|
||||
wall_time = read_curves(log, match="/time$")["series"]["Train/mean_episode_length/time"]
|
||||
assert wall_time["step_axis"] == "elapsed_seconds"
|
||||
assert wall_time["summary"]["tail_slope_per_second"] == 10
|
||||
with pytest.raises(ValueError, match="regex"):
|
||||
read_curves(log, match="[")
|
||||
assert read_curves(log, match="Loss/bad")["series"]["Loss/bad"]["nonfinite_points"] == 1
|
||||
with pytest.raises(FileExistsError):
|
||||
export_curves(log, tmp_path / "curves")
|
||||
with pytest.raises(FileNotFoundError):
|
||||
read_curves(tmp_path / "missing")
|
||||
|
||||
|
||||
def test_joint_csv_uses_named_order_and_projected_torque(tmp_path):
|
||||
robot = SimpleNamespace(
|
||||
joint_names=["a", "b"],
|
||||
data=SimpleNamespace(
|
||||
joint_pos=torch.tensor([[1.0, 2.0]]),
|
||||
joint_vel=torch.tensor([[3.0, 4.0]]),
|
||||
qfrc_actuator=torch.tensor([[5.0, 6.0]]),
|
||||
joint_pos_target=torch.tensor([[7.0, 8.0]]),
|
||||
),
|
||||
)
|
||||
term = SimpleNamespace(target_names=["b", "a"])
|
||||
raw = SimpleNamespace(
|
||||
scene={"robot": robot},
|
||||
step_dt=0.02,
|
||||
action_manager=SimpleNamespace(get_term=lambda _: term),
|
||||
)
|
||||
path = tmp_path / "measure.csv"
|
||||
recorder = JointRecorder(path, SimpleNamespace(unwrapped=raw, clip_actions=5))
|
||||
recorder.record(0, 0.02, [0], [1], [True], [False], torch.tensor([[10.0, -10.0]]))
|
||||
recorder.close(True)
|
||||
with path.open() as stream:
|
||||
rows = list(csv.DictReader(stream))
|
||||
assert [r["joint"] for r in rows] == ["b", "a"]
|
||||
assert float(rows[0]["position_rad"]) == 2
|
||||
assert float(rows[0]["actuator_joint_torque_nm"]) == 6
|
||||
assert float(rows[0]["applied_action"]) == 5
|
||||
assert float(rows[0]["target_rad"]) == 8
|
||||
assert rows[0]["terminated"] == "1"
|
||||
assert read_json(path.with_suffix(".csv.json"))["rows"] == 2
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Checkpoint publication/iteration semantics with a tiny fake upstream runner."""
|
||||
|
||||
import json
|
||||
import sys
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from universal_humanoid import artifacts
|
||||
from universal_humanoid.training import ProgressLogger, training_runner
|
||||
|
||||
|
||||
@dataclass
|
||||
class Agent:
|
||||
upload_model: bool = False
|
||||
|
||||
|
||||
class FakeRunner:
|
||||
def __init__(self, *args):
|
||||
self.current_learning_iteration = 0
|
||||
|
||||
def save(self, path, infos):
|
||||
artifacts.write_json(Path(path), {"iter": self.current_learning_iteration, "infos": infos})
|
||||
|
||||
|
||||
def test_save_is_atomic_committed_and_off_by_one_safe(tmp_path, monkeypatch):
|
||||
monkeypatch.setitem(sys.modules, "mjlab.rl", SimpleNamespace(MjlabOnPolicyRunner=FakeRunner))
|
||||
env = SimpleNamespace(unwrapped=SimpleNamespace(device="cpu"))
|
||||
run = {"checkpoints": {}, "checkpoint_metadata": {}}
|
||||
progress = {}
|
||||
runner = training_runner(env, Agent(), tmp_path, run, progress)
|
||||
runner.current_learning_iteration = 4
|
||||
checkpoint = tmp_path / "model_4.pt"
|
||||
runner.save(str(checkpoint))
|
||||
assert run["checkpoint_metadata"][checkpoint.name]["completed_iterations"] == 5
|
||||
assert run["checkpoints"][checkpoint.name] == artifacts.digest(checkpoint)
|
||||
assert json.loads(checkpoint.read_text())["infos"]["universal_humanoid"]["committed"]
|
||||
assert not list(tmp_path.glob("*.tmp"))
|
||||
original = checkpoint.read_bytes()
|
||||
runner.save(str(checkpoint)) # upstream repeats its last periodic save
|
||||
assert checkpoint.read_bytes() == original
|
||||
runner.current_learning_iteration = 5
|
||||
with pytest.raises(ValueError, match="overwrite"):
|
||||
runner.save(str(checkpoint))
|
||||
|
||||
|
||||
def test_progress_observer_flushes_before_callback():
|
||||
calls = []
|
||||
inner = SimpleNamespace(
|
||||
log=lambda **kw: calls.append("log"),
|
||||
writer=SimpleNamespace(flush=lambda: calls.append("flush")),
|
||||
)
|
||||
logger = ProgressLogger(inner, lambda kw: calls.append(kw["it"]))
|
||||
logger.log(it=3)
|
||||
assert calls == ["log", "flush", 3]
|
||||
Reference in New Issue
Block a user