Files
SkillFactory/tests/test_contact_cycle_sim_residual.py
chenlin 9fe9d27865 feat: checkpoint contact-cycle evaluation and RootXY PPO progress
Consolidate next-stage docs, archive superseded narratives, and preserve frozen document inputs. Retain invalid P2 pairs, partial RootXY training, failed attempts and nonselectable checkpoints as explicit limitations.

Include supervised evaluation/training, desktop GPU admission, bounded evidence and atomic-publication monitor repairs with CPU regressions. Ignore local dotenv configuration.

Validation: 1403 passed, 6 skipped for contact-cycle and related contracts/CLI tests. Full-suite legacy ABI and registration tests require Python 3.12/Torch 2.10/pxr; no runtime checks relaxed. No new physical run or accepted skill.
2026-10-15 14:18:17 +08:00

95 lines
4.5 KiB
Python

"""Pure CPU simulation-residual protocol tests. No robot optimization."""
import json
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
from SkillFactory.legs.contact_cycle_sim.config import FEATURE_VERSION, combine, load_config, pose_cost
from SkillFactory.legs.contact_cycle_sim.model import SimResidualActorCritic, features
from SkillFactory.legs.contact_cycle_sim.reference import ReferenceController
from SkillFactory.legs.spec import load_bundle
from SkillFactory.legs.tokens import LegKinematics
ROOT = Path(__file__).resolve().parents[1]
CONFIG = ROOT / 'configs/contact_cycle/simulation_residual_v1.json'
def test_composition_bounds_zero_identity_and_saturation():
reference = torch.tensor([[.99, -.99, .2], [.2, -.1, .5]])
full, requested, delta = combine(reference, torch.zeros_like(reference), .05, .5)
assert torch.equal(full, reference) and not delta.any() and not requested.any()
full, requested, delta = combine(reference, torch.tensor([[100., -100., 100.], [-100., 100., -100.]]), .05, .5)
assert full.abs().max() <= 1 and requested.abs().max() <= 1
assert delta.abs().max() <= .050001
assert abs(float(delta[0, 0]) - .005) < 1e-7 # projection can shrink, never enlarge, the requested residual
@pytest.mark.parametrize('bad', [torch.zeros(2, 4), torch.zeros(2, 3, dtype=torch.float64),
torch.full((2, 3), float('nan'))])
def test_invalid_residual_rejected(bad):
with pytest.raises(ValueError):
combine(torch.zeros(2, 3), bad, .05, .5)
@pytest.mark.parametrize('reference', [torch.full((2, 3), float('nan')), torch.full((2, 3), 1.1)])
def test_corrupt_reference_rejected(reference):
with pytest.raises(ValueError):
combine(reference, torch.zeros_like(reference), .05, .5)
def test_dense_pose_cost_removes_support_height_blind_spot():
c = load_config(CONFIG)['reward']
error = torch.tensor([[0., 0., 0.], [0., 0., -.05], [0., 0., -.0996]])
cost, velocity = pose_cost(error, torch.zeros_like(error), c)
assert cost[0] == 0 and cost[2] > cost[1] > 0 and not velocity.any()
assert .9255 - c['position_weight'] * cost[2] < 0
assert pose_cost(torch.full((1, 3), 100.), torch.full((1, 3), 100.), c)[0].item() == c['cost_cap']
def test_sim_network_zero_mean_and_distinct_feature_contract():
model = SimResidualActorCritic(hidden=16)
x = torch.randn(4, 46)
with torch.no_grad():
action, latent, logp, value = model.act(x, deterministic=True)
assert not action.any() and not latent.any() and torch.isfinite(logp).all() and torch.isfinite(value).all()
assert model.feature_version == FEATURE_VERSION
with pytest.raises(ValueError):
features(torch.zeros(4, 32))
@pytest.mark.parametrize('field,value', [('residual_limit_rad', .2), ('residual_limit_rad', float('nan')),
('features', 'contact-cycle-32-fixed-si-v1')])
def test_config_rejects_old_identity_or_unbounded_residual(tmp_path, field, value):
c = json.loads(CONFIG.read_text())
c[field] = value
p = tmp_path / 'bad.json'
p.write_text(json.dumps(c))
with pytest.raises(ValueError):
load_config(p)
def test_reference_indexed_reset_and_refresh_are_isolated():
bundle = load_bundle(ROOT / 'assets/generated/legs/go2_fl')
nominal = torch.tensor([j['q_default'] for j in bundle['spec']['joints']])
env = SimpleNamespace(num_envs=3, device='cpu', cfg=SimpleNamespace(support_parameters={'action_scale_rad': .5}))
fk = LegKinematics(bundle, 'cpu')
transform = fk.forward(nominal.expand(3, -1))[bundle['foot']['body']]
target = transform[:, :3, 3] + (transform[:, :3, :3] @ torch.tensor(bundle['foot']['xyz'])[:, None]).squeeze(-1)
zero = torch.zeros(3, 3)
quat = torch.tensor([[0., 0., 0., 1.]]).expand(3, -1)
s = SimpleNamespace(bundle=bundle, env=env, nominal=nominal,
root=lambda: (zero, quat, zero, zero),
reference=lambda: (None, None, target, torch.full((3,), 50.), None))
ref = ReferenceController(s, load_config(CONFIG)['reference'])
ref.reset(torch.arange(3))
old = ref.q_ik.clone(), ref.action.clone(), ref.refreshes.clone()
target[1, 0] += .01
ref.refresh(torch.tensor([1]))
assert torch.equal(ref.q_ik[[0, 2]], old[0][[0, 2]])
assert torch.equal(ref.action[[0, 2]], old[1][[0, 2]])
assert ref.refreshes.tolist() == [1, 2, 1]
ref.reset(torch.tensor([1]))
assert ref.refreshes.tolist() == [1, 1, 1]
assert torch.isfinite(ref.action).all() and ref.action.abs().max() <= 1