"""told_check2.py: the card 03 rerun with the replica-free told-gear planner (ideas/IDEA-03-PLANNER-TOLD-GEAR.md, repaired test; review/CLAUDE-QUESTION-TOLD-V2-2026-10-13.md, design accepted in principle by review/ASTRA-TOLD-V2-2026-10-13.md). A new implementation of the same declared comparator: never pooled or compared with card 03's INVALID K-plan arm. The released MT30 48M checkpoint, weights frozen, halved right knee (gear 50 to 25, bridge_adapt3.apply_change), the bridge evaluator (eval_mode=True, bank 1000 episodes 0 to 9). The UNMODIFIED upstream planner (agent._plan, pinned md5) plans in executed command units; only the model boundary is reparametrised (told2_logic): next, reward and Q receive m = S u (non-mutating), the policy proposal comes back as clip(S^-1 m, -1, 1). Idea 01's knee hook stays at scale 1 and only records the executed command (no doubling: the planner's u is the command). Order: refusals (mpc on, pinned tdmpc2.py); torque check; IDENTITY arm (half = 1, the wrapped path itself, measured against the saved A block at the unchanged 1e-3 tolerance); if identity fails the job writes told2.json with outcome INVALID and stops BEFORE any told evaluation; otherwise the K-plan2 arm (half = 0.5), once. python told_check2.py task=mt30 model_size=48 checkpoint=/path/mt30-48M.pt seed=2 compile=false \ enable_wandb=false save_video=false +out_dir=/path/told2 +gate_a=/path/gate_a_reading_2026-10-11.json \ +a_block=/path/seed2-Df-bridge_adapt.json +df_dir=/path/with/seed{2,3,4}-Df-bridge_adapt.json Outputs (mode 'x', empty out_dir): resolved_config.json, torque_check.json, arms/.json and .npz, told2.json. """ import dataclasses import json import os import time import numpy as np import calib_logic as CL import told2_logic as T2 import told_logic as TL from calib_check import KneeHook, progress, sha256_of from told_check import md5_of, torque_check RESULT_FILE = "told2.json" SEEDS = CL.GATE_A_SEEDS class Boundary: """Reparametrises the knee at the model boundary of an unmodified upstream planner; counts every conversion and records the largest knee value the model received.""" def __init__(self, agent, knee_index, torch): self.agent, self.knee_index, self.torch = agent, knee_index, torch self.originals = {n: getattr(agent.model, n) for n in ("next", "reward", "Q", "pi")} self.half = None def install(self, half): torch = self.torch self.half = half self.s = torch.tensor(T2.scale(self.agent.cfg.action_dim, self.knee_index, half), dtype=torch.float32, device=self.agent.device) self.calls = {n: 0 for n in self.originals} self.model_knee_max = torch.zeros((), device=self.agent.device) for n in ("next", "reward", "Q"): setattr(self.agent.model, n, self._to_model(n)) self.agent.model.pi = self._pi def _to_model(self, name): original = self.originals[name] def call(z, a, *args, **kwargs): self.calls[name] += 1 m = T2.to_model(a, self.s) # a new tensor; the planner's u is untouched self.model_knee_max = self.torch.maximum(self.model_knee_max, m[..., self.knee_index].abs().max()) return original(z, m, *args, **kwargs) return call def _pi(self, z, task): self.calls["pi"] += 1 m, info = self.originals["pi"](z, task) info["mean"] = T2.to_command(info["mean"], self.s, self.knee_index, self.half) # a new tensor in the entry return T2.to_command(m, self.s, self.knee_index, self.half), info def run_arm(name, half, boundary, hook, agent, env, idx, out_dir): import bridge_adapt3 as BA boundary.install(half) hook.scale = 1.0 commands = [] hook.observer = lambda inner, command: commands.append([float(x) for x in command]) r = BA.evaluate(agent, env, idx[TL.RUN_TASK], TL.RUN_EPISODES, f"told2 {name} {TL.RUN_TASK}", BA.DEFAULT_EVAL_SEED) hook.observer = None flags = hook.take() expected = BA.EPISODE_DECISIONS * 2 if len(flags) != TL.RUN_EPISODES or any(len(f) != expected for f in flags): raise RuntimeError(f"{name}: expected {TL.RUN_EPISODES} episodes of {expected} control steps, got {[len(f) for f in flags]}") cmd = np.array(commands) half_vec = T2.scale(cmd.shape[1], boundary.knee_index, half) model_space = T2.to_model(cmd, half_vec) # the model-space command each control step corresponds to arm = {"arm": name, "half": half, "task": TL.RUN_TASK, "result": r, "conversions": dict(boundary.calls), "max_abs_model_knee_input": float(boundary.model_knee_max.item()), "max_abs_executed_knee": float(np.abs(cmd[:, boundary.knee_index]).max()), "max_abs_executed_any": float(np.abs(cmd).max()), "clipped_steps": int(sum(sum(map(bool, f)) for f in flags)), "control_steps": int(cmd.shape[0]), "action_repeat_consistent": T2.action_repeat_consistent(commands), "max_abs_model_space_knee_of_executed": float(np.abs(model_space[:, boundary.knee_index]).max())} CL.write_once(os.path.join(out_dir, "arms", f"{name}.json"), arm) with open(os.path.join(out_dir, "arms", f"{name}.npz"), "xb") as f: np.savez_compressed(f, executed_command_per_control_step=cmd, model_space_command_per_control_step=model_space) print(f"{name} {TL.RUN_TASK} mean {r['mean']:.3f} conversions {arm['conversions']} " f"model knee max {arm['max_abs_model_knee_input']:.4f}", flush=True) return arm def run(cfg): import mujoco import torch from common.parser import parse_cfg from common.seed import set_seed from envs import make_env import tdmpc2 as upstream from tdmpc2 import TDMPC2 import bridge_adapt3 as BA assert torch.cuda.is_available() t_start = time.time() cfg = parse_cfg(cfg) if not cfg.mpc: raise SystemExit("REFUSED: the told planner needs mpc=true") tdmpc2_md5 = md5_of(upstream.__file__) if tdmpc2_md5 != TL.PINNED_TDMPC2_MD5: raise SystemExit(f"REFUSED: tdmpc2.py md5 {tdmpc2_md5} is not the pinned {TL.PINNED_TDMPC2_MD5}") out_dir, gate_a_path, a_block_path, df_dir = (str(cfg.get(k, "")) for k in ("out_dir", "gate_a", "a_block", "df_dir")) assert out_dir and gate_a_path and a_block_path and df_dir, "pass +out_dir, +gate_a, +a_block and +df_dir" with open(gate_a_path) as f: comp = CL.comparators(json.load(f)) with open(a_block_path) as f: a_record = json.load(f) saved_run = a_record["A"][TL.RUN_TASK] assert abs(saved_run["mean"] - comp["N"]) < 1e-9, "the A block file and the Gate A reading disagree on N" assert int(a_record["eval_seed"]) == BA.DEFAULT_EVAL_SEED and a_record["gear_joint"] == CL.KNEE df_after, df_paths = {}, {} for s in SEEDS: p = os.path.join(df_dir, f"seed{s}-Df-bridge_adapt.json") with open(p) as f: rec = json.load(f) after = rec["after"][TL.RUN_TASK] assert int(rec["seed"]) == s and abs(float(after["mean"]) - comp["Df_running_after_by_seed"][s]) < 1e-6, p df_after[s], df_paths[s] = after["episodes"], p CL.claim_out_dir(out_dir) os.makedirs(os.path.join(out_dir, "arms")) set_seed(cfg.seed) env = make_env(cfg) eval_env = make_env(cfg) tasks = list(cfg.tasks) idx = {t: tasks.index(t) for t in tasks} CL.write_once(os.path.join(out_dir, "resolved_config.json"), dataclasses.asdict(cfg)) gears = {"train_env": BA.apply_change(env, tasks, idx, CL.KNEE, CL.CHANGED_KNEE_SCALE), "eval_env": BA.apply_change(eval_env, tasks, idx, CL.KNEE, CL.CHANGED_KNEE_SCALE)} inner = BA.sub_env(eval_env, idx[TL.RUN_TASK]) names = [inner.physics.model.id2name(i, "actuator") for i in range(inner.physics.model.nu)] knee_index = names.index(CL.KNEE) hook = KneeHook([inner], knee_index) agent = TDMPC2(cfg) agent.load(cfg.checkpoint) BA.normalise_task_embeddings(agent) boundary = Boundary(agent, knee_index, torch) here = os.path.dirname(os.path.abspath(__file__)) out = {"script": "told_check2", "card": "ideas/IDEA-03-PLANNER-TOLD-GEAR.md (repaired test), replica-free runner", "checkpoint": cfg.checkpoint, "checkpoint_sha256": sha256_of(cfg.checkpoint), "seed": cfg.seed, "gears": gears, "actuators": names, "knee_index": knee_index, "eval_seed": BA.DEFAULT_EVAL_SEED, "tdmpc2_md5": tdmpc2_md5, "planner": "upstream agent._plan, unmodified; knee reparametrised at the model boundary", "inputs": {"gate_a": gate_a_path, "gate_a_sha256": sha256_of(gate_a_path), "a_block": a_block_path, "a_block_sha256": sha256_of(a_block_path), "df_after": {str(s): {"path": p, "sha256": sha256_of(p)} for s, p in df_paths.items()}}, "comparators": comp, "runner_sha256": {n: sha256_of(os.path.join(here, n)) for n in ("told_check2.py", "told2_logic.py", "told_logic.py", "told_check.py", "calib_check.py", "calib_logic.py", "bridge_adapt3.py")}, "quarantine": "card 03's INVALID K-plan arm (results/told/) is never compared or pooled with this run", "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "arms": {}} eval_env.reset(task_idx=idx[TL.RUN_TASK]) torque = torque_check(inner, CL.KNEE, mujoco) CL.write_once(os.path.join(out_dir, "torque_check.json"), torque) progress(f"told2 torque check {'passes' if torque['passes'] else 'FAILS'}") hook.take() out["torque_check"] = torque ident = run_arm("identity", 1.0, boundary, hook, agent, eval_env, idx, out_dir) ident["vs_saved_A_block"] = CL.n_check(ident["result"]["episodes"], saved_run["episodes"]) out["arms"]["identity"] = ident identity_ok = torque["passes"] and ident["vs_saved_A_block"]["reproduces"] if not identity_ok: out.update({"valid": False, "outcome": TL.INVALID, "stopped": "identity or torque check failed; no told evaluation ran", "finished": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}) CL.write_once(os.path.join(out_dir, RESULT_FILE), out) print("told2: INVALID, stopped before the told arm", flush=True) return elapsed = (time.time() - t_start) / 60.0 if not T2.told_arm_fits(elapsed): out.update({"valid": False, "outcome": "INCOMPLETE", "elapsed_minutes": elapsed, "stopped": f"the told arm would not fit the {T2.CAP_MINUTES} min allowance after {elapsed:.1f} min", "finished": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}) CL.write_once(os.path.join(out_dir, RESULT_FILE), out) print("told2: INCOMPLETE, the told arm did not fit the allowance", flush=True) return kplan = run_arm("K-plan2", T2.HALF, boundary, hook, agent, eval_env, idx, out_dir) out["arms"]["K-plan2"] = kplan checks = {"torque_check": torque["passes"], "identity_reproduces_A_block": True, "every_boundary_converted": all(v > 0 for v in kplan["conversions"].values()), "model_knee_within_box": kplan["max_abs_model_knee_input"] <= T2.HALF + 1e-6, "executed_within_limits": kplan["max_abs_executed_any"] <= 1.0 + 1e-6, "no_clipped_step": kplan["clipped_steps"] == 0, "action_repeat_consistent": kplan["action_repeat_consistent"] and ident["action_repeat_consistent"], "executed_is_twice_model_space": kplan["max_abs_model_space_knee_of_executed"] <= T2.HALF + 1e-6} out["checks"] = checks out["valid"] = all(checks.values()) mean = float(kplan["result"]["mean"]) out["outcome"] = T2.outcome(out["valid"], mean, comp["Df_bar"], comp["N"], comp["T"]) out["paired_vs_Df_after"] = TL.paired_differences(kplan["result"]["episodes"], df_after) out["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) CL.write_once(os.path.join(out_dir, RESULT_FILE), out) print(f"checks {checks}", flush=True) print(f"K-plan2: walker-run {mean:.1f} -> {out['outcome']}", flush=True) if __name__ == '__main__': os.environ['MUJOCO_GL'] = os.getenv("MUJOCO_GL", 'egl') import hydra hydra.main(config_name='config', config_path='.')(run)()