"""calib_check.py: the GPU job of idea card 01 (ideas/IDEA-01-CALIBRATION-ONLY.md, revised kill test; binding). Is the Gate A gain just calibration? The released MT30 48M checkpoint, weights frozen (no update anywhere), on the halved right knee (gear 50 to 25 on every walker task, bridge_adapt3.apply_change), evaluated through the bridge evaluator itself (bridge_adapt3.evaluate: eval_mode=True, episode i re-seeds the task's resets and the planner noise with 1000 + i), with ONE change: a hook on each walker sub-environment's dm_control step scales ONLY the right-knee entry of the command entering the simulator by the arm's factor, then clips it to [-1, 1] (calib_logic.scaled_command). The planner and policy keep their unscaled action. Every control step's clip flag is logged. Order (one process): 1. N-check: scale 1. Must reproduce the saved A block (walker-run mean 334.2) episode by episode; it also proves the hook is the identity at scale 1. 2. K2: scale 2 (the oracle ratio). 3. K-est estimation: the released policy WALKING (walker-walk, bank seed 1000, scale 1) for the first 200 control steps (100 decisions). At each control step, before the simulator steps: the state (qpos, qvel) and the applied command u_t are recorded and the simulator's own acceleration for them (qacc) is taken by mj_forward on a COPY of the simulator's data; then mj_inverse on (qpos, qvel, qacc) with the known HEALTHY model (knee gear 50) gives qfrc_inverse, and f_t = qfrc_inverse at the dof of hinge right_knee, nothing subtracted. qfrc_actuator is never read. Steps with right-leg contact, the knee near its limits or |u_t| < 0.05 are cut; g_hat is the least-squares slope through the origin (calib_logic.estimate_gain); scale = 50 / g_hat. 4. K-est: scale 50 / g_hat. Each arm: walker-run 10 episodes (the outcome), walker-stand and walker-walk-backwards 5 episodes each (reported only; the bridge A block's counts, so every block is paired episode for episode with the saved A block). Outcome per arm (K2, K-est), IN ORDER: SUFFICES if mean >= Df_bar - T, else PARTIAL if mean > N + T, else FAILS, with Df_bar, N and T computed from the saved Gate A reading (+gate_a). python calib_check.py task=mt30 model_size=48 checkpoint=/path/mt30-48M.pt seed=2 compile=false \ enable_wandb=false save_video=false +out_dir=/path/calib \ +gate_a=/path/gate_a_reading_2026-10-11.json +a_block=/path/seed2/Df/bridge_adapt.json One progress line per episode (BENCH_PROGRESS_FILE): 3 arms x 20 episodes + 1 estimation line = 61 (41 if g_hat cannot be estimated and K-est is skipped). Outputs are written once (mode 'x') into an empty out_dir: resolved_config.json, arms/.json, estimation.json, estimation.npz, calib.json. """ import copy import dataclasses import hashlib import json import os import time import numpy as np import calib_logic as CL RUN_TASK, RETENTION_TASKS, ARMS = CL.RUN_TASK, CL.RETENTION_TASKS, CL.ARMS WALK_TASK = "walker-walk" ACTUATORS = 6 ACTION_REPEAT = 2 EST_SEED = 1000 # AGENT-DECISION: the card names no seed for the walking look; the bank's first seed # is used (a walking episode, so no running episode is seen before g_hat exists) RESULT_FILE = "calib.json" def sha256_of(path, chunk=1 << 20): h = hashlib.sha256() with open(path, "rb") as f: for block in iter(lambda: f.read(chunk), b""): h.update(block) return h.hexdigest() def progress(line): p = os.environ.get("BENCH_PROGRESS_FILE") if p: with open(p, "a") as f: f.write(f"{time.strftime('%H:%M:%S')} {line}\n") class KneeHook: """Instance-level hooks on the walker sub-environments' dm_control step and reset (no file is changed). step scales the right-knee entry by self.scale and clips; every control step's clip flag is kept, and every reset marks an episode start. When self.observer is set it is called with (inner, command) BEFORE the simulator steps.""" def __init__(self, inners, knee_index): self.scale, self.knee_index, self.observer = 1.0, knee_index, None self.flags, self.starts = [], [] for inner in inners: self._wrap(inner) def _wrap(self, inner): original_step, original_reset = inner.step, inner.reset def step(action): if np.shape(action) != (ACTUATORS,): raise RuntimeError(f"expected a {ACTUATORS}-vector command, got shape {np.shape(action)}") command, clipped = CL.scaled_command(action, self.knee_index, self.scale) if self.observer is not None: self.observer(inner, command) self.flags.append(clipped) return original_step(command) def reset(*args, **kwargs): self.starts.append(len(self.flags)) return original_reset(*args, **kwargs) inner.step, inner.reset = step, reset def take(self): """The flags recorded since the last take, split into episodes; then clears them.""" episodes = CL.split_episodes(self.flags, self.starts) self.flags, self.starts = [], [] return episodes def run_arm(name, scale, hook, agent, env, idx, saved_a, comp, out_dir): import bridge_adapt3 as BA hook.scale = scale if hook.flags or hook.starts: raise RuntimeError(f"{name}: control steps recorded outside an arm ({len(hook.flags)})") arm = {"arm": name, "scale": scale, "tasks": {}} for task in (RUN_TASK,) + RETENTION_TASKS: episodes = CL.EPISODES_BY_TASK[task] r = BA.evaluate(agent, env, idx[task], episodes, f"calib {name} {task}", BA.DEFAULT_EVAL_SEED) flags = hook.take() if len(flags) != episodes or any(len(f) != BA.EPISODE_DECISIONS * ACTION_REPEAT for f in flags): raise RuntimeError(f"{name} {task}: expected {episodes} episodes of {BA.EPISODE_DECISIONS * ACTION_REPEAT} " f"control steps, got {[len(f) for f in flags]}") per_episode = [CL.clip_fraction(f) for f in flags] r["clip_fraction_per_episode"] = per_episode r["clip_fraction"] = float(np.mean(per_episode)) saved = saved_a[task]["episodes"] r["vs_saved_A_block"] = CL.n_check(r["episodes"], saved) # identity check at scale 1; a difference otherwise arm["tasks"][task] = r print(f"{name} {task} mean {r['mean']:.1f} clip {r['clip_fraction']:.3f}", flush=True) if name != "N-check": arm["outcome"] = CL.outcome(arm["tasks"][RUN_TASK]["mean"], comp["Df_bar"], comp["N"], comp["T"]) CL.write_once(os.path.join(out_dir, "arms", f"{name}.json"), arm) # kept if a later arm crashes return arm def right_leg_geoms(model, mujoco): """Geom ids on the bodies of the right_thigh subtree (thigh, leg, foot).""" root = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_BODY, "right_thigh") assert root >= 0, "walker has no body right_thigh" bodies = set() for b in range(model.nbody): a = b while a > 0 and a != root: a = int(model.body_parentid[a]) if a == root: bodies.add(b) return {g for g in range(model.ngeom) if int(model.geom_bodyid[g]) in bodies} def contact_geoms(data): n = int(data.ncon) if n == 0: return [] c = data.contact if hasattr(c, "geom1"): return list(zip(np.asarray(c.geom1)[:n].tolist(), np.asarray(c.geom2)[:n].tolist())) g = np.asarray(c.geom)[:n] return [(int(a), int(b)) for a, b in g] def estimate(hook, agent, env, task_idx, healthy_gear, torch): """K-est's look: the first CL.EST_CONTROL_STEPS control steps of walking at scale 1. Returns (record, arrays).""" import mujoco import bridge_adapt3 as BA inner = BA.sub_env(env, task_idx) physics = inner.physics true_model = physics.model.ptr # the simulator (halved knee): steps the copy only healthy = copy.copy(true_model) assert healthy is not true_model act = mujoco.mj_name2id(healthy, mujoco.mjtObj.mjOBJ_ACTUATOR, CL.KNEE) jnt = mujoco.mj_name2id(healthy, mujoco.mjtObj.mjOBJ_JOINT, CL.KNEE) assert act >= 0 and jnt >= 0, "walker has no right_knee actuator or joint" assert int(healthy.jnt_type[jnt]) == int(mujoco.mjtJoint.mjJNT_HINGE), "right_knee is not a hinge" assert int(healthy.actuator_trnid[act, 0]) == jnt, "the right_knee actuator does not drive the right_knee hinge" healthy.actuator_gear[act, 0] = healthy_gear # the known healthy model (inverse dynamics does # not read the gear; set so the model is the healthy one) names = [mujoco.mj_id2name(true_model, mujoco.mjtObj.mjOBJ_ACTUATOR, i) for i in range(true_model.nu)] knee_index = names.index(CL.KNEE) dof = int(healthy.jnt_dofadr[jnt]) qadr = int(healthy.jnt_qposadr[jnt]) lower, upper = (float(x) for x in healthy.jnt_range[jnt]) right = right_leg_geoms(healthy, mujoco) limit_type = int(mujoco.mjtConstraint.mjCNSTR_LIMIT_JOINT) inv = mujoco.MjData(healthy) rows = {k: [] for k in ("qpos", "qvel", "qacc", "u", "f", "contact", "near_limit", "limit_row")} def observe(stepped, command): if stepped is not inner or len(rows["u"]) >= CL.EST_CONTROL_STEPS: return d = copy.copy(physics.data.ptr) # a copy: the simulator's own data is untouched d.ctrl[:] = np.asarray(command, dtype=np.float64) mujoco.mj_forward(true_model, d) # the acceleration the simulator applies to this state inv.qpos[:], inv.qvel[:], inv.qacc[:] = d.qpos, d.qvel, d.qacc mujoco.mj_inverse(healthy, inv) contact = any(a in right or b in right for a, b in contact_geoms(d)) limit_row = bool(np.any((np.asarray(d.efc_type)[:d.nefc] == limit_type) & (np.asarray(d.efc_id)[:d.nefc] == jnt))) rows["qpos"].append(np.array(d.qpos)); rows["qvel"].append(np.array(d.qvel)); rows["qacc"].append(np.array(d.qacc)) rows["u"].append(float(command[knee_index])); rows["f"].append(float(inv.qfrc_inverse[dof])) rows["contact"].append(contact); rows["near_limit"].append(CL.near_limit(float(d.qpos[qadr]), lower, upper) or limit_row) rows["limit_row"].append(limit_row) hook.scale, hook.observer = 1.0, observe BA.task_of(env, task_idx)._random = np.random.RandomState(EST_SEED) torch.manual_seed(EST_SEED); torch.cuda.manual_seed_all(EST_SEED) with BA.TrainingRng(): obs, done, t, walk_return = env.reset(task_idx=task_idx), False, 0, 0.0 while not done and len(rows["u"]) < CL.EST_CONTROL_STEPS: action = agent.act(obs, t0=t == 0, eval_mode=True, task=task_idx) obs, reward, done, info = env.step(action) walk_return += float(reward); t += 1 hook.observer = None hook.take() if len(rows["u"]) != CL.EST_CONTROL_STEPS: raise RuntimeError(f"recorded {len(rows['u'])} control steps, expected {CL.EST_CONTROL_STEPS}") keep, cuts = CL.sample_mask(rows["u"], rows["contact"], rows["near_limit"]) record = {"task": WALK_TASK, "seed": EST_SEED, "control_steps": CL.EST_CONTROL_STEPS, "decisions": t, "partial_walk_return": walk_return, "healthy_gear": healthy_gear, "force": "qfrc_inverse at the dof of " "hinge right_knee, nothing subtracted (mj_inverse, healthy model); qfrc_actuator never read", "qacc_source": "mj_forward on a copy of the simulator's data with the applied command, before each step", "knee_dof": dof, "knee_range": [lower, upper], "limit_margin_rad": CL.LIMIT_MARGIN_RAD, "min_abs_command": CL.MIN_ABS_COMMAND, "cuts": cuts, "limit_rows_active": int(sum(rows["limit_row"]))} try: record.update(CL.estimate_gain(rows["u"], rows["f"], keep)) record["scale"] = CL.k_est_scale(record["g_hat"], healthy_gear) except ValueError as e: record.update({"g_hat": None, "scale": None, "not_estimable": str(e)}) arrays = {k: np.asarray(v) for k, v in rows.items()} arrays["keep"] = keep progress(f"calib K-est estimation {CL.EST_CONTROL_STEPS} control steps, used {cuts['used']}, g_hat {record['g_hat']}") return record, arrays def run(cfg): import torch from common.parser import parse_cfg from common.seed import set_seed from envs import make_env from tdmpc2 import TDMPC2 import bridge_adapt3 as BA assert torch.cuda.is_available() cfg = parse_cfg(cfg) out_dir, gate_a_path, a_block_path = (str(cfg.get(k, "")) for k in ("out_dir", "gate_a", "a_block")) assert out_dir and gate_a_path and a_block_path, "pass +out_dir, +gate_a and +a_block" 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_a = a_record["A"] assert abs(saved_a[RUN_TASK]["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 assert float(a_record["gear_scale"]) == CL.CHANGED_KNEE_SCALE CL.claim_out_dir(out_dir) os.makedirs(os.path.join(out_dir, "arms")) set_seed(cfg.seed) env = make_env(cfg) # built as bridge_adapt3 builds it (training env first, never used here) 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)} healthy_gear = {g[0] for g in gears["eval_env"].values()} assert healthy_gear == {CL.HEALTHY_KNEE_GEAR}, f"healthy knee gear {healthy_gear}, expected {CL.HEALTHY_KNEE_GEAR}" inners = [BA.sub_env(eval_env, idx[t]) for t in (RUN_TASK, WALK_TASK) + RETENTION_TASKS] names = [inners[0].physics.model.id2name(i, "actuator") for i in range(inners[0].physics.model.nu)] assert len(names) == ACTUATORS, f"walker has {len(names)} actuators" hook = KneeHook(inners, names.index(CL.KNEE)) agent = TDMPC2(cfg) agent.load(cfg.checkpoint) BA.normalise_task_embeddings(agent) here = os.path.dirname(os.path.abspath(__file__)) out = {"script": "calib_check", "card": "ideas/IDEA-01-CALIBRATION-ONLY.md (revised kill test)", "checkpoint": cfg.checkpoint, "checkpoint_sha256": sha256_of(cfg.checkpoint), "seed": cfg.seed, "gears": gears, "actuators": names, "eval_seed": BA.DEFAULT_EVAL_SEED, "episodes": CL.EPISODES_BY_TASK, "progress_total": CL.progress_total(True), "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)}, "comparators": comp, "runner_sha256": {n: sha256_of(os.path.join(here, n)) for n in ("calib_check.py", "calib_logic.py", "bridge_adapt3.py")}, "started": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "arms": {}} out["arms"]["N-check"] = run_arm("N-check", 1.0, hook, agent, eval_env, idx, saved_a, comp, out_dir) n_ok = all(r["vs_saved_A_block"]["reproduces"] for r in out["arms"]["N-check"]["tasks"].values()) # run, stand # and walk-backwards, every episode of the A block out["arms"]["K2"] = run_arm("K2", CL.ORACLE_SCALE, hook, agent, eval_env, idx, saved_a, comp, out_dir) record, arrays = estimate(hook, agent, eval_env, idx[WALK_TASK], CL.HEALTHY_KNEE_GEAR, torch) CL.write_once(os.path.join(out_dir, "estimation.json"), record) with open(os.path.join(out_dir, "estimation.npz"), "xb") as f: np.savez_compressed(f, **arrays) out["estimation"] = record print(f"K-est g_hat {record['g_hat']} scale {record['scale']} steps used {record['cuts']['used']}", flush=True) if record["scale"] is not None: out["arms"]["K-est"] = run_arm("K-est", record["scale"], hook, agent, eval_env, idx, saved_a, comp, out_dir) out["n_check_reproduces"] = n_ok out["readable"] = bool(n_ok) # a scale-1 run that misses the saved A block means a different evaluation path out["outcomes"] = {a: out["arms"][a]["outcome"] for a in ("K2", "K-est") if a in out["arms"]} out["finished"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) CL.write_once(os.path.join(out_dir, RESULT_FILE), out) for a, o in out["outcomes"].items(): print(f"{a}: walker-run {out['arms'][a]['tasks'][RUN_TASK]['mean']:.1f} -> {o}", flush=True) print("N-check reproduces" if n_ok else "N-CHECK FAILED: outcomes not readable", "written", os.path.join(out_dir, RESULT_FILE), flush=True) if __name__ == '__main__': os.environ['MUJOCO_GL'] = os.getenv("MUJOCO_GL", 'egl') import hydra hydra.main(config_name='config', config_path='.')(run)()