Files
SkillFactory/tests/test_contact_cycle_performance_math_v042.py
chenlin c528dd268f feat: checkpoint Go2 FL simulation performance v0.4.2
Include callable skill and live-GUI prerequisites, epoch sensor reads, packed snapshots, sampled bit-exact kinematics, and verified-tick rendering without changing the physical/control schedule.

Record bounded analytic S1 GUI/headless qualification, original failures and CPU evidence (1557 passed, 6 skipped). Preserve accepted_skill=false and sub-real-time limitations. Exclude native authorities, caches, large media and local delivery copies; retain sealed artifact digest.
2026-10-16 15:46:01 +08:00

96 lines
4.6 KiB
Python

"""Pure-CPU read-scope and unchanged-formula batching tests. Not native proof."""
import importlib.util
from pathlib import Path
from types import SimpleNamespace as NS, MethodType
import pytest
import torch
from SkillFactory.legs.spec import load_bundle
from SkillFactory.legs.contact_cycle_sim.reference import ReferenceController
ROOT=Path(__file__).resolve().parents[1]
TASK=ROOT/'source/SkillFactory/SkillFactory/tasks/manager_based/contact_cycle_sim'
def module(name):
spec=importlib.util.spec_from_file_location('_math_perf_'+name,TASK/(name+'.py'));m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);return m
class State:
def __init__(self):
self.env=NS(runtime_hooks=NS(completed_steps=0,reset_calls=0,pose_write_calls=0))
self.command_clock=object();self.reference_clock=object();self.anchors=object();self.reads=0;self.value=torch.ones(1)
def root(self):self.reads+=1;return self.value
def test_scope_lifetime_restoration_no_global_tick_or_cross_invocation_cache():
m=module('readonly_scope_v042');s=State();original=dict(vars(s))
with m.readonly_scope(s):
assert s.root() is s.root();assert s.reads==1
assert 'root' not in vars(s)
s.value=torch.zeros(1)
with m.readonly_scope(s):assert s.root().item()==0 and s.reads==2
assert 'root' not in vars(s)
assert s.command_clock is original['command_clock']
def test_scope_restores_overrides_and_exceptions():
m=module('readonly_scope_v042');s=State();override=lambda:torch.ones(2);s.root=override
with pytest.raises(RuntimeError,match='injected'):
with m.readonly_scope(s):assert s.root().shape==(2,);raise RuntimeError('injected')
assert s.root is override
@pytest.mark.parametrize('change',['completed_steps','reset_calls','pose_write_calls','clock','anchors'])
def test_scope_rejects_any_physics_or_clock_boundary(change):
m=module('readonly_scope_v042');s=State()
with pytest.raises(RuntimeError,match='readonly_scope_changed'):
with m.readonly_scope(s):
s.root()
if change=='clock':s.command_clock=object()
elif change=='anchors':s.anchors=object()
else:setattr(s.env.runtime_hooks,change,1)
assert 'root' not in vars(s)
def test_scope_does_not_cache_mutating_history_or_policy_methods():
m=module('readonly_scope_v042')
assert not set(m.NAMES)&{'apply_loads','after_physics','reset','refresh','policy','objective','raw_sensors'}
@pytest.mark.parametrize('batch',[1,4])
def test_batched_jacobian_same_finite_difference_formula_cpu(batch):
m=module('batched_kinematics_v042');bundle=load_bundle(ROOT/'assets/generated/legs/go2_fl')
cfg=__import__('json').loads((ROOT/'configs/contact_cycle/simulation_residual_v1.json').read_text())['reference']
nominal=torch.tensor([j['q_default'] for j in bundle['spec']['joints']])
state=NS(bundle=bundle,nominal=nominal,env=NS(device='cpu',num_envs=1))
c=ReferenceController(state,cfg);q=nominal[None].repeat(batch,1)+torch.linspace(-.25,.25,batch*3).reshape(batch,3)
before={k:v.clone() for k,v in vars(c).items() if isinstance(v,torch.Tensor)}
old=ReferenceController.jacobian(c,q);new=m.jacobian(c,q)
torch.testing.assert_close(old,new,atol=5e-5,rtol=1e-5)
assert new.shape==old.shape and new.dtype==old.dtype and new.is_contiguous()
assert all(torch.equal(v,getattr(c,k)) for k,v in before.items())
assert c.cfg==cfg
def test_inexact_runtime_qualification_explicitly_retains_original():
m=module('batched_kinematics_v042');c=NS(jacobian=lambda q:'original');old=c.jacobian;env=NS(_cycle_state=NS(controller=c))
record={'applied':False,'reason':'not_exact_keep_original'}
assert m.install(env,record)==record and c.jacobian is old
def test_sampled_bitwise_gate_rejects_signed_zero_and_preserves_original(monkeypatch):
m=module('batched_kinematics_v042')
positive=torch.zeros(1,3,3,dtype=torch.float32);negative=-positive
assert torch.equal(positive,negative) # numeric equality is insufficient
assert not m.same_bits(positive,negative)
assert m.same_bits(positive,positive.clone())
class FakeController:
def __init__(self,*a):pass
def jacobian(self,q):return positive
monkeypatch.setattr(m,'ReferenceController',FakeController)
monkeypatch.setattr(m,'jacobian',lambda c,q:negative)
record=m.qualify({}, {'jacobian_epsilon_rad':.001}, torch.zeros(3),'cpu')
assert not record['all_bitwise_equal'] and not record['applied']
assert record['max_abs']==0 and record['reason']=='not_exact_keep_original'
c=NS(jacobian=lambda q:'original');old=c.jacobian
m.install(NS(_cycle_state=NS(controller=c)),record)
assert c.jacobian is old