File size: 14,967 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
"""TD-MPC2 as a PLANNER -- gen_q#274 configuration (b), the MPPI/CEM row seeded by our RISE actor.

WHAT THIS ROW IS, said plainly here and repeated in the caption wherever its number appears.
Configuration (a) (td_backend.py) keeps RISE's proposer and only swaps the ranking function, so it is
close to "DINO-WM plus a value head".  THIS row is TD-MPC2 acting as TD-MPC2 does: it runs upstream's
own MPPI/CEM loop (`tdmpc2.py:_plan`, reproduced below step for step) over its learned latent
dynamics, and it PROPOSES ITS OWN ACTIONS.  The one thing we change -- and #274 explicitly licenses
it as our own design -- is the POLICY PRIOR: upstream seeds `num_pi_trajs` of its samples from its
own learned actor `model.pi`; we seed them from OUR RISE diffusion actor instead, which is the same
proposer every other column in the table uses.  That makes this row "TD-MPC2's search on top of our
proposer" rather than "a differently-trained policy", and it is the version that can be read against
the value columns without confounding search with the proposal distribution.

SEARCH BUDGET, disclosed -- this row is NOT a 128-candidate column and must never be printed beside
one without these numbers (#274's search-size disclosure, and the reason `describe()` below returns
them to the cell JSON):
    model rollouts per plan = num_samples * iterations        (default 512 * 6  = 3072)
    prior samples per plan  = num_pi_trajs                    (default 24, drawn from the RISE actor)
    plans per episode       = ceil(episode_frames / execute_frames)
A 128-candidate value column spends 128 rollouts per CHUNK.  At the defaults this row spends 3072 per
plan and replans every `execute_frames` frames, i.e. roughly 24x the search of the shared-candidate
column at the same cadence.  That is TD-MPC2's design, not a bug, but a win of this row over a value
column is a win of "more search + a latent model", and the ratio has to be on the page.

TWO HORIZONS, both disclosed, because they are not the same number.
  * `plan_horizon` (Hp) is how many steps MPPI actually optimises.  Upstream uses 3.  It is NOT
    1/(1-gamma): TD-MPC2 deliberately optimises a short window and lets its terminal Q carry the rest.
  * `gamma` is the checkpoint's trained discount, so the terminal Q covers H = 1/(1-gamma), which is
    the horizon family #273 sweeps and the one the comparison is indexed by.
Both go in the cell JSON.  A caption that prints only H would imply MPPI searched 200 steps; it did
not, and the RSM column's depth is likewise a read-out depth, not a search depth.

WHAT IS HELD FIXED (the #274 fairness conditions): env, initial-state distribution, rollout loop,
episode horizon, success test, the observation encoder (rsm_scorer.PooledDinoState -- the project's
frozen DINOv2 ViT-S/14 cls+GeM pooling with the task cache's feat_stats, exactly what the RSM scorer
and the DF planner see), and the action units (the 7-d OSC action, clamped to [-1, 1] as upstream's
action space requires and as td_backend.py already does).

PLANNER DIAGNOSTICS, published beside every score (#274 item 3):
  J_mean / J_std / J_spread   -- value spread over the plan's own samples.  J_spread ~ 0 means MPPI is
                                 not discriminating among its candidates and the score is not a search
                                 result, it is the prior.
  J_gain                      -- mean per-ITERATION improvement of the elite value (iteration i's elite
                                 mean minus iteration i-1's).  J_gain <= 0 means the CEM refinement is
                                 not refining and every extra iteration was spent for nothing.
  prior_elite_frac            -- fraction of elites that are RISE-actor prior trajectories rather than
                                 MPPI Gaussian samples.  ~1.0 means the search added nothing over the
                                 proposer; ~0.0 means the prior is being ignored and the "seeded by our
                                 actor" claim is decorative.  Either extreme must be said out loud.
Nothing here is a threshold that gates publication: the numbers are printed with the score, both ways.
"""
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_corpus import TD_SRC                                     # noqa: E402


class TDMPC2Planner:
    """Upstream's MPPI/CEM loop over our trained world model, with the RISE actor as policy prior.

    The loop below is `tdmpc2.py:_plan` step for step -- sample, estimate value, take elites, refit
    (mean, std) with the softmax-of-value weights, clamp std, repeat -- with three deliberate
    differences, each of which is recorded in `describe()`:
      P1  the prior trajectories come from `pi_fn` (our RISE actor) instead of `model.pi`;
      P2  we return the WHOLE elite-mean action sequence so the harness can execute a chunk of it at
          the same cadence the value columns commit a chunk, instead of one action per replan.  The
          cadence is `execute_frames` and is disclosed; execute_frames=1 IS upstream's own cadence
          and is available by setting it;
      P3  action selection is the elite MEAN (eval_mode, no exploration noise added), because this is
          an evaluation, not data collection.  Upstream's gumbel-softmax pick over the elites is
          available via `select="gumbel"` and is recorded when used.
    """

    def __init__(self, model, cfg, gamma, *, 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", device="cuda"):
        self.model, self.cfg, self.gamma = model, cfg, float(gamma)
        self.device = device
        self.Hp = int(plan_horizon)
        self.num_samples = int(num_samples)
        self.num_elites = int(num_elites)
        self.iterations = int(iterations)
        self.num_pi_trajs = int(num_pi_trajs)
        self.temperature = float(temperature)
        self.min_std, self.max_std = float(min_std), float(max_std)
        assert select in ("mean", "gumbel"), select
        self.select = select
        self.adim = int(cfg.action_dim)
        if self.num_elites > self.num_samples:
            raise ValueError(f"num_elites={self.num_elites} > num_samples={self.num_samples}")
        if self.num_pi_trajs > self.num_samples:
            raise ValueError(f"num_pi_trajs={self.num_pi_trajs} > num_samples={self.num_samples}")
        sys.path.insert(0, str(TD_SRC))
        from common import math as tdmath
        self._two_hot_inv = tdmath.two_hot_inv
        self._gumbel = tdmath.gumbel_softmax_sample
        self._prev_mean = None

    def reset(self):
        """New episode: drop the warm start, exactly as upstream's t0=True branch does."""
        self._prev_mean = None

    # -- upstream's read-out, tdmpc2.py:_estimate_value, shared with td_backend.py's configuration (a)
    @torch.no_grad()
    def _estimate_value_split(self, z, actions):
        """The SAME arithmetic as `_estimate_value`, returning its two ADDENDS separately.

        gen_q#274 run 46-main.  `sat_true ~ 1` -- J_elite 19.9996 against an analytic ceiling of
        exactly 20 -- is an objective-SHAPE observation, and the TOTAL cannot tell its two possible
        mechanisms apart: either the per-step learned-reward sum `G` saturates, or the terminal Q
        head sits at its own ceiling and carries the whole objective.  The two have different
        consequences for #274 (a saturating r_hat is a reward-scale problem in OUR integration; a
        pinned terminal Q is the published value head meeting a binary provenance reward), so the
        split has to be MEASURED, not argued.

        The two parts have DIFFERENT analytic ceilings and that is what makes the split readable:
        with gamma^t weights over Hp steps, G is bounded by sum_{t<Hp} gamma^t = (1-gamma^Hp)/(1-gamma)
        and the terminal term by gamma^Hp * 1/(1-gamma); they add to exactly 1/(1-gamma).
        At gamma=0.95, Hp=8: G <= 6.73, terminal <= 13.27, total 20.00.

        DIAGNOSTIC ONLY.  `_estimate_value` below returns `G + discount*Q` exactly as before -- it is
        now literally element [0] of this function -- so no measured cell moves and no ranking changes.
        """
        G, discount = 0.0, 1.0
        for t in range(actions.shape[0]):
            r = self._two_hot_inv(self.model.reward(z, actions[t], None), self.cfg)
            z = self.model.next(z, actions[t], None)
            G = G + discount * r
            discount = discount * self.gamma
        pi = self.model.pi(z, None)[0]
        term = discount * self.model.Q(z, pi, None, return_type="avg")
        return G + term, G, term

    @torch.no_grad()
    def _estimate_value(self, z, actions):
        return self._estimate_value_split(z, actions)[0]

    @torch.no_grad()
    def plan(self, x, pi_actions=None, generator=None):
        """x [1, d_state] normalised project state -> (actions [Hp, adim], diag dict).

        `pi_actions` [Hp, num_pi_trajs, adim] are the RISE actor's proposals, already trimmed to the
        planning horizon and in the same units.  Passing None falls back to TD-MPC2's OWN actor
        (`model.pi`) and records `prior="tdmpc2_pi"` so a cell that accidentally ran without the RISE
        prior cannot be mistaken for configuration (b).
        """
        z0 = self.model.encode(x.to(self.device), None)                       # [1, latent]
        n_pi = 0
        prior = "none"
        if self.num_pi_trajs > 0:
            if pi_actions is not None:
                pi = pi_actions.to(self.device).float().clamp(-1, 1)
                if pi.shape[0] != self.Hp or pi.shape[2] != self.adim:
                    raise ValueError(f"pi_actions {tuple(pi.shape)} != (Hp={self.Hp}, n, adim={self.adim})")
                n_pi = min(int(pi.shape[1]), self.num_pi_trajs)
                pi = pi[:, :n_pi]
                prior = "rise_actor"
            else:                                                              # upstream's own prior
                n_pi = self.num_pi_trajs
                pi = torch.empty(self.Hp, n_pi, self.adim, device=self.device)
                _z = z0.repeat(n_pi, 1)
                for t in range(self.Hp - 1):
                    pi[t], _ = self.model.pi(_z, None)
                    _z = self.model.next(_z, pi[t], None)
                pi[-1], _ = self.model.pi(_z, None)
                prior = "tdmpc2_pi"

        z = z0.repeat(self.num_samples, 1)
        mean = torch.zeros(self.Hp, self.adim, device=self.device)
        std = torch.full((self.Hp, self.adim), self.max_std, dtype=torch.float, device=self.device)
        if self._prev_mean is not None:                     # upstream's warm start (not t0)
            mean[:-1] = self._prev_mean[1:]
        actions = torch.empty(self.Hp, self.num_samples, self.adim, device=self.device)
        if n_pi:
            actions[:, :n_pi] = pi

        elite_means, elite_splits, score = [], [], None
        for _ in range(self.iterations):
            r = torch.randn(self.Hp, self.num_samples - n_pi, self.adim,
                            device=self.device, generator=generator)
            actions[:, n_pi:] = (mean.unsqueeze(1) + std.unsqueeze(1) * r).clamp(-1, 1)
            value, rsum, termq = self._estimate_value_split(z, actions)        # [num_samples, 1] x3
            value = value.nan_to_num(0)
            elite_idxs = torch.topk(value.squeeze(1), self.num_elites, dim=0).indices
            elite_value, elite_actions = value[elite_idxs], actions[:, elite_idxs]
            elite_means.append(float(elite_value.mean()))
            # run 46: the SAME elites, decomposed.  `rsum` is a python float 0.0 when Hp == 0, which
            # cannot be indexed -- that case is impossible for a real plan (Hp >= 1 is checked in
            # __init__) but the guard keeps the diagnostic from being the thing that raises.
            _rs = float(rsum[elite_idxs].mean()) if torch.is_tensor(rsum) else 0.0
            elite_splits.append((_rs, float(termq[elite_idxs].mean())))
            # prior_elite_frac: how many of the elites are the RISE actor's own trajectories.  The
            # prior occupies columns [0, n_pi) of `actions` by construction, so this is exact.
            prior_frac = float((elite_idxs < n_pi).float().mean()) if n_pi else 0.0
            max_value = elite_value.max(0).values
            score = torch.exp(self.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().clamp(self.min_std, self.max_std)

        if self.select == "gumbel":
            idx = self._gumbel(score.squeeze(1))
            out = torch.index_select(elite_actions, 1, idx).squeeze(1)
        else:
            out = mean
        self._prev_mean = mean.clone()
        v = value.squeeze(1)
        gains = np.diff(elite_means) if len(elite_means) > 1 else np.array([0.0])
        diag = dict(J_mean=float(v.mean()), J_std=float(v.std()), J_spread=float(v.max() - v.min()),
                    J_gain=float(gains.mean()), J_elite_first=elite_means[0],
                    J_elite_last=elite_means[-1], prior_elite_frac=prior_frac,
                    n_pi=n_pi, prior=prior,
                    # run 46 (#274 run-45 next-action (d)): the J_elite decomposition.  Sums to
                    # J_elite_{first,last} by construction -- the table asserts that, it does not
                    # assume it.  `*_ceil` are the two ANALYTIC bounds these parts are read against.
                    J_elite_rsum_first=elite_splits[0][0], J_elite_termq_first=elite_splits[0][1],
                    J_elite_rsum_last=elite_splits[-1][0], J_elite_termq_last=elite_splits[-1][1],
                    J_rsum_ceil=float((1.0 - self.gamma ** self.Hp) / (1.0 - self.gamma)),
                    J_termq_ceil=float(self.gamma ** self.Hp / (1.0 - self.gamma)))
        return out.clamp(-1, 1), diag

    def describe(self):
        return dict(row="gen_q#274 configuration (b): TD-MPC2 MPPI/CEM planner, RISE actor prior",
                    plan_horizon=self.Hp, num_samples=self.num_samples, num_elites=self.num_elites,
                    iterations=self.iterations, num_pi_trajs=self.num_pi_trajs,
                    temperature=self.temperature, min_std=self.min_std, max_std=self.max_std,
                    select=self.select, gamma=self.gamma,
                    H_terminal_q=1.0 / (1.0 - self.gamma),
                    rollouts_per_plan=self.num_samples * self.iterations)