File size: 18,905 Bytes
68d3a5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
"""told_check.py: the GPU job of idea card 03 (ideas/IDEA-03-PLANNER-TOLD-GEAR.md, repaired test; binding).

Does a planner that is TOLD the gear match Df? The released MT30 48M checkpoint, weights frozen (no update anywhere), on
the halved right knee (gear 50 to 25, bridge_adapt3.apply_change), evaluated through the bridge evaluator itself
(bridge_adapt3.evaluate: eval_mode=True, episode i re-seeds resets and planner noise with 1000 + i). The told-gear
constrained planner replaces the agent's cached plan function (agent._plan_val, read by the upstream `plan` property)
and wraps model.pi; no upstream file is changed. In model space the knee is held to [-0.5, 0.5] at every clamp site
(told_logic.CLAMP_SITES); idea 01's knee hook doubles only the knee entry of the command entering the simulator.

Order (one process), every check feeding validity (any failure makes the outcome INVALID):
  0. Refusals: mpc must be on; the loaded tdmpc2.py must be the pinned md5 (so the clamp-site lines hold).
  1. Torque check: on the walker's own simulator state, the healthy model (gear 50) with knee command m and the changed
     simulator (gear 25) with 2 m give the same knee actuator force, for m in {+0.5, -0.5, 0.3, -0.3, 0.0}.
  2. identity: the replica planner with the FULL box (half = 1) and hook scale 1 must reproduce the saved A block's ten
     running episodes (the scale-one identity: the replica is the released planner).
  3. K-plan: half = 0.5, hook scale 2: ten running episodes; no control step may clip and |u_k| <= 1 everywhere.
Outcome: told_logic.outcome against Df_bar, N and T from the saved Gate A reading; paired episode differences against
each seed's saved Df running-after episodes.

    python told_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/told +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

21 progress lines (BENCH_PROGRESS_FILE). Outputs written once (mode 'x') into an empty out_dir: resolved_config.json,
torque_check.json, arms/<arm>.json, told.json.
"""
import dataclasses
import hashlib
import json
import os
import time

import numpy as np

import calib_logic as CL
import told_logic as TL
from calib_check import KneeHook, progress, sha256_of

RESULT_FILE = "told.json"
SEEDS = CL.GATE_A_SEEDS


def md5_of(path):
    return hashlib.md5(open(path, "rb").read()).hexdigest()


class ToldPlanner:
    """Installs the told-gear constrained planner on an agent. With half = 1 it is the released planner (the identity
    arm proves it). Counts its calls so the run record shows it was the planner in use."""

    def __init__(self, agent, knee_index, torch):
        self.agent, self.knee_index, self.torch = agent, knee_index, torch
        self.original_pi = agent.model.pi
        self.calls, self.pi_calls, self.half = 0, 0, None
        self.originals = {n: getattr(agent.model, n) for n in ("next", "reward", "Q")}
        for n in self.originals:                          # observe the knee action every model call receives (Fable M1)
            setattr(agent.model, n, self._observed(n))
        self.reset_observations()

    def reset_observations(self):
        self.model_knee_max = self.torch.zeros((), device=self.agent.device)
        self.model_calls = 0
        self.decision_knee = []                           # the model-space knee action returned per decision

    def _observed(self, name):
        original = self.originals[name]

        def call(z, a, *args, **kwargs):
            self.model_calls += 1
            self.model_knee_max = self.torch.maximum(self.model_knee_max, a[..., self.knee_index].abs().max())
            return original(z, a, *args, **kwargs)
        return call

    def install(self, half):
        torch, cfg, dev = self.torch, self.agent.cfg, self.agent.device
        low, high = TL.box(cfg.action_dim, self.knee_index, half)
        smin, smax = TL.std_bounds(cfg.min_std, cfg.max_std, cfg.action_dim, self.knee_index, half)
        self.low, self.high = (torch.tensor(v, dtype=torch.float32, device=dev) for v in (low, high))
        self.smin, self.smax = (torch.tensor(v, dtype=torch.float32, device=dev) for v in (smin, smax))
        self.half = half
        self.agent.model.pi = self.pi
        self.agent._plan_val = self.plan              # the upstream `plan` property returns this cached function

    def proj(self, x):
        return self.torch.maximum(self.torch.minimum(x, self.high), self.low)

    def pi(self, z, task):
        self.pi_calls += 1
        action, info = self.original_pi(z, task)
        info["mean"] = self.proj(info["mean"])
        return self.proj(action), info

    def plan(self, obs, t0=False, eval_mode=False, task=None):
        """tdmpc2.py _plan (pinned e9f5932, lines 139-206) with the told box at every clamp site. Random draws are the
        same calls in the same order as upstream, so with half = 1 the actions are the released planner's."""
        torch, agent, cfg = self.torch, self.agent, self.agent.cfg
        from common import math as tmath
        self.calls += 1
        with torch.no_grad():
            z = agent.model.encode(obs, task)
            if cfg.num_pi_trajs > 0:
                pi_actions = torch.empty(cfg.horizon, cfg.num_pi_trajs, cfg.action_dim, device=agent.device)
                _z = z.repeat(cfg.num_pi_trajs, 1)
                for t in range(cfg.horizon - 1):
                    pi_actions[t], _ = agent.model.pi(_z, task)          # wrapped: projected (site 1)
                    _z = agent.model.next(_z, pi_actions[t], task)
                pi_actions[-1], _ = agent.model.pi(_z, task)
            z = z.repeat(cfg.num_samples, 1)
            mean = torch.zeros(cfg.horizon, cfg.action_dim, device=agent.device)
            std = self.smax.expand(cfg.horizon, cfg.action_dim).clone()  # upstream: full of max_std
            if not t0:
                mean[:-1] = agent._prev_mean[1:]
            mean = self.proj(mean)                                        # site 3 (shifted _prev_mean)
            actions = torch.empty(cfg.horizon, cfg.num_samples, cfg.action_dim, device=agent.device)
            if cfg.num_pi_trajs > 0:
                actions[:, :cfg.num_pi_trajs] = pi_actions
            for _ in range(cfg.iterations):
                r = torch.randn(cfg.horizon, cfg.num_samples - cfg.num_pi_trajs, cfg.action_dim, device=std.device)
                actions_sample = self.proj(mean.unsqueeze(1) + std.unsqueeze(1) * r)    # site 2
                actions[:, cfg.num_pi_trajs:] = actions_sample
                if cfg.multitask:
                    actions = actions * agent.model._action_masks[task]
                value = agent._estimate_value(z, actions, task).nan_to_num(0)   # bootstrap pi wrapped (site 5)
                elite_idxs = torch.topk(value.squeeze(1), cfg.num_elites, dim=0).indices
                elite_value, elite_actions = value[elite_idxs], actions[:, elite_idxs]
                max_value = elite_value.max(0).values
                score = torch.exp(cfg.temperature * (elite_value - max_value))
                score = score / score.sum(0)
                mean = (score.unsqueeze(0) * elite_actions).sum(dim=1) / (score.sum(0) + 1e-9)
                std = ((score.unsqueeze(0) * (elite_actions - mean.unsqueeze(1)) ** 2).sum(dim=1) / (score.sum(0) + 1e-9)).sqrt()
                std = torch.maximum(torch.minimum(std, self.smax), self.smin)   # site 3 (std per coordinate)
                mean = self.proj(mean)                                           # site 3 (elite mean)
                if cfg.multitask:
                    mean = mean * agent.model._action_masks[task]
                    std = std * agent.model._action_masks[task]
            rand_idx = tmath.gumbel_softmax_sample(score.squeeze(1))
            actions = torch.index_select(elite_actions, 1, rand_idx).squeeze(1)
            a, std = actions[0], std[0]
            if not eval_mode:
                a = a + std * torch.randn(cfg.action_dim, device=std.device)
            agent._prev_mean.copy_(mean)
            a = self.proj(a)                                              # site 4 (final action)
            self.decision_knee.append(a[self.knee_index])
            return a


def executed_matches(decision_knee, commands, scale, tol=1e-5):
    """Each decision's knee action reaches the simulator on both of its control steps as scale times the model value."""
    model = [float(x) for x in decision_knee]
    if len(commands) != 2 * len(model) or not model:
        return False
    return all(abs(commands[2 * i] - scale * m) <= tol and abs(commands[2 * i + 1] - scale * m) <= tol
               for i, m in enumerate(model))


def torch_max_abs(values):
    return max((abs(float(v)) for v in values), default=float("nan"))


def torque_check(inner, knee_name, mujoco):
    """The healthy model with m and the changed simulator with 2 m give the same knee actuator force on one state."""
    import copy
    changed = inner.physics.model.ptr
    healthy = copy.copy(changed)
    act = mujoco.mj_name2id(healthy, mujoco.mjtObj.mjOBJ_ACTUATOR, knee_name)
    jnt = mujoco.mj_name2id(healthy, mujoco.mjtObj.mjOBJ_JOINT, knee_name)
    assert act >= 0 and jnt >= 0, "walker has no right_knee actuator or joint"
    gear_changed = float(changed.actuator_gear[act, 0])
    healthy.actuator_gear[act, 0] = TL.HEALTHY_KNEE_GEAR
    dof = int(healthy.jnt_dofadr[jnt])
    rows = []
    for m in (0.5, -0.5, 0.3, -0.3, 0.0):
        forces = []
        for model, command in ((healthy, m), (changed, TL.EXEC_FACTOR * m)):
            d = copy.copy(inner.physics.data.ptr)
            d.ctrl[:] = 0.0
            d.ctrl[act] = command
            mujoco.mj_forward(model, d)
            forces.append(float(d.qfrc_actuator[dof]))
        rows.append({"m": m, "healthy_force": forces[0], "changed_force": forces[1],
                     "equal": abs(forces[0] - forces[1]) <= TL.TORQUE_TOLERANCE * max(1.0, abs(forces[0]))})
    return {"changed_gear": gear_changed, "healthy_gear": TL.HEALTHY_KNEE_GEAR, "rows": rows,
            "passes": gear_changed == TL.HEALTHY_KNEE_GEAR * TL.CHANGED_KNEE_SCALE and all(r["equal"] for r in rows)}


def run_arm(name, half, scale, planner, hook, agent, env, idx, out_dir):
    import bridge_adapt3 as BA
    planner.install(half)
    planner.reset_observations()
    hook.scale = scale
    commands = []
    hook.observer = lambda inner, command: commands.append(float(command[hook.knee_index]))
    calls_before = planner.calls
    r = BA.evaluate(agent, env, idx[TL.RUN_TASK], TL.RUN_EPISODES, f"told {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]}")
    arm = {"arm": name, "half": half, "hook_scale": scale, "task": TL.RUN_TASK, "result": r,
           "planner_calls": planner.calls - calls_before, "clipped_steps": int(sum(sum(map(bool, f)) for f in flags)),
           "max_abs_executed_knee": float(np.max(np.abs(commands))) if commands else None,
           "control_steps": len(commands), "model_calls": planner.model_calls,
           "max_abs_model_knee_seen_by_model": float(planner.model_knee_max.item()),
           "max_abs_model_knee_returned": float(torch_max_abs(planner.decision_knee)),
           "decisions_logged": len(planner.decision_knee),
           "executed_matches_scale_times_model": executed_matches(planner.decision_knee, commands, scale)}
    with open(os.path.join(out_dir, "arms", f"{name}.npz"), "xb") as f:   # per step: model-space and executed knee
        np.savez_compressed(f, model_knee_per_decision=np.array([float(x) for x in planner.decision_knee]),
                            executed_knee_per_control_step=np.array(commands))
    CL.write_once(os.path.join(out_dir, "arms", f"{name}.json"), arm)
    print(f"{name} {TL.RUN_TASK} mean {r['mean']:.1f} clipped {arm['clipped_steps']} max|u| {arm['max_abs_executed_knee']}", 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()
    cfg = parse_cfg(cfg)
    if not cfg.mpc:
        raise SystemExit("REFUSED: the told planner needs mpc=true (the non-MPC action path is rejected, card 03)")
    tdmpc2_md5 = md5_of(upstream.__file__)
    if tdmpc2_md5 != TL.PINNED_TDMPC2_MD5:
        raise SystemExit(f"REFUSED: {upstream.__file__} 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)
        assert int(rec["seed"]) == s and int(rec["eval_seed"]) == BA.DEFAULT_EVAL_SEED, f"{p}: wrong seed or bank"
        after = rec["after"][TL.RUN_TASK]
        assert abs(float(after["mean"]) - comp["Df_running_after_by_seed"][s]) < 1e-6, f"{p} disagrees with the Gate A reading"
        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)                 # 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)}
    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)
    planner = ToldPlanner(agent, knee_index, torch)
    here = os.path.dirname(os.path.abspath(__file__))
    out = {"script": "told_check", "card": "ideas/IDEA-03-PLANNER-TOLD-GEAR.md (repaired test)",
           "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,
           "episodes": TL.RUN_EPISODES, "progress_total": TL.progress_total(), "tdmpc2_md5": tdmpc2_md5,
           "clamp_sites": TL.CLAMP_SITES, "std_rule": "knee min_std and max_std scaled by the box half; others unchanged",
           "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_check.py", "told_logic.py", "calib_check.py", "calib_logic.py", "bridge_adapt3.py")},
           "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"told torque check {'passes' if torque['passes'] else 'FAILS'}")
    hook.take()
    out["torque_check"] = torque
    ident = run_arm("identity", 1.0, 1.0, planner, 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
    kplan = run_arm("K-plan", TL.HALF_BOX, TL.EXEC_FACTOR, planner, hook, agent, eval_env, idx, out_dir)
    out["arms"]["K-plan"] = kplan
    checks = {"torque_check": torque["passes"],
              "identity_reproduces_A_block": ident["vs_saved_A_block"]["reproduces"],
              "told_planner_in_use": ident["planner_calls"] > 0 and kplan["planner_calls"] > 0 and planner.pi_calls > 0,
              "no_clipped_step": kplan["clipped_steps"] == 0,
              "model_knee_within_box": kplan["model_calls"] > 0 and kplan["max_abs_model_knee_seen_by_model"] <= TL.HALF_BOX + 1e-6
                                       and kplan["max_abs_model_knee_returned"] <= TL.HALF_BOX + 1e-6,
              "executed_is_twice_model": kplan["executed_matches_scale_times_model"]
                                         and kplan["decisions_logged"] == TL.RUN_EPISODES * BA.EPISODE_DECISIONS,
              "identity_executed_equals_model": ident["executed_matches_scale_times_model"]}
    out["checks"] = checks
    out["replica_test"] = ("the identity arm is the replica planner's test: bit-equal actions at half = 1 reproduce the saved "
                           "A block per episode on the GPU; no CPU fake-agent test was written (Fable M2, accepted)")
    out["valid"] = all(checks.values())
    mean = float(kplan["result"]["mean"])
    out["outcome"] = TL.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["K2_reference"] = "idea 01 K2 414.4 (reported beside, never in the outcome)"
    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-plan: walker-run {mean:.1f} -> {out['outcome']}", flush=True)
    print("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)()