File size: 20,599 Bytes
1c78d11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
321
322
323
324
325
326
327
328
329
330
331
332
333
"""Harness wrapper for gen_q#274 configuration (b): TD-MPC2's MPPI/CEM planner in the RISE eval loop.

Installed the same way the Diffusion Forcing planner is (code/df_rise/df_policy.py): by replacing
`get_action` on the ALREADY CONSTRUCTED robomimic policy object.  No harness file is edited beyond the
one additive env-var block in sim_pipeline/eval/eval.py, which keeps this stream out of gen_q#273's
way in rsm_planner.py / rsm_scorer.py.

THE PRIOR IS THE RISE ACTOR, and it is drawn through the host policy's OWN released sampler
(`_sample_action_chunks`, the DDPM/DDIM chain), from the SAME observation, in the same units -- so the
prior trajectories here are drawn from exactly the distribution the 128 candidates of every value
column are drawn from.  If the sampler cannot be reached on the host object we RAISE rather than
silently falling back to TD-MPC2's own actor, because a cell that quietly ran with `model.pi` is
configuration (b) in name only.

CADENCE.  `execute_frames` actions are executed per plan, then we replan.  The default is
min(8, plan_horizon) -- the whole optimised window, capped at the project's 8-frame chunk -- which is
3 at the default plan_horizon=3, because that is the horizon the world models are trained at.  So
this row does NOT commit at the value columns' 8-frame cadence: it replans ~2.7x more often, which is
extra search and is disclosed as such (tab:searchsize).  `execute_frames=1` is upstream's own
receding-horizon cadence and is available.  Whichever is used is in the cell JSON, and the
per-episode plan count (hence the true search budget) follows from it.
"""
from __future__ import annotations

import json
import sys
from pathlib import Path

import numpy as np
import torch

sys.path.insert(0, str(Path(__file__).resolve().parent))

from td_backend import load_td_world_model                       # noqa: E402
from td_plan import TDMPC2Planner                                # noqa: E402


class TDMPC2PlannerPolicy:
    """Replaces `get_action` on a robomimic policy.  Same signature, same units, same cadence knob."""

    def __init__(self, host, ckpt, feat_stats, *, plan_horizon=3, num_samples=512, num_elites=64,
                 iterations=6, num_pi_trajs=24, temperature=0.5, min_std=0.05, max_std=2.0,
                 select="mean", execute_frames=None, device="cuda", seed=0, img_layout="chw",
                 act_limit=1.0, diag_path="", prior_src="rise_actor"):
        # gen_q#274 run 31.  WHICH POLICY PRIOR SEEDS MPPI.  Added because of a MEASURED structural
        # limit, not a preference: LSF 1893275 slot0, 07:17Z, cfg(b) Hp=16 with the RISE actor as
        # prior died at `_prior_actions` with
        #     "the actor's executed window is 8 frames but the planner horizon is 16"
        # The RISE actor emits an 8-frame executed chunk (rsm_planner._executed_window, Ta =
        # algo_config.horizon.action_horizon), so with OUR actor as the prior cfg(b) can never
        # optimise past 8 of the H=1/(1-0.95)=20 frames it is compared over.  That is a property of
        # the configuration and it is disclosed; it is not worked around by extending the actor's
        # chunk, which would be a bespoke mechanism.
        #   prior_src="rise_actor" (DEFAULT, unchanged)  the issue's own cfg(b): our actor seeds MPPI.
        #   prior_src="tdmpc2"     TD-MPC2's OWN learned prior (`model.pi`, td_plan.py:144-152) --
        #                          upstream's published design, so it is the faithful way to run a
        #                          horizon our actor structurally cannot cover.
        #   prior_src="none"       num_pi_trajs forced to 0: pure CEM, no prior at all.  The ablation
        #                          that says what the prior is worth at a matched search budget.
        # The planner already writes which prior actually ran into every cell JSON ("rise_actor" /
        # "tdmpc2_pi" / "none"), so a cell can never be read as cfg(b)-with-our-actor by mistake.
        if prior_src not in ("rise_actor", "tdmpc2", "none"):
            raise ValueError(f"prior_src={prior_src!r} must be rise_actor|tdmpc2|none")
        self.prior_src = prior_src
        if prior_src == "none":
            num_pi_trajs = 0
        from robomimic.algo.rsm_scorer import PooledDinoState
        self.host = host
        self.model, self.cfg, self.gamma, self.step, self.train_cache = \
            load_td_world_model(ckpt, device)
        import inspect
        _kw = {"img_layout": img_layout} \
            if "img_layout" in inspect.signature(PooledDinoState.__init__).parameters else {}
        self.enc = PooledDinoState(feat_stats, **_kw).to(device).eval()
        self.planner = TDMPC2Planner(self.model, self.cfg, self.gamma, plan_horizon=plan_horizon,
                                     num_samples=num_samples, num_elites=num_elites,
                                     iterations=iterations, num_pi_trajs=num_pi_trajs,
                                     temperature=temperature, min_std=min_std, max_std=max_std,
                                     select=select, device=device)
        self.device = device
        self.Hp = int(plan_horizon)
        # CADENCE DEFAULT (corrected 2026-09-23 12:4xZ).  The docstring below used to say the default
        # was 8, "the project's chunk" -- but the world models are trained at TD-MPC2's own
        # horizon=3 (train_tdmpc2.py:129), and the guard right underneath forbids executing past the
        # optimised window, so execute_frames=8 with the default plan_horizon=3 could only ever
        # RAISE.  The default is therefore the whole optimised window, capped at the project chunk:
        # min(8, Hp).  It is 3 at the defaults, which means configuration (b) commits 3 frames per
        # decision where every value column commits 8 -- i.e. ~2.7x MORE decisions per episode.  That
        # is a search-budget difference, not a modelling one, and it is disclosed in tab:searchsize.
        self.execute_frames = int(execute_frames) if execute_frames is not None else min(8, self.Hp)
        if not 1 <= self.execute_frames <= self.Hp:
            raise ValueError(f"execute_frames={self.execute_frames} must be in [1, plan_horizon={self.Hp}]: "
                             f"executing past the optimised window would run actions MPPI never scored")
        self.gen = torch.Generator(device=device); self.gen.manual_seed(int(seed))
        self.diag_path = diag_path
        self._prev_means = None
        self.act_limit = float(act_limit)
        self.reset()

    def reset(self):
        self._diag = []
        self._a_absmax = 0.0
        self._n_act = 0
        self._n_clip = 0
        self.planner.reset()

    # ---- the RISE actor, used as the MPPI policy prior ---------------------
    @torch.no_grad()
    def _prior_actions(self, obs_dict, goal_dict, n):
        """n RISE-actor chunks from THIS observation -> [Hp, n, adim], the MPPI prior."""
        sample = getattr(self.host, "_sample_action_chunks", None)
        if sample is None:
            raise RuntimeError(
                "gen_q#274 configuration (b) needs the RISE actor as its policy prior, but the host "
                f"policy {type(self.host).__name__} has no `_sample_action_chunks`.  Refusing to fall "
                "back to TD-MPC2's own actor: that would be a different row.")
        rep = {k: v.repeat_interleave(n, 0) for k, v in obs_dict.items()}
        rep_goal = None if goal_dict is None else {k: v.repeat_interleave(n, 0) for k, v in goal_dict.items()}
        naction = sample(rep, rep_goal)                                  # [B*n, Tp, adim]
        win, _ = self.host._executed_window(naction)                     # [B*n, Ta, adim]
        if win.shape[1] < self.Hp:
            raise RuntimeError(f"the actor's executed window is {win.shape[1]} frames but the planner "
                               f"horizon is {self.Hp}: the prior cannot cover the optimised window. "
                               f"This is a structural limit of configuration (b) as the issue defines "
                               f"it, and it is reported rather than worked around; to run this horizon "
                               f"honestly use RR_TD_PRIOR=tdmpc2 (TD-MPC2's own published prior) or "
                               f"RR_TD_PRIOR=none (pure CEM), both of which name themselves in the "
                               f"cell name and in the cell JSON's `prior` field.")
        return win[:, :self.Hp]                                          # [B*n, Hp, adim]

    # ---- resume state (gen_q#274 run 49-main; FINDING AK) -----------------
    # WHY THIS EXISTS.  FINDING AJ (stream DF_MAKEITWORK, 2026-09-24 20:36Z) fixed the DF half of
    # the episode-level resume: the plan sampler's torch.Generator and the planner health
    # accumulators were not carried, so a resumed cell replayed its tail with the wrong noise and
    # published health over [k:] while its success rate covered [0:].  The fix in eval.py reaches a
    # planner through `_rr_df_planner` ONLY, so configuration (b) -- which owns the SAME two kinds
    # of state -- was never covered:
    #     self.gen              a per-cell torch.Generator (__init__), the MPPI noise stream
    #     self._diag            the per-plan health records, which diagnostics() averages
    #     self._n_act/_n_clip/_a_absmax   the published action-clipping health
    #     self.planner._prev_mean         upstream TD-MPC2's warm start, carried plan to plan
    # `install()` wraps start_episode with reset(), but this harness has no start_episode call site
    # (df_policy.py:422-425), so all four accumulate across the WHOLE cell and a resume at k
    # restarts them from zero.  MEASURED consequence, status/nb/resume_audit.json: four landed
    # cfg(b) cells published 38%/44%/48%/96% health coverage and are marked NOT QUOTABLE in
    # status/nb/td_table.txt.  A FRESH run never calls state_load, so no landed cell's number moves.
    @staticmethod
    def _json_safe(rec):
        """A diag record with every value a JSON scalar.

        td_plan.py's `diag` already wraps every value in float()/int()/str(), so this is a no-op
        today.  It exists because this dict is now written into the .partial on every episode
        boundary: if a future diagnostic added a numpy scalar or a tensor, an unguarded json.dump
        would raise INSIDE the snapshot and kill a RUNNING cell.  Resume scaffolding must never be
        able to do that.
        """
        out = {}
        for k, v in rec.items():
            if v is None or isinstance(v, (bool, int, float, str)):
                out[str(k)] = v
            elif isinstance(v, (np.bool_,)):
                out[str(k)] = bool(v)
            elif isinstance(v, (np.integer,)):
                out[str(k)] = int(v)
            elif isinstance(v, (np.floating,)):
                out[str(k)] = float(v)
            else:
                out[str(k)] = str(v)
        return out

    @staticmethod
    def _t_dump(t):
        """A float tensor -> JSON-safe raw bytes, so the restore is EXACT and not a repr round-trip."""
        if t is None:
            return None
        a = t.detach().cpu().contiguous().numpy()
        return {"hex": a.tobytes().hex(), "shape": list(a.shape), "dtype": str(a.dtype)}

    def _t_load(self, d):
        if not d:
            return None
        a = np.frombuffer(bytes.fromhex(str(d["hex"])), dtype=np.dtype(str(d["dtype"])))
        return torch.from_numpy(a.reshape(tuple(int(x) for x in d["shape"])).copy()).to(self.device)

    def state_dump(self):
        """Everything of this planner that a resumed process must not restart from scratch."""
        return {
            "gen_device": str(self.device),
            # get_state() is a uint8 ByteTensor and does NOT advance the stream, so snapshotting it
            # every episode costs a fresh run nothing and changes nothing.
            "gen_state_hex": bytes(self.gen.get_state().cpu().numpy().tobytes()).hex(),
            "n_act": int(self._n_act),
            "n_clip": int(self._n_clip),
            "a_absmax": float(self._a_absmax),
            "prev_mean": self._t_dump(getattr(self.planner, "_prev_mean", None)),
            # the per-PLAN records verbatim, so the restored aggregate is computed by diagnostics()
            # over the same records in the same order a fresh run would have had -- the resumed
            # cell's health is IDENTICAL, not merely close.
            "diag": [self._json_safe(d) for d in self._diag],
        }

    def state_load(self, d):
        """Restore a state_dump().  True on success; False leaves the planner untouched."""
        if not isinstance(d, dict) or not d.get("gen_state_hex"):
            return False
        # Parse EVERYTHING before mutating anything, so a malformed snapshot leaves this planner in
        # its fresh-from-__init__ state (the old, warned-about behaviour) rather than half-restored.
        try:
            raw = bytes.fromhex(str(d["gen_state_hex"]))
            st = torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone()
            n_act, n_clip = int(d.get("n_act", 0)), int(d.get("n_clip", 0))
            a_absmax, diag = float(d.get("a_absmax", 0.0)), list(d.get("diag") or [])
            if not all(isinstance(r, dict) for r in diag):
                raise ValueError("diag is not a list of records")
            prev_mean = self._t_load(d.get("prev_mean"))
            self.gen.set_state(st)
        except Exception as ex:
            print(f"[gen_q#274] TD-MPC2 resume: cannot restore the MPPI sampler's state ({ex!r}) -- "
                  f"NOT restored")
            return False
        self._n_act, self._n_clip, self._a_absmax, self._diag = n_act, n_clip, a_absmax, diag
        self.planner._prev_mean = prev_mean
        return True

    def diagnostics(self):
        out = dict(self.planner.describe())
        out.update(prior_src=self.prior_src,
                   execute_frames=self.execute_frames, td_train_step=self.step,
                   train_cache=self.train_cache, plans=len(self._diag),
                   bypassed_planner=getattr(self, "bypassed_planner", None),
                   act_absmax=self._a_absmax,
                   act_clip_frac=(self._n_clip / self._n_act) if self._n_act else None,
                   act_components=self._n_act)
        out.update(__import__("td_env_pin").describe())   # gen_q#274: see td_env_pin.py
        if self._diag:
            for k in ("J_mean", "J_std", "J_spread", "J_gain", "prior_elite_frac",
                      "J_elite_first", "J_elite_last",
                      # run 46 (#274 run-43 next-action (e)): the J_elite DECOMPOSITION.  Averaged
                      # over plans exactly like J_elite_first/last are, so `rsum + termq` still
                      # equals `J_elite_*` after averaging (the mean is linear).  `.get` with a
                      # skip, not `d[k]`, so a diag recorded by the PRE-PATCH planner -- a plan
                      # replayed from an older pickle, or a future planner that does not decompose
                      # -- cannot take the whole diagnostics() call down with a KeyError.
                      "J_elite_rsum_first", "J_elite_termq_first",
                      "J_elite_rsum_last", "J_elite_termq_last",
                      "J_rsum_ceil", "J_termq_ceil"):
                vals = [d[k] for d in self._diag if k in d]
                if len(vals) != len(self._diag):
                    out[k + "_n_missing"] = len(self._diag) - len(vals)
                if vals:
                    out[k] = float(np.mean(vals))
            out["J_spread_frac_zero"] = float(np.mean([d["J_spread"] <= 1e-8 for d in self._diag]))
            out["J_gain_frac_nonpositive"] = float(np.mean([d["J_gain"] <= 0 for d in self._diag]))
            out["prior"] = self._diag[-1]["prior"]
        if self.diag_path:
            Path(self.diag_path).write_text(json.dumps(out, indent=2))
        return out

    # ---- the harness entry point -----------------------------------------
    @torch.no_grad()
    def get_action(self, obs_dict, goal_dict=None):
        """obs_dict [B, To, ...] as robomimic hands it to the released get_action.

        RETURNS AN ACTION CHUNK [B, execute_frames, ACT_DIM] -- the SAME contract df_policy.py
        returns under and the one every IDQL cell in this project already runs under.  Measured
        2026-09-23 16:11Z (LSF 1883253 slot1): returning a single [B, ACT_DIM] action killed all
        three cfg(b) smoke attempts at
            rollout_policies/robomimic_sampling_rollout_policy.py:94  actions = actions[:, 0, :]
            IndexError: too many indices for tensor of dimension 2
        which is the identical crash df_policy.py hit at 13:35Z and fixed the same way.  The private
        `_queue` that used to live here is GONE: `rollout.py:174-179` queues `actions[:, i]` over the
        chunk axis, so the HARNESS owns the execute-k-then-replan cadence.  Keeping a second queue in
        here would have made cfg(b) replan on a schedule no other column uses.
        """
        obs_t = {k: v[:, -1] for k, v in obs_dict.items()}
        x = self.enc(obs_t)                                          # [B, 1545]
        B = x.shape[0]
        n = self.planner.num_pi_trajs
        # run 31: only prior_src="rise_actor" hands MPPI our actor's chunks.  Under "tdmpc2" we pass
        # None with num_pi_trajs still > 0, which is td_plan.py's documented path for upstream's own
        # `model.pi` prior; under "none" num_pi_trajs is already 0 so no prior is drawn at all.
        prior = (self._prior_actions(obs_dict, goal_dict, n)
                 if (n > 0 and self.prior_src == "rise_actor") else None)
        acts = []
        for b in range(B):
            pi_b = None if prior is None else prior[b * n:(b + 1) * n].permute(1, 0, 2)
            a_b, diag = self.planner.plan(x[b:b + 1], pi_actions=pi_b, generator=self.gen)
            self._diag.append(diag)
            acts.append(a_b)
        chunk = torch.stack(acts, 0)[:, :self.execute_frames]        # [B, execute, adim]
        # the planner already clamps to the env box; these counters are the published health number
        # that says whether the trajectory MPPI scored is the trajectory the env actually executed.
        L = self.act_limit
        self._a_absmax = max(self._a_absmax, float(chunk.abs().max()))
        self._n_act += int(chunk.numel())
        self._n_clip += int((chunk.abs() > L).sum())
        if self.diag_path:                # flush every plan: an eval that dies still has its health
            self.diagnostics()
        return chunk.clamp(-L, L).contiguous()


def install(policy, **kw):
    """Monkey-patch an already-built robomimic RolloutPolicy so the harness runs TD-MPC2's planner."""
    inner = getattr(policy, "policy", policy)
    td = TDMPC2PlannerPolicy(inner, **kw)
    # gen_q#274, disclosure guard -- the same one df_policy.install carries, and the reason cfg(b)
    # needs `training.plan_n=1` on its command line.  Replacing `get_action` SHADOWS the cell's own
    # ranked planner; if plan_n were left >1 the harness would repeat the observation plan_n times
    # and the RISE critic would argmax over the rows AFTER MPPI chose them, so the row would be
    # "TD-MPC2's planner, re-ranked by our critic" while being printed as configuration (b).
    try:
        _pn = inner.planner_cfg().get("plan_n") if hasattr(inner, "planner_cfg") else None
        _on = bool(getattr(inner, "planning_enabled", False))
    except Exception:
        _pn, _on = None, False
    td.bypassed_planner = dict(plan_n=_pn, planning_was_enabled=_on)
    if _on:
        print(f"[gen_q#274] TD-MPC2 planner BYPASSES the cell's own ranked planner (plan_n={_pn}); "
              f"no RSM/IQL scorer contributes to this row -- MPPI proposes and selects.")
    # gen_q#274 run 49-main (FINDING AK): the handle eval.py's resume reaches this planner through,
    # the exact twin of df_policy.py:425 `inner._rr_df_planner = df`.  Without it the episode-level
    # resume cannot carry the MPPI noise stream or the planner health, and a resumed cfg(b) cell
    # publishes suffix-only health beside an all-episodes score (status/nb/resume_audit.json).
    inner._rr_td_planner = td
    inner.get_action = td.get_action
    if hasattr(policy, "start_episode"):
        _orig = policy.start_episode
        def start_episode(*a, **k):
            td.reset()
            return _orig(*a, **k)
        policy.start_episode = start_episode
    return td