wip: checkpoint paused Go2 FL four-skill development
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
"""CPU-only public command validation and exact supervisor-entry regression."""
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def load(name, path):
|
||||
spec = importlib.util.spec_from_file_location(name, ROOT / path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
api = load('four_api', 'source/SkillFactory/SkillFactory/legs/four_skills/api.py')
|
||||
cli = load('four_cli', 'scripts/four_skills.py')
|
||||
runtime = load('four_runtime', 'scripts/four_skills_runtime.py')
|
||||
|
||||
|
||||
def test_paused_stage_cannot_create_or_reuse_authority(tmp_path, monkeypatch):
|
||||
monkeypatch.setattr(cli, 'STAGE', tmp_path)
|
||||
(tmp_path / 'PAUSED.json').write_text('{"reason":"user"}')
|
||||
with pytest.raises(PermissionError, match='paused by user'):
|
||||
cli.scope()
|
||||
assert not (tmp_path / 'scope.json').exists()
|
||||
|
||||
|
||||
def test_exact_supervisor_command_relative_and_absolute():
|
||||
script = ROOT / 'scripts/four_skills.py'
|
||||
for name in (str(script), 'scripts/four_skills.py'):
|
||||
assert cli.supervisor_command_matches([b'/usr/bin/python3.12', name.encode(), b'smoke'], ROOT)
|
||||
assert not cli.supervisor_command_matches([b'python', b'/tmp/four_skills.py', b'smoke'], ROOT)
|
||||
assert not cli.supervisor_command_matches([b'python', str(script).encode(), b'--_worker-fd'], ROOT)
|
||||
assert not cli.supervisor_command_matches([b'python', b'scripts/four_skills.py', b'smoke'], '/tmp')
|
||||
assert not cli.supervisor_command_matches([b'python'], ROOT)
|
||||
|
||||
|
||||
class Sink:
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def request(self, *args):
|
||||
self.calls.append(args)
|
||||
return args
|
||||
|
||||
|
||||
@pytest.mark.parametrize('kwargs', [dict(skill='unknown'), dict(skill='support', direction_m=[.01, .02]),
|
||||
dict(skill='swing', direction_m=[0., 0.]), dict(skill='swing', direction_m=[.1, 0.]),
|
||||
dict(skill='swing', direction_m=[True, .02]), dict(skill='support', hold_seconds=True),
|
||||
dict(skill='support', hold_seconds=float('nan')), dict(skill='support', hold_seconds=11),
|
||||
dict(skill='support', external_force=[1, 2, 3]), dict(skill='support', desired_force=50)])
|
||||
def test_invalid_public_command_never_mutates_state(kwargs):
|
||||
state = Sink()
|
||||
service = api.SkillService(state)
|
||||
with pytest.raises((ValueError, TypeError)):
|
||||
service.call(**kwargs)
|
||||
assert state.calls == []
|
||||
|
||||
|
||||
def test_public_fields_only_and_legal_graph():
|
||||
s = Sink()
|
||||
api.SkillService(s).call('swing', hold_seconds=.3, direction_m=[.02, .01])
|
||||
assert s.calls == [('swing', .3, (.02, .01), None)]
|
||||
assert api.LEGAL == {'support': ('retract',), 'retract': ('swing', 'plant'),
|
||||
'swing': ('swing', 'plant'), 'plant': ('support',)}
|
||||
|
||||
|
||||
def test_training_composer_one_transition_per_row_per_feedback_sample():
|
||||
from types import SimpleNamespace
|
||||
import torch
|
||||
s = SimpleNamespace(episode_ids=[0, 0], skill=torch.tensor([0, 2]),
|
||||
ready=torch.ones(2, dtype=torch.bool), held=torch.ones(2), hold_required=torch.zeros(2),
|
||||
failed=torch.zeros(2, dtype=torch.bool), stopped=torch.zeros(2, dtype=torch.bool))
|
||||
calls = []
|
||||
class Service:
|
||||
def call(self, skill, *, env_ids, **kwargs):
|
||||
assert bool(s.ready[env_ids].all())
|
||||
calls.append((skill, env_ids.tolist()))
|
||||
s.skill[env_ids] = api.SKILLS.index(skill)
|
||||
s.ready[env_ids] = False
|
||||
env = SimpleNamespace(s=s, service=Service(), num_envs=2, device='cpu')
|
||||
driver = runtime.TrainingComposer(env)
|
||||
driver.update()
|
||||
assert calls == [('retract', [0]), ('plant', [1])]
|
||||
assert driver.transition_count == 2
|
||||
driver.update()
|
||||
assert len(calls) == 2
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Synthetic counterexamples for evidence checking, not physical success proof."""
|
||||
import copy
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
from SkillFactory.legs.four_skills.forces import ForceSchedule
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
spec = importlib.util.spec_from_file_location('four_auditor', ROOT / 'scripts/audit_four_skills.py')
|
||||
auditor = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(auditor)
|
||||
|
||||
|
||||
def js(path, value):
|
||||
path.write_text(json.dumps(value))
|
||||
|
||||
|
||||
def smooth(x):
|
||||
x = x.clamp(0, 1)
|
||||
return x.square() * (3 - 2*x)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def run(tmp_path):
|
||||
out = tmp_path / 'analytic'
|
||||
out.mkdir()
|
||||
sizes = [350, 1000, 950, 1850, 350]
|
||||
kinds = [0, 1, 2, 3, 0]
|
||||
count = sum(sizes)
|
||||
skill = torch.cat([torch.full((n,), k, dtype=torch.long) for k, n in zip(kinds, sizes)])
|
||||
age = torch.cat([torch.arange(1, n+1).float()*.002 for n in sizes])
|
||||
foot = torch.zeros(count, 1, 3)
|
||||
foot[..., 2] = .02
|
||||
fn = torch.ones(count, 1) * 50
|
||||
a, b, c, d = 350, 1350, 2300, 4150
|
||||
foot[a:b, 0, 2] += .05 * smooth((age[a:b]-1)/.6)
|
||||
fn[a:b, 0] *= 1-smooth(age[a:b])
|
||||
p = smooth(age[b:c]/1.4)
|
||||
foot[b:c, 0, :2] = p[:, None]*torch.tensor([.024, .010])
|
||||
foot[b:c, 0, 2] = .07
|
||||
fn[b:c] = 0
|
||||
foot[c:, 0, :2] = torch.tensor([.024, .010])
|
||||
foot[c:d, 0, 2] += .05*(1-smooth(age[c:d]/.8))
|
||||
fn[c:d, 0] *= smooth((age[c:d]-.8)/2.2)
|
||||
normal = torch.zeros(count, 1, 3)
|
||||
normal[..., 2] = fn
|
||||
zero = torch.zeros(count, 1)
|
||||
t = {'tick': torch.arange(1, count+1)[:, None],
|
||||
'time_s': (torch.arange(1, count+1).float()*.002)[:, None],
|
||||
'skill': skill[:, None], 'age_s': age[:, None], 'episode_id': torch.ones(count, 1, dtype=torch.long),
|
||||
'weight': torch.ones(count, 1)*50, 'failed': zero.bool(), 'root': torch.zeros(count, 1, 13),
|
||||
'joint_pos': torch.zeros(count, 1, 3), 'joint_vel': torch.zeros(count, 1, 3),
|
||||
'normal': normal, 'foot': foot, 'gap': foot[..., 2]-.02, 'target': foot.clone(),
|
||||
'reference': torch.zeros(count, 1, 3), 'q_ik': torch.zeros(count, 1, 3),
|
||||
'actor_observation': torch.zeros(count, 1, 48), 'external': torch.zeros(count, 1, 2, 6),
|
||||
'guide': torch.zeros(count, 1, 2, 6), 'auxiliary': torch.zeros(count, 1, 2, 6),
|
||||
'phase': torch.where(skill == 0, 0, torch.where(skill == 1, torch.where(age < 1., 1, 2),
|
||||
torch.where(skill == 2, 3, torch.where(age < .8, 4, 5))))[:, None],
|
||||
'limit_ratio': zero.clone(),
|
||||
'joint_excess': zero.clone(), 'height_error': zero.clone(), 'tilt': zero.clone()}
|
||||
initial = {k: v[0].clone() for k, v in t.items()}
|
||||
initial['time_s'].zero_()
|
||||
torch.save(t, out/'trace.pt')
|
||||
torch.save(initial, out/'initial-state.pt')
|
||||
approval = {'seed': 115011, 'sequence': 0, 'loops': 1, 'mode': 'evaluate', 'tier': 'none',
|
||||
'config_sha256': hashlib.sha256((ROOT/'configs/four_skills/v050.json').read_bytes()).hexdigest(),
|
||||
'controller': 'analytic', 'checkpoint': None, 'checkpoint_sha256': None}
|
||||
js(out/'approval.json', approval)
|
||||
counters = {'resets': 11, 'pose_writes': 14}
|
||||
js(out/'worker-result.json', {'actual_ticks': count, 'requested_loops': 1, 'completed_loops': 1,
|
||||
'functional_success': True, 'initialization_counters': counters, 'final_counters': counters,
|
||||
'physics_counts': {'initialization': 0, 'completed': count}})
|
||||
js(out/'supervisor-result.json', {'success': True, 'owned_cleanup': True, 'waited_exit': True})
|
||||
js(out/'runtime-identity.json', {'payload_body_index': 0, 'body_names': ['virtual_payload', 'foot']})
|
||||
js(out/'force-schedule.json', ForceSchedule(115011, [0], 'none', 'cpu', episode_ids=[1]).manifest())
|
||||
js(out/'transitions.json', [dict(zip(('from', 'to', 'at_tick'), (old, new, tick)),
|
||||
feedback_ready=True, feedback_hold_complete=True) for old, new, tick in
|
||||
[('support', 'retract', a), ('retract', 'swing', b), ('swing', 'plant', c), ('plant', 'support', d)]])
|
||||
assert auditor.audit(out)['passed']
|
||||
return out
|
||||
|
||||
|
||||
def change_trace(run, change):
|
||||
t = torch.load(run/'trace.pt', weights_only=True)
|
||||
change(t)
|
||||
torch.save(t, run/'trace.pt')
|
||||
return auditor.audit(run)
|
||||
|
||||
|
||||
def test_actual_tensor_skill_order_cannot_be_replaced_by_claimed_json(run):
|
||||
result = change_trace(run, lambda t: t['skill'].__setitem__(slice(350, 1350), 3))
|
||||
assert not result['passed'] and 'actual_skill_order_mismatch' in result['failure_reasons']
|
||||
|
||||
|
||||
@pytest.mark.parametrize('field', ['time_s', 'episode_id'])
|
||||
def test_timestamps_and_episode_identity_are_not_unchecked_labels(run, field):
|
||||
result = change_trace(run, lambda t: t[field].__setitem__((100, 0), t[field][100, 0]+1))
|
||||
assert not result['passed']
|
||||
|
||||
|
||||
def test_transition_tick_must_equal_actual_tensor_boundary(run):
|
||||
edges = json.loads((run/'transitions.json').read_text())
|
||||
edges[0]['at_tick'] += 1
|
||||
js(run/'transitions.json', edges)
|
||||
assert 'transition_tick_mismatch' in auditor.audit(run)['failure_reasons']
|
||||
|
||||
|
||||
def test_support_ratio_alone_cannot_hide_interrupted_continuous_hold(run):
|
||||
result = change_trace(run, lambda t: t['normal'].__setitem__((340, 0, 2), 0.))
|
||||
assert not result['passed']
|
||||
assert any('continuous_support' in reason for reason in result['failure_reasons'])
|
||||
|
||||
|
||||
def test_swing_progress_must_persist_through_hold_not_only_last_frame(run):
|
||||
result = change_trace(run, lambda t: t['foot'].__setitem__((slice(2100, 2299), 0, slice(0, 2)), 0.))
|
||||
assert any('continuous_signed_swing_hold' in reason for reason in result['failure_reasons'])
|
||||
|
||||
|
||||
def test_zero_requested_couple_is_verified_not_just_net_force(run):
|
||||
result = change_trace(run, lambda t: t['external'].__setitem__((20, 0, 0, 3), .1))
|
||||
assert 'sampled_force_not_actually_applied' in result['failure_reasons']
|
||||
|
||||
|
||||
def test_schedule_tier_must_equal_approval(run):
|
||||
js(run/'force-schedule.json', ForceSchedule(115011, [0], 'small', 'cpu', episode_ids=[1]).manifest())
|
||||
assert 'schedule_tier_not_approved' in auditor.audit(run)['failure_reasons']
|
||||
|
||||
|
||||
def test_same_initial_tensors_and_force_schedule_do_not_pair_different_tasks(run, tmp_path):
|
||||
import shutil
|
||||
other = tmp_path/'trained'
|
||||
shutil.copytree(run, other)
|
||||
a = json.loads((other/'approval.json').read_text())
|
||||
a.update(controller='trained', checkpoint='/example/weights.pt', checkpoint_sha256='a'*64, sequence=1)
|
||||
js(other/'approval.json', a)
|
||||
result = auditor.compare_pair(run, other)
|
||||
assert not result['paired'] and not result['approved_conditions_equal']['sequence']
|
||||
@@ -0,0 +1,208 @@
|
||||
"""CPU synthetic schedule tests, not simulator, hardware or task-success proof."""
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import random
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
|
||||
PATH = (Path(__file__).resolve().parents[1]
|
||||
/ "source/SkillFactory/SkillFactory/legs/four_skills/forces.py")
|
||||
SPEC = importlib.util.spec_from_file_location("four_skills_forces", PATH)
|
||||
MODULE = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(MODULE)
|
||||
ForceSchedule = MODULE.ForceSchedule
|
||||
|
||||
|
||||
def schedule(**kwargs):
|
||||
options = dict(seed=137, env_ids=[10, 20, 30], tier="full", device="cpu")
|
||||
options.update(kwargs)
|
||||
return ForceSchedule(**options)
|
||||
|
||||
|
||||
def test_paired_analytic_trained_schedules_are_identical_and_order_independent():
|
||||
analytic = schedule(episode_ids=[3, 4, 5])
|
||||
trained = schedule(episode_ids=[3, 4, 5])
|
||||
assert analytic.manifest() == trained.manifest()
|
||||
for t in torch.linspace(0, 300, 501, dtype=torch.float64):
|
||||
assert torch.equal(analytic.at(t.repeat(3)), trained.at(t.repeat(3)))
|
||||
reordered = schedule(env_ids=[30, 10, 20], episode_ids=[5, 3, 4])
|
||||
rows = analytic.manifest()["rows"]
|
||||
assert reordered.manifest()["rows"] == [rows[2], rows[0], rows[1]]
|
||||
alone = schedule(env_ids=[20], episode_ids=[4])
|
||||
assert alone.manifest()["rows"] == [rows[1]]
|
||||
assert schedule(seed=138).manifest()["rows"] != schedule().manifest()["rows"]
|
||||
|
||||
|
||||
def test_reset_order_subset_and_tiers_preserve_unselected_rows():
|
||||
first, second = schedule(), schedule()
|
||||
before = first.manifest()["rows"]
|
||||
first.reset([2, 0], [9, 7], tier="small")
|
||||
second.reset([0], [7], tier="small")
|
||||
second.reset([2], [9], tier="small")
|
||||
assert first.manifest() == second.manifest()
|
||||
assert first.manifest()["rows"][1] == before[1]
|
||||
expected = schedule(env_ids=[10, 30], episode_ids=[7, 9], tier="small")
|
||||
assert [first.manifest()["rows"][i] for i in [0, 2]] == expected.manifest()["rows"]
|
||||
first.reset([0], [8])
|
||||
assert first.manifest()["rows"][0]["tier"] == "small"
|
||||
first.reset([0], [7])
|
||||
assert first.manifest() == second.manifest()
|
||||
for t in [0.4, 8.5, 32.9, 99.4]:
|
||||
assert torch.equal(first.at(torch.full((3,), t)), second.at(torch.full((3,), t)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tier,maximum", [("none", 0), ("small", 1.5), ("medium", 4), ("full", 8)])
|
||||
def test_event_bounds_nonoverlap_and_force_bounds(tier, maximum):
|
||||
s = schedule(tier=tier)
|
||||
manifest = s.manifest()
|
||||
assert manifest["tier_maxima_N"] == dict(none=0, small=1.5, medium=4, full=8)
|
||||
assert manifest["frame"] == "world"
|
||||
assert manifest["application_point"] == "payload_com"
|
||||
assert manifest["requested_couple_Nm"] == [0, 0, 0]
|
||||
for row in manifest["rows"]:
|
||||
previous_end = -1
|
||||
for e in row["events"]:
|
||||
assert 0.2 - 1e-12 <= e["onset_s"] - e["slot_start_s"] <= 0.5 + 1e-12
|
||||
assert 0.5 <= e["duration_s"] <= 1.3
|
||||
assert 0.25 * maximum <= e["amplitude_N"] <= maximum
|
||||
assert math.isclose(sum(v*v for v in e["direction_world"]), 1, abs_tol=1e-14)
|
||||
assert previous_end < e["onset_s"]
|
||||
assert e["end_s"] < e["slot_start_s"] + 2
|
||||
previous_end = e["end_s"]
|
||||
for t in torch.linspace(0, 300, 1001):
|
||||
force = s.at(t.repeat(3))
|
||||
assert force.shape == (3, 3) and force.dtype == torch.float32
|
||||
assert force.device.type == "cpu"
|
||||
assert bool((force.norm(dim=1) <= maximum + 1e-6).all())
|
||||
|
||||
|
||||
def test_isotropic_directions_active_probability_and_uniform_sampling_sanity():
|
||||
# Fixed seed, broad statistical checks: implementation still defines the distribution.
|
||||
s = schedule(env_ids=list(range(40)))
|
||||
events = [e for r in s.manifest()["rows"] for e in r["events"]]
|
||||
directions = torch.tensor([e["direction_world"] for e in events], dtype=torch.float64)
|
||||
assert bool((directions.mean(0).abs() < 0.035).all())
|
||||
assert bool(((directions.square().mean(0) - 1/3).abs() < 0.025).all())
|
||||
assert 0.77 < sum(e["active"] for e in events) / len(events) < 0.83
|
||||
assert abs(sum(e["amplitude_N"] for e in events) / len(events) - 5) < 0.12
|
||||
|
||||
|
||||
def test_raised_cosine_values_ramp_bound_inactive_and_gaps():
|
||||
s = schedule(env_ids=[10])
|
||||
events = s.manifest()["rows"][0]["events"]
|
||||
active = next(e for e in events if e["active"])
|
||||
inactive = next(e for e in events if not e["active"])
|
||||
peak = torch.tensor(active["peak_force_world_N"], dtype=torch.float32)
|
||||
start, end = active["onset_s"], active["end_s"]
|
||||
for t, scale in [(start, 0), (start + .075, .5), (start + .15, 1),
|
||||
(end - .15, 1), (end - .075, .5), (end, 0)]:
|
||||
torch.testing.assert_close(s.at(torch.tensor([t], dtype=torch.float64))[0],
|
||||
scale * peak, atol=1e-6, rtol=1e-6)
|
||||
for t in [0, active["slot_start_s"], end + .05,
|
||||
inactive["onset_s"] + .2, 300]:
|
||||
assert torch.equal(s.at(torch.tensor([t], dtype=torch.float64)), torch.zeros(1, 3))
|
||||
# Sample both ramps at high resolution, measuring vector (not component) slope.
|
||||
times = torch.cat([torch.linspace(start - .01, start + .16, 1701, dtype=torch.float64),
|
||||
torch.linspace(end - .16, end + .01, 1701, dtype=torch.float64)])
|
||||
values = torch.stack([s.at(t.reshape(1))[0] for t in times])
|
||||
for segment in [slice(0, 1701), slice(1701, 3402)]:
|
||||
rates = values[segment].diff(dim=0).norm(dim=1) / times[segment].diff()
|
||||
assert rates.max() <= 100
|
||||
assert s.manifest()["maximum_force_derivative_N_per_s"] < 100
|
||||
|
||||
|
||||
def test_no_global_rng_mutation_on_construct_reset_or_query():
|
||||
python_state = random.getstate()
|
||||
torch_state = torch.random.get_rng_state().clone()
|
||||
s = schedule()
|
||||
s.reset([1, 0], [5, 9], tier="medium")
|
||||
s.at(torch.tensor([1., 2., 3.]))
|
||||
s.manifest()
|
||||
assert random.getstate() == python_state
|
||||
assert torch.equal(torch.random.get_rng_state(), torch_state)
|
||||
|
||||
|
||||
def test_manifest_is_complete_detached_and_reconstructs_force():
|
||||
s = schedule(duration_s=3.1)
|
||||
manifest = json.loads(json.dumps(s.manifest(), allow_nan=False))
|
||||
for i, row in enumerate(manifest["rows"]):
|
||||
assert len(row["events"]) == 2
|
||||
for event in row["events"]:
|
||||
assert event["truncated_by_horizon"] == (event["end_s"] > 3.1)
|
||||
assert event["onset_beyond_horizon"] == (event["onset_s"] > 3.1)
|
||||
t = min(3.1, event["onset_s"] + .1)
|
||||
edge = max(0, min(.15, t - event["onset_s"], event["end_s"] - t))
|
||||
scale = .5 * (1 - math.cos(math.pi * edge / .15))
|
||||
expected = torch.tensor(event["peak_force_world_N"]) * scale
|
||||
result = s.at(torch.full((3,), t, dtype=torch.float64))[i]
|
||||
torch.testing.assert_close(result, expected, atol=1e-6, rtol=1e-6)
|
||||
manifest["rows"][0]["events"][0]["amplitude_N"] = -1
|
||||
assert s.manifest()["rows"][0]["events"][0]["amplitude_N"] >= 2
|
||||
short = schedule(duration_s=.1)
|
||||
assert all(r["events"][0]["onset_beyond_horizon"] for r in short.manifest()["rows"])
|
||||
assert torch.equal(short.at(torch.full((3,), .1, dtype=torch.float64)), torch.zeros(3, 3))
|
||||
s.at(torch.full((3,), 3.1, dtype=torch.float64))
|
||||
with pytest.raises(ValueError, match="exceeds"):
|
||||
s.at(torch.full((3,), 3.10000001, dtype=torch.float64))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kwargs,error", [
|
||||
({"seed": True}, TypeError), ({"seed": 1.0}, TypeError),
|
||||
({"env_ids": [1, True]}, TypeError), ({"env_ids": [1., 2]}, TypeError),
|
||||
({"env_ids": [1, 1]}, ValueError), ({"env_ids": "12"}, TypeError),
|
||||
({"episode_ids": [1]}, ValueError), ({"episode_ids": [0, 0, False]}, TypeError),
|
||||
({"tier": "large"}, ValueError), ({"tier": []}, ValueError),
|
||||
({"duration_s": True}, ValueError), ({"duration_s": "300"}, ValueError),
|
||||
({"duration_s": 0}, ValueError), ({"duration_s": -1}, ValueError),
|
||||
({"duration_s": float("nan")}, ValueError), ({"duration_s": float("inf")}, ValueError),
|
||||
])
|
||||
def test_constructor_bad_inputs(kwargs, error):
|
||||
with pytest.raises(error):
|
||||
schedule(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("time,error", [
|
||||
([0, 0, 0], TypeError), (torch.zeros(3, 1), ValueError),
|
||||
(torch.zeros(2), ValueError), (torch.tensor([0, 0, -1]), ValueError),
|
||||
(torch.tensor([0., float("nan"), 0]), ValueError),
|
||||
(torch.tensor([0., float("inf"), 0]), ValueError),
|
||||
(torch.tensor([0, 301, 0]), ValueError), (torch.ones(3, dtype=torch.bool), TypeError),
|
||||
(torch.zeros(3, dtype=torch.complex64), TypeError),
|
||||
])
|
||||
def test_at_bad_inputs(time, error):
|
||||
with pytest.raises(error):
|
||||
schedule().at(time)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("ids,episodes,tier,error", [
|
||||
([0, 0], [1, 2], None, ValueError), ([3], [0], None, ValueError),
|
||||
([-1], [0], None, ValueError), ([True], [0], None, TypeError),
|
||||
([1.0], [0], None, TypeError), ([0], [True], None, TypeError),
|
||||
([0], [], None, ValueError), ([0], [0], "unknown", ValueError),
|
||||
([0, 9], [1, 2], "small", ValueError),
|
||||
])
|
||||
def test_reset_bad_inputs_do_not_mutate(ids, episodes, tier, error):
|
||||
s = schedule()
|
||||
before = s.manifest()
|
||||
with pytest.raises(error):
|
||||
s.reset(ids, episodes, tier)
|
||||
assert s.manifest() == before
|
||||
|
||||
|
||||
def test_empty_batch_empty_reset_and_integer_times():
|
||||
empty = schedule(env_ids=[])
|
||||
assert empty.at(torch.empty(0)).shape == (0, 3)
|
||||
empty.reset([], [])
|
||||
assert empty.manifest()["rows"] == []
|
||||
s = schedule()
|
||||
before = s.manifest()
|
||||
s.reset([], [], tier="none")
|
||||
assert s.manifest() == before
|
||||
assert s.at(torch.zeros(3, dtype=torch.int64)).shape == (3, 3)
|
||||
# No unspecified nonnegative constraint on integer identity keys.
|
||||
assert schedule(seed=-1, env_ids=[-10], episode_ids=[-3]).manifest()["seed"] == -1
|
||||
@@ -0,0 +1,314 @@
|
||||
"""Synthetic CPU-only four-skills seam tests: no Kit, robot data, or physical claims."""
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import types
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LEGS = ROOT / "source/SkillFactory/SkillFactory/legs"
|
||||
SPEC = importlib.util.spec_from_file_location("_four_skills_model_test", LEGS / "four_skills/model.py")
|
||||
model_module = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(model_module)
|
||||
FourSkillActorCritic = model_module.FourSkillActorCritic
|
||||
features = model_module.features
|
||||
save_checkpoint = model_module.save_checkpoint
|
||||
load_policy = model_module.load_policy
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def cpu_only():
|
||||
# Small synthetic matrices do not benefit from a large host thread pool.
|
||||
previous = torch.get_num_threads()
|
||||
torch.set_num_threads(1)
|
||||
yield
|
||||
torch.set_num_threads(previous)
|
||||
|
||||
|
||||
def test_four_skills_model_shapes_zero_baseline_and_shared_inputs():
|
||||
model = FourSkillActorCritic(hidden=16)
|
||||
x = torch.randn(7, 48)
|
||||
assert features(x) is x
|
||||
action, latent, logp, value = model.act(x, deterministic=True)
|
||||
assert action.shape == latent.shape == (7, 3)
|
||||
assert logp.shape == value.shape == (7,)
|
||||
assert not action.any() and not latent.any()
|
||||
assert torch.isfinite(logp).all() and torch.isfinite(value).all()
|
||||
assert torch.equal(value, model.value(x))
|
||||
assert model.actor[0].in_features == model.critic[0].in_features == 48
|
||||
assert model.feature_version == "four-skills-48-fixed-si-v1"
|
||||
assert model.model_config == {"hidden": 16, "initial_std": 0.08}
|
||||
assert model.critic[-1].weight.any()
|
||||
assert not torch.optim.Adam(model.parameters()).state
|
||||
|
||||
|
||||
def test_four_skills_model_fixed_si_order_and_actor_critic_normalization():
|
||||
model = FourSkillActorCritic(hidden=8)
|
||||
expected_offset = torch.zeros(48)
|
||||
expected_offset[:3] = torch.tensor([0.0, 0.8, -1.5])
|
||||
expected_scale = torch.tensor(
|
||||
[0.5] * 3 + [10.0] * 3 + [50.0] * 3 + [5.0] * 3
|
||||
+ [1.0] * 3 + [5.0] * 3 + [0.1] * 3 + [0.5] * 3
|
||||
+ [0.4] * 3 + [1.0] * 3 + [50.0] * 3 + [0.05]
|
||||
+ [1.0] * 4 + [0.4] * 3 + [1.0] + [1.0] * 3 + [1.0] * 3
|
||||
)
|
||||
assert torch.equal(model.offset, expected_offset)
|
||||
assert torch.equal(model.scale, expected_scale)
|
||||
seen = []
|
||||
handles = [net[0].register_forward_pre_hook(lambda _, args: seen.append(args[0]))
|
||||
for net in (model.actor, model.critic)]
|
||||
normalized = torch.linspace(-2, 2, 48).expand(2, -1)
|
||||
model.value(expected_offset + expected_scale * normalized)
|
||||
for handle in handles:
|
||||
handle.remove()
|
||||
assert len(seen) == 2
|
||||
assert torch.allclose(seen[0], normalized, atol=1e-6)
|
||||
assert torch.equal(seen[0], seen[1])
|
||||
|
||||
|
||||
def test_four_skills_model_latent_logp_tanh_and_std_bounds():
|
||||
model = FourSkillActorCritic(hidden=8)
|
||||
x = torch.randn(11, 48)
|
||||
action, latent, logp, value = model.act(x)
|
||||
assert latent.any() and action.abs().max() <= 1
|
||||
assert torch.equal(action, latent.tanh())
|
||||
evaluated_logp, evaluated_value = model.evaluate(x, latent)
|
||||
assert torch.equal(logp, evaluated_logp) and torch.equal(value, evaluated_value)
|
||||
expected = torch.distributions.Normal(torch.zeros_like(latent), 0.08).log_prob(latent).sum(-1)
|
||||
assert torch.allclose(logp, expected, atol=1e-6)
|
||||
for log_std, expected_std in [(-100.0, 0.02), (100.0, 0.5)]:
|
||||
with torch.no_grad():
|
||||
model.log_std.fill_(log_std)
|
||||
assert torch.allclose(model.distribution_value(x)[0].stddev, torch.full_like(latent, expected_std))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("kwargs", [
|
||||
{"hidden": True}, {"hidden": 8.0}, {"hidden": 7}, {"hidden": 0}, {"hidden": -1},
|
||||
{"initial_std": True}, {"initial_std": "0.08"}, {"initial_std": 0.0},
|
||||
{"initial_std": float("nan")}, {"initial_std": float("inf")},
|
||||
{"initial_std": 0.019}, {"initial_std": 0.501},
|
||||
])
|
||||
def test_four_skills_model_rejects_invalid_args(kwargs):
|
||||
with pytest.raises(ValueError):
|
||||
FourSkillActorCritic(**kwargs)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [
|
||||
torch.zeros(2, 46), torch.zeros(2, 32), torch.zeros(48), torch.zeros(0, 48),
|
||||
torch.zeros(2, 48, dtype=torch.float64), torch.zeros(2, 48, dtype=torch.int64),
|
||||
torch.full((2, 48), float("nan")), torch.full((2, 48), float("inf")), [[0.0] * 48],
|
||||
torch.empty(2, 48, device="meta"), torch.zeros(2, 48).to_sparse(),
|
||||
])
|
||||
def test_four_skills_model_rejects_bad_features(bad):
|
||||
model = FourSkillActorCritic(hidden=8)
|
||||
for method in (features, model.act, model.value):
|
||||
with pytest.raises(ValueError, match="features"):
|
||||
method(bad)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("bad", [torch.zeros(2, 4), torch.zeros(3, 3),
|
||||
torch.zeros(2, 3, dtype=torch.float64),
|
||||
torch.full((2, 3), float("nan")), None,
|
||||
torch.empty(2, 3, device="meta")])
|
||||
def test_four_skills_model_rejects_bad_latents(bad):
|
||||
with pytest.raises(ValueError, match="latent"):
|
||||
FourSkillActorCritic(hidden=8).evaluate(torch.zeros(2, 48), bad)
|
||||
|
||||
|
||||
def test_four_skills_model_exact_types_and_global_default_dtype():
|
||||
with pytest.raises(ValueError, match="bool"):
|
||||
FourSkillActorCritic(hidden=8).act(torch.zeros(2, 48), deterministic=1)
|
||||
default = FourSkillActorCritic()
|
||||
assert default.model_config == {"hidden": 128, "initial_std": 0.08}
|
||||
for std in (0.02, 0.5):
|
||||
assert FourSkillActorCritic(hidden=8, initial_std=std).model_config["initial_std"] == std
|
||||
previous = torch.get_default_dtype()
|
||||
try:
|
||||
torch.set_default_dtype(torch.float64)
|
||||
model = FourSkillActorCritic(hidden=8)
|
||||
assert all(p.dtype == torch.float32 for p in model.parameters())
|
||||
assert model.value(torch.zeros(2, 48, dtype=torch.float32)).dtype == torch.float32
|
||||
finally:
|
||||
torch.set_default_dtype(previous)
|
||||
|
||||
|
||||
def test_four_skills_model_generic_standing_ppo_step_synthetic():
|
||||
# Private test namespace avoids SkillFactory.__init__ (Kit registration), even
|
||||
# when this test is invoked directly rather than through scripts/test_cpu.py.
|
||||
name = "_four_skills_cpu_legs"
|
||||
package = types.ModuleType(name)
|
||||
package.__path__ = [str(LEGS)]
|
||||
sys.modules[name] = package
|
||||
try:
|
||||
spec = importlib.util.spec_from_file_location(name + ".standing_ppo", LEGS / "standing_ppo.py")
|
||||
standing = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(standing)
|
||||
torch.manual_seed(23)
|
||||
model = FourSkillActorCritic(hidden=8)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=3e-4)
|
||||
x = torch.randn(3, 4, 48)
|
||||
with torch.no_grad():
|
||||
_, latent, logp, value = model.act(x.flatten(0, 1))
|
||||
data = {"features": x, "latent": latent.reshape(3, 4, 3),
|
||||
"log_prob": logp.reshape(3, 4), "value": value.reshape(3, 4),
|
||||
"next_value": torch.zeros(3, 4), "reward": torch.randn(3, 4),
|
||||
"done": torch.zeros(3, 4, dtype=torch.bool)}
|
||||
cfg = {"gamma": 0.99, "gae_lambda": 0.95, "epochs": 2, "minibatch_size": 4,
|
||||
"target_kl": 1.0, "clip_ratio": 0.2, "value_coefficient": 0.5, "max_gradient_norm": 1.0}
|
||||
result = standing.ppo_step(model, optimizer, data, cfg)
|
||||
assert result["minibatches"] == 6 and result["sampling_log_prob_error"] == 0
|
||||
assert optimizer.state and model.actor[-1].weight.any()
|
||||
assert all(torch.isfinite(p).all() for p in model.parameters())
|
||||
finally:
|
||||
for module in list(sys.modules):
|
||||
if module == name or module.startswith(name + "."):
|
||||
del sys.modules[module]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def checkpoint(tmp_path):
|
||||
torch.manual_seed(7)
|
||||
model = FourSkillActorCritic(hidden=8)
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=3e-4)
|
||||
# Exercise nonempty Adam moments without robot data or a training run.
|
||||
x = torch.randn(4, 48)
|
||||
logp, value = model.evaluate(x, torch.randn(4, 3) * 0.08)
|
||||
(value.square().mean() - logp.mean()).backward()
|
||||
optimizer.step()
|
||||
path = tmp_path / "policy.pt"
|
||||
identity = {"task": "go2-fl-four-skills-v0.5.0", "source": "synthetic", "seed": 7}
|
||||
save_checkpoint(path, model, optimizer, identity, 1, {"loss": 0.25})
|
||||
return path, model, optimizer, identity, x
|
||||
|
||||
|
||||
def assert_tree_equal(left, right):
|
||||
assert type(left) is type(right)
|
||||
if isinstance(left, torch.Tensor):
|
||||
assert torch.equal(left, right)
|
||||
elif isinstance(left, dict):
|
||||
assert left.keys() == right.keys()
|
||||
for key in left:
|
||||
assert_tree_equal(left[key], right[key])
|
||||
elif isinstance(left, (list, tuple)):
|
||||
assert len(left) == len(right)
|
||||
for a, b in zip(left, right):
|
||||
assert_tree_equal(a, b)
|
||||
else:
|
||||
assert left == right
|
||||
|
||||
|
||||
def test_four_skills_model_checkpoint_exact_roundtrip(checkpoint):
|
||||
path, model, optimizer, identity, x = checkpoint
|
||||
rng = torch.get_rng_state().clone()
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
loaded, payload = load_policy(path, expected_sha256=digest, expected_identity=dict(reversed(list(identity.items()))))
|
||||
assert not loaded.training and next(loaded.parameters()).device.type == "cpu"
|
||||
assert torch.equal(rng, torch.get_rng_state()) # loading does not reseed callers
|
||||
assert payload["format"] == "skillfactory.four-skills-ppo.v1"
|
||||
assert payload["features"] == model.feature_version and payload["feature_dim"] == 48
|
||||
assert payload["update"] == 1 and payload["metrics"] == {"loss": 0.25}
|
||||
assert_tree_equal(dict(model.state_dict()), dict(loaded.state_dict()))
|
||||
assert_tree_equal(optimizer.state_dict(), payload["optimizer"])
|
||||
assert torch.equal(payload["rng"]["cpu"], rng)
|
||||
assert payload["rng"]["cuda"] == []
|
||||
for a, b in zip(model.act(x, deterministic=True), loaded.act(x, deterministic=True)):
|
||||
assert torch.equal(a, b)
|
||||
with pytest.raises(ValueError, match="identity"):
|
||||
load_policy(path, expected_identity={**identity, "source": "wrong"})
|
||||
with pytest.raises(ValueError, match="device"):
|
||||
load_policy(path, device="not-a-device")
|
||||
|
||||
|
||||
def test_four_skills_model_digest_checked_before_torch_load(checkpoint, monkeypatch):
|
||||
path, *_ = checkpoint
|
||||
calls = []
|
||||
monkeypatch.setattr(torch, "load", lambda *args, **kwargs: calls.append(args))
|
||||
with pytest.raises(ValueError, match="SHA256"):
|
||||
load_policy(path, expected_sha256="0" * 64)
|
||||
assert not calls
|
||||
|
||||
|
||||
@pytest.mark.parametrize("field,value", [
|
||||
("format", "skillfactory.standing-ppo-checkpoint.v1"),
|
||||
("features", "contact-cycle-sim-46-fixed-si-v1"), ("feature_dim", 46), ("feature_dim", 32),
|
||||
("feature_dim", 48.0), ("model_config", {"hidden": True, "initial_std": 0.08}),
|
||||
("model_config", {"hidden": 8, "initial_std": float("nan")}),
|
||||
("model_config", {"hidden": 8, "initial_std": 0.08, "extra": 1}),
|
||||
("update", True), ("update", -1), ("rng", {}), ("optimizer", {}), ("identity", {}),
|
||||
("rng", {"cpu": torch.zeros(2, dtype=torch.uint8), "cuda": []}),
|
||||
("identity", {"not_json": torch.zeros(1)}), ("metrics", {"loss": float("inf")}),
|
||||
])
|
||||
def test_four_skills_model_rejects_malformed_checkpoint(checkpoint, field, value):
|
||||
path, *_ = checkpoint
|
||||
payload = torch.load(path, weights_only=True)
|
||||
payload[field] = value
|
||||
torch.save(payload, path)
|
||||
with pytest.raises(ValueError):
|
||||
load_policy(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("corruption", ["nonfinite", "optimizer_nonfinite", "shape", "dtype", "scale", "missing", "extra"])
|
||||
def test_four_skills_model_rejects_corrupt_state(checkpoint, corruption):
|
||||
path, *_ = checkpoint
|
||||
payload = torch.load(path, weights_only=True)
|
||||
state = payload["model"]
|
||||
if corruption == "nonfinite":
|
||||
state["critic.0.weight"][0, 0] = float("inf")
|
||||
elif corruption == "optimizer_nonfinite":
|
||||
next(iter(payload["optimizer"]["state"].values()))["exp_avg"].flatten()[0] = float("nan")
|
||||
elif corruption == "shape":
|
||||
state["actor.0.weight"] = torch.zeros(8, 46)
|
||||
elif corruption == "dtype":
|
||||
state["log_std"] = state["log_std"].double()
|
||||
elif corruption == "scale":
|
||||
state["scale"][0] = 1.0
|
||||
elif corruption == "missing":
|
||||
del state["log_std"]
|
||||
else:
|
||||
state["extra"] = torch.zeros(1)
|
||||
torch.save(payload, path)
|
||||
with pytest.raises(ValueError):
|
||||
load_policy(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("corruption", ["parameter", "optimizer", "metrics", "custom"])
|
||||
def test_four_skills_model_atomic_nonfinite_and_custom_object_rejection(checkpoint, corruption):
|
||||
path, model, optimizer, identity, _ = checkpoint
|
||||
original = path.read_bytes()
|
||||
metrics = None
|
||||
if corruption == "parameter":
|
||||
with torch.no_grad():
|
||||
next(model.parameters()).flatten()[0] = float("nan")
|
||||
elif corruption == "optimizer":
|
||||
next(iter(optimizer.state.values()))["exp_avg"].flatten()[0] = float("inf")
|
||||
elif corruption == "metrics":
|
||||
metrics = {"loss": float("nan")}
|
||||
else:
|
||||
metrics = {"custom": object()}
|
||||
with pytest.raises(ValueError):
|
||||
save_checkpoint(path, model, optimizer, identity, 2, metrics)
|
||||
assert path.read_bytes() == original
|
||||
assert list(path.parent.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_four_skills_model_atomic_replace_failure_cleanup(checkpoint, monkeypatch):
|
||||
path, model, optimizer, identity, _ = checkpoint
|
||||
original = path.read_bytes()
|
||||
def fail_replace(*args):
|
||||
raise OSError("synthetic replace failure")
|
||||
monkeypatch.setattr(model_module.os, "replace", fail_replace)
|
||||
with pytest.raises(OSError, match="synthetic"):
|
||||
save_checkpoint(path, model, optimizer, identity, 2)
|
||||
assert path.read_bytes() == original
|
||||
assert list(path.parent.iterdir()) == [path]
|
||||
|
||||
|
||||
def test_four_skills_model_rejects_unreadable_checkpoint(tmp_path):
|
||||
path = tmp_path / "bad.pt"
|
||||
path.write_bytes(b"not a torch checkpoint")
|
||||
with pytest.raises(ValueError, match="weights-only"):
|
||||
load_policy(path)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Synthetic safety fault injection, never native physical acceptance."""
|
||||
import ast
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace as NS
|
||||
|
||||
import pytest
|
||||
import torch
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PATH = ROOT / 'source/SkillFactory/SkillFactory/tasks/manager_based/four_skills/mdp.py'
|
||||
tree = ast.parse(PATH.read_text())
|
||||
method = next(n for c in tree.body if isinstance(c, ast.ClassDef) and c.name == 'FourSkillState'
|
||||
for n in c.body if isinstance(n, ast.FunctionDef) and n.name == 'safety')
|
||||
from SkillFactory.legs.contact_cycle.task import phase_failures, phase_objective
|
||||
namespace = {'torch': torch, 'phase_failures': phase_failures}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[method], type_ignores=[])), str(PATH), 'exec'), namespace)
|
||||
|
||||
|
||||
def fake_state():
|
||||
torque = torch.zeros(1, 3)
|
||||
q = torch.zeros(1, 3)
|
||||
return NS(root=lambda: (torch.tensor([[0., 0., .3]]), torch.tensor([[0., 0., 0., 1.]]),
|
||||
torch.zeros(1, 3), torch.zeros(1, 3)),
|
||||
foot_center=lambda: torch.tensor([[0., 0., .02]]), bundle={'foot': {'radius': .02}},
|
||||
robot=NS(data=NS(applied_torque=NS(torch=torque), joint_vel=NS(torch=torch.zeros(1, 3)))),
|
||||
joints=[0, 1, 2], effort=torch.ones(3) * 20, speed=torch.ones(3) * 20,
|
||||
lower=torch.ones(3) * -2, upper=torch.ones(3) * 2, q=lambda: q,
|
||||
raw_sensors=lambda: torch.zeros(1, 18), contact=lambda: torch.tensor([[0., 0., 50.]]),
|
||||
guide=torch.zeros(1, 2, 6), auxiliary=torch.zeros(1, 2, 6), external=torch.zeros(1, 2, 6),
|
||||
base_origin=torch.tensor([[0., 0., .3]]), acquisition=NS(failed=torch.tensor([False])),
|
||||
separation=NS(premature=torch.tensor([False])), weight=torch.tensor([50.]),
|
||||
reference=lambda: (torch.tensor([0]), torch.tensor([0.]), None, None, None),
|
||||
controller=NS(q_ik=torch.zeros(1, 3), action=torch.zeros(1, 3)),
|
||||
residual_request=torch.zeros(1, 3), tilt=lambda: torch.zeros(1))
|
||||
|
||||
|
||||
@pytest.mark.parametrize('bad', [float('nan'), float('inf'), -float('inf')])
|
||||
def test_nonfinite_torque_fails_closed_not_nan_comparison_bypass(bad):
|
||||
s = fake_state()
|
||||
assert not any(bool(x.any()) for x in namespace['safety'](s).values())
|
||||
s.robot.data.applied_torque.torch[0, 1] = bad
|
||||
assert namespace['safety'](s)['nonfinite'].tolist() == [True]
|
||||
|
||||
|
||||
def test_original_actuator_collision_and_guide_limits_preserved():
|
||||
s = fake_state()
|
||||
s.robot.data.applied_torque.torch[0, 0] = 21
|
||||
assert namespace['safety'](s)['effort_velocity'].item()
|
||||
s = fake_state()
|
||||
s.guide[0, 0, 2] = .001
|
||||
assert namespace['safety'](s)['vertical_guide'].item()
|
||||
s = fake_state()
|
||||
s.foot_center = lambda: torch.tensor([[0., 0., .0179]])
|
||||
assert namespace['safety'](s)['penetration'].item()
|
||||
|
||||
|
||||
def test_brief_ready_cannot_disable_requested_hold_watchdog():
|
||||
method = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == 'hold_watchdog')
|
||||
ns = {'torch': torch}
|
||||
exec(compile(ast.fix_missing_locations(ast.Module(body=[method], type_ignores=[])), str(PATH), 'exec'), ns)
|
||||
completed = torch.tensor([False])
|
||||
deadline = torch.tensor([4.])
|
||||
required = torch.tensor([.4])
|
||||
expired = torch.tensor([False])
|
||||
# Even granting brief ready intervals directly, no0.4s hold can complete.
|
||||
for tick in range(1, 2501):
|
||||
ready = torch.tensor([tick % 100 < 26])
|
||||
held = torch.tensor([.002 * (tick % 100) if bool(ready[0]) else 0.])
|
||||
completed, now_expired = ns['hold_watchdog'](ready, held, required, completed,
|
||||
torch.tensor([tick * .002]), deadline)
|
||||
expired |= now_expired
|
||||
assert expired.item() and not completed.item()
|
||||
# A genuinely completed hold stays complete during indefinite endpoint hold;
|
||||
# the separate existing bad-hold rule still owns later physical failures.
|
||||
completed, expired = ns['hold_watchdog'](torch.tensor([True]), torch.tensor([.5]), required,
|
||||
torch.tensor([False]), torch.tensor([3.]), deadline)
|
||||
assert completed.item() and not expired.item()
|
||||
completed, expired = ns['hold_watchdog'](torch.tensor([False]), torch.tensor([0.]), required,
|
||||
completed, torch.tensor([100.]), deadline)
|
||||
assert completed.item() and not expired.item()
|
||||
|
||||
|
||||
def test_phase_reward_does_not_pay_for_early_lift_during_unload():
|
||||
def score(gap):
|
||||
return phase_objective(torch.tensor([1]), torch.tensor([.5]), torch.tensor([gap]),
|
||||
torch.tensor([gap]), torch.tensor([25.]), torch.tensor([25.]), torch.zeros(1),
|
||||
torch.zeros(1), torch.tensor([50.]))[0]
|
||||
assert score(0.).item() > score(.01).item()
|
||||
Reference in New Issue
Block a user