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.
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
"""Go2 FL contact-cycle v1: simulator-independent contracts and test oracles."""
|
||||
|
||||
CONTRACT = "go2-fl-contact-cycle-v1"
|
||||
PHASES = ("support", "unload", "lift", "swing", "land", "reload")
|
||||
@@ -0,0 +1,141 @@
|
||||
"""Fail-closed configuration for the deliberately bounded v1 fixture domain."""
|
||||
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from . import CONTRACT
|
||||
|
||||
|
||||
def _keys(value, expected):
|
||||
if not isinstance(value, dict) or set(value) != set(expected.split()):
|
||||
raise ValueError(f"Expected exactly: {expected}")
|
||||
|
||||
|
||||
def _number(value, low, high):
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
|
||||
raise ValueError(f"Number outside [{low}, {high}]: {value}")
|
||||
|
||||
|
||||
def _vector(value, size, bound):
|
||||
if not isinstance(value, list) or len(value) != size:
|
||||
raise ValueError("Invalid vector size")
|
||||
for x in value:
|
||||
_number(x, -bound, bound)
|
||||
|
||||
|
||||
def _unique_pairs(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError(f"Duplicate key: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def load_config(path):
|
||||
cfg = json.loads(Path(path).read_text(), object_pairs_hook=_unique_pairs)
|
||||
validate_config(cfg)
|
||||
return cfg
|
||||
|
||||
|
||||
def require_scenario_coverage(c, count):
|
||||
if type(count) is not int or count < len(c["scenarios"]):
|
||||
raise ValueError("num_envs must cover every configured development scenario")
|
||||
|
||||
|
||||
def validate_config(c):
|
||||
_keys(c, "schema_version contract support_config phase_durations_s swing_displacement_m clearance_m "
|
||||
"support base_motion sensor actuator limits scenarios events contact_transition initialization")
|
||||
if type(c["schema_version"]) is not int or c["schema_version"] != 1 or c["contract"] != CONTRACT:
|
||||
raise ValueError("Unsupported cycle contract")
|
||||
if c["support_config"] != "configs/standing/go2_fl_support_v0.json":
|
||||
raise ValueError("v1 binds the existing Go2 FL 3kg asset; rebuild/revalidate to change it")
|
||||
_vector(c["phase_durations_s"], 6, 10)
|
||||
for x in c["phase_durations_s"]:
|
||||
_number(x, 0.2, 10)
|
||||
_vector(c["swing_displacement_m"], 3, 0.03)
|
||||
if c["swing_displacement_m"][2] != 0:
|
||||
raise ValueError("v1 lands on the same flat plane; uneven terrain is not implemented")
|
||||
_number(c["clearance_m"], 0.02, 0.06)
|
||||
transition = c["contact_transition"]
|
||||
_keys(transition, "separation_on_m separation_off_m dwell_s unload_tracking_scale_m")
|
||||
for key in ("separation_on_m", "separation_off_m", "unload_tracking_scale_m"):
|
||||
_number(transition[key], 1e-5, 0.01)
|
||||
if transition["separation_off_m"] >= transition["separation_on_m"]:
|
||||
raise ValueError("Separation requires ordered geometric hysteresis")
|
||||
_number(transition["dwell_s"], 0.002, 0.05)
|
||||
init = c["initialization"]
|
||||
_keys(init, "foot_clearance_m contact_deadline_s min_load_fraction dwell_s")
|
||||
_number(init["foot_clearance_m"], 0, 0) # cycle only: do not inherit standing's airborne reset
|
||||
_number(init["contact_deadline_s"], 0.01, min(0.2, c["phase_durations_s"][0]))
|
||||
_number(init["dwell_s"], 0.002, init["contact_deadline_s"])
|
||||
_number(init["min_load_fraction"], 0.5, 1.0)
|
||||
_keys(c["support"], "kp_N_m kd_Ns_m max_N")
|
||||
for key, hi in (("kp_N_m", 3000), ("kd_Ns_m", 200), ("max_N", 150)):
|
||||
_number(c["support"][key], 0, hi)
|
||||
_keys(c["base_motion"], "amplitude_m frequency_Hz")
|
||||
_vector(c["base_motion"]["amplitude_m"], 3, 0.01)
|
||||
_number(c["base_motion"]["frequency_Hz"], 0.05, 0.5)
|
||||
_keys(c["sensor"], "joint_noise_std_rad velocity_noise_std_rad_s wrench_noise_std delay_steps")
|
||||
for key, hi in (("joint_noise_std_rad", 0.005), ("velocity_noise_std_rad_s", 0.05), ("wrench_noise_std", 0.1)):
|
||||
_number(c["sensor"][key], 0, hi)
|
||||
_keys(c["actuator"], "gain bias_rad delay_steps")
|
||||
_number(c["actuator"]["gain"], 0.95, 1.05)
|
||||
_vector(c["actuator"]["bias_rad"], 3, 0.01)
|
||||
for group in ("actuator", "sensor"):
|
||||
n = c[group]["delay_steps"]
|
||||
if type(n) is not int or not 0 <= n <= 2:
|
||||
raise ValueError("delay_steps must be integer 0..2")
|
||||
_keys(c["limits"], "force_N couple_Nm point_radius_m force_rate_N_s couple_rate_Nm_s")
|
||||
for key, hi in (("force_N", 10), ("couple_Nm", 1), ("point_radius_m", 0.12),
|
||||
("force_rate_N_s", 100), ("couple_rate_Nm_s", 10)):
|
||||
_number(c["limits"][key], 1e-6, hi)
|
||||
if (not isinstance(c["scenarios"], list) or not c["scenarios"]
|
||||
or any(not isinstance(x, str) or not x for x in c["scenarios"])
|
||||
or len(set(c["scenarios"])) != len(c["scenarios"])):
|
||||
raise ValueError("Unique scenarios required")
|
||||
if c["scenarios"][0] != "baseline":
|
||||
raise ValueError("Scenario 0 must remain no-disturbance regression")
|
||||
if not isinstance(c["events"], list):
|
||||
raise ValueError("events must be a list")
|
||||
for e in c["events"]:
|
||||
_keys(e, "scenario body frame point_frame point_m force_N couple_Nm trigger phase start_s duration_s ramp_s")
|
||||
if type(e["scenario"]) is not int or not 1 <= e["scenario"] < len(c["scenarios"]):
|
||||
raise ValueError("Invalid event scenario (baseline cannot be disturbed)")
|
||||
if e["body"] not in ("virtual_payload", "FL_hip", "FL_thigh", "FL_calf", "FL_foot"):
|
||||
raise ValueError("Unsupported application body")
|
||||
if e["frame"] not in ("body", "mount", "world") or e["point_frame"] not in ("body", "mount", "world"):
|
||||
raise ValueError("Unknown frame")
|
||||
if e["trigger"] not in ("time", "phase", "liftoff", "touchdown"):
|
||||
raise ValueError("Unknown trigger")
|
||||
if type(e["phase"]) is not int or not 0 <= e["phase"] < 6:
|
||||
raise ValueError("Unknown phase")
|
||||
for key in ("start_s", "duration_s", "ramp_s"):
|
||||
_number(e[key], 0 if key == "start_s" else 0.01, 60)
|
||||
if e["duration_s"] < 2 * e["ramp_s"]:
|
||||
raise ValueError("Pulse must include both ramps")
|
||||
# Contact triggers may happen anywhere in their declared phase. Reserve room for the entire pulse.
|
||||
durations = c["phase_durations_s"]
|
||||
trigger_latest = (0 if e["trigger"] == "time" else
|
||||
sum(durations[:e["phase"] + (e["trigger"] in ("liftoff", "touchdown"))]))
|
||||
if trigger_latest + e["start_s"] + e["duration_s"] >= sum(durations):
|
||||
raise ValueError("Event cannot reliably finish before episode deadline")
|
||||
for field, limit, rate in (("force_N", "force_N", "force_rate_N_s"),
|
||||
("couple_Nm", "couple_Nm", "couple_rate_Nm_s"),
|
||||
("point_m", "point_radius_m", None)):
|
||||
_vector(e[field], 3, 1e3)
|
||||
norm = math.sqrt(sum(v * v for v in e[field]))
|
||||
# world points are env-origin-relative, so still bounded to the local fixture workspace.
|
||||
bound = 0.65 if field == "point_m" and e["point_frame"] == "world" else c["limits"][limit]
|
||||
if norm > bound + 1e-9 or (rate and norm / e["ramp_s"] > c["limits"][rate] + 1e-9):
|
||||
raise ValueError(f"Event amplitude/rate outside domain: {field}")
|
||||
# Conservative aggregate bound, even if pulses do not overlap. No implicit clipping.
|
||||
for scenario in range(1, len(c["scenarios"])):
|
||||
for field, rate in (("force_N", "force_rate_N_s"), ("couple_Nm", "couple_rate_Nm_s")):
|
||||
events = [e for e in c["events"] if e["scenario"] == scenario]
|
||||
if sum(math.sqrt(sum(x*x for x in e[field])) for e in events) > c["limits"][field] + 1e-9:
|
||||
raise ValueError("Combined event budget exceeded")
|
||||
if sum(math.sqrt(sum(x*x for x in e[field])) / e["ramp_s"] for e in events) > c["limits"][rate] + 1e-9:
|
||||
raise ValueError("Combined event rate budget exceeded")
|
||||
return c
|
||||
@@ -0,0 +1,146 @@
|
||||
"""Episode-local train/validation sampling. No independent-test generator is provided.
|
||||
|
||||
All ranges are engineering assumptions, not calibrated Go2 uncertainties.
|
||||
Directions/partitions are in each event's DECLARED command frame, not world space.
|
||||
Reset sampling is keyed by seed, environment index, episode counter and stage;
|
||||
reset order/batch grouping cannot change another environment's future samples.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
from .config import validate_config
|
||||
from .mechanics import canonical_ids
|
||||
|
||||
DIRECTION_EXCLUSIONS = ((0.35, 0.55), (-2.55, -2.35))
|
||||
POINT_RADIUS_MAX = 0.08
|
||||
EDGE_DELAY_MAX = 0.08
|
||||
SAMPLER_VERSION = "cycle-episode-sampler-v1"
|
||||
|
||||
|
||||
def curriculum_stage(update):
|
||||
if type(update) is not int or not 1 <= update <= 2048:
|
||||
raise ValueError("Curriculum update must be in [1, 2048]")
|
||||
return 0 if update <= 512 else 1 if update <= 1024 else 2
|
||||
|
||||
|
||||
def excluded_direction(v):
|
||||
azimuth = torch.atan2(v[..., 1], v[..., 0])
|
||||
return sum(((azimuth >= lo) & (azimuth <= hi)).int() for lo, hi in DIRECTION_EXCLUSIONS).bool()
|
||||
|
||||
|
||||
def direction(generator):
|
||||
# Conditional isotropic sphere sampling. Deliberately not uniform azimuth/elevation.
|
||||
for _ in range(1024):
|
||||
v = torch.randn(3, generator=generator)
|
||||
norm = v.norm()
|
||||
if norm > 1e-8 and not excluded_direction(v):
|
||||
return v / norm
|
||||
raise RuntimeError("Direction rejection sampling exhausted")
|
||||
|
||||
|
||||
class EpisodeSampler:
|
||||
def __init__(self, config, count, seed, split="train", update=1):
|
||||
validate_config(config)
|
||||
if split not in ("train", "validation"):
|
||||
raise ValueError("Independent testing is deliberately unavailable to the trainer")
|
||||
if type(count) is not int or count < 1 or type(seed) is not int or seed < 0:
|
||||
raise ValueError("Invalid batch/seed")
|
||||
if len(config["scenarios"]) != 4 or {e["scenario"] for e in config["events"]} != {1, 2, 3}:
|
||||
raise ValueError("Sampler v1 requires nominal plus three development scenario families")
|
||||
if any(e["point_frame"] == "world" for e in config["events"]):
|
||||
raise ValueError("Radius partition applies only to body/mount local points")
|
||||
self.config, self.count, self.seed, self.split = config, count, seed, split
|
||||
self.episodes = torch.zeros(count, dtype=torch.long)
|
||||
self.set_update(update)
|
||||
|
||||
def set_update(self, update):
|
||||
self.stage = curriculum_stage(update)
|
||||
|
||||
def state_dict(self):
|
||||
return {"version": SAMPLER_VERSION, "seed": self.seed, "split": self.split,
|
||||
"count": self.count, "stage": self.stage, "episodes": self.episodes.clone()}
|
||||
|
||||
def load_state_dict(self, data):
|
||||
for key in ("version", "seed", "split", "count"):
|
||||
if data[key] != self.state_dict()[key]:
|
||||
raise ValueError("Sampler identity mismatch")
|
||||
if (data["episodes"].shape != (self.count,) or data["episodes"].dtype != torch.long
|
||||
or (data["episodes"] < 0).any() or data["stage"] not in (0, 1, 2)):
|
||||
raise ValueError("Invalid sampler state")
|
||||
self.episodes.copy_(data["episodes"].cpu())
|
||||
self.stage = data["stage"]
|
||||
|
||||
def sample(self, ids):
|
||||
ids = canonical_ids(torch.as_tensor(ids, device="cpu"), self.count)
|
||||
events, limits = self.config["events"], self.config["limits"]
|
||||
n, k = len(ids), len(events)
|
||||
out = {"scenario": torch.zeros(n, dtype=torch.long), "stand": torch.zeros(n, dtype=torch.bool),
|
||||
"commands": torch.zeros(n, k, 6), "points": torch.zeros(n, k, 3),
|
||||
"delays": torch.zeros(n, k), "stage": torch.zeros(n, dtype=torch.long)}
|
||||
for row, env_id in enumerate(ids.tolist()):
|
||||
stage = self.stage if self.split == "train" else 2
|
||||
key = f"{SAMPLER_VERSION}:{self.seed}:{self.split}:{env_id}:{int(self.episodes[env_id])}:{stage}"
|
||||
seed = int.from_bytes(hashlib.sha256(key.encode()).digest()[:8], "little") % (2**63 - 1)
|
||||
generator = torch.Generator().manual_seed(seed)
|
||||
regression = bool(torch.rand((), generator=generator) < 0.25)
|
||||
if stage == 0:
|
||||
out["stand"][row] = regression
|
||||
elif regression:
|
||||
# Half of final-stage regression revisits the preceding disturbance stage.
|
||||
stage = 0 if stage == 1 or torch.rand((), generator=generator) < 0.5 else 1
|
||||
out["stage"][row] = stage
|
||||
scenario = 0 if stage == 0 else int(torch.randint(1, 4, (), generator=generator))
|
||||
out["scenario"][row] = scenario
|
||||
for j, event in enumerate(events):
|
||||
siblings = sum(e["scenario"] == event["scenario"] for e in events)
|
||||
# Conservative sums enforce both magnitude AND declared-frame rate budgets,
|
||||
# even if all same-scenario pulses overlap. Frame rotation rates are separate.
|
||||
caps = [min(limits["force_N"], limits["force_rate_N_s"] * event["ramp_s"]) / siblings,
|
||||
min(limits["couple_Nm"], limits["couple_rate_Nm_s"] * event["ramp_s"]) / siblings]
|
||||
for axis, cap in enumerate(caps):
|
||||
gain = 0.0 if stage == 0 or (stage == 1 and axis == 1) else 0.5 if stage == 1 else 1.0
|
||||
out["commands"][row, j, axis*3:(axis+1)*3] = (
|
||||
direction(generator) * cap * gain * torch.rand((), generator=generator))
|
||||
# Uniform volume within the allowed local ball; not held-out outer shell.
|
||||
radius = min(POINT_RADIUS_MAX, limits["point_radius_m"]) * float(
|
||||
torch.rand((), generator=generator)) ** (1/3)
|
||||
point = torch.randn(3, generator=generator)
|
||||
out["points"][row, j] = point / point.norm().clamp(min=1e-8) * radius
|
||||
out["delays"][row, j] = (EDGE_DELAY_MAX * torch.rand((), generator=generator)
|
||||
if event["trigger"] in ("liftoff", "touchdown") else event["start_s"])
|
||||
self.episodes[env_id] += 1
|
||||
return out
|
||||
|
||||
|
||||
def assert_sample_domain(config, batch):
|
||||
"""Independent batched domain audit; can run on recorded episode samples."""
|
||||
if not all(torch.isfinite(v).all() for v in batch.values()):
|
||||
raise ValueError("Nonfinite sampled command")
|
||||
commands, points = batch["commands"], batch["points"]
|
||||
if (points.norm(dim=-1) > POINT_RADIUS_MAX + 1e-6).any():
|
||||
raise ValueError("Reserved point shell entered")
|
||||
for axis in (0, 3):
|
||||
v = commands[..., axis:axis+3]
|
||||
if (excluded_direction(v) & (v.norm(dim=-1) > 1e-8)).any():
|
||||
raise ValueError("Reserved direction cone entered")
|
||||
for scenario in range(1, 4):
|
||||
indices = [j for j, e in enumerate(config["events"]) if e["scenario"] == scenario]
|
||||
ramps = torch.tensor([config["events"][j]["ramp_s"] for j in indices], device=commands.device)
|
||||
for axis, magnitude, rate in ((0, "force_N", "force_rate_N_s"), (3, "couple_Nm", "couple_rate_Nm_s")):
|
||||
norms = commands[:, indices, axis:axis+3].norm(dim=-1)
|
||||
if (norms.sum(-1) > config["limits"][magnitude] + 1e-5).any():
|
||||
raise ValueError("Aggregate magnitude budget exceeded")
|
||||
if ((norms/ramps).sum(-1) > config["limits"][rate] + 1e-4).any():
|
||||
raise ValueError("Aggregate rate budget exceeded")
|
||||
for j, e in enumerate(config["events"]):
|
||||
delay = batch["delays"][:, j]
|
||||
if e["trigger"] in ("liftoff", "touchdown"):
|
||||
if ((delay < 0) | (delay > EDGE_DELAY_MAX + 1e-6)).any():
|
||||
raise ValueError("Reserved edge-delay band entered")
|
||||
elif not torch.allclose(delay, torch.full_like(delay, e["start_s"]), atol=1e-6, rtol=0):
|
||||
raise ValueError("Unexpected time/phase start modification")
|
||||
if not math.isfinite(float(commands.norm())):
|
||||
raise ValueError("Invalid command norm")
|
||||
@@ -0,0 +1,198 @@
|
||||
"""SI, right-handed, xyzw quaternion mechanics; no Isaac imports.
|
||||
|
||||
External disturbances are NOT contact-force commands. A free couple is specified
|
||||
at the force application point; reduction to COM adds r x F exactly once.
|
||||
"""
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def canonical_ids(ids, count):
|
||||
"""Isaac emits int32; public reset and learner boundaries accept either integer width."""
|
||||
if (not isinstance(ids, torch.Tensor) or ids.ndim != 1 or ids.dtype not in (torch.int32, torch.int64)
|
||||
or (ids < 0).any() or (ids >= count).any() or ids.unique().numel() != len(ids)):
|
||||
raise ValueError("Require unique in-range int32/int64 reset indices")
|
||||
return ids.long()
|
||||
|
||||
|
||||
def rotate(q, v):
|
||||
"""Rotate vectors by unit xyzw q (caller owns pose validity)."""
|
||||
u = q[..., :3]
|
||||
t = 2 * torch.cross(u, v, dim=-1)
|
||||
return v + q[..., 3:] * t + torch.cross(u, t, dim=-1)
|
||||
|
||||
|
||||
def inverse_rotate(q, v):
|
||||
return rotate(torch.cat((-q[..., :3], q[..., 3:]), -1), v)
|
||||
|
||||
|
||||
def reduce_to_com(force, couple, frame_quat, point_world, com_world):
|
||||
f = rotate(frame_quat, force)
|
||||
return torch.cat((f, rotate(frame_quat, couple) + torch.cross(point_world - com_world, f, dim=-1)), -1)
|
||||
|
||||
|
||||
def cone_violation(force, normal, mu):
|
||||
"""Return unilateral and Coulomb residuals; never project measured physics."""
|
||||
fn = (force * normal).sum(-1)
|
||||
ft = (force - fn[..., None] * normal).norm(dim=-1)
|
||||
return (-fn).clamp(min=0), (ft - mu * fn.clamp(min=0)).clamp(min=0)
|
||||
|
||||
|
||||
def uniform_directions(count, generator, device="cpu"):
|
||||
"""Continuous isotropic directions, not uniform Euler angles or axis labels."""
|
||||
x = torch.randn(count, 3, generator=generator, device=device)
|
||||
return x / x.norm(dim=-1, keepdim=True).clamp(min=1e-12)
|
||||
|
||||
|
||||
def delivered_events(events, scenario, fired, completed, integral, tolerance_s=0.002):
|
||||
"""Per-env delivery gate: scheduling bits alone cannot certify a disturbance."""
|
||||
expected = scenario[:, None] == scenario.new_tensor([e["scenario"] for e in events])
|
||||
area = integral.new_tensor([e["duration_s"] - e["ramp_s"] for e in events])
|
||||
return ((fired == expected).all(-1) & (completed == expected).all(-1)
|
||||
& ((integral - expected * area).abs() <= tolerance_s).all(-1))
|
||||
|
||||
|
||||
class ContactLatch:
|
||||
"""Force hysteresis + dwell. Read once per physics step, not per observation."""
|
||||
|
||||
def __init__(self, count, device, on=2.0, off=0.5, dwell=0.01):
|
||||
self.on, self.off, self.dwell = on, off, dwell
|
||||
self.contact = torch.zeros(count, device=device, dtype=torch.bool)
|
||||
self.timer = torch.zeros(count, device=device)
|
||||
|
||||
def reset(self, ids):
|
||||
self.contact[ids] = False
|
||||
self.timer[ids] = 0
|
||||
|
||||
def update(self, normal_force, dt):
|
||||
candidate = torch.where(self.contact, normal_force > self.off, normal_force >= self.on)
|
||||
changed = candidate != self.contact
|
||||
self.timer = torch.where(changed, self.timer + dt, torch.zeros_like(self.timer))
|
||||
commit = changed & (self.timer >= self.dwell - 1e-7)
|
||||
touchdown = commit & candidate
|
||||
liftoff = commit & ~candidate
|
||||
self.contact = torch.where(commit, candidate, self.contact)
|
||||
self.timer[commit] = 0
|
||||
return liftoff, touchdown
|
||||
|
||||
|
||||
class ContactAcquisition:
|
||||
"""Bounded load acquisition INSIDE support time; never restarts/pauses the phase clock.
|
||||
|
||||
Failure is latched at the deadline and cannot be repaired by a later landing.
|
||||
Separate from contact loss: a never-contacted foot must not escape termination.
|
||||
"""
|
||||
|
||||
def __init__(self, count, device, deadline, dwell, min_load_fraction, max_gap):
|
||||
self.deadline, self.dwell = deadline, dwell
|
||||
self.min_load_fraction, self.max_gap = min_load_fraction, max_gap
|
||||
self.acquired = torch.zeros(count, device=device, dtype=torch.bool)
|
||||
self.failed = torch.zeros_like(self.acquired)
|
||||
self.timer = torch.zeros(count, device=device)
|
||||
|
||||
def reset(self, ids):
|
||||
self.acquired[ids] = self.failed[ids] = False
|
||||
self.timer[ids] = 0
|
||||
|
||||
def update(self, time, gap, normal_force, weight, dt):
|
||||
valid = (gap <= self.max_gap) & (normal_force >= self.min_load_fraction * weight)
|
||||
pending = ~self.acquired & ~self.failed
|
||||
self.timer = torch.where(pending & valid, self.timer + dt, torch.zeros_like(self.timer))
|
||||
# Accept a completed dwell at the deadline, but never after it.
|
||||
self.acquired |= pending & (self.timer >= self.dwell - 1e-7) & (time <= self.deadline + 1e-7)
|
||||
self.failed |= ~self.acquired & (time >= self.deadline - 1e-7)
|
||||
|
||||
|
||||
class SeparationLatch:
|
||||
"""Geometric liftoff is NOT a loss of normal load at an unloaded, touching foot.
|
||||
|
||||
Ground contact arms liftoff; gap hysteresis/dwell confirms physical separation.
|
||||
Remember onset phase so dwelling across unload->lift cannot launder early lift.
|
||||
Premature separation is sticky until indexed reset, including sub-control blips.
|
||||
"""
|
||||
|
||||
def __init__(self, count, device, on, off, dwell):
|
||||
self.on, self.off, self.dwell = on, off, dwell
|
||||
self.separated = torch.zeros(count, device=device, dtype=torch.bool)
|
||||
self.armed = torch.zeros_like(self.separated)
|
||||
self.premature = torch.zeros_like(self.separated)
|
||||
self.timer = torch.zeros(count, device=device)
|
||||
self.onset_phase = torch.full((count,), -1, device=device, dtype=torch.long)
|
||||
self.edge_phase = torch.full_like(self.onset_phase, -1)
|
||||
|
||||
def reset(self, ids):
|
||||
self.separated[ids] = self.armed[ids] = self.premature[ids] = False
|
||||
self.timer[ids] = 0
|
||||
self.onset_phase[ids] = self.edge_phase[ids] = -1
|
||||
|
||||
def update(self, gap, loaded_contact, phase, dt):
|
||||
self.armed |= loaded_contact & (gap <= self.off)
|
||||
candidate = torch.where(self.separated, gap > self.off, gap >= self.on)
|
||||
changed = candidate != self.separated
|
||||
begin = changed & (self.timer == 0)
|
||||
self.onset_phase = torch.where(begin, phase, self.onset_phase)
|
||||
self.timer = torch.where(changed, self.timer + dt, torch.zeros_like(self.timer))
|
||||
commit = changed & (self.timer >= self.dwell - 1e-7)
|
||||
rising = commit & candidate
|
||||
liftoff = rising & self.armed
|
||||
self.edge_phase = torch.where(liftoff, self.onset_phase, -1)
|
||||
# "Departure" requires a preceding ground contact. Never-contacted flight is
|
||||
# independently bounded by ContactAcquisition, not silently permitted forever.
|
||||
self.premature |= liftoff & (self.onset_phase < 2)
|
||||
self.separated = torch.where(commit, candidate, self.separated)
|
||||
self.timer[commit] = 0
|
||||
return liftoff
|
||||
|
||||
|
||||
class WrenchSchedule:
|
||||
"""One-shot per episode triggers, finite ramped pulses, selective reset.
|
||||
|
||||
start_s is time after reset for time triggers, otherwise delay after first
|
||||
phase entry/contact edge. A missed trigger does not silently become a pulse.
|
||||
duration includes ramp-in AND ramp-out; ending is exactly zero.
|
||||
"""
|
||||
|
||||
def __init__(self, events, count, device):
|
||||
self.events = events
|
||||
self.fired = torch.zeros(count, len(events), dtype=torch.bool, device=device)
|
||||
self.start = torch.zeros(count, len(events), device=device)
|
||||
self.envelope = torch.zeros_like(self.start)
|
||||
self.integral = torch.zeros_like(self.start)
|
||||
self.completed = torch.zeros_like(self.fired)
|
||||
# Optional episode-local training values; None preserves the frozen preflight semantics.
|
||||
self.commands = None
|
||||
self.delays = None
|
||||
|
||||
def reset(self, ids):
|
||||
self.fired[ids] = False
|
||||
self.start[ids] = 0
|
||||
self.envelope[ids] = self.integral[ids] = 0
|
||||
self.completed[ids] = False
|
||||
|
||||
def step(self, time, phase, liftoff, touchdown, scenario, dt=0.0, liftoff_phase=None):
|
||||
values = time.new_zeros(len(time), len(self.events), 6)
|
||||
for j, event in enumerate(self.events):
|
||||
trigger = event["trigger"]
|
||||
delay = (torch.full_like(time, event["start_s"]) if self.delays is None else self.delays[:, j])
|
||||
condition = {
|
||||
"time": time >= delay,
|
||||
"phase": phase == event["phase"],
|
||||
"liftoff": liftoff & (phase == event["phase"]) & (
|
||||
(phase if liftoff_phase is None else liftoff_phase) == event["phase"]),
|
||||
"touchdown": touchdown & (phase == event["phase"]),
|
||||
}[trigger]
|
||||
fire = condition & ~self.fired[:, j] & (scenario == event["scenario"])
|
||||
self.start[fire, j] = (
|
||||
delay[fire] if trigger == "time" else time[fire] + delay[fire]
|
||||
)
|
||||
self.fired[:, j] |= fire
|
||||
age = time - self.start[:, j]
|
||||
envelope = torch.minimum(age / event["ramp_s"], (event["duration_s"] - age) / event["ramp_s"]).clamp(0, 1)
|
||||
envelope *= self.fired[:, j]
|
||||
self.envelope[:, j] = envelope
|
||||
self.integral[:, j] += envelope * dt
|
||||
self.completed[:, j] |= self.fired[:, j] & (age >= event["duration_s"])
|
||||
vector = (time.new_tensor(event["force_N"] + event["couple_Nm"])
|
||||
if self.commands is None else self.commands[:, j])
|
||||
values[:, j] = envelope[:, None] * vector
|
||||
return values
|
||||
@@ -0,0 +1,112 @@
|
||||
"""CPU-recomputable phase/episode metrics. Missing phases fail closed."""
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
from .mechanics import cone_violation
|
||||
|
||||
|
||||
def summarize(trace, dt, thresholds, scenario_names):
|
||||
"""All inputs [physics_steps, env, ...]; preserve failed samples, never reset."""
|
||||
t = trace
|
||||
rows = []
|
||||
for env in range(t["phase"].shape[1]):
|
||||
phase, progress = t["phase"][:, env].long(), t["progress"][:, env]
|
||||
stance = ((phase == 0) & (t["time"][:, env] >= 2)) | ((phase == 5) & (progress >= 0.8))
|
||||
swing, land = phase == 3, phase == 4
|
||||
fn = t["normal"][:, env, 2]
|
||||
weight = float(t["weight"][0, env])
|
||||
error = (t["foot"][:, env] - t["target"][:, env]).norm(dim=-1)
|
||||
joint_excess = t["joint_excess"][:, env]
|
||||
normal = torch.zeros_like(t["normal"][:, env])
|
||||
normal[:, 2] = 1
|
||||
unilateral, friction = cone_violation(t["normal"][:, env] + t["friction"][:, env], normal,
|
||||
thresholds["friction_cone_mu_upper"])
|
||||
complete = (all((phase == i).any().item() for i in range(6))
|
||||
and bool(stance.any() and swing.any() and land.any()))
|
||||
finite = all(torch.isfinite(v[:, env]).all().item() for v in t.values())
|
||||
# Missing coverage is represented by null + failed gate, not NaN or an invented zero.
|
||||
row = {"env": env, "scenario": scenario_names[int(t["scenario"][0, env])],
|
||||
"complete": complete, "finite": finite}
|
||||
if not complete or not finite:
|
||||
row.update(success=False, failure_reasons=["missing_phase_or_nonfinite"])
|
||||
rows.append(row)
|
||||
continue
|
||||
contact = fn > 0.5 * weight
|
||||
reload = phase == 5
|
||||
landed = torch.nonzero((phase >= 4) & (fn > 2)).flatten()
|
||||
recovery = None
|
||||
if len(landed):
|
||||
start = int(landed[0])
|
||||
stable = contact & (t["height_error"][:, env] < 0.02) & (t["slip_speed"][:, env] < 0.03) & reload
|
||||
dwell = 0
|
||||
for k in range(start, len(stable)):
|
||||
dwell = dwell + 1 if stable[k] else 0
|
||||
if dwell * dt >= 0.2 - 1e-7:
|
||||
recovery = (k - start + 1) * dt
|
||||
break
|
||||
row.update(
|
||||
stance_contact_fraction=float(contact[stance].float().mean()),
|
||||
stance_load_mae_weight_fraction=float((fn[stance]-t["desired_force"][:, env][stance]).abs().mean()/weight),
|
||||
height_error_m_max=float(t["height_error"][:, env][t["time"][:, env] >= 2].max()),
|
||||
swing_rms_m=float(error[swing].square().mean().sqrt()),
|
||||
swing_clearance_m_min=float(t["gap"][:, env][swing].min()),
|
||||
swing_contact_fraction=float((fn[swing] > 2).float().mean()),
|
||||
stance_slip_m=float((t["slip_speed"][:, env] * (stance & (fn > 2))).sum() * dt),
|
||||
landing_peak_N=float(fn[land | reload].max()),
|
||||
landing_impulse_Ns=float(fn[land].sum() * dt),
|
||||
recovery_s=recovery,
|
||||
joint_limit_excess_rad_max=float(joint_excess.max()),
|
||||
joint_limit_violation_steps=int((joint_excess > thresholds["joint_limit_excess_rad_max"]).sum()),
|
||||
would_terminate_steps=int(t["would_fail"][:, env].sum()),
|
||||
max_tilt_rad=float(t["tilt"][:, env].max()),
|
||||
normalized_effort_velocity_max=float(t["limit_ratio"][:, env].max()),
|
||||
unilateral_residual_N_max=float(unilateral.max()),
|
||||
friction_residual_N_max=float(friction.max()),
|
||||
auxiliary_peak_N=float(t["auxiliary"][:, env, :, :3].norm(dim=-1).sum(-1).max()),
|
||||
auxiliary_vertical_impulse_Ns=float(t["auxiliary"][:, env, :, 2].sum() * dt),
|
||||
guide_force_peak_N=float(t["guide"][:, env, :, :3].norm(dim=-1).sum(-1).max()),
|
||||
external_force_peak_N=float(t["external"][:, env, :, :3].norm(dim=-1).sum(-1).max()),
|
||||
external_couple_com_peak_Nm=float(t["external"][:, env, :, 3:].norm(dim=-1).sum(-1).max()),
|
||||
)
|
||||
row["phase_metrics"] = {
|
||||
str(i): {"samples": int((phase == i).sum()),
|
||||
"tracking_rms_m": float(error[phase == i].square().mean().sqrt()),
|
||||
"normal_force_mean_N": float(fn[phase == i].mean()),
|
||||
"normal_force_peak_N": float(fn[phase == i].max()),
|
||||
"gap_min_m": float(t["gap"][:, env][phase == i].min())}
|
||||
for i in range(6)
|
||||
}
|
||||
lift_deadline = (phase == 2) & (progress > 0.9)
|
||||
checks = {
|
||||
"task_termination": row["would_terminate_steps"] == 0,
|
||||
"tilt": row["max_tilt_rad"] <= 0.6,
|
||||
"lift_deadline": bool(lift_deadline.any()) and bool(
|
||||
((t["gap"][:, env][lift_deadline] >= 0.02) & (fn[lift_deadline] <= 2)).all()),
|
||||
"stance_contact": row["stance_contact_fraction"] >= thresholds["stance_contact_fraction_min"],
|
||||
"load": row["stance_load_mae_weight_fraction"] <= thresholds["stance_load_mae_weight_fraction_max"],
|
||||
"height": row["height_error_m_max"] <= thresholds["height_error_m_max"],
|
||||
"swing_tracking": row["swing_rms_m"] <= thresholds["swing_rms_m_max"],
|
||||
"clearance": row["swing_clearance_m_min"] >= thresholds["swing_clearance_m_min"],
|
||||
"airborne": row["swing_contact_fraction"] <= thresholds["swing_contact_fraction_max"],
|
||||
"slip": row["stance_slip_m"] <= thresholds["stance_slip_m_max"],
|
||||
"impact": row["landing_peak_N"] <= thresholds["landing_peak_weight_fraction_max"] * weight,
|
||||
"recovery": recovery is not None and recovery <= thresholds["recovery_s_max"],
|
||||
"joint_limits": row["joint_limit_excess_rad_max"] <= thresholds["joint_limit_excess_rad_max"],
|
||||
"actuation": row["normalized_effort_velocity_max"] <= thresholds["normalized_effort_velocity_max"],
|
||||
"unilateral": row["unilateral_residual_N_max"] <= thresholds["unilateral_residual_N_max"],
|
||||
"friction": row["friction_residual_N_max"] <= thresholds["friction_residual_N_max"],
|
||||
}
|
||||
row.update(success=all(checks.values()), failure_reasons=[k for k, v in checks.items() if not v], gates=checks)
|
||||
rows.append(row)
|
||||
return rows
|
||||
|
||||
|
||||
def wilson(successes, count):
|
||||
if count <= 0 or not 0 <= successes <= count:
|
||||
raise ValueError("Invalid trial count")
|
||||
p, z = successes/count, 1.959963984540054
|
||||
center = (p + z*z/(2*count))/(1+z*z/count)
|
||||
half = z * math.sqrt(p*(1-p)/count + z*z/(4*count*count))/(1+z*z/count)
|
||||
return [center-half, center+half]
|
||||
@@ -0,0 +1,211 @@
|
||||
"""New 32D symmetric PPO contract; never loads standing/Reach checkpoints.
|
||||
|
||||
The frozen standing module supplies only generic PPO math and RNG helpers.
|
||||
No optimizer is invoked merely by importing or preparing a run.
|
||||
"""
|
||||
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributions import Normal
|
||||
|
||||
from ..standing_ppo import ppo_step, restore_rng, rng_state # noqa: F401
|
||||
from .mechanics import canonical_ids
|
||||
from .task import FAILURE_NAMES
|
||||
|
||||
CONTRACT = "go2-fl-contact-cycle-v1"
|
||||
FEATURE_VERSION = "contact-cycle-32-fixed-si-v1"
|
||||
CHECKPOINT_FORMAT = "skillfactory.contact-cycle-ppo-checkpoint.v1"
|
||||
|
||||
|
||||
def features(policy):
|
||||
if (not isinstance(policy, torch.Tensor) or policy.ndim != 2 or policy.shape[1] != 32
|
||||
or len(policy) < 1 or policy.dtype != torch.float32 or not torch.isfinite(policy).all()):
|
||||
raise ValueError("Require finite float32 [B,32] policy sensors/commands, not privileged observations")
|
||||
return policy
|
||||
|
||||
|
||||
class CycleActorCritic(nn.Module):
|
||||
def __init__(self, hidden=128, initial_std=0.15):
|
||||
super().__init__()
|
||||
if type(hidden) is not int or hidden < 8 or not math.isfinite(initial_std) or not 0.02 <= initial_std <= 0.5:
|
||||
raise ValueError("Invalid network configuration")
|
||||
self.model_config = {"hidden": hidden, "initial_std": initial_std}
|
||||
offset, scale = torch.zeros(32), torch.ones(32)
|
||||
offset[:3] = torch.tensor([0., 0.8, -1.5])
|
||||
scale[:3], scale[3:6] = 0.5, 10.0
|
||||
scale[6:12] = torch.tensor([50., 50., 50., 5., 5., 5.])
|
||||
scale[15:18], scale[28:31], scale[31] = 5.0, 0.4, 50.0
|
||||
self.register_buffer("offset", offset)
|
||||
self.register_buffer("scale", scale)
|
||||
self.actor = nn.Sequential(nn.Linear(32, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(),
|
||||
nn.Linear(hidden, 3))
|
||||
self.critic = nn.Sequential(nn.Linear(32, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(),
|
||||
nn.Linear(hidden, 1))
|
||||
for layer in self.modules():
|
||||
if isinstance(layer, nn.Linear):
|
||||
nn.init.orthogonal_(layer.weight, math.sqrt(2))
|
||||
nn.init.zeros_(layer.bias)
|
||||
nn.init.orthogonal_(self.actor[-1].weight, 0.01)
|
||||
nn.init.orthogonal_(self.critic[-1].weight, 1.0)
|
||||
self.log_std = nn.Parameter(torch.full((3,), math.log(initial_std)))
|
||||
self.float()
|
||||
|
||||
def distribution_value(self, x):
|
||||
x = ((features(x) - self.offset) / self.scale).clamp(-10, 10)
|
||||
return (Normal(self.actor(x), self.log_std.clamp(math.log(0.02), math.log(0.5)).exp(), validate_args=False),
|
||||
self.critic(x).squeeze(-1))
|
||||
|
||||
def act(self, x, deterministic=False):
|
||||
dist, value = self.distribution_value(x)
|
||||
latent = dist.mean if deterministic else dist.sample()
|
||||
return latent.tanh(), latent, dist.log_prob(latent).sum(-1), value
|
||||
|
||||
def evaluate(self, x, latent):
|
||||
dist, value = self.distribution_value(x)
|
||||
return dist.log_prob(latent).sum(-1), value
|
||||
|
||||
def value(self, x):
|
||||
return self.distribution_value(x)[1]
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def bootstrap_values(model, next_features, terminated, truncated, info):
|
||||
value = model.value(features(next_features))
|
||||
timeout = truncated & ~terminated
|
||||
if timeout.any():
|
||||
ids, terminal = info.get("terminal_ids"), info.get("terminal_observation")
|
||||
if ids is None or terminal is None:
|
||||
raise RuntimeError("Missing/invalid pre-reset timeout observations")
|
||||
try:
|
||||
ids = canonical_ids(ids, len(value))
|
||||
except ValueError as error:
|
||||
raise RuntimeError("Invalid terminal indices") from error
|
||||
if not torch.isin(timeout.nonzero().flatten(), ids).all():
|
||||
raise RuntimeError("Missing pre-reset timeout observations")
|
||||
terminal_x = features(terminal["policy"])
|
||||
if len(terminal_x) != len(ids):
|
||||
raise RuntimeError("Terminal observation/index mismatch")
|
||||
selected = timeout[ids]
|
||||
value[ids[selected]] = model.value(terminal_x[selected])
|
||||
value[terminated] = 0
|
||||
return value
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def collect_rollout(env, model, x, config, guard=lambda: None):
|
||||
data = {key: torch.empty(config["horizon"], env.num_envs, *shape, device=env.device, dtype=dtype)
|
||||
for key, shape, dtype in (("features", (32,), torch.float32), ("latent", (3,), torch.float32),
|
||||
("log_prob", (), torch.float32), ("value", (), torch.float32), ("reward", (), torch.float32),
|
||||
("next_value", (), torch.float32), ("done", (), torch.bool),
|
||||
("phase", (), torch.long), ("failure_flags", (len(FAILURE_NAMES),), torch.bool))}
|
||||
failures = timeouts = 0
|
||||
for step in range(config["horizon"]):
|
||||
guard()
|
||||
action, latent, logp, value = model.act(x)
|
||||
obs, reward, terminated, truncated, info = env.step(action)
|
||||
nx = features(obs["policy"])
|
||||
nv = bootstrap_values(model, nx, terminated, truncated, info)
|
||||
reward = reward / env.step_dt - config["failure_penalty"] * terminated.float()
|
||||
if not torch.isfinite(reward).all() or not torch.isfinite(nv).all():
|
||||
raise RuntimeError("Nonfinite rollout rewards/values")
|
||||
for key, item in (("features", x), ("latent", latent), ("log_prob", logp), ("value", value),
|
||||
("reward", reward), ("next_value", nv), ("done", terminated | truncated)):
|
||||
data[key][step].copy_(item)
|
||||
diagnostic = info.get("cycle_step")
|
||||
data["phase"][step].fill_(-1)
|
||||
data["failure_flags"][step].zero_()
|
||||
if diagnostic is not None:
|
||||
data["phase"][step].copy_(diagnostic["phase"])
|
||||
data["failure_flags"][step].copy_(diagnostic["failure_flags"])
|
||||
failures += int(terminated.sum())
|
||||
timeouts += int(truncated.sum())
|
||||
x = nx
|
||||
return data, x, failures, timeouts
|
||||
|
||||
|
||||
def rollout_diagnostics(data, cfg):
|
||||
"""Aggregate already-collected samples; no policy inference or optimizer call."""
|
||||
from ..policy import compute_gae
|
||||
|
||||
adv, returns = compute_gae(data["reward"], data["value"], data["next_value"], data["done"],
|
||||
cfg["gamma"], cfg["gae_lambda"])
|
||||
|
||||
def stats(x):
|
||||
return {"min": float(x.min()), "mean": float(x.mean()), "max": float(x.max()),
|
||||
"std": float(x.std(unbiased=False))}
|
||||
|
||||
phases = data["phase"].flatten()
|
||||
return {"phase_control_samples": torch.bincount(phases[phases >= 0], minlength=6).cpu().tolist(),
|
||||
"missing_diagnostic_samples": int((phases < 0).sum()),
|
||||
"terminal_causes": dict(zip(FAILURE_NAMES, data["failure_flags"].sum((0, 1)).cpu().tolist())),
|
||||
"reward": stats(data["reward"]), "advantage_before_normalization": stats(adv),
|
||||
"return_target": stats(returns)}
|
||||
|
||||
|
||||
def selection_score(rows):
|
||||
"""Validation only. Failed/missing samples cannot benefit from early termination.
|
||||
|
||||
Each failure receives fixed worst cost 16 (=10+2+2+2); each successful
|
||||
normalized term is clipped to [0,2]. All candidates/thresholds remain locked
|
||||
before any future independent testing.
|
||||
"""
|
||||
if not rows:
|
||||
raise ValueError("Empty validation is not a candidate")
|
||||
scores = []
|
||||
for row in rows:
|
||||
if not row.get("success", False):
|
||||
scores.append(16.)
|
||||
continue
|
||||
values = [row["swing_rms_m"]/0.025, row["stance_load_mae_weight_fraction"]/0.25,
|
||||
row["stance_slip_m"]/0.03]
|
||||
if not all(math.isfinite(v) and v >= 0 for v in values):
|
||||
raise ValueError("Nonfinite/negative validation metric")
|
||||
scores.append(sum(min(v, 2.) for v in values))
|
||||
return sum(scores)/len(scores)
|
||||
|
||||
|
||||
def save_checkpoint(path, model, optimizer, identity, update, sampler, best, budget, max_bytes=None):
|
||||
path = Path(path)
|
||||
data = {"format": CHECKPOINT_FORMAT, "contract": CONTRACT, "features": FEATURE_VERSION,
|
||||
"model_config": model.model_config, "model": model.state_dict(), "optimizer": optimizer.state_dict(),
|
||||
"identity": identity, "update": update, "sampler": sampler.state_dict(), "best": best,
|
||||
"rng": rng_state(), "budget_snapshot": budget, "accepted_skill": False,
|
||||
"resume_semantics": "Learner/RNG/curriculum counters restored; physics episodes restart, not exact replay"}
|
||||
buffer = io.BytesIO()
|
||||
torch.save(data, buffer)
|
||||
payload = buffer.getvalue()
|
||||
if max_bytes is not None and len(payload) > max_bytes:
|
||||
raise RuntimeError("Insufficient artifact budget for atomic checkpoint temporary file")
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
||||
temporary = Path(stream.name)
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return len(payload)
|
||||
|
||||
|
||||
def restore_checkpoint(path, model, optimizer, identity, sampler):
|
||||
data = torch.load(path, map_location=next(model.parameters()).device, weights_only=True)
|
||||
if (data["format"] != CHECKPOINT_FORMAT or data["contract"] != CONTRACT or data["features"] != FEATURE_VERSION
|
||||
or data["identity"] != identity or data["model_config"] != model.model_config
|
||||
or type(data["update"]) is not int or data["update"] < 0
|
||||
or any(not torch.isfinite(v).all() for v in data["model"].values())):
|
||||
raise ValueError("Cycle checkpoint/config/source mismatch")
|
||||
sampler.load_state_dict(data["sampler"])
|
||||
model.load_state_dict(data["model"])
|
||||
optimizer.load_state_dict(data["optimizer"])
|
||||
restore_rng(data["rng"])
|
||||
return data
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Explicit timed commands; phase-conditioned objective, no all-phase contact bonus."""
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def smooth(x):
|
||||
x = x.clamp(0, 1)
|
||||
return x.square() * (3 - 2 * x)
|
||||
|
||||
|
||||
def command(time, cfg, origin, weight):
|
||||
durations = time.new_tensor(cfg["phase_durations_s"])
|
||||
ends = durations.cumsum(0)
|
||||
phase = torch.bucketize(time.contiguous(), ends[:-1], right=True)
|
||||
starts = torch.cat((time.new_zeros(1), ends[:-1]))
|
||||
progress = ((time - starts[phase]) / durations[phase]).clamp(0, 1)
|
||||
u = smooth(progress)
|
||||
target = origin.clone()
|
||||
delta = time.new_tensor(cfg["swing_displacement_m"])
|
||||
xy_progress = torch.where(phase < 3, 0.0, torch.where(phase == 3, u, 1.0))
|
||||
target += xy_progress[:, None] * delta
|
||||
height = torch.where(phase == 2, u, torch.where(phase == 3, 1.0, torch.where(phase == 4, 1-u, 0.0)))
|
||||
target[:, 2] += cfg["clearance_m"] * height
|
||||
# A genuine three-dimensional swing curve, zero derivative at endpoints.
|
||||
target[:, 2] += torch.where(phase == 3, 0.01 * torch.sin(torch.pi * progress).square(), 0.0)
|
||||
load_fraction = torch.where(phase == 0, 1.0, torch.where(phase == 1, 1-u, torch.where(phase == 5, u, 0.0)))
|
||||
return phase, progress, target, weight * load_fraction, 1-load_fraction
|
||||
|
||||
|
||||
FAILURE_NAMES = ("nonfinite", "contact_acquisition_timeout", "premature_separation", "lift_deadline",
|
||||
"swing_clearance", "reload_deadline", "low_height", "tilt")
|
||||
|
||||
|
||||
def phase_failures(phase, progress, gap, normal_force, weight):
|
||||
return {
|
||||
"lift_deadline": (phase == 2) & (progress > 0.9) & ((gap < 0.02) | (normal_force > 2)),
|
||||
"swing_clearance": (phase == 3) & (gap < 0.01),
|
||||
"reload_deadline": (phase == 5) & (progress > 0.8) & (normal_force < 0.5 * weight),
|
||||
}
|
||||
|
||||
|
||||
def phase_objective(phase, progress, error, gap, normal_force, desired_force, slip_speed, impact, weight,
|
||||
unload_tracking_scale_m=0.005):
|
||||
"""Dimensionless shaped reward and deadline violations; not acceptance metrics.
|
||||
|
||||
No early-contact bonus in lift/swing. No air-time bonus in support/reload.
|
||||
Measured ground force is privileged reward input, NEVER an actor observation.
|
||||
"""
|
||||
airborne = (phase == 2) | (phase == 3)
|
||||
stance = (phase == 0) | (phase == 5)
|
||||
load_score = torch.exp(-((normal_force - desired_force) / (0.25 * weight)).square())
|
||||
track = torch.exp(-(error / 0.025).square())
|
||||
reward = torch.where(airborne, track - (normal_force > 2).float(), load_score)
|
||||
# Unload means shed load while holding the ground target, NOT lift early to attain Fn=0.
|
||||
unload_track = torch.exp(-(error / unload_tracking_scale_m).square())
|
||||
reward = torch.where(phase == 1, load_score + unload_track - 1, reward)
|
||||
reward = torch.where(phase == 4, track - (impact / (3 * weight)).square(), reward)
|
||||
reward -= stance.float() * (slip_speed / 0.05).square().clamp(max=4)
|
||||
reward -= (phase == 3).float() * (gap < 0.02).float()
|
||||
# End-of-phase deadlines prevent persistent contact AND indefinite flight.
|
||||
violation = torch.stack(list(phase_failures(phase, progress, gap, normal_force, weight).values()), -1).any(-1)
|
||||
return reward, violation
|
||||
|
||||
|
||||
class DelayLine:
|
||||
"""Control-clock history with selective reset; repeated reads never advance it."""
|
||||
|
||||
def __init__(self, count, width, delay, device):
|
||||
self.delay = delay
|
||||
self.data = torch.zeros(delay + 1, count, width, device=device)
|
||||
|
||||
def reset(self, ids, value=0.0):
|
||||
self.data[:, ids] = value
|
||||
|
||||
def push(self, value):
|
||||
self.data = torch.roll(self.data, -1, 0)
|
||||
self.data[-1] = value
|
||||
return self.data[0].clone()
|
||||
@@ -0,0 +1,304 @@
|
||||
"""Pre-registration, explicit authorization and fail-closed multi-seed budget ledger.
|
||||
|
||||
This file has no simulator imports. Preparation is not permission to optimize.
|
||||
The budget is an absolute CLOCK_BOOTTIME window (includes suspend and same-boot
|
||||
downtime), not adjustable UTC. Reboots and legacy ledgers fail closed. Reserved
|
||||
interrupted rollouts are not refunded; changing this code does not authorize migration.
|
||||
"""
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .config import load_config
|
||||
from .ppo import CONTRACT, FEATURE_VERSION
|
||||
|
||||
|
||||
class BudgetExceeded(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def digest(value):
|
||||
encoded = json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def atomic_json(path, value):
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(mode="w", dir=path.parent, delete=False) as stream:
|
||||
temporary = Path(stream.name)
|
||||
json.dump(value, stream, indent=2, allow_nan=False)
|
||||
stream.write("\n")
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def load_training_config(path, root):
|
||||
cfg = json.loads(Path(path).read_text())
|
||||
keys = {"format", "contract", "proposal", "task_config", "seeds", "validation_seed", "num_envs", "horizon",
|
||||
"updates_per_seed", "checkpoint_interval", "validation_interval", "max_total_transitions",
|
||||
"max_total_wall_s", "max_artifact_bytes", "algorithm"}
|
||||
formats = {"skillfactory.contact-cycle-training.v1", "skillfactory.contact-cycle-diagnostic-training.v1"}
|
||||
if set(cfg) != keys or cfg["format"] not in formats or cfg["contract"] != CONTRACT:
|
||||
raise ValueError("Unknown training config/contract")
|
||||
diagnostic = cfg["format"] == "skillfactory.contact-cycle-diagnostic-training.v1"
|
||||
for key in keys - {"format", "contract", "proposal", "task_config", "seeds", "algorithm"}:
|
||||
if type(cfg[key]) is not int or cfg[key] <= 0:
|
||||
raise ValueError(f"Invalid positive integer: {key}")
|
||||
proposal = json.loads((Path(root)/cfg["proposal"]).read_text())
|
||||
plan = proposal["proposed_training"]
|
||||
for key in ("seeds", "num_envs", "horizon", "updates_per_seed", "max_total_transitions",
|
||||
"max_total_wall_s", "max_artifact_bytes"):
|
||||
if cfg[key] != plan[key]:
|
||||
raise ValueError(f"Budget/seed scope changed from proposal: {key}")
|
||||
seed_count = 1 if diagnostic else 3
|
||||
reserved_seeds = proposal["independent_test"]["seed_commitment"]
|
||||
if (not isinstance(cfg["seeds"], list) or len(cfg["seeds"]) != seed_count
|
||||
or len(set(cfg["seeds"])) != seed_count or any(type(s) is not int or s < 0 for s in cfg["seeds"])
|
||||
or set(cfg["seeds"]) & set(reserved_seeds)
|
||||
or cfg["validation_seed"] in cfg["seeds"] + reserved_seeds):
|
||||
raise ValueError("Train/validation/independent seed overlap or count")
|
||||
if cfg["updates_per_seed"] != (512 if diagnostic else 2048) or cfg["num_envs"] < 4:
|
||||
raise ValueError("Unsupported curriculum/batch")
|
||||
if diagnostic and (cfg["num_envs"] != 128 or cfg["horizon"] != 32
|
||||
or cfg["max_total_wall_s"] > 1800 or cfg["max_artifact_bytes"] > 1073741824):
|
||||
raise ValueError("Diagnostic pilot exceeds fixed scope")
|
||||
if any(cfg[k] != 256 for k in ("checkpoint_interval", "validation_interval")):
|
||||
raise ValueError("Selection schedule is locked to every 256 updates")
|
||||
expected = len(cfg["seeds"]) * cfg["updates_per_seed"] * cfg["horizon"] * cfg["num_envs"]
|
||||
if cfg["max_total_transitions"] != expected:
|
||||
raise ValueError("Inconsistent total transition budget")
|
||||
a = cfg["algorithm"]
|
||||
expected_keys = {"hidden", "initial_std", "learning_rate", "gamma", "gae_lambda", "clip_ratio", "epochs",
|
||||
"minibatch_size", "value_coefficient", "max_gradient_norm", "target_kl", "failure_penalty"}
|
||||
if set(a) != expected_keys:
|
||||
raise ValueError("Invalid PPO keys")
|
||||
for key, value in a.items():
|
||||
if type(value) not in (int, float) or not math.isfinite(value) or value <= 0:
|
||||
raise ValueError(f"Invalid algorithm value: {key}")
|
||||
if any(type(a[k]) is not int for k in ("hidden", "epochs", "minibatch_size")):
|
||||
raise ValueError("Integer PPO parameters required")
|
||||
if (a["hidden"] < 8 or not 0.02 <= a["initial_std"] <= 0.5 or not 0 < a["gamma"] <= 1
|
||||
or not 0 < a["gae_lambda"] <= 1 or not 0 < a["clip_ratio"] < 1
|
||||
or cfg["num_envs"]*cfg["horizon"] % a["minibatch_size"]):
|
||||
raise ValueError("Invalid PPO discounts/std/minibatches")
|
||||
load_config(Path(root)/cfg["task_config"])
|
||||
return cfg
|
||||
|
||||
|
||||
def source_identity(root, cfg, config_path):
|
||||
root = Path(root).resolve()
|
||||
task = load_config(root/cfg["task_config"])
|
||||
support = json.loads((root/task["support_config"]).read_text())
|
||||
files = {root/cfg["task_config"], root/cfg["proposal"], Path(config_path).resolve(), root/task["support_config"]}
|
||||
files.update((root/"source/SkillFactory").rglob("*.py"))
|
||||
files.add(root/"source/SkillFactory/SkillFactory/legs/resources/ground.usda")
|
||||
for name in ("train_contact_cycle.py", "runtime_common.py", "supervise_sim.py"):
|
||||
files.add(root/"scripts"/name)
|
||||
for folder in (support["support_asset"], support["source_bundle"]):
|
||||
files.update(p for p in (root/folder).rglob("*") if p.is_file())
|
||||
if any(not p.resolve().is_relative_to(root) for p in files):
|
||||
raise ValueError("Training identity inputs must be inside repository")
|
||||
return {str(p.resolve().relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(files)}
|
||||
|
||||
|
||||
def make_manifest(root, config_path):
|
||||
cfg = load_training_config(config_path, root)
|
||||
diagnostic = cfg["format"] == "skillfactory.contact-cycle-diagnostic-training.v1"
|
||||
return {"format": "skillfactory.contact-cycle-preregistration.v1", "contract": CONTRACT,
|
||||
"features": FEATURE_VERSION, "training": cfg, "sources": source_identity(root, cfg, config_path),
|
||||
"sampler": "cycle-episode-sampler-v1", "critic": "symmetric_policy32_no_privileged_input",
|
||||
"selection": "validation every 256; failures=16, successes=sum clipped [0,2] normalized rms/load/slip; "
|
||||
"mean over every environment; tie earliest; "
|
||||
+ ("one diagnostic candidate only; no independent acceptance eligibility" if diagnostic
|
||||
else "lock all three before independent test"),
|
||||
"resume": "learner/RNG/counters restored; reset physics; no refund of interrupted reserved rollouts",
|
||||
"wall_budget": "CLOCK_BOOTTIME absolute deadline including suspend/downtime/validation; "
|
||||
"same boot only; no automatic legacy-ledger migration",
|
||||
"contact_transition": "geometric liftoff with onset-phase provenance; premature separation terminates",
|
||||
"independent_test": "not_materialized_not_executed", "accepted_skill": False}
|
||||
|
||||
|
||||
def require_authorization(path, manifest):
|
||||
if path is None:
|
||||
raise PermissionError("New training requires explicit user authorization bound to this prepared manifest")
|
||||
grant = json.loads(Path(path).read_text())
|
||||
required = {"format", "approved", "manifest_sha256", "operator", "authorization_reference"}
|
||||
if (set(grant) != required or grant["format"] != "skillfactory.contact-cycle-authorization.v1"
|
||||
or grant["approved"] is not True or grant["manifest_sha256"] != digest(manifest)
|
||||
or not isinstance(grant["operator"], str) or not grant["operator"].strip()
|
||||
or not isinstance(grant["authorization_reference"], str) or not grant["authorization_reference"].strip()):
|
||||
raise PermissionError("Invalid/stale authorization; do not synthesize approval from a configuration file")
|
||||
return grant
|
||||
|
||||
|
||||
def save_trace_subset(path, trace, selected, stops, reserve):
|
||||
"""Detach backing storage, measure exact serialization bytes, then atomically write."""
|
||||
import torch
|
||||
|
||||
path = Path(path)
|
||||
if path.exists():
|
||||
raise FileExistsError("Never overwrite validation evidence")
|
||||
evidence = {str(e): {k: v[:stops[e], e:e+1].clone().contiguous() for k, v in trace.items()} for e in selected}
|
||||
stream = io.BytesIO()
|
||||
torch.save(evidence, stream)
|
||||
payload = stream.getvalue()
|
||||
reserve(len(payload)) # must fail before any temporary/partial artifact is created
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as out:
|
||||
temporary = Path(out.name)
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return len(payload)
|
||||
|
||||
|
||||
def artifact_bytes(root):
|
||||
return sum(p.stat().st_size for p in Path(root).rglob("*") if p.is_file())
|
||||
|
||||
|
||||
class BudgetLedger:
|
||||
"""One exclusive writer for ALL training seeds and resumptions in this experiment."""
|
||||
|
||||
FORMAT = "skillfactory.contact-cycle-budget.v2"
|
||||
|
||||
def __init__(self, root, manifest, now=time.time, *, boot_now=None, boot_id=None):
|
||||
self.root, self.manifest, self.now = Path(root), manifest, now
|
||||
self.boot_now = boot_now or (lambda: time.clock_gettime(time.CLOCK_BOOTTIME))
|
||||
self.boot_id = boot_id if boot_id is not None else Path("/proc/sys/kernel/random/boot_id").read_text().strip()
|
||||
if not isinstance(self.boot_id, str) or not self.boot_id:
|
||||
raise ValueError("A Linux boot identity is required; never fall back to UTC")
|
||||
self.path = self.root/"budget.json"
|
||||
self.cfg = manifest["training"]
|
||||
self.lock = None
|
||||
|
||||
def clocks(self):
|
||||
wall, boot = self.now(), self.boot_now()
|
||||
if not math.isfinite(wall) or not math.isfinite(boot) or boot < 0:
|
||||
raise BudgetExceeded(f"Nonfinite/invalid clock: wall={wall!r}, boottime={boot!r}")
|
||||
return wall, boot
|
||||
|
||||
def __enter__(self):
|
||||
self.root.mkdir(parents=True, exist_ok=True)
|
||||
self.lock = (self.root/"budget.lock").open("a+")
|
||||
try:
|
||||
fcntl.flock(self.lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
now, boot = self.clocks()
|
||||
if self.path.exists():
|
||||
self.data = json.loads(self.path.read_text())
|
||||
if self.data.get("format") != self.FORMAT:
|
||||
raise ValueError("Legacy/unknown ledger: explicit newly authorized recovery protocol required")
|
||||
if self.data["manifest_sha256"] != digest(self.manifest):
|
||||
raise ValueError("Experiment identity changed")
|
||||
clock = self.data["clock"]
|
||||
if clock["boot_id"] != self.boot_id:
|
||||
raise BudgetExceeded("Boot identity changed; cannot prove downtime, refusing automatic resume")
|
||||
start, last, deadline = (clock[k] for k in ("start_s", "last_seen_s", "deadline_s"))
|
||||
if (not all(math.isfinite(v) for v in (start, last, deadline)) or not 0 <= start <= last < deadline
|
||||
or deadline != start + self.cfg["max_total_wall_s"]):
|
||||
raise ValueError("Invalid immutable boot-clock deadline")
|
||||
else:
|
||||
self.data = {"format": self.FORMAT, "manifest_sha256": digest(self.manifest),
|
||||
"started_at": now, "last_seen_at": now,
|
||||
"clock": {"boot_id": self.boot_id, "start_s": boot, "last_seen_s": boot,
|
||||
"deadline_s": boot + self.cfg["max_total_wall_s"],
|
||||
"wall_rollbacks": 0, "last_wall_rollback": None},
|
||||
"reserved_transitions": 0, "reservations": 0, "pending": None,
|
||||
"updates": {str(s): 0 for s in self.cfg["seeds"]}}
|
||||
atomic_json(self.path, self.data)
|
||||
self.guard()
|
||||
return self
|
||||
except BaseException:
|
||||
self.lock.close()
|
||||
raise
|
||||
|
||||
def __exit__(self, *_):
|
||||
if self.lock is not None:
|
||||
self.lock.close()
|
||||
|
||||
def guard(self, reserve_bytes=0):
|
||||
now, boot = self.clocks()
|
||||
clock = self.data["clock"]
|
||||
if boot < clock["last_seen_s"]:
|
||||
raise BudgetExceeded(f"Boot clock rollback: observed={boot!r}, last={clock['last_seen_s']!r}, wall={now!r}")
|
||||
if boot >= clock["deadline_s"]:
|
||||
raise BudgetExceeded(f"Global wall-time budget exhausted: boottime={boot!r}, "
|
||||
f"deadline={clock['deadline_s']!r}, wall={now!r}")
|
||||
if artifact_bytes(self.root) + reserve_bytes > self.cfg["max_artifact_bytes"]:
|
||||
raise BudgetExceeded("Global artifact budget exhausted")
|
||||
if now < self.data["last_seen_at"]:
|
||||
clock["wall_rollbacks"] += 1
|
||||
clock["last_wall_rollback"] = {"previous": self.data["last_seen_at"], "observed": now, "boottime": boot}
|
||||
clock["last_seen_s"] = boot
|
||||
self.data["last_seen_at"] = now # diagnostic only; never changes the boot-clock deadline
|
||||
|
||||
def write_json(self, path, value):
|
||||
payload = json.dumps(value, indent=2, allow_nan=False) + "\n"
|
||||
self.guard(reserve_bytes=len(payload.encode()) + 65536)
|
||||
atomic_json(path, value)
|
||||
|
||||
def append_json(self, path, value):
|
||||
payload = json.dumps(value, allow_nan=False) + "\n"
|
||||
self.guard(reserve_bytes=len(payload.encode()) + 65536)
|
||||
with Path(path).open("a") as stream:
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
|
||||
def reconcile_checkpoint(self, seed, update):
|
||||
"""Reconcile the checkpoint-before-ledger-commit crash window. Never refund work."""
|
||||
self.guard()
|
||||
previous = self.data["updates"][str(seed)]
|
||||
pending = self.data["pending"]
|
||||
if update not in (previous, previous + 1):
|
||||
raise ValueError("Only latest checkpoint recovery is allowed")
|
||||
if update == previous + 1 and pending != {"seed": seed, "update": update}:
|
||||
raise ValueError("Unreserved checkpoint progress")
|
||||
if pending is not None and pending["seed"] != seed:
|
||||
raise ValueError("A different seed has interrupted work; recover it first")
|
||||
self.data["updates"][str(seed)] = update
|
||||
self.data["pending"] = None
|
||||
atomic_json(self.path, self.data)
|
||||
|
||||
def reserve_rollout(self, seed, update):
|
||||
self.guard()
|
||||
if self.data["pending"] is not None:
|
||||
raise ValueError("Uncommitted reservation must be reconciled before continuing")
|
||||
if (seed not in self.cfg["seeds"] or type(update) is not int or not 1 <= update <= self.cfg["updates_per_seed"]
|
||||
or update != self.data["updates"][str(seed)] + 1):
|
||||
raise ValueError("Unexpected seed/update sequence")
|
||||
cost = self.cfg["num_envs"] * self.cfg["horizon"]
|
||||
if self.data["reserved_transitions"] + cost > self.cfg["max_total_transitions"]:
|
||||
raise BudgetExceeded("Global transition budget exhausted")
|
||||
self.data["reserved_transitions"] += cost
|
||||
self.data["reservations"] += 1
|
||||
self.data["pending"] = {"seed": seed, "update": update}
|
||||
atomic_json(self.path, self.data) # durable BEFORE any environment transitions
|
||||
|
||||
def commit_update(self, seed, update):
|
||||
self.guard()
|
||||
if (update != self.data["updates"][str(seed)] + 1
|
||||
or self.data["pending"] != {"seed": seed, "update": update}):
|
||||
raise ValueError("Nonsequential/unreserved completed update")
|
||||
self.data["updates"][str(seed)] = update
|
||||
self.data["pending"] = None
|
||||
atomic_json(self.path, self.data)
|
||||
@@ -0,0 +1 @@
|
||||
"""Simulation-truth reference/residual protocol; incompatible with historical policy32."""
|
||||
@@ -0,0 +1,49 @@
|
||||
"""Explicit simulation-only contract. Loading a config never authorizes optimization."""
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
FEATURE_VERSION = 'contact-cycle-sim-truth-residual-46-v1'
|
||||
TASK_ID = 'SkillFactory-Go2FL-ContactCycleSim-v1'
|
||||
|
||||
|
||||
def load_config(path):
|
||||
c = json.loads(Path(path).read_text())
|
||||
keys = {'format', 'task_id', 'cycle_config', 'features', 'residual_limit_rad', 'reference', 'reward', 'scope'}
|
||||
if (set(c) != keys
|
||||
or c['format'] != 'skillfactory.contact-cycle-sim-residual.v1'
|
||||
or c['task_id'] != TASK_ID or c['features'] != FEATURE_VERSION):
|
||||
raise ValueError('Invalid simulation-residual identity')
|
||||
ref, r = c['reference'], c['reward']
|
||||
if (set(ref) != {'ik_iterations', 'ik_damping', 'ik_step_limit_rad', 'jacobian_epsilon_rad'}
|
||||
or set(r) != {'position_scale_m', 'velocity_scale_m_s', 'cost_cap', 'position_weight',
|
||||
'velocity_weight', 'residual_weight'} or len(r['position_scale_m']) != 3):
|
||||
raise ValueError('Invalid reference/reward parameters')
|
||||
vals = [c['residual_limit_rad'], *ref.values(), *r['position_scale_m'],
|
||||
*[v for k, v in r.items() if k != 'position_scale_m']]
|
||||
if any(type(x) not in (int, float) or not math.isfinite(x) or x <= 0 for x in vals):
|
||||
raise ValueError('Require positive finite simulation parameters')
|
||||
if (not 0 < c['residual_limit_rad'] <= .1 or type(ref['ik_iterations']) is not int
|
||||
or not 1 <= ref['ik_iterations'] <= 10 or ref['ik_step_limit_rad'] > .1
|
||||
or ref['jacobian_epsilon_rad'] > .01):
|
||||
raise ValueError('Reference/residual bounds exceeded')
|
||||
return c
|
||||
|
||||
|
||||
def combine(reference_action, residual, limit_rad, action_scale_rad):
|
||||
if (residual.ndim != 2 or residual.shape != reference_action.shape or residual.shape[-1] != 3
|
||||
or residual.dtype != torch.float32 or reference_action.dtype != torch.float32
|
||||
or not torch.isfinite(residual).all() or not torch.isfinite(reference_action).all()
|
||||
or (reference_action.abs() > 1).any()):
|
||||
raise ValueError('Require finite float32 residuals matching [B,3] reference')
|
||||
request = residual.clamp(-1, 1)
|
||||
full = (reference_action + request * (limit_rad / action_scale_rad)).clamp(-1, 1)
|
||||
return full, request, (full - reference_action) * action_scale_rad
|
||||
|
||||
|
||||
def pose_cost(position_error, velocity_error, reward_cfg):
|
||||
position = (position_error / position_error.new_tensor(reward_cfg['position_scale_m'])).square().sum(-1)
|
||||
velocity = (velocity_error / reward_cfg['velocity_scale_m_s']).square().sum(-1)
|
||||
return position.clamp(max=reward_cfg['cost_cap']), velocity.clamp(max=reward_cfg['cost_cap'])
|
||||
@@ -0,0 +1,261 @@
|
||||
"""Exact external P1 evidence adoption, never a launch or a physical-pass claim.
|
||||
|
||||
Historical source/config hashes are evidence of the old execution, not a claim
|
||||
that today's edited evaluator equals those sources. Source artifacts are opened
|
||||
read-only; the independently reviewed adoption digest is the trust boundary.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .evaluation_budget import (
|
||||
CAP_BYTES, EXTENDED_PROFILE, FORMAT as BUDGET_FORMAT, artifact_size, digest,
|
||||
durable_write, encode, sync_directory, SECOND_EXTENDED_ROOT,
|
||||
)
|
||||
|
||||
FORMAT = 'skillfactory.external-p1-adoption.v1'
|
||||
SOURCE_ROOT = Path('/home/cen/sf-runs/p1-03')
|
||||
TARGET_ROOT = Path('/home/cen/sf-runs/p2-01')
|
||||
SOURCE_CAMPAIGN = 'short-p1-03'
|
||||
CANDIDATE_SHA256 = 'c088bb3aecaca751867118858626fd508f7a3983303802d7524353f80802cf99'
|
||||
P1_PROTOCOL = 'configs/contact_cycle/continuous_eval_p1_v1.json'
|
||||
ROOT = Path(__file__).resolve().parents[5]
|
||||
|
||||
|
||||
def _require(condition, name):
|
||||
if not condition:
|
||||
raise ValueError('adoption_' + name)
|
||||
|
||||
|
||||
def _json(path):
|
||||
_require(path == path.resolve(strict=True) and path.is_file(), 'canonical_regular_file')
|
||||
return json.loads(path.read_bytes())
|
||||
|
||||
|
||||
def _hash_value(value):
|
||||
return hashlib.sha256(encode(value)).hexdigest()
|
||||
|
||||
|
||||
def source_snapshot(*, check_trace=False):
|
||||
"""Parse both closed rows, retain failures, bind all original launch bytes."""
|
||||
root = SOURCE_ROOT
|
||||
_require(root == root.resolve(strict=True), 'source_root')
|
||||
ledger = _json(root / 'budget.json')
|
||||
_require(ledger['format'] == BUDGET_FORMAT and ledger['campaign_id'] == SOURCE_CAMPAIGN
|
||||
and len(ledger['launches']) == 2, 'original_two_closed_rows_required')
|
||||
preflight = _json(root / 'row1-preflight.json')
|
||||
_require(preflight['cumulative_prior_consumed_physical_calls'] == 58000
|
||||
and preflight['budget_before']['launches'] == ledger['launches'][:1]
|
||||
and preflight['budget_before']['first_run_boottime'] == ledger['first_run_boottime'],
|
||||
'historical_no_refund_accounting')
|
||||
files = {name: digest(root / name) for name in (
|
||||
'budget.json', 'row1-preflight.json', 'FINAL_P1_ROW0.md', 'FINAL_P1_ROW1.md', 'PAIRED_P1_SUMMARY.md')}
|
||||
summaries = []
|
||||
for index, (controller, tick) in enumerate((('learned_policy', 1829), ('analytic_reference', 1770))):
|
||||
launch = root / f'launch-{index}'
|
||||
artifact_size(launch) # refuse linked/nonregular evidence, including extra files
|
||||
for path in sorted(launch.rglob('*')):
|
||||
if path.is_file():
|
||||
files[str(path.relative_to(root))] = digest(path)
|
||||
row = ledger['launches'][index]
|
||||
grant = _json(launch / 'grant.json')
|
||||
reservation = _json(launch / 'reservation.json')
|
||||
result = _json(launch / 'result.json')
|
||||
metrics = _json(launch / f'trial-{index:02d}/metrics.json')
|
||||
supervisor = _json(launch / 'supervisor.json')
|
||||
preclose = _json(launch / 'preclose-filesystem.json')
|
||||
postexit = _json(launch / 'postexit-filesystem.json')
|
||||
manifest = _json(launch / 'manifest.json')
|
||||
_require(row['index'] == index and row['status'] == 'closed'
|
||||
and row['cleanup_clean'] is True and row['continuation_eligible'] is True
|
||||
and row['reserved_physical_calls'] == 14500 and row['rollout_cap'] == 13500
|
||||
and row['initialization_cap'] == 1000 and row['grant'] == grant
|
||||
and grant['stage'] == 'P1' and grant['trial_indices'] == [index]
|
||||
and grant['launch_index'] == index and grant['campaign_id'] == SOURCE_CAMPAIGN
|
||||
and grant['artifact_root'] == str(root) and grant['boot_id'] == ledger['boot_id'],
|
||||
'closed_row_identity')
|
||||
_require(reservation == {k: v for k, v in row.items()
|
||||
if k not in ('cleanup_clean', 'ended_boottime')}
|
||||
| {'status': 'reserved', 'continuation_eligible': False, 'observed_counts': None},
|
||||
'reservation_changed')
|
||||
trial = metrics['trial']
|
||||
_require(trial == manifest['protocol']['trials'][index]
|
||||
and trial['index'] == index and trial['seed'] == 93501
|
||||
and trial['controller_kind'] == controller
|
||||
and trial['trial_id'] == f'P1/nominal/93501/{controller}'
|
||||
and manifest['trial_seeds'] == {'0': 93501, '1': 93501}, 'trial_stage_controller_seed')
|
||||
_require(result['accepted_skill'] is False and result['optimizer_steps'] == 0
|
||||
and result['selected_rows'] == [index] and len(result['rows']) == 2
|
||||
and result['rows'][index] == metrics and result['rows'][1-index]['status'] == 'not_run'
|
||||
and result['failures'] == [] and result['preclose_identity_verified'] is True
|
||||
and result['continuation_eligible'] is True, 'partial_or_forged_result')
|
||||
_require(metrics['accepted_skill'] is False and metrics['functional_passed'] is False
|
||||
and metrics['protocol_complete'] is False and metrics['completed_clock_cycles'] == 0
|
||||
and metrics['passed_prefix_cycles'] == 0 and metrics['observed_physics_ticks'] == tick
|
||||
and metrics['all_causes'] == ['P1_root_horizontal']
|
||||
and metrics['first_failure'] == {'global_tick': tick, 'time_s': tick * .002,
|
||||
'cycle_index': 0, 'local_tick': tick, 'kind': 'tick',
|
||||
'causes': ['P1_root_horizontal'], 'phase': 1}, 'original_failure_required')
|
||||
counts = {'attempted_steps': tick, 'completed_steps': tick, 'initialization_steps': 0,
|
||||
'rollout_steps': tick}
|
||||
_require(row['observed_counts'] == result['observed_counts'] == supervisor['observed_counts'] == counts
|
||||
and supervisor['cleanup_clean'] is True and supervisor['continuation_eligible'] is True
|
||||
and supervisor['ownership_unknown'] is False and supervisor['returncode'] == 0
|
||||
and supervisor['errors'] == [] and supervisor['stdout_discarded_bytes'] == 0
|
||||
and supervisor['stdout_eof_observed'] is True
|
||||
and postexit['status'] == 'PASS' and postexit['files_rehashed'] == len(preclose['files']),
|
||||
'actual_cleanup_and_identity_required')
|
||||
for name, key in (('manifest.json', 'manifest_sha256'), ('inventory.json', 'inventory_sha256'),
|
||||
('launch-identity.json', 'launch_identity_sha256')):
|
||||
_require(digest(launch / name) == grant[key], 'grant_artifact_hash')
|
||||
protocol = ROOT / P1_PROTOCOL
|
||||
_require(manifest['protocol']['path'] == str(protocol)
|
||||
and manifest['protocol']['sha256'] == grant['protocol_sha256'] == digest(protocol),
|
||||
'original_protocol_hash')
|
||||
frozen = manifest['frozen_policy']
|
||||
_require(frozen['candidate_sha256'] == CANDIDATE_SHA256
|
||||
and preclose['files'][frozen['candidate_path']] == CANDIDATE_SHA256,
|
||||
'frozen_candidate_hash')
|
||||
# Preserve every frozen/snapshot file, not current mutable evaluator sources.
|
||||
frozen_files = {p: sha for p, sha in preclose['files'].items()
|
||||
if Path(p).is_relative_to(preclose['frozen_root'])}
|
||||
_require(bool(frozen_files), 'missing_frozen_files')
|
||||
for path, sha in frozen_files.items():
|
||||
_require(digest(path) == sha, 'frozen_files_changed')
|
||||
trace = launch / f'trial-{index:02d}/trace.v1.jsonl.gz'
|
||||
_require(str(trace.relative_to(root)) in files, 'missing_trace')
|
||||
if check_trace:
|
||||
_check_trace(trace, index, tick)
|
||||
summaries.append({'trial': trial, 'first_failure': metrics['first_failure'],
|
||||
'functional_passed': False, 'accepted_skill': False,
|
||||
'observed_counts': counts, 'cleanup_clean': True,
|
||||
'historical_closed_row': row, 'frozen_policy': frozen,
|
||||
'frozen_files': frozen_files,
|
||||
'effective_config_sha256': _hash_value(manifest['effective_config']),
|
||||
'historical_sources': manifest['sources'],
|
||||
'protocol': manifest['protocol']})
|
||||
_require(all(digest(root / name) == sha for name, sha in files.items()), 'source_changed_during_snapshot')
|
||||
return {'source_root': str(root), 'source_campaign_id': SOURCE_CAMPAIGN,
|
||||
'source_boot_id': ledger['boot_id'], 'source_first_run_boottime': ledger['first_run_boottime'],
|
||||
'source_files_sha256': files, 'rows': summaries,
|
||||
'historical_reserved_calls_before_reference': 58000,
|
||||
'historical_reserved_calls': 72500, 'local_reserved_calls_at_adoption': 0,
|
||||
'prospective_local_reserved_calls': 91000, 'cumulative_reserved_calls_if_launched': 163500}
|
||||
|
||||
|
||||
def _check_trace(path, index, tick):
|
||||
spec = importlib.util.spec_from_file_location('_adoption_trace_reader', ROOT / 'scripts/audit_cycle_sim_evaluation.py')
|
||||
reader = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(reader)
|
||||
terminal = None
|
||||
physics = 0
|
||||
initial = False
|
||||
deadline = time.monotonic() + 120
|
||||
for number, line in enumerate(reader.trace_lines(path, compressed=True, max_bytes=CAP_BYTES,
|
||||
max_record_bytes=1 << 20, max_decoded_bytes=CAP_BYTES, deadline=deadline)):
|
||||
_require(number < 2 * 13500 + 16 and terminal is None, 'trace_partial_or_trailing')
|
||||
record = json.loads(line)
|
||||
if number == 0:
|
||||
_require(record['kind'] == 'initial', 'trace_missing_initial')
|
||||
if record['kind'] == 'initial':
|
||||
_require(not initial and number == 0 and record['event']['clock']['global_tick'] == 0,
|
||||
'trace_duplicate_initial')
|
||||
initial = True
|
||||
event = record.get('event')
|
||||
if event is not None:
|
||||
_require(event['trial_index'] == index, 'trace_cross_trial')
|
||||
if record['kind'] == 'tick':
|
||||
physics += 1
|
||||
_require(event['clock']['global_tick'] == physics, 'trace_noncontiguous_ticks')
|
||||
if record['kind'] == 'terminal':
|
||||
terminal = record
|
||||
_require(terminal is not None, 'trace_missing_terminal')
|
||||
stop = terminal['runtime_stop']
|
||||
_require(stop['trial_index'] == index and stop['reason'] == 'failure' and stop['fatal'] is False
|
||||
and stop['physics_ticks'] == tick and stop['clock']['global_tick'] == tick
|
||||
and stop['causes'] == ['P1_root_horizontal'] and terminal['recording_faults'] == []
|
||||
and terminal['external_failure'] is None and physics == tick, 'trace_failure_mismatch')
|
||||
|
||||
|
||||
# Exact failed attempt reviewed by the parent; no dynamic predecessor discovery.
|
||||
PRIOR_P2_ROOT = Path('/home/cen/sf-runs/p2-01')
|
||||
PRIOR_P2_FILES = {
|
||||
'budget.json': 'a0da00090f18bf28a0b2814aa3f130ef484176f220669621b458b0c3d7b409d7',
|
||||
'launch-0/result.json': '462a6588aaeefe8634ea494800314a1249ddc97c57b938d131e437ecc07923bd',
|
||||
'launch-0/supervisor.json': '5f0d62785679c7709f6d9d7250e5b2d09eae74915a3b020d804451623f4ab778',
|
||||
'launch-0/grant.json': 'c2d894a7b9233a6311e6d1234b2cf5e11a8a5586ad001fc40255025edeb8c781',
|
||||
'launch-0/reservation.json': 'b0f78f729b7de734ba453d00235550f82b2c6aa76bfc59419d80862dfdf7d27c',
|
||||
}
|
||||
|
||||
|
||||
def prior_p2_snapshot(source_boot_id):
|
||||
"""Retain the consumed failure, not a successful trial or measured-zero claim."""
|
||||
for name, sha in PRIOR_P2_FILES.items():
|
||||
_json(PRIOR_P2_ROOT / name) # canonical regular files only
|
||||
_require(digest(PRIOR_P2_ROOT / name) == sha, 'prior_P2_changed')
|
||||
ledger = _json(PRIOR_P2_ROOT / 'budget.json')
|
||||
result = _json(PRIOR_P2_ROOT / 'launch-0/result.json')
|
||||
supervisor = _json(PRIOR_P2_ROOT / 'launch-0/supervisor.json')
|
||||
_require(ledger['boot_id'] == source_boot_id and len(ledger['launches']) == 1
|
||||
and ledger['launches'][0]['status'] == 'closed'
|
||||
and ledger['local_reserved_calls'] == 91000
|
||||
and ledger['cumulative_reserved_calls'] == 163500
|
||||
and ledger['historical_reserved_calls'] == 72500, 'prior_P2_debit')
|
||||
_require(supervisor['cleanup_clean'] is True and supervisor['ownership_unknown'] is False
|
||||
and supervisor['returncode'] == 1 and result['continuation_eligible'] is False
|
||||
and result['accepted_skill'] is False and result['observed_counts'] is None
|
||||
and result['rows'] == [{'status': 'not_run', 'trial_index': i} for i in range(20)],
|
||||
'prior_P2_failure')
|
||||
return {'root': str(PRIOR_P2_ROOT), 'files_sha256': dict(PRIOR_P2_FILES),
|
||||
'reserved_calls': 91000, 'observed_counts': None, 'rows': result['rows'],
|
||||
'failures': result['failures'], 'cleanup_clean': True, 'accepted_skill': False}
|
||||
|
||||
|
||||
def snapshot_for_target(target, *, check_trace=False):
|
||||
_require(target in (TARGET_ROOT, SECOND_EXTENDED_ROOT), 'fixed_target')
|
||||
snapshot = source_snapshot(check_trace=check_trace)
|
||||
if target == SECOND_EXTENDED_ROOT:
|
||||
snapshot.update(prior_failed_P2=prior_p2_snapshot(snapshot['source_boot_id']),
|
||||
historical_reserved_calls=163500,
|
||||
cumulative_reserved_calls_if_launched=254500)
|
||||
return snapshot
|
||||
|
||||
|
||||
def create_adoption(*, parent_review, trusted_source_budget_sha256, target_root=None):
|
||||
"""Explicit parent review gate; writes only a new read-only, untrusted proposal."""
|
||||
_require(isinstance(parent_review, str) and bool(parent_review.strip()), 'explicit_parent_review_required')
|
||||
_require(digest(SOURCE_ROOT / 'budget.json') == trusted_source_budget_sha256,
|
||||
'reviewed_source_budget_digest')
|
||||
target = TARGET_ROOT if target_root is None else Path(target_root)
|
||||
snapshot = snapshot_for_target(target, check_trace=True)
|
||||
document = {'format': FORMAT, 'resource_profile': EXTENDED_PROFILE, 'target_root': str(target),
|
||||
'parent_review': parent_review, 'execution_authorized': False, 'accepted_skill': False,
|
||||
'P1_requirement': 'reviewed_interface_and_failure_evidence_not_physical_pass', **snapshot}
|
||||
# No local ledger, launch tree, reservation or clock is created by adoption.
|
||||
path = target / 'p1-adoption.json'
|
||||
_require(target == target.resolve(strict=True), 'target_root')
|
||||
durable_write(path, encode(document))
|
||||
path.chmod(0o444)
|
||||
sync_directory(target)
|
||||
return digest(path)
|
||||
|
||||
|
||||
def verify_adoption(root, trusted_sha256):
|
||||
path = Path(root) / 'p1-adoption.json'
|
||||
_require(Path(root) in (TARGET_ROOT, SECOND_EXTENDED_ROOT) and path.stat().st_mode & 0o222 == 0,
|
||||
'read_only_fixed_target')
|
||||
_require(isinstance(trusted_sha256, str) and len(trusted_sha256) == 64
|
||||
and digest(path) == trusted_sha256, 'independently_reviewed_digest')
|
||||
document = _json(path)
|
||||
expected = {'format': FORMAT, 'resource_profile': EXTENDED_PROFILE, 'target_root': str(root),
|
||||
'parent_review': document.get('parent_review'), 'execution_authorized': False,
|
||||
'accepted_skill': False,
|
||||
'P1_requirement': 'reviewed_interface_and_failure_evidence_not_physical_pass',
|
||||
**snapshot_for_target(Path(root))}
|
||||
_require(isinstance(document.get('parent_review'), str) and bool(document['parent_review'].strip())
|
||||
and document == expected, 'stale_mutated_or_forged_evidence')
|
||||
return document
|
||||
@@ -0,0 +1,940 @@
|
||||
"""Streaming CPU evidence audit. Clocks are not passed cycles; no simulator imports."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
from dataclasses import asdict
|
||||
from typing import TypedDict
|
||||
|
||||
from .evaluation_protocol import CYCLE_TICKS, PHASE_END_TICKS, PHYSICS_DT_S, Clock
|
||||
|
||||
FORMAT = 'skillfactory.contact-cycle-evaluation-evidence.v1'
|
||||
TRACE_ENCODING = 'jsonl-xz-finalized-chunks.v2'
|
||||
TRACE_FILENAME = 'trace.v2.jsonl.xz'
|
||||
MAX_RECORD_BYTES = 1024 * 1024
|
||||
MAX_CHUNK_RECORDS = 64
|
||||
MAX_CHUNK_RAW_BYTES = 8 * 1024 * 1024
|
||||
XZ_PRESET = 0 # liblzma preset 0: 256 KiB dictionary; independent streams.
|
||||
XZ_DECODER_MEMORY_BYTES = 8 * 1024 * 1024
|
||||
DT = PHYSICS_DT_S
|
||||
NOT_EVALUATED = 'not_evaluated'
|
||||
SCHEDULE_ROUNDOFF_S = 2e-6
|
||||
|
||||
|
||||
class AppliedEvent(TypedDict):
|
||||
event_index: int
|
||||
body_index: int
|
||||
envelope: float
|
||||
force_world: list[float]
|
||||
couple_world: list[float]
|
||||
point_world: list[float]
|
||||
com_world: list[float]
|
||||
frame_quat_xyzw: list[float]
|
||||
point_frame_quat_xyzw: list[float]
|
||||
point_frame_origin_world: list[float]
|
||||
|
||||
|
||||
class AppliedEvidence(TypedDict):
|
||||
"""Read-only pre-step capture, from the SAME unique writer invocation.
|
||||
|
||||
global_tick identifies the ensuing interval, i.e. pre-step substeps + 1.
|
||||
total_com_wrench is the actual setter buffer, not an independently recomposed
|
||||
command. events describe external contributions only; guide/auxiliary are
|
||||
checked separately against the captured state buffers.
|
||||
"""
|
||||
format: str # skillfactory.contact-cycle-applied-wrench.v1
|
||||
trial_index: int
|
||||
global_tick: int
|
||||
events: list[AppliedEvent]
|
||||
total_com_wrench: list[list[float]]
|
||||
|
||||
|
||||
def cross(a, b):
|
||||
return [a[1]*b[2]-a[2]*b[1], a[2]*b[0]-a[0]*b[2], a[0]*b[1]-a[1]*b[0]]
|
||||
|
||||
|
||||
def rotate(q, v):
|
||||
t = [2*x for x in cross(q[:3], v)]
|
||||
return [a + q[3]*b + c for a, b, c in zip(v, t, cross(q[:3], t))]
|
||||
|
||||
|
||||
def close(a, b, tolerance=1e-5):
|
||||
return len(a) == len(b) and all(abs(x-y) <= tolerance for x, y in zip(a, b))
|
||||
|
||||
|
||||
def plain(value):
|
||||
"""Independent JSON-compatible copy, also accepting protocol immutable mappings."""
|
||||
# Exact immutable JSON scalars need no deepcopy; subclasses retain the old path.
|
||||
if value is None or type(value) in (str, bool, int, float):
|
||||
return value
|
||||
if hasattr(value, 'items'):
|
||||
return {k: plain(v) for k, v in value.items()}
|
||||
if isinstance(value, (tuple, list)):
|
||||
return [plain(v) for v in value]
|
||||
return copy.deepcopy(value)
|
||||
|
||||
|
||||
def fingerprint(value):
|
||||
return hashlib.sha256(json.dumps(value, sort_keys=True, allow_nan=False,
|
||||
separators=(',', ':')).encode()).hexdigest()
|
||||
|
||||
|
||||
def finite(value):
|
||||
if isinstance(value, dict):
|
||||
return all(finite(v) for v in value.values())
|
||||
if isinstance(value, (list, tuple)):
|
||||
return all(finite(v) for v in value)
|
||||
return not isinstance(value, float) or math.isfinite(value)
|
||||
|
||||
|
||||
def norm(v):
|
||||
return math.sqrt(sum(x * x for x in v))
|
||||
|
||||
|
||||
def sub(a, b):
|
||||
return [x - y for x, y in zip(a, b, strict=True)]
|
||||
|
||||
|
||||
def mean(values):
|
||||
return sum(values) / len(values)
|
||||
|
||||
|
||||
def longest(values):
|
||||
best = current = 0
|
||||
for value in values:
|
||||
current = current + 1 if value else 0
|
||||
best = max(best, current)
|
||||
return best
|
||||
|
||||
|
||||
def vector(value, size):
|
||||
return (isinstance(value, list) and len(value) == size
|
||||
and all(type(x) in (int, float) and math.isfinite(x) for x in value))
|
||||
|
||||
|
||||
# Every field is mandatory. Nonfinite records are retained in the raw stream, never repaired.
|
||||
SCALARS = ('weight', 'gap', 'tilt', 'slip_speed', 'limit_ratio', 'joint_excess', 'time',
|
||||
'contact_timer', 'separation_timer', 'acquisition_timer', 'anchor_height')
|
||||
BOOLS = ('contact', 'separated', 'premature', 'acquired', 'acquisition_failed', 'armed',
|
||||
'load_off', 'liftoff', 'touchdown')
|
||||
VECTORS = {'foot': 3, 'normal': 3, 'friction': 3, 'root': 13, 'q': 3, 'qdot': 3, 'torque': 3,
|
||||
'processed_target': 3, 'executed': 3, 'residual_request': 3, 'effective_residual_rad': 3,
|
||||
'ik_target': 3, 'q_ik': 3, 'reference_action': 3, 'sensed': 18, 'policy': 46,
|
||||
'manager_action': 3, 'manager_previous_action': 3, 'env_origin': 3}
|
||||
STATE_FIELDS = (*SCALARS, *BOOLS, *VECTORS, 'onset_phase', 'edge_phase', 'refreshes', 'substeps',
|
||||
'external', 'guide', 'auxiliary', 'events', 'sensor_delay', 'action_delay',
|
||||
'rng', 'actuator_state', 'reward_components', 'counters', 'scenario', 'anchors',
|
||||
'event_program', 'body_names', 'applied')
|
||||
|
||||
|
||||
def validate_state(s):
|
||||
if not isinstance(s, dict):
|
||||
raise ValueError('state_not_object')
|
||||
missing = set(STATE_FIELDS) - s.keys()
|
||||
if missing:
|
||||
raise ValueError('missing_state:' + ','.join(sorted(missing)))
|
||||
if not finite(s):
|
||||
raise ValueError('nonfinite_state')
|
||||
for k in SCALARS:
|
||||
if type(s[k]) not in (int, float):
|
||||
raise ValueError('scalar:' + k)
|
||||
for k in BOOLS:
|
||||
if type(s[k]) is not bool:
|
||||
raise ValueError('boolean:' + k)
|
||||
for k, n in VECTORS.items():
|
||||
if not vector(s[k], n):
|
||||
raise ValueError('vector:' + k)
|
||||
for k in ('onset_phase', 'edge_phase', 'refreshes', 'substeps', 'scenario'):
|
||||
if type(s[k]) is not int:
|
||||
raise ValueError('integer:' + k)
|
||||
if (s['weight'] <= 0 or s['slip_speed'] < 0 or s['limit_ratio'] < 0 or s['joint_excess'] < 0
|
||||
or abs(norm(s['root'][3:7]) - 1) > 1e-5):
|
||||
raise ValueError('invalid_physical_scalar_or_quaternion')
|
||||
if not s['body_names'] or len(set(s['body_names'])) != len(s['body_names']):
|
||||
raise ValueError('body_names')
|
||||
for k in ('external', 'guide', 'auxiliary'):
|
||||
if len(s[k]) != len(s['body_names']) or not all(vector(v, 6) for v in s[k]):
|
||||
raise ValueError('wrench:' + k)
|
||||
for k, width in (('sensor_delay', 18), ('action_delay', 3)):
|
||||
if not s[k] or not all(vector(v, width) for v in s[k]):
|
||||
raise ValueError('delay:' + k)
|
||||
if (set(s['anchors']) != {'anchor_a_world', 'root_origin_world', 'initial_root_world'}
|
||||
or not all(vector(v, 3) for v in s['anchors'].values())):
|
||||
raise ValueError('anchors')
|
||||
for k in ('reset_calls', 'pose_write_calls', 'composer_buffer_replacements', 'initialization_steps',
|
||||
'rollout_steps', 'attempted_steps', 'completed_steps'):
|
||||
if type(s['counters'][k]) is not int or s['counters'][k] < 0:
|
||||
raise ValueError('counter:' + k)
|
||||
if not isinstance(s['rng'], dict) or not s['rng'] or not isinstance(s['actuator_state'], dict):
|
||||
raise ValueError('rng_or_actuator_state')
|
||||
if set(s['reward_components']) != {'task', 'effort', 'action_rate', 'root_position', 'root_velocity', 'residual'}:
|
||||
raise ValueError('reward_components')
|
||||
if len(s['events']) != len(s['event_program']):
|
||||
raise ValueError('event_count')
|
||||
for e in s['events']:
|
||||
if (set(e) != {'fired', 'completed', 'start', 'envelope', 'integral'}
|
||||
or type(e['fired']) is not bool or type(e['completed']) is not bool
|
||||
or any(type(e[k]) not in (int, float) for k in ('start', 'envelope', 'integral'))):
|
||||
raise ValueError('event_shape')
|
||||
|
||||
|
||||
def carry_state(s):
|
||||
"""Everything that a metadata transition + one IK refresh must leave bit-identical."""
|
||||
allowed = {'ik_target', 'q_ik', 'reference_action', 'refreshes', 'policy', 'reward_components'}
|
||||
return {k: v for k, v in s.items() if k not in allowed}
|
||||
|
||||
|
||||
class TrialAudit:
|
||||
"""Consumes initial/control/tick/seam/next_reference records in runtime order.
|
||||
|
||||
Gates become determinate at the *last included sample*, not a later control
|
||||
boundary. After the first failure only terminal evidence is admissible.
|
||||
"""
|
||||
def __init__(self, protocol, trial_index):
|
||||
self.protocol, self.trial = protocol, protocol.trial(trial_index)
|
||||
thresholds = protocol.document['thresholds']
|
||||
self.f, self.m, self.r = (thresholds[k] for k in ('functional', 'P1_margins', 'original_runtime'))
|
||||
self.initial = self.last = self.reference = self.control = None
|
||||
self.tick = 0
|
||||
self.first_failure = None
|
||||
self.cycles = []
|
||||
self.frames = []
|
||||
self.total_slip = 0.
|
||||
self.admitted = []
|
||||
self.seams = []
|
||||
self.needs_reference = False
|
||||
self.gates = {}
|
||||
self.margins = {}
|
||||
self.metrics = {}
|
||||
self._cycle_start()
|
||||
self.event_integrals = None
|
||||
self.event_previous = None
|
||||
self.delivery = []
|
||||
self.recovery = {'status': NOT_EVALUATED, 'time_s': None, 'definition':
|
||||
'first 0.1s after final pulse; root xy<=.03,z<=.06,tilt<=.3; original phase bounds'}
|
||||
self.recovery_run = 0
|
||||
self.terminal = None
|
||||
self.step_results = []
|
||||
self.all_causes = []
|
||||
|
||||
def _cycle_start(self):
|
||||
self.gates = {k: NOT_EVALUATED for k in (
|
||||
'support_ground_support', 'unloaded', 'real_flight', 'three_dimensional_command', 'xy_swing_motion',
|
||||
'reload_ground_support', 'landing_position', 'contact_acquired', 'complete_clock',
|
||||
'runtime_safety', 'condition_identity', 'event_delivery')}
|
||||
self.margins = {k: NOT_EVALUATED for k in (
|
||||
'root_horizontal', 'root_z', 'seam_root_drift', 'reload_mean_position', 'reload_position',
|
||||
'cycle_slip', 'run_slip', 'repeat_B_drift', 'unload_ratio', 'lift_dwell', 'reload_dwell')}
|
||||
self.metrics = {}
|
||||
|
||||
def fail(self, causes, *, kind='tick', tick=None):
|
||||
causes = list(dict.fromkeys(causes))
|
||||
if not causes:
|
||||
return ()
|
||||
self.all_causes = list(dict.fromkeys(self.all_causes + causes))
|
||||
tick = self.tick if tick is None else tick
|
||||
if self.first_failure is None:
|
||||
clock = self.protocol.evidence_clock(self.trial.index, tick) if tick else Clock(0, 0, 0)
|
||||
self.first_failure = {'global_tick': tick, 'time_s': tick * DT, 'cycle_index': clock.cycle_index,
|
||||
'local_tick': clock.local_tick, 'kind': kind, 'causes': causes}
|
||||
if self.last is not None:
|
||||
self.first_failure['phase'] = self.last.get('event', {}).get('command', {}).get('phase')
|
||||
elif self.first_failure['global_tick'] == tick:
|
||||
self.first_failure['causes'] = list(dict.fromkeys(self.first_failure['causes'] + causes))
|
||||
return tuple(causes)
|
||||
|
||||
def consume(self, record):
|
||||
"""Return ALL current causes; malformed evidence is a fatal recording cause."""
|
||||
if not isinstance(record, dict):
|
||||
return self.fail(('recording_invalid:record_not_object',), kind='unknown')
|
||||
try:
|
||||
return self._consume(record)
|
||||
except (KeyError, TypeError, ValueError, IndexError, OverflowError) as exc:
|
||||
event = record.get('event')
|
||||
event = event if isinstance(event, dict) else {}
|
||||
clock = event.get('clock')
|
||||
clock = clock if isinstance(clock, dict) else {}
|
||||
g = clock.get('global_tick', self.tick)
|
||||
if type(g) is not int or not 0 <= g <= self.trial.total_ticks:
|
||||
g = self.tick
|
||||
if record.get('kind') == 'tick' and g == self.tick + 1:
|
||||
self.tick = g
|
||||
self.last = plain(record)
|
||||
stop = record.get('runtime_stop', record.get('stop'))
|
||||
runtime_causes = stop.get('causes', []) if isinstance(stop, dict) else event.get('causes', [])
|
||||
if not isinstance(runtime_causes, list) or any(not isinstance(c, str) for c in runtime_causes):
|
||||
runtime_causes = []
|
||||
return self.fail((*runtime_causes, f'recording_invalid:{exc}'),
|
||||
kind=record.get('kind', 'unknown'), tick=g)
|
||||
|
||||
def _stop_causes(self, stop):
|
||||
if not isinstance(stop, dict):
|
||||
raise ValueError('terminal_stop_shape')
|
||||
integer_fields = ('trial_index', 'physics_ticks', 'completed_controls', 'partial_control_ticks',
|
||||
'completed_clock_cycles', 'all_sim_steps_attempted', 'all_sim_steps_completed',
|
||||
'initialization_steps', 'rollout_steps', 'reset_calls', 'pose_write_calls',
|
||||
'composer_buffer_replacements')
|
||||
if (set(stop) != {*integer_fields, 'reason', 'clock', 'causes', 'fatal'}
|
||||
or any(type(stop[k]) is not int or stop[k] < 0 for k in integer_fields)
|
||||
or type(stop['fatal']) is not bool or not isinstance(stop['causes'], list)
|
||||
or any(not isinstance(c, str) or not c for c in stop['causes'])):
|
||||
raise ValueError('terminal_stop_shape')
|
||||
g = stop['physics_ticks']
|
||||
clock = self.protocol.evidence_clock(self.trial.index, g) if g else Clock(0, 0, 0)
|
||||
if (stop['trial_index'] != self.trial.index or g != self.tick or stop['clock'] != asdict(clock)
|
||||
or stop['completed_controls'] != g // 5 or stop['partial_control_ticks'] != g % 5
|
||||
or stop['completed_clock_cycles'] != g // CYCLE_TICKS):
|
||||
raise ValueError('terminal_clock')
|
||||
if (stop['reason'] not in ('failure', 'protocol_complete')
|
||||
or (stop['reason'] == 'failure') != bool(stop['causes'])
|
||||
or stop['reason'] == 'protocol_complete' and g != self.trial.total_ticks):
|
||||
raise ValueError('terminal_reason')
|
||||
causes = list(stop['causes'])
|
||||
fatal = any(c.startswith(('nonfinite', 'hardware', 'identity', 'illegal_', 'storage', 'recording',
|
||||
'budget', 'process', 'infrastructure', 'guide_', 'auxiliary_')) for c in causes)
|
||||
if stop['fatal'] != fatal:
|
||||
causes.append('recording_terminal_fatal_classification')
|
||||
if self.last is not None:
|
||||
counters = self.last['state']['counters']
|
||||
names = {'all_sim_steps_attempted': 'attempted_steps', 'all_sim_steps_completed': 'completed_steps',
|
||||
**{k: k for k in integer_fields[7:]}}
|
||||
if any(stop[k] != counters[v] for k, v in names.items()):
|
||||
causes.append('recording_terminal_counter_mismatch')
|
||||
return causes
|
||||
|
||||
def _step_result(self, record):
|
||||
n = record['ticks_advanced']
|
||||
prior = sum(s['ticks_advanced'] for s in self.step_results)
|
||||
if (set(record) != {'kind', 'ticks_advanced', 'observed_tick', 'reward', 'has_next_observation', 'stop'}
|
||||
or type(n) is not int or not 0 <= n <= 5 or type(record['observed_tick']) is not int
|
||||
or record['observed_tick'] != self.tick or prior + n != self.tick
|
||||
or type(record['has_next_observation']) is not bool
|
||||
or n < 5 and record['reward'] is not None
|
||||
or record['reward'] is not None and not vector(record['reward'], 1)):
|
||||
raise ValueError('partial_step_result')
|
||||
if self.step_results and self.step_results[-1]['stop'] is not None:
|
||||
raise ValueError('step_after_stop')
|
||||
if record['stop'] is None:
|
||||
if n != 5 or not record['has_next_observation'] or record['reward'] is None or self.first_failure:
|
||||
raise ValueError('continuing_step_result')
|
||||
causes = ()
|
||||
else:
|
||||
if record['has_next_observation']:
|
||||
raise ValueError('stopped_next_observation')
|
||||
causes = self._stop_causes(record['stop'])
|
||||
self.step_results.append(plain(record))
|
||||
return self.fail(causes, kind='step_result')
|
||||
|
||||
def _terminal(self, record):
|
||||
if set(record) != {'kind', 'runtime_stop', 'external_failure', 'recording_faults'}:
|
||||
raise ValueError('terminal_fields')
|
||||
self.terminal = plain(record) # Retain even an invalid terminal for offline diagnosis.
|
||||
stop, external, faults = record['runtime_stop'], record['external_failure'], record['recording_faults']
|
||||
if not isinstance(faults, list) or any(not isinstance(c, str) or not c for c in faults):
|
||||
raise ValueError('terminal_faults')
|
||||
causes = list(faults)
|
||||
if stop is None and external is None:
|
||||
raise ValueError('missing_terminal_reason')
|
||||
if external is not None:
|
||||
if (not isinstance(external, dict) or set(external) != {'causes', 'fatal', 'context'}
|
||||
or external['fatal'] is not True or not isinstance(external['context'], dict)
|
||||
or not isinstance(external['causes'], list) or not external['causes']
|
||||
or any(not isinstance(c, str) or not c for c in external['causes'])):
|
||||
raise ValueError('runner_terminal')
|
||||
causes.extend(external['causes'])
|
||||
if stop is not None:
|
||||
causes.extend(self._stop_causes(stop))
|
||||
if self.step_results and self.step_results[-1]['stop'] != stop:
|
||||
causes.append('recording_terminal_step_stop_mismatch')
|
||||
if sum(s['ticks_advanced'] for s in self.step_results) != self.tick:
|
||||
causes.append('recording_missing_step_results')
|
||||
return self.fail(causes, kind='terminal')
|
||||
|
||||
def _control(self, record):
|
||||
if (set(record) != {'kind', 'origin_tick', 'observation', 'action', 'mean', 'std'}
|
||||
or type(record['origin_tick']) is not int
|
||||
or self.initial is None or self.needs_reference or self.control is not None
|
||||
or record['origin_tick'] != self.tick):
|
||||
raise ValueError('control_order')
|
||||
if not vector(record['observation'], 46) or not vector(record['action'], 3):
|
||||
raise ValueError('actor_shape')
|
||||
learned = self.trial.controller_kind == 'learned_policy'
|
||||
if learned:
|
||||
if (not vector(record['mean'], 3) or not vector(record['std'], 3)
|
||||
or any(x <= 0 for x in record['std'])):
|
||||
raise ValueError('actor_metadata')
|
||||
if any(abs(a - math.tanh(m)) > 1e-6 for a, m in zip(record['action'], record['mean'])):
|
||||
raise ValueError('deterministic_actor_action')
|
||||
elif record['mean'] is not None or record['std'] is not None or any(record['action']):
|
||||
raise ValueError('reference_actor_metadata')
|
||||
if record['observation'] != self.reference['state']['policy']:
|
||||
raise ValueError('actor_observation_provenance')
|
||||
self.control = plain(record)
|
||||
return ()
|
||||
|
||||
def _reference_event(self, record, kind, s, e, g):
|
||||
if kind == 'seam':
|
||||
if (g != self.tick or not g or g % CYCLE_TICKS or g == self.trial.total_ticks
|
||||
or g in self.admitted or len(self.cycles) != g // CYCLE_TICKS
|
||||
or not self.cycles[-1]['passed'] or self.last != {**record, 'kind': 'tick'}):
|
||||
raise ValueError('seam_not_completed_passing_or_state_mutation')
|
||||
self.admitted.append(g)
|
||||
self.seams.append({'tick': g, 'pre': fingerprint(s), 'carry_pre': fingerprint(carry_state(s)),
|
||||
'post': None, 'carry_post': None})
|
||||
return ()
|
||||
if kind == 'next_reference':
|
||||
if not self.needs_reference or g != self.tick or self.last is None:
|
||||
raise ValueError('duplicate_or_skipped_reference')
|
||||
before = self.last['state']
|
||||
if carry_state(before) != carry_state(s) or s['refreshes'] != before['refreshes'] + 1:
|
||||
raise ValueError('reference_refresh_mutated_carry_state')
|
||||
if g % CYCLE_TICKS == 0:
|
||||
self.seams[-1].update(post=fingerprint(s), carry_post=fingerprint(carry_state(s)))
|
||||
self.reference = plain(record)
|
||||
self.needs_reference = False
|
||||
return self.fail(e['causes'], kind=kind)
|
||||
if kind == 'initial':
|
||||
if e['reference_used_clock'] is not None:
|
||||
raise ValueError('initial_held_reference')
|
||||
if any(event != {'fired': False, 'completed': False, 'start': 0., 'envelope': 0., 'integral': 0.}
|
||||
for event in s['events']):
|
||||
raise ValueError('initial_event_schedule')
|
||||
if any(abs(x) > 1e-6 for v in s['external'] for x in v):
|
||||
raise ValueError('initial_external_wrench')
|
||||
self.last = plain(record)
|
||||
self.event_previous = plain(record)
|
||||
return self.fail(e['causes'], kind=kind)
|
||||
return None
|
||||
|
||||
def _event_shape(self, record, kind):
|
||||
s, e = record['state'], record['event']
|
||||
if set(record) != {'kind', 'state', 'event'} or set(e) != {
|
||||
'kind', 'trial_index', 'clock', 'command', 'held_control_index', 'action_origin_tick',
|
||||
'reference_used_clock', 'reference_used', 'reference_next_clock', 'reference_next', 'causes'
|
||||
}:
|
||||
raise ValueError('event_fields')
|
||||
if (not isinstance(e['causes'], list) or any(not isinstance(c, str) or not c for c in e['causes'])
|
||||
or not vector(e['reference_used'], 3) or not vector(e['reference_next'], 3)
|
||||
or type(e['trial_index']) is not int):
|
||||
raise ValueError('event_types')
|
||||
for name in ('clock', 'reference_next_clock', 'reference_used_clock'):
|
||||
value = e[name]
|
||||
if value is None and name == 'reference_used_clock':
|
||||
continue
|
||||
if (not isinstance(value, dict) or set(value) != {'global_tick', 'cycle_index', 'local_tick'}
|
||||
or any(type(x) is not int for x in value.values())):
|
||||
raise ValueError('clock_types')
|
||||
validate_state(s)
|
||||
if not finite(e) or e['trial_index'] != self.trial.index or e['kind'] != ('tick' if kind == 'seam' else kind):
|
||||
raise ValueError('event_identity')
|
||||
if e['clock'] != asdict(Clock(**e['clock'])):
|
||||
raise ValueError('clock_shape')
|
||||
return s, e
|
||||
|
||||
def _held_action(self, s, e, g):
|
||||
if self.needs_reference or g != self.tick + 1 or self.control is None:
|
||||
raise ValueError('duplicate_skipped_tick_or_missing_control')
|
||||
if (e['held_control_index'] != (g - 1) // 5 or e['action_origin_tick'] != 5 * ((g - 1) // 5)
|
||||
or e['action_origin_tick'] != self.control['origin_tick']
|
||||
or e['reference_used_clock'] != self.reference['event']['clock']
|
||||
or e['reference_used'] != self.reference['event']['reference_next']
|
||||
or e['reference_next_clock'] != self.reference['event']['clock']
|
||||
or e['reference_next'] != e['reference_used']
|
||||
or s['refreshes'] != self.reference['state']['refreshes']):
|
||||
raise ValueError('held_action_provenance')
|
||||
if any(abs(a - b) > 1e-6 for a, b in zip(s['residual_request'], self.control['action'])):
|
||||
raise ValueError('requested_residual_provenance')
|
||||
for ref, req, actual, delta in zip(e['reference_used'], s['residual_request'], s['executed'],
|
||||
s['effective_residual_rad']):
|
||||
full = max(-1., min(1., ref + max(-1., min(1., req)) * .1))
|
||||
if abs(actual - full) > 1e-6 or abs(delta - (full - ref) * .5) > 1e-6:
|
||||
raise ValueError('residual_composition')
|
||||
if s['q_ik'] != self.reference['state']['q_ik']:
|
||||
raise ValueError('IK_changed_between_refreshes')
|
||||
if (s['counters']['rollout_steps'] - self.initial['state']['counters']['rollout_steps'] != g
|
||||
or s['counters']['completed_steps'] - self.initial['state']['counters']['completed_steps'] != g):
|
||||
raise ValueError('unobserved_physics_steps')
|
||||
|
||||
def _consume(self, record):
|
||||
kind = record['kind']
|
||||
if self.terminal is not None:
|
||||
raise ValueError('recording_after_terminal')
|
||||
if kind == 'step_result':
|
||||
return self._step_result(record)
|
||||
if kind == 'terminal':
|
||||
return self._terminal(record)
|
||||
if kind == 'capture_fault':
|
||||
causes = self.fail(record['causes'], kind=kind, tick=record['event']['clock']['global_tick'])
|
||||
if self.first_failure['global_tick'] == record['event']['clock']['global_tick']:
|
||||
self.first_failure['phase'] = record['event'].get('command', {}).get('phase')
|
||||
return causes
|
||||
if self.first_failure:
|
||||
return self.fail(('recording_after_failure',), kind=kind)
|
||||
if kind == 'control':
|
||||
return self._control(record)
|
||||
if kind not in ('initial', 'tick', 'next_reference', 'seam'):
|
||||
raise ValueError('record_kind')
|
||||
s, e = self._event_shape(record, kind)
|
||||
g = e['clock']['global_tick']
|
||||
if type(g) is not int or s['substeps'] != g or abs(s['time'] - g * DT) > 1e-5:
|
||||
raise ValueError('physical_clock')
|
||||
if kind == 'initial':
|
||||
if self.initial is not None or g != 0:
|
||||
raise ValueError('duplicate_initial')
|
||||
clock = self.protocol.next_command_clock(self.trial.index, 0)
|
||||
self.initial = plain(record)
|
||||
self.reference = plain(record)
|
||||
else:
|
||||
if self.initial is None:
|
||||
raise ValueError('missing_initial')
|
||||
clock = (self.protocol.evidence_clock(self.trial.index, g) if kind in ('tick', 'seam') else
|
||||
self.protocol.next_command_clock(self.trial.index, g, seam_admitted=g in self.admitted))
|
||||
if (s['anchors'] != self.initial['state']['anchors']
|
||||
or s['env_origin'] != self.initial['state']['env_origin']):
|
||||
raise ValueError('recentered_anchors')
|
||||
for k in ('reset_calls', 'pose_write_calls', 'initialization_steps'):
|
||||
if s['counters'][k] != self.initial['state']['counters'][k]:
|
||||
raise ValueError('illegal_state_reset:' + k)
|
||||
if clock is None or e['clock'] != asdict(clock):
|
||||
raise ValueError('command_clock')
|
||||
command = self.protocol.command(self.trial.index, clock,
|
||||
anchor_a_world=s['anchors']['anchor_a_world'],
|
||||
root_origin_world=s['anchors']['root_origin_world'], weight_N=s['weight'])
|
||||
if e['command'] != plain(asdict(command)) or s['weight'] != self.initial['state']['weight']:
|
||||
raise ValueError('command_or_weight')
|
||||
local = rotate([-x for x in s['root'][3:6]] + [s['root'][6]],
|
||||
sub(e['command']['target_world_m'], s['root'][:3]))
|
||||
if not close(local, s['ik_target']):
|
||||
raise ValueError('IK_world_to_actual_body_coordinates')
|
||||
if s['scenario'] != self.trial.scenario_id:
|
||||
raise ValueError('condition_scenario')
|
||||
program = s['event_program']
|
||||
selected = [i for i, p in enumerate(program) if p['scenario'] == s['scenario']]
|
||||
if selected != list(self.trial.event_indices):
|
||||
raise ValueError('condition_event_indices')
|
||||
if self.protocol.document['events'] and program != plain(self.protocol.document['events']):
|
||||
raise ValueError('condition_event_program')
|
||||
if program != self.initial['state']['event_program']:
|
||||
raise ValueError('changed_event_program')
|
||||
if kind in ('initial', 'next_reference'):
|
||||
if e['held_control_index'] is not None or e['action_origin_tick'] is not None:
|
||||
raise ValueError('reference_labeled_as_action')
|
||||
if e['reference_next_clock'] != e['clock'] or e['reference_next'] != s['reference_action']:
|
||||
raise ValueError('reference_next_provenance')
|
||||
handled = self._reference_event(record, kind, s, e, g)
|
||||
if handled is not None:
|
||||
return handled
|
||||
self._held_action(s, e, g)
|
||||
self.tick = g
|
||||
self.last = plain(record)
|
||||
self.frames.append({'state': {k: s[k] for k in ('foot', 'normal', 'gap', 'root', 'weight',
|
||||
'onset_phase', 'contact', 'separated')}, 'command': e['command']})
|
||||
causes = list(e['causes']) + self._instant(s, command, clock)
|
||||
causes += self._windows(clock)
|
||||
causes += self._events(s, clock)
|
||||
if g % 5 == 0:
|
||||
self.control = None
|
||||
self.needs_reference = g != self.trial.total_ticks
|
||||
result = self.fail(causes)
|
||||
if clock.local_tick == CYCLE_TICKS:
|
||||
self.gates['complete_clock'] = len(self.frames) == CYCLE_TICKS
|
||||
self.gates['runtime_safety'] = not bool(result)
|
||||
self.gates['condition_identity'] = True
|
||||
self._finish_cycle(clock, result)
|
||||
if self.first_failure:
|
||||
result = tuple(self.first_failure['causes'])
|
||||
return result
|
||||
|
||||
def _gate(self, name, passed, causes, *, margin=False):
|
||||
(self.margins if margin else self.gates)[name] = bool(passed)
|
||||
if not passed and (not margin or self.protocol.document['stage'] == 'P1'):
|
||||
causes.append(('P1_' if margin else '') + name)
|
||||
|
||||
def _instant(self, s, c, clock):
|
||||
f, m, r = self.f, self.m, self.r
|
||||
p, t, fn, w, gap = c.phase, clock.local_tick, s['normal'][2], s['weight'], s['gap']
|
||||
error = sub(s['root'][:3], c.root_target_world_m)
|
||||
causes = []
|
||||
checks = {
|
||||
'contact_acquisition_timeout': s['acquisition_failed'] or (self.tick >= 100 and not s['acquired']),
|
||||
'premature_separation': s['premature'],
|
||||
'lift_deadline': p == 2 and c.progress > r['lift_progress_strictly_greater'] and (
|
||||
gap < r['lift_gap_m_min'] or fn > r['lift_normal_N_max']),
|
||||
'swing_clearance': p == 3 and gap < r['swing_gap_m_min'],
|
||||
'reload_deadline': p == 5 and c.progress > r['reload_progress_strictly_greater']
|
||||
and fn < r['reload_load_fraction_min'] * w,
|
||||
'low_height': s['root'][2] < s['anchor_height'] - r['root_height_below_nominal_m_max'],
|
||||
'root_height_error': abs(error[2]) > f['root_height_error_m_max'],
|
||||
'tilt': s['tilt'] > f['root_tilt_rad_max'],
|
||||
'negative_normal': fn < -f['normal_force_negative_tolerance_N'],
|
||||
'ground_penetration': gap < -f['ground_penetration_m_max'],
|
||||
'hardware_effort_velocity': s['limit_ratio'] > f['normalized_effort_velocity_max'],
|
||||
'hardware_joint_limit': s['joint_excess'] > f['joint_limit_excess_rad_max'],
|
||||
'guide_vertical': any(v[2] != r['guide_vertical_N_exact'] for v in s['guide']),
|
||||
'auxiliary_force': sum(v[2] for v in s['auxiliary']) > f['auxiliary_vertical_N_max'],
|
||||
'auxiliary_geometry': any(abs(v[0]) > 1e-6 or abs(v[1]) > 1e-6 or v[2] < -1e-6
|
||||
or abs(v[5]) > 1e-6 or norm(v[3:]) > f['auxiliary_lever_arm_m_max'] * max(v[2], 0) + 1e-6
|
||||
for v in s['auxiliary']),
|
||||
'auxiliary_support_phase': p == 0 and any(abs(x) > 1e-6 for v in s['auxiliary'] for x in v),
|
||||
}
|
||||
causes.extend(k for k, hit in checks.items() if hit)
|
||||
if self.tick >= 100:
|
||||
self.gates['contact_acquired'] = s['acquired']
|
||||
slip = s['slip_speed'] * DT if p in (0, 5) else 0.
|
||||
self.total_slip += slip
|
||||
self.metrics['stance_slip_m'] = self.metrics.get('stance_slip_m', 0.) + slip
|
||||
for name, value in (('root_horizontal_error_m', norm(error[:2])), ('root_absolute_z_error_m', abs(error[2])),
|
||||
('tilt_rad', s['tilt']), ('peak_impact_over_weight', fn / w),
|
||||
('root_displacement_from_initial_m', norm(sub(s['root'][:3],
|
||||
s['anchors']['initial_root_world'])))):
|
||||
self.metrics['max_' + name] = max(value, self.metrics.get('max_' + name, 0.))
|
||||
margins = {'root_horizontal': norm(error[:2]) <= m['root_horizontal_error_m_max'],
|
||||
'root_z': abs(error[2]) <= m['root_absolute_z_error_m_max'],
|
||||
'cycle_slip': self.metrics['stance_slip_m'] <= m['stance_slip_per_cycle_m_max'],
|
||||
'run_slip': self.total_slip <= m['stance_slip_per_run_m_max']}
|
||||
if t >= 4400:
|
||||
margins['reload_position'] = (norm(sub(s['foot'], c.target_world_m))
|
||||
<= m['reload_instantaneous_3d_error_m_max'])
|
||||
if t == CYCLE_TICKS:
|
||||
drift = norm(sub(s['root'][:2], s['anchors']['initial_root_world'][:2]))
|
||||
self.metrics['seam_root_horizontal_drift_m'] = drift
|
||||
margins['seam_root_drift'] = drift <= m['seam_to_initial_root_horizontal_drift_m_max']
|
||||
for name, passed in margins.items():
|
||||
self._gate(name, passed and self.margins[name] is not False, causes, margin=True)
|
||||
if not s['separated'] and s['separation_timer'] > 0 and gap >= .001:
|
||||
self.metrics.setdefault('liftoff_onset_time_s', clock.local_time_s - s['separation_timer'] + DT)
|
||||
if s['liftoff']:
|
||||
self.metrics.setdefault('liftoff_onset_time_s', None)
|
||||
self.metrics.setdefault('liftoff_edge_local_tick', t)
|
||||
self.metrics.setdefault('liftoff_onset_phase', s['edge_phase'])
|
||||
return causes
|
||||
|
||||
def _windows(self, clock):
|
||||
t, f, m = clock.local_tick, self.f, self.m
|
||||
causes = []
|
||||
states = None
|
||||
if t in (1499, 1999, m['lift_deadline_local_tick'], 2999, CYCLE_TICKS):
|
||||
states = [x['state'] for x in self.frames]
|
||||
for name, end, start in (('support', 1499, 1250), ('unload', 1999, 1950), ('reload', 4500, 4400)):
|
||||
if t != end:
|
||||
continue
|
||||
window = states[start - 1:end]
|
||||
contact = mean([s['normal'][2] > f['contact_force_on_N'] for s in window])
|
||||
load = mean([s['normal'][2] / s['weight'] for s in window])
|
||||
self.metrics[name + '_contact_fraction'] = contact
|
||||
self.metrics[name + '_load_fraction'] = load
|
||||
if name != 'unload':
|
||||
self._gate(name + '_ground_support', contact >= f['support_reload_contact_fraction_min']
|
||||
and load >= f['support_reload_load_fraction_min'], causes)
|
||||
else:
|
||||
ratio = load / max(self.metrics['support_load_fraction'], 1e-6)
|
||||
self.metrics['unload_remaining_support_fraction'] = ratio
|
||||
self._gate('unloaded', ratio <= f['unload_remaining_support_fraction_max'], causes)
|
||||
self._gate('unload_ratio', ratio <= m['unload_remaining_support_fraction_max'], causes, margin=True)
|
||||
self.metrics['unload_min_separation_margin_m'] = min(.001 - s['gap'] for s in states[1499:1999])
|
||||
if t == m['lift_deadline_local_tick']:
|
||||
lift = states[1999:t]
|
||||
valid = [s['gap'] >= m['lift_gap_m_min'] and s['normal'][2] <= m['lift_normal_N_max']
|
||||
and s['onset_phase'] == m['lift_onset_phase'] for s in lift]
|
||||
dwell = longest(valid)
|
||||
self.metrics['lift_longest_dwell_ticks_by_deadline'] = dwell
|
||||
self._gate('lift_dwell', dwell >= m['lift_dwell_ticks'], causes, margin=True)
|
||||
first = next((i for i in range(m['lift_dwell_ticks'] - 1, len(valid))
|
||||
if all(valid[i - m['lift_dwell_ticks'] + 1:i + 1])), None)
|
||||
self.metrics['lift_dwell_completed_local_tick'] = None if first is None else first + 2000
|
||||
self.metrics['lift_deadline_reserve_s'] = None if first is None else (2270 - first - 2000) * DT
|
||||
if t == 2999:
|
||||
swing = states[2299:2999]
|
||||
air = [s['gap'] >= f['swing_gap_m_min'] and s['normal'][2] <= f['contact_force_on_N'] for s in swing]
|
||||
self.metrics['swing_air_fraction'] = mean(air)
|
||||
self.metrics['swing_contiguous_air_s'] = longest(air) * DT
|
||||
self._gate('real_flight', mean(air) >= f['swing_air_fraction_min']
|
||||
and longest(air) * DT >= f['swing_contiguous_air_s_min'], causes)
|
||||
requested = sub(self.frames[2998]['command']['target_world_m'][:2],
|
||||
self.frames[2298]['command']['target_world_m'][:2])
|
||||
actual = sub(states[2998]['foot'][:2], states[2298]['foot'][:2])
|
||||
progress = [a * (1 if r >= 0 else -1) / max(abs(r), 1e-6) for a, r in zip(actual, requested)]
|
||||
self.metrics['swing_xy_progress_fraction'] = progress
|
||||
self._gate('three_dimensional_command', all(abs(x) > .001 for x in requested), causes)
|
||||
self._gate('xy_swing_motion', all(x >= f['swing_xy_progress_fraction_min'] for x in progress), causes)
|
||||
self.metrics['swing_rms_m'] = math.sqrt(mean([norm(sub(x['state']['foot'],
|
||||
x['command']['target_world_m'])) ** 2 for x in self.frames[2299:2999]]))
|
||||
self.metrics['swing_min_gap_minus_10mm_m'] = min(s['gap'] for s in swing) - .01
|
||||
self.metrics['swing_min_gap_minus_historical_20mm_m'] = min(s['gap'] for s in swing) - .02
|
||||
if t == CYCLE_TICKS:
|
||||
window = self.frames[4399:4500]
|
||||
errors = [norm(sub(x['state']['foot'], x['command']['target_world_m'])) for x in window]
|
||||
self.metrics['landing_error_m'] = mean(errors)
|
||||
self.metrics['landing_max_error_m'] = max(errors)
|
||||
foot_mean = [mean([x['state']['foot'][j] for x in window]) for j in range(3)]
|
||||
self.metrics['reload_mean_foot_world_m'] = foot_mean
|
||||
self.metrics['reload_signed_anchor_error_m'] = sub(foot_mean, window[-1]['command']['target_world_m'])
|
||||
self._gate('landing_position', mean(errors) <= f['landing_position_error_m_max'], causes)
|
||||
self._gate('reload_mean_position', mean(errors) <= m['reload_mean_3d_error_m_max'], causes, margin=True)
|
||||
valid = [s['gap'] <= m['reload_gap_m_max'] and
|
||||
m['reload_load_fraction_min'] <= s['normal'][2] / s['weight'] <= m['reload_load_fraction_max']
|
||||
and s['contact'] and not s['separated'] for s in states]
|
||||
tail = 0
|
||||
for ok in reversed(valid):
|
||||
if not ok:
|
||||
break
|
||||
tail += 1
|
||||
self.metrics['reload_final_dwell_ticks'] = tail
|
||||
self._gate('reload_dwell', tail >= m['reload_final_dwell_ticks'], causes, margin=True)
|
||||
if clock.cycle_index == 2:
|
||||
drift = norm(sub(foot_mean[:2], self.cycles[0]['metrics']['reload_mean_foot_world_m'][:2]))
|
||||
self.metrics['repeat_B_reload_mean_xy_drift_m'] = drift
|
||||
self._gate('repeat_B_drift', drift <= m['repeat_B_reload_mean_xy_drift_m_max'], causes, margin=True)
|
||||
return causes
|
||||
|
||||
def _applied(self, s, clock):
|
||||
if not self.trial.event_indices:
|
||||
if any(abs(x) > 1e-6 for v in s['external'] for x in v):
|
||||
raise ValueError('unexpected_external_wrench')
|
||||
return {}
|
||||
applied = s['applied']
|
||||
if (not isinstance(applied, dict) or set(applied) != {'format', 'trial_index', 'global_tick',
|
||||
'events', 'total_com_wrench'}
|
||||
or applied['format'] != 'skillfactory.contact-cycle-applied-wrench.v1'
|
||||
or type(applied['trial_index']) is not int or type(applied['global_tick']) is not int
|
||||
or applied['trial_index'] != self.trial.index or applied['global_tick'] != clock.global_tick):
|
||||
raise ValueError('missing_or_stale_prephysics_applied_evidence')
|
||||
if [e['event_index'] for e in applied['events']] != list(self.trial.event_indices):
|
||||
raise ValueError('applied_event_identity')
|
||||
external = [[0.] * 6 for _ in s['body_names']]
|
||||
actual = {}
|
||||
for e in applied['events']:
|
||||
i, body = e['event_index'], e['body_index']
|
||||
program = s['event_program'][i]
|
||||
if (set(e) != set(AppliedEvent.__annotations__) or type(i) is not int or type(body) is not int
|
||||
or type(e['envelope']) not in (int, float)
|
||||
or not 0 <= body < len(external) or s['body_names'][body] != program['body']
|
||||
or any(not vector(e[k], 3) for k in ('force_world', 'couple_world', 'point_world',
|
||||
'com_world', 'point_frame_origin_world'))
|
||||
or any(not vector(e[k], 4) or abs(norm(e[k]) - 1) > 1e-5
|
||||
for k in ('frame_quat_xyzw', 'point_frame_quat_xyzw'))
|
||||
or abs(e['envelope'] - s['events'][i]['envelope']) > 1e-6):
|
||||
raise ValueError('applied_event_shape_or_frame')
|
||||
if program['frame'] == 'world' and not close(e['frame_quat_xyzw'], [0, 0, 0, 1]):
|
||||
raise ValueError('applied_world_frame')
|
||||
if program['point_frame'] == 'world' and (
|
||||
not close(e['point_frame_quat_xyzw'], [0, 0, 0, 1])
|
||||
or not close(e['point_frame_origin_world'], s['env_origin'])):
|
||||
raise ValueError('applied_world_point_frame')
|
||||
if program['frame'] == program['point_frame'] and not close(
|
||||
e['frame_quat_xyzw'], e['point_frame_quat_xyzw']):
|
||||
raise ValueError('applied_inconsistent_same_frame')
|
||||
for field, command in (('force_world', 'force_N'), ('couple_world', 'couple_Nm')):
|
||||
expected = [x * e['envelope'] for x in rotate(e['frame_quat_xyzw'], program[command])]
|
||||
if not close(e[field], expected):
|
||||
raise ValueError('applied_frame_transform:' + field)
|
||||
point = [a+b for a, b in zip(e['point_frame_origin_world'],
|
||||
rotate(e['point_frame_quat_xyzw'], program['point_m']))]
|
||||
if not close(point, e['point_world']):
|
||||
raise ValueError('applied_point_transform')
|
||||
moment = cross(sub(e['point_world'], e['com_world']), e['force_world'])
|
||||
wrench = e['force_world'] + [a+b for a, b in zip(e['couple_world'], moment)]
|
||||
external[body] = [a+b for a, b in zip(external[body], wrench)]
|
||||
actual[i] = e
|
||||
total = applied['total_com_wrench']
|
||||
if len(total) != len(external) or not all(vector(v, 6) for v in total):
|
||||
raise ValueError('applied_total_shape')
|
||||
for i, v in enumerate(external):
|
||||
if not close(v, s['external'][i]):
|
||||
raise ValueError('applied_external_COM_moment')
|
||||
expected = [a+b+c for a, b, c in zip(v, s['guide'][i], s['auxiliary'][i])]
|
||||
if not close(expected, total[i]):
|
||||
raise ValueError('applied_total_COM_wrench')
|
||||
return actual
|
||||
|
||||
def _schedule_causes(self, e, old, program, previous, expected, index):
|
||||
"""Check the frozen scheduler against the prior, pre-step trigger state."""
|
||||
t = previous['state']['time']
|
||||
phase = previous['event']['command']['phase']
|
||||
state = previous['state']
|
||||
trigger = program['trigger']
|
||||
condition = {
|
||||
'time': t >= program['start_s'],
|
||||
'phase': phase == program['phase'],
|
||||
'liftoff': state['liftoff'] and phase == program['phase'] and state['edge_phase'] == program['phase'],
|
||||
'touchdown': state['touchdown'] and phase == program['phase'],
|
||||
}[trigger]
|
||||
fire = expected and condition and not old['fired']
|
||||
fired = old['fired'] or fire
|
||||
start = (program['start_s'] if trigger == 'time' else t + program['start_s']) if fire else old['start']
|
||||
age = t - start
|
||||
envelope = max(0., min(1., age / program['ramp_s'],
|
||||
(program['duration_s'] - age) / program['ramp_s'])) if fired else 0.
|
||||
completed = old['completed'] or fired and age >= program['duration_s']
|
||||
# Float32 schedule clocks may straddle the exact end by a few ulps.
|
||||
completion_ok = e['completed'] == completed or fired and abs(age - program['duration_s']) <= SCHEDULE_ROUNDOFF_S
|
||||
if (e['fired'] != fired or abs(e['start'] - start) > 2e-6
|
||||
or abs(e['envelope'] - envelope) > 1e-5 or not completion_ok):
|
||||
return ['recording_event_trigger_or_envelope:' + str(index)]
|
||||
return []
|
||||
|
||||
def _events(self, s, clock):
|
||||
causes = []
|
||||
try:
|
||||
actual = self._applied(s, clock)
|
||||
except (KeyError, TypeError, ValueError, IndexError) as exc:
|
||||
causes.append('recording_applied:' + str(exc))
|
||||
actual = {}
|
||||
if self.event_integrals is None:
|
||||
self.event_integrals = [{'force_impulse_Ns': [0.] * 3, 'couple_impulse_Nms': [0.] * 3,
|
||||
'peak_force_N': 0., 'peak_couple_Nm': 0.} for _ in s['events']]
|
||||
delivery = []
|
||||
previous = self.event_previous['state'] if self.event_previous else self.initial['state']
|
||||
for i, (e, program) in enumerate(zip(s['events'], s['event_program'])):
|
||||
expected = i in self.trial.event_indices
|
||||
old = previous['events'][i]
|
||||
causes += self._schedule_causes(e, old, program, self.event_previous or self.initial, expected, i)
|
||||
if (e['integral'] < old['integral'] or e['fired'] < old['fired']
|
||||
or e['completed'] < old['completed']
|
||||
or abs(e['integral'] - old['integral'] - e['envelope'] * DT) > 1e-6
|
||||
or not 0 <= e['envelope'] <= 1
|
||||
or old['fired'] and e['start'] != old['start']):
|
||||
causes.append('recording_event_history:' + str(i))
|
||||
integral = self.event_integrals[i]
|
||||
if i in actual:
|
||||
for key, field in (('force_impulse_Ns', 'force_world'), ('couple_impulse_Nms', 'couple_world')):
|
||||
integral[key] = [a + b * DT for a, b in zip(integral[key], actual[i][field])]
|
||||
integral['peak_force_N'] = max(integral['peak_force_N'], norm(actual[i]['force_world']))
|
||||
integral['peak_couple_Nm'] = max(integral['peak_couple_Nm'], norm(actual[i]['couple_world']))
|
||||
area = program['duration_s'] - program['ramp_s'] if expected else 0.
|
||||
tolerance = self.protocol.document['thresholds']['event_delivery']['area_tolerance_s']
|
||||
ok = (e['fired'] == expected and e['completed'] == expected
|
||||
and abs(e['integral'] - area) <= tolerance)
|
||||
# Fired schedules use the recorded pre-step clock/start, not a nominal
|
||||
# phase deadline. A false completion gets only bounded float32 slack.
|
||||
if e['fired']:
|
||||
age = previous['time'] - e['start']
|
||||
due = e['completed'] or age > program['duration_s'] + SCHEDULE_ROUNDOFF_S
|
||||
elif program['trigger'] == 'time':
|
||||
due = previous['time'] >= program['start_s'] + program['duration_s']
|
||||
else:
|
||||
# This tick consumed the final eligible pre-step invocation.
|
||||
# An edge first observed at the boundary belongs to the next phase.
|
||||
due = clock.local_tick >= PHASE_END_TICKS[program['phase']]
|
||||
determinate = due or not expected or clock.global_tick == self.trial.total_ticks
|
||||
if determinate and not ok:
|
||||
causes.append('event_delivery:' + str(i))
|
||||
if not expected and e['envelope']:
|
||||
causes.append('identity_unexpected_event:' + str(i))
|
||||
delivery.append({'index': i, 'expected': expected, 'fired': e['fired'], 'completed': e['completed'],
|
||||
'missed': expected and not e['fired'], 'expected_area_s': area,
|
||||
'actual_area_s': e['integral'], 'area_error_s': e['integral'] - area,
|
||||
'absolute_start_s': e['start'] if e['fired'] else None,
|
||||
'trigger_delay_s': program['start_s'],
|
||||
'actual_applied_evidence_available': i in actual or not expected,
|
||||
'status': ok if determinate else NOT_EVALUATED, **plain(integral)})
|
||||
if not self.trial.event_indices and any(abs(x) > 1e-6 for v in s['external'] for x in v):
|
||||
causes.append('identity_unexpected_external_wrench')
|
||||
self.delivery = delivery
|
||||
self.event_previous = plain(self.last)
|
||||
if clock.local_tick == CYCLE_TICKS:
|
||||
self.gates['event_delivery'] = all(e['status'] is True for e in delivery)
|
||||
if self.trial.event_indices and all(s['events'][i]['completed'] for i in self.trial.event_indices):
|
||||
c = self.last['event']['command']
|
||||
error = sub(s['root'][:3], c['root_target_world_m'])
|
||||
p = c['phase']
|
||||
appropriate = (s['gap'] >= .01 if p == 3 else
|
||||
s['gap'] >= .02 and s['normal'][2] <= 2 if p == 2 and c['progress'] > .9 else
|
||||
s['gap'] <= .0005 and s['normal'][2] >= .5 * s['weight'] if p in (0, 5) else
|
||||
not s['premature'])
|
||||
good = norm(error[:2]) <= .03 and abs(error[2]) <= .06 and s['tilt'] <= .3 and appropriate
|
||||
self.recovery_run = self.recovery_run + 1 if good else 0
|
||||
if self.recovery_run >= 50 and self.recovery['status'] != 'recovered':
|
||||
completion = max(s['events'][i]['start'] + s['event_program'][i]['duration_s']
|
||||
for i in self.trial.event_indices)
|
||||
start = (clock.global_tick - 49) * DT
|
||||
self.recovery.update(status='recovered', time_s=start - completion, absolute_start_s=start)
|
||||
elif self.recovery['status'] != 'recovered':
|
||||
self.recovery['status'] = 'censored_not_recovered'
|
||||
return causes
|
||||
|
||||
def _cycle_report(self, index, passed=False):
|
||||
metrics = plain(self.metrics)
|
||||
if self.frames:
|
||||
metrics['height_rms_m'] = math.sqrt(mean([
|
||||
(x['state']['root'][2] - x['command']['root_target_world_m'][2]) ** 2 for x in self.frames]))
|
||||
metrics['phase_counts'] = [sum(x['command']['phase'] == p for x in self.frames) for p in range(6)]
|
||||
metrics['phase_min_gap_m'] = [min((x['state']['gap'] for x in self.frames if x['command']['phase'] == p),
|
||||
default=None) for p in range(6)]
|
||||
metrics['phase_max_normal_N'] = [max((x['state']['normal'][2] for x in self.frames
|
||||
if x['command']['phase'] == p), default=None) for p in range(6)]
|
||||
return {'cycle_index': index, 'samples': len(self.frames), 'passed': passed,
|
||||
'gates': plain(self.gates), 'P1_margins': plain(self.margins),
|
||||
'P1_margins_role': self.protocol.document['thresholds']['P1_margins_role'], 'metrics': metrics}
|
||||
|
||||
def _finish_cycle(self, clock, causes):
|
||||
applicable = [v for k, v in self.margins.items() if k != 'repeat_B_drift' or clock.cycle_index == 2]
|
||||
passed = (not causes and all(v is True for v in self.gates.values())
|
||||
and (self.protocol.document['stage'] == 'P2' or all(v is True for v in applicable)))
|
||||
self.cycles.append(self._cycle_report(clock.cycle_index, passed))
|
||||
if not passed and not self.first_failure:
|
||||
self.fail(('recording_incomplete_cycle_gates',))
|
||||
self.frames = []
|
||||
self._cycle_start()
|
||||
|
||||
def report(self):
|
||||
cycles = plain(self.cycles)
|
||||
if self.frames:
|
||||
cycles.append(self._cycle_report(len(cycles)))
|
||||
for i in range(len(cycles), len(self.trial.anchor_sequence) - 1):
|
||||
cycles.append({'cycle_index': i, 'samples': 0, 'passed': False, 'status': NOT_EVALUATED})
|
||||
prefix = 0
|
||||
for c in cycles:
|
||||
if not c['passed']:
|
||||
break
|
||||
prefix += 1
|
||||
return {'format': FORMAT, 'trial': plain(asdict(self.trial)), 'observed_physics_ticks': self.tick,
|
||||
'completed_clock_cycles': self.tick // CYCLE_TICKS, 'passed_prefix_cycles': prefix,
|
||||
'requested_cycles': len(cycles), 'cycles': cycles, 'first_failure': plain(self.first_failure),
|
||||
'protocol_complete': self.tick == self.trial.total_ticks,
|
||||
'all_causes': plain(self.all_causes),
|
||||
'functional_passed': self.tick == self.trial.total_ticks and prefix == len(cycles)
|
||||
and self.first_failure is None,
|
||||
'total_stance_slip_m': self.total_slip, 'delivery': plain(self.delivery),
|
||||
'recovery_diagnostic': plain(self.recovery), 'seams': plain(self.seams),
|
||||
'initial_pair_state': (None if self.initial is None else
|
||||
{k: plain(self.initial['state'][k]) for k in (
|
||||
'root', 'q', 'qdot', 'foot', 'anchors', 'sensor_delay', 'action_delay',
|
||||
'q_ik', 'sensed', 'actuator_state', 'rng')}),
|
||||
'accepted_skill': False, 'optimizer_steps': 0}
|
||||
|
||||
|
||||
def matrix_report(protocol, rows):
|
||||
"""All preregistered rows, including not-run; pair equality is evidence, not assumed."""
|
||||
indexed = {}
|
||||
for row in rows:
|
||||
index = row['trial']['index']
|
||||
if index in indexed or row['trial'] != plain(asdict(protocol.trial(index))):
|
||||
raise ValueError('Duplicate or foreign trial row')
|
||||
indexed[index] = row
|
||||
result = [indexed.get(t.index, {'trial': plain(asdict(t)), 'status': 'not_run',
|
||||
'functional_passed': False, 'accepted_skill': False}) for t in protocol.trials]
|
||||
pairs = []
|
||||
for a, b in zip(result[::2], result[1::2]):
|
||||
pair = {'pair_id': a['trial']['pair_id'], 'status': NOT_EVALUATED}
|
||||
if isinstance(a.get('initial_pair_state'), dict) and isinstance(b.get('initial_pair_state'), dict):
|
||||
pair['initial_exactly_equal'] = a['initial_pair_state'] == b['initial_pair_state']
|
||||
if not pair['initial_exactly_equal']:
|
||||
pair.update(status='invalid_initial_pair', both_functional_passed=False,
|
||||
learned_minus_reference=NOT_EVALUATED)
|
||||
pairs.append(pair)
|
||||
continue
|
||||
pair['status'] = 'evaluated'
|
||||
pair['both_functional_passed'] = a['functional_passed'] and b['functional_passed']
|
||||
pair['failure_onsets'] = [x['first_failure'] for x in (a, b)]
|
||||
pair['learned_minus_reference'] = {}
|
||||
for metric in ('swing_rms_m', 'landing_error_m', 'max_root_horizontal_error_m'):
|
||||
left = a['cycles'][0].get('metrics', {}).get(metric)
|
||||
right = b['cycles'][0].get('metrics', {}).get(metric)
|
||||
pair['learned_minus_reference'][metric] = (left - right if left is not None and right is not None
|
||||
else NOT_EVALUATED)
|
||||
pair['recovery_diagnostics'] = [x['recovery_diagnostic'] for x in (a, b)]
|
||||
pairs.append(pair)
|
||||
return {'rows': result, 'pairs': pairs, 'accepted_skill': False, 'optimizer_steps': 0}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,288 @@
|
||||
"""Linux same-boot, single-writer evaluation reservations. No simulator imports.
|
||||
|
||||
Reservations are debits, NOT observations of executed physics. No refund, resume,
|
||||
retry, transfer or new boot. The parent-reviewed grant identifies this campaign.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import fcntl
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import stat
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
CAP_BYTES = 1 << 30
|
||||
HEADROOM_BYTES = 16 << 20
|
||||
STDOUT_BYTES = 1 << 20
|
||||
STDOUT_ALLOWANCE = 3 * STDOUT_BYTES
|
||||
STORAGE_SCOPE = "validation-outputs-only.native-monitored-stop.v1"
|
||||
CLEANUP_SECONDS = 120
|
||||
TOTAL_SECONDS = 3600
|
||||
SLOTS = ((14500, 13500, 600), (14500, 13500, 600), (91000, 90000, 2100))
|
||||
FORMAT = 'skillfactory.evaluation-budget.v2'
|
||||
EXTENDED_PROFILE = 'p2-wall10800-aggregate14400-v1'
|
||||
EXTENDED_FORMAT = 'skillfactory.evaluation-budget.p2-extended.v1'
|
||||
EXTENDED_GRANT_FORMAT = 'skillfactory.evaluation-parent-grant.p2-extended.v1'
|
||||
EXTENDED_POLICY_FORMAT = 'skillfactory.output-storage-policy.p2-extended.v1'
|
||||
EXTENDED_TOTAL_SECONDS = 14400
|
||||
EXTENDED_SLOTS = ((91000, 90000, 10800),)
|
||||
EXTENDED_ROOT = Path('/home/cen/sf-runs/p2-01')
|
||||
SECOND_EXTENDED_ROOT = Path('/home/cen/sf-runs/p2-02')
|
||||
|
||||
|
||||
def extended_historical_calls(root):
|
||||
"""Finite campaigns only; second campaign retains the failed 91000 debit."""
|
||||
if Path(root) == EXTENDED_ROOT:
|
||||
return 72500
|
||||
if Path(root) == SECOND_EXTENDED_ROOT:
|
||||
return 163500
|
||||
raise ValueError('budget_extended_fixed_root_required')
|
||||
|
||||
|
||||
def profile_limits(profile):
|
||||
if profile is None:
|
||||
return SLOTS, TOTAL_SECONDS, FORMAT
|
||||
if profile == EXTENDED_PROFILE:
|
||||
return EXTENDED_SLOTS, EXTENDED_TOTAL_SECONDS, EXTENDED_FORMAT
|
||||
raise ValueError('budget_unknown_resource_profile')
|
||||
|
||||
|
||||
def boottime():
|
||||
return time.clock_gettime(time.CLOCK_BOOTTIME)
|
||||
|
||||
|
||||
def boot_id():
|
||||
return Path('/proc/sys/kernel/random/boot_id').read_text().strip()
|
||||
|
||||
|
||||
def digest(path):
|
||||
h = hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
for block in iter(lambda: stream.read(1 << 20), b''):
|
||||
h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def durable_directory(path):
|
||||
path = Path(path)
|
||||
path.mkdir() # ancestors must already be durable; never recursively invent them
|
||||
sync_directory(path)
|
||||
sync_directory(path.parent)
|
||||
|
||||
|
||||
def encode(value):
|
||||
return (json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + '\n').encode()
|
||||
|
||||
|
||||
def durable_write(path, data):
|
||||
path = Path(path)
|
||||
with path.open('xb', buffering=0) as stream:
|
||||
if stream.write(data) != len(data):
|
||||
raise OSError('Short durable write')
|
||||
os.fsync(stream.fileno())
|
||||
sync_directory(path.parent)
|
||||
|
||||
|
||||
def artifact_size(root, *, exclude_native=False):
|
||||
root = Path(root)
|
||||
if root != root.resolve(strict=True) or not root.is_dir():
|
||||
raise RuntimeError('storage_artifact_root_moved_or_linked')
|
||||
def walk_error(error):
|
||||
raise error # never silently skip inaccessible owned directories
|
||||
|
||||
# Atomic writer publication can rename a listed .pending file before lstat.
|
||||
# Restart the WHOLE scan (not skip the entry or return a partial total), since
|
||||
# the destination may already have been counted at its previous smaller size.
|
||||
# Persistent churn fails closed; this remains sampled accounting, not a quota.
|
||||
for attempt in range(4):
|
||||
total = 0
|
||||
try:
|
||||
for directory, dirs, files in os.walk(root, followlinks=False, onerror=walk_error):
|
||||
if exclude_native and Path(directory) == root and "native" in dirs:
|
||||
dirs.remove("native")
|
||||
for name in dirs + files:
|
||||
p = Path(directory) / name
|
||||
info = p.lstat() # one no-follow metadata read, no second stat race
|
||||
mode = info.st_mode
|
||||
if stat.S_ISLNK(mode) or not (stat.S_ISREG(mode) or stat.S_ISDIR(mode)):
|
||||
raise RuntimeError('storage_nonregular_artifact: ' + str(p))
|
||||
if stat.S_ISREG(mode):
|
||||
total += info.st_size
|
||||
if root != root.resolve(strict=True) or not root.is_dir():
|
||||
raise RuntimeError('storage_artifact_root_moved_or_linked')
|
||||
return total
|
||||
except FileNotFoundError:
|
||||
if attempt == 3:
|
||||
raise RuntimeError('storage_artifact_scan_unstable_after_4_attempts')
|
||||
raise AssertionError('unreachable bounded artifact scan')
|
||||
|
||||
|
||||
def tree_digest(root):
|
||||
"""Bind every retained P1 child/log/cleanup artifact for the P2 review gate."""
|
||||
artifact_size(root)
|
||||
entries = {str(p.relative_to(root)): digest(p) for p in sorted(Path(root).rglob('*')) if p.is_file()}
|
||||
return hashlib.sha256(encode(entries)).hexdigest()
|
||||
|
||||
|
||||
class BudgetLedger:
|
||||
def __init__(self, root, campaign_id, *, clock=boottime, boot=boot_id, cap_bytes=CAP_BYTES,
|
||||
resource_profile=None):
|
||||
self.root = Path(root)
|
||||
self.resource_profile = resource_profile
|
||||
self.slots, self.total_seconds, self.format = profile_limits(resource_profile)
|
||||
historical = extended_historical_calls(self.root) if resource_profile is not None else None
|
||||
if type(cap_bytes) is not int or not HEADROOM_BYTES < cap_bytes <= CAP_BYTES:
|
||||
raise ValueError('Require reviewed artifact cap with cleanup headroom')
|
||||
self.cap_bytes = cap_bytes
|
||||
if not self.root.is_absolute() or self.root != self.root.resolve():
|
||||
raise ValueError('Canonical absolute artifact root required')
|
||||
if not self.root.exists():
|
||||
durable_directory(self.root)
|
||||
self.clock, self.boot = clock, boot
|
||||
self.lock = (self.root / 'budget.lock').open('a+b')
|
||||
try:
|
||||
fcntl.flock(self.lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
self.path = self.root / 'budget.json'
|
||||
if self.path.exists():
|
||||
self.data = json.loads(self.path.read_bytes())
|
||||
if (self.data['format'] != self.format
|
||||
or self.data.get('resource_profile') != resource_profile or self.data['campaign_id'] != campaign_id
|
||||
or self.data['boot_id'] != boot() or self.data['artifact_cap_bytes'] != cap_bytes
|
||||
or self.data.get('storage_scope') != STORAGE_SCOPE):
|
||||
raise RuntimeError('budget_campaign_or_boot_mismatch')
|
||||
else:
|
||||
if list(self.root.glob('launch-*')):
|
||||
raise RuntimeError('budget_missing_ledger_no_recovery')
|
||||
self.data = {'format': self.format, 'campaign_id': campaign_id, 'boot_id': boot(),
|
||||
'first_run_boottime': None, 'launches': [], 'artifact_cap_bytes': cap_bytes,
|
||||
'storage_scope': STORAGE_SCOPE}
|
||||
if resource_profile is not None:
|
||||
self.data.update(resource_profile=resource_profile,
|
||||
historical_reserved_calls=historical, local_reserved_calls=0,
|
||||
cumulative_reserved_calls=historical, p1_adoption_sha256=None)
|
||||
self._save()
|
||||
except BaseException:
|
||||
self.lock.close()
|
||||
raise
|
||||
|
||||
def _save(self):
|
||||
temporary = self.root / 'budget.pending'
|
||||
payload = encode(self.data)
|
||||
if artifact_size(self.root, exclude_native=True) + len(payload) > self.cap_bytes:
|
||||
raise RuntimeError('storage_ledger_headroom_exhausted')
|
||||
durable_write(temporary, payload)
|
||||
os.replace(temporary, self.path)
|
||||
sync_directory(self.root)
|
||||
|
||||
def reserve(self, grant, *, enforcement_deadline=float('inf')):
|
||||
rows = self.data['launches']
|
||||
index = len(rows)
|
||||
if index >= len(self.slots) or grant['launch_index'] != index:
|
||||
raise RuntimeError('budget_no_retry_resume_or_reused_grant')
|
||||
if rows and rows[-1]['status'] != 'closed':
|
||||
raise RuntimeError('budget_interrupted_or_overlapping_campaign')
|
||||
if rows and not rows[-1]['continuation_eligible']:
|
||||
raise RuntimeError('budget_previous_fatal_or_unclean')
|
||||
if self.resource_profile is not None:
|
||||
if (grant.get('format') != EXTENDED_GRANT_FORMAT
|
||||
or grant.get('resource_profile') != self.resource_profile
|
||||
or grant.get('stage') != 'P2' or grant.get('trial_indices') != list(range(20))):
|
||||
raise RuntimeError('budget_grant_resource_profile_mismatch')
|
||||
from .evaluation_adoption import verify_adoption
|
||||
adoption = verify_adoption(self.root, grant['p1_adoption_sha256'])
|
||||
if adoption['source_boot_id'] != self.boot():
|
||||
raise RuntimeError('budget_adoption_boot_mismatch')
|
||||
if (adoption['historical_reserved_calls'] != extended_historical_calls(self.root)
|
||||
or self.data['historical_reserved_calls'] != adoption['historical_reserved_calls']
|
||||
or self.data['local_reserved_calls'] != 0
|
||||
or self.data['cumulative_reserved_calls'] != adoption['historical_reserved_calls']):
|
||||
raise RuntimeError('budget_historical_debits_mismatch')
|
||||
elif grant.get('resource_profile') is not None or grant.get('format') == EXTENDED_GRANT_FORMAT:
|
||||
raise RuntimeError('budget_grant_resource_profile_mismatch')
|
||||
now = self.clock()
|
||||
first = self.data['first_run_boottime']
|
||||
if first is None:
|
||||
first = now
|
||||
if self.boot() != self.data['boot_id'] or now < first or now >= first + self.total_seconds - CLEANUP_SECONDS:
|
||||
raise RuntimeError('budget_aggregate_deadline_or_boot')
|
||||
if now >= grant['not_after_boottime']:
|
||||
raise RuntimeError('budget_expired_parent_grant')
|
||||
if artifact_size(self.root, exclude_native=True) >= self.cap_bytes - HEADROOM_BYTES:
|
||||
raise RuntimeError('budget_artifact_headroom')
|
||||
if index == 2:
|
||||
expected = [tree_digest(self.root / f'launch-{i}') for i in (0, 1)]
|
||||
if grant['p1_evidence_sha256'] != expected:
|
||||
raise RuntimeError('identity_P2_review_does_not_bind_retained_P1_evidence')
|
||||
ticks, rollout, seconds = self.slots[index]
|
||||
row = {'index': index, 'status': 'reserved', 'grant': grant,
|
||||
'reserved_physical_calls': ticks, 'rollout_cap': rollout, 'initialization_cap': 1000,
|
||||
'started_boottime': now,
|
||||
'deadline_boottime': min(now + seconds, first + self.total_seconds, enforcement_deadline),
|
||||
'continuation_eligible': False, 'observed_counts': None, 'artifact_cap_bytes': self.cap_bytes}
|
||||
if self.resource_profile is not None:
|
||||
row['resource_profile'] = self.resource_profile
|
||||
self.data.update(p1_adoption_sha256=grant['p1_adoption_sha256'],
|
||||
local_reserved_calls=91000,
|
||||
cumulative_reserved_calls=self.data['historical_reserved_calls'] + 91000)
|
||||
self.data['first_run_boottime'] = first
|
||||
rows.append(row)
|
||||
self._save() # irrevocable BEFORE Popen, including failed Popen
|
||||
return row
|
||||
|
||||
def finish(self, *, counts, clean, eligible):
|
||||
row = self.data['launches'][-1]
|
||||
if row['status'] != 'reserved':
|
||||
raise RuntimeError('budget_reservation_already_closed')
|
||||
row.update(status='closed', observed_counts=counts, cleanup_clean=bool(clean),
|
||||
continuation_eligible=bool(clean and eligible), ended_boottime=self.clock())
|
||||
self._save()
|
||||
|
||||
def close(self):
|
||||
self.lock.close()
|
||||
|
||||
|
||||
class LaunchBudget:
|
||||
def __init__(self, root, reservation, *, clock=boottime, boot=boot_id):
|
||||
self.root, self.reservation = Path(root), reservation
|
||||
self.clock, self.boot = clock, boot
|
||||
self.interrupted = False
|
||||
|
||||
def check(self, *, pending=0, cleanup=False):
|
||||
r = self.reservation
|
||||
limit = r['deadline_boottime'] - (0 if cleanup else CLEANUP_SECONDS)
|
||||
if self.boot() != r['grant']['boot_id'] or self.clock() >= limit:
|
||||
raise RuntimeError('budget_time_or_boot')
|
||||
if self.interrupted and not cleanup:
|
||||
raise InterruptedError('process_signal')
|
||||
cap = min(CAP_BYTES, r.get('artifact_cap_bytes', CAP_BYTES))
|
||||
ceiling = cap - STDOUT_ALLOWANCE - (0 if cleanup else HEADROOM_BYTES)
|
||||
if artifact_size(self.root, exclude_native=True) + pending > ceiling:
|
||||
raise RuntimeError('storage_aggregate_cap')
|
||||
|
||||
def before_step(self, hooks):
|
||||
self.check()
|
||||
r = self.reservation
|
||||
# Attempt counter is incremented by RuntimeHooks before this callback.
|
||||
# A rejected attempt is not relabeled as a completed physical call.
|
||||
if (hooks.attempted_steps > r['reserved_physical_calls']
|
||||
or (hooks.mode == 'rollout' and hooks.rollout_steps >= r['rollout_cap'])
|
||||
or (hooks.mode != 'rollout' and hooks.initialization_steps >= r['initialization_cap'])):
|
||||
raise RuntimeError('budget_physical_calls')
|
||||
|
||||
def recording(self, stage, pending_bytes, written_bytes):
|
||||
self.check(pending=pending_bytes, cleanup=stage == 'finalize')
|
||||
|
||||
def write(self, path, value):
|
||||
data = encode(value)
|
||||
self.check(pending=len(data), cleanup=True)
|
||||
durable_write(path, data)
|
||||
@@ -0,0 +1,433 @@
|
||||
"""Pure, preregistered P1/P2 development protocol; never an execution grant.
|
||||
|
||||
Integer clocks are authoritative. Evidence is right-closed per cycle; a seam's
|
||||
next command is available only with explicit admission by the future evaluator.
|
||||
No simulator, tensor, controller, RNG, or measured-landing state is accessed.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
from bisect import bisect_right
|
||||
from collections.abc import Mapping, Sequence
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from types import MappingProxyType
|
||||
from typing import Any
|
||||
|
||||
PHYSICS_DT_S = 0.002
|
||||
CONTROL_TICKS = 5
|
||||
PHASE_TICKS = (1500, 500, 300, 700, 400, 1100)
|
||||
PHASE_END_TICKS = (1500, 2000, 2300, 3000, 3400, 4500)
|
||||
CYCLE_TICKS = 4500
|
||||
EVIDENCE_PHASE_COUNTS = (1499, 500, 300, 700, 400, 1101)
|
||||
EXTENDED_PROFILE = "p2-wall10800-aggregate14400-v1"
|
||||
Vec3 = tuple[float, float, float]
|
||||
|
||||
_FUNCTIONAL_GATES = {
|
||||
"minimum_complete_cycles": 1,
|
||||
"support_final_window_s": 0.5,
|
||||
"reload_final_window_s": 0.2,
|
||||
"contact_force_on_N": 2.0,
|
||||
"support_reload_contact_fraction_min": 0.8,
|
||||
"support_reload_load_fraction_min": 0.5,
|
||||
"unload_final_window_s": 0.1,
|
||||
"unload_remaining_support_fraction_max": 0.8,
|
||||
"swing_gap_m_min": 0.01,
|
||||
"swing_air_fraction_min": 0.8,
|
||||
"swing_contiguous_air_s_min": 0.1,
|
||||
"swing_xy_progress_fraction_min": 0.5,
|
||||
"landing_position_error_m_max": 0.05,
|
||||
"root_height_error_m_max": 0.1,
|
||||
"normal_force_negative_tolerance_N": 0.5,
|
||||
"root_tilt_rad_max": 0.6,
|
||||
"ground_penetration_m_max": 0.002,
|
||||
"auxiliary_vertical_N_max": 140.0,
|
||||
"auxiliary_lever_arm_m_max": 0.06,
|
||||
"guide_vertical_N_max": 0.000001,
|
||||
"normalized_effort_velocity_max": 1.00001,
|
||||
"joint_limit_excess_rad_max": 0.01,
|
||||
}
|
||||
|
||||
_P1_MARGINS = {
|
||||
"root_horizontal_error_m_max": 0.030,
|
||||
"root_absolute_z_error_m_max": 0.060,
|
||||
"seam_to_initial_root_horizontal_drift_m_max": 0.020,
|
||||
"reload_mean_3d_error_m_max": 0.020,
|
||||
"reload_instantaneous_3d_error_m_max": 0.030,
|
||||
"stance_slip_per_cycle_m_max": 0.030,
|
||||
"stance_slip_per_run_m_max": 0.060,
|
||||
"repeat_B_reload_mean_xy_drift_m_max": 0.015,
|
||||
"unload_remaining_support_fraction_max": 0.70,
|
||||
"premature_separation_allowed": False,
|
||||
"lift_gap_m_min": 0.022,
|
||||
"lift_normal_N_max": 2.0,
|
||||
"lift_deadline_local_tick": 2260,
|
||||
"lift_dwell_ticks": 5,
|
||||
"lift_onset_phase": 2,
|
||||
"reload_final_dwell_ticks": 50,
|
||||
"reload_gap_m_max": 0.0005,
|
||||
"reload_load_fraction_min": 0.8,
|
||||
"reload_load_fraction_max": 1.2,
|
||||
"reload_contact_required": True,
|
||||
"reload_separation_allowed": False,
|
||||
}
|
||||
|
||||
_EVENTS = [
|
||||
{"scenario": 1, "body": "virtual_payload", "frame": "world", "point_frame": "body",
|
||||
"point_m": [0.03, -0.02, 0.06], "force_N": [3.0, -4.0, -2.0], "couple_Nm": [0.2, 0.1, -0.1],
|
||||
"trigger": "time", "phase": 0, "start_s": 1.0, "duration_s": 6.5, "ramp_s": 0.5},
|
||||
{"scenario": 2, "body": "FL_thigh", "frame": "body", "point_frame": "body",
|
||||
"point_m": [0.02, 0.01, -0.06], "force_N": [-2.0, 1.0, 2.0], "couple_Nm": [0.1, -0.1, 0.2],
|
||||
"trigger": "liftoff", "phase": 2, "start_s": 0.02, "duration_s": 0.2, "ramp_s": 0.1},
|
||||
{"scenario": 3, "body": "virtual_payload", "frame": "mount", "point_frame": "mount",
|
||||
"point_m": [-0.03, 0.04, 0.04], "force_N": [2.0, 2.0, -3.0], "couple_Nm": [-0.2, 0.3, 0.1],
|
||||
"trigger": "phase", "phase": 4, "start_s": 0.1, "duration_s": 0.6, "ramp_s": 0.15},
|
||||
{"scenario": 3, "body": "FL_calf", "frame": "world", "point_frame": "body",
|
||||
"point_m": [0.01, 0.0, -0.08], "force_N": [-1.0, 1.5, 0.5], "couple_Nm": [0.0, -0.1, 0.1],
|
||||
"trigger": "touchdown", "phase": 4, "start_s": 0.0, "duration_s": 0.3, "ramp_s": 0.1},
|
||||
]
|
||||
|
||||
|
||||
def _approved_document(stage: str, resource_profile: str | None = None) -> dict[str, Any]:
|
||||
"""Exact preregistered schemas/values; only the named P2 wall profile is additive."""
|
||||
if stage not in ("P1", "P2"):
|
||||
raise ValueError("Unknown evaluation stage")
|
||||
conditions = [
|
||||
{"id": name, "scenario_id": scenario, "swing_displacement_m": delta,
|
||||
"event_indices": indices}
|
||||
for name, scenario, delta, indices in (
|
||||
("nominal", 0, [0.025, 0.020, 0.0], []),
|
||||
("oblique_sustained", 1, [0.025, 0.020, 0.0], [0]),
|
||||
("eccentric_liftoff", 2, [0.025, 0.020, 0.0], [1]),
|
||||
("landing_combination", 3, [0.025, 0.020, 0.0], [2, 3]),
|
||||
("target_only", 0, [0.030, 0.025, 0.0], []),
|
||||
)
|
||||
]
|
||||
document = {
|
||||
"format": "skillfactory.contact-cycle-evaluation-protocol.v1",
|
||||
"stage": stage,
|
||||
"status": "prospective_development_not_acceptance",
|
||||
"execution_authorized": False,
|
||||
"requires_parent_physics_approval": True,
|
||||
"requires_P1_evidence_review": stage == "P2",
|
||||
"accepted_skill": False,
|
||||
"optimizer_steps": 0,
|
||||
"num_envs": 1,
|
||||
"frozen_model": {
|
||||
"candidate": "logs/contact_cycle/sim_residual_training_v1/prepared01/candidate_u0256.pt",
|
||||
"candidate_sha256": "c088bb3aecaca751867118858626fd508f7a3983303802d7524353f80802cf99",
|
||||
"features": "contact-cycle-sim-truth-residual-46-v1",
|
||||
"learned_policy": "deterministic_mean_residual_plus_unchanged_analytic_reference",
|
||||
"analytic_reference": "zero_residual_plus_unchanged_analytic_reference",
|
||||
"verification": "unchanged_verify_bundle_plus_separate_new_evaluation_binding",
|
||||
"selection_or_tuning": False,
|
||||
},
|
||||
"controllers": ["learned_policy", "analytic_reference"],
|
||||
"seeds": [93501] if stage == "P1" else [94501, 94502],
|
||||
"trial_order": "condition_then_seed_then_controller",
|
||||
"trial_count": 2 if stage == "P1" else 20,
|
||||
"cycles_per_trial": 3 if stage == "P1" else 1,
|
||||
"anchor_sequence": ["A", "B", "A", "B"] if stage == "P1" else ["A", "B"],
|
||||
"conditions": conditions[:1] if stage == "P1" else conditions,
|
||||
"events": [] if stage == "P1" else _EVENTS,
|
||||
"clock": {
|
||||
"physics_dt_s": PHYSICS_DT_S, "control_ticks": CONTROL_TICKS,
|
||||
"phase_durations_s": [3.0, 1.0, 0.6, 1.4, 0.8, 2.2],
|
||||
"phase_ticks": list(PHASE_TICKS), "cycle_ticks": CYCLE_TICKS,
|
||||
"evidence_phase_counts": list(EVIDENCE_PHASE_COUNTS),
|
||||
"evidence_intervals": "right_closed_initial_tick_separate",
|
||||
"phase_boundary": "next_phase_at_exact_internal_boundary",
|
||||
},
|
||||
"command": {
|
||||
"anchor_frame": "world_fixed_from_initial_ground_foot_target",
|
||||
"root_target": "fixed_initial_commanded_mounting_port",
|
||||
"measured_landing_reanchor": False,
|
||||
"clearance_m": 0.05, "swing_arch_m": 0.01,
|
||||
"actor_target_coordinates": "world_axis_target_minus_commanded_port_origin",
|
||||
"ik_target_coordinates": "inverse_rotate_actual_root_quaternion_target_minus_actual_root_position",
|
||||
"noise_or_domain_randomization": False,
|
||||
"reference_controller_reward_residual_changes": False,
|
||||
},
|
||||
"thresholds": {
|
||||
"functional_source": "configs/contact_cycle/simulation_functional_v1.json#gates",
|
||||
"functional": _FUNCTIONAL_GATES,
|
||||
"functional_application": "each_complete_cycle_with_signed_requested_xy_progress",
|
||||
"excluded_nominal_auditor_checks": ["nominal_only", "no_external_disturbance"],
|
||||
"replacement_condition_check": "exact_bound_trial_scenario_and_event_program",
|
||||
"original_runtime_source": "source/SkillFactory/SkillFactory/legs/contact_cycle/task.py#phase_failures",
|
||||
"original_runtime": {
|
||||
"lift_progress_strictly_greater": 0.9, "lift_gap_m_min": 0.02,
|
||||
"lift_normal_N_max": 2.0, "swing_gap_m_min": 0.01,
|
||||
"reload_progress_strictly_greater": 0.8, "reload_load_fraction_min": 0.5,
|
||||
"root_height_below_nominal_m_max": 0.1, "root_tilt_rad_max": 0.6,
|
||||
"guide_vertical_N_exact": 0.0,
|
||||
"nonfinite_allowed": False, "premature_separation_allowed": False,
|
||||
},
|
||||
"contact_source": "configs/contact_cycle/go2_fl_v1.json; contact_cycle/mechanics.py",
|
||||
"contact": {
|
||||
"force_on_N": 2.0, "force_off_N": 0.5, "dwell_ticks": 5,
|
||||
"separation_on_m": 0.001, "separation_off_m": 0.0005,
|
||||
"initial_acquisition_deadline_tick": 100,
|
||||
"initial_acquisition_load_fraction_min": 0.5,
|
||||
"initial_acquisition_gap_m_max": 0.0005,
|
||||
"initial_acquisition_rearmed_at_seam": False,
|
||||
},
|
||||
"P1_margins_source": "parent_approved_prospective_development_v1_not_P0_pass_claim",
|
||||
"P1_height_value_precedent": "configs/contact_cycle/acceptance_v1.json#gates.height_error_m_max",
|
||||
"P1_margins": _P1_MARGINS,
|
||||
"P1_margins_role": "gate" if stage == "P1" else "diagnostic_only",
|
||||
"historical_swing_clearance_diagnostic_m": 0.02,
|
||||
"event_delivery": {"fired_and_completed_required": True, "area": "duration_s_minus_ramp_s",
|
||||
"area_tolerance_s": 0.002},
|
||||
"event_delivery_source": (
|
||||
"source/SkillFactory/SkillFactory/legs/contact_cycle/mechanics.py#delivered_events"
|
||||
),
|
||||
},
|
||||
"resources": {
|
||||
"proposal_only": True, "max_launches": 3, "max_sim_step_ticks_including_initialization": 120000,
|
||||
"max_rollout_ticks": 117000, "max_initialization_reset_ticks": 3000,
|
||||
"max_control_steps": 23400, "aggregate_same_boot_window_s": 3600,
|
||||
"max_artifact_bytes": 1073741824, "cleanup_reserve_s": 120,
|
||||
"P1_max_launches": 2, "P1_launch_wall_cap_s": 600,
|
||||
"P1_rollout_ticks_per_launch": 13500,
|
||||
"P2_max_launches": 1, "P2_launch_wall_cap_s": 2100,
|
||||
"P2_rollout_ticks_per_launch": 90000,
|
||||
"overlapping_jobs": False, "retries_or_resume": False,
|
||||
"count_hook_before_construction": True,
|
||||
},
|
||||
"handoff": {
|
||||
"seam_order": ["physics_and_latches", "safety_and_endpoint_snapshot", "cycle_gate",
|
||||
"command_metadata_only", "single_reference_refresh", "next_observation"],
|
||||
"carry_state": ["physical_pose_velocity", "previous_action_processed_target_residual",
|
||||
"actuator_sensor_delay", "IK_warm_start_action_refresh_count", "contact_latches_timers",
|
||||
"separation_onset_armed_premature", "initial_acquisition", "global_substeps", "RNG",
|
||||
"one_shot_event_scheduler"],
|
||||
"reset_or_pose_write_within_trial": False,
|
||||
"completion": "protocol_complete_without_terminal_reset",
|
||||
"seam_admission_failure": "stop_at_endpoint_no_extension_or_wait",
|
||||
"initial_reset_per_trial": True,
|
||||
"P1_separate_fresh_launch_per_controller": True,
|
||||
"P2_reset_only_between_trials": True,
|
||||
"failure_check": "after_each_scene_tick_before_another_sim_step",
|
||||
"failure_reporting": "first_tick_all_causes_passed_prefix_only_remaining_gates_not_evaluated",
|
||||
"P2_functional_failure": "retain_row_continue_matrix_if_safe",
|
||||
"fatal_failures": ["hardware", "nonfinite", "identity", "illegal_reset_or_pose_write",
|
||||
"storage_or_recording", "process", "budget_expired"],
|
||||
"pairing": "same_seed_initial_state_targets_trigger_rule_not_equal_wall_time_force_samples",
|
||||
"P2_all_rows_required": True,
|
||||
"P2_new_seeds_are": "development_repeatability_not_independent_robustness",
|
||||
},
|
||||
}
|
||||
|
||||
if resource_profile is not None:
|
||||
if resource_profile != EXTENDED_PROFILE or stage != "P2":
|
||||
raise ValueError("Unknown or incompatible resource profile")
|
||||
document["format"] = "skillfactory.contact-cycle-evaluation-protocol.v2"
|
||||
document["resource_profile"] = EXTENDED_PROFILE
|
||||
document["resources"]["P2_launch_wall_cap_s"] = 10800
|
||||
document["resources"]["aggregate_same_boot_window_s"] = 14400
|
||||
return document
|
||||
|
||||
|
||||
def _match(actual: Any, expected: Any, path: str = "protocol") -> None:
|
||||
# Exact numeric types reject bool-as-int, coercion, and nonfinite values.
|
||||
if type(actual) is not type(expected):
|
||||
raise ValueError(f"{path}: invalid type")
|
||||
if isinstance(expected, dict):
|
||||
if actual.keys() != expected.keys():
|
||||
raise ValueError(f"{path}: missing or unknown keys")
|
||||
for key in expected:
|
||||
_match(actual[key], expected[key], f"{path}.{key}")
|
||||
elif isinstance(expected, list):
|
||||
if len(actual) != len(expected):
|
||||
raise ValueError(f"{path}: invalid length")
|
||||
for index, value in enumerate(expected):
|
||||
_match(actual[index], value, f"{path}[{index}]")
|
||||
elif actual != expected:
|
||||
raise ValueError(f"{path}: differs from preregistered value")
|
||||
|
||||
|
||||
def _freeze(value: Any) -> Any:
|
||||
if isinstance(value, dict):
|
||||
return MappingProxyType({key: _freeze(item) for key, item in value.items()})
|
||||
if isinstance(value, list):
|
||||
return tuple(_freeze(item) for item in value)
|
||||
return value
|
||||
|
||||
|
||||
def _integer(value: int, low: int, high: int, name: str) -> None:
|
||||
if type(value) is not int or not low <= value <= high:
|
||||
raise ValueError(f"{name}: require integer in [{low}, {high}]")
|
||||
|
||||
|
||||
def _vector(value: Sequence[float], name: str) -> Vec3:
|
||||
if (not isinstance(value, (list, tuple)) or len(value) != 3
|
||||
or any(type(x) not in (int, float) or not math.isfinite(x) for x in value)):
|
||||
raise ValueError(f"{name}: require three finite real coordinates")
|
||||
return tuple(float(x) for x in value)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Trial:
|
||||
"""Ordered, paired descriptor. Event indices address Protocol.document['events']."""
|
||||
|
||||
index: int
|
||||
trial_id: str
|
||||
pair_id: str
|
||||
condition_id: str
|
||||
seed: int
|
||||
controller_kind: str
|
||||
scenario_id: int
|
||||
swing_displacement_m: Vec3
|
||||
event_indices: tuple[int, ...]
|
||||
anchor_sequence: tuple[str, ...]
|
||||
|
||||
@property
|
||||
def total_ticks(self) -> int:
|
||||
return (len(self.anchor_sequence) - 1) * CYCLE_TICKS
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Clock:
|
||||
global_tick: int
|
||||
cycle_index: int
|
||||
local_tick: int
|
||||
|
||||
@property
|
||||
def global_time_s(self) -> float:
|
||||
return self.global_tick * PHYSICS_DT_S
|
||||
|
||||
@property
|
||||
def local_time_s(self) -> float:
|
||||
return self.local_tick * PHYSICS_DT_S
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Command:
|
||||
phase: int
|
||||
progress: float
|
||||
start_anchor: str
|
||||
end_anchor: str
|
||||
target_world_m: Vec3
|
||||
target_velocity_world_m_s: Vec3
|
||||
desired_normal_N: float
|
||||
auxiliary_fraction: float
|
||||
root_target_world_m: Vec3
|
||||
root_velocity_world_m_s: Vec3
|
||||
actor_target_displacement_world_m: Vec3
|
||||
|
||||
|
||||
@dataclass(frozen=True, init=False)
|
||||
class Protocol:
|
||||
"""Validated immutable handoff; methods compute metadata, never admit physics."""
|
||||
|
||||
document: Mapping[str, Any]
|
||||
trials: tuple[Trial, ...]
|
||||
|
||||
def __init__(self, document: dict[str, Any]):
|
||||
if type(document) is not dict or document.get("stage") not in ("P1", "P2"):
|
||||
raise ValueError("Require P1/P2 protocol document")
|
||||
_match(document, _approved_document(document["stage"], document.get("resource_profile")))
|
||||
frozen = _freeze(document)
|
||||
rows = []
|
||||
for condition in frozen["conditions"]:
|
||||
for seed in frozen["seeds"]:
|
||||
pair = f"{frozen['stage']}/{condition['id']}/{seed}"
|
||||
for controller in frozen["controllers"]:
|
||||
rows.append(Trial(len(rows), f"{pair}/{controller}", pair, condition["id"], seed, controller,
|
||||
condition["scenario_id"], condition["swing_displacement_m"],
|
||||
condition["event_indices"], frozen["anchor_sequence"]))
|
||||
object.__setattr__(self, "document", frozen)
|
||||
object.__setattr__(self, "trials", tuple(rows))
|
||||
|
||||
def trial(self, index: int) -> Trial:
|
||||
_integer(index, 0, len(self.trials) - 1, "trial index")
|
||||
return self.trials[index]
|
||||
|
||||
def evidence_clock(self, trial_index: int, global_tick: int) -> Clock:
|
||||
"""Ticks 1..4500 belong to cycle 0; tick 0 is initial state, not evidence."""
|
||||
trial = self.trial(trial_index)
|
||||
_integer(global_tick, 1, trial.total_ticks, "evidence global tick")
|
||||
cycle = (global_tick - 1) // CYCLE_TICKS
|
||||
return Clock(global_tick, cycle, global_tick - cycle * CYCLE_TICKS)
|
||||
|
||||
def next_command_clock(self, trial_index: int, global_tick: int, *, seam_admitted: bool = False) -> Clock | None:
|
||||
"""Control boundary only. Snapshot/evaluate old endpoint BEFORE requesting this.
|
||||
|
||||
``seam_admitted`` is a caller assertion, not a gate result computed here.
|
||||
At final completion return None: never invent a fourth cycle or reset.
|
||||
"""
|
||||
trial = self.trial(trial_index)
|
||||
_integer(global_tick, 0, trial.total_ticks, "command global tick")
|
||||
if type(seam_admitted) is not bool or global_tick % CONTROL_TICKS:
|
||||
raise ValueError("Require a control boundary and boolean seam admission")
|
||||
if global_tick == trial.total_ticks:
|
||||
return None
|
||||
if global_tick and global_tick % CYCLE_TICKS == 0 and not seam_admitted:
|
||||
raise ValueError("Preceding endpoint must pass before advancing command metadata")
|
||||
return Clock(global_tick, global_tick // CYCLE_TICKS, global_tick % CYCLE_TICKS)
|
||||
|
||||
def command(self, trial_index: int, clock: Clock, *, anchor_a_world: Sequence[float],
|
||||
root_origin_world: Sequence[float], weight_N: float) -> Command:
|
||||
"""Fixed A/B targets, not measured landings. SI world coordinates.
|
||||
|
||||
Clock may be an evidence endpoint or a separately admitted next command.
|
||||
Root origin is the initial commanded mounting-port origin, not measured root.
|
||||
"""
|
||||
trial = self.trial(trial_index)
|
||||
if type(clock) is not Clock:
|
||||
raise ValueError("Require Clock metadata")
|
||||
_integer(clock.cycle_index, 0, len(trial.anchor_sequence) - 2, "cycle index")
|
||||
_integer(clock.local_tick, 0, CYCLE_TICKS, "local tick")
|
||||
_integer(clock.global_tick, 0, trial.total_ticks, "global tick")
|
||||
if clock.global_tick != clock.cycle_index * CYCLE_TICKS + clock.local_tick:
|
||||
raise ValueError("Inconsistent global/local clock")
|
||||
a, root = _vector(anchor_a_world, "anchor A"), _vector(root_origin_world, "root origin")
|
||||
if type(weight_N) not in (float, int) or not math.isfinite(weight_N) or weight_N <= 0:
|
||||
raise ValueError("Require positive finite weight_N")
|
||||
start, end = trial.anchor_sequence[clock.cycle_index:clock.cycle_index + 2]
|
||||
b = tuple(x + d for x, d in zip(a, trial.swing_displacement_m))
|
||||
origin, finish = (a, b) if start == "A" else (b, a)
|
||||
delta = tuple(y - x for x, y in zip(origin, finish))
|
||||
phase = bisect_right(PHASE_END_TICKS[:-1], clock.local_tick)
|
||||
phase_start = 0 if phase == 0 else PHASE_END_TICKS[phase - 1]
|
||||
progress = (clock.local_tick - phase_start) / PHASE_TICKS[phase]
|
||||
u = progress * progress * (3 - 2 * progress)
|
||||
du = 6 * progress * (1 - progress) / (PHASE_TICKS[phase] * PHYSICS_DT_S)
|
||||
travel = 0.0 if phase < 3 else u if phase == 3 else 1.0
|
||||
height = u if phase == 2 else 1.0 if phase == 3 else 1 - u if phase == 4 else 0.0
|
||||
dz = 0.05 * (du if phase == 2 else -du if phase == 4 else 0.0)
|
||||
arch = 0.0
|
||||
if phase == 3:
|
||||
arch = 0.01 * math.sin(math.pi * progress) ** 2
|
||||
dz += 0.01 * math.pi * math.sin(2 * math.pi * progress) / (PHASE_TICKS[phase] * PHYSICS_DT_S)
|
||||
target = tuple(origin[j] + travel * delta[j] + (0.05 * height + arch if j == 2 else 0.0)
|
||||
for j in range(3))
|
||||
velocity = tuple((du * delta[j] if phase == 3 else 0.0) + (dz if j == 2 else 0.0) for j in range(3))
|
||||
load = 1.0 if phase == 0 else 1 - u if phase == 1 else u if phase == 5 else 0.0
|
||||
values = (*b, *target, *velocity, *(x - y for x, y in zip(target, root)), weight_N * load)
|
||||
if not all(math.isfinite(x) for x in values):
|
||||
raise ValueError("Nonfinite derived command")
|
||||
return Command(phase, progress, start, end, target, velocity, weight_N * load, 1 - load,
|
||||
root, (0.0, 0.0, 0.0), tuple(x - y for x, y in zip(target, root)))
|
||||
|
||||
|
||||
def validate_protocol(document: dict[str, Any]) -> Protocol:
|
||||
"""Validate exact preregistered v1 keys/types/values; return an immutable copy."""
|
||||
return Protocol(document)
|
||||
|
||||
|
||||
def _unique_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError(f"Duplicate JSON key: {key}")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
|
||||
def load_protocol(path: str | Path) -> Protocol:
|
||||
"""Read JSON without duplicate-key or nonfinite-value escape hatches."""
|
||||
return validate_protocol(json.loads(Path(path).read_text(), object_pairs_hook=_unique_keys))
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Untrained 46D residual network API. No trainer/checkpoint migration in this module."""
|
||||
import math
|
||||
|
||||
import torch
|
||||
from torch import nn
|
||||
from torch.distributions import Normal
|
||||
|
||||
from .config import FEATURE_VERSION
|
||||
|
||||
|
||||
def features(x):
|
||||
if (not isinstance(x, torch.Tensor) or x.ndim != 2 or x.shape[1] != 46 or not len(x)
|
||||
or x.dtype != torch.float32 or not torch.isfinite(x).all()):
|
||||
raise ValueError('Require finite float32 [B,46] simulation-truth residual features')
|
||||
return x
|
||||
|
||||
|
||||
class SimResidualActorCritic(nn.Module):
|
||||
feature_version = FEATURE_VERSION
|
||||
|
||||
def __init__(self, hidden=128, initial_std=.1):
|
||||
super().__init__()
|
||||
if type(hidden) is not int or hidden < 8 or not .02 <= initial_std <= .5:
|
||||
raise ValueError('Invalid residual network parameters')
|
||||
offset, scale = torch.zeros(46), torch.ones(46)
|
||||
offset[:3] = torch.tensor([0., .8, -1.5])
|
||||
scale[:3], scale[3:6] = .5, 10.
|
||||
scale[6:12] = torch.tensor([50., 50., 50., 5., 5., 5.])
|
||||
scale[15:18], scale[28:31], scale[31] = 5., .4, 50.
|
||||
scale[32:35], scale[35:38], scale[38], scale[39] = .1, 1., 50., .05
|
||||
self.register_buffer('offset', offset)
|
||||
self.register_buffer('scale', scale)
|
||||
self.actor = nn.Sequential(nn.Linear(46, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(),
|
||||
nn.Linear(hidden, 3))
|
||||
self.critic = nn.Sequential(nn.Linear(46, hidden), nn.Tanh(), nn.Linear(hidden, hidden), nn.Tanh(),
|
||||
nn.Linear(hidden, 1))
|
||||
for layer in self.modules():
|
||||
if isinstance(layer, nn.Linear):
|
||||
nn.init.orthogonal_(layer.weight, math.sqrt(2))
|
||||
nn.init.zeros_(layer.bias)
|
||||
nn.init.zeros_(self.actor[-1].weight) # deterministic initial policy is EXACTLY zero residual
|
||||
nn.init.orthogonal_(self.critic[-1].weight, 1.)
|
||||
self.log_std = nn.Parameter(torch.full((3,), math.log(initial_std)))
|
||||
self.float()
|
||||
|
||||
def distribution_value(self, x):
|
||||
normalized = ((features(x) - self.offset) / self.scale).clamp(-10, 10)
|
||||
return Normal(self.actor(normalized), self.log_std.clamp(math.log(.02), math.log(.5)).exp()), \
|
||||
self.critic(normalized).squeeze(-1)
|
||||
|
||||
def act(self, x, deterministic=False):
|
||||
dist, value = self.distribution_value(x)
|
||||
latent = dist.mean if deterministic else dist.sample()
|
||||
return latent.tanh(), latent, dist.log_prob(latent).sum(-1), value
|
||||
|
||||
def evaluate(self, x, latent):
|
||||
dist, value = self.distribution_value(x)
|
||||
return dist.log_prob(latent).sum(-1), value
|
||||
|
||||
def value(self, x):
|
||||
return self.distribution_value(x)[1]
|
||||
@@ -0,0 +1,342 @@
|
||||
"""46D residual learner boundary; no training launch or legacy checkpoint migration.
|
||||
|
||||
PPO math is unchanged. Callers must collect with this module (diagnostics fail
|
||||
closed), record rollout_diagnostics before ppo_step, and own authorization/budgets.
|
||||
"""
|
||||
|
||||
import copy
|
||||
import io
|
||||
import math
|
||||
import os
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from ..contact_cycle.mechanics import canonical_ids
|
||||
from ..contact_cycle.ppo import rollout_diagnostics # noqa: F401
|
||||
from ..contact_cycle.task import FAILURE_NAMES
|
||||
from ..standing_ppo import ppo_step, restore_rng, rng_state # noqa: F401
|
||||
from .config import FEATURE_VERSION
|
||||
from .model import SimResidualActorCritic, features
|
||||
|
||||
CONTRACT = "go2-fl-contact-cycle-sim-residual-v1"
|
||||
CHECKPOINT_FORMAT = "skillfactory.contact-cycle-sim-residual-ppo-checkpoint.v1"
|
||||
|
||||
|
||||
def _tensor(x, shape, dtype, device, name):
|
||||
if (not isinstance(x, torch.Tensor) or x.shape != shape or x.dtype != dtype
|
||||
or x.device != device or not torch.isfinite(x).all()):
|
||||
raise ValueError(f"Invalid {name}: require finite {dtype} {shape} on {device}")
|
||||
return x
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def bootstrap_values(model, next_features, terminated, truncated, info):
|
||||
"""Failures are zero; only pre-reset terminal policy can bootstrap timeouts."""
|
||||
x = features(next_features)
|
||||
shape = (len(x),)
|
||||
_tensor(terminated, shape, torch.bool, x.device, "terminated")
|
||||
_tensor(truncated, shape, torch.bool, x.device, "truncated")
|
||||
if not isinstance(info, dict):
|
||||
raise ValueError("Invalid step info")
|
||||
value = torch.zeros(len(x), device=x.device, dtype=torch.float32)
|
||||
continuing = ~(terminated | truncated)
|
||||
if continuing.any():
|
||||
v = model.value(x[continuing])
|
||||
value[continuing] = _tensor(v, (int(continuing.sum()),), torch.float32, x.device, "next value")
|
||||
timeout = truncated & ~terminated
|
||||
if timeout.any():
|
||||
ids, terminal = info.get("terminal_ids"), info.get("terminal_observation")
|
||||
if ids is None or not isinstance(terminal, dict) or "policy" not in terminal:
|
||||
raise RuntimeError("Missing pre-reset timeout observations")
|
||||
try:
|
||||
ids = canonical_ids(ids, len(x)).to(x.device)
|
||||
except ValueError as error:
|
||||
raise RuntimeError("Invalid terminal indices") from error
|
||||
if (not torch.isin(timeout.nonzero().flatten(), ids).all()
|
||||
or not (terminated | truncated)[ids].all()):
|
||||
raise RuntimeError("Invalid terminal coverage: missing timeout or nonterminal index")
|
||||
terminal_x = features(terminal["policy"])
|
||||
if len(terminal_x) != len(ids) or terminal_x.device != x.device:
|
||||
raise RuntimeError("Terminal observation/index shape or device mismatch")
|
||||
selected = timeout[ids]
|
||||
v = model.value(terminal_x[selected])
|
||||
value[ids[selected]] = _tensor(v, (int(selected.sum()),), torch.float32, x.device, "terminal value")
|
||||
return value
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def collect_rollout(env, model, x, config, guard=lambda: None):
|
||||
"""Copy pre-step tensors before an environment may reuse observation buffers.
|
||||
|
||||
Counts distinguish true failures (including simultaneous timeout flags) from
|
||||
timeout-only resets. Every reset ends GAE, even when its value bootstraps.
|
||||
"""
|
||||
horizon, penalty = config["horizon"], config["failure_penalty"]
|
||||
if (type(horizon) is not int or horizon < 1 or type(env.num_envs) is not int or env.num_envs < 1
|
||||
or type(penalty) not in (int, float) or not math.isfinite(penalty) or penalty < 0
|
||||
or not math.isfinite(env.step_dt) or env.step_dt <= 0):
|
||||
raise ValueError("Invalid rollout dimensions/reward scaling")
|
||||
x = features(x).clone()
|
||||
device, batch = x.device, env.num_envs
|
||||
# Tensor.device canonicalizes CUDA's default index, unlike torch.device('cuda').
|
||||
if len(x) != batch or torch.empty(0, device=env.device).device != device:
|
||||
raise ValueError("Environment/feature batch or device mismatch")
|
||||
data = {key: torch.empty(horizon, batch, *shape, device=device, dtype=dtype)
|
||||
for key, shape, dtype in (
|
||||
("features", (46,), torch.float32), ("latent", (3,), torch.float32),
|
||||
("log_prob", (), torch.float32), ("value", (), torch.float32),
|
||||
("reward", (), torch.float32), ("next_value", (), torch.float32),
|
||||
("done", (), torch.bool), ("phase", (), torch.long),
|
||||
("failure_flags", (len(FAILURE_NAMES),), torch.bool))}
|
||||
failures = timeouts = 0
|
||||
for step in range(horizon):
|
||||
guard()
|
||||
action, latent, logp, value = model.act(x)
|
||||
_tensor(action, (batch, 3), torch.float32, device, "action")
|
||||
if (action.abs() > 1).any():
|
||||
raise ValueError("Residual action outside [-1,1]")
|
||||
for key, item, shape in (("features", x, (batch, 46)), ("latent", latent, (batch, 3)),
|
||||
("log_prob", logp, (batch,)), ("value", value, (batch,))):
|
||||
data[key][step].copy_(_tensor(item, shape, torch.float32, device, key))
|
||||
obs, reward, terminated, truncated, info = env.step(action)
|
||||
nx = features(obs["policy"])
|
||||
_tensor(nx, (batch, 46), torch.float32, device, "next features")
|
||||
nv = bootstrap_values(model, nx, terminated, truncated, info)
|
||||
_tensor(reward, (batch,), torch.float32, device, "reward")
|
||||
reward = reward / env.step_dt - penalty * terminated.float()
|
||||
_tensor(reward, (batch,), torch.float32, device, "scaled reward")
|
||||
diagnostic = info.get("cycle_step")
|
||||
if not isinstance(diagnostic, dict) or not {"phase", "failure_flags"} <= diagnostic.keys():
|
||||
raise RuntimeError("Missing cycle_step diagnostics; rollout cannot be optimized")
|
||||
phase = diagnostic["phase"]
|
||||
if not isinstance(phase, torch.Tensor) or phase.dtype not in (torch.int32, torch.int64):
|
||||
raise ValueError("Invalid cycle_step phase type")
|
||||
_tensor(phase, (batch,), phase.dtype, device, "phase")
|
||||
if ((phase < 0) | (phase > 5)).any():
|
||||
raise ValueError("Invalid cycle_step phase range")
|
||||
flags = _tensor(diagnostic["failure_flags"], (batch, len(FAILURE_NAMES)), torch.bool,
|
||||
device, "failure_flags")
|
||||
for key, item in (("reward", reward), ("next_value", nv), ("done", terminated | truncated),
|
||||
("phase", phase), ("failure_flags", flags)):
|
||||
data[key][step].copy_(item)
|
||||
failures += int(terminated.sum())
|
||||
timeouts += int((truncated & ~terminated).sum())
|
||||
x = nx.clone()
|
||||
return data, x, failures, timeouts
|
||||
|
||||
|
||||
def selection_key(rows):
|
||||
"""Preregistered lexicographic (failure fraction, all-row mean cost)."""
|
||||
if not rows:
|
||||
raise ValueError("Empty validation is not a candidate")
|
||||
failures, scores = 0, []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or type(row.get("success", False)) is not bool:
|
||||
raise ValueError("Invalid validation success flag")
|
||||
if not row.get("success", False):
|
||||
failures += 1
|
||||
scores.append(16.)
|
||||
continue
|
||||
values = [row.get(key) for key in ("height_rms_m", "swing_rms_m", "landing_error_m")]
|
||||
if any(type(v) not in (int, float) or not math.isfinite(v) or v < 0 for v in values):
|
||||
raise ValueError("Missing/nonfinite/negative successful validation metric")
|
||||
scores.append(sum(min(v / scale, 2.) for v, scale in zip(values, (.06, .025, .05))))
|
||||
return failures / len(rows), sum(scores) / len(rows)
|
||||
|
||||
|
||||
def _finite_tree(value):
|
||||
if isinstance(value, torch.Tensor):
|
||||
if not torch.isfinite(value).all():
|
||||
raise ValueError("Nonfinite checkpoint tensor")
|
||||
elif isinstance(value, dict):
|
||||
for key, item in value.items():
|
||||
if type(key) not in (str, int):
|
||||
raise ValueError("Invalid checkpoint mapping key")
|
||||
_finite_tree(item)
|
||||
elif isinstance(value, (list, tuple)):
|
||||
for item in value:
|
||||
_finite_tree(item)
|
||||
elif type(value) is float:
|
||||
if not math.isfinite(value):
|
||||
raise ValueError("Nonfinite checkpoint scalar")
|
||||
elif value is not None and type(value) not in (str, int, bool):
|
||||
raise ValueError("Unsupported checkpoint value type")
|
||||
|
||||
|
||||
def _model_contract(model, model_config):
|
||||
if (type(model) is not SimResidualActorCritic or model.feature_version != FEATURE_VERSION
|
||||
or not isinstance(model_config, dict) or set(model_config) != {"hidden", "initial_std"}
|
||||
or type(model_config["hidden"]) is not int or model_config["hidden"] < 8
|
||||
or type(model_config["initial_std"]) not in (int, float)
|
||||
or not math.isfinite(model_config["initial_std"]) or not .02 <= model_config["initial_std"] <= .5):
|
||||
raise ValueError("Residual model/config/type mismatch")
|
||||
# Construction only checks topology and fixed normalization, not trained weights.
|
||||
# initial_std is explicit provenance: the unchanged model stores no constructor config.
|
||||
with torch.random.fork_rng(devices=[]):
|
||||
expected = SimResidualActorCritic(**model_config)
|
||||
_model_state(model.state_dict(), expected.state_dict())
|
||||
for name in ("actor", "critic"):
|
||||
actual_layers, expected_layers = list(getattr(model, name)), list(getattr(expected, name))
|
||||
if len(actual_layers) != len(expected_layers) or any(
|
||||
type(a) is not type(b) for a, b in zip(actual_layers, expected_layers)):
|
||||
raise ValueError("Residual model topology mismatch")
|
||||
|
||||
|
||||
def _model_state(state, expected):
|
||||
if not isinstance(state, dict) or set(state) != set(expected):
|
||||
raise ValueError("Residual model state keys mismatch")
|
||||
for key, reference in expected.items():
|
||||
value = state[key]
|
||||
if (not isinstance(value, torch.Tensor) or value.shape != reference.shape
|
||||
or value.dtype != reference.dtype or not torch.isfinite(value).all()):
|
||||
raise ValueError(f"Residual model state shape/type/finite mismatch: {key}")
|
||||
if key in ("offset", "scale") and not torch.equal(value.cpu(), reference.cpu()):
|
||||
raise ValueError("Residual fixed normalization mismatch")
|
||||
|
||||
|
||||
def _optimizer_type(optimizer):
|
||||
return f"{type(optimizer).__module__}.{type(optimizer).__qualname__}"
|
||||
|
||||
|
||||
def _same_types(value, reference):
|
||||
if type(value) is not type(reference):
|
||||
return False
|
||||
if isinstance(reference, (tuple, list)):
|
||||
return len(value) == len(reference) and all(_same_types(a, b) for a, b in zip(value, reference))
|
||||
if isinstance(reference, torch.Tensor):
|
||||
return value.shape == reference.shape and value.dtype == reference.dtype
|
||||
return True
|
||||
|
||||
|
||||
def _optimizer_state(optimizer, state):
|
||||
if not isinstance(state, dict) or set(state) != {"state", "param_groups"}:
|
||||
raise ValueError("Invalid optimizer state")
|
||||
groups = state["param_groups"]
|
||||
if not isinstance(groups, list) or len(groups) != len(optimizer.param_groups):
|
||||
raise ValueError("Optimizer parameter groups mismatch")
|
||||
parameters, amsgrad = {}, {}
|
||||
for saved, current in zip(groups, optimizer.param_groups):
|
||||
if not isinstance(saved, dict) or set(saved) != set(current):
|
||||
raise ValueError("Optimizer parameter group fields mismatch")
|
||||
if any(not _same_types(saved[key], current[key]) for key in current if key != "params"):
|
||||
raise ValueError("Optimizer parameter group value type mismatch")
|
||||
ids = saved["params"]
|
||||
if not isinstance(ids, list) or len(ids) != len(current["params"]):
|
||||
raise ValueError("Optimizer parameter count mismatch")
|
||||
for ident, parameter in zip(ids, current["params"]):
|
||||
if type(ident) is not int or ident in parameters:
|
||||
raise ValueError("Invalid optimizer parameter indices")
|
||||
parameters[ident] = parameter
|
||||
amsgrad[ident] = saved.get("amsgrad", False)
|
||||
if not isinstance(state["state"], dict) or not state["state"].keys() <= parameters.keys():
|
||||
raise ValueError("Invalid optimizer state indices")
|
||||
_finite_tree(state)
|
||||
for ident, slots in state["state"].items():
|
||||
if not isinstance(slots, dict):
|
||||
raise ValueError("Invalid optimizer slots")
|
||||
if isinstance(optimizer, torch.optim.Adam):
|
||||
expected_slots = {"step", "exp_avg", "exp_avg_sq"}
|
||||
if amsgrad[ident]:
|
||||
expected_slots.add("max_exp_avg_sq")
|
||||
if set(slots) != expected_slots or any(not isinstance(v, torch.Tensor) for v in slots.values()):
|
||||
raise ValueError("Invalid Adam optimizer slots/types")
|
||||
for key, value in slots.items():
|
||||
if isinstance(value, torch.Tensor):
|
||||
parameter = parameters[ident]
|
||||
if key == "step":
|
||||
if (value.shape != () or not value.is_floating_point()
|
||||
or value.item() < 0 or value.item() != int(value.item())):
|
||||
raise ValueError("Invalid optimizer step")
|
||||
elif value.shape != parameter.shape or value.dtype != parameter.dtype:
|
||||
raise ValueError("Optimizer tensor shape/type mismatch")
|
||||
# Load into a detached copy so framework-level rejection cannot partially mutate the learner.
|
||||
copy.deepcopy(optimizer).load_state_dict(copy.deepcopy(state))
|
||||
|
||||
|
||||
def _rng_contract(state):
|
||||
if not isinstance(state, dict) or set(state) != {"cpu", "cuda"} or not isinstance(state["cuda"], list):
|
||||
raise ValueError("Invalid RNG state")
|
||||
if state["cuda"] and len(state["cuda"]) != torch.cuda.device_count():
|
||||
raise ValueError("RNG CUDA device count mismatch")
|
||||
for device, value in [("cpu", state["cpu"])] + [(f"cuda:{i}", v) for i, v in enumerate(state["cuda"])]:
|
||||
if not isinstance(value, torch.Tensor) or value.dtype != torch.uint8 or value.ndim != 1:
|
||||
raise ValueError("Invalid RNG tensor")
|
||||
try:
|
||||
torch.Generator(device=device).set_state(value.cpu())
|
||||
except RuntimeError as error:
|
||||
raise ValueError("Invalid RNG state bytes") from error
|
||||
|
||||
|
||||
def _checkpoint_contract(data, model, optimizer, identity, model_config):
|
||||
required = {"format", "contract", "features", "model_config", "model", "optimizer", "optimizer_type",
|
||||
"identity", "update", "best", "rng", "budget_snapshot", "accepted_skill"}
|
||||
if (not isinstance(data, dict) or set(data) != required or data["format"] != CHECKPOINT_FORMAT
|
||||
or data["contract"] != CONTRACT or data["features"] != FEATURE_VERSION
|
||||
or not isinstance(identity, dict) or data["identity"] != identity
|
||||
or data["model_config"] != model_config or data["optimizer_type"] != _optimizer_type(optimizer)
|
||||
or type(data["update"]) is not int or data["update"] < 0 or data["accepted_skill"] is not False
|
||||
or not isinstance(data["budget_snapshot"], dict)):
|
||||
raise ValueError("Residual checkpoint/config/source/type mismatch")
|
||||
_finite_tree(data)
|
||||
_model_contract(model, model_config)
|
||||
# Validate the saved config's types as well (bool/int equality is not a type check).
|
||||
if any(type(data["model_config"][k]) is not type(model_config[k]) for k in model_config):
|
||||
raise ValueError("Residual checkpoint model_config type mismatch")
|
||||
_model_state(data["model"], model.state_dict())
|
||||
model_parameters = list(model.parameters())
|
||||
optimizer_parameters = [p for group in optimizer.param_groups for p in group["params"]]
|
||||
if len(optimizer_parameters) != len(model_parameters) or {id(p) for p in optimizer_parameters} != {
|
||||
id(p) for p in model_parameters}:
|
||||
raise ValueError("Optimizer is not bound to the residual model")
|
||||
_optimizer_state(optimizer, data["optimizer"])
|
||||
_rng_contract(data["rng"])
|
||||
|
||||
|
||||
def save_checkpoint(path, model, optimizer, identity, update, best, budget, model_config, max_bytes=None):
|
||||
"""Atomically save the distinct learner format; return exact serialized byte count.
|
||||
|
||||
max_bytes is available capacity for the entire temporary file, not net growth
|
||||
after replacement. It must be supplied by the caller's artifact ledger.
|
||||
"""
|
||||
_model_contract(model, model_config)
|
||||
data = {"format": CHECKPOINT_FORMAT, "contract": CONTRACT, "features": FEATURE_VERSION,
|
||||
"model_config": copy.deepcopy(model_config), "model": model.state_dict(),
|
||||
"optimizer": optimizer.state_dict(), "optimizer_type": _optimizer_type(optimizer),
|
||||
"identity": identity, "update": update, "best": best, "rng": rng_state(),
|
||||
"budget_snapshot": budget, "accepted_skill": False}
|
||||
_checkpoint_contract(data, model, optimizer, identity, model_config)
|
||||
buffer = io.BytesIO()
|
||||
torch.save(data, buffer)
|
||||
payload = buffer.getvalue()
|
||||
if max_bytes is not None:
|
||||
if type(max_bytes) is not int or max_bytes < 0:
|
||||
raise ValueError("Invalid temporary checkpoint byte budget")
|
||||
if len(payload) > max_bytes:
|
||||
raise RuntimeError("Insufficient artifact budget for atomic checkpoint temporary file")
|
||||
path = Path(path)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream:
|
||||
temporary = Path(stream.name)
|
||||
stream.write(payload)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return len(payload)
|
||||
|
||||
|
||||
def restore_checkpoint(path, model, optimizer, identity, model_config):
|
||||
"""Validate before mutating; synthetic/future authorized resume, not pilot CLI."""
|
||||
_model_contract(model, model_config)
|
||||
data = torch.load(path, map_location="cpu", weights_only=True)
|
||||
_checkpoint_contract(data, model, optimizer, identity, model_config)
|
||||
model.load_state_dict(data["model"])
|
||||
optimizer.load_state_dict(data["optimizer"])
|
||||
restore_rng(data["rng"])
|
||||
return data
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Privileged simulation reference, factored from the validated analytic verifier.
|
||||
|
||||
Only explicit control-clock refresh/reset advances IK state. Observation reads never do.
|
||||
"""
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle.mechanics import inverse_rotate
|
||||
from SkillFactory.legs.tokens import LegKinematics
|
||||
|
||||
|
||||
class ReferenceController:
|
||||
def __init__(self, state, config):
|
||||
self.s, self.cfg = state, config
|
||||
self.fk = LegKinematics(state.bundle, state.env.device)
|
||||
self.nominal = state.nominal.expand(state.env.num_envs, -1)
|
||||
self.q_ik = self.nominal.clone()
|
||||
self.action = torch.zeros_like(self.q_ik)
|
||||
self.refreshes = torch.zeros(state.env.num_envs, dtype=torch.long, device=state.env.device)
|
||||
self.kp = self.q_ik.new_tensor([j['kp'] for j in state.bundle['spec']['joints']])
|
||||
|
||||
def foot(self, q):
|
||||
transform = self.fk.forward(q)[self.s.bundle['foot']['body']]
|
||||
offset = q.new_tensor(self.s.bundle['foot']['xyz'])
|
||||
return transform[:, :3, 3] + (transform[:, :3, :3] @ offset[:, None]).squeeze(-1)
|
||||
|
||||
def jacobian(self, q):
|
||||
eps = self.cfg['jacobian_epsilon_rad']
|
||||
columns = []
|
||||
for j in range(3):
|
||||
delta = torch.zeros_like(q)
|
||||
delta[:, j] = eps
|
||||
columns.append((self.foot(q + delta) - self.foot(q - delta)) / (2 * eps))
|
||||
return torch.stack(columns, -1)
|
||||
|
||||
def reset(self, ids):
|
||||
self.q_ik[ids] = self.nominal[ids]
|
||||
self.action[ids] = 0
|
||||
self.refreshes[ids] = 0
|
||||
self.refresh(ids)
|
||||
|
||||
def refresh(self, ids):
|
||||
if not len(ids):
|
||||
return
|
||||
s = self.s
|
||||
_, _, target, normal, _ = s.reference()
|
||||
pos, quat, _, _ = s.root()
|
||||
q = self.q_ik[ids].clone()
|
||||
local = inverse_rotate(quat[ids], target[ids] - pos[ids])
|
||||
nominal = self.nominal[ids]
|
||||
for _ in range(self.cfg['ik_iterations']):
|
||||
j = self.jacobian(q)
|
||||
rhs = (local - self.foot(q))[:, :, None]
|
||||
regularizer = torch.eye(3, device=q.device) * self.cfg['ik_damping']
|
||||
dq = j.transpose(-1, -2) @ torch.linalg.solve(j @ j.transpose(-1, -2) + regularizer, rhs)
|
||||
q += dq.squeeze(-1).clamp(-self.cfg['ik_step_limit_rad'], self.cfg['ik_step_limit_rad'])
|
||||
q.clamp_(min=nominal - .5, max=nominal + .5)
|
||||
force = torch.zeros_like(local)
|
||||
force[:, 2] = normal[ids]
|
||||
torque = -(self.jacobian(q).transpose(-1, -2)
|
||||
@ inverse_rotate(quat[ids], force)[:, :, None]).squeeze(-1)
|
||||
scale = s.env.cfg.support_parameters['action_scale_rad']
|
||||
self.q_ik[ids] = q
|
||||
self.action[ids] = ((q + torque / self.kp - nominal) / scale).clamp(-1, 1)
|
||||
self.refreshes[ids] += 1
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Frozen u256 inference boundary; never restore optimizer, RNG or training state."""
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from .config import FEATURE_VERSION, TASK_ID, load_config
|
||||
from .model import SimResidualActorCritic, features
|
||||
|
||||
CANDIDATE = "logs/contact_cycle/sim_residual_training_v1/prepared01/candidate_u0256.pt"
|
||||
CANDIDATE_SHA256 = "c088bb3aecaca751867118858626fd508f7a3983303802d7524353f80802cf99"
|
||||
MANIFEST_SHA256 = "a70a226f176104414d2da295f08cce230f6b91ed3e2b78490c78f7ffce95ab01"
|
||||
MODEL_CONFIG = {"hidden": 128, "initial_std": 0.1}
|
||||
CONTRACT = "go2-fl-contact-cycle-sim-residual-v1"
|
||||
CHECKPOINT_FORMAT = "skillfactory.contact-cycle-sim-residual-ppo-checkpoint.v1"
|
||||
REPLAY_SOURCES = (
|
||||
"scripts/replay_cycle_sim_residual.py",
|
||||
"source/SkillFactory/SkillFactory/legs/contact_cycle_sim/replay.py",
|
||||
)
|
||||
CONTROLLERS = {
|
||||
"learned": "analytic_reference_plus_learned_residual",
|
||||
"reference": "analytic_reference_zero_residual",
|
||||
"script": "analytic_reference_plus_scripted_residual",
|
||||
}
|
||||
|
||||
|
||||
def sha256(payload):
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
|
||||
def canonical(value):
|
||||
return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
||||
|
||||
|
||||
def _bound_file(base, relative):
|
||||
path = base / relative
|
||||
if (Path(relative).is_absolute() or ".." in Path(relative).parts
|
||||
or not path.resolve().is_relative_to(base.resolve())
|
||||
or any(p.is_symlink() for p in (path, *path.parents) if p != base.parent)):
|
||||
raise ValueError(f"Unsafe bound source path: {relative}")
|
||||
return path
|
||||
|
||||
|
||||
def verify_bundle(root, checkpoint=None):
|
||||
"""Check all immutable snapshot bytes and live inputs, not a newly generated manifest.
|
||||
|
||||
AGENT.md is the sole parent-approved live-only exception: instructions are not
|
||||
runtime code. Its immutable snapshot MUST still match, and drift is reported.
|
||||
New replay files are separately bound; no training source is rewritten.
|
||||
"""
|
||||
root = Path(root).resolve()
|
||||
checkpoint = Path(checkpoint) if checkpoint is not None else root / CANDIDATE
|
||||
manifest = json.loads((checkpoint.parent / "manifest.json").read_text())
|
||||
if sha256(canonical(manifest).encode()) != MANIFEST_SHA256:
|
||||
raise ValueError("Frozen training manifest SHA256 mismatch")
|
||||
if (manifest["contract"] != CONTRACT or manifest["task_id"] != TASK_ID
|
||||
or manifest["features"] != FEATURE_VERSION
|
||||
or canonical(manifest["model_config"]) != canonical(MODEL_CONFIG)):
|
||||
raise ValueError("Frozen manifest 46D/config identity mismatch")
|
||||
exceptions = []
|
||||
for relative, expected in manifest["sources"].items():
|
||||
snapshot = _bound_file(checkpoint.parent / "source_snapshot", relative)
|
||||
if sha256(snapshot.read_bytes()) != expected:
|
||||
raise ValueError(f"Training source snapshot mismatch: {relative}")
|
||||
live = _bound_file(root, relative)
|
||||
actual = sha256(live.read_bytes())
|
||||
if actual != expected:
|
||||
if relative != "AGENT.md":
|
||||
raise ValueError(f"Live bound source/config mismatch: {relative}")
|
||||
exceptions.append({"path": relative, "snapshot_sha256": expected, "live_sha256": actual,
|
||||
"reason": "Parent-approved non-runtime instruction drift only; snapshot unchanged"})
|
||||
if relative.startswith("source/SkillFactory/SkillFactory/") and relative.endswith(".py"):
|
||||
name = relative.removeprefix("source/SkillFactory/").removesuffix(".py").replace("/", ".")
|
||||
name = name.removesuffix(".__init__")
|
||||
loaded = sys.modules.get(name)
|
||||
if loaded is not None and Path(getattr(loaded, "__file__", "")).resolve() != live.resolve():
|
||||
raise ValueError(f"Imported runtime source is outside verified tree: {name}")
|
||||
cfg = manifest["training"]
|
||||
task = load_config(root / cfg["task_config"])
|
||||
if task["residual_limit_rad"] != .05:
|
||||
raise ValueError("Frozen residual config mismatch")
|
||||
# Check before torch deserialization, including reference/script invocations.
|
||||
if sha256(checkpoint.read_bytes()) != CANDIDATE_SHA256:
|
||||
raise ValueError("Frozen candidate SHA256 mismatch")
|
||||
return manifest, {"candidate_path": str(checkpoint.resolve()), "candidate_sha256": CANDIDATE_SHA256,
|
||||
"manifest_sha256": MANIFEST_SHA256, "snapshot_files_verified": len(manifest["sources"]),
|
||||
"live_source_exceptions": exceptions,
|
||||
"replay_sources": {p: sha256((root / p).read_bytes()) for p in REPLAY_SOURCES}}
|
||||
|
||||
|
||||
def load_frozen_policy(checkpoint, manifest):
|
||||
"""Deserialize the exact verified bytes on CPU; optimizer/RNG payload is ignored."""
|
||||
payload = Path(checkpoint).read_bytes()
|
||||
if sha256(payload) != CANDIDATE_SHA256:
|
||||
raise ValueError("Frozen candidate SHA256 mismatch")
|
||||
data = torch.load(io.BytesIO(payload), map_location="cpu", weights_only=True)
|
||||
identity = data.get("identity", {}) if isinstance(data, dict) else {}
|
||||
if (not isinstance(data, dict) or not isinstance(identity, dict) or data.get("format") != CHECKPOINT_FORMAT
|
||||
or data.get("contract") != CONTRACT or data.get("features") != FEATURE_VERSION
|
||||
or type(data.get("update")) is not int or data["update"] != 256
|
||||
or data.get("accepted_skill") is not False
|
||||
or canonical(data.get("model_config")) != canonical(MODEL_CONFIG)
|
||||
or canonical(identity.get("manifest")) != canonical(manifest)
|
||||
or sha256(canonical(manifest).encode()) != MANIFEST_SHA256
|
||||
or canonical(identity.get("model_config")) != canonical(MODEL_CONFIG)
|
||||
or type(identity.get("seed")) is not int or identity["seed"] != 91501):
|
||||
raise ValueError("Frozen checkpoint 46D/config/source identity mismatch (no legacy migration)")
|
||||
with torch.random.fork_rng(devices=[]):
|
||||
policy = SimResidualActorCritic(**MODEL_CONFIG)
|
||||
expected, saved = policy.state_dict(), data.get("model")
|
||||
if not isinstance(saved, dict) or set(saved) != set(expected):
|
||||
raise ValueError("Frozen model state keys mismatch")
|
||||
for name, reference in expected.items():
|
||||
value = saved[name]
|
||||
if (not isinstance(value, torch.Tensor) or value.shape != reference.shape
|
||||
or value.dtype != reference.dtype or not torch.isfinite(value).all()):
|
||||
raise ValueError(f"Frozen model state shape/dtype/finite mismatch: {name}")
|
||||
if name in ("offset", "scale") and not torch.equal(value, reference):
|
||||
raise ValueError("Frozen 46D normalization mismatch")
|
||||
policy.load_state_dict(saved, strict=True)
|
||||
return policy.eval().requires_grad_(False)
|
||||
|
||||
|
||||
def controller_identity(mode, script_action=None):
|
||||
if mode not in CONTROLLERS:
|
||||
raise ValueError("Explicit learned/reference/script controller required")
|
||||
if mode == "script":
|
||||
if (script_action is None or len(script_action) != 3
|
||||
or any(type(v) not in (float, int) or not -1 <= v <= 1 for v in script_action)):
|
||||
raise ValueError("Script requires three finite normalized residuals in [-1,1]")
|
||||
elif script_action is not None:
|
||||
raise ValueError("Script action is only valid for script controller")
|
||||
return {"controller_mode": mode, "controller_kind": CONTROLLERS[mode],
|
||||
"trained_residual_policy": mode == "learned", "script_action_normalized": script_action,
|
||||
"feature_version": FEATURE_VERSION, "task_id": TASK_ID,
|
||||
"optimizer_steps": 0, "accepted_skill": False, "independent_test_executed": False}
|
||||
|
||||
|
||||
@torch.inference_mode()
|
||||
def inference_action(observation, mode, policy=None, script_action=None):
|
||||
controller_identity(mode, script_action)
|
||||
x = features(observation)
|
||||
if mode == "learned":
|
||||
if policy is None:
|
||||
raise ValueError("Missing learned policy; reference fallback is forbidden")
|
||||
normalized = ((x - policy.offset) / policy.scale).clamp(-10, 10)
|
||||
mean = policy.actor(normalized)
|
||||
std = policy.log_std.clamp(math.log(.02), math.log(.5)).exp()
|
||||
action = mean.tanh()
|
||||
if not all(bool(torch.isfinite(v).all()) for v in (action, mean, std)):
|
||||
raise ValueError("Nonfinite frozen policy output")
|
||||
return action, mean, std
|
||||
if policy is not None:
|
||||
raise ValueError("Non-learned controller cannot receive learned policy")
|
||||
action = torch.zeros(len(x), 3, dtype=torch.float32, device=x.device)
|
||||
if mode == "script":
|
||||
action[:] = action.new_tensor(script_action)
|
||||
return action, None, None
|
||||
|
||||
|
||||
def create_output(root, output, checkpoint):
|
||||
output = Path(output).resolve()
|
||||
# No replay artifact may be placed inside any historical training or release tree.
|
||||
protected = (Path(root).resolve() / "releases",
|
||||
Path(root).resolve() / "logs/contact_cycle/sim_residual_training_v1",
|
||||
Path(checkpoint).resolve().parent)
|
||||
if any(output.is_relative_to(p) for p in protected):
|
||||
raise ValueError("Replay output must be independent of frozen/historical artifacts")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
return output
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Finite RootXY training provenance, not an evaluation/P1/P2 binding.
|
||||
|
||||
Uses the reviewed lossless config and installed import provenance mechanisms.
|
||||
No interpreter-wide attestation: only explicit source roles/config references and
|
||||
installed namespaces are bound. Incidental third-party imports are not traversed.
|
||||
"""
|
||||
from pathlib import Path
|
||||
|
||||
FORMAT = 'skillfactory.rootxy-training-binding.v2'
|
||||
PROFILE = 'rootxy-v2-7200s-1GiB-73460calls'
|
||||
SCRIPT = 'scripts/train_cycle_sim_rootxy_v2.py'
|
||||
ROLES = (
|
||||
'SkillFactory.legs.contact_cycle_sim.rootxy_training_v2',
|
||||
'SkillFactory.legs.contact_cycle_sim.rootxy_runner_v2',
|
||||
'SkillFactory.legs.contact_cycle_sim.rootxy_binding_v2',
|
||||
'SkillFactory.legs.contact_cycle_sim.rootxy_runtime_v2',
|
||||
'SkillFactory.legs.contact_cycle_sim.rootxy_selection_v2',
|
||||
'SkillFactory.legs.contact_cycle_sim.training',
|
||||
'SkillFactory.legs.contact_cycle_sim.ppo',
|
||||
'SkillFactory.legs.contact_cycle_sim.model',
|
||||
'SkillFactory.legs.contact_cycle_sim.replay',
|
||||
'SkillFactory.tasks.manager_based.contact_cycle_sim.rootxy_cfg_v2',
|
||||
'SkillFactory.tasks.manager_based.contact_cycle_sim.rootxy_recording_v2',
|
||||
'SkillFactory.tasks.manager_based.contact_cycle_sim.env',
|
||||
'SkillFactory.tasks.manager_based.contact_cycle_sim.mdp',
|
||||
'SkillFactory.tasks.manager_based.contact_cycle.recording',
|
||||
'audit_contact_cycle_functional', 'rootxy_launch_v2', 'evaluate_cycle_sim_residual', '__main__',
|
||||
)
|
||||
HOOKS = {'physics': 'RootXYPhysicsHooks.class_step_before_after',
|
||||
'safety': 'PhysicalSafetyAudit.scene_update_500Hz_including_resets',
|
||||
'learner': 'rootxy_runner_v2.RuntimeHooks',
|
||||
'cleanup': 'OwnedProcesses.pidfd_subreaper_waited_exit',
|
||||
'candidate': 'supervisor_only_after_postexit_and_cleanup'}
|
||||
|
||||
|
||||
def sources(root, binding):
|
||||
names = set(ROLES)
|
||||
result = {}
|
||||
for name in sorted(names):
|
||||
path = binding._module_file(name)
|
||||
if name.startswith('SkillFactory.'):
|
||||
expected = root / 'source/SkillFactory' / (name.replace('.', '/') + '.py')
|
||||
else:
|
||||
expected = root / (SCRIPT if name == '__main__' else 'scripts/' + name + '.py')
|
||||
if path != expected:
|
||||
raise ValueError('RootXY source-role path mismatch: ' + name)
|
||||
result[name] = {'path': str(path), 'sha256': binding.sha256(path.read_bytes())}
|
||||
return result, names
|
||||
|
||||
|
||||
def components(root, cfg):
|
||||
from . import evaluation_binding as binding
|
||||
records, names = sources(Path(root), binding)
|
||||
roles = set(names)
|
||||
encoded = binding._encode(cfg, names, set())
|
||||
imports = binding._imports(names, Path(root))
|
||||
return binding, records, roles, encoded, imports
|
||||
|
||||
|
||||
def propose_inventory(root, cfg, native_layouts):
|
||||
"""Preparation proposal only; later grant binds the exact unchanged bytes."""
|
||||
b, _, roles, _, imports = components(root, cfg)
|
||||
required = b.required_dependencies(set(imports), roles)
|
||||
modules = {name: b._dependency_module_identity(name) for name in sorted(required)}
|
||||
roots = {name: Path(modules[name]['path']).parent for name in b.NUMERICAL_ROOTS}
|
||||
artifacts = {}
|
||||
|
||||
def add(path, owner, vendor=False):
|
||||
path = b._file(path)
|
||||
label = str(path)
|
||||
if label in artifacts:
|
||||
raise ValueError('Duplicate native artifact: ' + label)
|
||||
artifacts[label] = {'module': owner, 'path': label, 'sha256': b.sha256(path.read_bytes()),
|
||||
'purpose': 'Installed numerical implementation consumed by ' + owner}
|
||||
if vendor:
|
||||
artifacts[label]['vendor'] = 'NVIDIA'
|
||||
|
||||
for owner, directories in native_layouts(roots).items():
|
||||
for directory in directories:
|
||||
paths = sorted(directory.glob('*.so*'))
|
||||
if not paths:
|
||||
raise ValueError('Missing native layout: ' + str(directory))
|
||||
for path in paths:
|
||||
add(path, owner)
|
||||
if (roots['torch'] / 'lib/libtorch_cuda.so').is_file():
|
||||
for package in b.NVIDIA_CUDA_PACKAGES:
|
||||
for path in sorted((roots['torch'].parent / 'nvidia' / package / 'lib').glob('*.so*')):
|
||||
add(path, 'torch', True)
|
||||
inventory = {'scope': b.INVENTORY_SCOPE, 'modules': modules, 'artifacts': artifacts}
|
||||
return b._dependency_inventory(inventory, set(imports), roles)
|
||||
|
||||
|
||||
def normalization_updates(cfg):
|
||||
from . import evaluation_binding as binding
|
||||
return binding._typed_normalization_updates(cfg,
|
||||
'SkillFactory.tasks.manager_based.contact_cycle_sim.rootxy_cfg_v2',
|
||||
'RootXYContactCycleEnvCfg', 128)
|
||||
|
||||
|
||||
def normalize_config(cfg):
|
||||
"""Exact128-env RootXY PREconstruction normalization; never runtime repair."""
|
||||
for obj, field, value in normalization_updates(cfg):
|
||||
setattr(obj, field, value)
|
||||
|
||||
|
||||
def snapshot(root, output, cfg, inventory, manifest):
|
||||
from . import rootxy_training_v2 as p
|
||||
from SkillFactory.tasks.manager_based.contact_cycle_sim.rootxy_cfg_v2 import RootXYContactCycleEnvCfg
|
||||
b, records, roles, encoded, imports = components(root, cfg)
|
||||
if (type(cfg) is not RootXYContactCycleEnvCfg or type(cfg.seed) is not int
|
||||
or cfg.seed not in (92511, 93511) or cfg.scene.num_envs != 128
|
||||
or cfg.task_identity != p.TASK_ID or normalization_updates(cfg)):
|
||||
raise ValueError('RootXY actual config/seed/normalization mismatch')
|
||||
if not p.exact(manifest, p.make_manifest(root, Path(root) / p.CONFIG_PATH)):
|
||||
raise ValueError('RootXY preregistration changed')
|
||||
# The ONLY temporary override, validated above; never normalize other drift.
|
||||
encoded['fields']['mapping']['seed'] = {'override': '92511_train_or_93511_development_only'}
|
||||
_, frozen = p.replay.verify_bundle(root)
|
||||
return {'format': FORMAT, 'profile': PROFILE, 'root': str(Path(root).resolve()),
|
||||
'artifact_root': str(Path(output).resolve()), 'task_id': p.TASK_ID,
|
||||
'hooks': HOOKS, 'preregistration_sha256': p.digest(manifest),
|
||||
'sources': records, 'imports': imports, 'effective_config': encoded,
|
||||
'dependency_inventory': b._dependency_inventory(inventory, set(imports), roles),
|
||||
'runtime_layout_pins': dict(b.RUNTIME_LAYOUT_PINS),
|
||||
'required_runtime_roles': dict(b.REQUIRED_RUNTIME),
|
||||
'scope': b.PROVENANCE_SCOPE, 'limitations': b.PROVENANCE_LIMITATIONS,
|
||||
'frozen_weights_only_source': frozen, 'accepted_skill': False,
|
||||
'execution_authorized': False}
|
||||
|
||||
|
||||
def verify(expected, **arguments):
|
||||
from . import rootxy_training_v2 as p
|
||||
actual = snapshot(**arguments)
|
||||
if not p.exact(expected, actual):
|
||||
raise ValueError('RootXY training binding drift (no postconstruction repair)')
|
||||
return actual
|
||||
@@ -0,0 +1,89 @@
|
||||
"""Bounded, streaming first-episode XY diagnostics at PHYSICS frequency.
|
||||
|
||||
No 30mm termination: breach is latched even after recovery. Partial intervals
|
||||
never become full-episode RMS evidence. No physics-frequency full-state log.
|
||||
"""
|
||||
import torch
|
||||
|
||||
|
||||
class RootXYMetrics:
|
||||
def __init__(self, num_envs, device="cpu"):
|
||||
self.num_envs = num_envs
|
||||
self.device = torch.device(device)
|
||||
self.count = torch.zeros(num_envs, dtype=torch.long, device=device)
|
||||
self.live = torch.ones(num_envs, dtype=torch.bool, device=device)
|
||||
self.clock_ok = self.live.clone()
|
||||
self.breached = ~self.live
|
||||
self.safety_ok = self.live.clone()
|
||||
self.first_breach = torch.full((num_envs,), -1, dtype=torch.long, device=device)
|
||||
self.maximum = torch.zeros(num_envs, dtype=torch.float64, device=device)
|
||||
self.sum_square = self.maximum.clone()
|
||||
self.uncapped_xy_sum = self.maximum.clone()
|
||||
self.cap_count = self.count.clone()
|
||||
self.reference_saturated = self.count.clone()
|
||||
self.authority_shortfall = self.maximum.clone()
|
||||
self.phase_count = torch.zeros(num_envs, 6, dtype=torch.long, device=device)
|
||||
self.phase_square = torch.zeros(num_envs, 6, dtype=torch.float64, device=device)
|
||||
|
||||
def tick(self, *, time, position_error, phase, reference, request, effective_residual, safety_ok):
|
||||
n = self.num_envs
|
||||
for name, value, shape in (("time", time, (n,)), ("position_error", position_error, (n, 3)),
|
||||
("phase", phase, (n,)), ("reference", reference, (n, 3)),
|
||||
("request", request, (n, 3)), ("effective_residual", effective_residual, (n, 3)),
|
||||
("safety_ok", safety_ok, (n,))):
|
||||
if (not isinstance(value, torch.Tensor) or value.shape != shape or value.device != self.device
|
||||
or not torch.isfinite(value).all()):
|
||||
raise ValueError("Invalid physics-tick " + name)
|
||||
if (phase.dtype != torch.long or safety_ok.dtype != torch.bool or (phase < 0).any() or (phase > 5).any()
|
||||
or (reference.abs() > 1).any() or (request.abs() > 1).any()
|
||||
or (effective_residual.abs() > .05 + 1e-6).any()):
|
||||
raise ValueError("Invalid physics phase/action/safety contract")
|
||||
live = self.live
|
||||
if (self.count[live] >= 4500).any():
|
||||
raise ValueError("Extra first-episode physics ticks")
|
||||
self.count += live.long()
|
||||
self.clock_ok &= ~live | ((time.double() - self.count * .002).abs() <= 1e-5)
|
||||
square = position_error[:, :2].double().square().sum(-1)
|
||||
xy = square.sqrt()
|
||||
hit = live & (xy > .03)
|
||||
self.first_breach[hit & ~self.breached] = self.count[hit & ~self.breached]
|
||||
self.breached |= hit
|
||||
self.maximum = torch.maximum(self.maximum, torch.where(live, xy, 0.))
|
||||
self.sum_square += square * live
|
||||
uncapped_xy = square / .03**2
|
||||
self.uncapped_xy_sum += uncapped_xy * live
|
||||
self.cap_count += (live & (uncapped_xy + (position_error[:, 2].double() / .04).square() >= 10)).long()
|
||||
self.reference_saturated += (live & (reference.abs() >= 1).any(-1)).long()
|
||||
shortfall = (request.double() * .05 - effective_residual.double()).abs().amax(-1)
|
||||
self.authority_shortfall = torch.maximum(self.authority_shortfall, torch.where(live, shortfall, 0.))
|
||||
self.safety_ok &= ~live | safety_ok
|
||||
ids = live.nonzero().flatten()
|
||||
self.phase_count[ids, phase[ids]] += 1
|
||||
self.phase_square[ids, phase[ids]] += square[ids]
|
||||
|
||||
def end_control(self, terminated, truncated):
|
||||
for value in (terminated, truncated):
|
||||
if value.shape != self.live.shape or value.dtype != torch.bool or value.device != self.device:
|
||||
raise ValueError("Invalid first-episode terminal flags")
|
||||
self.live &= ~(terminated | truncated)
|
||||
|
||||
def rows(self):
|
||||
if (self.count == 0).any():
|
||||
raise ValueError("Missing physics-tick diagnostics")
|
||||
rows = []
|
||||
for e in range(self.num_envs):
|
||||
count = int(self.count[e])
|
||||
rows.append({"env": e, "physics_samples": count,
|
||||
"complete_clock": bool(count == 4500 and self.clock_ok[e] and not self.live[e]),
|
||||
"rootxy_rms_m": float((self.sum_square[e] / count).sqrt()),
|
||||
"rms_scope": "full_episode" if count == 4500 else "observed_prefix_only",
|
||||
"rootxy_max_m": float(self.maximum[e]), "rootxy_breached": bool(self.breached[e]),
|
||||
"first_rootxy_breach_tick": int(self.first_breach[e]) if self.breached[e] else None,
|
||||
"uncapped_xy_cost_mean": float(self.uncapped_xy_sum[e] / count),
|
||||
"position_cap_fraction": float(self.cap_count[e] / count),
|
||||
"reference_saturated_fraction": float(self.reference_saturated[e] / count),
|
||||
"effective_authority_shortfall_max_rad": float(self.authority_shortfall[e]),
|
||||
"phase_physics_samples": self.phase_count[e].cpu().tolist(),
|
||||
"phase_xy_square_sum_m2": self.phase_square[e].cpu().tolist(),
|
||||
"safety_ok": bool(self.safety_ok[e])})
|
||||
return rows
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Reusable learner body, NOT a launcher or authorization adapter.
|
||||
|
||||
The future sole-owner supervisor supplies authenticated admission, native monitor,
|
||||
BOOTTIME/physical-call debit instrumentation, installed/full actual-cfg identity,
|
||||
cooperative cancellation and bounded cleanup. Nothing here spawns a subprocess.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import traceback
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import torch
|
||||
|
||||
from . import rootxy_training_v2 as protocol
|
||||
from .model import features
|
||||
from .replay import inference_action
|
||||
from .training import isolated_validation_rng, optimize_reserved_rollout, save_trace_subset
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeHooks:
|
||||
# All hooks are mandatory. The adapter must instrument actual sim.step calls
|
||||
# separately: a control call is NOT a physics tick or 128 physical calls.
|
||||
admit: Callable[[dict], dict]
|
||||
guard: Callable[[], None]
|
||||
verify_identity: Callable[[], None]
|
||||
before_control: Callable[[str], None]
|
||||
after_control: Callable[[str], None]
|
||||
progress: Callable[[dict], None]
|
||||
finish: Callable[[dict], None] # notification only; owner closes env/app, waits, verifies cleanup
|
||||
|
||||
|
||||
class _ControlledEnv:
|
||||
def __init__(self, env, hooks, guard):
|
||||
self.env, self.hooks, self.guard = env, hooks, guard
|
||||
self.kind = 'optimization'
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self.env, name)
|
||||
|
||||
def step(self, action):
|
||||
self.guard()
|
||||
self.hooks.before_control(self.kind) # durable adapter debit before attempted call
|
||||
result = self.env.step(action)
|
||||
self.hooks.after_control(self.kind)
|
||||
self.guard()
|
||||
return result
|
||||
|
||||
|
||||
def execute(env, root, output, manifest, ledger, observations, hooks, evaluate):
|
||||
"""Future admitted worker API. This function is not reached by the staged CLI.
|
||||
|
||||
observations are saved46D CPU parity rows, not a request for simulator inference.
|
||||
evaluate is the unchanged audit_contact_cycle_functional.evaluate callable.
|
||||
Outputs: bounded JSON result/progress, six validations, at most five eval-only
|
||||
checkpoints and four compact trajectories per validation; no rollout snapshots.
|
||||
"""
|
||||
root, output = Path(root), Path(output)
|
||||
cfg = protocol.load_training_config(root / protocol.CONFIG_PATH, root)
|
||||
if not protocol.exact(manifest, protocol.make_manifest(root, root / protocol.CONFIG_PATH)):
|
||||
raise ValueError('Stale RootXY-v2 manifest')
|
||||
# Admission is delegated, not inferred from a training config or old grant.
|
||||
admission = hooks.admit(manifest)
|
||||
if (not isinstance(admission, dict) or admission.get('manifest_sha256') != protocol.digest(manifest)
|
||||
or admission.get('p2_review_approved') is not True
|
||||
or admission.get('sole_cleanup_owner') is not True
|
||||
or admission.get('native_monitor_active') is not True):
|
||||
raise PermissionError('Missing supervised RootXY-v2 admission')
|
||||
from SkillFactory.tasks.manager_based.contact_cycle_sim.rootxy_cfg_v2 import verify_actual_config
|
||||
from SkillFactory.tasks.manager_based.contact_cycle_sim.rootxy_recording_v2 import RootXYRecorder
|
||||
|
||||
result = {'format': 'skillfactory.contact-cycle-rootxy-result.v2', 'training_complete': False,
|
||||
'accepted_skill': False, 'candidate': None, 'status': 'started',
|
||||
'candidate_authority': 'none; supervisor waited-exit/postexit-identity/cleanup lock required',
|
||||
'checkpoints_selectable': False}
|
||||
provisional_candidate = None
|
||||
|
||||
def invalidate():
|
||||
result.update(status='failed', candidate=None, training_complete=False,
|
||||
checkpoints_selectable=False, error=traceback.format_exc()[-16384:])
|
||||
result.pop('outcome', None)
|
||||
|
||||
def guard():
|
||||
ledger.work_guard()
|
||||
hooks.guard() # stop request, same-boot deadline, native aggregate storage, ownership, physical safety
|
||||
|
||||
def check_identity():
|
||||
guard()
|
||||
hooks.verify_identity()
|
||||
verify_actual_config(env)
|
||||
if protocol.source_identity(root, root / protocol.CONFIG_PATH) != manifest['sources']:
|
||||
raise RuntimeError('Bound sources changed')
|
||||
protocol.v1.verify_snapshot(output, manifest)
|
||||
|
||||
controlled = _ControlledEnv(env, hooks, guard)
|
||||
try:
|
||||
check_identity()
|
||||
model, optimizer, frozen, imported = protocol.import_actor_weights_only(root, observations)
|
||||
if optimizer.state:
|
||||
raise ValueError('Warm-start optimizer must be empty')
|
||||
model.to(env.device)
|
||||
frozen.to(env.device)
|
||||
# Bind after transfer even if framework device conversion replaces Parameters.
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=cfg['algorithm']['learning_rate'],
|
||||
eps=cfg['algorithm']['adam_eps'])
|
||||
identity = {'task_id': protocol.TASK_ID, 'contract': protocol.CONTRACT,
|
||||
'manifest_sha256': protocol.digest(manifest), 'resolved_task': manifest['resolved_task'],
|
||||
'source_sha256': protocol.replay.CANDIDATE_SHA256, 'seed': 92511}
|
||||
ledger.write_json(output / 'warmstart.json', imported)
|
||||
functional = json.loads((root / cfg['functional_config']).read_text())
|
||||
baseline_pair = None
|
||||
|
||||
def save(update):
|
||||
check_identity()
|
||||
path = output / f'checkpoint_u{update:04d}.pt'
|
||||
remaining = cfg['max_artifact_bytes'] - protocol.artifact_bytes(output) - 1048576
|
||||
sha = protocol.save_checkpoint(path, model, identity, update, imported, ledger.data, remaining)
|
||||
guard()
|
||||
return {'path': path.name, 'sha256': sha, 'update': update}
|
||||
|
||||
@torch.no_grad()
|
||||
def validate(label, policy):
|
||||
nonlocal baseline_pair
|
||||
check_identity()
|
||||
ledger.begin_validation(label)
|
||||
controlled.kind = 'validation'
|
||||
with isolated_validation_rng(env, cfg['validation_seed'], cfg['seeds'][0]):
|
||||
observation = features(env.reset()[0]['policy'])
|
||||
with RootXYRecorder(env, functional, policy is not None) as recorder:
|
||||
if baseline_pair is None:
|
||||
baseline_pair = recorder.initial_pair
|
||||
elif any(not torch.equal(value, baseline_pair[key])
|
||||
for key, value in recorder.initial_pair.items()):
|
||||
raise RuntimeError('Validation initial observable pairing mismatch (not full-state proof)')
|
||||
returns = torch.zeros(env.num_envs, device=env.device)
|
||||
for step in range(900):
|
||||
ledger.before_validation_control()
|
||||
action, mean, std = inference_action(observation, 'learned' if policy is not None
|
||||
else 'reference', policy)
|
||||
recorder.before_control(observation, action, mean, std)
|
||||
live = recorder.metrics.live.clone()
|
||||
obs, reward, terminated, truncated, _ = controlled.step(action)
|
||||
ledger.after_validation_control()
|
||||
if not torch.isfinite(reward).all():
|
||||
raise RuntimeError('Nonfinite validation reward')
|
||||
returns += reward * live
|
||||
recorder.end_control(terminated, truncated, step == 899)
|
||||
observation = features(obs['policy'])
|
||||
rows = recorder.rows(evaluate)
|
||||
for row, total in zip(rows, returns.cpu().tolist()):
|
||||
row['episode_return'] = total
|
||||
ledger.write_json(output / f'validation_{label}.json', {
|
||||
'label': label, 'validation_seed': 93511, 'rows': rows, 'accepted_skill': False})
|
||||
selected = ([r['env'] for r in rows if not r['success'] or r['rootxy_breached']]
|
||||
or list(range(env.num_envs)))[:4]
|
||||
save_trace_subset(output / f'validation_{label}_selected.pt', recorder.columns, selected,
|
||||
recorder.stops, lambda size: ledger.guard(reserve_bytes=size + 1048576))
|
||||
if len(rows) != 128 or not all(r['success'] for r in rows):
|
||||
raise RuntimeError('Original functional128/128 regression: stop, no retry')
|
||||
check_identity()
|
||||
controlled.kind = 'optimization'
|
||||
return rows
|
||||
|
||||
save(0)
|
||||
validate('analytic_zero', None)
|
||||
validate('frozen_u256', frozen)
|
||||
ledger.write_json(output / 'warmstart_u0_equivalence.json', {
|
||||
'physical_evaluation': False, 'equivalent_actor': 'frozen_u256', 'evidence': imported,
|
||||
'note': 'Exact CPU actor equivalence only, not physical repeat/full-state equivalence'})
|
||||
best_key = None
|
||||
algo = {**cfg['algorithm'], 'horizon': cfg['horizon']}
|
||||
x = features(env.reset()[0]['policy'])
|
||||
for update in range(1, 257):
|
||||
x, failures, timeouts, learning = optimize_reserved_rollout(
|
||||
controlled, model, optimizer, x, algo, 92511, update, ledger, guard, check_identity)
|
||||
if update in cfg['validation_updates']:
|
||||
rows = validate(f'u{update:04d}', model)
|
||||
key = protocol.candidate_key(rows, update)
|
||||
checkpoint = save(update)
|
||||
if key is not None and (best_key is None or key < best_key):
|
||||
best_key = key
|
||||
provisional_candidate = {**checkpoint, 'selection_key': list(key)}
|
||||
x = features(env.reset()[0]['policy'])
|
||||
# No resume/latest is offered. Pending interrupted work remains fully debited.
|
||||
ledger.commit_update(92511, update)
|
||||
progress = {'format': 'skillfactory.contact-cycle-rootxy-progress.v2', 'update': update,
|
||||
'optimization_reserved_environment_transitions': ledger.data['reserved_transitions'],
|
||||
'validation_reserved_environment_transitions': 806400,
|
||||
'failures': failures, 'timeouts': timeouts, 'learner': learning, 'accepted_skill': False}
|
||||
ledger.append_json(output / 'progress.jsonl', progress)
|
||||
hooks.progress(progress)
|
||||
check_identity()
|
||||
if provisional_candidate is not None:
|
||||
candidate = provisional_candidate
|
||||
if hashlib.sha256((output / candidate['path']).read_bytes()).hexdigest() != candidate['sha256']:
|
||||
raise ValueError('Selected checkpoint changed')
|
||||
result.update(training_complete=True, status='completed_provisional', candidate=provisional_candidate,
|
||||
outcome='provisional_candidate' if provisional_candidate is not None else 'no_candidate')
|
||||
except BaseException:
|
||||
invalidate()
|
||||
raise
|
||||
finally:
|
||||
# No worker lock is authoritative, even on success. Retained checkpoints
|
||||
# are forensic/nonselectable until the external owner commits its own lock.
|
||||
result['budget'] = ledger.data
|
||||
try:
|
||||
try:
|
||||
ledger.write_json(output / 'result.json', result)
|
||||
except BaseException:
|
||||
invalidate()
|
||||
# Failure publication is not a learner retry. Persistent storage
|
||||
# failure still propagates; the owner must treat missing evidence as fatal.
|
||||
ledger.write_json(output / 'result.json', result)
|
||||
raise
|
||||
finally:
|
||||
try:
|
||||
hooks.finish(result)
|
||||
except BaseException:
|
||||
invalidate()
|
||||
ledger.write_json(output / 'result.json', result)
|
||||
raise
|
||||
return result
|
||||
@@ -0,0 +1,191 @@
|
||||
"""RootXY-only lifetime hooks; original environment and safety source stay intact."""
|
||||
from contextlib import ExitStack, contextmanager
|
||||
from functools import wraps
|
||||
|
||||
|
||||
class RootXYPhysicsHooks:
|
||||
"""Instrument actual shared sim.step calls, including constructor and reset.
|
||||
|
||||
Reservation is 72,460 rollout + 1,000 initialization calls, never a refund.
|
||||
Attempted calls are charged even when sim.step throws. Postconstruction every
|
||||
completed call MUST have one original PhysicalSafetyAudit scene-update sample
|
||||
before another step/work boundary. Unsupported reset coverage is fatal.
|
||||
"""
|
||||
def __init__(self, simulation_class, environment_class, guard, publish, *, preparation=False):
|
||||
self.simulation_class, self.environment_class = simulation_class, environment_class
|
||||
self.guard, self.publish, self.preparation = guard, publish, preparation
|
||||
self.attempted = self.completed = self.initialization = self.rollout = 0
|
||||
self.mode = 'initialization'
|
||||
self.audit = None
|
||||
self.audit_start = 0
|
||||
self.patches = []
|
||||
self.active = False
|
||||
|
||||
def report(self):
|
||||
return {'attempted_shared_calls': self.attempted, 'completed_shared_calls': self.completed,
|
||||
'initialization_attempted_shared_calls': self.initialization,
|
||||
'rollout_attempted_shared_calls': self.rollout,
|
||||
'initialization_cap': 1000, 'rollout_reserved_shared_calls': 72460,
|
||||
'total_cap': 73460, 'reservation_unused_is_not_refunded': True,
|
||||
'startup_completed_without_task_audit': self.audit_start,
|
||||
'safety': None if self.audit is None else self.audit.report()}
|
||||
|
||||
def safety_boundary(self):
|
||||
if self.audit is not None:
|
||||
if self.audit.samples != self.completed - self.audit_start:
|
||||
raise RuntimeError('RootXY missing/duplicate 500Hz safety sample, including reset')
|
||||
self.audit.check()
|
||||
|
||||
def attach_audit(self, audit):
|
||||
if self.audit is not None:
|
||||
raise RuntimeError('Duplicate physics audit')
|
||||
self.audit, self.audit_start = audit, self.completed
|
||||
if audit.samples != 0:
|
||||
raise RuntimeError('Audit must begin before first training/reset action')
|
||||
|
||||
def patch(self, owner, name, new):
|
||||
self.patches.append((owner, name, getattr(owner, name), name in vars(owner)))
|
||||
setattr(owner, name, new)
|
||||
|
||||
@contextmanager
|
||||
def scope(self, mode):
|
||||
old = self.mode
|
||||
self.mode = mode
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.mode = old
|
||||
|
||||
def __enter__(self):
|
||||
if self.active:
|
||||
raise RuntimeError('Duplicate physics hook owner')
|
||||
self.active = True
|
||||
original = self.simulation_class.step
|
||||
|
||||
@wraps(original)
|
||||
def step(sim, *args, **kwargs):
|
||||
self.guard()
|
||||
self.safety_boundary()
|
||||
if self.preparation:
|
||||
raise PermissionError('PREP is config-only: sim.step forbidden')
|
||||
if self.mode not in ('initialization', 'rollout'):
|
||||
raise RuntimeError('Unowned physics call')
|
||||
count, cap = ((self.initialization, 1000) if self.mode == 'initialization'
|
||||
else (self.rollout, 72460))
|
||||
if count >= cap or self.attempted >= 73460:
|
||||
raise RuntimeError('RootXY shared physics call cap')
|
||||
self.attempted += 1
|
||||
if self.mode == 'initialization':
|
||||
self.initialization += 1
|
||||
else:
|
||||
self.rollout += 1
|
||||
# Bounded atomic publication BEFORE an actual call, including partial failure.
|
||||
self.publish(self.report())
|
||||
result = original(sim, *args, **kwargs)
|
||||
self.completed += 1
|
||||
self.publish(self.report())
|
||||
self.guard()
|
||||
return result
|
||||
|
||||
self.patch(self.simulation_class, 'step', step)
|
||||
for name in ('reset', '_reset_idx'):
|
||||
old = getattr(self.environment_class, name)
|
||||
|
||||
@wraps(old)
|
||||
def reset(*args, _old=old, **kwargs):
|
||||
self.guard()
|
||||
self.safety_boundary()
|
||||
with self.scope('initialization'):
|
||||
result = _old(*args, **kwargs)
|
||||
self.safety_boundary()
|
||||
self.guard()
|
||||
return result
|
||||
|
||||
self.patch(self.environment_class, name, reset)
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
for owner, name, old, own in reversed(self.patches):
|
||||
if own:
|
||||
setattr(owner, name, old)
|
||||
else:
|
||||
delattr(owner, name)
|
||||
self.patches.clear()
|
||||
self.active = False
|
||||
|
||||
|
||||
def worker_lifecycle(api, *, prepare, guard, verify, publish):
|
||||
"""One owner from partial startup through env.close and app.close.
|
||||
|
||||
api.start must publish app ownership as soon as acquired (including a partially
|
||||
constructed launcher). No result can authorize a candidate. A missing close,
|
||||
verification, or final publication is a failed worker even after learner success.
|
||||
"""
|
||||
result = {'status': 'failed', 'accepted_skill': False, 'training_complete': False,
|
||||
'candidate': None, 'postclose_identity_verified': False}
|
||||
error = None
|
||||
stack = ExitStack()
|
||||
try:
|
||||
guard()
|
||||
api.start()
|
||||
guard()
|
||||
physics = stack.enter_context(api.physics())
|
||||
api.physics_hooks = physics
|
||||
verify()
|
||||
if prepare:
|
||||
result = api.prepare()
|
||||
if physics.attempted:
|
||||
raise RuntimeError('PREP observed physics')
|
||||
else:
|
||||
api.construct() # owner retains partially initialized object for close
|
||||
verify() # immediately postconstructor, BEFORE reset/actions
|
||||
api.check_actual()
|
||||
with api.safety() as audit:
|
||||
physics.attach_audit(audit)
|
||||
result = api.learn()
|
||||
physics.safety_boundary()
|
||||
except BaseException as caught:
|
||||
error = caught
|
||||
finally:
|
||||
try:
|
||||
if api.physics_hooks is not None:
|
||||
api.physics_hooks.mode = 'closed'
|
||||
api.close_env()
|
||||
except BaseException as caught:
|
||||
error = error or caught
|
||||
try:
|
||||
if api.started:
|
||||
verify() # actual same-object cfg after env.close, before app.close
|
||||
result['postclose_identity_verified'] = True
|
||||
except BaseException as caught:
|
||||
error = error or caught
|
||||
try:
|
||||
if api.physics_hooks is not None:
|
||||
result['physics'] = api.physics_hooks.report()
|
||||
except BaseException as caught:
|
||||
error = error or caught
|
||||
if error is not None:
|
||||
result.update(status='failed', training_complete=False, candidate=None,
|
||||
checkpoints_selectable=False, error=str(error)[-8192:])
|
||||
try:
|
||||
publish(result)
|
||||
except BaseException as caught:
|
||||
error = error or caught
|
||||
finally:
|
||||
try:
|
||||
api.close_app(0 if error is None else 1)
|
||||
except BaseException as caught:
|
||||
error = error or caught
|
||||
finally:
|
||||
try:
|
||||
stack.close() # closed-mode sim.step guard covers app teardown too
|
||||
except BaseException as caught:
|
||||
error = error or caught
|
||||
if error is not None:
|
||||
# app.close can itself fail after earlier provisional publication.
|
||||
result.update(status='failed', training_complete=False, candidate=None,
|
||||
checkpoints_selectable=False, error=str(error)[-8192:])
|
||||
publish(result)
|
||||
if error is not None:
|
||||
raise error
|
||||
return result
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Shared stdlib candidate gates for learner and independent supervisor."""
|
||||
import math
|
||||
|
||||
|
||||
def tracking_cost(rows):
|
||||
# Exactly the successful-row branch of the original PPO selection composite.
|
||||
scores = []
|
||||
for row in rows:
|
||||
values = [row.get(key) for key in ("height_rms_m", "swing_rms_m", "landing_error_m")]
|
||||
if any(type(v) not in (int, float) or not math.isfinite(v) or v < 0 for v in values):
|
||||
raise ValueError("Missing/nonfinite/negative successful validation metric")
|
||||
scores.append(sum(min(v / scale, 2.) for v, scale in zip(values, (.06, .025, .05))))
|
||||
return sum(scores) / len(rows)
|
||||
|
||||
|
||||
def candidate_key(rows, update):
|
||||
if type(update) is not int or update not in (64, 128, 192, 256):
|
||||
raise ValueError("Only u64/u128/u192/u256 are selectable")
|
||||
if len(rows) != 128 or [r.get("env") for r in rows] != list(range(128)):
|
||||
raise ValueError("Require all128 unique ordered validation rows")
|
||||
if any(r.get("success") is not True for r in rows):
|
||||
raise RuntimeError("Original functional regression: stop trial")
|
||||
for row in rows:
|
||||
for key in ("rootxy_rms_m", "rootxy_max_m"):
|
||||
value = row.get(key)
|
||||
if type(value) not in (float, int) or not math.isfinite(value) or value < 0:
|
||||
raise ValueError("Missing/nonfinite XY diagnostics")
|
||||
if (type(row.get("physics_samples")) is not int or row["physics_samples"] != 4500
|
||||
or row.get("complete_clock") is not True
|
||||
or type(row.get("rootxy_breached")) is not bool or row.get("safety_ok") is not True):
|
||||
raise ValueError("Missing/partial physics-tick evidence or safety violation")
|
||||
if row["rootxy_rms_m"] > row["rootxy_max_m"] + 1e-12:
|
||||
raise ValueError("Inconsistent RMS/max")
|
||||
if any(r["rootxy_breached"] or r["rootxy_max_m"] > .03 for r in rows):
|
||||
return None
|
||||
return sum(r["rootxy_rms_m"] for r in rows) / 128, tracking_cost(rows), update
|
||||
@@ -0,0 +1,346 @@
|
||||
"""Additive RootXY-v2 protocol; no simulator imports and no launch authorization.
|
||||
|
||||
The additive supervised adapter owns launch admission; CPU identity is not a grant.
|
||||
V1 source/checkpoint identities and restore behavior remain untouched.
|
||||
"""
|
||||
import copy
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from . import replay, training as v1
|
||||
from .config import FEATURE_VERSION, load_config
|
||||
from .model import SimResidualActorCritic, features
|
||||
from .ppo import _finite_tree, _model_state
|
||||
from .rootxy_selection_v2 import candidate_key
|
||||
from ..contact_cycle.training import BudgetExceeded, atomic_json, digest
|
||||
from .evaluation_budget import artifact_size as artifact_bytes
|
||||
|
||||
TASK_ID = "SkillFactory-Go2FL-ContactCycleSimRootXY-v2"
|
||||
CONTRACT = "go2-fl-contact-cycle-sim-rootxy-v2"
|
||||
CONFIG_PATH = "configs/contact_cycle/sim_training_rootxy_v2.json"
|
||||
TASK_PATH = "configs/contact_cycle/simulation_residual_rootxy_v2.json"
|
||||
PROPOSAL_PATH = "configs/contact_cycle/sim_training_rootxy_proposal_v2.json"
|
||||
PLAN_PATH = "docs/contact_cycle_rootxy_v2_plan.md"
|
||||
BASE_PATH = "configs/contact_cycle/simulation_residual_v1.json"
|
||||
BASE_SHA256 = "a2352c197bd6e13a2a729792657b26da120fd2d295d00f205eca8154aed82628"
|
||||
MODEL_CONFIG = dict(v1.MODEL_CONFIG)
|
||||
CHECKPOINT_FORMAT = "skillfactory.contact-cycle-sim-rootxy-checkpoint.v2"
|
||||
TASK = {
|
||||
"format": "skillfactory.contact-cycle-sim-rootxy.v2", "task_id": TASK_ID,
|
||||
"features": FEATURE_VERSION, "base_config": BASE_PATH, "base_sha256": BASE_SHA256,
|
||||
"overrides": {"reward.position_scale_m": [.03, .03, .04]},
|
||||
}
|
||||
PILOT = {
|
||||
**copy.deepcopy(v1.PILOT), "format": "skillfactory.contact-cycle-sim-rootxy-training.v2",
|
||||
"contract": CONTRACT, "task_id": TASK_ID, "proposal": PROPOSAL_PATH, "task_config": TASK_PATH,
|
||||
"seeds": [92511], "validation_seed": 93511, "holdout_seed": 95511,
|
||||
"validation_updates": [64, 128, 192, 256], "max_total_wall_s": 7200,
|
||||
"cleanup_reserve_s": 120, "max_validation_transitions": 806400,
|
||||
"source_checkpoint": replay.CANDIDATE, "source_sha256": replay.CANDIDATE_SHA256,
|
||||
"source_manifest_sha256": replay.MANIFEST_SHA256,
|
||||
}
|
||||
PROPOSAL = {
|
||||
"format": "skillfactory.contact-cycle-sim-rootxy-proposal.v2", "contract": CONTRACT,
|
||||
"actual_training_launches": 1, "resume": False, "accepted_skill": False,
|
||||
"initialization": "actor_log_std_exact_normalization_only_fresh_critic_Adam_RNG",
|
||||
"baselines": ["analytic_zero", "frozen_u256"],
|
||||
"warmstart_u0": "CPU_exact_actor_equivalence_not_physical_repeat_or_full_state_equivalence",
|
||||
"validation_reservation": "128*900*7_no_refund_actual_two_baselines_plus_four_development",
|
||||
"selection": "all128_original_functional_and_full4500ticks_XY_le_0.03_then_mean_full_RMS_tracking_earliest",
|
||||
"termination": "original_safety_only_no_early_30mm_termination",
|
||||
"scope": "independent_nominal_9s_single_cycle_not_continuous_learning",
|
||||
"launch_barrier": "P2_review_then_supervised_adapter_review_then_fresh_parent_manifest_hash_grant",
|
||||
"native_storage": "aggregate_new_owned_1GiB_MONITOR_and_stop_not_hard_quota",
|
||||
"downstream": "holdout_P1_P2_require_separate_grants_not_remaining_pilot_budget",
|
||||
}
|
||||
|
||||
|
||||
def exact(actual, expected):
|
||||
return json.dumps(actual, sort_keys=True, allow_nan=False) == json.dumps(expected, sort_keys=True, allow_nan=False)
|
||||
|
||||
|
||||
def load_task_config(path, root):
|
||||
if not exact(json.loads(Path(path).read_text()), TASK):
|
||||
raise ValueError("RootXY-v2 identity/override whitelist mismatch")
|
||||
base = Path(root) / BASE_PATH
|
||||
if hashlib.sha256(base.read_bytes()).hexdigest() != BASE_SHA256:
|
||||
raise ValueError("Frozen base config changed")
|
||||
resolved = load_config(base)
|
||||
resolved.update(format=TASK["format"], task_id=TASK_ID,
|
||||
scope=PROPOSAL["scope"])
|
||||
resolved["reward"]["position_scale_m"] = [.03, .03, .04]
|
||||
return resolved
|
||||
|
||||
|
||||
def load_training_config(path, root):
|
||||
cfg = json.loads(Path(path).read_text())
|
||||
if not exact(cfg, PILOT):
|
||||
raise ValueError("RootXY-v2 fixed pilot config mismatch")
|
||||
if not exact(json.loads((Path(root) / PROPOSAL_PATH).read_text()), PROPOSAL):
|
||||
raise ValueError("RootXY-v2 fixed proposal mismatch")
|
||||
load_task_config(Path(root) / TASK_PATH, root)
|
||||
return cfg
|
||||
|
||||
|
||||
def source_identity(root, config_path):
|
||||
# Reuse the frozen dependency inventory, then explicitly bind every additive seam.
|
||||
root = Path(root).resolve()
|
||||
sources = v1.source_identity(root, v1.PILOT, root / v1.CONFIG_PATH)
|
||||
paths = [Path(config_path).resolve(), root / TASK_PATH, root / PROPOSAL_PATH, root / PLAN_PATH,
|
||||
root / "scripts/train_cycle_sim_rootxy_v2.py", root / "scripts/rootxy_launch_v2.py",
|
||||
root / "scripts/evaluate_cycle_sim_residual.py",
|
||||
root / "docs/contact_cycle_rootxy_v2_launch.md",
|
||||
root / "tests/test_contact_cycle_sim_rootxy_launch_v2.py",
|
||||
root / "tests/test_contact_cycle_sim_rootxy_v2.py"]
|
||||
for path in paths:
|
||||
if not path.is_relative_to(root) or path.is_symlink():
|
||||
raise ValueError("Unsafe RootXY-v2 identity input")
|
||||
sources[str(path.relative_to(root))] = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
return dict(sorted(sources.items()))
|
||||
|
||||
|
||||
def make_manifest(root, config_path):
|
||||
cfg = load_training_config(config_path, root)
|
||||
_, source = replay.verify_bundle(root)
|
||||
parity_path = Path(root) / Path(replay.CANDIDATE).parent / 'validation_u0256_trace.pt'
|
||||
return {"format": "skillfactory.contact-cycle-sim-rootxy-preregistration.v2",
|
||||
"contract": CONTRACT, "task_id": TASK_ID, "features": FEATURE_VERSION,
|
||||
"training": cfg, "proposal": PROPOSAL, "model_config": MODEL_CONFIG,
|
||||
"resolved_task": load_task_config(Path(root) / TASK_PATH, root),
|
||||
"sources": source_identity(root, config_path), "warmstart_source": source,
|
||||
"parity_trace": {"path": str(parity_path.resolve()),
|
||||
"sha256": hashlib.sha256(parity_path.read_bytes()).hexdigest()},
|
||||
"launch_integration_complete": True, "runtime_qualified": False, "accepted_skill": False, "resume": False}
|
||||
|
||||
|
||||
def writable_output(root, output):
|
||||
output = Path(output).resolve()
|
||||
protected = [Path(root).resolve() / "releases", (Path(root) / replay.CANDIDATE).resolve().parent.parent]
|
||||
if (any(output.is_relative_to(path) for path in protected)
|
||||
or output.is_relative_to(Path(root).resolve())
|
||||
and not output.is_relative_to(Path(root).resolve() / "logs/contact_cycle/rootxy_v2")):
|
||||
raise ValueError("Use new rootxy_v2 outputs or external directory; frozen/historical/source paths are immutable")
|
||||
return output
|
||||
|
||||
|
||||
def prepare(root, config_path, output):
|
||||
"""Legacy CPU snapshot helper only; NOT actual Kit config preparation/admission.
|
||||
|
||||
The dedicated CLI uses rootxy_launch_v2 and its distinct preparation schema.
|
||||
This snapshot alone is never accepted by the supervisor.
|
||||
"""
|
||||
output = writable_output(root, output)
|
||||
manifest = make_manifest(root, config_path)
|
||||
size = sum((Path(root) / p).stat().st_size for p in manifest["sources"])
|
||||
if size + len(json.dumps(manifest).encode()) + 1048576 > PILOT["max_artifact_bytes"]:
|
||||
raise BudgetExceeded("Preparation exceeds aggregate output cap")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
atomic_json(output / "manifest.json", manifest)
|
||||
for relative in manifest["sources"]:
|
||||
target = output / "source_snapshot" / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(Path(root) / relative, target)
|
||||
atomic_json(output / "preparation.json", {"prepared": True, "authorized": False, "trained": False,
|
||||
"manifest_sha256": digest(manifest)})
|
||||
return manifest
|
||||
|
||||
|
||||
def require_launch_admission(*_):
|
||||
raise PermissionError("RootXY-v2 supervised launch integration INCOMPLETE: P2 review, reviewed admission/native "
|
||||
"monitor/sole-owner cleanup adapter and fresh parent manifest-hash grant required")
|
||||
|
||||
|
||||
def import_actor_weights_only(root, observations):
|
||||
"""CPU-only exact saved-observation parity; never restore optimizer, critic or RNG.
|
||||
|
||||
This intentionally initializes NEW Python/NumPy/Torch streams with seed92511.
|
||||
Model construction consumes only that new stream. Frozen loading preserves it.
|
||||
"""
|
||||
import numpy as np
|
||||
|
||||
x = features(observations)
|
||||
if x.device.type != "cpu":
|
||||
raise ValueError("Warm-start parity is CPU-only")
|
||||
manifest, source = replay.verify_bundle(root)
|
||||
frozen = replay.load_frozen_policy(Path(root) / replay.CANDIDATE, manifest)
|
||||
seed = PILOT["seeds"][0]
|
||||
random.seed(seed)
|
||||
np.random.seed(seed)
|
||||
torch.manual_seed(seed)
|
||||
model = SimResidualActorCritic(**MODEL_CONFIG)
|
||||
initial_critic = {k: v.clone() for k, v in model.critic.state_dict().items()}
|
||||
saved, target = frozen.state_dict(), model.state_dict()
|
||||
_model_state(saved, target)
|
||||
imported = sorted(k for k in saved if k.startswith("actor.") or k in ("log_std", "offset", "scale"))
|
||||
target.update({k: saved[k].clone() for k in imported})
|
||||
model.load_state_dict(target)
|
||||
with torch.no_grad():
|
||||
old, new = replay.inference_action(x, "learned", frozen), replay.inference_action(x, "learned", model)
|
||||
if not all(torch.equal(a, b) for a, b in zip(old, new)):
|
||||
raise ValueError("Exact CPU warm-start actor/action/std parity failed")
|
||||
if not all(torch.equal(v, initial_critic[k]) for k, v in model.critic.state_dict().items()):
|
||||
raise ValueError("Warm-start changed fresh critic")
|
||||
optimizer = torch.optim.Adam(model.parameters(), lr=PILOT["algorithm"]["learning_rate"],
|
||||
eps=PILOT["algorithm"]["adam_eps"])
|
||||
evidence = {"source": source, "imported_keys": imported,
|
||||
"excluded_model_keys": sorted(set(saved) - set(imported)),
|
||||
"excluded_state": ["optimizer", "rng", "critic", "best", "budget_snapshot", "update"],
|
||||
"parity": "exact_CPU_action_mean_std", "observations": len(x),
|
||||
"observations_sha256": hashlib.sha256(x.contiguous().numpy().tobytes()).hexdigest(),
|
||||
"fresh_seed": seed, "physical_repeat": False, "full_state_equivalence": False}
|
||||
return model, optimizer, frozen, evidence
|
||||
|
||||
|
||||
|
||||
|
||||
class RootXYBudgetLedger(v1.FreshBudgetLedger):
|
||||
"""Fresh debit plus separately reserved validation. Adapter supplies BOOTTIME start.
|
||||
|
||||
Instantiate BEFORE Kit startup. Native monitoring and physical-call accounting
|
||||
remain the supervisor adapter's responsibility; this is not a hard disk quota.
|
||||
"""
|
||||
FORMAT = "skillfactory.contact-cycle-rootxy-budget.v2"
|
||||
|
||||
def __init__(self, *args, launch_start_s, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
if type(launch_start_s) not in (float, int) or not math.isfinite(launch_start_s) or launch_start_s < 0:
|
||||
raise ValueError("Require supervisor BOOTTIME start")
|
||||
self.launch_start_s = launch_start_s
|
||||
|
||||
def __enter__(self):
|
||||
super().__enter__()
|
||||
try:
|
||||
clock = self.data["clock"]
|
||||
if self.launch_start_s > clock["start_s"]:
|
||||
raise ValueError("Supervisor start is in the future")
|
||||
clock.update(start_s=self.launch_start_s, deadline_s=self.launch_start_s + 7200)
|
||||
self.data.update(validation_reserved_transitions=806400, validation_evaluations_started=[],
|
||||
validation_completed_control_calls=0, validation_attempted_control_calls=0)
|
||||
self.guard()
|
||||
atomic_json(self.path, self.data)
|
||||
return self
|
||||
except BaseException:
|
||||
super().__exit__()
|
||||
raise
|
||||
|
||||
def guard(self, reserve_bytes=0):
|
||||
# Preserve every inherited clock/debit/cap check. Its legacy size scan can
|
||||
# race the supervisor's atomic heartbeat rename. Retry the entire guard,
|
||||
# boundedly; never accept a partial scan or modify the frozen v1 helper.
|
||||
for attempt in range(4):
|
||||
try:
|
||||
return super().guard(reserve_bytes=reserve_bytes)
|
||||
except FileNotFoundError:
|
||||
if attempt == 3:
|
||||
raise BudgetExceeded('RootXY legacy artifact scan unstable after4attempts')
|
||||
|
||||
def work_guard(self):
|
||||
self.guard()
|
||||
if self.boot_now() >= self.data["clock"]["deadline_s"] - 120:
|
||||
raise BudgetExceeded("Cleanup reserve reached; no new work")
|
||||
|
||||
def begin_validation(self, label):
|
||||
self.work_guard()
|
||||
labels = ["analytic_zero", "frozen_u256", "u0064", "u0128", "u0192", "u0256"]
|
||||
used = self.data["validation_evaluations_started"]
|
||||
if len(used) >= len(labels) or label != labels[len(used)]:
|
||||
raise ValueError("No duplicate/reordered/retry validation")
|
||||
used.append(label)
|
||||
self._evaluation_calls = 0
|
||||
self.write_json(self.path, self.data)
|
||||
|
||||
def before_validation_control(self):
|
||||
self.work_guard()
|
||||
if not hasattr(self, "_evaluation_calls") or self._evaluation_calls >= 900:
|
||||
raise BudgetExceeded("Validation control-call cap")
|
||||
self._evaluation_calls += 1
|
||||
self.data["validation_attempted_control_calls"] += 1
|
||||
|
||||
def after_validation_control(self):
|
||||
self.data["validation_completed_control_calls"] += 1
|
||||
|
||||
|
||||
def _checkpoint_identity(identity, imported):
|
||||
keys = {"task_id", "contract", "manifest_sha256", "resolved_task", "source_sha256", "seed"}
|
||||
if (not isinstance(identity, dict) or set(identity) != keys or identity["task_id"] != TASK_ID
|
||||
or identity["contract"] != CONTRACT or identity["source_sha256"] != replay.CANDIDATE_SHA256
|
||||
or type(identity["seed"]) is not int or identity["seed"] != 92511
|
||||
or not isinstance(identity["manifest_sha256"], str) or len(identity["manifest_sha256"]) != 64
|
||||
or any(c not in "0123456789abcdef" for c in identity["manifest_sha256"])
|
||||
or identity["resolved_task"].get("task_id") != TASK_ID
|
||||
or identity["resolved_task"].get("reward", {}).get("position_scale_m") != [.03, .03, .04]
|
||||
or imported.get("source", {}).get("candidate_sha256") != replay.CANDIDATE_SHA256
|
||||
or imported.get("source", {}).get("manifest_sha256") != replay.MANIFEST_SHA256
|
||||
or imported.get("parity") != "exact_CPU_action_mean_std" or imported.get("fresh_seed") != 92511):
|
||||
raise ValueError("RootXY-v2 checkpoint provenance mismatch")
|
||||
|
||||
|
||||
def save_checkpoint(path, model, identity, update, import_evidence, budget, max_bytes):
|
||||
"""New eval-only artifact; no resume payload. Exact temporary capacity reserved."""
|
||||
if (identity.get("task_id") != TASK_ID or identity.get("contract") != CONTRACT
|
||||
or type(update) is not int or update not in [0, *PILOT["validation_updates"]]):
|
||||
raise ValueError("RootXY-v2 checkpoint identity/update mismatch")
|
||||
_checkpoint_identity(identity, import_evidence)
|
||||
with torch.random.fork_rng(devices=[]):
|
||||
expected = SimResidualActorCritic(**MODEL_CONFIG)
|
||||
_model_state(model.state_dict(), expected.state_dict())
|
||||
data = {"format": CHECKPOINT_FORMAT, "task_id": TASK_ID, "contract": CONTRACT,
|
||||
"features": FEATURE_VERSION, "model_config": MODEL_CONFIG,
|
||||
"model": {k: v.detach().cpu() for k, v in model.state_dict().items()},
|
||||
"identity": identity, "update": update, "import_evidence": import_evidence,
|
||||
"budget_snapshot": copy.deepcopy(budget), "accepted_skill": False, "resume": False}
|
||||
_finite_tree(data)
|
||||
stream = io.BytesIO()
|
||||
torch.save(data, stream)
|
||||
payload = stream.getvalue()
|
||||
if type(max_bytes) is not int or max_bytes < len(payload):
|
||||
raise BudgetExceeded("Atomic checkpoint temporary capacity exceeded")
|
||||
path = Path(path)
|
||||
if path.exists():
|
||||
raise FileExistsError("Never overwrite checkpoint evidence")
|
||||
temporary = None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as out:
|
||||
temporary = Path(out.name)
|
||||
out.write(payload)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
os.replace(temporary, path)
|
||||
finally:
|
||||
if temporary is not None:
|
||||
temporary.unlink(missing_ok=True)
|
||||
return hashlib.sha256(payload).hexdigest()
|
||||
|
||||
|
||||
def load_evaluation_policy(path, expected_sha256, identity):
|
||||
"""New v2-only loader: does not masquerade as frozen v1 or restore learner state."""
|
||||
payload = Path(path).read_bytes()
|
||||
if hashlib.sha256(payload).hexdigest() != expected_sha256:
|
||||
raise ValueError("RootXY-v2 checkpoint digest mismatch")
|
||||
data = torch.load(io.BytesIO(payload), map_location="cpu", weights_only=True)
|
||||
required = {"format", "task_id", "contract", "features", "model_config", "model", "identity",
|
||||
"update", "import_evidence", "budget_snapshot", "accepted_skill", "resume"}
|
||||
if (not isinstance(data, dict) or set(data) != required
|
||||
or data.get("format") != CHECKPOINT_FORMAT or data.get("task_id") != TASK_ID
|
||||
or data.get("contract") != CONTRACT or data.get("features") != FEATURE_VERSION
|
||||
or not exact(data.get("identity"), identity) or identity.get("task_id") != TASK_ID
|
||||
or not exact(data.get("model_config"), MODEL_CONFIG)
|
||||
or data.get("accepted_skill") is not False or data.get("resume") is not False
|
||||
or type(data.get("update")) is not int or data["update"] not in [0, *PILOT["validation_updates"]]):
|
||||
raise ValueError("RootXY-v2 eval identity mismatch")
|
||||
_finite_tree(data)
|
||||
_checkpoint_identity(identity, data["import_evidence"])
|
||||
with torch.random.fork_rng(devices=[]):
|
||||
model = SimResidualActorCritic(**MODEL_CONFIG)
|
||||
_model_state(data["model"], model.state_dict())
|
||||
model.load_state_dict(data["model"])
|
||||
return model.eval().requires_grad_(False), data
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Deterministic scripted requests, not a policy or a controller modification."""
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
|
||||
def residual_signals(plan, case):
|
||||
"""Return CPU float32 normalized requests [control, environment, joint]."""
|
||||
shape = (plan['controls_per_case'], plan['num_envs'], 3)
|
||||
kind = case['kind']
|
||||
if kind == 'gaussian':
|
||||
generator = torch.Generator(device='cpu').manual_seed(case['seed'])
|
||||
return (torch.randn(shape, generator=generator) * plan['gaussian_normalized_std']).tanh()
|
||||
amplitude = case['amplitude_rad']
|
||||
if not math.isfinite(amplitude) or not 0 <= amplitude <= plan['residual_limit_rad']:
|
||||
raise ValueError('Amplitude exceeds the original residual contract')
|
||||
scale = amplitude / plan['residual_limit_rad']
|
||||
if kind == 'zero':
|
||||
return torch.zeros(shape)
|
||||
if kind == 'constant':
|
||||
signs = [[1 if e & (1 << j) else -1 for j in range(3)] for e in range(shape[1])]
|
||||
return (torch.tensor(signs, dtype=torch.float32) * scale).expand(shape).clone()
|
||||
if kind in ('sine', 'gated_sine'):
|
||||
t = torch.arange(shape[0], dtype=torch.float64) * plan['control_dt_s']
|
||||
phase = (torch.tensor(plan['joint_phase_rad'], dtype=torch.float64)[None, :]
|
||||
+ torch.arange(shape[1], dtype=torch.float64)[:, None]
|
||||
* plan['environment_phase_increment_rad'])
|
||||
return (scale * torch.sin(2 * math.pi * plan['frequency_Hz'] * t[:, None, None] + phase)).float()
|
||||
raise ValueError(f'Unknown scripted signal: {kind}')
|
||||
|
||||
|
||||
def gate_residual(request, phase, enabled_phases):
|
||||
"""Gate at the control-start command phase; never infer phase from observed contact."""
|
||||
enabled = torch.zeros_like(phase, dtype=torch.bool)
|
||||
for value in enabled_phases:
|
||||
enabled |= phase == value
|
||||
return torch.where(enabled[:, None], request, torch.zeros_like(request))
|
||||
|
||||
|
||||
def first_failure(trace, failure_names):
|
||||
"""Find physics-rate onset separately from the later control-boundary reset."""
|
||||
flags = trace['failure_flags'][:, 0]
|
||||
hits = flags.any(-1).nonzero().flatten()
|
||||
if not len(hits):
|
||||
return None
|
||||
tick = int(hits[0])
|
||||
return {'physics_tick': tick + 1, 'time_s': float(trace['time'][tick, 0]),
|
||||
'phase': int(trace['phase'][tick, 0]),
|
||||
'causes': [name for j, name in enumerate(failure_names) if flags[tick, j]],
|
||||
'gap_m': float(trace['gap'][tick, 0]),
|
||||
'normal_N': float(trace['normal'][tick, 0, 2]),
|
||||
'signed_height_error_m': float(trace['signed_height_error'][tick, 0]),
|
||||
'tilt_rad': float(trace['tilt'][tick, 0])}
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Fresh-only 46D pilot protocol. Preparation is never authorization.
|
||||
|
||||
Generic BOOTTIME accounting is reused, not the old task manifest or sampler.
|
||||
This module and the CLI reject resume, legacy grants and mutable preparation.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
from contextlib import contextmanager, suppress
|
||||
from pathlib import Path
|
||||
|
||||
from ..contact_cycle.training import (
|
||||
BudgetExceeded,
|
||||
BudgetLedger,
|
||||
artifact_bytes,
|
||||
atomic_json,
|
||||
digest,
|
||||
)
|
||||
from ..contact_cycle.training import (
|
||||
save_trace_subset as save_trace_subset,
|
||||
)
|
||||
from .config import FEATURE_VERSION, TASK_ID, load_config
|
||||
from .ppo import CONTRACT, collect_rollout, ppo_step, rollout_diagnostics, selection_key
|
||||
|
||||
CONFIG_PATH = "configs/contact_cycle/sim_training_v1.json"
|
||||
PROPOSAL_PATH = "configs/contact_cycle/sim_training_proposal_v1.json"
|
||||
PLAN_PATH = "docs/contact_cycle_sim_training_plan.md"
|
||||
AUTHORIZATION_FORMAT = "skillfactory.contact-cycle-sim-residual-authorization.v1"
|
||||
VALIDATION_UPDATES = (0, 64, 128, 192, 256)
|
||||
MODEL_CONFIG = {"hidden": 128, "initial_std": 0.1}
|
||||
PILOT = {
|
||||
"format": "skillfactory.contact-cycle-sim-residual-training.v1",
|
||||
"contract": CONTRACT,
|
||||
"task_id": TASK_ID,
|
||||
"features": FEATURE_VERSION,
|
||||
"proposal": PROPOSAL_PATH,
|
||||
"task_config": "configs/contact_cycle/simulation_residual_v1.json",
|
||||
"functional_config": "configs/contact_cycle/simulation_functional_v1.json",
|
||||
"safety_config": "configs/contact_cycle/acceptance_v1.json",
|
||||
"seeds": [91501],
|
||||
"validation_seed": 93501,
|
||||
"num_envs": 128,
|
||||
"horizon": 32,
|
||||
"updates_per_seed": 256,
|
||||
"validation_updates": list(VALIDATION_UPDATES),
|
||||
"max_total_transitions": 1048576,
|
||||
"max_total_wall_s": 3600,
|
||||
"max_artifact_bytes": 1073741824,
|
||||
"algorithm": {
|
||||
**MODEL_CONFIG, "learning_rate": 0.0003, "adam_eps": 0.00001,
|
||||
"gamma": 0.99, "gae_lambda": 0.95, "clip_ratio": 0.2, "epochs": 4,
|
||||
"minibatch_size": 1024, "value_coefficient": 0.5,
|
||||
"max_gradient_norm": 1.0, "target_kl": 0.02, "failure_penalty": 10.0,
|
||||
},
|
||||
}
|
||||
PROPOSAL = {
|
||||
"format": "skillfactory.contact-cycle-sim-residual-proposal.v1",
|
||||
"contract": CONTRACT,
|
||||
"parent_plan": PLAN_PATH,
|
||||
"scope": "fresh_nominal_only_pilot_no_external_DR_holdout",
|
||||
"actual_training_launches": 1,
|
||||
"resume": False,
|
||||
"warm_start": False,
|
||||
"accepted_skill": False,
|
||||
"baseline": "u0_untrained_zero_residual_network_requires_128_of_128_functional_passes",
|
||||
"selection": "u64_u128_u192_u256_lexicographic_failure_fraction_then_all_row_mean_cost_earliest_tie",
|
||||
"row_cost": "failed=16; success=min(height_rms/.06,2)+min(swing_rms/.025,2)+min(landing_error/.05,2)",
|
||||
"physics": "unchanged_reference_full_phase_residual_limit_0.05rad_500Hz_safety",
|
||||
"validation": "same128_nominal_envs_seed93501_first_episode_only_full9s",
|
||||
"post_result_changes": "separate_version_no_second_optimization_authorized",
|
||||
"supervisor_timeout_s": 3480,
|
||||
}
|
||||
|
||||
|
||||
def _exact(value, expected):
|
||||
# Python's True == 1 and NaN handling must not weaken the fixed protocol.
|
||||
return json.dumps(value, sort_keys=True, allow_nan=False) == json.dumps(expected, sort_keys=True, allow_nan=False)
|
||||
|
||||
|
||||
def load_training_config(path, root):
|
||||
cfg = json.loads(Path(path).read_text())
|
||||
if not _exact(cfg, PILOT):
|
||||
raise ValueError("Unsupported residual pilot config: seed/budget/schema/algorithm are fixed")
|
||||
proposal = json.loads((Path(root) / cfg["proposal"]).read_text())
|
||||
if not _exact(proposal, PROPOSAL):
|
||||
raise ValueError("Unsupported residual pilot proposal")
|
||||
task = load_config(Path(root) / cfg["task_config"])
|
||||
if task["residual_limit_rad"] != .05:
|
||||
raise ValueError("Full-phase residual contract must remain +/-0.05rad")
|
||||
return cfg
|
||||
|
||||
|
||||
def source_identity(root, cfg, config_path):
|
||||
root = Path(root).resolve()
|
||||
task = load_config(root / cfg["task_config"])
|
||||
cycle = json.loads((root / task["cycle_config"]).read_text())
|
||||
support = json.loads((root / cycle["support_config"]).read_text())
|
||||
files = {Path(config_path).resolve(), root / cfg["proposal"], root / cfg["task_config"],
|
||||
root / cfg["functional_config"], root / cfg["safety_config"], root / PLAN_PATH,
|
||||
root / task["cycle_config"], root / cycle["support_config"], root / "AGENT.md",
|
||||
root / "source/SkillFactory/SkillFactory/legs/resources/ground.usda"}
|
||||
files.update((root / "source/SkillFactory").rglob("*.py"))
|
||||
for name in ("train_cycle_sim_residual.py", "verify_cycle_sim_learning_runtime.py",
|
||||
"audit_contact_cycle_functional.py", "runtime_common.py", "supervise_sim.py"):
|
||||
files.add(root / "scripts" / name)
|
||||
for name in ("test_contact_cycle_sim_training.py", "test_contact_cycle_sim_learning_physics.py",
|
||||
"test_contact_cycle_sim_learning.py"):
|
||||
files.add(root / "tests" / name)
|
||||
for folder in (support["support_asset"], support["source_bundle"]):
|
||||
files.update(p for p in (root / folder).rglob("*") if p.is_file())
|
||||
if any(not p.resolve().is_relative_to(root) for p in files):
|
||||
raise ValueError("Identity input escaped repository")
|
||||
return {str(p.relative_to(root)): hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(files)}
|
||||
|
||||
|
||||
def make_manifest(root, config_path):
|
||||
cfg = load_training_config(config_path, root)
|
||||
return {"format": "skillfactory.contact-cycle-sim-residual-preregistration.v1",
|
||||
"contract": CONTRACT, "task_id": TASK_ID, "features": FEATURE_VERSION,
|
||||
"training": cfg, "proposal": PROPOSAL, "model_config": MODEL_CONFIG,
|
||||
"sources": source_identity(root, cfg, config_path),
|
||||
"critic": "symmetric_sim_truth_policy46", "sampler": None,
|
||||
"resume": False, "accepted_skill": False,
|
||||
"wall_budget": "same_boot_CLOCK_BOOTTIME_includes_startup_validation_suspend_shutdown"}
|
||||
|
||||
|
||||
def require_authorization(path, manifest):
|
||||
if path is None:
|
||||
raise PermissionError("Explicit parent-bound final manifest grant required before Kit or budget")
|
||||
grant = json.loads(Path(path).read_text())
|
||||
keys = {"format", "approved", "manifest_sha256", "operator", "authorization_reference"}
|
||||
if (set(grant) != keys or grant["format"] != AUTHORIZATION_FORMAT or grant["approved"] is not True
|
||||
or grant["manifest_sha256"] != digest(manifest)
|
||||
or any(not isinstance(grant[k], str) or not grant[k].strip()
|
||||
for k in ("operator", "authorization_reference"))):
|
||||
raise PermissionError("Invalid/stale/legacy training grant")
|
||||
return grant
|
||||
|
||||
|
||||
def writable_output(root, output):
|
||||
output = Path(output).resolve()
|
||||
if output.is_relative_to((Path(root) / "releases").resolve()):
|
||||
raise ValueError("Frozen releases are not writable pilot outputs")
|
||||
return output
|
||||
|
||||
|
||||
def prepare(root, config_path, output):
|
||||
output = writable_output(root, output)
|
||||
manifest = make_manifest(root, config_path)
|
||||
size = sum((Path(root) / p).stat().st_size for p in manifest["sources"])
|
||||
if size + len(json.dumps(manifest).encode()) + 1048576 > manifest["training"]["max_artifact_bytes"]:
|
||||
raise BudgetExceeded("Preparation snapshot exceeds total artifact cap")
|
||||
output.mkdir(parents=True, exist_ok=False)
|
||||
atomic_json(output / "manifest.json", manifest)
|
||||
for relative in manifest["sources"]:
|
||||
target = output / "source_snapshot" / relative
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copyfile(Path(root) / relative, target)
|
||||
atomic_json(output / "preparation.json", {"prepared": True, "authorized": False, "trained": False,
|
||||
"manifest_sha256": digest(manifest)})
|
||||
return manifest
|
||||
|
||||
|
||||
def validate_prepared(root, output, manifest):
|
||||
output = writable_output(root, output)
|
||||
if json.loads((output / "manifest.json").read_text()) != manifest:
|
||||
raise ValueError("Prepared manifest is stale or mismatched")
|
||||
expected = {"prepared": True, "authorized": False, "trained": False, "manifest_sha256": digest(manifest)}
|
||||
if json.loads((output / "preparation.json").read_text()) != expected:
|
||||
raise ValueError("Invalid preparation metadata")
|
||||
if any((output / name).exists() for name in ("budget.json", "budget.lock", "launch_claim.json")):
|
||||
raise FileExistsError("Fresh-only pilot refuses existing budget/launch: no retry or resume")
|
||||
verify_snapshot(output, manifest)
|
||||
allowed = {"manifest.json", "preparation.json", "source_snapshot", "console.log", "supervisor.json"}
|
||||
if any(p.name not in allowed for p in output.iterdir()):
|
||||
raise ValueError("Prepared output contains undeclared prior artifacts")
|
||||
if artifact_bytes(output) + 1048576 > manifest["training"]["max_artifact_bytes"]:
|
||||
raise BudgetExceeded("Prepared artifacts exceed cap")
|
||||
|
||||
|
||||
def verify_snapshot(output, manifest):
|
||||
for relative, sha in manifest["sources"].items():
|
||||
path = Path(output) / "source_snapshot" / relative
|
||||
if path.is_symlink() or hashlib.sha256(path.read_bytes()).hexdigest() != sha:
|
||||
raise ValueError("Prepared source snapshot changed")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def isolated_validation_rng(env, validation_seed, training_seed):
|
||||
"""Environment seeding changes Python/NumPy too; restore all learner-side streams."""
|
||||
import numpy as np
|
||||
|
||||
from .ppo import restore_rng, rng_state
|
||||
|
||||
saved = rng_state(), random.getstate(), np.random.get_state()
|
||||
try:
|
||||
env.seed(validation_seed)
|
||||
yield
|
||||
finally:
|
||||
try:
|
||||
env.seed(training_seed)
|
||||
env.reset() # physics is intentionally reset, never spliced into a training rollout
|
||||
finally:
|
||||
restore_rng(saved[0])
|
||||
random.setstate(saved[1])
|
||||
np.random.set_state(saved[2])
|
||||
|
||||
|
||||
def assert_no_conflicting_processes(proc=Path("/proc")):
|
||||
conflicts = []
|
||||
for entry in proc.glob("[0-9]*"):
|
||||
if int(entry.name) == os.getpid():
|
||||
continue
|
||||
try:
|
||||
argv = entry.joinpath("cmdline").read_bytes().split(b"\0")
|
||||
executable = Path(argv[0].decode(errors="replace")).name.lower()
|
||||
# Match executables and script argv, not shell/supervisor quoted command text.
|
||||
is_kit = executable in ("kit", "isaac-sim", "isaac-sim.sh")
|
||||
suffix = executable.removeprefix("python")
|
||||
is_python = executable == "python" or (executable.startswith("python")
|
||||
and suffix.replace(".", "").isdigit())
|
||||
# Only the Python entry script counts; supervisor command arguments are not workers.
|
||||
entry_args = [a for a in argv[1:] if a not in (b"-u", b"-B", b"-s", b"-E", b"-I")]
|
||||
first_arg = entry_args[0] if entry_args else b""
|
||||
script = Path(first_arg.decode(errors="replace")).name if first_arg.endswith(b".py") else None
|
||||
is_worker = is_python and script in {
|
||||
"train_cycle_sim_residual.py", "train_contact_cycle.py", "train_standing.py",
|
||||
"verify_cycle_sim_learning_runtime.py", "verify_cycle_sim_residual.py",
|
||||
"verify_cycle_sim_stress.py", "verify_cycle_learning_runtime.py", "verify_contact_cycle.py"}
|
||||
loaded_kit = False
|
||||
if is_python:
|
||||
with suppress(OSError):
|
||||
loaded_kit = "libomni.kit.app" in entry.joinpath("maps").read_text()
|
||||
if is_kit or is_worker or loaded_kit:
|
||||
conflicts.append(int(entry.name))
|
||||
except (OSError, IndexError):
|
||||
continue
|
||||
if conflicts:
|
||||
raise RuntimeError(f"Conflicting simulator/training processes: {conflicts}")
|
||||
|
||||
|
||||
class FreshBudgetLedger(BudgetLedger):
|
||||
"""No reconciliation/retry path; an exclusive claim also closes concurrent invocation races."""
|
||||
|
||||
def __enter__(self):
|
||||
if self.path.exists() or (self.root / "budget.lock").exists():
|
||||
raise FileExistsError("Existing ledger is forbidden for this fresh-only pilot")
|
||||
with (self.root / "launch_claim.json").open("x") as stream:
|
||||
json.dump({"manifest_sha256": digest(self.manifest), "pid": os.getpid()}, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
return super().__enter__()
|
||||
|
||||
def reconcile_checkpoint(self, *_):
|
||||
raise PermissionError("No resume or interrupted reservation refund in this pilot")
|
||||
|
||||
|
||||
def optimize_reserved_rollout(env, model, optimizer, x, algo, seed, update, ledger, guard, check_source):
|
||||
"""The sole optimizer entry: reserve, collect, verify AND persist diagnostics first."""
|
||||
check_source()
|
||||
ledger.reserve_rollout(seed, update)
|
||||
data, next_x, failures, timeouts = collect_rollout(env, model, x, algo, guard)
|
||||
diagnostic = rollout_diagnostics(data, algo)
|
||||
if diagnostic["missing_diagnostic_samples"]:
|
||||
raise RuntimeError("Missing phase/cause diagnostics; no optimization")
|
||||
ledger.append_json(ledger.root / "rollout_diagnostics.jsonl", {"update": update, **diagnostic})
|
||||
check_source()
|
||||
learning = ppo_step(model, optimizer, data, algo)
|
||||
guard()
|
||||
return next_x, failures, timeouts, learning
|
||||
|
||||
|
||||
def checkpoint_then_commit(ledger, seed, update, save_latest):
|
||||
size = save_latest() # atomic latest checkpoint must succeed BEFORE durable commit
|
||||
ledger.commit_update(seed, update)
|
||||
return size
|
||||
|
||||
|
||||
def choose_candidate(best, update, rows):
|
||||
if update not in VALIDATION_UPDATES[1:]:
|
||||
raise ValueError("Only u64/u128/u192/u256 are trained candidates; never u0")
|
||||
key = selection_key(rows)
|
||||
return best is None or key < tuple(best["selection_key"])
|
||||
|
||||
|
||||
def parameter_deltas(model, initial):
|
||||
import torch
|
||||
|
||||
result = {}
|
||||
for group in ("actor", "critic", "log_std"):
|
||||
delta = torch.cat([(v.detach().cpu() - initial[k]).reshape(-1) for k, v in model.named_parameters()
|
||||
if k == group or k.startswith(group + ".")])
|
||||
if not torch.isfinite(delta).all():
|
||||
raise ValueError("Nonfinite parameter delta")
|
||||
result[group] = {"l2": float(delta.norm()), "max_abs": float(delta.abs().max()),
|
||||
"changed_parameters": int((delta != 0).sum())}
|
||||
return result
|
||||
|
||||
|
||||
def validation_rows(trace, stops, early, nominal, functional, evaluate):
|
||||
"""Audit each *first* episode; learned_policy is only the frozen metadata interface."""
|
||||
import torch
|
||||
|
||||
if not trace or any(s is None or type(s) is not int or s <= 0 for s in stops):
|
||||
raise RuntimeError("Missing first-episode terminal boundary")
|
||||
if any(not torch.isfinite(v).all() for v in trace.values()):
|
||||
raise RuntimeError("Nonfinite validation histories")
|
||||
rows = []
|
||||
for e, stop in enumerate(stops):
|
||||
episode = {k: v[:stop, e:e+1] for k, v in trace.items()}
|
||||
d = {k: v[:, 0] for k, v in episode.items()}
|
||||
actual = d["processed_target"] - nominal.cpu() - .5 * d["reference_used_normalized"]
|
||||
invariants = {
|
||||
"actor46": d["actor_input"].shape == (stop, 46),
|
||||
"metadata": bool(d["actor_metadata_available"].all() and d["control_action_available"].all()),
|
||||
"deterministic_action": bool(torch.allclose(
|
||||
d["requested_action"], d["actor_mean"].tanh(), atol=1e-6, rtol=0)),
|
||||
"request_bound": bool((d["requested_action"].abs() <= 1).all()),
|
||||
"reference_bound": bool((d["reference_used_normalized"].abs() <= 1).all()),
|
||||
"template_bound": bool(((d["processed_target"] - nominal.cpu()).abs() <= .5 + 1e-6).all()),
|
||||
"actual_residual_bound": bool((actual.abs() <= .05 + 1e-6).all()),
|
||||
"actual_residual_logged": bool(torch.allclose(actual, d["effective_residual_rad"], atol=1e-6, rtol=0)),
|
||||
"nominal_only": bool((d["scenario"] == 0).all() and not d["external"].any()),
|
||||
}
|
||||
if not all(invariants.values()):
|
||||
raise RuntimeError(f"Required validation invariant failed env{e}: {invariants}")
|
||||
audited = evaluate(episode, functional, "learned_policy")
|
||||
swing = d["phase"] == 3
|
||||
height = float(d["signed_height_error"].square().mean().sqrt())
|
||||
swing_rms = (float((d["foot"][swing] - d["target"][swing]).square().sum(-1).mean().sqrt())
|
||||
if swing.any() else None)
|
||||
rows.append({"env": e, "success": bool(audited["sim_functional_passed"] and not early[e]
|
||||
and not d["would_fail"].any()),
|
||||
"first_episode_samples": stop, "functional_audit": audited, "invariants": invariants,
|
||||
"height_rms_m": height, "swing_rms_m": swing_rms,
|
||||
"landing_error_m": audited["metrics"].get("landing_error_m"),
|
||||
"reference_rms_rad": float((.5 * d["reference_used_normalized"]).square().mean().sqrt()),
|
||||
"reference_max_rad": float((.5 * d["reference_used_normalized"]).abs().max()),
|
||||
"actual_residual_rms_rad": float(actual.square().mean().sqrt()),
|
||||
"actual_residual_max_rad": float(actual.abs().max()),
|
||||
"deterministic_request_rms": float(d["requested_action"].square().mean().sqrt()),
|
||||
"template_max_rad": float((d["processed_target"] - nominal.cpu()).abs().max()),
|
||||
"failure_flags": d["failure_flags"].any(0).tolist()})
|
||||
selection_key(rows) # successful rows require all three finite metrics
|
||||
return rows
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Experimental fixture-supported contact cycle, not a frozen skill."""
|
||||
|
||||
import gymnasium as gym
|
||||
|
||||
gym.register(
|
||||
id="SkillFactory-Go2FL-ContactCycle-v1",
|
||||
entry_point=f"{__name__}.env:ContactCycleEnv",
|
||||
disable_env_checker=True,
|
||||
kwargs={"env_cfg_entry_point": f"{__name__}.cfg:ContactCycleEnvCfg"},
|
||||
)
|
||||
@@ -0,0 +1,70 @@
|
||||
"""New task/config identity. Old standing physics, rewards and releases are untouched."""
|
||||
|
||||
from isaaclab.envs import mdp as base_mdp
|
||||
from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, RewardTermCfg, TerminationTermCfg
|
||||
from isaaclab.utils.configclass import configclass
|
||||
|
||||
from SkillFactory.legs.contact_cycle.config import load_config
|
||||
from SkillFactory.tasks.manager_based.loaded_leg.cfg import LoadedLegEnvCfg
|
||||
from SkillFactory.tasks.manager_based.single_leg_anchor.mdp.actions import BoundedJointPositionActionCfg
|
||||
|
||||
from . import mdp
|
||||
|
||||
|
||||
@configclass
|
||||
class ObservationsCfg:
|
||||
@configclass
|
||||
class Policy(ObservationGroupCfg):
|
||||
state = ObservationTermCfg(func=mdp.observation)
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = False
|
||||
self.concatenate_terms = True
|
||||
|
||||
@configclass
|
||||
class Privileged(ObservationGroupCfg):
|
||||
truth = ObservationTermCfg(func=mdp.observation, params={"privileged": True})
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = False
|
||||
self.concatenate_terms = True
|
||||
|
||||
policy = Policy()
|
||||
privileged = Privileged()
|
||||
|
||||
|
||||
@configclass
|
||||
class RewardsCfg:
|
||||
task = RewardTermCfg(func=mdp.reward, weight=1.0)
|
||||
effort = RewardTermCfg(func=mdp.effort, weight=-0.01)
|
||||
action_rate = RewardTermCfg(func=mdp.action_rate, weight=-0.005)
|
||||
|
||||
|
||||
@configclass
|
||||
class TerminationsCfg:
|
||||
time_out = TerminationTermCfg(func=base_mdp.time_out, time_out=True)
|
||||
failed = TerminationTermCfg(func=mdp.failed)
|
||||
|
||||
|
||||
@configclass
|
||||
class ContactCycleEnvCfg(LoadedLegEnvCfg):
|
||||
cycle_config: str = "configs/contact_cycle/go2_fl_v1.json"
|
||||
cycle_parameters: dict | None = None
|
||||
auxiliary_enabled: bool = True
|
||||
observations = ObservationsCfg()
|
||||
rewards = RewardsCfg()
|
||||
terminations = TerminationsCfg()
|
||||
|
||||
def __post_init__(self):
|
||||
self.cycle_parameters = load_config(self.cycle_config)
|
||||
self.support_config = self.cycle_parameters["support_config"]
|
||||
super().__post_init__()
|
||||
# Override only this task's spawn. Historical standing keeps its 3mm clearance.
|
||||
self.scene.robot.init_state.pos = (
|
||||
0.0, 0.0, self.anchor_height + self.cycle_parameters["initialization"]["foot_clearance_m"])
|
||||
self.scene.foot_contact.track_friction_forces = True
|
||||
self.actions.joint_position = BoundedJointPositionActionCfg(
|
||||
class_type=mdp.CycleAction, asset_name="robot", joint_names=self.leg_bundle["joint_order"],
|
||||
scale=self.support_parameters["action_scale_rad"], preserve_order=True, use_default_offset=True
|
||||
)
|
||||
self.episode_length_s = sum(self.cycle_parameters["phase_durations_s"])
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Control/physics clock separation and isolated reset, including terminal observations."""
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
|
||||
from SkillFactory.legs.contact_cycle.mechanics import canonical_ids
|
||||
from SkillFactory.legs.contact_cycle.task import FAILURE_NAMES
|
||||
from SkillFactory.tasks.manager_based.loaded_leg.env import LoadedLegEnv
|
||||
|
||||
from .mdp import failure_flags, state
|
||||
|
||||
|
||||
class ContactCycleEnv(LoadedLegEnv):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
original_update = self.scene.update
|
||||
|
||||
def update(dt):
|
||||
original_update(dt)
|
||||
if dt > 0:
|
||||
state(self).after_physics(dt)
|
||||
|
||||
self.scene.update = update
|
||||
|
||||
def step(self, action):
|
||||
self.extras["terminal_failure_flags"] = None
|
||||
phase = state(self).reference()[0].clone()
|
||||
self._step_failures = torch.zeros(self.num_envs, len(FAILURE_NAMES), dtype=torch.bool, device=self.device)
|
||||
result = super().step(action)
|
||||
self.extras["cycle_step"] = {"phase": phase, "failure_flags": self._step_failures.clone()}
|
||||
return result
|
||||
|
||||
def _reset_idx(self, env_ids):
|
||||
env_ids = canonical_ids(env_ids, self.num_envs)
|
||||
if getattr(self, "_standing_step", False):
|
||||
self._step_failures[env_ids] = failure_flags(self)[env_ids]
|
||||
self.extras["terminal_failure_names"] = FAILURE_NAMES
|
||||
self.extras["terminal_failure_flags"] = self._step_failures[env_ids].clone()
|
||||
self.extras["terminal_ids"] = env_ids.clone()
|
||||
self.extras["terminal_observation"] = {
|
||||
"policy": state(self).policy()[env_ids].clone(),
|
||||
"privileged": state(self).privileged()[env_ids].clone(),
|
||||
}
|
||||
# Deliberately bypass LoadedLegEnv's old 45D terminal/reset implementation.
|
||||
ManagerBasedRLEnv._reset_idx(self, env_ids)
|
||||
if hasattr(self, "_cycle_state"):
|
||||
self._cycle_state.reset(env_ids)
|
||||
@@ -0,0 +1,284 @@
|
||||
"""Fixture-supported FL task. All external loads have exactly one composer owner."""
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.utils.math import axis_angle_from_quat
|
||||
|
||||
from SkillFactory.legs.contact_cycle.mechanics import (
|
||||
ContactAcquisition,
|
||||
ContactLatch,
|
||||
SeparationLatch,
|
||||
WrenchSchedule,
|
||||
inverse_rotate,
|
||||
reduce_to_com,
|
||||
rotate,
|
||||
)
|
||||
from SkillFactory.legs.contact_cycle.task import FAILURE_NAMES, DelayLine, command, phase_failures, phase_objective
|
||||
from SkillFactory.tasks.manager_based.loaded_leg.mdp import LoadedState
|
||||
from SkillFactory.tasks.manager_based.single_leg_anchor.mdp.actions import BoundedJointPositionAction
|
||||
|
||||
|
||||
class CycleState(LoadedState):
|
||||
def __init__(self, env):
|
||||
super().__init__(env)
|
||||
self.cc = env.cfg.cycle_parameters
|
||||
b, device = env.num_envs, env.device
|
||||
self.time = torch.zeros(b, device=device)
|
||||
self.scenarios = torch.arange(b, device=device) % len(self.cc["scenarios"])
|
||||
self.schedule = WrenchSchedule(self.cc["events"], b, device)
|
||||
self.latch = ContactLatch(b, device)
|
||||
transition = self.cc["contact_transition"]
|
||||
self.separation = SeparationLatch(b, device, transition["separation_on_m"],
|
||||
transition["separation_off_m"], transition["dwell_s"])
|
||||
init = self.cc["initialization"]
|
||||
self.acquisition = ContactAcquisition(b, device, init["contact_deadline_s"], init["dwell_s"],
|
||||
init["min_load_fraction"], transition["separation_off_m"])
|
||||
self.load_off = torch.zeros(b, device=device, dtype=torch.bool)
|
||||
self.edge_off = torch.zeros(b, device=device, dtype=torch.bool)
|
||||
self.edge_on = torch.zeros_like(self.edge_off)
|
||||
self.weight = self.robot.data.body_mass.torch.sum(-1) * 9.81
|
||||
self.origin = self.foot_center().clone()
|
||||
self.origin[:, 2] = self.bundle["foot"]["radius"]
|
||||
self.base_origin = env.scene.env_origins.clone()
|
||||
self.base_origin[:, 2] += env.cfg.anchor_height
|
||||
self.all_bodies = torch.arange(self.robot.num_bodies, device=device)
|
||||
self.external = torch.zeros(b, self.robot.num_bodies, 6, device=device)
|
||||
self.guide = torch.zeros_like(self.external)
|
||||
self.auxiliary = torch.zeros_like(self.external)
|
||||
self.sensor_delay = DelayLine(b, 18, self.cc["sensor"]["delay_steps"], device)
|
||||
self.action_delay = DelayLine(b, 3, self.cc["actuator"]["delay_steps"], device)
|
||||
self.sensed = torch.zeros(b, 18, device=device)
|
||||
self.executed = torch.zeros(b, 3, device=device)
|
||||
self.substeps = torch.zeros(b, dtype=torch.long, device=device)
|
||||
self.impact = torch.zeros(b, device=device)
|
||||
self.sampler = None
|
||||
self.stand_only = torch.zeros(b, dtype=torch.bool, device=device)
|
||||
self.sampled_points = None
|
||||
self.sampled_stage = torch.zeros(b, dtype=torch.long, device=device)
|
||||
self.reset(torch.arange(b, device=device))
|
||||
|
||||
def reset(self, ids):
|
||||
self.time[ids] = 0
|
||||
self.substeps[ids] = 0
|
||||
self.schedule.reset(ids)
|
||||
if self.sampler is not None and len(ids):
|
||||
from SkillFactory.legs.contact_cycle.curriculum import assert_sample_domain
|
||||
|
||||
sample = self.sampler.sample(ids.cpu())
|
||||
assert_sample_domain(self.cc, sample)
|
||||
for target, key in ((self.scenarios, "scenario"), (self.stand_only, "stand"),
|
||||
(self.sampled_stage, "stage"), (self.schedule.commands, "commands"),
|
||||
(self.sampled_points, "points"), (self.schedule.delays, "delays")):
|
||||
target[ids] = sample[key].to(self.env.device)
|
||||
self.latch.reset(ids)
|
||||
self.separation.reset(ids)
|
||||
self.acquisition.reset(ids)
|
||||
self.edge_on[ids] = self.edge_off[ids] = self.load_off[ids] = False
|
||||
self.impact[ids] = 0
|
||||
self.executed[ids] = 0
|
||||
self.external[ids] = self.guide[ids] = self.auxiliary[ids] = 0
|
||||
self.action_delay.reset(ids)
|
||||
# Reset all sensor history to the new measurement, not the previous episode.
|
||||
sensed = self.raw_sensors()[ids]
|
||||
self.sensor_delay.reset(ids, sensed)
|
||||
self.sensed[ids] = sensed
|
||||
self.robot.permanent_wrench_composer.reset(env_ids=ids)
|
||||
|
||||
def set_sampler(self, sampler):
|
||||
"""Install distribution only at an explicit reset boundary. Never changes old defaults."""
|
||||
if sampler is not None and (sampler.count != self.env.num_envs or sampler.config != self.cc):
|
||||
raise ValueError("Sampler/environment identity mismatch")
|
||||
self.sampler = sampler
|
||||
self.stand_only.zero_()
|
||||
self.scenarios[:] = torch.arange(self.env.num_envs, device=self.env.device) % len(self.cc["scenarios"])
|
||||
if sampler is None:
|
||||
self.schedule.commands = self.schedule.delays = self.sampled_points = None
|
||||
else:
|
||||
shape = (self.env.num_envs, len(self.cc["events"]))
|
||||
self.schedule.commands = torch.zeros(*shape, 6, device=self.env.device)
|
||||
self.schedule.delays = torch.zeros(*shape, device=self.env.device)
|
||||
self.sampled_points = torch.zeros(*shape, 3, device=self.env.device)
|
||||
|
||||
def reference(self):
|
||||
phase, progress, target, force, fraction = command(self.time, self.cc, self.origin, self.weight)
|
||||
if self.sampler is not None:
|
||||
phase = torch.where(self.stand_only, 0, phase)
|
||||
progress = torch.where(self.stand_only, self.time / sum(self.cc["phase_durations_s"]), progress)
|
||||
target = torch.where(self.stand_only[:, None], self.origin, target)
|
||||
force = torch.where(self.stand_only, self.weight, force)
|
||||
fraction = torch.where(self.stand_only, 0., fraction)
|
||||
return phase, progress, target, force, fraction
|
||||
|
||||
def port_reference(self):
|
||||
motion = self.cc["base_motion"]
|
||||
w = 2 * torch.pi * motion["frequency_Hz"]
|
||||
amp = self.time.new_tensor(motion["amplitude_m"])
|
||||
# zero initial position and velocity, bounded displacement by configured amplitude
|
||||
pos = self.base_origin + 0.5 * (1 - torch.cos(w * self.time[:, None])) * amp
|
||||
vel = 0.5 * w * torch.sin(w * self.time[:, None]) * amp
|
||||
return pos, vel
|
||||
|
||||
def apply_loads(self):
|
||||
phase, _, _, _, fraction = self.reference()
|
||||
values = self.schedule.step(self.time, phase, self.edge_off, self.edge_on, self.scenarios,
|
||||
self.env.physics_dt, liftoff_phase=self.separation.edge_phase)
|
||||
self.external.zero_()
|
||||
self.guide.zero_()
|
||||
self.auxiliary.zero_()
|
||||
d = self.robot.data
|
||||
com = d.body_com_pos_w.torch
|
||||
pos, quat, vel, omega = self.root()
|
||||
identity = torch.zeros_like(quat)
|
||||
identity[:, 3] = 1
|
||||
for j, event in enumerate(self.cc["events"]):
|
||||
body = self.robot.body_names.index(event["body"])
|
||||
bpos, bquat = d.body_link_pos_w.torch[:, body], d.body_link_quat_w.torch[:, body]
|
||||
frames = {"world": (self.env.scene.env_origins, identity),
|
||||
"mount": (d.body_link_pos_w.torch[:, self.anchor], d.body_link_quat_w.torch[:, self.anchor]),
|
||||
"body": (bpos, bquat)}
|
||||
point_origin, point_quat = frames[event["point_frame"]]
|
||||
local_point = (self.time.new_tensor(event["point_m"]).expand_as(pos)
|
||||
if self.sampled_points is None else self.sampled_points[:, j])
|
||||
point = point_origin + rotate(point_quat, local_point)
|
||||
self.external[:, body] += reduce_to_com(values[:, j, :3], values[:, j, 3:],
|
||||
frames[event["frame"]][1], point, com[:, body])
|
||||
target, target_vel = self.port_reference()
|
||||
disp = torch.cat((pos - target, axis_angle_from_quat(quat)), -1)
|
||||
velocity = torch.cat((vel - target_vel, omega), -1)
|
||||
raw_guide = (-self.stiffness * disp - self.damping * velocity).clamp(-self.wrench_limit, self.wrench_limit)
|
||||
if not self.env.cfg.guide_enabled:
|
||||
raw_guide.zero_()
|
||||
self.guide[:, self.payload] = reduce_to_com(
|
||||
raw_guide[:, :3], raw_guide[:, 3:], identity, pos, com[:, self.payload]
|
||||
)
|
||||
# Explicit equivalent other-leg support: gravity share + finite impedance at mounting port.
|
||||
# Exactly zero in full support; full system weight in flight. This is an active fixture, not free balance.
|
||||
support = self.cc["support"]
|
||||
fz = fraction * (self.weight + support["kp_N_m"] * (target[:, 2] - pos[:, 2])
|
||||
+ support["kd_Ns_m"] * (target_vel[:, 2] - vel[:, 2]))
|
||||
f = torch.zeros_like(pos)
|
||||
f[:, 2] = fz.clamp(0, support["max_N"]) if self.env.cfg.auxiliary_enabled else 0
|
||||
self.auxiliary[:, self.payload] = reduce_to_com(f, torch.zeros_like(f), identity, pos, com[:, self.payload])
|
||||
# COM-reduced loads; positions=None prevents the backend from adding r x F a second time.
|
||||
# ONE set call across ALL bodies: the installed composer resets the whole selected env on set.
|
||||
total = self.external + self.guide + self.auxiliary
|
||||
self.robot.permanent_wrench_composer.set_forces_and_torques_index(
|
||||
forces=total[..., :3], torques=total[..., 3:], body_ids=self.all_bodies, positions=None, is_global=True
|
||||
)
|
||||
|
||||
def point_velocity(self):
|
||||
d = self.robot.data
|
||||
return d.body_link_lin_vel_w.torch[:, self.foot] + torch.cross(
|
||||
d.body_link_ang_vel_w.torch[:, self.foot],
|
||||
rotate(d.body_link_quat_w.torch[:, self.foot], self.offset), dim=-1)
|
||||
|
||||
def slip_velocity(self):
|
||||
# Actual velocity of the spherical surface point at z-down, not sphere-center drift.
|
||||
r = torch.zeros_like(self.point_velocity())
|
||||
r[:, 2] = -self.bundle["foot"]["radius"]
|
||||
surface = self.point_velocity() + torch.cross(
|
||||
self.robot.data.body_link_ang_vel_w.torch[:, self.foot], r, dim=-1
|
||||
)
|
||||
return surface[:, :2].norm(dim=-1)
|
||||
|
||||
def friction(self):
|
||||
return self.env.scene["foot_contact"].data.friction_forces_w.torch[:, 0].sum(1)
|
||||
|
||||
def raw_sensors(self):
|
||||
_, quat, _, omega = self.root()
|
||||
gravity = torch.zeros_like(omega)
|
||||
gravity[:, 2] = -1
|
||||
return torch.cat((self.q(), self.robot.data.joint_vel.torch[:, self.joints], self.mount_wrench(),
|
||||
inverse_rotate(quat, gravity), inverse_rotate(quat, omega)), -1)
|
||||
|
||||
def after_physics(self, dt):
|
||||
self.substeps += 1
|
||||
self.time[:] = self.substeps * dt
|
||||
force = self.contact()[:, 2]
|
||||
self.load_off, self.edge_on = self.latch.update(force, dt)
|
||||
phase = self.reference()[0]
|
||||
gap = self.foot_center()[:, 2] - self.bundle["foot"]["radius"]
|
||||
self.acquisition.update(self.time, gap, force, self.weight, dt)
|
||||
self.edge_off = self.separation.update(gap, self.latch.contact, phase, dt)
|
||||
self.impact = torch.where(phase == 4, torch.maximum(self.impact, force), torch.zeros_like(force))
|
||||
if (self.substeps % self.env.cfg.decimation == 0).all():
|
||||
x = self.raw_sensors()
|
||||
noise = self.cc["sensor"]
|
||||
scale = x.new_tensor([noise["joint_noise_std_rad"]]*3 + [noise["velocity_noise_std_rad_s"]]*3
|
||||
+ [noise["wrench_noise_std"]]*6 + [0.0]*6)
|
||||
self.sensed = self.sensor_delay.push(x + torch.randn_like(x) * scale)
|
||||
|
||||
def policy(self):
|
||||
phase, progress, target, force, _ = self.reference()
|
||||
# Desired position expressed in commanded (not ground-truth actual) port frame.
|
||||
cmd = torch.cat((torch.nn.functional.one_hot(phase, 6).float(), progress[:, None],
|
||||
target - self.port_reference()[0], force[:, None]), -1)
|
||||
return torch.cat((self.sensed, self.executed, cmd), -1) # 18 + 3 + 11 = 32
|
||||
|
||||
def privileged(self):
|
||||
return torch.cat((self.root()[0] - self.env.scene.env_origins, self.foot_center(),
|
||||
self.contact(), self.friction(), self.external.flatten(1),
|
||||
self.guide.flatten(1), self.auxiliary.flatten(1)), -1)
|
||||
|
||||
def objective(self):
|
||||
phase, progress, target, force, _ = self.reference()
|
||||
center = self.foot_center()
|
||||
reward, violation = phase_objective(
|
||||
phase, progress, (center-target).norm(dim=-1), center[:, 2] - self.bundle["foot"]["radius"],
|
||||
self.contact()[:, 2], force, self.slip_velocity(), self.impact, self.weight,
|
||||
self.cc["contact_transition"]["unload_tracking_scale_m"])
|
||||
return reward, violation | self.separation.premature | self.acquisition.failed
|
||||
|
||||
|
||||
def state(env):
|
||||
if not hasattr(env, "_cycle_state"):
|
||||
env._cycle_state = CycleState(env)
|
||||
return env._cycle_state
|
||||
|
||||
|
||||
def observation(env, privileged=False):
|
||||
return state(env).privileged() if privileged else state(env).policy()
|
||||
|
||||
|
||||
class CycleAction(BoundedJointPositionAction):
|
||||
def process_actions(self, actions):
|
||||
s = state(self._env)
|
||||
c = s.cc["actuator"]
|
||||
effective = s.action_delay.push(actions.clamp(-1, 1)) * c["gain"]
|
||||
effective += actions.new_tensor(c["bias_rad"]) / self._env.cfg.support_parameters["action_scale_rad"]
|
||||
super().process_actions(effective)
|
||||
s.executed[:] = self.raw_actions
|
||||
|
||||
def apply_actions(self):
|
||||
state(self._env).apply_loads()
|
||||
super().apply_actions()
|
||||
|
||||
|
||||
def reward(env):
|
||||
return state(env).objective()[0]
|
||||
|
||||
|
||||
def failure_flags(env):
|
||||
"""Independent, overlapping causes in a stable order, evaluated BEFORE reset."""
|
||||
s = state(env)
|
||||
phase, progress, _, _, _ = s.reference()
|
||||
reasons = phase_failures(phase, progress, s.foot_center()[:, 2] - s.bundle["foot"]["radius"],
|
||||
s.contact()[:, 2], s.weight)
|
||||
reasons.update(
|
||||
nonfinite=~torch.isfinite(torch.cat((s.raw_sensors(), s.root()[0], s.contact()), -1)).all(-1),
|
||||
contact_acquisition_timeout=s.acquisition.failed, premature_separation=s.separation.premature,
|
||||
low_height=s.root()[0][:, 2] < env.cfg.anchor_height - 0.1, tilt=s.tilt() > 0.6)
|
||||
return torch.stack([reasons[name] for name in FAILURE_NAMES], -1)
|
||||
|
||||
|
||||
def failed(env):
|
||||
return failure_flags(env).any(-1)
|
||||
|
||||
|
||||
def effort(env):
|
||||
s = state(env)
|
||||
return (s.robot.data.applied_torque.torch[:, s.joints] / s.effort).square().mean(-1)
|
||||
|
||||
|
||||
def action_rate(env):
|
||||
return (env.action_manager.action - env.action_manager.prev_action).square().mean(-1)
|
||||
@@ -0,0 +1,184 @@
|
||||
"""Physics-rate validation capture; evaluate the first episode, never repaired autoresets."""
|
||||
|
||||
import math
|
||||
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle.mechanics import delivered_events
|
||||
from SkillFactory.legs.contact_cycle.metrics import summarize
|
||||
from SkillFactory.legs.contact_cycle.task import FAILURE_NAMES
|
||||
|
||||
from .mdp import effort, failed, failure_flags, state
|
||||
|
||||
|
||||
class PhysicalSafetyAudit:
|
||||
"""Accumulate at every physics tick, check at control boundaries (also across resets)."""
|
||||
|
||||
def __init__(self, env, thresholds):
|
||||
self.env, self.thresholds, self.s = env, thresholds, state(env)
|
||||
self.maximum = torch.zeros(3, device=env.device)
|
||||
self.finite = torch.tensor(True, device=env.device)
|
||||
self.samples = 0
|
||||
self.lower = torch.tensor([j["limits"]["lower"] for j in self.s.bundle["joints"]], device=env.device)
|
||||
self.upper = torch.tensor([j["limits"]["upper"] for j in self.s.bundle["joints"]], device=env.device)
|
||||
self.speed = torch.tensor([j["limits"]["velocity"] for j in self.s.bundle["joints"]], device=env.device)
|
||||
|
||||
def __enter__(self):
|
||||
self.previous = self.env.scene.update
|
||||
|
||||
def update(dt):
|
||||
self.previous(dt)
|
||||
if dt > 0:
|
||||
s = self.s
|
||||
ratio = torch.maximum((s.robot.data.applied_torque.torch[:, s.joints]/s.effort).abs().amax(),
|
||||
(s.robot.data.joint_vel.torch[:, s.joints]/self.speed).abs().amax())
|
||||
excess = torch.maximum(self.lower - s.q(), s.q() - self.upper).clamp(min=0).amax()
|
||||
values = torch.stack((ratio, excess, s.guide[..., 2].abs().amax()))
|
||||
self.maximum = torch.maximum(self.maximum, values)
|
||||
self.finite &= (torch.isfinite(values).all() & torch.isfinite(s.raw_sensors()).all()
|
||||
& torch.isfinite(s.robot.data.root_state_w.torch).all())
|
||||
self.samples += 1
|
||||
|
||||
self.env.scene.update = update
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
self.env.scene.update = self.previous
|
||||
|
||||
def report(self):
|
||||
values = self.maximum.cpu().tolist()
|
||||
return {"physics_samples": self.samples, "finite": bool(self.finite),
|
||||
"max_effort_velocity_ratio": values[0] if math.isfinite(values[0]) else None,
|
||||
"max_joint_excess_rad": values[1] if math.isfinite(values[1]) else None,
|
||||
"max_guide_vertical_N": values[2] if math.isfinite(values[2]) else None}
|
||||
|
||||
def check(self):
|
||||
report = self.report()
|
||||
if (not report["finite"] or report["max_effort_velocity_ratio"] is None
|
||||
or report["max_effort_velocity_ratio"] > self.thresholds["normalized_effort_velocity_max"]
|
||||
or report["max_joint_excess_rad"] > self.thresholds["joint_limit_excess_rad_max"]
|
||||
or report["max_guide_vertical_N"] != 0):
|
||||
raise RuntimeError(f"Physical safety gate failed: {report}")
|
||||
|
||||
|
||||
class CycleRecorder:
|
||||
def __init__(self, env):
|
||||
self.env, self.state = env, state(env)
|
||||
self.frames = []
|
||||
self.stops = [None] * env.num_envs
|
||||
self.early = torch.zeros(env.num_envs, dtype=torch.bool)
|
||||
s = self.state
|
||||
self.lower = torch.tensor([j["limits"]["lower"] for j in s.bundle["joints"]], device=env.device)
|
||||
self.upper = torch.tensor([j["limits"]["upper"] for j in s.bundle["joints"]], device=env.device)
|
||||
self.speed = torch.tensor([j["limits"]["velocity"] for j in s.bundle["joints"]], device=env.device)
|
||||
self.previous = None
|
||||
self.actor_input = torch.zeros(env.num_envs, 32)
|
||||
self.actor_mean = torch.zeros(env.num_envs, 3)
|
||||
self.actor_std = torch.zeros(env.num_envs, 3)
|
||||
self.requested_action = torch.zeros(env.num_envs, 3)
|
||||
self.actor_available = torch.zeros(env.num_envs, dtype=torch.bool)
|
||||
self.action_available = torch.zeros(env.num_envs, dtype=torch.bool)
|
||||
|
||||
def before_control(self, observation, action, mean=None, std=None):
|
||||
if observation is not None:
|
||||
self.actor_input = observation.detach().cpu().clone()
|
||||
self.requested_action = action.detach().cpu().clone()
|
||||
self.action_available.fill_(True)
|
||||
self.actor_available.fill_(observation is not None and mean is not None and std is not None)
|
||||
if mean is not None and std is not None:
|
||||
self.actor_mean = mean.detach().cpu().clone()
|
||||
self.actor_std = std.detach().cpu().expand(self.env.num_envs, 3).clone()
|
||||
|
||||
def __enter__(self):
|
||||
self.initial_state = self.snapshot() # t=0 separately; not an extra physics tick
|
||||
self.previous = self.env.scene.update
|
||||
|
||||
def update(dt):
|
||||
self.previous(dt)
|
||||
if dt > 0:
|
||||
self.record()
|
||||
|
||||
self.env.scene.update = update
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
self.env.scene.update = self.previous
|
||||
|
||||
def snapshot(self):
|
||||
s = self.state
|
||||
phase, progress, target, force, _ = s.reference()
|
||||
ratio = torch.maximum((s.robot.data.applied_torque.torch[:, s.joints]/s.effort).abs().amax(-1),
|
||||
(s.robot.data.joint_vel.torch[:, s.joints]/self.speed).abs().amax(-1))
|
||||
values = {"phase": phase, "progress": progress, "time": s.time, "scenario": s.scenarios,
|
||||
"weight": s.weight, "normal": s.contact(), "friction": s.friction(), "foot": s.foot_center(),
|
||||
"target": target, "gap": s.foot_center()[:, 2] - s.bundle["foot"]["radius"],
|
||||
"desired_force": force,
|
||||
"joint_excess": torch.maximum(self.lower - s.q(), s.q() - self.upper).clamp(min=0).amax(-1),
|
||||
"limit_ratio": ratio, "slip_speed": s.slip_velocity(),
|
||||
"height_error": (s.root()[0][:, 2] - s.port_reference()[0][:, 2]).abs(),
|
||||
"external": s.external, "guide": s.guide, "auxiliary": s.auxiliary,
|
||||
"would_fail": failed(self.env), "failure_flags": failure_flags(self.env), "tilt": s.tilt(),
|
||||
"root_state": torch.cat(s.root(), -1),
|
||||
"signed_height_error": s.root()[0][:, 2] - s.port_reference()[0][:, 2],
|
||||
"joint_pos": s.q(), "joint_vel": s.robot.data.joint_vel.torch[:, s.joints],
|
||||
"applied_torque": s.robot.data.applied_torque.torch[:, s.joints],
|
||||
"processed_target": self.env.action_manager.get_term("joint_position").processed_actions,
|
||||
"effective_action": s.executed, "policy_snapshot": s.policy(),
|
||||
"actor_input": self.actor_input, "actor_mean": self.actor_mean, "actor_std": self.actor_std,
|
||||
"requested_action": self.requested_action, "actor_metadata_available": self.actor_available,
|
||||
"control_action_available": self.action_available,
|
||||
"task_reward_unweighted": s.objective()[0], "effort_cost_unweighted": effort(self.env),
|
||||
"contact_acquired": s.acquisition.acquired, "acquisition_failed": s.acquisition.failed,
|
||||
"acquisition_timer": s.acquisition.timer, "contact_armed": s.separation.armed,
|
||||
"separation_timer": s.separation.timer,
|
||||
"load_off": s.load_off, "liftoff": s.edge_off, "liftoff_phase": s.separation.edge_phase,
|
||||
"separated": s.separation.separated, "premature_separation": s.separation.premature,
|
||||
"event_fired": s.schedule.fired, "event_completed": s.schedule.completed,
|
||||
"event_integral": s.schedule.integral}
|
||||
return {k: v.detach().cpu().clone() for k, v in values.items()}
|
||||
|
||||
def record(self):
|
||||
self.frames.append(self.snapshot())
|
||||
|
||||
def end_control(self, terminated, truncated, final_step):
|
||||
done = (terminated | truncated).nonzero().flatten().cpu().tolist()
|
||||
for e in done:
|
||||
if self.stops[e] is None:
|
||||
self.stops[e] = len(self.frames)
|
||||
self.early[e] = bool(terminated[e]) or not final_step
|
||||
|
||||
def summarize(self, thresholds):
|
||||
if not self.frames:
|
||||
raise RuntimeError("No physics samples captured")
|
||||
trace = {k: torch.stack([f[k] for f in self.frames]) for k in self.frames[0]}
|
||||
rows = []
|
||||
for e, stop in enumerate(self.stops):
|
||||
episode = {k: v[:stop, e:e+1] for k, v in trace.items()}
|
||||
row = summarize(episode, self.env.physics_dt, thresholds, self.state.cc["scenarios"])[0]
|
||||
row["env"] = e
|
||||
row["first_episode_samples"] = len(episode["time"])
|
||||
flags = episode["failure_flags"][:, 0]
|
||||
row["terminal_causes"] = [name for j, name in enumerate(FAILURE_NAMES) if flags[:, j].any()]
|
||||
hits = flags.any(-1).nonzero().flatten()
|
||||
row["first_failure_time_s"] = float(episode["time"][int(hits[0]), 0]) if len(hits) else None
|
||||
row["contact_acquired"] = bool(episode["contact_acquired"][:, 0].any())
|
||||
delivered = bool(delivered_events(
|
||||
self.state.cc["events"], episode["scenario"][0], episode["event_fired"][-1],
|
||||
episode["event_completed"][-1], episode["event_integral"][-1])[0])
|
||||
row.setdefault("gates", {})["disturbance_delivery"] = delivered
|
||||
if not delivered:
|
||||
row["success"] = False
|
||||
row["failure_reasons"].append("disturbance_not_delivered")
|
||||
if episode["acquisition_failed"].any():
|
||||
row["success"] = False
|
||||
row["failure_reasons"].append("contact_acquisition_timeout")
|
||||
if episode["premature_separation"].any():
|
||||
row["success"] = False
|
||||
row["failure_reasons"].append("premature_separation")
|
||||
complete_clock = (len(episode["time"]) == round(sum(self.state.cc["phase_durations_s"])/self.env.physics_dt)
|
||||
and float(episode["time"][-1, 0]) >= sum(self.state.cc["phase_durations_s"]) - 1e-5)
|
||||
if self.early[e] or not complete_clock:
|
||||
row["success"] = False
|
||||
row["failure_reasons"].append("terminated_or_incomplete_first_episode")
|
||||
rows.append(row)
|
||||
return rows, trace
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Nominal simulation-truth residual task, NOT a hardware or learned-skill release."""
|
||||
import gymnasium as gym
|
||||
|
||||
gym.register(
|
||||
id='SkillFactory-Go2FL-ContactCycleSim-v1',
|
||||
entry_point=f'{__name__}.env:SimContactCycleEnv',
|
||||
disable_env_checker=True,
|
||||
kwargs={'env_cfg_entry_point': f'{__name__}.cfg:SimContactCycleEnvCfg'},
|
||||
)
|
||||
@@ -0,0 +1,61 @@
|
||||
"""Separate nominal simulation-only config. No historical task parameters are mutated."""
|
||||
from isaaclab.managers import ObservationGroupCfg, ObservationTermCfg, RewardTermCfg
|
||||
from isaaclab.utils.configclass import configclass
|
||||
|
||||
from SkillFactory.legs.contact_cycle_sim.config import load_config
|
||||
from SkillFactory.tasks.manager_based.contact_cycle.cfg import ContactCycleEnvCfg
|
||||
from SkillFactory.tasks.manager_based.single_leg_anchor.mdp.actions import BoundedJointPositionActionCfg
|
||||
|
||||
from . import mdp
|
||||
|
||||
|
||||
@configclass
|
||||
class ObservationsCfg:
|
||||
@configclass
|
||||
class Policy(ObservationGroupCfg):
|
||||
state = ObservationTermCfg(func=mdp.observation)
|
||||
|
||||
def __post_init__(self):
|
||||
self.enable_corruption = False
|
||||
self.concatenate_terms = True
|
||||
|
||||
@configclass
|
||||
class Privileged(ObservationGroupCfg):
|
||||
truth = ObservationTermCfg(func=mdp.observation, params={'privileged': True})
|
||||
|
||||
policy = Policy()
|
||||
privileged = Privileged()
|
||||
|
||||
|
||||
@configclass
|
||||
class RewardsCfg:
|
||||
task = RewardTermCfg(func=mdp.base.reward, weight=1.)
|
||||
effort = RewardTermCfg(func=mdp.base.effort, weight=-.01)
|
||||
action_rate = RewardTermCfg(func=mdp.base.action_rate, weight=-.005)
|
||||
root_position = RewardTermCfg(func=mdp.root_position_cost, weight=-1.)
|
||||
root_velocity = RewardTermCfg(func=mdp.root_velocity_cost, weight=-.1)
|
||||
residual = RewardTermCfg(func=mdp.residual_cost, weight=-.05)
|
||||
|
||||
|
||||
@configclass
|
||||
class SimContactCycleEnvCfg(ContactCycleEnvCfg):
|
||||
residual_config: str = 'configs/contact_cycle/simulation_residual_v1.json'
|
||||
residual_parameters: dict | None = None
|
||||
observations = ObservationsCfg()
|
||||
rewards = RewardsCfg()
|
||||
|
||||
def __post_init__(self):
|
||||
self.residual_parameters = c = load_config(self.residual_config)
|
||||
self.cycle_config = c['cycle_config']
|
||||
super().__post_init__()
|
||||
cycle = self.cycle_parameters
|
||||
if (any(cycle['sensor'].values()) or cycle['actuator']['gain'] != 1
|
||||
or any(cycle['actuator']['bias_rad']) or cycle['actuator']['delay_steps'] != 0
|
||||
or any(cycle['base_motion']['amplitude_m']) or self.support_parameters['action_scale_rad'] != .5):
|
||||
raise ValueError('Sim residual v1 requires declared noiseless, undelayed nominal fixture and .5rad scale')
|
||||
self.actions.joint_position = BoundedJointPositionActionCfg(
|
||||
class_type=mdp.SimResidualAction, asset_name='robot', joint_names=self.leg_bundle['joint_order'],
|
||||
scale=.5, preserve_order=True, use_default_offset=True)
|
||||
self.rewards.root_position.weight = -c['reward']['position_weight']
|
||||
self.rewards.root_velocity.weight = -c['reward']['velocity_weight']
|
||||
self.rewards.residual.weight = -c['reward']['residual_weight']
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Reuse physical clock, safety terminations and PRE-reset capture via virtual policy()."""
|
||||
from SkillFactory.tasks.manager_based.contact_cycle.env import ContactCycleEnv
|
||||
|
||||
from .mdp import state
|
||||
|
||||
|
||||
class SimContactCycleEnv(ContactCycleEnv):
|
||||
def __init__(self, *args, **kwargs):
|
||||
super().__init__(*args, **kwargs)
|
||||
state(self) # fail closed on a wrong state contract
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
"""Distinct, directly instantiated evaluation config; frozen config is unchanged."""
|
||||
from isaaclab.utils.configclass import configclass
|
||||
|
||||
from .cfg import SimContactCycleEnvCfg
|
||||
from .evaluation_mdp import EvaluationResidualAction
|
||||
|
||||
|
||||
@configclass
|
||||
class EvaluationContactCycleEnvCfg(SimContactCycleEnvCfg):
|
||||
def __post_init__(self):
|
||||
super().__post_init__()
|
||||
self.scene.num_envs = 1
|
||||
self.actions.joint_position.class_type = EvaluationResidualAction
|
||||
# Keep frozen reward/observation/termination definitions. The evaluation
|
||||
# runtime checks their failure floors per physics tick, not manager timeout.
|
||||
# Cycle count comes from Protocol, never by extending a training episode.
|
||||
+498
@@ -0,0 +1,498 @@
|
||||
"""Evaluation-only no-autoreset runtime. Not a Gym training environment.
|
||||
|
||||
Callbacks are synchronous/read-only and must copy tensor evidence before returning.
|
||||
The installed RL step has no reusable single-substep helper. Only its scalar
|
||||
physics-loop branch is reproduced; manager autoreset is never entered.
|
||||
"""
|
||||
from collections.abc import Callable
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, replace
|
||||
from functools import wraps
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from isaaclab.envs import ManagerBasedRLEnv
|
||||
|
||||
from SkillFactory.legs.contact_cycle_sim.evaluation_protocol import (
|
||||
CONTROL_TICKS,
|
||||
CYCLE_TICKS,
|
||||
PHYSICS_DT_S,
|
||||
Clock,
|
||||
Command,
|
||||
Protocol,
|
||||
)
|
||||
|
||||
from .evaluation_mdp import EvaluationCycleState, state, vector_tuple
|
||||
|
||||
# Expose exact installed source dependencies for the separate evaluation binding.
|
||||
INSTALLED_ISAAC_SOURCES = {
|
||||
'manager_based_rl_env.py': 'a963cfcdb4cd60955cd022ed709d27c99a6935685b69180bb29d74f8983f6566',
|
||||
'manager_based_env.py': '2159b887235fd664684be917c34890e9054e51848855148229216d4f2ec85ad8',
|
||||
}
|
||||
INSTALLED_COMPOSER_SHA256 = '8fb3ab4e59db121165db52daf61e0de0e73653f0c154a143f6a828c198082c06'
|
||||
|
||||
|
||||
def verify_installed_stepping(envs_directory):
|
||||
for name, expected in INSTALLED_ISAAC_SOURCES.items():
|
||||
if sha256((Path(envs_directory) / name).read_bytes()).hexdigest() != expected:
|
||||
raise RuntimeError(f'Installed Isaac stepping dependency changed: {name}')
|
||||
|
||||
|
||||
class RuntimeViolation(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class RuntimeHooks:
|
||||
"""Class hooks MUST surround construction through close (single writer only).
|
||||
|
||||
Counts attempted and completed sim.step calls, including constructor/reset.
|
||||
before_step is the future aggregate budget/deadline owner's hook; exceptions
|
||||
fail closed. Guard lists are public binding evidence, not a security sandbox.
|
||||
"""
|
||||
def __init__(self, simulation_class, guarded_methods, *, before_step=None):
|
||||
self.simulation_class = simulation_class
|
||||
self.guarded_methods = tuple(guarded_methods)
|
||||
self.before_step = before_step
|
||||
self.active = False
|
||||
self.mode = 'closed'
|
||||
self.attempted_steps = self.completed_steps = 0
|
||||
self.initialization_steps = self.rollout_steps = 0
|
||||
self.reset_calls = self.pose_write_calls = self.composer_buffer_replacements = 0
|
||||
self._load_owner = self._replacement_owner = None
|
||||
self.violations = []
|
||||
self._patches = []
|
||||
self._guarded = set()
|
||||
|
||||
@classmethod
|
||||
def isaac(cls, *, before_step=None):
|
||||
"""Call after AppLauncher/import setup but BEFORE environment construction."""
|
||||
from isaaclab_physx.assets.articulation import Articulation
|
||||
|
||||
from isaaclab.scene import InteractiveScene
|
||||
from isaaclab.sim import SimulationContext
|
||||
|
||||
guards = [(SimulationContext, 'reset'), (InteractiveScene, 'reset'), (InteractiveScene, 'reset_to')]
|
||||
# Backend class, not the articulation factory: also covers legacy aliases.
|
||||
guards += [(Articulation, name) for name in dir(Articulation)
|
||||
if name == 'reset' or (name.startswith('write_') and '_to_sim' in name
|
||||
and name != 'write_data_to_sim')]
|
||||
return cls(SimulationContext, guards, before_step=before_step)
|
||||
|
||||
def _patch(self, owner, name, replacement):
|
||||
own = name in vars(owner)
|
||||
old = getattr(owner, name)
|
||||
self._patches.append((owner, name, old, own))
|
||||
setattr(owner, name, replacement)
|
||||
|
||||
def require_initialization(self, operation):
|
||||
if not self.active or self.mode not in ('construction', 'initialization'):
|
||||
self.violations.append(operation)
|
||||
raise RuntimeViolation(f'Illegal reset/pose write: {operation}')
|
||||
|
||||
def guard_object(self, obj, names):
|
||||
for name in names:
|
||||
key = (id(obj), name)
|
||||
if key in self._guarded:
|
||||
continue
|
||||
self._guarded.add(key)
|
||||
old = getattr(obj, name)
|
||||
|
||||
@wraps(old)
|
||||
def guarded(*args, _old=old, _name=name, **kwargs):
|
||||
self.require_initialization(_name)
|
||||
if 'reset' in _name:
|
||||
self.reset_calls += 1
|
||||
else:
|
||||
self.pose_write_calls += 1
|
||||
return _old(*args, **kwargs)
|
||||
|
||||
self._patch(obj, name, guarded)
|
||||
|
||||
def guard_composer(self, composer):
|
||||
"""Setter-internal input-buffer replacement is not a trial/state reset."""
|
||||
key = (id(composer), 'reset')
|
||||
if key in self._guarded:
|
||||
return
|
||||
self._guarded.add(key)
|
||||
reset = composer.reset
|
||||
setter = composer.set_forces_and_torques_index
|
||||
|
||||
@wraps(reset)
|
||||
def guarded_reset(*args, **kwargs):
|
||||
if self._replacement_owner is composer:
|
||||
self.composer_buffer_replacements += 1
|
||||
else:
|
||||
self.require_initialization('composer.reset')
|
||||
self.reset_calls += 1
|
||||
return reset(*args, **kwargs)
|
||||
|
||||
@wraps(setter)
|
||||
def guarded_setter(*args, **kwargs):
|
||||
if self._load_owner is not composer or self._replacement_owner is not None:
|
||||
self.violations.append('unowned composer setter')
|
||||
raise RuntimeViolation('Only the bound physics action may replace wrench buffers')
|
||||
self._replacement_owner = composer
|
||||
try:
|
||||
return setter(*args, **kwargs)
|
||||
finally:
|
||||
self._replacement_owner = None
|
||||
|
||||
self._patch(composer, 'reset', guarded_reset)
|
||||
self._patch(composer, 'set_forces_and_torques_index', guarded_setter)
|
||||
|
||||
@contextmanager
|
||||
def wrench_update(self, composer):
|
||||
if not self.active or self.mode != 'locked' or self._load_owner is not None:
|
||||
raise RuntimeViolation('Invalid unique-writer scope')
|
||||
self._load_owner = composer
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._load_owner = None
|
||||
|
||||
def __enter__(self):
|
||||
if self.active:
|
||||
raise RuntimeError('Runtime hooks already installed')
|
||||
self.active, self.mode = True, 'construction'
|
||||
old = self.simulation_class.step
|
||||
|
||||
@wraps(old)
|
||||
def step(sim, *args, **kwargs):
|
||||
if self.mode not in ('construction', 'initialization', 'rollout'):
|
||||
self.violations.append('sim.step outside runtime')
|
||||
raise RuntimeViolation('Unowned sim.step')
|
||||
self.attempted_steps += 1
|
||||
if self.before_step is not None:
|
||||
self.before_step(self)
|
||||
result = old(sim, *args, **kwargs)
|
||||
self.completed_steps += 1
|
||||
if self.mode == 'rollout':
|
||||
self.rollout_steps += 1
|
||||
else:
|
||||
self.initialization_steps += 1
|
||||
return result
|
||||
|
||||
self._patch(self.simulation_class, 'step', step)
|
||||
for owner, name in self.guarded_methods:
|
||||
self.guard_object(owner, (name,))
|
||||
return self
|
||||
|
||||
@contextmanager
|
||||
def scope(self, mode):
|
||||
if not self.active or self.mode != 'locked' or mode not in ('initialization', 'rollout'):
|
||||
raise RuntimeViolation('Invalid runtime hook scope')
|
||||
self.mode = mode
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self.mode = 'locked'
|
||||
|
||||
def __exit__(self, *_):
|
||||
for owner, name, old, own in reversed(self._patches):
|
||||
if own:
|
||||
setattr(owner, name, old)
|
||||
else:
|
||||
delattr(owner, name)
|
||||
self._patches.clear()
|
||||
self._guarded.clear()
|
||||
self.active, self.mode = False, 'closed'
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RuntimeEvent:
|
||||
kind: str # initial, tick, next_reference
|
||||
trial_index: int
|
||||
clock: Clock
|
||||
command: Command
|
||||
held_control_index: int | None
|
||||
action_origin_tick: int | None
|
||||
reference_used_clock: Clock | None
|
||||
reference_used: tuple[float, ...]
|
||||
reference_next_clock: Clock
|
||||
reference_next: tuple[float, ...]
|
||||
causes: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class SeamDecision:
|
||||
admitted: bool
|
||||
causes: tuple[str, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StopResult:
|
||||
reason: str # failure or protocol_complete, never a gate-pass assertion
|
||||
trial_index: int
|
||||
clock: Clock
|
||||
causes: tuple[str, ...]
|
||||
fatal: bool
|
||||
physics_ticks: int
|
||||
completed_controls: int
|
||||
partial_control_ticks: int
|
||||
completed_clock_cycles: int
|
||||
all_sim_steps_attempted: int
|
||||
all_sim_steps_completed: int
|
||||
initialization_steps: int
|
||||
rollout_steps: int
|
||||
reset_calls: int
|
||||
pose_write_calls: int
|
||||
composer_buffer_replacements: int
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class StepResult:
|
||||
observation: object | None
|
||||
reward: object | None
|
||||
ticks_advanced: int
|
||||
stop: StopResult | None
|
||||
|
||||
|
||||
EvidenceCallback = Callable[[RuntimeEvent, EvaluationCycleState], tuple[str, ...]]
|
||||
SeamCallback = Callable[[RuntimeEvent, EvaluationCycleState], SeamDecision]
|
||||
|
||||
|
||||
def _causes(value):
|
||||
if not isinstance(value, tuple) or any(not isinstance(v, str) or not v for v in value):
|
||||
raise TypeError('Callback must return a tuple of nonempty cause strings')
|
||||
return value
|
||||
|
||||
|
||||
def _fatal(causes):
|
||||
return any(c.startswith(('nonfinite', 'hardware', 'identity', 'illegal_', 'storage', 'recording',
|
||||
'budget', 'process', 'infrastructure', 'guide_', 'auxiliary_')) for c in causes)
|
||||
|
||||
|
||||
class EvaluationContactCycleEnv(ManagerBasedRLEnv):
|
||||
"""Direct construction only; no registration or inherited autoreset step.
|
||||
|
||||
Required evidence callback: initial snapshot, then every post-latch tick
|
||||
(including the old endpoint), then next_reference after admission/refresh.
|
||||
Its returned causes join ALL runtime causes. Missing/raising callbacks stop.
|
||||
Intermediate endpoint seam callback must return explicit SeamDecision(True).
|
||||
No callback means no admission. Final endpoint has no next reference/reset.
|
||||
"""
|
||||
def __init__(self, cfg, *, protocol: Protocol, trial_index: int, runtime_hooks: RuntimeHooks,
|
||||
evidence_callback: EvidenceCallback, seam_callback: SeamCallback | None = None, **kwargs):
|
||||
if not runtime_hooks.active or runtime_hooks.mode != 'construction':
|
||||
raise RuntimeError('Install RuntimeHooks before environment construction')
|
||||
if not callable(evidence_callback):
|
||||
raise ValueError('Evidence callback required before construction')
|
||||
protocol.trial(trial_index)
|
||||
if protocol.document['stage'] == 'P2' and trial_index != 0:
|
||||
raise ValueError('P2 must start with preregistered row zero')
|
||||
self.evaluation_protocol, self.evaluation_trial_index = protocol, trial_index
|
||||
self.runtime_hooks = runtime_hooks
|
||||
self.evidence_callback, self.seam_callback = evidence_callback, seam_callback
|
||||
self.stop_result = None
|
||||
self._started = self._initial_reset = self._finalized = False
|
||||
self._consumed_rows = set()
|
||||
cfg.seed = protocol.trial(trial_index).seed
|
||||
if cfg.scene.num_envs != 1 or cfg.decimation != CONTROL_TICKS or cfg.sim.dt != PHYSICS_DT_S:
|
||||
raise ValueError('Evaluation requires one environment and 500Hz/100Hz clocks')
|
||||
try:
|
||||
super().__init__(cfg, **kwargs)
|
||||
if self._physics_handles_decimation or self.recorder_manager.active_terms:
|
||||
raise ValueError('Require scalar physics ticks and external evidence callbacks, not manager recorders')
|
||||
if 'interval' in self.event_manager.available_modes:
|
||||
raise ValueError('Evaluation disallows unbound interval events')
|
||||
initial_state = state(self)
|
||||
# Preserve the constructor command, NOT a post-reset measured foot.
|
||||
# Later P2 states are constructed at the previous row's terminal pose.
|
||||
self._canonical_command_origins = (initial_state.origin.clone(),
|
||||
initial_state.base_origin.clone())
|
||||
self._guard_trial_objects()
|
||||
except Exception:
|
||||
self.runtime_hooks.violations.append('infrastructure_constructor')
|
||||
raise
|
||||
finally:
|
||||
self.runtime_hooks.mode = 'locked'
|
||||
|
||||
def _guard_trial_objects(self):
|
||||
s = state(self)
|
||||
self.runtime_hooks.guard_composer(s.robot.permanent_wrench_composer)
|
||||
objects = [s.controller, s.schedule, s.latch, s.separation, s.acquisition,
|
||||
s.sensor_delay, s.action_delay]
|
||||
objects += [getattr(self, name) for name in (
|
||||
'action_manager', 'observation_manager', 'reward_manager', 'termination_manager',
|
||||
'command_manager', 'event_manager', 'curriculum_manager')]
|
||||
objects += list(self.scene.sensors.values()) + list(s.robot.actuators.values())
|
||||
for obj in objects:
|
||||
self.runtime_hooks.guard_object(obj, ('reset',))
|
||||
|
||||
def _event(self, kind, causes=()):
|
||||
s = state(self)
|
||||
g = s.command_clock.global_tick
|
||||
held = (g - 1) // CONTROL_TICKS if kind == 'tick' else None
|
||||
return RuntimeEvent(kind, self.evaluation_trial_index, s.command_clock, s.protocol_command(), held,
|
||||
None if held is None else held * CONTROL_TICKS, s.reference_used_clock,
|
||||
vector_tuple(s.reference_used), s.reference_clock, vector_tuple(s.controller.action),
|
||||
tuple(causes))
|
||||
|
||||
def _evidence(self, event):
|
||||
try:
|
||||
return _causes(self.evidence_callback(event, state(self)))
|
||||
except Exception as exc:
|
||||
return (f'recording_callback:{type(exc).__name__}:{exc}',)
|
||||
|
||||
def _stop(self, causes=()):
|
||||
causes = tuple(dict.fromkeys((*causes, *(
|
||||
('illegal_reset_or_pose_write',) if self.runtime_hooks.violations else ()))))
|
||||
if self.stop_result is not None:
|
||||
combined = tuple(dict.fromkeys((*self.stop_result.causes, *causes)))
|
||||
if combined != self.stop_result.causes:
|
||||
self.stop_result = replace(self.stop_result, reason='failure', causes=combined,
|
||||
fatal=_fatal(combined))
|
||||
return self.stop_result
|
||||
s = state(self)
|
||||
h = self.runtime_hooks
|
||||
trial_index = self.evaluation_trial_index
|
||||
g = int(s.substeps[0]) if s.trial.index == trial_index else 0
|
||||
clock = (s.protocol.evidence_clock(trial_index, g) if g else
|
||||
s.protocol.next_command_clock(trial_index, 0))
|
||||
self.stop_result = StopResult('failure' if causes else 'protocol_complete', trial_index, clock,
|
||||
causes, _fatal(causes), g, g // CONTROL_TICKS, g % CONTROL_TICKS,
|
||||
g // CYCLE_TICKS, h.attempted_steps, h.completed_steps,
|
||||
h.initialization_steps, h.rollout_steps, h.reset_calls, h.pose_write_calls,
|
||||
h.composer_buffer_replacements)
|
||||
return self.stop_result
|
||||
|
||||
def reset(self, seed=None, env_ids=None, options=None):
|
||||
if self._started or self._initial_reset or env_ids is not None or options is not None:
|
||||
self.runtime_hooks.violations.append('env.reset')
|
||||
if hasattr(self, '_cycle_state'):
|
||||
self._stop(('illegal_reset_or_pose_write',))
|
||||
raise RuntimeViolation('Only one full initial reset per trial is permitted')
|
||||
trial = self.evaluation_protocol.trial(self.evaluation_trial_index)
|
||||
if seed is not None and seed != trial.seed:
|
||||
raise ValueError('Reset seed must match bound trial')
|
||||
self._initial_reset = True
|
||||
self._started = True # failed initialization is consumed, never retried
|
||||
self._consumed_rows.add(trial.index)
|
||||
try:
|
||||
with self.runtime_hooks.scope('initialization'):
|
||||
# Base reset performs reset events + forward; its provisional observation
|
||||
# is not published. Final capture/refresh follows forward before inference.
|
||||
ManagerBasedRLEnv.reset(self, seed=trial.seed)
|
||||
s = state(self)
|
||||
s.initialize_trial()
|
||||
causes = s.safety_causes()
|
||||
causes = (*causes, *self._evidence(self._event('initial', causes)))
|
||||
if causes or self.runtime_hooks.violations:
|
||||
self._stop(causes)
|
||||
return None, {'evaluation_stop': self.stop_result}
|
||||
self.obs_buf = self.observation_manager.compute(update_history=False)
|
||||
return self.obs_buf, self.extras
|
||||
except Exception as exc:
|
||||
self._stop((f'infrastructure_initialization:{type(exc).__name__}:{exc}',))
|
||||
raise
|
||||
finally:
|
||||
self._initial_reset = False
|
||||
|
||||
def _reset_idx(self, env_ids):
|
||||
if not self._initial_reset:
|
||||
self.runtime_hooks.violations.append('env._reset_idx')
|
||||
raise RuntimeViolation('No automatic or partial reset allowed')
|
||||
self.runtime_hooks.require_initialization('env._reset_idx')
|
||||
ManagerBasedRLEnv._reset_idx(self, env_ids)
|
||||
|
||||
def reset_to(self, *args, **kwargs):
|
||||
self.runtime_hooks.violations.append('env.reset_to')
|
||||
raise RuntimeViolation('Evaluation never accepts reset_to')
|
||||
|
||||
def acknowledge_finalized(self, result: StopResult):
|
||||
if result is not self.stop_result or result is None:
|
||||
raise ValueError('Acknowledge the exact stopped row after preserving evidence')
|
||||
self._finalized = True
|
||||
|
||||
def begin_trial(self, protocol: Protocol, trial_index: int):
|
||||
if (protocol is not self.evaluation_protocol or protocol.document['stage'] != 'P2'
|
||||
or self.stop_result is None or self.stop_result.fatal or not self._finalized
|
||||
or self.runtime_hooks.violations or trial_index != self.evaluation_trial_index + 1
|
||||
or trial_index in self._consumed_rows):
|
||||
raise RuntimeViolation('No active/fatal/retried/skipped/unfinalized or P1 between-row reset')
|
||||
protocol.trial(trial_index)
|
||||
self.evaluation_trial_index = trial_index
|
||||
self.stop_result = None
|
||||
self._started = self._finalized = False
|
||||
try:
|
||||
with self.runtime_hooks.scope('initialization'):
|
||||
# New row only. Never used at a continuous-cycle seam.
|
||||
self._cycle_state = EvaluationCycleState(self)
|
||||
# Restore command inputs before the physical reset refreshes IK.
|
||||
# Never called at a continuous-cycle seam; no physical pose write.
|
||||
self._cycle_state.origin.copy_(self._canonical_command_origins[0])
|
||||
self._cycle_state.base_origin.copy_(self._canonical_command_origins[1])
|
||||
self._guard_trial_objects()
|
||||
return self.reset()
|
||||
except Exception as exc:
|
||||
self._started = True
|
||||
self._consumed_rows.add(trial_index)
|
||||
self._stop((f'infrastructure_begin_trial:{type(exc).__name__}:{exc}',))
|
||||
raise
|
||||
|
||||
def step(self, action):
|
||||
if not self._started or self.stop_result is not None:
|
||||
raise RuntimeViolation('Initialize trial once; never step a stopped trial')
|
||||
if (not isinstance(action, torch.Tensor) or action.shape != (1, 3) or action.dtype != torch.float32
|
||||
or action.device != torch.device(self.device) or not torch.isfinite(action).all()):
|
||||
return StepResult(None, None, 0, self._stop(('nonfinite_or_invalid_action',)))
|
||||
s = state(self)
|
||||
if s.trial.controller_kind == 'analytic_reference' and bool(action.any()):
|
||||
return StepResult(None, None, 0, self._stop(('identity_nonzero_reference_residual',)))
|
||||
start = int(s.substeps[0])
|
||||
reward = None
|
||||
try:
|
||||
if self.runtime_hooks.violations:
|
||||
return StepResult(None, None, 0, self._stop())
|
||||
self.action_manager.process_action(action)
|
||||
for _ in range(CONTROL_TICKS):
|
||||
self._sim_step_counter += 1
|
||||
with self.runtime_hooks.wrench_update(s.robot.permanent_wrench_composer):
|
||||
self.action_manager.apply_action()
|
||||
self.scene.write_data_to_sim()
|
||||
with self.runtime_hooks.scope('rollout'):
|
||||
self.sim.step(render=False)
|
||||
self.scene.update(dt=self.physics_dt)
|
||||
s.after_physics(self.physics_dt)
|
||||
causes = s.safety_causes()
|
||||
event = self._event('tick', causes)
|
||||
causes = (*causes, *self._evidence(event))
|
||||
if causes or self.runtime_hooks.violations:
|
||||
return StepResult(None, None, int(s.substeps[0]) - start, self._stop(causes))
|
||||
# Safety/snapshot always precedes rendering or another physical step.
|
||||
if self._sim_step_counter % self.cfg.sim.render_interval == 0 and self.sim.is_rendering:
|
||||
self.sim.render(skip_app_pumping=not self.render_enabled)
|
||||
self.episode_length_buf += 1
|
||||
self.common_step_counter += 1
|
||||
reward = self.reward_manager.compute(dt=self.step_dt)
|
||||
g = int(s.substeps[0])
|
||||
if g == s.trial.total_ticks:
|
||||
return StepResult(None, reward, CONTROL_TICKS, self._stop())
|
||||
admitted = False
|
||||
if g % CYCLE_TICKS == 0:
|
||||
decision = None if self.seam_callback is None else self.seam_callback(event, s)
|
||||
if not isinstance(decision, SeamDecision) or type(decision.admitted) is not bool:
|
||||
return StepResult(None, reward, CONTROL_TICKS, self._stop(('seam_not_admitted',)))
|
||||
causes = _causes(decision.causes)
|
||||
if not decision.admitted or causes or self.runtime_hooks.violations:
|
||||
return StepResult(None, reward, CONTROL_TICKS,
|
||||
self._stop(causes or ('seam_not_admitted',)))
|
||||
admitted = True
|
||||
clock = s.protocol.next_command_clock(s.trial.index, g, seam_admitted=admitted)
|
||||
self.command_manager.compute(dt=self.step_dt)
|
||||
s.advance_reference(clock)
|
||||
# Do not re-label the old physical sample with the new seam phase.
|
||||
# Only freshly computed controller values are new evidence here.
|
||||
reference_finite = bool(torch.isfinite(s.controller.q_ik).all()
|
||||
and torch.isfinite(s.controller.action).all())
|
||||
causes = () if reference_finite else ('nonfinite_reference',)
|
||||
causes = (*causes, *self._evidence(self._event('next_reference', causes)))
|
||||
if causes or self.runtime_hooks.violations:
|
||||
return StepResult(None, reward, CONTROL_TICKS, self._stop(causes))
|
||||
self.obs_buf = self.observation_manager.compute(update_history=True)
|
||||
return StepResult(self.obs_buf, reward, CONTROL_TICKS, None)
|
||||
except Exception as exc:
|
||||
return StepResult(None, reward, int(s.substeps[0]) - start,
|
||||
self._stop((f'infrastructure_step:{type(exc).__name__}:{exc}',)))
|
||||
+421
@@ -0,0 +1,421 @@
|
||||
"""Read-only observers of the frozen schedule return and existing unique writer.
|
||||
|
||||
Install after RuntimeHooks/environment construction, before initial reset; unwind
|
||||
before RuntimeHooks. No simulator imports at module import. Identity verification
|
||||
and qualification of the mandatory backend RNG inventory precede construction.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import random
|
||||
import sys
|
||||
from contextlib import ExitStack
|
||||
from functools import wraps
|
||||
from types import MappingProxyType
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle.mechanics import rotate
|
||||
|
||||
|
||||
class InstrumentationError(RuntimeError):
|
||||
"""Incomplete, unsupported or misaligned observable evidence."""
|
||||
|
||||
|
||||
# Exact classes only: subclasses may contain unobserved recurrent/delay state.
|
||||
ACTUATOR_MODULE = 'isaaclab.actuators.actuator_pd'
|
||||
ACTUATOR_FIELDS = frozenset([
|
||||
'_num_envs', '_device', '_joint_names', '_joint_indices', 'joint_property_resolution_table',
|
||||
'velocity_limit_sim', 'effort_limit_sim', 'stiffness', 'damping', 'armature', 'friction',
|
||||
'dynamic_friction', 'viscous_friction', 'velocity_limit', 'effort_limit', 'computed_effort', 'applied_effort',
|
||||
])
|
||||
DELAY_FIELDS = frozenset(['_history_length', '_min_time_lag', '_max_time_lag', '_time_lags', '_circular_buffer'])
|
||||
CIRCULAR_FIELDS = frozenset(['_batch_size', '_device', '_ALL_INDICES', '_max_len', '_num_pushes', '_buffer'])
|
||||
DELAY_NAMES = ('positions_delay_buffer', 'velocities_delay_buffer', 'efforts_delay_buffer')
|
||||
SCHEDULE_FIELDS = ('fired', 'start', 'envelope', 'integral', 'completed')
|
||||
|
||||
|
||||
def _tensor(value):
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value
|
||||
# Pinned Warp arrays (not ProxyArray output properties that trigger composition).
|
||||
import warp as wp
|
||||
if not isinstance(value, wp.array):
|
||||
raise InstrumentationError('Unsupported backend buffer')
|
||||
return wp.to_torch(value)
|
||||
|
||||
|
||||
def _copy(value):
|
||||
"""Owned JSON-compatible values; no returned tensor shares live storage."""
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value.detach().cpu().clone().tolist()
|
||||
if isinstance(value, np.ndarray):
|
||||
return value.copy().tolist()
|
||||
if isinstance(value, np.generic):
|
||||
return value.item()
|
||||
if value is None or type(value) in (str, bool, int, float):
|
||||
return value
|
||||
if isinstance(value, slice):
|
||||
return {'slice': [_copy(value.start), _copy(value.stop), _copy(value.step)]}
|
||||
if isinstance(value, (tuple, list)):
|
||||
return [_copy(v) for v in value]
|
||||
if isinstance(value, dict) and all(type(k) is str for k in value):
|
||||
return {k: _copy(v) for k, v in value.items()}
|
||||
raise InstrumentationError(f'Unsupported snapshot value: {type(value)}')
|
||||
|
||||
|
||||
def _exact_class(obj, module, name):
|
||||
loaded = sys.modules.get(module)
|
||||
if loaded is None or type(obj) is not getattr(loaded, name, None):
|
||||
raise InstrumentationError(f'Unsupported hidden state: require exact {module}.{name}')
|
||||
|
||||
|
||||
def _fields(obj, expected, *, ignored=()):
|
||||
if set(vars(obj)) - set(ignored) != set(expected):
|
||||
raise InstrumentationError(f'Unsupported hidden state layout: {type(obj).__name__}')
|
||||
return {name: getattr(obj, name) for name in sorted(expected)}
|
||||
|
||||
|
||||
def actuator_snapshot(robot):
|
||||
"""Pinned observable Lab actuator memory, including full unrolled delay storage.
|
||||
|
||||
Implicit means no recurrent Python controller memory, NOT no PhysX solver
|
||||
state. Solver internals are not represented as an empty actuator dictionary.
|
||||
"""
|
||||
if getattr(robot, '_has_newton_actuators', False) or getattr(robot, 'newton_actuator_adapter', None) is not None:
|
||||
raise InstrumentationError('Unsupported hidden Newton actuator state')
|
||||
if not robot.actuators:
|
||||
raise InstrumentationError('No bound actuator inventory')
|
||||
groups = {}
|
||||
for name, actuator in robot.actuators.items():
|
||||
kind = type(actuator).__name__
|
||||
if kind not in ('ImplicitActuator', 'IdealPDActuator', 'DelayedPDActuator'):
|
||||
raise InstrumentationError('Unsupported hidden actuator state: ' + kind)
|
||||
_exact_class(actuator, ACTUATOR_MODULE, kind)
|
||||
delayed = kind == 'DelayedPDActuator'
|
||||
fields = ACTUATOR_FIELDS | (set(DELAY_NAMES) | {'_ALL_INDICES'} if delayed else set())
|
||||
data = _fields(actuator, fields, ignored=('cfg', 'reset'))
|
||||
for key in DELAY_NAMES if delayed else ():
|
||||
delay = data[key]
|
||||
_exact_class(delay, 'isaaclab.utils.buffers.delay_buffer', 'DelayBuffer')
|
||||
delay_data = _fields(delay, DELAY_FIELDS)
|
||||
circular = delay_data['_circular_buffer']
|
||||
_exact_class(circular, 'isaaclab.utils.buffers.circular_buffer', 'CircularBuffer')
|
||||
delay_data['_circular_buffer'] = _fields(circular, CIRCULAR_FIELDS)
|
||||
data[key] = delay_data
|
||||
groups[name] = {'class': ACTUATOR_MODULE + '.' + kind,
|
||||
'memory': 'delayed' if delayed else 'stateless_controller',
|
||||
'implicit_solver': kind == 'ImplicitActuator', 'buffers': _copy(data)}
|
||||
targets = {key: _copy(_tensor(getattr(robot, key))) for key in
|
||||
('_joint_pos_target_sim', '_joint_vel_target_sim', '_joint_effort_target_sim')}
|
||||
targets.update({key: _copy(getattr(robot.data, key).torch) for key in
|
||||
('joint_pos_target', 'joint_vel_target', 'joint_effort_target')})
|
||||
return {'groups': groups, 'targets': targets}
|
||||
|
||||
|
||||
def qualify_backend_rng(snapshot):
|
||||
"""Validate coverage structure, never certify a provider's completeness claim.
|
||||
|
||||
Sources/evidence and the bounded scope must be independently bound/reviewed.
|
||||
Native internals are explicitly unobserved, never constant pseudo-state.
|
||||
"""
|
||||
snapshot = _copy(snapshot)
|
||||
if (not isinstance(snapshot, dict)
|
||||
or set(snapshot) != {'coverage', 'evidence_scope', 'unobserved_internals'}
|
||||
or not isinstance(snapshot['coverage'], dict) or not snapshot['coverage']):
|
||||
raise InstrumentationError('Explicit backend RNG coverage required')
|
||||
scope = snapshot['evidence_scope']
|
||||
if (not isinstance(scope, dict) or set(scope) != {'format', 'equality', 'sources', 'claims'}
|
||||
or scope['format'] != 'skillfactory.observable-state-scope.v1'
|
||||
or scope['equality'] != 'recorded_application_controller_and_enumerated_observable_rng_only'
|
||||
or not isinstance(scope['claims'], dict)
|
||||
or set(scope['claims']) != {'complete_backend_state_equality', 'deterministic_replay'}
|
||||
or any(value is not False for value in scope['claims'].values())
|
||||
or not isinstance(scope['sources'], list) or not scope['sources']
|
||||
or any(type(p) is not str or not p for p in scope['sources'])):
|
||||
raise InstrumentationError('Bound/versioned observable evidence scope required')
|
||||
internals = snapshot['unobserved_internals']
|
||||
if (not isinstance(internals, dict) or set(internals) != {
|
||||
'physx_solver_contact_caches', 'internal_stochastic_state_if_any', 'numerical_scheduling_effects'}
|
||||
or any(value != 'unobserved' for value in internals.values())):
|
||||
raise InstrumentationError('Native internals must be explicitly unobserved')
|
||||
for name, entry in snapshot['coverage'].items():
|
||||
if (not name or not isinstance(entry, dict)
|
||||
or set(entry) != {'status', 'sources', 'evidence', 'state'}
|
||||
or not isinstance(entry['sources'], list) or not entry['sources']
|
||||
or any(type(p) is not str or not p for p in entry['sources'])
|
||||
or type(entry['evidence']) is not str or not entry['evidence']):
|
||||
raise InstrumentationError('Invalid backend RNG source coverage')
|
||||
if entry['status'] == 'observed':
|
||||
if entry['state'] is None or entry['state'] == {} or entry['state'] == []:
|
||||
raise InstrumentationError('Missing observable backend RNG state')
|
||||
elif entry['status'] == 'not_applicable':
|
||||
if entry['state'] is not None:
|
||||
raise InstrumentationError('Not-applicable RNG must not invent state')
|
||||
else:
|
||||
raise InstrumentationError('Unavailable/unqualified backend RNG coverage: ' + name)
|
||||
return snapshot
|
||||
|
||||
|
||||
def rng_snapshot(state, backend_rng, generators):
|
||||
extra = {}
|
||||
for name, generator in generators.items():
|
||||
if type(generator) is random.Random:
|
||||
value = generator.getstate()
|
||||
elif type(generator) is np.random.Generator:
|
||||
value = generator.bit_generator.state
|
||||
elif type(generator) is np.random.RandomState or type(generator) is torch.Generator:
|
||||
value = generator.get_state()
|
||||
else:
|
||||
raise InstrumentationError('Unsupported RNG generator: ' + name)
|
||||
extra[name] = _copy(value)
|
||||
return {'python': _copy(random.getstate()), 'numpy': _copy(np.random.get_state()),
|
||||
'generators': extra, 'backend': qualify_backend_rng(backend_rng(state))}
|
||||
|
||||
|
||||
class EvaluationInstrumentation:
|
||||
"""One environment, one context; supplemental(state) matches recorder schema.
|
||||
|
||||
Repeated reads retain the *same completed interval*, including next_reference
|
||||
and seam fingerprints. Only runtime tick records integrate delivery. A new
|
||||
P2 state is attached at its initial supplemental call (before inference).
|
||||
"""
|
||||
def __init__(self, env, *, backend_rng, generators):
|
||||
if not callable(backend_rng) or not isinstance(generators, dict) or any(
|
||||
type(k) is not str or not k for k in generators):
|
||||
raise InstrumentationError('Explicit backend RNG provider and named generator inventory required')
|
||||
self.env, self.backend_rng = env, backend_rng
|
||||
self.generators = dict(generators)
|
||||
self._stack = self._schedule_stack = None
|
||||
self._state = self._pending = self._capture = self._schedule_state = None
|
||||
self._last_tick = 0
|
||||
self._fault = False
|
||||
|
||||
@staticmethod
|
||||
def _patch(stack, obj, name, wrapper):
|
||||
own, old = name in vars(obj), getattr(obj, name)
|
||||
setattr(obj, name, wrapper)
|
||||
stack.callback(lambda: setattr(obj, name, old) if own else delattr(obj, name))
|
||||
|
||||
def __enter__(self):
|
||||
h = self.env.runtime_hooks
|
||||
if self._stack is not None or not h.active or h.mode != 'locked':
|
||||
raise InstrumentationError('Install inside active RuntimeHooks after construction')
|
||||
self._stack = ExitStack()
|
||||
try:
|
||||
s = self.env._cycle_state
|
||||
self._composer = s.robot.permanent_wrench_composer
|
||||
if (id(self._composer), 'reset') not in h._guarded:
|
||||
raise InstrumentationError('Runtime composer guard must be installed first')
|
||||
old = self._composer.set_forces_and_torques_index
|
||||
if hasattr(old, '_evaluation_instrumentation_owner'):
|
||||
raise InstrumentationError('Nested unique-writer instrumentation is not supported')
|
||||
self._attach(s)
|
||||
|
||||
@wraps(old)
|
||||
def setter(*args, **kwargs):
|
||||
try:
|
||||
evidence = self._before_setter(args, kwargs)
|
||||
result = old(*args, **kwargs) # preserve guard's replacement permission scope
|
||||
self._check_buffers(kwargs)
|
||||
self._capture, self._pending = evidence, None
|
||||
self._last_tick = evidence['global_tick']
|
||||
return result
|
||||
except BaseException:
|
||||
self._fault = True
|
||||
self._capture = self._pending = None
|
||||
raise
|
||||
|
||||
setter._evaluation_instrumentation_owner = self
|
||||
self._patch(self._stack, self._composer, 'set_forces_and_torques_index', setter)
|
||||
return self
|
||||
except BaseException:
|
||||
self.__exit__(None, None, None)
|
||||
raise
|
||||
|
||||
def __exit__(self, *exc):
|
||||
try:
|
||||
if self._schedule_stack is not None:
|
||||
self._schedule_stack.close()
|
||||
finally:
|
||||
if self._stack is not None:
|
||||
self._stack.close()
|
||||
self._stack = self._schedule_stack = None
|
||||
self._pending = self._capture = None
|
||||
|
||||
def _attach(self, s):
|
||||
if int(s.substeps[0]) != 0 or s.robot.permanent_wrench_composer is not self._composer:
|
||||
raise InstrumentationError('Attach only new initial state on the bound composer')
|
||||
if self._pending is not None or (self._state is not None and s.trial.index != self._state.trial.index + 1):
|
||||
raise InstrumentationError('Invalid P2 state transition')
|
||||
if self._schedule_stack is not None:
|
||||
self._schedule_stack.close()
|
||||
self._state, self._capture, self._schedule_state = s, None, None
|
||||
self._last_tick = 0
|
||||
self._schedule_stack = ExitStack()
|
||||
old = s.schedule.step
|
||||
|
||||
@wraps(old)
|
||||
def scheduled(*args, **kwargs):
|
||||
try:
|
||||
tick = int(s.substeps[0]) + 1
|
||||
if (self._fault or s is not self.env._cycle_state or self._pending is not None
|
||||
or tick != self._last_tick + 1
|
||||
or self.env.runtime_hooks._load_owner is not self._composer):
|
||||
raise InstrumentationError('Unexpected/duplicate schedule invocation')
|
||||
if s.schedule.commands is not None or s.schedule.delays is not None or s.sampled_points is not None:
|
||||
raise InstrumentationError('Unbound schedule overrides')
|
||||
values = old(*args, **kwargs) # the ONLY scheduler invocation
|
||||
self._pending = (tick, values.detach().clone(), self._poses(s))
|
||||
self._schedule_state = {k: _copy(getattr(s.schedule, k)) for k in SCHEDULE_FIELDS}
|
||||
return values
|
||||
except BaseException:
|
||||
self._fault = True
|
||||
self._pending = self._capture = None
|
||||
raise
|
||||
|
||||
self._patch(self._schedule_stack, s.schedule, 'step', scheduled)
|
||||
|
||||
@staticmethod
|
||||
def _poses(s):
|
||||
d = s.robot.data
|
||||
return tuple(t.detach().clone() for t in (d.body_link_pos_w.torch,
|
||||
d.body_link_quat_w.torch, d.body_com_pos_w.torch, s.env.scene.env_origins))
|
||||
|
||||
def _before_setter(self, args, kw):
|
||||
s = self._state
|
||||
if (self._fault or self._pending is None or s is not self.env._cycle_state
|
||||
or self.env.runtime_hooks._load_owner is not self._composer):
|
||||
raise InstrumentationError('Missing matching schedule result')
|
||||
tick, values, poses = self._pending
|
||||
if tick != int(s.substeps[0]) + 1 or any(not torch.equal(a, b) for a, b in zip(poses, self._poses(s))):
|
||||
raise InstrumentationError('Pre-step pose/tick changed between schedule and setter')
|
||||
if (args or set(kw) != {'forces', 'torques', 'body_ids', 'positions', 'is_global'}
|
||||
or kw['positions'] is not None or kw['is_global'] is not True
|
||||
or _copy(kw['body_ids']) != list(range(len(s.robot.body_names)))):
|
||||
raise InstrumentationError('Require exact frozen all-body world COM setter')
|
||||
total = torch.cat((kw['forces'], kw['torques']), -1).detach().clone()
|
||||
if total.shape != s.external.shape or not torch.equal(total, s.external + s.guide + s.auxiliary):
|
||||
raise InstrumentationError('Actual setter arguments differ from composed buffers')
|
||||
bpos, bquat, com, origin = poses
|
||||
identity = bquat.new_tensor([[0., 0., 0., 1.]])
|
||||
external = torch.zeros_like(total)
|
||||
events = []
|
||||
selected = tuple(i for i, e in enumerate(s.cc['events']) if e['scenario'] == s.trial.scenario_id)
|
||||
if selected != s.trial.event_indices or int(s.scenarios[0]) != s.trial.scenario_id:
|
||||
raise InstrumentationError('Event/trial identity mismatch')
|
||||
for j, e in enumerate(s.cc['events']):
|
||||
body = s.robot.body_names.index(e['body'])
|
||||
frames = {'world': (origin, identity), 'mount': (bpos[:, s.anchor], bquat[:, s.anchor]),
|
||||
'body': (bpos[:, body], bquat[:, body])}
|
||||
point_origin, point_quat = frames[e['point_frame']]
|
||||
quat = frames[e['frame']][1]
|
||||
point = point_origin + rotate(point_quat, values.new_tensor([e['point_m']]))
|
||||
force, couple = rotate(quat, values[:, j, :3]), rotate(quat, values[:, j, 3:])
|
||||
external[:, body] += torch.cat((force, couple + torch.cross(point - com[:, body], force, dim=-1)), -1)
|
||||
if j in selected:
|
||||
events.append({'event_index': j, 'body_index': body,
|
||||
'envelope': self._schedule_state['envelope'][0][j],
|
||||
**{k: _copy(v[0]) for k, v in {
|
||||
'force_world': force, 'couple_world': couple, 'point_world': point,
|
||||
'com_world': com[:, body], 'frame_quat_xyzw': quat,
|
||||
'point_frame_quat_xyzw': point_quat,
|
||||
'point_frame_origin_world': point_origin}.items()}})
|
||||
elif bool(values[:, j].any()):
|
||||
raise InstrumentationError('Unselected event produced a wrench')
|
||||
if not torch.equal(external, s.external):
|
||||
raise InstrumentationError('Observed schedule/frames disagree with external COM buffer')
|
||||
return {'format': 'skillfactory.contact-cycle-applied-wrench.v1', 'trial_index': s.trial.index,
|
||||
'global_tick': tick, 'events': events, 'total_com_wrench': _copy(total[0])}
|
||||
|
||||
def _check_buffers(self, kw):
|
||||
# Do not read out_force_b/out_torque_b: their accessors mutate dirty composition.
|
||||
c = self._composer
|
||||
for name, expected in (('global_force_at_com_w', kw['forces']), ('global_torque_w', kw['torques'])):
|
||||
if not torch.equal(_tensor(getattr(c, name)), expected):
|
||||
raise InstrumentationError('Composer input buffer differs from actual submission: ' + name)
|
||||
for name in ('global_force_w', 'local_force_b', 'local_torque_b'):
|
||||
if bool(_tensor(getattr(c, name)).any()):
|
||||
raise InstrumentationError('Unexpected positional/global or local composer contribution')
|
||||
|
||||
def supplemental(self, s):
|
||||
if self._stack is None or self._fault or s is not self.env._cycle_state:
|
||||
raise InstrumentationError('Inactive/faulted instrumentation or foreign state')
|
||||
if s is not self._state:
|
||||
self._attach(s) # begin_trial replaces state; first callback is initial at tick zero
|
||||
tick = int(s.substeps[0])
|
||||
if self._pending is not None:
|
||||
raise InstrumentationError('Schedule result without completed unique setter')
|
||||
if tick == 0:
|
||||
if self._capture is not None:
|
||||
raise InstrumentationError('Future application at initial snapshot')
|
||||
applied = None
|
||||
else:
|
||||
if (self._capture is None
|
||||
or (self._capture['trial_index'], self._capture['global_tick']) != (s.trial.index, tick)):
|
||||
raise InstrumentationError('Missing/stale/future applied evidence')
|
||||
if self._schedule_state != {k: _copy(getattr(s.schedule, k)) for k in SCHEDULE_FIELDS}:
|
||||
raise InstrumentationError('Scheduler changed after pre-step capture')
|
||||
applied = copy.deepcopy(self._capture) if s.trial.event_indices else None
|
||||
actuators = actuator_snapshot(s.robot)
|
||||
# Frozen project delay lines are separate from backend actuator delays.
|
||||
from SkillFactory.legs.contact_cycle.task import DelayLine
|
||||
for name in ('sensor_delay', 'action_delay'):
|
||||
line = getattr(s, name)
|
||||
if type(line) is not DelayLine:
|
||||
raise InstrumentationError('Unsupported project delay history')
|
||||
actuators[name] = _copy(_fields(line, {'delay', 'data'}, ignored=('reset',)))
|
||||
return {'actuator_state': actuators, 'rng': rng_snapshot(s, self.backend_rng, self.generators),
|
||||
'applied': applied}
|
||||
|
||||
|
||||
# Bind these actual imported modules (not merely matching bytes in another tree).
|
||||
BACKEND_SOURCE_INVENTORY = MappingProxyType({
|
||||
'isaaclab_physx.assets.articulation.articulation': (
|
||||
'/home/cen/IsaacLab/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation.py',
|
||||
'47d96553282b389493e69f691b8dcbfeb98997a5a80b88c2571c60ba8b58cb6d'),
|
||||
'isaaclab_physx.assets.articulation.articulation_data': (
|
||||
'/home/cen/IsaacLab/source/isaaclab_physx/isaaclab_physx/assets/articulation/articulation_data.py',
|
||||
'43a31992353ad3a500024d0ec908d5b253ada7a0aac9a1cd2261466e10bda4ff'),
|
||||
'isaaclab.actuators.actuator_base': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_base.py',
|
||||
'de715f048558dfeb9917ec48d7a110e6942eef6f242e9bab379281e8398beedb'),
|
||||
'isaaclab.actuators.actuator_pd': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd.py',
|
||||
'105f0341f972102f6bd5b0c544bc7c0510662241389a9decd24406bb2371d27e'),
|
||||
'isaaclab.utils.buffers.delay_buffer': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/utils/buffers/delay_buffer.py',
|
||||
'648ce0cf011798a1ab4a8980bafbbeba16ef8cf02affbc404c67ff312ac02da2'),
|
||||
'isaaclab.utils.buffers.circular_buffer': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/utils/buffers/circular_buffer.py',
|
||||
'f1443d6eaa8b7bbfcfea6d70249143b9bf5a3deda16a2b2cfa00ea01a5af4155'),
|
||||
'isaaclab.utils.wrench_composer': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/utils/wrench_composer.py',
|
||||
'8fb3ab4e59db121165db52daf61e0de0e73653f0c154a143f6a828c198082c06'),
|
||||
'isaaclab.utils.warp.kernels': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/utils/warp/kernels.py',
|
||||
'9991d03fe46fa964b7e9531d5fba8e1b44a0701926d3c900f1e1ac3cf84ad906'),
|
||||
'isaaclab.utils.warp.utils': (
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/utils/warp/utils.py',
|
||||
'dfffeb6d683061a0e169e4e28f6f05137d6b2dfdeb8953b0878b6dc1b45705de'),
|
||||
})
|
||||
|
||||
|
||||
def verify_backend_sources():
|
||||
"""Read-only imported-source precheck; NOT a replacement for verify_binding.
|
||||
|
||||
Eagerly import these dependencies in the authorized runtime setup first. The
|
||||
binding owner also inventories Torch/numpy/Warp and the backend RNG provider,
|
||||
plus its explicitly declared state sources, before environment construction.
|
||||
"""
|
||||
from hashlib import sha256
|
||||
from pathlib import Path
|
||||
|
||||
for name, (path, digest) in BACKEND_SOURCE_INVENTORY.items():
|
||||
module = sys.modules.get(name)
|
||||
file = getattr(module, '__file__', None)
|
||||
spec = getattr(module, '__spec__', None)
|
||||
if (file != path or getattr(spec, 'origin', None) != path
|
||||
or str(Path(path).resolve()) != path or sha256(Path(path).read_bytes()).hexdigest() != digest):
|
||||
raise InstrumentationError('Actual imported backend identity mismatch: ' + name)
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
"""Protocol commands with frozen observation, residual, IK and wrench math.
|
||||
|
||||
No refresh in after_physics: the environment admits the endpoint before advancing
|
||||
command metadata and refreshing the carried controller exactly once.
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle.task import FAILURE_NAMES
|
||||
from SkillFactory.legs.contact_cycle_sim.evaluation_protocol import CONTROL_TICKS, PHYSICS_DT_S, Protocol
|
||||
from SkillFactory.tasks.manager_based.contact_cycle import mdp as base
|
||||
from SkillFactory.tasks.manager_based.single_leg_anchor.mdp.actions import BoundedJointPositionAction
|
||||
|
||||
from .mdp import SimCycleState, SimResidualAction
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CapturedAnchors:
|
||||
anchor_a_world: tuple[float, float, float]
|
||||
root_origin_world: tuple[float, float, float]
|
||||
initial_root_world: tuple[float, float, float]
|
||||
|
||||
|
||||
def vector_tuple(value):
|
||||
return tuple(value.detach().cpu().reshape(-1).tolist())
|
||||
|
||||
|
||||
class EvaluationCycleState(SimCycleState):
|
||||
def __init__(self, env):
|
||||
self.protocol: Protocol = env.evaluation_protocol
|
||||
self.trial = self.protocol.trial(env.evaluation_trial_index)
|
||||
self.command_clock = self.protocol.next_command_clock(self.trial.index, 0)
|
||||
self.reference_clock = self.command_clock
|
||||
self.reference_used_clock = None
|
||||
self._anchors = None
|
||||
super().__init__(env)
|
||||
self._install_descriptor()
|
||||
|
||||
@property
|
||||
def anchors(self):
|
||||
return self._anchors
|
||||
|
||||
def _install_descriptor(self):
|
||||
# Select existing events, never introduce a second force writer or sampler.
|
||||
expected = self.protocol.document['events']
|
||||
actual = self.cc['events']
|
||||
if expected and tuple(actual) != tuple(dict(e) for e in expected):
|
||||
# JSON lists versus immutable protocol tuples are normalized explicitly.
|
||||
for a, b in zip(actual, expected, strict=True):
|
||||
if a.keys() != b.keys() or any(
|
||||
(tuple(a[k]) if isinstance(a[k], list) else a[k]) != b[k] for k in a
|
||||
):
|
||||
raise ValueError('Bound event program differs from frozen wrench schedule')
|
||||
indices = tuple(i for i, e in enumerate(actual) if e['scenario'] == self.trial.scenario_id)
|
||||
if indices != self.trial.event_indices:
|
||||
raise ValueError('Bound scenario/event indices mismatch')
|
||||
self.scenarios.fill_(self.trial.scenario_id)
|
||||
self.stand_only.zero_()
|
||||
if self.sampler is not None or self.schedule.commands is not None or self.schedule.delays is not None:
|
||||
raise ValueError('Evaluation disallows sampler/event overrides')
|
||||
|
||||
def reset(self, ids):
|
||||
self.env.runtime_hooks.require_initialization('state.reset')
|
||||
super().reset(ids)
|
||||
self._install_descriptor() # inherited nominal reset must not win
|
||||
|
||||
def set_sampler(self, sampler):
|
||||
raise RuntimeError('Evaluation descriptor is immutable; no sampler installation')
|
||||
|
||||
def initialize_trial(self):
|
||||
"""Called after the single physical reset/forward, before public inference."""
|
||||
if self._anchors is not None:
|
||||
raise RuntimeError('Anchors already captured')
|
||||
# Frozen CycleState retains the constructor's ground target across reset.
|
||||
# The forwarded measured foot is sensor evidence, not a new command anchor.
|
||||
a = self.origin[0].clone()
|
||||
self._anchors = CapturedAnchors(vector_tuple(a), vector_tuple(self.base_origin[0]),
|
||||
vector_tuple(self.root()[0][0]))
|
||||
ids = torch.arange(self.env.num_envs, device=self.env.device)
|
||||
# Refresh reset sensor histories from the forwarded initial pose.
|
||||
self.reset(ids)
|
||||
self.reference_clock = self.command_clock
|
||||
|
||||
def protocol_command(self):
|
||||
anchors = self.anchors
|
||||
return self.protocol.command(
|
||||
self.trial.index, self.command_clock,
|
||||
anchor_a_world=vector_tuple(self.origin[0]) if anchors is None else anchors.anchor_a_world,
|
||||
root_origin_world=vector_tuple(self.base_origin[0]) if anchors is None else anchors.root_origin_world,
|
||||
weight_N=float(self.weight[0]))
|
||||
|
||||
def reference(self):
|
||||
c = self.protocol_command()
|
||||
return (torch.tensor([c.phase], device=self.env.device, dtype=torch.long),
|
||||
self.time.new_tensor([c.progress]), self.time.new_tensor([c.target_world_m]),
|
||||
self.time.new_tensor([c.desired_normal_N]), self.time.new_tensor([c.auxiliary_fraction]))
|
||||
|
||||
def port_reference(self):
|
||||
c = self.protocol_command()
|
||||
return (self.time.new_tensor([c.root_target_world_m]),
|
||||
self.time.new_tensor([c.root_velocity_world_m_s]))
|
||||
|
||||
def after_physics(self, dt):
|
||||
if dt != PHYSICS_DT_S:
|
||||
raise ValueError('Evaluation requires individual 0.002s physics ticks')
|
||||
tick = int(self.substeps[0]) + 1
|
||||
self.command_clock = self.protocol.evidence_clock(self.trial.index, tick)
|
||||
# Deliberately bypass SimCycleState.after_physics's automatic IK refresh.
|
||||
base.CycleState.after_physics(self, dt)
|
||||
|
||||
def advance_reference(self, clock):
|
||||
if clock.global_tick % CONTROL_TICKS:
|
||||
raise ValueError('Reference refresh requires control boundary')
|
||||
self.command_clock = clock
|
||||
self.controller.refresh(torch.arange(self.env.num_envs, device=self.env.device))
|
||||
self.reference_clock = clock
|
||||
|
||||
def safety_causes(self):
|
||||
"""Instantaneous floors only; window/dwell/delivery gates belong to callback owner."""
|
||||
flags = base.failure_flags(self.env)[0].tolist()
|
||||
causes = [name for name, hit in zip(FAILURE_NAMES, flags) if hit]
|
||||
f = self.protocol.document['thresholds']['functional']
|
||||
d = self.robot.data
|
||||
lower = self.time.new_tensor([j['limits']['lower'] for j in self.bundle['joints']])
|
||||
upper = self.time.new_tensor([j['limits']['upper'] for j in self.bundle['joints']])
|
||||
speed = self.time.new_tensor([j['limits']['velocity'] for j in self.bundle['joints']])
|
||||
torque, velocity = d.applied_torque.torch[:, self.joints], d.joint_vel.torch[:, self.joints]
|
||||
root = self.root()[0]
|
||||
foot = self.foot_center()
|
||||
gap = foot[:, 2] - self.bundle['foot']['radius']
|
||||
error = root - self.port_reference()[0]
|
||||
auxiliary_vertical = self.auxiliary[..., 2]
|
||||
auxiliary_moment = self.auxiliary[..., 3:].norm(dim=-1)
|
||||
finite = torch.cat((d.root_state_w.torch.flatten(), self.q().flatten(), velocity.flatten(),
|
||||
torque.flatten(), self.external.flatten(), self.guide.flatten(),
|
||||
self.auxiliary.flatten(), self.sensed.flatten(), foot.flatten(),
|
||||
self.controller.q_ik.flatten(), self.controller.action.flatten()))
|
||||
checks = {
|
||||
'nonfinite': not bool(torch.isfinite(finite).all()),
|
||||
'hardware_effort_velocity': bool(torch.maximum((torque / self.effort).abs().amax(),
|
||||
(velocity / speed).abs().amax())
|
||||
> f['normalized_effort_velocity_max']),
|
||||
'hardware_joint_limit': bool(torch.maximum(lower - self.q(), self.q() - upper).amax()
|
||||
> f['joint_limit_excess_rad_max']),
|
||||
'guide_vertical': bool(self.guide[..., 2].abs().amax() != 0),
|
||||
'root_height_error': bool(error[:, 2].abs().amax() > f['root_height_error_m_max']),
|
||||
'ground_penetration': bool(gap.min() < -f['ground_penetration_m_max']),
|
||||
'negative_normal': bool(self.contact()[:, 2].min() < -f['normal_force_negative_tolerance_N']),
|
||||
'auxiliary_force': bool(auxiliary_vertical.sum(-1).amax() > f['auxiliary_vertical_N_max']),
|
||||
# Preserve the original functional auditor's point-applied fixture checks/tolerance.
|
||||
'auxiliary_geometry': bool(
|
||||
(auxiliary_moment > f['auxiliary_lever_arm_m_max'] * auxiliary_vertical.clamp_min(0) + 1e-6).any()
|
||||
or self.auxiliary[..., :2].abs().amax() > 1e-6
|
||||
or auxiliary_vertical.amin() < -1e-6 or self.auxiliary[..., 5].abs().amax() > 1e-6),
|
||||
'auxiliary_support_phase': bool(self.protocol_command().phase == 0
|
||||
and self.auxiliary.abs().amax() > 1e-6),
|
||||
}
|
||||
if self.protocol.document['stage'] == 'P1':
|
||||
m = self.protocol.document['thresholds']['P1_margins']
|
||||
checks['P1_root_horizontal'] = bool(error[:, :2].norm(dim=-1).amax() > m['root_horizontal_error_m_max'])
|
||||
checks['P1_root_z'] = bool(error[:, 2].abs().amax() > m['root_absolute_z_error_m_max'])
|
||||
local = self.command_clock.local_tick
|
||||
if local >= 4400:
|
||||
checks['P1_reload_position'] = bool((foot - self.reference()[2]).norm(dim=-1).amax()
|
||||
> m['reload_instantaneous_3d_error_m_max'])
|
||||
if local == 4500:
|
||||
initial = root.new_tensor(self.anchors.initial_root_world)
|
||||
checks['P1_seam_root_drift'] = bool((root - initial)[:, :2].norm(dim=-1).amax()
|
||||
> m['seam_to_initial_root_horizontal_drift_m_max'])
|
||||
return tuple(dict.fromkeys(causes + [name for name, hit in checks.items() if hit]))
|
||||
|
||||
|
||||
def state(env):
|
||||
if not hasattr(env, '_cycle_state'):
|
||||
env._cycle_state = EvaluationCycleState(env)
|
||||
if not isinstance(env._cycle_state, EvaluationCycleState):
|
||||
raise RuntimeError('Wrong evaluation state contract')
|
||||
return env._cycle_state
|
||||
|
||||
|
||||
class EvaluationResidualAction(SimResidualAction):
|
||||
def __init__(self, cfg, env):
|
||||
# Install the new state before any frozen lazy-state helper can run.
|
||||
BoundedJointPositionAction.__init__(self, cfg, env)
|
||||
state(env)
|
||||
|
||||
def process_actions(self, actions):
|
||||
super().process_actions(actions)
|
||||
s = state(self._env)
|
||||
s.reference_used_clock = s.reference_clock
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
"""Read-only synchronous evidence callbacks. No reset/refresh/scene-update wrappers.
|
||||
|
||||
The future runner supplies actor records, resource checks, stop results and bound
|
||||
actuator/RNG snapshots. No default unlimited disk/time budget is provided.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import lzma
|
||||
import math
|
||||
import os
|
||||
from dataclasses import asdict
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle.mechanics import inverse_rotate
|
||||
from SkillFactory.legs.contact_cycle_sim.config import pose_cost
|
||||
from SkillFactory.legs.contact_cycle_sim.evaluation_audit import (
|
||||
MAX_CHUNK_RAW_BYTES,
|
||||
MAX_CHUNK_RECORDS,
|
||||
MAX_RECORD_BYTES,
|
||||
TRACE_ENCODING,
|
||||
TRACE_FILENAME,
|
||||
XZ_PRESET,
|
||||
TrialAudit,
|
||||
plain,
|
||||
)
|
||||
|
||||
|
||||
def copied(value):
|
||||
"""Synchronously detach/copy tensors before callback return (no live aliases)."""
|
||||
if value is None or type(value) in (str, bool, int, float):
|
||||
return value
|
||||
if isinstance(value, torch.Tensor):
|
||||
return value.detach().cpu().clone().tolist()
|
||||
if isinstance(value, dict):
|
||||
return {k: copied(v) for k, v in value.items()}
|
||||
if isinstance(value, (tuple, list)):
|
||||
return [copied(v) for v in value]
|
||||
return plain(value)
|
||||
|
||||
|
||||
def _json_safe(value):
|
||||
# Preserve offending nonfinite values explicitly; never emit invalid JSON or turn them into zeros.
|
||||
if isinstance(value, float) and not math.isfinite(value):
|
||||
return {'nonfinite': repr(value)}
|
||||
if isinstance(value, dict):
|
||||
return {k: _json_safe(v) for k, v in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [_json_safe(v) for v in value]
|
||||
return value
|
||||
|
||||
|
||||
def _row(value):
|
||||
return copied(value[0])
|
||||
|
||||
|
||||
def snapshot(s, supplemental):
|
||||
"""Copy existing state only. supplemental is a required read-only owner callback.
|
||||
|
||||
It supplies {actuator_state: dict, rng: dict, applied: AppliedEvidence | None};
|
||||
applied MUST come from pre-physics unique-writer observation, never post-step
|
||||
reconstruction (see evaluation_audit.AppliedEvidence). Actuator internals and non-Torch
|
||||
RNGs are backend-dependent and must be separately bound by the runner. Empty
|
||||
actuator dict explicitly means no hidden actuator memory (requires binding).
|
||||
"""
|
||||
d, env = s.robot.data, s.env
|
||||
root = s.root()
|
||||
q, vel, torque = s.q(), d.joint_vel.torch[:, s.joints], d.applied_torque.torch[:, s.joints]
|
||||
lower = q.new_tensor([j['limits']['lower'] for j in s.bundle['joints']])
|
||||
upper = q.new_tensor([j['limits']['upper'] for j in s.bundle['joints']])
|
||||
speed = q.new_tensor([j['limits']['velocity'] for j in s.bundle['joints']])
|
||||
foot, contact = s.foot_center(), s.contact()
|
||||
target = s.reference()[2]
|
||||
events = []
|
||||
for j, event in enumerate(s.cc['events']):
|
||||
events.append({'fired': bool(s.schedule.fired[0, j]), 'completed': bool(s.schedule.completed[0, j]),
|
||||
'start': float(s.schedule.start[0, j]), 'envelope': float(s.schedule.envelope[0, j]),
|
||||
'integral': float(s.schedule.integral[0, j])})
|
||||
h = env.runtime_hooks
|
||||
root_position, root_velocity = pose_cost(*s.errors(), s.residual_cfg['reward'])
|
||||
extra = copied(supplemental(s))
|
||||
if set(extra) != {'actuator_state', 'rng', 'applied'}:
|
||||
raise ValueError('Supplemental evidence requires actuator_state, rng and applied only')
|
||||
# torch RNGs are copied in addition to owner-supplied Python/numpy/backend RNG state.
|
||||
extra['rng']['torch_cpu'] = copied(torch.get_rng_state())
|
||||
if q.is_cuda:
|
||||
extra['rng']['torch_cuda'] = copied(torch.cuda.get_rng_state(q.device))
|
||||
result = {
|
||||
'time': float(s.time[0]), 'substeps': int(s.substeps[0]), 'scenario': int(s.scenarios[0]),
|
||||
'weight': float(s.weight[0]), 'anchor_height': float(env.cfg.anchor_height),
|
||||
'anchors': plain(asdict(s.anchors)), 'env_origin': _row(env.scene.env_origins),
|
||||
'body_names': list(s.robot.body_names), 'event_program': plain(s.cc['events']),
|
||||
'foot': _row(foot), 'normal': _row(contact), 'friction': _row(s.friction()),
|
||||
'gap': float(foot[0, 2] - s.bundle['foot']['radius']), 'tilt': float(s.tilt()[0]),
|
||||
'slip_speed': float(s.slip_velocity()[0]), 'root': _row(torch.cat(root, -1)),
|
||||
'q': _row(q), 'qdot': _row(vel), 'torque': _row(torque),
|
||||
'limit_ratio': float(torch.maximum((torque / s.effort).abs().max(), (vel / speed).abs().max())),
|
||||
'joint_excess': float(torch.maximum(lower - q, q - upper).clamp_min(0).max()),
|
||||
'external': _row(s.external), 'guide': _row(s.guide), 'auxiliary': _row(s.auxiliary),
|
||||
'processed_target': _row(env.action_manager.get_term('joint_position').processed_actions),
|
||||
'executed': _row(s.executed), 'residual_request': _row(s.residual_request),
|
||||
'effective_residual_rad': _row(s.effective_residual_rad), 'sensed': _row(s.sensed),
|
||||
'policy': _row(s.policy()), 'manager_action': _row(env.action_manager.action),
|
||||
'manager_previous_action': _row(env.action_manager.prev_action),
|
||||
'ik_target': _row(inverse_rotate(root[1], target - root[0])),
|
||||
'q_ik': _row(s.controller.q_ik), 'reference_action': _row(s.controller.action),
|
||||
'refreshes': int(s.controller.refreshes[0]),
|
||||
'sensor_delay': copied(s.sensor_delay.data[:, 0]), 'action_delay': copied(s.action_delay.data[:, 0]),
|
||||
'contact': bool(s.latch.contact[0]), 'contact_timer': float(s.latch.timer[0]),
|
||||
'separated': bool(s.separation.separated[0]), 'premature': bool(s.separation.premature[0]),
|
||||
'armed': bool(s.separation.armed[0]), 'separation_timer': float(s.separation.timer[0]),
|
||||
'onset_phase': int(s.separation.onset_phase[0]), 'edge_phase': int(s.separation.edge_phase[0]),
|
||||
'acquired': bool(s.acquisition.acquired[0]), 'acquisition_failed': bool(s.acquisition.failed[0]),
|
||||
'acquisition_timer': float(s.acquisition.timer[0]), 'load_off': bool(s.load_off[0]),
|
||||
'liftoff': bool(s.edge_off[0]), 'touchdown': bool(s.edge_on[0]), 'events': events,
|
||||
'counters': {k: getattr(h, k) for k in ('reset_calls', 'pose_write_calls', 'composer_buffer_replacements',
|
||||
'initialization_steps', 'rollout_steps', 'attempted_steps', 'completed_steps')},
|
||||
'reward_components': {'task': float(s.objective()[0][0]),
|
||||
'effort': float((torque / s.effort).square().mean()),
|
||||
'action_rate': float((env.action_manager.action - env.action_manager.prev_action)
|
||||
.square().mean()),
|
||||
'root_position': float(root_position[0]), 'root_velocity': float(root_velocity[0]),
|
||||
'residual': float(s.residual_request.square().mean())}, **extra}
|
||||
return result
|
||||
|
||||
|
||||
class EvaluationRecorder:
|
||||
"""One trial, exclusive directory; lossless JSONL in bounded finalized XZ chunks.
|
||||
|
||||
budget_check(stage, pending_bytes, written_bytes) MUST raise on aggregate
|
||||
disk/time expiry. Stages: create, record, finalize. Every record checks a
|
||||
conservative reservation for pending raw memory plus estimated encoded bytes;
|
||||
every actual write separately checks exact bytes including headers/trailers.
|
||||
The runner MUST account all other artifacts across every trial/launch.
|
||||
Pending raw data is bounded by 64 records AND 8 MiB, independently of the
|
||||
unchanged 1 MiB record limit. Compression uses the bounded preset-0 dictionary.
|
||||
Initial/seam/step_result/terminal/capture_fault and any audit failure flush
|
||||
synchronously. Forced kill can lose the uncommitted chunk (or tear a write);
|
||||
only finalize fsyncs and acknowledges. A readable prefix is NOT a complete trace.
|
||||
Hook calls cannot grant physics. Recording faults are sticky and fatal.
|
||||
The caller MUST supply an existing, durably established parent directory and
|
||||
keep that path stable through finalization. Only the exclusive trial directory
|
||||
is created here; finalization fsyncs it and its parent before acknowledgment.
|
||||
"""
|
||||
def __init__(self, protocol, trial_index, directory, *, budget_check, supplemental):
|
||||
if not callable(budget_check) or not callable(supplemental):
|
||||
raise ValueError('Explicit resource and supplemental-state hooks required')
|
||||
self.audit = TrialAudit(protocol, trial_index)
|
||||
self.directory = Path(directory)
|
||||
self.budget_check, self.supplemental = budget_check, supplemental
|
||||
self.written_bytes = 0
|
||||
self.pending: list[bytes] = []
|
||||
self.pending_raw_bytes = 0
|
||||
self.faults = []
|
||||
self.finalized = False
|
||||
self.budget_check('create', 0, 0)
|
||||
self.directory.mkdir(exist_ok=False)
|
||||
self.stream = (self.directory / TRACE_FILENAME).open('xb', buffering=0)
|
||||
|
||||
def _flush(self, *, stage='record'):
|
||||
if not self.pending:
|
||||
return
|
||||
data = lzma.compress(b''.join(self.pending), format=lzma.FORMAT_XZ, preset=XZ_PRESET)
|
||||
self.budget_check(stage, len(data), self.written_bytes)
|
||||
written = self.stream.write(data)
|
||||
self.written_bytes += written
|
||||
if written != len(data):
|
||||
raise OSError('Short evidence write')
|
||||
self.pending.clear()
|
||||
self.pending_raw_bytes = 0
|
||||
|
||||
def _write(self, record, *, stage='record', flush=False):
|
||||
raw = (json.dumps(_json_safe(record), allow_nan=False, separators=(',', ':')) + '\n').encode()
|
||||
if len(raw) > MAX_RECORD_BYTES:
|
||||
raise ValueError('Decoded evidence record exceeds bounded reader limit')
|
||||
if (len(self.pending) >= MAX_CHUNK_RECORDS
|
||||
or self.pending_raw_bytes + len(raw) > MAX_CHUNK_RAW_BYTES):
|
||||
self._flush(stage=stage)
|
||||
self.pending.append(raw)
|
||||
self.pending_raw_bytes += len(raw)
|
||||
# Reserve raw memory plus a deliberately conservative encoded-size estimate.
|
||||
# Actual disk admission still uses exact finalized bytes immediately pre-write.
|
||||
# Retain pending evidence if admission fails, for handled cleanup/finalization.
|
||||
self.budget_check(stage, 3 * self.pending_raw_bytes + 65536, self.written_bytes)
|
||||
if (flush or record['kind'] in ('initial', 'seam', 'step_result', 'terminal', 'capture_fault')
|
||||
or len(self.pending) >= MAX_CHUNK_RECORDS or self.pending_raw_bytes >= MAX_CHUNK_RAW_BYTES):
|
||||
self._flush(stage=stage)
|
||||
|
||||
def _fault(self, exc):
|
||||
cause = f'recording_fault:{type(exc).__name__}:{exc}'
|
||||
self.faults.append(cause)
|
||||
self.audit.fail((cause,), kind='recording')
|
||||
return (cause,)
|
||||
|
||||
def _record(self, record):
|
||||
if self.finalized or self.faults:
|
||||
return self._fault(RuntimeError('Recorder finalized or faulted'))
|
||||
# Evaluate AND write: malformed/nonfinite first-offending evidence is not dropped.
|
||||
causes = self.audit.consume(record)
|
||||
try:
|
||||
self._write(record, flush=bool(causes))
|
||||
except Exception as exc:
|
||||
causes = (*causes, *self._fault(exc))
|
||||
return tuple(dict.fromkeys(causes))
|
||||
|
||||
def before_control(self, origin_tick, observation, action, *, mean=None, std=None):
|
||||
"""Runner calls before env.step; nonempty return means DO NOT submit an action.
|
||||
|
||||
Learned metadata: raw 46D observation, pre-tanh mean, std and tanh(mean)
|
||||
action, all [1,N]. Reference: mean/std=None and zero action. No inference here.
|
||||
"""
|
||||
try:
|
||||
return self._record({'kind': 'control', 'origin_tick': origin_tick, 'observation': _row(observation),
|
||||
'action': _row(action), 'mean': None if mean is None else _row(mean),
|
||||
'std': None if std is None else _row(std.expand(1, 3))})
|
||||
except Exception as exc:
|
||||
return self._fault(exc)
|
||||
|
||||
def __call__(self, event, state):
|
||||
try:
|
||||
record = {'kind': event.kind, 'event': plain(asdict(event)),
|
||||
'state': snapshot(state, self.supplemental)}
|
||||
return self._record(record)
|
||||
except Exception as exc:
|
||||
cause = f'recording_fault:{type(exc).__name__}:{exc}'
|
||||
self.faults.append(cause)
|
||||
# Locate a failed accessor at the actual event, without inventing its state/tick sample.
|
||||
record = {'kind': 'capture_fault', 'event': plain(asdict(event)), 'causes': [*event.causes, cause]}
|
||||
causes = self.audit.consume(record)
|
||||
try:
|
||||
self._write(record)
|
||||
except Exception as write_exc:
|
||||
causes += self._fault(write_exc)
|
||||
return causes
|
||||
|
||||
def seam_callback(self, event, state):
|
||||
# Lazy import: the metric/audit and offline reader have no Isaac dependency.
|
||||
from .evaluation_env import SeamDecision
|
||||
|
||||
try:
|
||||
causes = self._record({'kind': 'seam', 'event': plain(asdict(event)),
|
||||
'state': snapshot(state, self.supplemental)})
|
||||
except Exception as exc:
|
||||
causes = self._fault(exc)
|
||||
return SeamDecision(not bool(causes), causes)
|
||||
|
||||
def after_step(self, result):
|
||||
"""Persist actual StepResult, including partial controls; never invent a reward."""
|
||||
try:
|
||||
record = {'kind': 'step_result', 'ticks_advanced': result.ticks_advanced,
|
||||
'observed_tick': self.audit.tick, 'reward': copied(result.reward),
|
||||
'has_next_observation': result.observation is not None,
|
||||
'stop': None if result.stop is None else plain(asdict(result.stop))}
|
||||
if self.finalized:
|
||||
raise RuntimeError('Recorder finalized')
|
||||
causes = self.audit.consume(record)
|
||||
self._write(record)
|
||||
runtime_causes = () if result.stop is None else result.stop.causes
|
||||
return tuple(c for c in causes if c not in runtime_causes)
|
||||
except Exception as exc:
|
||||
return self._fault(exc)
|
||||
|
||||
def finalize(self, *, stop=None, external_failure=None, acknowledge=None):
|
||||
"""Durably persist trace, terminal, metrics; only then acknowledge EXACT stop.
|
||||
|
||||
external_failure is a runner-owned {causes:[nonempty strings], fatal:True,
|
||||
context:dict} for inference/identity/I/O/budget exceptions outside callbacks.
|
||||
It is NOT a synthetic StopResult/tick. Such rows are NEVER acknowledged:
|
||||
abort launch, including when an earlier runtime stop was nonfatal.
|
||||
On ANY write/fsync/budget error raises, leaves partial files, never acknowledges.
|
||||
"""
|
||||
if self.finalized:
|
||||
raise RuntimeError('Already finalized')
|
||||
if stop is None and external_failure is None:
|
||||
raise ValueError('Runtime stop or explicit runner terminal required')
|
||||
terminal = {'kind': 'terminal', 'runtime_stop': None if stop is None else plain(asdict(stop)),
|
||||
'external_failure': plain(external_failure), 'recording_faults': list(self.faults)}
|
||||
self.audit.consume(terminal)
|
||||
report = self.audit.report()
|
||||
report['terminal'] = terminal
|
||||
report['trace_encoding'] = TRACE_ENCODING
|
||||
try:
|
||||
self._write(terminal, stage='finalize')
|
||||
self.stream.flush()
|
||||
os.fsync(self.stream.fileno())
|
||||
encoded = (json.dumps(_json_safe(report), indent=2, allow_nan=False) + '\n').encode()
|
||||
self.budget_check('finalize', len(encoded), self.written_bytes)
|
||||
with (self.directory / 'metrics.json').open('xb') as output:
|
||||
if output.write(encoded) != len(encoded):
|
||||
raise OSError('Short metrics write')
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
self.written_bytes += len(encoded)
|
||||
# Directory entries as well as data must be durable before lifecycle admission.
|
||||
for directory in (self.directory, self.directory.parent):
|
||||
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
self.stream.close()
|
||||
except Exception as exc:
|
||||
self._fault(exc)
|
||||
raise
|
||||
self.finalized = True
|
||||
# Audit recording faults also block nonfatal runtime lifecycle continuation.
|
||||
recording_failure = any(c.startswith(('recording', 'identity', 'nonfinite', 'storage', 'budget'))
|
||||
for c in report['all_causes'])
|
||||
if acknowledge is not None and stop is not None and external_failure is None and not self.faults \
|
||||
and not recording_failure:
|
||||
acknowledge(stop)
|
||||
return report
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
"""Source-qualified observable RNG inventory, NOT complete PhysX state capture.
|
||||
|
||||
No sampling, restoration, solver getter or inference of hidden native state.
|
||||
The runner binds this provider and its scope under the instrumentation source role.
|
||||
"""
|
||||
from copy import deepcopy
|
||||
|
||||
PREFIX = 'source/SkillFactory/SkillFactory/'
|
||||
SCOPE_SOURCE = PREFIX + 'tasks/manager_based/contact_cycle_sim/evaluation_rng_scope.py'
|
||||
SOURCES = [SCOPE_SOURCE,
|
||||
PREFIX + 'tasks/manager_based/contact_cycle_sim/evaluation_instrumentation.py',
|
||||
PREFIX + 'tasks/manager_based/contact_cycle_sim/evaluation_recording.py',
|
||||
PREFIX + 'tasks/manager_based/contact_cycle/mdp.py',
|
||||
PREFIX + 'tasks/manager_based/contact_cycle_sim/cfg.py',
|
||||
PREFIX + 'tasks/manager_based/contact_cycle_sim/evaluation_env.py',
|
||||
'/home/cen/IsaacLab/source/isaaclab/isaaclab/actuators/actuator_pd.py']
|
||||
EVIDENCE_SCOPE = {
|
||||
'format': 'skillfactory.observable-state-scope.v1',
|
||||
'equality': 'recorded_application_controller_and_enumerated_observable_rng_only',
|
||||
'sources': SOURCES,
|
||||
'claims': {'complete_backend_state_equality': False, 'deterministic_replay': False},
|
||||
}
|
||||
UNOBSERVED_INTERNALS = dict.fromkeys((
|
||||
'physx_solver_contact_caches', 'internal_stochastic_state_if_any',
|
||||
'numerical_scheduling_effects'), 'unobserved')
|
||||
# Source inventory, not a search of arbitrary native memory. Unexpected task or
|
||||
# actuator layouts fail qualification; instrumentation separately checks fields.
|
||||
GENERATOR_INVENTORY = {
|
||||
'python_global': 'observed by instrumentation.random.getstate',
|
||||
'numpy_global': 'observed by instrumentation.numpy.random.get_state',
|
||||
'torch_cpu_global': 'observed by recorder.torch.get_rng_state',
|
||||
'torch_current_cuda_device': 'observed by recorder when state.device is CUDA',
|
||||
'additional_generators': [],
|
||||
'task_sampling': 'CycleState.after_physics calls torch.randn_like even with zero noise scale',
|
||||
'warp_sampling': 'no configured task sampling or project-owned Warp random-state buffers',
|
||||
'replicator_sampling': 'no configured task Replicator randomization',
|
||||
'actuator': 'exact IdealPDActuator; no additional generator in active task path',
|
||||
}
|
||||
|
||||
|
||||
def qualify_config(cfg):
|
||||
"""Require the source-reviewed nominal task, not a generic no-RNG assertion."""
|
||||
from isaaclab.actuators.actuator_pd import IdealPDActuator
|
||||
from isaaclab.actuators.actuator_pd_cfg import IdealPDActuatorCfg
|
||||
from isaaclab.utils.string import ResolvableString
|
||||
|
||||
def qualified(actuator):
|
||||
if type(actuator) is not IdealPDActuatorCfg:
|
||||
return False
|
||||
target = actuator.class_type
|
||||
return target is IdealPDActuator or (
|
||||
type(target) is ResolvableString
|
||||
and str(target) == 'isaaclab.actuators.actuator_pd:IdealPDActuator'
|
||||
and target._resolved_callable is IdealPDActuator and target._resolve_error is None)
|
||||
|
||||
groups = cfg.scene.robot.actuators
|
||||
if not groups or not all(qualified(a) for a in groups.values()):
|
||||
raise ValueError('RNG inventory requires exact IdealPD task configuration')
|
||||
if (cfg.scene.num_envs != 1 or cfg.load_randomization is not None
|
||||
or cfg.observations.policy.enable_corruption
|
||||
or any(cfg.cycle_parameters['sensor'].values())):
|
||||
raise ValueError('RNG inventory does not cover changed task randomization')
|
||||
return deepcopy(GENERATOR_INVENTORY)
|
||||
|
||||
|
||||
def backend_rng(state):
|
||||
"""Observe actual Torch state; label only source-qualified unused samplers N/A.
|
||||
|
||||
Python/numpy globals and named generators are copied by instrumentation.
|
||||
Torch is also copied by the recorder; this read does not advance either RNG.
|
||||
Native PhysX internal stochastic state, if any, is explicitly NOT covered.
|
||||
"""
|
||||
import torch
|
||||
|
||||
device = torch.device('cpu' if state is None else state.env.device)
|
||||
actual = {'cpu': torch.get_rng_state().tolist()}
|
||||
if device.type == 'cuda':
|
||||
actual['cuda'] = torch.cuda.get_rng_state(device).tolist()
|
||||
coverage = {
|
||||
'torch_task_global': {
|
||||
'status': 'observed', 'sources': SOURCES,
|
||||
'evidence': 'Actual global RNG; randn_like executes even when noise scale is zero.',
|
||||
'state': actual,
|
||||
},
|
||||
}
|
||||
for name in ('warp_sampling', 'replicator_sampling'):
|
||||
coverage[name] = {
|
||||
'status': 'not_applicable', 'sources': SOURCES,
|
||||
'evidence': GENERATOR_INVENTORY[name] + '; not a claim about native internals.',
|
||||
'state': None,
|
||||
}
|
||||
return {'coverage': coverage, 'evidence_scope': deepcopy(EVIDENCE_SCOPE),
|
||||
'unobserved_internals': deepcopy(UNOBSERVED_INTERNALS)}
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Simulation truth is deliberately available to reference AND residual actor."""
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle_sim.config import combine, pose_cost
|
||||
from SkillFactory.legs.contact_cycle_sim.reference import ReferenceController
|
||||
from SkillFactory.tasks.manager_based.contact_cycle import mdp as base
|
||||
|
||||
|
||||
class SimCycleState(base.CycleState):
|
||||
def __init__(self, env):
|
||||
super().__init__(env)
|
||||
self.residual_cfg = env.cfg.residual_parameters
|
||||
self.residual_request = torch.zeros_like(self.executed)
|
||||
self.reference_used = torch.zeros_like(self.executed)
|
||||
self.effective_residual_rad = torch.zeros_like(self.executed)
|
||||
self.controller = ReferenceController(self, self.residual_cfg['reference'])
|
||||
self.controller.reset(torch.arange(env.num_envs, device=env.device))
|
||||
|
||||
def reset(self, ids):
|
||||
super().reset(ids)
|
||||
self.scenarios[ids] = 0
|
||||
self.stand_only[ids] = False
|
||||
if hasattr(self, 'controller'):
|
||||
self.residual_request[ids] = 0
|
||||
self.reference_used[ids] = 0
|
||||
self.effective_residual_rad[ids] = 0
|
||||
self.controller.reset(ids)
|
||||
|
||||
def set_sampler(self, sampler):
|
||||
if sampler is not None:
|
||||
raise ValueError('Simulation residual v1 is nominal-cycle only; old training sampler is incompatible')
|
||||
super().set_sampler(None)
|
||||
self.scenarios.zero_()
|
||||
|
||||
def after_physics(self, dt):
|
||||
super().after_physics(dt)
|
||||
ids = (self.substeps % self.env.cfg.decimation == 0).nonzero().flatten()
|
||||
self.controller.refresh(ids)
|
||||
|
||||
def errors(self):
|
||||
target, target_velocity = self.port_reference()
|
||||
pos, _, velocity, _ = self.root()
|
||||
return pos - target, velocity - target_velocity
|
||||
|
||||
def policy(self):
|
||||
error, velocity_error = self.errors()
|
||||
gap = self.foot_center()[:, 2] - self.bundle['foot']['radius']
|
||||
# 32 + root error3 + linear velocity3 + Fn1 + gap1 + NEXT reference3 + PREVIOUS residual3.
|
||||
# Read-only: repeated observations do not solve/advance the reference controller.
|
||||
return torch.cat((super().policy(), error, velocity_error, self.contact()[:, 2:3], gap[:, None],
|
||||
self.controller.action, self.residual_request), -1)
|
||||
|
||||
|
||||
def state(env):
|
||||
if not hasattr(env, '_cycle_state'):
|
||||
env._cycle_state = SimCycleState(env)
|
||||
if not isinstance(env._cycle_state, SimCycleState):
|
||||
raise RuntimeError('Wrong state contract; do not silently reuse historical policy32 state')
|
||||
return env._cycle_state
|
||||
|
||||
|
||||
def observation(env, privileged=False):
|
||||
s = state(env)
|
||||
return s.privileged() if privileged else s.policy()
|
||||
|
||||
|
||||
class SimResidualAction(base.CycleAction):
|
||||
def __init__(self, cfg, env):
|
||||
super().__init__(cfg, env)
|
||||
state(env) # install the distinct state BEFORE old wrappers can create policy32 state
|
||||
|
||||
def process_actions(self, actions):
|
||||
s = state(self._env)
|
||||
try:
|
||||
full, request, delta = combine(s.controller.action, actions, s.residual_cfg['residual_limit_rad'],
|
||||
self._env.cfg.support_parameters['action_scale_rad'])
|
||||
except ValueError:
|
||||
# Direct ActionManager callers bypass LoadedLegEnv.step's outer validation.
|
||||
# Manager stores input first; restore history before rejecting composition.
|
||||
self._env.action_manager.action[:] = self.raw_actions
|
||||
raise
|
||||
super().process_actions(full)
|
||||
s.reference_used.copy_(s.controller.action)
|
||||
s.residual_request.copy_(request)
|
||||
s.effective_residual_rad.copy_(delta)
|
||||
|
||||
|
||||
def root_position_cost(env):
|
||||
s = state(env)
|
||||
return pose_cost(*s.errors(), s.residual_cfg['reward'])[0]
|
||||
|
||||
|
||||
def root_velocity_cost(env):
|
||||
s = state(env)
|
||||
return pose_cost(*s.errors(), s.residual_cfg['reward'])[1]
|
||||
|
||||
|
||||
def residual_cost(env):
|
||||
return state(env).residual_request.square().mean(-1)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Residual requests are NOT absolute joint actions. Log both with explicit units."""
|
||||
import torch
|
||||
|
||||
from SkillFactory.tasks.manager_based.contact_cycle.recording import CycleRecorder
|
||||
|
||||
from .mdp import residual_cost, root_position_cost, root_velocity_cost
|
||||
|
||||
|
||||
class SimCycleRecorder(CycleRecorder):
|
||||
def __init__(self, env):
|
||||
super().__init__(env)
|
||||
self.actor_input = torch.zeros(env.num_envs, 46)
|
||||
|
||||
def snapshot(self):
|
||||
values = super().snapshot()
|
||||
s = self.state
|
||||
extra = {'residual_request_normalized': s.residual_request,
|
||||
'reference_used_normalized': s.reference_used,
|
||||
'reference_next_normalized': s.controller.action,
|
||||
'effective_residual_rad': s.effective_residual_rad,
|
||||
'reference_ik_rad': s.controller.q_ik,
|
||||
'root_position_cost_unweighted': root_position_cost(self.env),
|
||||
'root_velocity_cost_unweighted': root_velocity_cost(self.env),
|
||||
'residual_cost_unweighted': residual_cost(self.env)}
|
||||
values.update({k: v.detach().cpu().clone() for k, v in extra.items()})
|
||||
return values
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"""Direct-construction RootXY-v2 config. No registry/v1 source mutation."""
|
||||
from pathlib import Path
|
||||
|
||||
from isaaclab.utils.configclass import configclass
|
||||
|
||||
from SkillFactory.legs.contact_cycle_sim.rootxy_training_v2 import (
|
||||
BASE_PATH, TASK_ID, TASK_PATH, exact, load_task_config,
|
||||
)
|
||||
from .cfg import SimContactCycleEnvCfg
|
||||
from . import mdp
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[6]
|
||||
|
||||
|
||||
@configclass
|
||||
class RootXYContactCycleEnvCfg(SimContactCycleEnvCfg):
|
||||
rootxy_config: str = str(ROOT / TASK_PATH)
|
||||
task_identity: str = TASK_ID
|
||||
residual_config: str = str(ROOT / BASE_PATH)
|
||||
|
||||
def __post_init__(self):
|
||||
resolved = load_task_config(self.rootxy_config, ROOT)
|
||||
if Path(self.residual_config).resolve() != ROOT / BASE_PATH or self.task_identity != TASK_ID:
|
||||
raise ValueError("RootXY-v2 must construct from the pinned v1 base")
|
||||
super().__post_init__() # unchanged controller/fixture/46D/actions/termination
|
||||
self.residual_parameters = resolved # honest v2 identity, single whitelisted reward override
|
||||
|
||||
|
||||
def verify_actual_config(env):
|
||||
"""Task seam checks, supplementary to the future supervisor full cfg binding.
|
||||
|
||||
Call before first reset/action and after close. Never substitutes for installed
|
||||
source/namespace/constructor normalization identity checks in the adapter.
|
||||
"""
|
||||
cfg = env.cfg
|
||||
resolved = load_task_config(ROOT / TASK_PATH, ROOT)
|
||||
if (type(cfg) is not RootXYContactCycleEnvCfg or cfg.task_identity != TASK_ID
|
||||
or not exact(cfg.residual_parameters, resolved)
|
||||
or cfg.actions.joint_position.class_type is not mdp.SimResidualAction
|
||||
or cfg.rewards.root_position.func is not mdp.root_position_cost
|
||||
or cfg.rewards.root_position.weight != -1.
|
||||
or cfg.rewards.root_velocity.weight != -.1 or cfg.rewards.residual.weight != -.05
|
||||
or cfg.rewards.task.weight != 1. or cfg.rewards.effort.weight != -.01
|
||||
or cfg.rewards.action_rate.weight != -.005
|
||||
or cfg.terminations.failed is None or cfg.episode_length_s != 9
|
||||
or env.num_envs != 128 or env.physics_dt != .002 or env.step_dt != .01
|
||||
or cfg.sim.physics.solver_type != 0 or cfg.sim.physics.enable_external_forces_every_iteration
|
||||
or mdp.state(env).robot.is_fixed_base):
|
||||
raise ValueError("Actual-used RootXY-v2 task seam mismatch")
|
||||
if not exact(mdp.state(env).residual_cfg, resolved):
|
||||
raise ValueError("Actual-used residual state identity mismatch")
|
||||
return {"task_id": TASK_ID, "resolved_task": resolved, "full_adapter_binding_required": True}
|
||||
|
||||
|
||||
def construct_environment(device="cuda:0"):
|
||||
"""For the future admitted worker only; never imported by the CPU CLI."""
|
||||
from .env import SimContactCycleEnv
|
||||
|
||||
cfg = RootXYContactCycleEnvCfg()
|
||||
cfg.scene.num_envs = 128
|
||||
cfg.sim.device = device
|
||||
cfg.seed = 92511
|
||||
env = SimContactCycleEnv(cfg=cfg)
|
||||
try:
|
||||
verify_actual_config(env)
|
||||
except BaseException:
|
||||
env.close()
|
||||
raise
|
||||
return env
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
"""Compact functional columns plus streaming XY/authority metrics, never full snapshots.
|
||||
|
||||
4500x128 bounded columns are retained in RAM for the unchanged functional auditor.
|
||||
Only four selected trajectories are publishable; learner rollouts are not traced.
|
||||
"""
|
||||
import torch
|
||||
|
||||
from SkillFactory.legs.contact_cycle_sim.rootxy_diagnostics_v2 import RootXYMetrics
|
||||
from .mdp import state, base
|
||||
|
||||
|
||||
class RootXYRecorder:
|
||||
def __init__(self, env, functional, learned):
|
||||
self.env, self.s, self.functional, self.learned = env, state(env), functional, learned
|
||||
self.metrics = RootXYMetrics(env.num_envs, env.device)
|
||||
self.columns = {}
|
||||
self.ticks = 0
|
||||
self.stops = [None] * env.num_envs
|
||||
self.early = [False] * env.num_envs
|
||||
self.action_available = False
|
||||
self.height_square = torch.zeros(env.num_envs, device=env.device, dtype=torch.float64)
|
||||
self.swing_square = self.height_square.clone()
|
||||
self.swing_count = torch.zeros(env.num_envs, device=env.device, dtype=torch.long)
|
||||
self.failure = torch.zeros(env.num_envs, device=env.device, dtype=torch.bool)
|
||||
s = self.s
|
||||
self.lower = torch.tensor([j['limits']['lower'] for j in s.bundle['joints']], device=env.device)
|
||||
self.upper = torch.tensor([j['limits']['upper'] for j in s.bundle['joints']], device=env.device)
|
||||
self.speed = torch.tensor([j['limits']['velocity'] for j in s.bundle['joints']], device=env.device)
|
||||
self.initial_pair = None
|
||||
|
||||
def before_control(self, observation, action, mean, std):
|
||||
if (observation.shape != (self.env.num_envs, 46) or action.shape != (self.env.num_envs, 3)
|
||||
or not torch.isfinite(observation).all() or not torch.isfinite(action).all()
|
||||
or (action.abs() > 1).any()):
|
||||
raise ValueError('Invalid validation actor input/action')
|
||||
if self.learned:
|
||||
if (mean is None or std is None or not torch.isfinite(mean).all()
|
||||
or not torch.isfinite(std).all() or not torch.equal(action, mean.tanh())):
|
||||
raise ValueError('Missing/nonfinite deterministic learned metadata')
|
||||
elif mean is not None or std is not None or action.any():
|
||||
raise ValueError('Analytic baseline must have zero residual and no actor metadata')
|
||||
self.action_available = True
|
||||
|
||||
def __enter__(self):
|
||||
s = self.s
|
||||
self.initial_pair = {k: v.detach().cpu().clone() for k, v in {
|
||||
'policy': s.policy(), 'root': torch.cat(s.root(), -1), 'joint_pos': s.q(),
|
||||
'target_root': s.port_reference()[0], 'target_foot': s.reference()[2],
|
||||
'reference': s.controller.action, 'normal': s.contact(), 'foot': s.foot_center(),
|
||||
}.items()}
|
||||
self.previous = self.env.scene.update
|
||||
|
||||
def update(dt):
|
||||
self.previous(dt)
|
||||
if dt > 0:
|
||||
if dt != .002:
|
||||
raise ValueError('Unexpected diagnostic physics dt')
|
||||
self.record()
|
||||
|
||||
self.env.scene.update = update
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
self.env.scene.update = self.previous
|
||||
|
||||
def record(self):
|
||||
if self.ticks >= 4500 or not self.action_available:
|
||||
raise ValueError('Extra tick or missing control metadata')
|
||||
s, g = self.s, self.functional['gates']
|
||||
phase, _, target, _, _ = s.reference()
|
||||
error, _ = s.errors()
|
||||
ratio = torch.maximum((s.robot.data.applied_torque.torch[:, s.joints] / s.effort).abs().amax(-1),
|
||||
(s.robot.data.joint_vel.torch[:, s.joints] / self.speed).abs().amax(-1))
|
||||
excess = torch.maximum(self.lower - s.q(), s.q() - self.upper).clamp(min=0).amax(-1)
|
||||
actual = (self.env.action_manager.get_term('joint_position').processed_actions
|
||||
- s.nominal - .5 * s.reference_used)
|
||||
if (not torch.allclose(actual, s.effective_residual_rad, atol=1e-6, rtol=0)
|
||||
or (actual.abs() > .05 + 1e-6).any()):
|
||||
raise ValueError('Effective residual authority invariant failed')
|
||||
safe = ((ratio <= g['normalized_effort_velocity_max']) & (excess <= g['joint_limit_excess_rad_max'])
|
||||
& (s.guide[..., 2].abs().reshape(self.env.num_envs, -1).amax(-1) == 0))
|
||||
self.metrics.tick(time=s.time, position_error=error, phase=phase, reference=s.reference_used,
|
||||
request=s.residual_request, effective_residual=actual, safety_ok=safe)
|
||||
live = self.metrics.live
|
||||
self.height_square += error[:, 2].double().square() * live
|
||||
swing = live & (phase == 3)
|
||||
self.swing_square += (s.foot_center() - target).double().square().sum(-1) * swing
|
||||
self.swing_count += swing.long()
|
||||
self.failure |= live & base.failed(self.env)
|
||||
values = {'time': s.time, 'phase': phase, 'scenario': s.scenarios, 'weight': s.weight,
|
||||
'normal': s.contact(), 'foot': s.foot_center(), 'target': target,
|
||||
'gap': s.foot_center()[:, 2] - s.bundle['foot']['radius'],
|
||||
'signed_height_error': error[:, 2], 'tilt': s.tilt(), 'external': s.external,
|
||||
'guide': s.guide, 'auxiliary': s.auxiliary, 'joint_excess': excess, 'limit_ratio': ratio,
|
||||
'contact_acquired': s.acquisition.acquired,
|
||||
'actor_metadata_available': torch.full_like(live, self.learned),
|
||||
'control_action_available': torch.full_like(live, self.action_available),
|
||||
'root_position_error': error, 'reference_used_normalized': s.reference_used,
|
||||
'effective_residual_rad': actual}
|
||||
for name, value in values.items():
|
||||
if not torch.isfinite(value).all():
|
||||
raise ValueError('Nonfinite validation column: ' + name)
|
||||
if name not in self.columns:
|
||||
self.columns[name] = torch.empty((4500, *value.shape), dtype=value.dtype, device='cpu')
|
||||
self.columns[name][self.ticks].copy_(value.detach().cpu())
|
||||
self.ticks += 1
|
||||
|
||||
def end_control(self, terminated, truncated, final_step):
|
||||
for e in (terminated | truncated).nonzero().flatten().cpu().tolist():
|
||||
if self.stops[e] is None:
|
||||
self.stops[e] = self.ticks
|
||||
self.early[e] = bool(terminated[e]) or not final_step
|
||||
self.metrics.end_control(terminated, truncated)
|
||||
|
||||
def rows(self, evaluate):
|
||||
result = self.metrics.rows()
|
||||
for e, row in enumerate(result):
|
||||
stop = self.stops[e]
|
||||
if stop is None or stop != row['physics_samples']:
|
||||
raise ValueError('Missing/partial first-episode terminal capture')
|
||||
episode = {k: v[:stop, e:e+1] for k, v in self.columns.items()}
|
||||
audit = evaluate(episode, self.functional, 'learned_policy' if self.learned else 'analytic_reference')
|
||||
row.update(success=bool(audit['sim_functional_passed'] and not self.early[e] and not self.failure[e]),
|
||||
functional_audit=audit, height_rms_m=float((self.height_square[e] / stop).sqrt()),
|
||||
swing_rms_m=float((self.swing_square[e] / self.swing_count[e]).sqrt())
|
||||
if self.swing_count[e] else None, landing_error_m=audit['metrics'].get('landing_error_m'))
|
||||
return result
|
||||
Reference in New Issue
Block a user