chore: streamline next-stage handoff docs and regression files

This commit is contained in:
2026-10-16 16:07:29 +08:00
parent c528dd268f
commit 37d1b03b1a
94 changed files with 1101 additions and 9630 deletions
-87
View File
@@ -1,87 +0,0 @@
"""Contract tests; opt into fresh Kit integration runs with ANCHOR_RUNTIME_TESTS=1."""
import importlib.util
import json
import os
import runpy
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).parents[1]
def test_metadata_schema(tmp_path):
spec = importlib.util.spec_from_file_location("extract_schema", ROOT / "scripts/assets/extract_go2_leg.py")
extractor = importlib.util.module_from_spec(spec)
spec.loader.exec_module(extractor)
manifest = extractor.extract(extractor.DEFAULT_SOURCE, tmp_path / "asset")
assert manifest["schema_version"] == 1
assert manifest["interface"]["policy_shape"] == ["B", 19]
assert manifest["interface"]["action_shape"] == ["B", 3]
assert manifest["interface"]["quaternion_order"] == "xyzw"
assert manifest["control"]["physics_dt"] == 0.002
assert manifest["control"]["decimation"] == 5
assert [j["limits"]["effort"] for j in manifest["joints"]] == [23.7, 23.7, 45.43]
assert [j["limits"]["velocity"] for j in manifest["joints"]] == [30.1, 30.1, 15.7]
assert all(len(v["origin"]["xyz"]) == 3 for v in manifest["links"].values() if v is not None)
def test_task_registration_preserves_template():
import gymnasium as gym
import SkillFactory.tasks # noqa: F401
ids = ["Template-Skillfactory-v0", "SkillFactory-SingleLegAnchor-Go2-v0"]
for task in ids:
spec = gym.spec(task)
assert spec.entry_point == "isaaclab.envs:ManagerBasedRLEnv"
assert spec.kwargs["env_cfg_entry_point"].startswith("SkillFactory.")
generic = gym.spec("SkillFactory-LegSkill-v0")
assert generic.entry_point == "SkillFactory.tasks.manager_based.leg_skill.leg_env:LegSkillEnv"
def test_packaging_discovers_task_subpackages(monkeypatch):
import setuptools
captured = {}
monkeypatch.setattr(setuptools, "setup", lambda **kwargs: captured.update(kwargs))
monkeypatch.chdir(ROOT / "source/SkillFactory")
runpy.run_path(str(ROOT / "source/SkillFactory/setup.py"))
prefix = "SkillFactory.tasks.manager_based.single_leg_anchor"
assert prefix in captured["packages"]
assert prefix + ".mdp" in captured["packages"]
assert "SkillFactory.assets" in captured["packages"]
assert "SkillFactory.legs" in captured["packages"]
assert "SkillFactory.tasks.manager_based.leg_skill" in captured["packages"]
assert captured["package_data"]["SkillFactory.legs"] == ["resources/*.usda"]
assert (ROOT / "source/SkillFactory/SkillFactory/legs/resources/ground.usda").is_file()
@pytest.mark.skipif(os.environ.get("ANCHOR_RUNTIME_TESTS") != "1", reason="Opt-in Kit/CUDA integration")
@pytest.mark.parametrize("num_envs", [1, 16, 64])
def test_cuda_contract(num_envs, tmp_path):
env = dict(os.environ)
env["PYTHONPATH"] = str(ROOT / "source/SkillFactory") + os.pathsep + env.get("PYTHONPATH", "")
with (tmp_path / "runtime.log").open("w") as log:
result = subprocess.run(
[
sys.executable,
str(ROOT / "scripts/verify_anchor.py"),
"--suite",
"contract",
"--num_envs",
str(num_envs),
"--output",
str(tmp_path / "report"),
"--headless",
],
cwd=ROOT,
env=env,
stdout=log,
stderr=subprocess.STDOUT,
)
assert result.returncode == 0, (tmp_path / "runtime.log").read_text()[-4000:]
report = json.loads((tmp_path / "report/result.json").read_text())
assert report["passed"] and report["contract"]["policy_shape"] == [num_envs, 19]
-60
View File
@@ -1,60 +0,0 @@
"""Diagnostic scope validation; never starts Kit or robot optimization."""
import copy
import json
from pathlib import Path
import pytest
from SkillFactory.legs.contact_cycle.training import load_training_config, make_manifest, require_authorization
ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT/'configs/contact_cycle/training_diagnostic_v1.json'
def test_diagnostic_scope_gates_and_algorithm_are_not_relaxed():
pilot = load_training_config(CONFIG, ROOT)
full = load_training_config(ROOT/'configs/contact_cycle/training_v1.json', ROOT)
proposal = json.loads((ROOT/pilot['proposal']).read_text())
original = json.loads((ROOT/full['proposal']).read_text())
assert proposal['gates'] == original['gates']
assert pilot['algorithm'] == full['algorithm']
assert pilot['task_config'] == full['task_config']
assert pilot['seeds'] == [91101]
assert pilot['max_total_transitions'] == 512*128*32 == 2097152
assert pilot['max_total_wall_s'] == 1800
assert pilot['max_artifact_bytes'] == 1024**3
manifest = make_manifest(ROOT, CONFIG)
assert 'diagnostic candidate' in manifest['selection']
assert manifest['accepted_skill'] is False
with pytest.raises(PermissionError):
require_authorization(None, manifest)
@pytest.mark.parametrize('key,value', [
('seeds', [91101, 91102, 91103]), ('seeds', [95101]), ('updates_per_seed', 1024),
('num_envs', 256), ('horizon', 64), ('max_total_wall_s', 1801),
('max_artifact_bytes', 1073741825), ('max_total_transitions', 2097153),
('validation_interval', 128), ('validation_seed', 95101),
])
def test_pilot_rejects_scope_expansion_even_with_matching_proposal(tmp_path, key, value):
cfg = copy.deepcopy(json.loads(CONFIG.read_text()))
proposal = json.loads((ROOT/cfg['proposal']).read_text())
cfg[key] = value
if key in proposal['proposed_training']:
proposal['proposed_training'][key] = value
proposal_path = tmp_path/'proposal.json'
proposal_path.write_text(json.dumps(proposal))
cfg['proposal'] = str(proposal_path)
path = tmp_path/'config.json'
path.write_text(json.dumps(cfg))
with pytest.raises(ValueError):
load_training_config(path, ROOT)
def test_full_study_does_not_silently_become_a_pilot(tmp_path):
cfg = json.loads(CONFIG.read_text())
cfg['format'] = 'skillfactory.contact-cycle-training.v1'
path = tmp_path/'bad_full.json'
path.write_text(json.dumps(cfg))
with pytest.raises(ValueError):
load_training_config(path, ROOT)
-264
View File
@@ -1,264 +0,0 @@
"""CPU/synthetic learner tests only; none performs robot training or holdout evaluation."""
import copy
import json
from pathlib import Path
import pytest
import torch
from SkillFactory.legs.contact_cycle.config import load_config
from SkillFactory.legs.contact_cycle.curriculum import EpisodeSampler, assert_sample_domain, curriculum_stage
from SkillFactory.legs.contact_cycle.ppo import (
CycleActorCritic,
bootstrap_values,
collect_rollout,
features,
ppo_step,
restore_checkpoint,
save_checkpoint,
selection_score,
)
from SkillFactory.legs.contact_cycle.training import (
BudgetExceeded,
BudgetLedger,
digest,
load_training_config,
require_authorization,
save_trace_subset,
)
ROOT = Path(__file__).resolve().parents[1]
TASK = ROOT/"configs/contact_cycle/go2_fl_v1.json"
TRAINING = ROOT/"configs/contact_cycle/training_v1.json"
@pytest.mark.parametrize("update,stage", [(1, 0), (512, 0), (513, 1), (1024, 1), (1025, 2), (2048, 2)])
def test_stage_boundaries(update, stage):
assert curriculum_stage(update) == stage
def test_sampler_no_holdout_and_reset_order_independence():
cfg = load_config(TASK)
with pytest.raises(ValueError, match="Independent"):
EpisodeSampler(cfg, 4, 1, "holdout")
a, b = EpisodeSampler(cfg, 4, 17, update=1500), EpisodeSampler(cfg, 4, 17, update=1500)
first = a.sample(torch.tensor([0, 2]))
second = b.sample(torch.tensor([2, 0]))
for key in first:
torch.testing.assert_close(first[key], second[key].flip(0))
a.sample(torch.tensor([1]))
resumed = EpisodeSampler(cfg, 4, 17)
resumed.load_state_dict(a.state_dict())
x, y = a.sample(torch.tensor([0])), resumed.sample(torch.tensor([0]))
for key in x:
torch.testing.assert_close(x[key], y[key])
assert b.episodes.tolist() == [1, 0, 1, 0]
assert a.sample(torch.tensor([], dtype=torch.long))["commands"].shape == (0, 4, 6)
with pytest.raises(ValueError):
a.sample(torch.tensor([0, 0]))
def test_curriculum_distribution_budgets_exclusions_and_regression():
cfg = load_config(TASK)
for update in (1, 600, 1500):
sample = EpisodeSampler(cfg, 512, 91101, update=update).sample(torch.arange(512))
assert_sample_domain(cfg, sample)
if update == 1:
assert not sample["commands"].any()
assert 0.15 < sample["stand"].float().mean() < 0.35
if update == 600:
assert not sample["commands"][..., 3:].any()
if update == 1500:
assert set(sample["scenario"].tolist()) == {0, 1, 2, 3}
assert set(sample["stage"].tolist()) == {0, 1, 2}
assert sample["commands"][..., 3:].abs().max() > 0
for fault in ("commands", "points", "delays"):
bad = copy.deepcopy(sample)
bad[fault][0] = 100
with pytest.raises(ValueError):
assert_sample_domain(cfg, bad)
def test_validation_distribution_independent_of_training_update():
cfg = load_config(TASK)
a = EpisodeSampler(cfg, 8, 93101, "validation", update=1).sample(torch.arange(8))
b = EpisodeSampler(cfg, 8, 93101, "validation", update=1500).sample(torch.arange(8))
for key in a:
torch.testing.assert_close(a[key], b[key])
assert not a["stand"].any()
@pytest.mark.parametrize("bad", [torch.zeros(2, 45), torch.zeros(2, 32, dtype=torch.float64),
torch.full((2, 32), float("nan")), {"privileged": torch.zeros(2, 32)}])
def test_feature_contract_rejects_other_interfaces(bad):
with pytest.raises(ValueError):
features(bad)
class ValueModel:
def value(self, x):
return x[:, 0].clone()
@pytest.mark.parametrize("dtype", [torch.int32, torch.int64])
def test_timeout_bootstraps_terminal_not_reset_and_failure_zero(dtype):
x = torch.ones(3, 32)
terminal = torch.zeros(2, 32)
terminal[:, 0] = torch.tensor([30., 20.])
terminated, truncated = torch.tensor([True, False, False]), torch.tensor([True, True, True])
info = {"terminal_ids": torch.tensor([2, 1], dtype=dtype), "terminal_observation": {"policy": terminal}}
v = bootstrap_values(ValueModel(), x, terminated, truncated, info)
torch.testing.assert_close(v, torch.tensor([0., 20., 30.]))
with pytest.raises(RuntimeError):
bootstrap_values(ValueModel(), x, terminated, truncated, {})
class FakeEnv:
num_envs, device, step_dt = 2, "cpu", 0.01
def step(self, action):
assert action.shape == (2, 3) and (action.abs() <= 1).all()
# Both episodes timeout; deliberately distinct reset/terminal states.
return ({"policy": torch.zeros(2, 32), "privileged": torch.full((2, 71), float("nan"))},
torch.ones(2)*0.01, torch.zeros(2, dtype=torch.bool), torch.ones(2, dtype=torch.bool),
{"terminal_ids": torch.tensor([0, 1]), "terminal_observation": {"policy": torch.ones(2, 32)}})
def test_synthetic_ppo_and_atomic_restore(tmp_path):
torch.set_num_threads(1)
torch.manual_seed(4)
model = CycleActorCritic(hidden=16)
cfg = {**json.loads(TRAINING.read_text())["algorithm"], "horizon": 4, "minibatch_size": 4}
optimizer = torch.optim.Adam(model.parameters(), lr=cfg["learning_rate"])
data, x, failures, timeouts = collect_rollout(FakeEnv(), model, torch.zeros(2, 32), cfg)
assert x.shape == (2, 32) and failures == 0 and timeouts == 8
assert data["done"].all() and torch.isfinite(data["features"]).all()
result = ppo_step(model, optimizer, data, cfg)
assert result["sampling_log_prob_error"] <= 2e-4
sampler = EpisodeSampler(load_config(TASK), 2, 11)
sampler.sample(torch.arange(2))
path = tmp_path/"model.pt"
save_checkpoint(path, model, optimizer, {"test": "synthetic"}, 1, sampler, None, {})
expected = model.act(x, deterministic=True)[0].detach().clone()
with torch.no_grad():
model.actor[-1].bias.add_(1)
restore_checkpoint(path, model, optimizer, {"test": "synthetic"}, sampler)
torch.testing.assert_close(model.act(x, deterministic=True)[0], expected)
with pytest.raises(ValueError, match="mismatch"):
restore_checkpoint(path, model, optimizer, {"test": "different"}, sampler)
with pytest.raises(RuntimeError, match="budget"):
save_checkpoint(tmp_path/"too_big.pt", model, optimizer, {}, 1, sampler, None, {}, max_bytes=1)
assert not (tmp_path/"too_big.pt").exists()
def test_selection_failure_cannot_profit_from_missing_metrics():
good = {"success": True, "swing_rms_m": 0.025, "stance_load_mae_weight_fraction": 0.25, "stance_slip_m": 0.03}
assert selection_score([good]) == 3
assert selection_score([{"success": False}]) == 16
assert selection_score([good, {"success": False}]) == 9.5
with pytest.raises(ValueError):
selection_score([])
with pytest.raises(ValueError):
selection_score([{**good, "swing_rms_m": float("nan")}])
def test_configuration_and_explicit_authorization(tmp_path):
cfg = load_training_config(TRAINING, ROOT)
manifest = {"training": cfg}
with pytest.raises(PermissionError):
require_authorization(None, manifest)
grant = {"format": "skillfactory.contact-cycle-authorization.v1", "approved": True,
"manifest_sha256": digest(manifest), "operator": "synthetic_test_only",
"authorization_reference": "unit-test fixture, not robot training approval"}
path = tmp_path/"grant.json"
path.write_text(json.dumps(grant))
require_authorization(path, manifest)
with pytest.raises(PermissionError):
require_authorization(path, {"training": {}})
bad = copy.deepcopy(cfg)
bad["horizon"] = True
path.write_text(json.dumps(bad))
with pytest.raises(ValueError):
load_training_config(path, ROOT)
def small_manifest():
return {"training": {"seeds": [1, 2, 3], "num_envs": 2, "horizon": 4, "updates_per_seed": 2,
"max_total_transitions": 16, "max_total_wall_s": 100, "max_artifact_bytes": 100000}}
def test_global_budget_crash_charge_resume_and_lock(tmp_path):
now = [100.]
manifest = small_manifest()
with BudgetLedger(tmp_path, manifest, lambda: now[0], boot_now=lambda: now[0], boot_id="test-boot") as ledger:
ledger.reserve_rollout(1, 1)
with pytest.raises(ValueError):
ledger.reserve_rollout(1, 1)
with pytest.raises(BlockingIOError), BudgetLedger(
tmp_path, manifest, lambda: now[0], boot_now=lambda: now[0], boot_id="test-boot"):
pass
with BudgetLedger(tmp_path, manifest, lambda: now[0], boot_now=lambda: now[0], boot_id="test-boot") as resumed:
resumed.reconcile_checkpoint(1, 0) # interrupted rollout lost, no refund
resumed.reserve_rollout(1, 1)
resumed.commit_update(1, 1)
assert resumed.data["reserved_transitions"] == 16
with pytest.raises(BudgetExceeded, match="transition"):
resumed.reserve_rollout(2, 1)
now[0] = 201
with pytest.raises(BudgetExceeded, match="wall"):
resumed.guard()
def test_validation_rejects_missing_or_partial_disturbance_delivery():
from SkillFactory.legs.contact_cycle.mechanics import delivered_events
events = load_config(TASK)["events"]
scenario = torch.tensor([0, 1])
mask = scenario[:, None] == torch.tensor([e["scenario"] for e in events])
zero = torch.zeros_like(mask, dtype=torch.float32)
assert delivered_events(events, scenario, mask, mask, zero).tolist() == [True, False]
areas = torch.tensor([e["duration_s"] - e["ramp_s"] for e in events])
assert delivered_events(events, scenario, mask, mask, mask*areas).all()
assert delivered_events(events, scenario, mask, torch.zeros_like(mask), mask*areas).tolist() == [True, False]
def test_engine_int32_reset_ids_and_invalid_float():
from SkillFactory.legs.contact_cycle.mechanics import canonical_ids
ids = canonical_ids(torch.tensor([0, 2], dtype=torch.int32), 4)
assert ids.dtype == torch.int64 and ids.tolist() == [0, 2]
sampler = EpisodeSampler(load_config(TASK), 4, 1)
sampler.sample(torch.tensor([0, 2], dtype=torch.int32))
assert sampler.episodes.tolist() == [1, 0, 1, 0]
with pytest.raises(ValueError):
canonical_ids(torch.tensor([0., 2.]), 4)
def test_trace_storage_is_bounded_and_budget_failure_leaves_no_file(tmp_path):
trace = {"foot": torch.arange(100*128*3, dtype=torch.float32).reshape(100, 128, 3)}
sizes = []
path = tmp_path/"subset.pt"
size = save_trace_subset(path, trace, [1], [2]*128, sizes.append)
assert size == path.stat().st_size == sizes[0] and size < 8192
saved = torch.load(path, weights_only=True)["1"]["foot"]
assert saved.untyped_storage().nbytes() == saved.numel()*saved.element_size() == 24
torch.testing.assert_close(saved, trace["foot"][:2, 1:2])
def refuse(size):
raise BudgetExceeded(f"synthetic capacity less than {size}")
with pytest.raises(BudgetExceeded):
save_trace_subset(tmp_path/"insufficient.pt", trace, [1], [2]*128, refuse)
assert not (tmp_path/"insufficient.pt").exists()
assert list(tmp_path.iterdir()) == [path]
def test_checkpoint_commit_crash_window_and_disk_guard(tmp_path):
with BudgetLedger(tmp_path, small_manifest(), lambda: 100.) as ledger:
ledger.reserve_rollout(1, 1)
ledger.reconcile_checkpoint(1, 1) # optimizer/checkpoint completed before commit
assert ledger.data["updates"]["1"] == 1 and ledger.data["pending"] is None
with pytest.raises(ValueError):
ledger.commit_update(1, 2)
with pytest.raises(BudgetExceeded, match="artifact"):
ledger.guard(reserve_bytes=100001)
-69
View File
@@ -1,69 +0,0 @@
"""Synthetic negative coverage for report logic; not physical validation."""
import json
from pathlib import Path
import pytest
import torch
from SkillFactory.legs.contact_cycle.metrics import summarize
@pytest.fixture
def fixture_trace():
# Deliberately idealized input to test gate branches, not a dynamic simulator.
count = 600
phase = torch.arange(6).repeat_interleave(100)[:, None]
progress = torch.linspace(0, 1, 100).repeat(6)[:, None]
time = (torch.arange(count)*0.02)[:, None]
force = torch.zeros(count, 1, 3)
force[:, :, 2] = torch.where((phase == 0) | (phase >= 4), 50., 0.)
trace = {
"phase": phase, "progress": progress, "time": time, "scenario": torch.zeros(count, 1),
"weight": torch.full((count, 1), 50.), "normal": force,
"friction": torch.zeros_like(force), "foot": torch.zeros_like(force), "target": torch.zeros_like(force),
"gap": torch.full((count, 1), 0.05), "desired_force": force[..., 2],
"joint_excess": torch.zeros(count, 1), "limit_ratio": torch.zeros(count, 1),
"slip_speed": torch.zeros(count, 1), "height_error": torch.zeros(count, 1),
"external": torch.zeros(count, 1, 1, 6), "guide": torch.zeros(count, 1, 1, 6),
"auxiliary": torch.zeros(count, 1, 1, 6), "would_fail": torch.zeros(count, 1).bool(),
"tilt": torch.zeros(count, 1),
}
path = Path(__file__).resolve().parents[1]/"configs/contact_cycle/acceptance_v1.json"
thresholds = json.loads(path.read_text())["gates"]
return trace, thresholds
def report(fixture):
trace, thresholds = fixture
return summarize(trace, 0.02, thresholds, ["baseline"])[0]
def test_complete_fixture_passes_logic_only(fixture_trace):
assert report(fixture_trace)["success"]
@pytest.mark.parametrize("fault,reason", [
("tilt", "tilt"), ("lift", "lift_deadline"), ("terminate", "task_termination"),
("hover", "stance_contact"), ("drag", "slip"), ("nan", "missing_phase_or_nonfinite"),
("missing", "missing_phase_or_nonfinite"), ("impact", "impact"),
])
def test_negative_metrics_cannot_pass(fixture_trace, fault, reason):
t, _ = fixture_trace
if fault == "tilt":
t["tilt"][300] = 0.7
elif fault == "lift":
t["gap"][290:300] = 0
elif fault == "terminate":
t["would_fail"][100] = True
elif fault == "hover":
t["normal"][500:] = 0
elif fault == "drag":
t["slip_speed"][500:] = 0.1
elif fault == "nan":
t["normal"][400] = float("nan")
elif fault == "missing":
t["phase"][300:400] = 4
elif fault == "impact":
t["normal"][405, 0, 2] = 200
row = report(fixture_trace)
assert not row["success"] and reason in row["failure_reasons"]
-34
View File
@@ -1,34 +0,0 @@
"""Opt-in true PhysX integration; skips are NOT evidence of physical success."""
import json
import os
import subprocess
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
pytestmark = pytest.mark.skipif(os.environ.get("CYCLE_RUNTIME_TESTS") != "1", reason="requires supervised Isaac PhysX")
@pytest.mark.parametrize("script", [
"verify_wrench_physics.py", "verify_contact_cycle.py", "verify_cycle_learning_runtime.py",
])
def test_real_physics_contract(script, tmp_path):
env = os.environ.copy()
env.pop("CONDA_PREFIX", None)
env.pop("VIRTUAL_ENV", None)
env["PYTHONPATH"] = str(ROOT/"source/SkillFactory")
lab = env.get("ISAACLAB_LAUNCHER", "/home/cen/IsaacLab/isaaclab.sh")
process = subprocess.run([
sys.executable, str(ROOT/"scripts/supervise_sim.py"),
"--log", str(tmp_path/"kit.log"), "--report", str(tmp_path/"process.json"), "--timeout", "240", "--",
lab, "-p", str(ROOT/"scripts"/script), "--output", str(tmp_path/"trial"), "--headless",
], cwd=ROOT, env=env, capture_output=True, text=True, timeout=270)
assert process.returncode == 0, process.stdout[-3000:] + process.stderr[-3000:]
result = json.loads((tmp_path/"trial/result.json").read_text())
supervision = json.loads((tmp_path/"process.json").read_text())
assert result["passed"] and not result["accepted_skill"]
assert supervision["passed"] and supervision["cleanup"]["clean"]
assert not supervision["critical_log_lines"]
-71
View File
@@ -1,71 +0,0 @@
"""Pure XML tests: no Kit, Isaac Lab, network or GPU required."""
import importlib.util
import shutil
import xml.etree.ElementTree as ET
from pathlib import Path
import pytest
SPEC = importlib.util.spec_from_file_location(
"extract_leg", Path(__file__).parents[1] / "scripts/assets/extract_go2_leg.py"
)
extractor = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(extractor)
def test_repeatable_and_real_subtree(tmp_path):
a, b = tmp_path / "a", tmp_path / "b"
manifest = extractor.extract(extractor.DEFAULT_SOURCE, a)
extractor.extract(extractor.DEFAULT_SOURCE, b)
assert (a / "go2_fl.urdf").read_bytes() == (b / "go2_fl.urdf").read_bytes()
assert (a / "manifest.json").read_bytes() == (b / "manifest.json").read_bytes()
robot = ET.parse(a / "go2_fl.urdf").getroot()
assert manifest["joint_order"] == list(extractor.JOINTS)
assert len([j for j in robot.findall("joint") if j.get("type") == "revolute"]) == 3
assert {link.get("name") for link in robot.findall("link")} == {
"anchor_base",
"FL_hip",
"FL_thigh",
"FL_calf",
"FL_foot",
"FL_hip_rotor",
"FL_thigh_rotor",
"FL_calf_rotor",
"FL_calflower",
"FL_calflower1",
}
assert robot.find("joint[@name='FL_foot_joint']").get("dont_collapse") == "true"
assert robot.find("joint[@name='FL_hip_joint']/origin").get("xyz") == "0 0 0"
assert robot.find("link[@name='anchor_base']/collision") is None
for mesh in robot.findall(".//mesh"):
assert (a / mesh.get("filename")).is_file()
assert manifest["skill"]["valid"] is False
assert (a / "LICENSE").is_file()
assert manifest["missing_inertial_fixed_links"] == ["FL_calflower", "FL_calflower1"]
center = extractor.foot_center(robot)
assert abs(center[2] + manifest["anchor"]["default_height"] - 0.022 - 0.01) < 1e-12
original = ET.parse(extractor.DEFAULT_SOURCE / "urdf/go2_description.urdf").getroot()
old = extractor.foot_center(original)
assert all(
abs(new + shift - old_value) < 1e-10
for new, shift, old_value in zip(center, manifest["anchor"]["original_mount_translation"], old)
)
def test_missing_reference_fails(tmp_path):
source = tmp_path / "unitree/robots/go2_description"
shutil.copytree(extractor.DEFAULT_SOURCE, source)
(source / "dae/hip.dae").unlink()
with pytest.raises(FileNotFoundError):
extractor.extract(source, tmp_path / "out")
def test_invalid_inertia_fails(tmp_path):
source = tmp_path / "unitree/robots/go2_description"
shutil.copytree(extractor.DEFAULT_SOURCE, source)
tree = ET.parse(source / "urdf/go2_description.urdf")
tree.find("link[@name='FL_thigh']/inertial/inertia").set("ixy", "100")
tree.write(source / "urdf/go2_description.urdf")
with pytest.raises(ValueError, match="Invalid inertia"):
extractor.extract(source, tmp_path / "out")
-214
View File
@@ -1,214 +0,0 @@
"""Declarative extraction tests, including non-Go2 names and arbitrary axes."""
import dataclasses
import json
import math
import xml.etree.ElementTree as ET
from pathlib import Path
import pytest
from SkillFactory.legs import JointSpec, LegSpec
from SkillFactory.legs.spec import load_bundle
from SkillFactory.legs.urdf import extract_leg, forward, multiply, pose
ROOT = Path(__file__).parents[1]
def fixture_spec(tmp_path, n=2, box=False):
robot = ET.Element("robot", name="fixture")
for name in ["mount", *(f"segment{i}" for i in range(n)), "toe"]:
link = ET.SubElement(robot, "link", name=name)
link.append(
ET.fromstring('<inertial><mass value="0.2"/><inertia ixx="0.001" iyy="0.001" izz="0.001"/></inertial>')
)
if name == "toe":
link.append(
ET.fromstring(
'<collision><origin xyz="0.01 0 0" rpy="0 0.2 0"/><geometry>'
+ ('<box size="0.03 0.04 0.05"/>' if box else '<sphere radius="0.02"/>')
+ "</geometry></collision>"
)
)
for index in range(n):
joint = ET.SubElement(robot, "joint", name=f"pivot{index}", type="revolute")
ET.SubElement(joint, "parent", link="mount" if index == 0 else f"segment{index - 1}")
ET.SubElement(joint, "child", link=f"segment{index}")
ET.SubElement(
joint,
"origin",
xyz="0.2 0.1 -0.3" if index == 0 else "0.1 0 -0.15",
rpy="0.1 0.2 0.3" if index == 0 else "0 0 0",
)
ET.SubElement(joint, "axis", xyz="0.2 0.7 -0.3")
ET.SubElement(joint, "limit", lower="-1", upper="1", effort="10", velocity="5")
joint = ET.SubElement(robot, "joint", name="toe_mount", type="fixed")
ET.SubElement(joint, "parent", link=f"segment{n - 1}")
ET.SubElement(joint, "child", link="toe")
ET.SubElement(joint, "origin", xyz="0 0 -0.1", rpy="0 0 0")
ET.ElementTree(robot).write(tmp_path / "robot.urdf")
(tmp_path / "LICENSE").write_text("Fixture license\n")
return LegSpec(
1,
"fixture",
tmp_path,
"robot.urdf",
"fixture",
"LICENSE",
"test",
"pivot0",
(),
tuple(JointSpec(f"pivot{i}", 0.0, 0.1, 20.0, 0.5) for i in range(n)),
"toe",
)
@pytest.mark.parametrize("preset", ["go2_fl", "go1_fl"])
def test_real_legs_deterministic_and_complete(tmp_path, preset):
spec = LegSpec.load(ROOT / f"configs/legs/{preset}.json")
first = extract_leg(spec, tmp_path / "one")
second = extract_leg(spec, tmp_path / "two")
assert first == second
assert (tmp_path / "one/leg.urdf").read_bytes() == (tmp_path / "two/leg.urdf").read_bytes()
assert first["joint_order"] == [item.name for item in spec.joints]
assert spec.foot_body in first["links"] and "FL_hip_rotor" in first["links"]
assert all(name.startswith("FL_") for name in first["links"])
assert first["skill"]["trained"] is False
assert load_bundle(tmp_path / "one")["source"]["sha256"] == first["source"]["sha256"]
@pytest.mark.parametrize("n", [1, 2, 4])
def test_arbitrary_names_axes_and_mount_frame(tmp_path, n):
spec = fixture_spec(tmp_path, n)
bundle = extract_leg(spec, tmp_path / "out")
q = {joint.name: 0.3 for joint in spec.joints}
links, _ = forward(bundle["tree"], q)
expected = pose([0.2, 0.1, -0.3], [0.1, 0.2, 0.3])
original = ET.parse(tmp_path / "robot.urdf").getroot()
from SkillFactory.legs.urdf import origin, rotation, vector
for joint in original.findall("joint"):
expected = multiply(expected, pose(**origin(joint))) if joint.get("name") != "pivot0" else expected
if joint.get("type") == "revolute":
axis = vector(joint.find("axis").get("xyz"))
norm = math.sqrt(sum(v * v for v in axis))
expected = multiply(expected, rotation([v / norm for v in axis], 0.3))
actual = multiply(pose([0.2, 0.1, -0.3], [0.1, 0.2, 0.3]), links["toe"])
assert max(abs(a - b) for row_a, row_b in zip(actual, expected) for a, b in zip(row_a, row_b)) < 1e-10
assert len(bundle["joints"]) == n
def test_box_foot_and_declared_actuator_order(tmp_path):
spec = fixture_spec(tmp_path, 2, box=True)
spec = dataclasses.replace(spec, joints=tuple(reversed(spec.joints)))
bundle = extract_leg(spec, tmp_path / "out")
assert bundle["foot"]["type"] == "box"
assert bundle["joint_order"] == ["pivot1", "pivot0"]
assert bundle["tree"][0]["name"] == "pivot0"
def test_invalid_uncontrolled_and_stale_inputs(tmp_path):
spec = fixture_spec(tmp_path)
with pytest.raises(ValueError, match="moving joints"):
extract_leg(dataclasses.replace(spec, joints=spec.joints[:1]), tmp_path / "bad")
with pytest.raises(ValueError):
JointSpec("a", 0.0, 0.0, 20.0, 0.5)
with pytest.raises(ValueError):
dataclasses.replace(spec, decimation=0)
extract_leg(spec, tmp_path / "out")
with (tmp_path / "out/leg.urdf").open("a") as stream:
stream.write("<!-- tampered -->")
with pytest.raises(ValueError, match="hash mismatch"):
load_bundle(tmp_path / "out")
def test_missing_license_and_unsafe_resource(tmp_path):
spec = fixture_spec(tmp_path)
with pytest.raises(FileNotFoundError):
extract_leg(dataclasses.replace(spec, license_file="missing"), tmp_path / "bad")
robot = ET.parse(tmp_path / "robot.urdf")
visual = ET.SubElement(robot.getroot().find("link[@name='toe']"), "visual")
ET.SubElement(ET.SubElement(visual, "geometry"), "mesh", filename="../../outside.stl")
robot.write(tmp_path / "robot.urdf")
with pytest.raises(ValueError, match="escapes"):
extract_leg(spec, tmp_path / "bad")
def test_output_cannot_overwrite_sources_or_escape_through_symlink(tmp_path):
spec = fixture_spec(tmp_path)
before = (tmp_path / "robot.urdf").read_bytes()
with pytest.raises(ValueError, match="source root"):
extract_leg(spec, tmp_path)
assert (tmp_path / "robot.urdf").read_bytes() == before
output = tmp_path / "out"
output.mkdir()
(output / "leg.urdf").symlink_to(tmp_path / "robot.urdf")
with pytest.raises(ValueError, match="symlink"):
extract_leg(spec, output)
assert (tmp_path / "robot.urdf").read_bytes() == before
def test_nested_output_does_not_overwrite_an_existing_source_leg(tmp_path):
source = tmp_path / "nested"
source.mkdir()
spec = fixture_spec(source)
(source / "robot.urdf").rename(source / "leg.urdf")
spec = dataclasses.replace(spec, source_root=tmp_path, urdf="nested/leg.urdf", license_file="nested/LICENSE")
before = (source / "leg.urdf").read_bytes()
with pytest.raises(ValueError, match="overwrite source file"):
extract_leg(spec, source)
assert (source / "leg.urdf").read_bytes() == before
@pytest.mark.parametrize("change", ["missing_parent", "missing_limit", "missing_geometry"])
def test_malformed_urdf_fails_with_actionable_error(tmp_path, change):
spec = fixture_spec(tmp_path)
tree = ET.parse(tmp_path / "robot.urdf")
root = tree.getroot()
if change == "missing_geometry":
item = root.find("link[@name='toe']/collision")
item.remove(item.find("geometry"))
else:
item = root.find("joint[@name='pivot0']")
item.remove(item.find("parent" if change == "missing_parent" else "limit"))
tree.write(tmp_path / "robot.urdf")
with pytest.raises(ValueError, match="Missing"):
extract_leg(spec, tmp_path / "out")
@pytest.mark.parametrize("invalid", ["scale", "mapping", "layer", "support"])
def test_stale_or_invalid_conversion_rejected_before_kit(tmp_path, invalid):
from SkillFactory.legs.urdf import digest
bundle = extract_leg(fixture_spec(tmp_path), tmp_path / "out")
directory = tmp_path / "out"
(directory / "leg.usda").write_text("#usda 1.0\\n")
conversion = {
"usd_path": "leg.usda",
"manifest_sha256": digest(directory / "manifest.json"),
"used_layers": ["leg.usda"],
"fixed_to_world": True,
"body_paths": {name: "/Geometry/" + name for name in (*bundle["links"], bundle["anchor_body"])},
"joint_paths": {name: "/Joints/" + name for name in bundle["joint_order"]},
}
if invalid == "scale":
bundle["length_scale_m"] = 0
(directory / "manifest.json").write_text(json.dumps(bundle))
conversion["manifest_sha256"] = digest(directory / "manifest.json")
elif invalid == "mapping":
conversion["body_paths"]["toe"] = "/Geometry/" + bundle["anchor_body"]
elif invalid == "layer":
conversion["used_layers"] = []
else:
conversion["fixed_to_world"] = False
(directory / "conversion.json").write_text(json.dumps(conversion))
with pytest.raises(ValueError):
load_bundle(directory, require_usd=True)
def test_unknown_spec_fields_rejected(tmp_path):
data = LegSpec.load(ROOT / "configs/legs/go2_fl.json").to_dict()
data["typo"] = True
path = tmp_path / "spec.json"
path.write_text(json.dumps(data))
with pytest.raises(TypeError):
LegSpec.load(path)
-183
View File
@@ -1,183 +0,0 @@
"""Masking, variable DoF, equivalent token permutations, FK, and PPO semantics."""
import copy
import pytest
import torch
from SkillFactory.legs.policy import LegActorCritic, compute_gae, load_policy, ppo_update, save_policy
from SkillFactory.legs.tokens import FEATURE_SCHEMA, LegKinematics, pad_joint_observations, static_tokens
from SkillFactory.legs.urdf import extract_leg, forward
from test_leg_assets import fixture_spec
def batch(b=3, j=6, e=1):
result = {
name: torch.randn(b, j if name.startswith("joint") else e, len(FEATURE_SCHEMA[name]))
for name in ("joint_description", "joint_observation", "effector_description", "effector_observation")
}
result.update(
joint_mask=torch.tensor([[True, True, False, False, False, False]]).expand(b, -1).clone(),
effector_mask=torch.ones(b, e, dtype=torch.bool),
context=torch.randn(b, len(FEATURE_SCHEMA["context"])),
goal=torch.randn(b, 3),
)
return result
def test_padding_and_missing_feet_do_not_affect_active_policy():
torch.manual_seed(3)
model = LegActorCritic()
original = batch()
action, logp, value = model.act(original, deterministic=True)
changed = copy.deepcopy(original)
changed["joint_description"][:, 2:] = torch.nan
changed["joint_observation"][:, 2:] = torch.nan
other, other_log, other_value = model.act(changed, deterministic=True)
assert torch.equal(action, other) and torch.equal(logp, other_log) and torch.equal(value, other_value)
assert (action[:, 2:] == 0).all()
original["effector_mask"][:] = False
original["effector_description"][:] = torch.nan
original["effector_observation"][:] = torch.nan
assert all(torch.isfinite(t).all() for t in model.act(original))
def test_permutation_equivariance_and_no_inactive_gradients():
torch.manual_seed(42)
model = LegActorCritic()
original = batch()
original["joint_description"].requires_grad_()
original["joint_observation"].requires_grad_()
permutation = torch.tensor([3, 1, 5, 0, 4, 2])
shuffled = {k: v[:, permutation] if k.startswith("joint") else v for k, v in original.items()}
a, _, v = model.act(original, deterministic=True)
b, _, w = model.act(shuffled, deterministic=True)
torch.testing.assert_close(b, a[:, permutation], atol=1e-6, rtol=1e-6)
torch.testing.assert_close(v, w, atol=1e-6, rtol=1e-6)
(a.sum() + v.sum()).backward()
assert original["joint_description"].grad[:, 2:].abs().max() == 0
assert original["joint_observation"].grad[:, 2:].abs().max() == 0
assert original["joint_observation"].grad[:, :2].abs().sum() > 0
distribution, _ = model.distribution_value(original)
_, entropy, _ = model.evaluate(original, a)
torch.testing.assert_close(entropy, distribution.entropy()[:, :2].sum(dim=-1))
@pytest.mark.parametrize("n", [1, 2, 4])
def test_actual_fk_and_shared_network_across_declared_dof(tmp_path, n):
spec = fixture_spec(tmp_path, n)
bundle = extract_leg(spec, tmp_path / "asset")
static = static_tokens(bundle, 6)
q = torch.linspace(-0.2, 0.3, n, dtype=torch.float32)[None, :].expand(3, -1)
fk = LegKinematics(bundle)
actual = fk.foot_position(q)[0]
expected, _ = forward(bundle["tree"], dict(zip(bundle["joint_order"], q[0].tolist())))
torch.testing.assert_close(actual, torch.tensor([expected["toe"][i][3] for i in range(3)]), atol=1e-6, rtol=1e-6)
tokens = {k: v.expand(3, *v.shape[1:]) for k, v in static.items()}
tokens.update(
joint_observation=pad_joint_observations(q, q * 0, q * 0, bundle, 6),
effector_observation=torch.zeros(3, 1, 11),
context=torch.zeros(3, len(FEATURE_SCHEMA["context"])),
goal=torch.zeros(3, 3),
)
model = LegActorCritic()
action, _, _ = model.act(tokens)
assert action.shape == (3, 6) and (action[:, n:] == 0).all()
assert static["joint_mask"].sum() == n
with pytest.raises(ValueError):
static_tokens(bundle, n - 1)
def test_inertia_and_com_are_in_anchor_nominal_frame(tmp_path):
import xml.etree.ElementTree as ET
spec = fixture_spec(tmp_path, 1)
tree = ET.parse(tmp_path / "robot.urdf")
item = tree.getroot().find("link[@name='segment0']/inertial")
ET.SubElement(item, "origin", xyz="0.01 0 0", rpy="0 0 1.5707963267948966")
item.find("inertia").set("iyy", "0.002")
item.find("inertia").set("izz", "0.003")
tree.write(tmp_path / "robot.urdf")
bundle = extract_leg(spec, tmp_path / "asset")
description = static_tokens(bundle, 3)["joint_description"][0, 0]
scale = bundle["known_mass_scale_kg"] * bundle["length_scale_m"] ** 2
torch.testing.assert_close(
description[[15, 18, 20]] * scale, torch.tensor([0.002, 0.001, 0.003]), atol=1e-7, rtol=1e-6
)
torch.testing.assert_close(
description[21:24] * bundle["length_scale_m"], torch.tensor([0.01, 0.0, 0.0]), atol=1e-7, rtol=1e-6
)
def test_checkpoint_reload_is_exact(tmp_path):
model = LegActorCritic().eval()
observation = batch()
save_policy(model, tmp_path / "policy.pt", {"test": True})
loaded = load_policy(tmp_path / "policy.pt").eval()
assert all(torch.equal(a, b) for a, b in zip(model.act(observation, True), loaded.act(observation, True)))
def test_gae_bootstraps_timeout_not_reset_state():
rewards = torch.tensor([[1.0, 1.0], [1.0, 1.0]])
values = torch.zeros_like(rewards)
# terminal first env bootstrap=0, timeout second env terminal critic=10
next_values = torch.tensor([[0.0, 0.0], [0.0, 10.0]])
done = torch.tensor([[False, False], [True, True]])
advantage, returns = compute_gae(rewards, values, next_values, done, gamma=0.9, lam=1.0)
torch.testing.assert_close(returns, torch.tensor([[1.9, 10.0], [1.0, 10.0]]))
assert torch.equal(returns, advantage)
def test_ppo_mixed_masks_updates_actor_without_rollout_gradients():
torch.manual_seed(1)
model = LegActorCritic(hidden=16, latent=8)
observation = batch(b=4)
observation["joint_mask"][2:, 2] = True
action, logp, value = model.act(observation)
data = {
"observation": {key: item[None].repeat(3, *([1] * item.ndim)) for key, item in observation.items()},
"actions": action[None].expand(3, -1, -1),
"log_prob": logp[None].expand(3, -1),
"values": value[None].expand(3, -1),
"rewards": torch.randn(3, 4),
"next_values": value[None].expand(3, -1),
"done": torch.zeros(3, 4, dtype=torch.bool),
}
before = model.mean[-1].weight.detach().clone()
stats = ppo_update(model, torch.optim.Adam(model.parameters(), lr=1e-3), data, epochs=2, minibatch=5)
assert not torch.equal(before, model.mean[-1].weight)
assert all(torch.isfinite(torch.tensor(v)) for v in stats.values())
advantage, _ = compute_gae(data["rewards"], data["values"], data["next_values"], data["done"])
assert not advantage.requires_grad
with pytest.raises(ValueError, match="positive"):
ppo_update(model, torch.optim.Adam(model.parameters()), data, epochs=0)
data["log_prob"] = torch.full((3, 4), torch.nan)
frozen = {key: item.clone() for key, item in model.state_dict().items()}
with pytest.raises(ValueError, match="finite"):
ppo_update(model, torch.optim.Adam(model.parameters()), data)
assert all(torch.equal(model.state_dict()[key], item) for key, item in frozen.items())
@pytest.mark.parametrize("empty", [True, False])
def test_gae_rejects_empty_or_nonfinite_inputs(empty):
reward = torch.zeros(0 if empty else 1, 2)
if not empty:
reward[0, 0] = torch.nan
with pytest.raises(ValueError):
compute_gae(reward, reward, reward, torch.zeros_like(reward, dtype=torch.bool))
def test_float32_contract_ignores_global_default_dtype(tmp_path):
spec = fixture_spec(tmp_path, 2)
bundle = extract_leg(spec, tmp_path / "asset")
old = torch.get_default_dtype()
try:
torch.set_default_dtype(torch.float64)
static = static_tokens(bundle, 4)
q = torch.zeros(2, 2, dtype=torch.float32)
assert static["joint_description"].dtype == torch.float32
assert static["effector_description"].dtype == torch.float32
assert LegKinematics(bundle).foot_position(q).dtype == torch.float32
assert pad_joint_observations(q, q, q, bundle, 4).dtype == torch.float32
assert all(p.dtype == torch.float32 for p in LegActorCritic().parameters())
finally:
torch.set_default_dtype(old)
-204
View File
@@ -1,204 +0,0 @@
"""Pure configuration/mechanics oracles; these are NOT physical standing evidence."""
import copy
import json
import subprocess
import sys
import xml.etree.ElementTree as ET
from pathlib import Path
import pytest
import torch
from SkillFactory.legs.support import (
disturbance_wrench,
load_config,
load_support_asset,
negative_control_collapsed,
passive_wrench,
payload_urdf,
relative_point_velocity,
sha256,
shift_wrench,
)
ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / "configs/standing/go2_fl_support_v0.json"
@pytest.mark.parametrize("message,passed", [("normal completion", True), ("[Error] backend rejected a setting", False)])
def test_supervisor_rejects_critical_log_even_with_zero_child_exit(tmp_path, message, passed):
report = tmp_path / "process.json"
result = subprocess.run(
[
sys.executable,
str(ROOT / "scripts/supervise_sim.py"),
"--log",
str(tmp_path / "worker.log"),
"--report",
str(report),
"--",
sys.executable,
"-c",
f"print({message!r})",
],
capture_output=True,
text=True,
)
data = json.loads(report.read_text())
assert data["returncode"] == 0 and data["cleanup"]["clean"]
assert data["passed"] is passed and (result.returncode == 0) is passed
assert bool(data["critical_log_lines"]) is not passed
def test_support_config():
cfg = load_config(CONFIG)
assert cfg["payload_mass_kg"] == 3
for key in ("guide_stiffness", "guide_damping", "guide_wrench_limit"):
assert cfg[key][2] == 0
@pytest.mark.parametrize(
"key,value",
[
("payload_mass_kg", 0),
("payload_mass_kg", True),
("payload_mass_kg", float("nan")),
("guide_stiffness", [1, 1, 1, 1, 1, 1]),
("guide_damping", [1, 1, 1, 1, 1, 1]),
("guide_wrench_limit", [1, 1, 1, 1, 1, 1]),
("guide_stiffness", [-1, 0, 0, 0, 0, 0]),
("payload_size_m", [0.1, 0.1]),
("payload_size_m", [0, 0.1, 0.1]),
("disturbance_amplitude", [5, 5, 10, 1, 1, 0]),
("contact_fraction_min", 1.01),
("episode_seconds", 5),
("seed", 1.5),
("unknown", 42),
],
)
def test_bad_config_rejected(tmp_path, key, value):
data = json.loads(CONFIG.read_text())
data[key] = value
p = tmp_path / "config.json"
p.write_text(json.dumps(data))
with pytest.raises(ValueError):
load_config(p)
def test_derived_payload_is_separate_and_preserves_original_mechanics(tmp_path):
# Synthetic URDF fixture, independently specified root and child.
source = tmp_path / "source.urdf"
source.write_text(
'<robot name="fixture"><link name="anchor_base"><inertial><mass value="1"/>'
'<inertia ixx="0.001" iyy="0.001" izz="0.001" ixy="0" ixz="0" iyz="0"/>'
'</inertial></link><link name="limb"/><joint name="actuator" type="revolute">'
'<parent link="anchor_base"/><child link="limb"/><axis xyz="0 1 0"/></joint></robot>'
)
before = source.read_bytes()
cfg = load_config(CONFIG)
tree = ET.fromstring(payload_urdf(source, cfg))
assert source.read_bytes() == before
sensor = tree.find("joint[@name='mount_ft_joint']")
assert sensor.get("type") == "fixed" and sensor.get("dont_collapse") == "true"
assert sensor.find("parent").get("link") == "virtual_payload"
assert sensor.find("child").get("link") == "anchor_base"
children = {j.find("child").get("link") for j in tree.findall("joint")}
assert {link.get("name") for link in tree.findall("link")} - children == {"virtual_payload"}
assert tree.find("link[@name='anchor_base']/inertial/mass").get("value") == "0.05"
inertia = tree.find("link[@name='virtual_payload']/inertial/inertia")
assert float(inertia.get("ixx")) == pytest.approx(3 * (0.18**2 + 0.08**2) / 12)
def structure(node):
return node.tag, node.attrib, tuple(structure(child) for child in node)
assert structure(tree.find("joint[@name='actuator']")) == structure(
ET.fromstring(before).find("joint[@name='actuator']")
)
def test_bushing_passivity_and_no_vertical_hanging():
cfg = load_config(CONFIG)
k, d, limit = [torch.tensor(cfg[x]) for x in ("guide_stiffness", "guide_damping", "guide_wrench_limit")]
torch.manual_seed(7)
velocity = torch.randn(64, 6)
damping = passive_wrench(torch.zeros_like(velocity), velocity, k, d, limit)
assert ((damping * velocity).sum(-1) <= 0).all()
displacement = torch.randn(64, 6)
restoring = passive_wrench(displacement, torch.zeros_like(displacement), k, d, limit)
assert ((restoring * displacement).sum(-1) <= 0).all()
assert torch.equal(restoring[:, 2], torch.zeros(64))
assert (restoring.abs() <= limit).all()
@pytest.mark.parametrize(
"time,amplitude", [(0, 0), (3, 0), (3.25, 0.5), (4, 1), (5.75, 0.5), (6, 0), (7, 0), (9, 1), (12, 0)]
)
def test_all_thirteen_signed_disturbance_cases(time, amplitude):
amps = torch.tensor([5.0, 5.0, 10.0, 1.0, 1.0, 1.0])
result = disturbance_wrench(torch.full((13,), float(time)), torch.arange(13), amps)
expected = torch.zeros(13, 6)
for axis in range(6):
expected[1 + 2 * axis, axis] = amplitude * amps[axis]
expected[2 + 2 * axis, axis] = -amplitude * amps[axis]
torch.testing.assert_close(result, expected, rtol=0, atol=0)
def test_rotating_frame_relative_velocity_and_wrench_origin():
r = torch.tensor([[1.0, 0, 0]])
omega = torch.tensor([[0.0, 0, 2.0]])
v_root = torch.tensor([[3.0, 0, 0]])
# A point rigidly attached to a rotating root has zero relative velocity.
v_point = v_root + torch.cross(omega, r, dim=-1)
torch.testing.assert_close(relative_point_velocity(v_point, v_root, omega, r), torch.zeros(1, 3))
force, torque = shift_wrench(torch.tensor([[0.0, 5, 0]]), torch.zeros(1, 3), r)
torch.testing.assert_close(torque, torch.tensor([[0.0, 0, 5]]))
torch.testing.assert_close(force, torch.tensor([[0.0, 5, 0]]))
@pytest.mark.parametrize(
"drops,torques,expected",
[
([0.2, 0.3], [0, 0], True),
([0.0, 0.3], [0, 0], False),
([0.09, 0.3], [0, 0], False),
([0.2, 0.3], [0.1, 0], False),
([], [], False),
],
)
def test_negative_control_requires_downward_collapse_of_all_envs(drops, torques, expected):
rows = [
{"max_base_drop_m": drop, "max_normalized_torque": torque, "max_height_error_m": 0.5}
for drop, torque in zip(drops, torques)
]
assert negative_control_collapsed(rows) is expected
def test_support_identity_and_path_integrity(tmp_path):
cfg = copy.deepcopy(load_config(CONFIG))
source = tmp_path / "source"
source.mkdir()
(source / "manifest.json").write_text("source identity")
cfg["source_bundle"] = str(source)
asset = tmp_path / "support"
asset.mkdir()
(asset / "a.usda").write_text("fixture, not an actual USD")
manifest = {
"contract": "go2-fl-loaded-stand-v0",
"fixed_to_world": False,
"mount_joint": "mount_ft_joint",
"usd_path": "a.usda",
"source_manifest_sha256": sha256(source / "manifest.json"),
"files": {"a.usda": sha256(asset / "a.usda")},
**{k: cfg[k] for k in ("payload_mass_kg", "payload_size_m", "payload_com_m", "sensor_carrier_mass_kg")},
}
path = asset / "support.json"
path.write_text(json.dumps(manifest))
assert load_support_asset(asset, cfg)["fixed_to_world"] is False
cfg["payload_mass_kg"] = 4
with pytest.raises(ValueError, match="config mismatch"):
load_support_asset(asset, cfg)
cfg["payload_mass_kg"] = 3
manifest["files"] = {"../source/manifest.json": sha256(source / "manifest.json")}
path.write_text(json.dumps(manifest))
with pytest.raises(ValueError, match="integrity"):
load_support_asset(asset, cfg)
-190
View File
@@ -1,190 +0,0 @@
"""No Kit required: offline updates, exact resume, padding and immutable inference."""
import copy
import importlib.util
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
from SkillFactory.legs.frozen_policy import Actor, FrozenPolicy
from SkillFactory.legs.offline import IQL, atomic_save, canonical_hash, features, sha256
ROOT = Path(__file__).resolve().parents[1]
def training_config():
return json.loads((ROOT / "configs/training/go2_fl_offline_v1.json").read_text())["training"]
def test_iql_exact_resume_and_finite_update(tmp_path):
torch.set_num_threads(1)
torch.manual_seed(7)
cfg = training_config()
learner = IQL(cfg, torch.zeros(15), torch.ones(15))
data = {
"state": torch.randn(64, 15),
"next_state": torch.randn(64, 15),
"action": torch.randn(64, 3).tanh(),
"reward": torch.rand(64),
"terminated": torch.zeros(64, dtype=torch.bool),
}
before = copy.deepcopy(learner.actor.state_dict())
for _ in range(3):
learner.update(data)
atomic_save(learner.state_dict(), tmp_path / "checkpoint.pt")
ids = torch.randint(64, (32,))
learner.update({k: v[ids] for k, v in data.items()})
after = learner.state_dict()
restored = IQL(cfg, torch.zeros(15), torch.ones(15))
restored.load_state_dict(torch.load(tmp_path / "checkpoint.pt", weights_only=True))
restored_ids = torch.randint(64, (32,))
assert torch.equal(ids, restored_ids)
restored.update({k: v[restored_ids] for k, v in data.items()})
for name, values in after["models"].items():
assert all(torch.equal(value, restored.state_dict()["models"][name][key]) for key, value in values.items())
assert any(not torch.equal(value, learner.actor.state_dict()[key]) for key, value in before.items())
data["reward"][0] = float("nan")
with pytest.raises(RuntimeError, match="Non-finite"):
learner.update(data)
def make_package(tmp_path):
torch.manual_seed(1)
shapes = {
"joint_description": (1, 8, 25),
"joint_observation": (1, 8, 3),
"joint_mask": (1, 8),
"effector_description": (1, 1, 16),
"effector_observation": (1, 1, 11),
"effector_mask": (1, 1),
"context": (1, 10),
"goal": (1, 3),
}
tokens = {
key: torch.zeros(shape, dtype=torch.bool if "mask" in key else torch.float32) for key, shape in shapes.items()
}
tokens["joint_mask"][:, :3] = True
tokens["effector_mask"][:] = True
binding = {
"part_id": "go2_fl",
"manifest_sha256": "a" * 64,
"context": tokens["context"][0].tolist(),
"static_tokens": {
k: tokens[k][0].tolist()
for k in ("joint_description", "joint_mask", "effector_description", "effector_mask")
},
}
(tmp_path / "binding.json").write_text(json.dumps(binding))
torch.save(Actor().state_dict(), tmp_path / "actor.pt")
for name in ("config.json", "README.md", "frozen_policy.py"):
(tmp_path / name).write_text("test")
manifest = {
"format": "skillfactory.skillbundle.v1",
"interface": "go2-fl-reach-leg-token-v1",
"hidden": 128,
"version": "test",
"files": {p.name: sha256(p) for p in tmp_path.iterdir()},
}
(tmp_path / "manifest.json").write_text(json.dumps(manifest))
return tokens, binding
def test_frozen_inference_and_fail_closed(tmp_path):
tokens, binding = make_package(tmp_path)
policy = FrozenPolicy(tmp_path, part_id="go2_fl", manifest_sha256=binding["manifest_sha256"])
state = copy.deepcopy(policy._actor.state_dict())
result = policy.act(tokens)
assert result.shape == (1, 8) and not result.requires_grad
assert features(tokens).shape == (1, 15)
tokens["joint_observation"][:, 3:] = float("nan")
tokens["joint_description"][:, 3:] = float("nan")
assert torch.equal(result, policy.act(tokens))
assert all(torch.equal(value, policy._actor.state_dict()[key]) for key, value in state.items())
tokens["goal"][0, 0] = float("inf")
with pytest.raises(ValueError, match="Non-finite"):
policy.act(tokens)
with pytest.raises(ValueError, match="hardware"):
FrozenPolicy(tmp_path, part_id="go1_fl", manifest_sha256=binding["manifest_sha256"])
with (tmp_path / "actor.pt").open("ab") as stream:
stream.write(b"x")
with pytest.raises(ValueError, match="integrity"):
FrozenPolicy(tmp_path, part_id="go2_fl", manifest_sha256=binding["manifest_sha256"])
def test_release_rejects_same_actor_different_tested_package(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(ROOT / "scripts"))
from stage2_acceptance import independent_load_passed
candidate = tmp_path / "candidate"
candidate.mkdir()
make_package(candidate)
tested_digest = sha256(candidate / "manifest.json")
# Same weights, changed inference payload/binding metadata: old evidence is stale.
(candidate / "README.md").write_text("changed payload")
manifest = json.loads((candidate / "manifest.json").read_text())
manifest["files"]["README.md"] = sha256(candidate / "README.md")
(candidate / "manifest.json").write_text(json.dumps(manifest))
report = {
"passed": True,
"status": "completed",
"isolated": True,
"package_only": True,
"parameters_and_buffers_unchanged": True,
"requires_grad": False,
"training_or_simulator_imports": False,
"actor_sha256": sha256(candidate / "actor.pt"),
"manifest_sha256": tested_digest,
}
assert independent_load_passed(report, candidate, tested_digest)
assert not independent_load_passed(report, candidate, sha256(candidate / "manifest.json"))
def test_hash_is_order_independent_and_nan_rejected():
assert canonical_hash({"a": 1, "b": 2}) == canonical_hash({"b": 2, "a": 1})
with pytest.raises(ValueError):
canonical_hash({"bad": float("nan")})
def test_stability_samples_memory_at_end(tmp_path, monkeypatch):
monkeypatch.syspath_prepend(str(ROOT / "scripts"))
spec = importlib.util.spec_from_file_location("stage2_sim", ROOT / "scripts/stage2_sim.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
tokens, _ = make_package(tmp_path)
weights = tmp_path / "checkpoint.pt"
torch.save({"learner": {"models": {"actor": Actor().state_dict()}}}, weights)
env = SimpleNamespace(
device="cpu",
num_envs=1,
step_dt=0.01,
reset=lambda **kwargs: None,
step=lambda action: (
None,
torch.zeros(1),
torch.zeros(1, dtype=torch.bool),
torch.zeros(1, dtype=torch.bool),
None,
),
)
adapter = SimpleNamespace(snapshot=lambda: tokens)
monkeypatch.setattr(module, "goals", lambda *a, **kw: None)
audit = {
"max_normalized_torque": 0,
"max_normalized_velocity": 0,
"joint_limit_excess_rad": 0,
"anchor_pose_error": 0,
"invalid_states": 0,
"physical_samples": 0,
}
monkeypatch.setattr(module, "Audit", lambda *a: SimpleNamespace(report=lambda: audit))
memory = iter([(1000, 2000), (1000, 2000), (800, 2000)])
monkeypatch.setattr(torch.cuda, "synchronize", lambda: None)
monkeypatch.setattr(torch.cuda, "mem_get_info", lambda: next(memory))
cfg = json.loads((ROOT / "configs/training/go2_fl_offline_v1.json").read_text())
cfg["test"]["stability_seconds"] = 0.1
args = SimpleNamespace(package=None, weights=weights, mode="stability")
report = module.evaluate(env, adapter, cfg, args)
assert report["device_used_before"] == 1000 and report["device_used_max"] == 1200
assert report["memory_growth_fraction"] == 0.2 and not report["passed"]
-423
View File
@@ -1,423 +0,0 @@
"""Fail-closed publication, full boundary strata, and report lifecycle regressions (no Kit)."""
import itertools
import json
import subprocess
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
from SkillFactory.legs.offline import canonical_hash, sha256
from test_offline_leg import make_package
ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture(autouse=True)
def scripts(monkeypatch):
monkeypatch.syspath_prepend(str(ROOT / "scripts"))
def put(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(json.dumps(value))
def load_report(package):
return {
"passed": True,
"status": "completed",
"isolated": True,
"package_only": True,
"parameters_and_buffers_unchanged": True,
"requires_grad": False,
"training_or_simulator_imports": False,
"actor_sha256": sha256(package / "actor.pt"),
"manifest_sha256": sha256(package / "manifest.json"),
}
@pytest.fixture
def run_fixture(tmp_path, request):
from export_leg_bundle import manifest
from stage2_boundary import apply_boundary, boundary_coverage
cfg = json.loads((ROOT / "configs/training/go2_fl_offline_v1_attempt2.json").read_text())
cfg.update(num_envs=26, episode_steps=2)
cfg["collection"]["shards"] = 1
cfg["training"]["updates"] = 10
cfg["selection"].update(candidate_updates=[10], batches=1)
cfg["test"].update(batches=1, boundary_batches=1, stability_seconds=1, stability_envs=2)
run, candidate = tmp_path / "run", tmp_path / "candidate"
candidate.mkdir()
_, binding = make_package(candidate)
binding["spec"] = {"physics_dt": 0.002, "decimation": 5}
put(candidate / "binding.json", binding)
(run / "data").mkdir(parents=True)
(run / "data/shard.pt").write_bytes(b"unit-test-only-data")
digest = canonical_hash(cfg)
index = {
"complete": True,
"config_sha256": digest,
"transitions": 52,
"shards": [{"path": "shard.pt", "sha256": sha256(run / "data/shard.pt"), "transitions": 52}],
}
put(run / "data/dataset.json", index)
identity = {"config_sha256": digest, "dataset_sha256": sha256(run / "data/dataset.json")}
put(
run / "train/result.json",
{"passed": True, "training_complete": True, "status": "completed", "updates": 10, "identity": identity},
)
(run / "train/step_000010.pt").write_bytes(b"unit-test-only-checkpoint")
weights_hash = sha256(run / "train/step_000010.pt")
put(
candidate / "selection.json",
{
"selected_update": 10,
"checkpoint_sha256": weights_hash,
"actor_sha256": sha256(candidate / "actor.pt"),
"config_sha256": digest,
"training_identity": identity,
},
)
version = getattr(request, "param", None)
if version:
put(
candidate / "release.json",
{"format": "skillfactory.release.v1", "version": version, "training_config_sha256": digest},
)
manifest(candidate, cfg, "candidate")
put(run / "resume_exact.json", {"passed": True, "full_learner_optimizer_rng_exact": True})
for name in ("pytest.log", "ruff.log"):
(run / name).write_text("unit-test fixture: passed\n")
put(
run / "engineering_checks.json",
{
"passed": True,
"git_diff_check": True,
"review_blockers_remaining": 0,
"pytest_log_sha256": sha256(run / "pytest.log"),
"ruff_log_sha256": sha256(run / "ruff.log"),
},
)
put(
run / "validation_000010/result.json",
{
"passed": True,
"status": "completed",
"gates": {"mean": True},
"config_sha256": digest,
"weight_sha256": weights_hash,
"policy": {"episodes": 26, "mean_error_m": 0.002},
},
)
(run / "validation_000010.log").write_text("passed\n")
base = {
"passed": True,
"status": "completed",
"weight_sha256": sha256(candidate / "actor.pt"),
"package_manifest_sha256": sha256(candidate / "manifest.json"),
"config_sha256": digest,
"max_normalized_torque": 0.5,
"max_normalized_velocity": 0.5,
"joint_limit_excess_rad": 0,
"anchor_pose_error": 0,
"invalid_states": 0,
"physical_samples": 500,
}
for mode in ("test", "boundary", "stability"):
row = dict(base)
if mode == "stability":
row.update(
control_steps=100,
environment_control_steps=200,
seconds_per_env=1,
num_envs=2,
memory_growth_fraction=0,
)
else:
for name, error in (("policy", 0.002), ("zero", 0.05)):
row[name] = {
"episodes": 26,
"mean_error_m": error,
"p95_error_m": error,
"success_fraction": float(error <= 0.015),
"episode_mean_errors_m": [error] * 26,
"episode_peak_errors_m": [error] * 26,
}
row.update(
baseline_error_reduction=0.96, seed=cfg["test"]["boundary_seed" if mode == "boundary" else "seed"]
)
if mode == "boundary":
row["boundary_actions"] = apply_boundary(torch.zeros(26, 3)).tolist()
row["boundary_coverage"] = boundary_coverage(row["boundary_actions"])
put(run / mode / "result.json", row)
(run / f"{mode}.log").write_text("passed\n")
put(run / "standalone.json", load_report(candidate))
return SimpleNamespace(
run=run, candidate=candidate, output=tmp_path / "published", python=Path(sys.executable)
), cfg
@pytest.mark.parametrize("name", ["engineering_checks", "resume_exact"])
@pytest.mark.parametrize("damage", ["false", "missing", "malformed"])
def test_failed_or_missing_mandatory_gate_never_publishes(run_fixture, name, damage):
from export_leg_bundle import finalize
from stage2_acceptance import evaluate_acceptance
args, cfg = run_fixture
assert evaluate_acceptance(args.run, args.candidate, cfg)["passed"]
path = args.run / f"{name}.json"
if damage == "missing":
path.unlink()
elif damage == "malformed":
path.write_text("{")
else:
report = json.loads(path.read_text())
report["passed"] = False
put(path, report)
checks = evaluate_acceptance(args.run, args.candidate, cfg)["checks"]
assert not checks["engineering" if name == "engineering_checks" else "resumable"]
with pytest.raises((ValueError, FileNotFoundError)):
finalize(args, cfg)
assert not args.output.exists()
assert not list(args.output.parent.glob(".published*"))
def test_float32_window_roundoff_does_not_fail_valid_evidence(run_fixture):
from stage2_acceptance import goal_metrics_passed
args, cfg = run_fixture
row = json.loads((args.run / "test/result.json").read_text())
row["zero"]["episode_mean_errors_m"][0] += 1e-8
assert goal_metrics_passed(row, cfg, "test")
row["zero"]["episode_mean_errors_m"][0] += 1e-3
assert not goal_metrics_passed(row, cfg, "test")
def test_both_false_cannot_publish(run_fixture):
from export_leg_bundle import finalize
args, cfg = run_fixture
for name in ("engineering_checks", "resume_exact"):
row = json.loads((args.run / f"{name}.json").read_text())
row["passed"] = False
put(args.run / f"{name}.json", row)
with pytest.raises(ValueError, match="engineering, resumable"):
finalize(args, cfg)
assert not args.output.exists()
@pytest.mark.parametrize("damage", ["coverage", "hash", "stale_load", "missing_log", "short_stability"])
def test_other_gates_shared_by_publication_and_verification(run_fixture, damage):
from export_leg_bundle import finalize
from stage2_acceptance import evaluate_acceptance
args, cfg = run_fixture
if damage in ("coverage", "hash"):
p = args.run / "boundary/result.json"
row = json.loads(p.read_text())
row.pop("boundary_actions" if damage == "coverage" else "package_manifest_sha256")
put(p, row)
elif damage == "stale_load":
row = load_report(args.candidate)
row.update(passed=False, status="running")
put(args.run / "standalone.json", row)
elif damage == "missing_log":
(args.run / "test.log").unlink()
else:
p = args.run / "stability/result.json"
row = json.loads(p.read_text())
row["physical_samples"] = 499
put(p, row)
assert not evaluate_acceptance(args.run, args.candidate, cfg)["passed"]
with pytest.raises(ValueError, match="Acceptance failed"):
finalize(args, cfg)
assert not args.output.exists()
def test_same_weights_different_manifest_cannot_publish(run_fixture):
from export_leg_bundle import finalize, manifest
from stage2_acceptance import evaluate_acceptance
args, cfg = run_fixture
actor_hash = sha256(args.candidate / "actor.pt")
(args.candidate / "README.md").write_text("different package payload")
manifest(args.candidate, cfg, "candidate")
checks = evaluate_acceptance(args.run, args.candidate, cfg)["checks"]
assert sha256(args.candidate / "actor.pt") == actor_hash
assert not checks["test"] and not checks["independent_candidate_load"]
with pytest.raises(ValueError, match="Acceptance failed"):
finalize(args, cfg)
assert not args.output.exists()
@pytest.mark.parametrize("run_fixture", [None, "1.0.1"], indirect=True)
def test_publish_is_atomic_and_uses_final_staged_manifest(run_fixture, monkeypatch):
import verify_frozen_leg
from export_leg_bundle import finalize
from stage2_acceptance import evaluate_release
args, cfg = run_fixture
seen = []
def verify(staged, python, output):
assert not args.output.exists()
assert staged != args.candidate and staged.parent.parent == args.output.parent
result = load_report(staged)
assert result["manifest_sha256"] != sha256(args.candidate / "manifest.json")
put(output, result)
seen.append(result)
return result
monkeypatch.setattr(verify_frozen_leg, "verify_package", verify)
finalize(args, cfg)
assert len(seen) == 1 and json.loads((args.output / "manifest.json").read_text())["status"] == "accepted"
assert evaluate_release(args.run, args.output, cfg, seen[0])["passed"]
assert cfg["release_version"] == "1.0.0"
assert (
json.loads((args.output / "manifest.json").read_text())["version"]
== json.loads((args.candidate / "manifest.json").read_text())["version"]
)
before = sha256(args.output / "manifest.json")
with pytest.raises(ValueError, match="Immutable"):
finalize(args, cfg)
assert sha256(args.output / "manifest.json") == before
assert not list(args.output.parent.glob(".published*"))
row = json.loads((args.run / "engineering_checks.json").read_text())
row["passed"] = False
put(args.run / "engineering_checks.json", row)
assert not evaluate_release(args.run, args.output, cfg, seen[0])["passed"]
@pytest.mark.parametrize("damage", ["config_hash", "format", "invalid_version", "finalize_version"])
def test_release_metadata_cannot_bypass_training_identity(run_fixture, damage):
from export_leg_bundle import finalize
from stage2_acceptance import package_version
args, cfg = run_fixture
metadata = {"format": "skillfactory.release.v1", "version": "1.0.1", "training_config_sha256": canonical_hash(cfg)}
if damage == "config_hash":
metadata["training_config_sha256"] = "wrong"
elif damage == "format":
metadata["format"] = "unsupported"
elif damage == "invalid_version":
metadata["version"] = "../1.0.1"
if damage == "finalize_version":
args.release_version = "1.0.1" # Cannot relabel a tested 1.0.0 candidate.
with pytest.raises(ValueError, match="cannot change"):
finalize(args, cfg)
else:
put(args.candidate / "release.json", metadata)
with pytest.raises(ValueError, match="Release"):
package_version(args.candidate, cfg)
assert not args.output.exists()
@pytest.mark.parametrize("failure", ["load", "copy", "negative_load"])
def test_failed_staging_leaves_no_accepted_destination(run_fixture, monkeypatch, failure):
import export_leg_bundle
import verify_frozen_leg
args, cfg = run_fixture
def fail(*a, **kw):
assert not args.output.exists()
if failure == "negative_load":
return dict(load_report(a[0]), passed=False)
raise RuntimeError("injected failure")
monkeypatch.setattr(
export_leg_bundle.shutil if failure == "copy" else verify_frozen_leg,
"copytree" if failure == "copy" else "verify_package",
fail,
)
with pytest.raises((RuntimeError, ValueError), match="injected failure|independent_release_load"):
export_leg_bundle.finalize(args, cfg)
assert not args.output.exists() and not list(args.output.parent.glob(".published*"))
@pytest.mark.parametrize("size", [26, 52, 256])
@pytest.mark.parametrize("seed", [0, 1, 41000])
def test_boundary_covers_every_axis_and_sign_in_actual_goals(size, seed):
from stage2_boundary import boundary_coverage
from stage2_sim import goals
term = SimpleNamespace(goal_q=torch.zeros(size, 3), _command=torch.zeros(size, 3))
env = SimpleNamespace(num_envs=size, device="cpu", command_manager=SimpleNamespace(get_term=lambda _: term))
adapter = SimpleNamespace(nominal=torch.zeros(3), scale=0.25, fk=SimpleNamespace(foot_position=lambda q: q.clone()))
actions = goals(env, adapter, seed, boundary=True)
repeated = goals(env, adapter, seed, boundary=True)
assert torch.equal(actions, repeated) and torch.equal(term.goal_q, actions * 0.25)
# Independent oracle: every nonzero axis/sign signature must appear.
signatures = {tuple(int(v / 0.75) if abs(v) == 0.75 else 0 for v in row) for row in actions.tolist()}
expected = set(itertools.product((-1, 0, 1), repeat=3)) - {(0, 0, 0)}
assert signatures == expected
coverage = boundary_coverage(actions.tolist())
assert (coverage["faces"], coverage["edges"], coverage["corners"]) == (6, 12, 8)
assert coverage["complete"] and sum(coverage["strata_counts"].values()) == size
assert max(coverage["strata_counts"].values()) - min(coverage["strata_counts"].values()) <= 1
def test_small_boundary_batch_cannot_silently_undercover():
from stage2_boundary import apply_boundary
with pytest.raises(ValueError, match="26"):
apply_boundary(torch.zeros(25, 3))
@pytest.mark.parametrize("failure", ["copy", "python", "child", "malformed", "negative", "interrupt"])
def test_independent_failure_replaces_old_success_atomically(tmp_path, monkeypatch, failure):
import verify_frozen_leg as verifier
package = tmp_path / "package"
package.mkdir()
(package / "actor.pt").write_bytes(b"weight")
(package / "manifest.json").write_text("{}")
output = tmp_path / "report.json"
put(output, {"passed": True, "status": "completed", "actor_sha256": "stale"})
def fail(*a, **kw):
initial = json.loads(output.read_text())
assert initial["passed"] is False and initial["status"] == "running"
if failure in ("copy", "python"):
raise FileNotFoundError("injected")
if failure == "child":
raise subprocess.CalledProcessError(7, ["child"], output="out", stderr="bad weights")
if failure == "interrupt":
raise KeyboardInterrupt()
return SimpleNamespace(stdout="not JSON" if failure == "malformed" else '{"passed":false}', stderr="failure")
monkeypatch.setattr(
verifier.shutil if failure == "copy" else verifier.subprocess, "copytree" if failure == "copy" else "run", fail
)
with pytest.raises((ValueError, FileNotFoundError, subprocess.CalledProcessError, KeyboardInterrupt)):
verifier.verify_package(package, Path(sys.executable), output)
report = json.loads(output.read_text())
assert report["passed"] is False and report["status"] == "failed" and "error" in report
assert "actor_sha256" not in report and report["run_id"]
if failure == "child":
assert report["returncode"] == 7 and report["stderr"] == "bad weights"
assert not [p for p in tmp_path.iterdir() if p.name not in ("package", "report.json")]
def test_independent_success_and_package_change_detection(tmp_path, monkeypatch):
import verify_frozen_leg as verifier
package = tmp_path / "package"
package.mkdir()
(package / "actor.pt").write_bytes(b"weight")
(package / "manifest.json").write_text("{}")
output = tmp_path / "report.json"
report = load_report(package)
monkeypatch.setattr(
verifier.subprocess, "run", lambda *a, **kw: SimpleNamespace(stdout=json.dumps(report), stderr="")
)
result = verifier.verify_package(package, Path(sys.executable), output)
assert result["passed"] and json.loads(output.read_text())["status"] == "completed"
(package / "actor.pt").write_bytes(b"different weight")
with pytest.raises(ValueError, match="changed"):
verifier.verify_package(package, Path(sys.executable), output)
assert json.loads(output.read_text())["passed"] is False
-276
View File
@@ -1,276 +0,0 @@
"""Pure regressions: frozen standing ABI and independent protocol reducer."""
import json
import sys
from pathlib import Path
import pytest
import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
from SkillFactory.legs.frozen_standing import CORE, SHAPES, Actor, FrozenStanding, file_hash
from SkillFactory.legs.standing_ppo import canonical_hash
from SkillFactory.legs.support import disturbance_wrench
from standing_protocol import WIDTHS, calibration_errors, inputs_for, load_at, reduce_trace
@pytest.fixture
def package(tmp_path):
task = tmp_path / "task.json"
task.write_text("{}")
binding = {
"task_sha256": file_hash(task),
"support_sha256": "a" * 64,
"height_m": 0.33,
"nominal": [0.0, 0.8, -1.5],
"action_scale_rad": 0.5,
"soft_limits": [[-0.8, 0.8], [-1.0, 3.0], [-2.6, -0.9]],
}
for name in CORE - {"task.json", "actor.pt", "binding.json"}:
(tmp_path / name).write_text("fixture")
(tmp_path / "binding.json").write_text(json.dumps(binding))
torch.save(Actor().state_dict(), tmp_path / "actor.pt")
manifest = {
"format": "skillfactory.standing-bundle.v1",
"contract": "go2-fl-loaded-stand-v0",
"version": "1.0.0",
"hidden": 128,
"files": {p.name: file_hash(p) for p in tmp_path.iterdir()},
}
(tmp_path / "manifest.json").write_text(json.dumps(manifest))
return tmp_path, {
"manifest_sha256": file_hash(tmp_path / "manifest.json"),
"task_sha256": binding["task_sha256"],
"support_sha256": binding["support_sha256"],
}
def observation(batch=3):
obs = {k: torch.zeros(batch, *shape) for k, shape in SHAPES.items()}
obs["goal"][:] = 0.33
obs["base_state"][:, 6] = 1
return obs
def test_frozen_abi_stateless_and_rejects_bad_contract(package):
path, kwargs = package
p = FrozenStanding(path, **kwargs)
obs = observation()
before = {k: v.clone() for k, v in obs.items()}
a = p.act(obs)
assert a.shape == (3, 3) and not a.requires_grad and torch.equal(a, p.act(obs))
assert all(torch.equal(v, before[k]) for k, v in obs.items())
for key in kwargs:
with pytest.raises(ValueError):
FrozenStanding(path, **{**kwargs, key: "0" * 64})
for key in obs:
bad = {k: v.clone() for k, v in obs.items()}
bad[key].flatten()[0] = torch.nan
with pytest.raises(ValueError):
p.act(bad)
for key, value in (
("goal", torch.zeros(3, 2)),
("goal", torch.zeros(3, 1, dtype=torch.float64)),
("goal", torch.zeros(3, 1, device="meta")),
):
with pytest.raises(ValueError):
p.act({**obs, key: value})
with pytest.raises(ValueError):
p.act(observation(0))
(path / "actor.pt").write_bytes(b"corrupted")
with pytest.raises(ValueError, match="integrity"):
FrozenStanding(path, **kwargs)
def test_required_manifest_entries_cannot_be_deleted(package):
path, kwargs = package
m = json.loads((path / "manifest.json").read_text())
del m["files"]["actor.pt"]
(path / "manifest.json").write_text(json.dumps(m))
with pytest.raises(ValueError, match="Missing"):
FrozenStanding(path, **{**kwargs, "manifest_sha256": file_hash(path / "manifest.json")})
def test_protocol_fixed_coverage_and_original_load_equivalence():
full = inputs_for("full")
for time in (0.0, 3.2, 4.0, 5.75, 10.0, 13.99):
t = torch.full((13,), time)
actual = load_at(
t,
torch.tensor(full["basis"]),
torch.ones(13),
torch.zeros(13),
torch.tensor([5.0, 5.0, 10.0, 1.0, 1.0, 1.0]),
)
expected = disturbance_wrench(t, torch.arange(13), torch.tensor([5.0, 5.0, 10.0, 1.0, 1.0, 1.0]))
torch.testing.assert_close(actual, expected, atol=0, rtol=0)
h = inputs_for("holdout")
assert h == inputs_for("holdout") and h["seed"] == 83000
assert len(set(map(tuple, h["basis"]))) == 13
e = torch.tensor(inputs_for("exploratory")["basis"])
assert (e.abs().sum(-1) == 2).all() and len(e.unique(dim=0)) == 60
def test_calibration_cannot_average_away_or_cancel_a_bad_cycle():
expected = torch.zeros(21000, 1, 6)
measured = expected.clone()
measured[999:1499, :, 2] = -10
measured[7999:8499, :, 2] = 10
error, counts = calibration_errors(measured, expected, 42.0)
assert counts == [500] * 9
assert error[0, 0, 2] == 10 and error[3, 0, 2] == 10
assert error.max() > 1.5
def test_release_guards_reject_stale_success_and_missing_memory(tmp_path):
from standing_acceptance import check_process, memory_gate, read_json
log = tmp_path / "bad.log"
log.write_text("[Error] backend exploded\n")
result = {"passed": True, "status": "completed"}
process = {
"passed": True,
"status": "completed",
"returncode": 0,
"cleanup": {"clean": True, "remaining": []},
"critical_log_lines": ["[Error] backend exploded"],
}
with pytest.raises(ValueError, match="process"):
check_process(result, process, log, True)
with pytest.raises(ValueError, match="memory"):
memory_gate([])
values = [{"sim_seconds": i, "bytes": 1000 if i < 110 else 1100} for i in range(1, 121)]
assert memory_gate(values) > 0.05
bad = tmp_path / "invalid.json"
bad.write_text('{"passed": true, "value": NaN}')
with pytest.raises(ValueError, match="Nonfinite"):
read_json(bad)
def test_atomic_publication_never_overwrites_existing_directory(tmp_path):
from publish_standing import rename_no_replace
source, target = tmp_path / "stage", tmp_path / "version"
source.mkdir()
target.mkdir()
(target / "sentinel").write_text("keep")
with pytest.raises(OSError):
rename_no_replace(source, target)
assert source.exists() and (target / "sentinel").read_text() == "keep"
def test_failed_gate_leaves_no_release_or_lock(tmp_path, monkeypatch):
import publish_standing as publish
def reject(*args):
raise ValueError("No physics evidence")
monkeypatch.setattr(publish, "audit", reject)
with pytest.raises(ValueError, match="physics"):
publish.publish(tmp_path / "missing", tmp_path / "releases", Path(sys.executable))
releases = tmp_path / "releases"
assert not (releases / publish.NAME).exists()
assert not list(releases.glob(".*.publish.lock"))
assert not json.loads((releases / f"{publish.NAME}.acceptance.json").read_text())["passed"]
@pytest.mark.parametrize("fail_at", [1, 2, 3, 4])
def test_load_and_postcommit_failures_never_leave_accepted_paths(tmp_path, monkeypatch, fail_at):
import publish_standing as publish
run = tmp_path / "run"
package = run / "candidate"
package.mkdir(parents=True)
(package / "actor.pt").write_bytes(b"fixture")
files = {"actor.pt": file_hash(package / "actor.pt")}
(package / "manifest.json").write_text(json.dumps({"files": files}))
evidence = {
"passed": True,
"stage": "eligible_for_frozen_publication",
"candidate_manifest_sha256": file_hash(package / "manifest.json"),
"core_files": files,
"artifacts": {},
"trials": {},
"training": {},
"holdout_improvement_fraction": 1.0,
}
for name in ("publication_gate", "independent_candidate", "candidate_lock"):
(run / f"{name}.json").write_text("{}")
log = run / "checks.log"
log.write_text("fixture")
(run / "engineering.json").write_text(
json.dumps(dict.fromkeys(("pytest_log", "ruff_log", "review_report"), str(log)))
)
for name in ("full", "holdout", "hold", "stability", "exploratory"):
(run / name).mkdir()
(run / name / "result.json").write_text("{}")
(run / f"{name}_process.json").write_text("{}")
monkeypatch.setattr(publish, "audit", lambda *args: evidence)
calls = 0
def check(directory, *args):
nonlocal calls
calls += 1
if calls == fail_at:
raise ValueError("Injected publication failure")
return {"passed": True, "manifest_sha256": file_hash(directory / "manifest.json")}
writer = publish.write_json
def write(path, value):
if fail_at == 4 and path.name.endswith(".acceptance.json") and value.get("passed"):
raise ValueError("Injected publication failure")
writer(path, value)
monkeypatch.setattr(publish, "verify", check)
monkeypatch.setattr(publish, "write_json", write)
releases = tmp_path / "releases"
with pytest.raises(ValueError, match="Injected"):
publish.publish(run, releases, Path(sys.executable))
assert not (releases / publish.NAME).exists()
assert not (releases / f"{publish.NAME}.tar.gz").exists()
assert not list(releases.glob(".*.stage-*")) and not list(releases.glob(".*.publish.lock"))
report = json.loads((releases / f"{publish.NAME}.acceptance.json").read_text())
assert not report["passed"]
if fail_at > 1:
assert Path(report["quarantine"]).is_dir()
assert (Path(report["quarantine"]) / publish.NAME / "actor.pt").read_bytes() == b"fixture"
if fail_at == 4:
assert (Path(report["quarantine"]) / f"{publish.NAME}.tar.gz").is_file()
def test_version_race_cannot_overwrite_winner_report(tmp_path, monkeypatch):
import publish_standing as publish
releases = tmp_path / "releases"
original_open = publish.os.open
winner = b'{"passed":true,"owner":"other invocation"}\n'
def race_open(path, *args):
descriptor = original_open(path, *args)
(releases / publish.NAME).mkdir()
(releases / f"{publish.NAME}.acceptance.json").write_bytes(winner)
return descriptor
monkeypatch.setattr(publish.os, "open", race_open)
with pytest.raises(ValueError, match="Immutable"):
publish.publish(tmp_path / "unused", releases, Path(sys.executable))
assert (releases / f"{publish.NAME}.acceptance.json").read_bytes() == winner
assert (releases / publish.NAME).is_dir()
assert not list(releases.glob(".*.publish.lock"))
def test_trace_reducer_rejects_missing_and_forged_protocol():
cfg = json.loads(Path("configs/standing/go2_fl_support_v0.json").read_text())
i = inputs_for("full")
meta = {"inputs": i, "input_hash": canonical_hash(i)}
with pytest.raises(ValueError, match="trace"):
reduce_trace({}, meta, cfg)
data = {k: torch.zeros(7000, 13, width) for k, width in WIDTHS.items()}
meta["input_hash"] = "0" * 64
with pytest.raises(ValueError, match="Protocol"):
reduce_trace(data, meta, cfg)
data["base"][0, 0, 0] = torch.nan
with pytest.raises(ValueError, match="trace"):
reduce_trace(data, meta, cfg)
-161
View File
@@ -1,161 +0,0 @@
"""The explicit operator waiver can never become a general relaxed threshold."""
import copy
import json
import sys
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
from standing_deviation import apply_drift_waiver, load_waiver, sha256
@pytest.fixture
def case(tmp_path):
candidate = tmp_path / "candidate"
candidate.mkdir()
(candidate / "manifest.json").write_text("{}")
(candidate / "actor.pt").write_bytes(b"fixture")
(candidate / "binding.json").write_text(json.dumps({"checkpoint_sha256": "b" * 64}))
names = [
"stability/result.json",
"stability/metadata.json",
"stability/physics_trace.pt",
"stability/memory.json",
"stability_process.json",
"stability.log",
]
for name in names:
path = tmp_path / name
path.parent.mkdir(exist_ok=True)
path.write_text("recorded evidence")
rows = [{"max_foot_drift_m": 0.004} for _ in range(26)]
rows[6]["max_foot_drift_m"], rows[19]["max_foot_drift_m"] = 0.030620924223339147, 0.03078258298377699
waiver = {
"format": "skillfactory.standing-deviation.v1",
"authorization": "explicit_user_instruction",
"operator_statement": "Accept this recorded deviation only",
"approved": True,
"scope": "exact_candidate_and_trial_only",
"waived_gate": "stability.foot_drift",
"original_limit_m": 0.03,
"duration_s": 120.0,
"num_envs": 26,
"physical_samples": 60000,
"candidate_manifest_sha256": sha256(candidate / "manifest.json"),
"actor_sha256": sha256(candidate / "actor.pt"),
"checkpoint_sha256": "b" * 64,
"evidence_sha256": {p: sha256(tmp_path / p) for p in names},
"observed_failures": [{"environment": i, "max_foot_drift_m": rows[i]["max_foot_drift_m"]} for i in (6, 19)],
}
path = tmp_path / "waiver.json"
path.write_text(json.dumps(waiver))
gates = {"foot_drift": False, "height": True, "finite": True, "memory": True}
cfg = {"foot_drift_limit_m": 0.03}
meta = {"inputs": {"mode": "stability", "duration_s": 120.0, "count": 26}}
return tmp_path, candidate, path, waiver, gates, rows, cfg, meta
def test_explicit_exact_waiver_preserves_raw_failure(case):
root, candidate, path, original, gates, rows, cfg, meta = case
before = copy.deepcopy((gates, rows, cfg))
waiver = load_waiver(path, sha256(path), root, candidate)
receipt = apply_drift_waiver(waiver, gates, rows, cfg, meta)
assert receipt["accepted_by_operator_waiver"] and receipt["raw_gate_passed"] is False
assert (gates, rows, cfg) == before and gates["foot_drift"] is False
assert load_waiver(None, None, root, candidate) is None
with pytest.raises(ValueError, match="pinned"):
load_waiver(path, None, root, candidate)
with pytest.raises(ValueError, match="pinned"):
load_waiver(path, "0" * 64, root, candidate)
@pytest.mark.parametrize(
"key,value",
[
("approved", False),
("approved", 1),
("waived_gate", "stability.limits"),
("scope", "all_future_trials"),
("original_limit_m", 0.031),
("num_envs", 13),
("candidate_manifest_sha256", "0" * 64),
("actor_sha256", "0" * 64),
("checkpoint_sha256", "0" * 64),
],
)
def test_wrong_waiver_scope_or_binding_rejected_even_with_explicit_hash(case, key, value):
root, candidate, path, waiver, *_ = case
waiver[key] = value
path.write_text(json.dumps(waiver))
with pytest.raises(ValueError):
load_waiver(path, sha256(path), root, candidate)
def test_parsed_authorization_is_from_the_single_pinned_read(case, monkeypatch):
root, candidate, path, waiver, *_ = case
original = path.read_bytes()
pin = sha256(path)
replaced = {**waiver, "approved": False}
read_bytes = Path.read_bytes
def replace_after_read(file):
content = read_bytes(file)
if file == path:
path.write_text(json.dumps(replaced))
return content
monkeypatch.setattr(Path, "read_bytes", replace_after_read)
try:
consumed = load_waiver(path, pin, root, candidate)
finally:
path.write_bytes(original)
assert consumed == waiver and consumed["approved"] is True
assert read_bytes(path) == original
def test_replacement_and_restore_during_copy_cannot_package_unpinned_waiver(case, monkeypatch):
import publish_standing as publish
root, _, path, waiver, *_ = case
original = path.read_bytes()
pin = sha256(path)
destination = root / "staged_waiver.json"
copy_file = publish.shutil.copyfile
def substituted(source, target):
try:
path.write_text(json.dumps({**waiver, "approved": False}))
return copy_file(source, target)
finally:
path.write_bytes(original)
monkeypatch.setattr(publish.shutil, "copyfile", substituted)
with pytest.raises(ValueError, match="Staged waiver"):
publish.copy_pinned_waiver(path, destination, pin)
assert sha256(path) == pin and sha256(destination) != pin
def test_changed_physical_evidence_rejected(case):
root, candidate, path, *_ = case
(root / "stability/physics_trace.pt").write_bytes(b"changed")
with pytest.raises(ValueError, match="evidence changed"):
load_waiver(path, sha256(path), root, candidate)
@pytest.mark.parametrize("mutation", ["extra_gate", "larger_drift", "additional_environment", "threshold", "duration"])
def test_waiver_does_not_cover_any_extra_failure(case, mutation):
_, _, _, waiver, gates, rows, cfg, meta = case
if mutation == "extra_gate":
gates["memory"] = False
elif mutation == "larger_drift":
rows[19]["max_foot_drift_m"] = 0.0309
elif mutation == "additional_environment":
rows[0]["max_foot_drift_m"] = 0.0301
elif mutation == "threshold":
cfg["foot_drift_limit_m"] = 0.031
else:
meta["inputs"]["duration_s"] = 119.0
with pytest.raises(ValueError):
apply_drift_waiver(waiver, gates, rows, cfg, meta)
-117
View File
@@ -1,117 +0,0 @@
"""No-Kit geometry and read-only applied-force visualization regressions."""
import sys
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts"))
import standing_force_visualizer as viz
def rotated_z(q):
z = torch.zeros_like(q[:, :3])
z[:, 2] = 1
t = 2 * torch.cross(q[:, :3], z, dim=-1)
return z + q[:, 3:] * t + torch.cross(q[:, :3], t, dim=-1)
@pytest.mark.parametrize("dtype", [torch.float32, torch.float64])
def test_arrow_world_tail_tip_and_xyzw_all_directions(dtype):
force = torch.tensor(
[
[5, 0, 0],
[-5, 0, 0],
[0, 5, 0],
[0, -5, 0],
[0, 0, 10],
[0, 0, -10],
[2, -3, 4],
[0.001, -0.002, -10],
[1e-5, 0, 0],
],
dtype=dtype,
)
origin = torch.arange(len(force) * 3, dtype=dtype).reshape(-1, 3) / 10
before = origin.clone(), force.clone()
g = viz.arrow_geometry(origin, force, 0.03)
n = len(force)
direction = force / force.norm(dim=-1, keepdim=True)
assert g["translations"].shape == (2 * n, 3)
assert torch.allclose(rotated_z(g["orientations"][:n]), direction, atol=2e-7)
assert torch.allclose(g["orientations"].norm(dim=-1), torch.ones(2 * n, dtype=dtype))
assert torch.allclose(g["translations"][:n] - direction * g["scales"][:n, 2:] / 2, origin, atol=1e-6)
assert torch.allclose(g["translations"][n:] + direction * g["scales"][n:, 2:] / 2, origin + 0.03 * force, atol=1e-6)
assert g["marker_indices"].tolist() == [0] * n + [1] * n
assert torch.equal(origin, before[0]) and torch.equal(force, before[1])
def test_zero_force_and_zero_batch_have_no_visible_geometry():
for count in (0, 5):
g = viz.arrow_geometry(torch.zeros(count, 3), torch.zeros(count, 3))
assert g["translations"].shape == (0, 3)
assert g["orientations"].shape == (0, 4)
assert all(torch.isfinite(v).all() for v in g.values())
@pytest.mark.parametrize("scale", [0, -0.01, float("nan"), float("inf")])
def test_bad_scale_rejected_before_kit_import(scale):
with pytest.raises(ValueError, match="scale"):
viz.DisturbanceForceArrows(scale)
with pytest.raises(ValueError, match="scale"):
viz.arrow_geometry(torch.zeros(1, 3), torch.ones(1, 3), scale)
@pytest.mark.parametrize(
"force", [torch.ones(1, 6), torch.ones(2, 3), torch.full((1, 3), float("nan")), torch.ones(1, 3).long()]
)
def test_bad_force_rejected(force):
with pytest.raises(ValueError):
viz.arrow_geometry(torch.zeros(1, 3), force)
def test_applied_disturbance_only_and_visibility_lifecycle(monkeypatch):
class Markers:
def __init__(self):
self.visible = True
self.frames = []
def set_visibility(self, value):
self.visible = value
def visualize(self, **kwargs):
self.frames.append(kwargs)
markers = Markers()
monkeypatch.setattr(viz, "_make_markers", lambda: markers)
arrows = viz.DisturbanceForceArrows()
assert not markers.visible
position = torch.tensor([[12.0, -3.0, 0.4], [-8.0, 4.0, 0.5]])
# First environment is pure torque: must not be interpreted as a force.
wrench = torch.tensor([[0.0, 0.0, 0.0, 1.0, 2.0, 3.0], [0.0, 0.0, -10.0, 0.0, 0.0, 0.0]])
state = SimpleNamespace(
root=lambda: (position,),
last_disturbance=wrench,
last_guide=torch.ones(2, 6) * 500,
mount_wrench=lambda: (_ for _ in ()).throw(AssertionError("Not sensor data")),
)
before = position.clone(), wrench.clone(), state.last_guide.clone(), torch.get_rng_state().clone()
arrows.update(state)
assert markers.visible and len(markers.frames) == 1
g = markers.frames[0]
assert len(g["translations"]) == 2 # one shaft + one head, not two arrows
assert torch.allclose(
g["translations"][1] + rotated_z(g["orientations"])[1] * g["scales"][1, 2] / 2,
position[1] + torch.tensor([0.0, 0.0, -0.3]),
)
assert all(torch.equal(a, b) for a, b in zip(before, (position, wrench, state.last_guide, torch.get_rng_state())))
wrench.zero_()
arrows.update(state)
assert not markers.visible and len(markers.frames) == 1 # no stale arrow
wrench[0, 0] = 5
arrows.update(state)
assert markers.visible and len(markers.frames) == 2
arrows.close()
assert not markers.visible
-164
View File
@@ -1,164 +0,0 @@
"""Pure PPO/interface tests; these fixtures are not physical standing acceptance."""
import copy
import json
from pathlib import Path
import pytest
import torch
from SkillFactory.legs.standing_ppo import (
SHAPES,
StandingActorCritic,
bootstrap_values,
canonical_hash,
features,
load_training_config,
ppo_step,
restore_checkpoint,
save_checkpoint,
selection_height_error,
)
ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / "configs/training/go2_fl_loaded_stand_ppo_v1.json"
def observations(n=13):
result = {k: torch.zeros(n, *shape) for k, shape in SHAPES.items()}
result["joint_state"][:, :, 0] = torch.tensor([0.0, 0.8, -1.5])
result["goal"][:] = 0.3346
result["base_state"][:, 2] = 0.3346
result["base_state"][:, 6] = 1 # xyzw
result["mount_wrench"][:, 2] = -29.43
result["foot_state"][:, 8] = 52.86
return result
def test_features_include_six_axis_sensor_without_input_mutation():
obs = observations()
old = {k: v.clone() for k, v in obs.items()}
x = features(obs)
assert x.shape == (13, 45) and (x[:, 11] == 0).all()
assert torch.equal(x[:, 22:28], obs["mount_wrench"])
assert all(torch.equal(v, old[k]) for k, v in obs.items())
model = StandingActorCritic(hidden=32)
assert (model.scale > 0).all()
with torch.no_grad():
a, latent, logp, value = model.act(x)
assert a.shape == (13, 3) and a.abs().max() <= 1 and torch.equal(a, latent.tanh())
torch.testing.assert_close(model.evaluate(x, latent)[0], logp)
assert value.shape == (13,)
assert torch.equal(model.act(x, True)[0], model.act(x, True)[0])
@pytest.mark.parametrize("mutation", ["missing", "dtype", "shape", "nan", "empty"])
def test_feature_contract_rejects(mutation):
obs = observations(0 if mutation == "empty" else 2)
if mutation == "missing":
obs.pop("mount_wrench")
if mutation == "dtype":
obs["mount_wrench"] = obs["mount_wrench"].double()
if mutation == "shape":
obs["mount_wrench"] = obs["mount_wrench"][:, :3]
if mutation == "nan":
obs["mount_wrench"][0, 0] = torch.nan
with pytest.raises(ValueError):
features(obs)
def test_selection_is_independent_of_post_failure_autoreset_trajectory():
failed = torch.tensor([False, True, True])
a = selection_height_error(torch.tensor([0.01, 0.02, 1.0]), failed)
b = selection_height_error(torch.tensor([0.01, 9.0, 0.0]), failed)
assert torch.equal(a, b)
torch.testing.assert_close(a, torch.tensor([0.01, 0.1, 0.1]))
def test_timeout_bootstrap_uses_terminal_sensor_not_reset_and_termination_wins():
class ValueFromSensor:
def value(self, x):
return x[:, 22].clone()
reset = observations(3)
reset["mount_wrench"][:, 0] = torch.tensor([1.0, 2.0, 3.0])
terminal = observations(2)
terminal["mount_wrench"][:, 0] = torch.tensor([30.0, 99.0])
info = {"terminal_ids": torch.tensor([1, 2], dtype=torch.int32), "terminal_observation": terminal}
value = bootstrap_values(
ValueFromSensor(), features(reset), torch.tensor([False, False, True]), torch.tensor([False, True, True]), info
)
assert value.tolist() == [1.0, 30.0, 0.0]
with pytest.raises(RuntimeError, match="pre-reset"):
bootstrap_values(
ValueFromSensor(),
features(reset),
torch.zeros(3, dtype=torch.bool),
torch.ones(3, dtype=torch.bool),
{"terminal_ids": None},
)
def rollout(model):
x = torch.randn(4, 13, 45)
with torch.no_grad():
_, z, logp, value = model.act(x.flatten(0, 1))
return {
"features": x,
"latent": z.reshape(4, 13, 3),
"log_prob": logp.reshape(4, 13),
"value": value.reshape(4, 13),
"next_value": torch.zeros(4, 13),
"reward": torch.randn(4, 13),
"done": torch.zeros(4, 13, dtype=torch.bool),
}
def test_optimizer_and_rng_exact_restore_for_same_next_batch(tmp_path):
torch.set_num_threads(1)
torch.manual_seed(123)
cfg = load_training_config(CONFIG)
cfg.update(minibatch_size=26, epochs=2, target_kl=1.0)
model = StandingActorCritic(hidden=32)
optimizer = torch.optim.Adam(model.parameters(), lr=cfg["learning_rate"], eps=1e-5)
ppo_step(model, optimizer, rollout(model), cfg)
data = rollout(model)
identity = {"config": canonical_hash(cfg)}
path = tmp_path / "checkpoint.pt"
save_checkpoint(path, model, optimizer, identity, 1, 3.0, None)
before = copy.deepcopy(model.state_dict())
a = ppo_step(model, optimizer, data, cfg)
result_a, opt_a = copy.deepcopy(model.state_dict()), copy.deepcopy(optimizer.state_dict())
restored = restore_checkpoint(path, model, optimizer, identity)
assert restored["update"] == 1 and restored["accepted_skill"] is False
assert all(torch.equal(model.state_dict()[k], v) for k, v in before.items())
b = ppo_step(model, optimizer, data, cfg)
assert a == b and any(not torch.equal(v, before[k]) for k, v in result_a.items())
assert all(torch.equal(model.state_dict()[k], v) for k, v in result_a.items())
for key, values in opt_a["state"].items():
for name, value in values.items():
assert torch.equal(optimizer.state_dict()["state"][key][name], value)
with pytest.raises(ValueError, match="identity"):
restore_checkpoint(path, model, optimizer, {"config": "wrong"})
@pytest.mark.parametrize(
"key,value",
[
("seed", 82000),
("gamma", 2.0),
("epochs", 0),
("initial_std", 1.0),
("train_amplitude_scale", [0.0, 1.0]),
("train_time_shift_s", [-1.0, 0.0]),
("num_envs", 12),
("learning_rate", float("nan")),
("horizon", True),
],
)
def test_training_config_rejects_invalid(tmp_path, key, value):
cfg = load_training_config(CONFIG)
cfg[key] = value
path = tmp_path / "cfg.json"
path.write_text(json.dumps(cfg))
with pytest.raises(ValueError):
load_training_config(path)
-56
View File
@@ -1,56 +0,0 @@
"""Trainer CLI forwards visualization to workers without importing Kit."""
import importlib.util
import sys
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[1]
@pytest.fixture
def trainer(monkeypatch):
monkeypatch.syspath_prepend(str(ROOT / "scripts"))
spec = importlib.util.spec_from_file_location("train_leg_skill", ROOT / "scripts/train_leg_skill.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
@pytest.mark.parametrize("viz_args", [[], ["--viz", "kit"], ["--viz", "none"], ["--visualizer", "kit"]])
def test_worker_visualization_forwarding(trainer, tmp_path, viz_args):
bundles = [tmp_path / "go2_fl", tmp_path / "go1_fl"]
args = trainer.parse_args(
[
"--bundles",
*map(str, bundles),
"--num_envs",
"1",
"--horizon",
"32",
"--updates",
"1",
*viz_args,
]
)
for index, bundle in enumerate(args.bundles):
directory = tmp_path / "update_0000" / bundle.name
command = trainer.worker_command(args, bundle, tmp_path / "sampling_policy.pt", directory, args.seed + index)
assert command[0] == sys.executable
assert Path(command[1]).name == "leg_worker.py"
assert command[command.index("--bundle") + 1] == str(bundle.resolve())
assert command[command.index("--output") + 1] == str(directory.resolve())
assert command[command.index("--seed") + 1] == str(args.seed + index)
assert command[command.index("--device") + 1] == args.device
assert command[command.index("--mode") + 1] == "rollout"
if viz_args:
assert command[-2:] == ["--viz", viz_args[-1]]
else:
assert "--viz" not in command
def test_invalid_visualization_rejected(trainer):
with pytest.raises(SystemExit) as error:
trainer.parse_args(["--bundles", "asset", "--viz", "invalid"])
assert error.value.code == 2