change-bench / scripts /told_logic.py
Mimarin's picture
Change Bench v0 (manifest e9200d808c16f8ecde8589ab612ec99b2f178e6c7593f64b3ab7738637add2c6)
68d3a5d verified
Raw History Blame Contribute Delete
6.39 kB
"""told_logic.py: the arithmetic of idea card 03 (ideas/IDEA-03-PLANNER-TOLD-GEAR.md, repaired test; binding), no torch
and no MuJoCo, so the Mac can test it. told_check.py (box, GPU) installs the told-gear planner and calls these functions.
The told-gear constrained planner: the released model is told the knee is at half strength by planning in MODEL units.
A model-space knee action m_k in [-HALF_BOX, HALF_BOX] is the torque gear 25 can deliver expressed in the healthy model's
units (50 m_k = 25 u_k); the simulator receives u_k = EXEC_FACTOR m_k, which never needs clipping. Every other coordinate
keeps [-1, 1]. The helpers work on numpy arrays and on torch tensors alike (both have .clip with array bounds).
"""
import math
import numpy as np
import calib_logic as CL
KNEE = CL.KNEE
HEALTHY_KNEE_GEAR = CL.HEALTHY_KNEE_GEAR # 50
CHANGED_KNEE_SCALE = CL.CHANGED_KNEE_SCALE # gear 50 to 25
HALF_BOX = 0.5 # model-space knee bound: what gear 25 can deliver in gear-50 units
EXEC_FACTOR = 1.0 / CHANGED_KNEE_SCALE # u_k = 2 m_k
RUN_TASK = CL.RUN_TASK
RUN_EPISODES = 10 # running only; standing and walking backwards dropped (Astra C2)
ARMS = ("identity", "K-plan") # identity: the replica planner with the full box, scale 1
TORQUE_TOLERANCE = 1e-9 # matched-state actuator force agreement (relative)
INVALID = "INVALID"
MATCHES, PARTIAL, NONE_SHOWN = "MATCHES IN THIS SCREEN", "PARTIAL RECOVERY", "NO RECOVERY SHOWN"
# The clamp sites of the pinned planner (tdmpc2-e9f59321933cbc8e11a002b842adc7d4ffae8ff1/tdmpc2/tdmpc2.py, md5
# a50fb6c850b49c60d698e50c244f3bf7) and what the told planner does at each. Written into the run record; told_check.py
# refuses a tdmpc2.py with another md5, so the line numbers hold.
PINNED_TDMPC2_MD5 = "a50fb6c850b49c60d698e50c244f3bf7"
CLAMP_SITES = [
{"site": "policy-prior trajectory actions before model.next", "lines": "tdmpc2.py:158-160",
"told": "model.pi is wrapped: its sampled action and info['mean'] are projected into the told box"},
{"site": "Gaussian candidate sampling", "lines": "tdmpc2.py:176-178", "told": "clamp to the told box per coordinate"},
{"site": "elite mean and std, shifted _prev_mean", "lines": "tdmpc2.py:192-197, 167, 205",
"told": "mean projected into the told box; std clamped to the told min/max std per coordinate"},
{"site": "final action after exploration noise", "lines": "tdmpc2.py:202-206", "told": "clamp to the told box"},
{"site": "bootstrap pi action passed to Q in _estimate_value", "lines": "tdmpc2.py:135-136",
"told": "through the wrapped model.pi"},
{"site": "non-MPC action path (act with cfg.mpc false)", "lines": "tdmpc2.py:116-120",
"told": "REJECTED: told_check.py refuses mpc=false"},
]
def box(action_dim, knee_index, half=HALF_BOX):
"""(low, high) per coordinate: the knee in [-half, half], every other coordinate in [-1, 1]."""
if not (0 <= knee_index < action_dim):
raise ValueError(f"knee index {knee_index} outside an action of {action_dim}")
if not (isinstance(half, (int, float)) and math.isfinite(half) and 0 < half <= 1):
raise ValueError(f"half must lie in (0, 1], got {half!r}")
high = np.ones(action_dim)
high[knee_index] = half
return -high, high
def std_bounds(min_std, max_std, action_dim, knee_index, half=HALF_BOX):
"""Per-coordinate (min_std, max_std): the knee's are scaled with its box (declared before data), the rest unchanged."""
if not (0 < min_std <= max_std):
raise ValueError(f"need 0 < min_std <= max_std, got {min_std}, {max_std}")
lo = np.full(action_dim, float(min_std))
hi = np.full(action_dim, float(max_std))
lo[knee_index] *= half
hi[knee_index] *= half
return lo, hi
def project(x, low, high):
"""Clamps every coordinate of x (last axis) into [low, high]; numpy arrays or torch tensors with matching bounds."""
return x.clip(low, high)
def executed_command(action, knee_index):
"""The command entering the simulator for a model-space action: only the knee is multiplied by EXEC_FACTOR. Returns
(command, clipped) through calib_logic.scaled_command, so the wrapper is the one idea 01 used; for an action inside
the told box clipped is always False."""
return CL.scaled_command(action, knee_index, EXEC_FACTOR)
def knee_torque(command_knee, gear):
"""Actuator force on the knee hinge for a motor actuator: gear times the (clipped) command."""
return float(gear) * max(-CL.COMMAND_LIMIT, min(CL.COMMAND_LIMIT, float(command_knee)))
def torque_equivalent(m_knee, healthy_gear=HEALTHY_KNEE_GEAR):
"""True when the healthy model's torque for m_k equals the changed body's torque for the executed 2 m_k."""
healthy = knee_torque(m_knee, healthy_gear)
changed = knee_torque(EXEC_FACTOR * m_knee, healthy_gear * CHANGED_KNEE_SCALE)
return abs(healthy - changed) <= TORQUE_TOLERANCE * max(1.0, abs(healthy))
def paired_differences(arm_episodes, df_after_by_seed):
"""Per seed: the arm's episode returns minus that seed's saved Df running-after episodes, same bank, same order."""
out = {}
for seed, df in sorted(df_after_by_seed.items()):
if len(df) != len(arm_episodes) or not df:
raise ValueError(f"seed {seed}: {len(df)} saved Df episodes against {len(arm_episodes)} arm episodes")
diffs = [float(a) - float(b) for a, b in zip(arm_episodes, df)]
out[str(seed)] = {"differences": diffs, "mean": float(np.mean(diffs))}
return out
def outcome(valid, arm_mean, df_bar, n, t):
"""The repaired card's classes, IN ORDER: INVALID unless every check passed; MATCHES IN THIS SCREEN if mean >= Df_bar
- T; PARTIAL RECOVERY if mean > N + T; NO RECOVERY SHOWN otherwise."""
if not valid:
return INVALID
for name, x in (("arm_mean", arm_mean), ("df_bar", df_bar), ("n", n), ("t", t)):
if not (isinstance(x, (int, float)) and math.isfinite(x)):
raise ValueError(f"{name} must be finite, got {x!r}")
if arm_mean >= df_bar - t:
return MATCHES
if arm_mean > n + t:
return PARTIAL
return NONE_SHOWN
def progress_total():
"""Dashboard progress lines: one per running episode per arm, plus the torque check line."""
return RUN_EPISODES * len(ARMS) + 1