File size: 12,573 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
"""TD-MPC2 as a SCORER backend -- gen_q#274 configuration (a), the shared-candidate column.

WHAT THIS COLUMN IS, said plainly here and repeated in the caption wherever its number appears:
this is close to DINO-WM plus a value head.  It scores the proposer's SAME 128 candidate action
chunks by rolling TD-MPC2's learned latent dynamics over the chunk, accumulating its learned
per-step reward, and adding its terminal Q.  It is not TD-MPC2's planner (that is configuration (b),
the MPPI/CEM row).  Nothing about the proposer, the candidate set, the env, the initial states or
the success test changes -- only the function that ranks the candidates.

INTERFACE.  `q()` mirrors `MLPBackend.q` / `DWMBackend.q` in
code/rise_robomimic/robomimic/algo/rsm_scorer.py exactly, so `rsm_planner.plan_get_action` calls it
with no change:  q(z, a, *, mode, depth, beta, gamma, n_particles, flow_steps, return_logit=False,
temperature=None) -> Q̄ [B]  (or (Q̄, Q̄_logit)).

FOUR HONEST NOTES about the arguments it CANNOT honour, each of which must travel with the number:

  N1  `n_particles` is IGNORED -- TD-MPC2's world model is deterministic, so every particle would be
      the same rollout and the per-candidate spread is exactly 0.  At the same nominal setting this
      column therefore spends LESS search than the RSM column, not more.  `last_stats["spread"]`
      reports the 0 rather than hiding it, and `n_particles_effective` is always 1.

  N2  `flow_steps` is IGNORED for the same reason: there is no flow to integrate.

  N3  `beta` / `depth` / `mode` are RSM read-out parameters with no TD-MPC2 counterpart.  The only
      read-out this backend has is the one TD-MPC2 itself uses, `_estimate_value` -- discounted
      learned reward over the chunk plus terminal Q.  Modes d1 / fold / chain are ACCEPTED and all
      return that same quantity (they are the harness's names for the RSM recursion, not requests
      TD-MPC2 can honour differently); the mode actually used is recorded in `last_stats["mode_in"]`
      so no table can imply a TD-MPC2 "fold" row differs from its "d1" row.

  N4  `gamma` must MATCH the gamma the checkpoint was TRAINED with (td_corpus T1/T2 pin both the
      discount and the value range to it).  Scoring with a different gamma would read a value head
      fitted to another horizon, so a mismatch RAISES instead of returning a plausible number.

SCALE.  `_estimate_value` returns a discounted return in [0, 1/(1-gamma)] because our reward is the
binary provenance label.  Q̄ is that value times (1-gamma), i.e. rescaled onto [0, 1] where the
membership-probability columns live.  This is a strictly monotone rescaling: it changes no ranking
and no argmax, it only makes the number readable on the same axis.  The raw value is kept in
`last_stats["value_raw_mean"]`.
"""
from __future__ import annotations

import sys
from pathlib import Path

import torch

ROOT = Path("/proj/dmfexp/zwhong/rsm_rise")
sys.path.insert(0, str(Path(__file__).parent))
from td_corpus import (build_cfg, TD_SRC, install_safe_to,  # noqa: E402
                       install_ensemble_grad_fix, load_real_state_dict)


def load_td_world_model(ckpt, device="cuda"):
    """Rebuild upstream's WorldModel from a train_tdmpc2.py checkpoint.  No env, no agent."""
    # gen_q#274.  Upstream imports tensordict unconditionally and the RISE eval environment has
    # none; td_env_pin installs the MEASURED-EQUIVALENT 0.6.2 (max|dQ| 3.8e-6 against the 0.14.2
    # these models were trained under, status/nb/td_env_probe.txt) and is a no-op inside
    # venv_tdmpc2, where the native 0.14.2 is the right one.  Every call site reaches the model
    # through this function, so this is the single place the pin has to be applied.
    import td_env_pin
    td_env_pin.install()
    sd = torch.load(ckpt, map_location="cpu", weights_only=False)
    gamma = float(sd["gamma"])
    saved = sd["cfg"]
    cfg = build_cfg(horizon=int(saved["horizon"]), gamma=gamma,
                    model_size=int(saved["model_size"]), work_dir="/tmp")
    for k, v in saved.items():                  # the checkpoint's own values win over any default
        setattr(cfg, k, v)
    WorldModel = install_safe_to()        # td_corpus T5: .to() and state_dict() vs the meta params
    install_ensemble_grad_fix()          # td_corpus T6.  Forward-neutral (diag_ensemble asserts
                                         # bitwise equality), but it keeps ONE Ensemble code path
                                         # between the trainer and the scorer that reads its weights.
    m = WorldModel(cfg)
    load_real_state_dict(m, sd["model"])
    return m.to(device).eval(), cfg, gamma, int(sd.get("step", -1)), sd.get("cache", "")


class TDMPC2Backend:
    """Drop-in for MLPBackend / DWMBackend; see the module docstring for N1-N4."""

    def __init__(self, ckpt, device="cuda", chunk=8, adim=7, normalize=None):
        self.core, self.cfg, self.gamma_trained, self.step, self.train_cache = \
            load_td_world_model(ckpt, device)
        self.device = device
        self.chunk = int(chunk)
        self.adim = int(adim)
        self.d_act = self.chunk * self.adim
        self.d_z = int(self.cfg.obs_shape["state"][0])
        assert int(self.cfg.action_dim) == self.adim, \
            f"checkpoint action_dim {self.cfg.action_dim} != {self.adim}"
        self.normalize = normalize if normalize is not None else (lambda x: x)
        self.temperature = 1.0                   # no calibration temperature: this is not a logit head
        self.q_action_winrate = None
        self.last_stats = {}
        # run 46 (#274): `last_stats` is OVERWRITTEN by every q() call, so td_scorer's
        # `last_backend_stats` describes the LAST decision of the whole eval and nothing else.  That
        # is thin evidence for a saturation claim, which is about the run.  These running sums give
        # the same three quantities as means over EVERY scored batch, with the call count beside them
        # so a reader can see how many decisions they average.
        self._acc_n = 0
        self._acc = {"value_raw_mean": 0.0, "value_rsum_mean": 0.0, "value_termq_mean": 0.0}
        sys.path.insert(0, str(TD_SRC))
        from common import math as tdmath
        self._two_hot_inv = tdmath.two_hot_inv

    # -- upstream's own read-out, tdmpc2.py:123 `_estimate_value`, written out because we need it
    #    without constructing a TDMPC2 agent (which hardcodes cuda:0 and builds optimisers).
    @torch.no_grad()
    def _estimate_value_split(self, z, actions):
        """z [B, latent]; actions [H, B, adim] -> (total, per-step r_hat sum, terminal term), each [B, 1].

        gen_q#274 run 46-main, the configuration-(a) half of the same decomposition td_plan.py now
        records for configuration (b).  cfg(a)'s saturation reads `sat_true ~ 1`; the total cannot
        say whether the learned per-step reward or the terminal Q head is what is pinned, and those
        are different defects.  The two addends carry different analytic ceilings --
        G <= (1 - gamma^H)/(1 - gamma) and terminal <= gamma^H/(1 - gamma), adding to 1/(1 - gamma) --
        so reading them apart localises the saturation.

        DIAGNOSTIC ONLY: `_estimate_value` is now element [0] of this function, byte-for-byte the
        same arithmetic in the same order, so every landed cfg(a) score is unchanged.
        """
        G, discount = 0.0, 1.0
        for t in range(actions.shape[0]):
            r = self._two_hot_inv(self.core.reward(z, actions[t], None), self.cfg)
            z = self.core.next(z, actions[t], None)
            G = G + discount * r
            discount = discount * self.gamma_trained
        pi = self.core.pi(z, None)[0]
        term = discount * self.core.Q(z, pi, None, return_type="avg")
        return G + term, G, term

    @torch.no_grad()
    def _estimate_value(self, z, actions):
        """z [B, latent]; actions [H, B, adim] -> discounted return + terminal Q, [B, 1]."""
        return self._estimate_value_split(z, actions)[0]

    def stats_mean(self):
        """Means of the value decomposition over EVERY q() call so far, with the call count.

        Returned (not printed) so td_scorer.describe() can put it in the cell's diag JSON beside the
        single-decision `last_backend_stats`.  `calls` is included because a mean over one decision
        and a mean over 20000 must not look alike in a table.
        """
        if not getattr(self, "_acc_n", 0):
            return {"calls": 0}
        out = {k: v / self._acc_n for k, v in self._acc.items()}
        out["calls"] = self._acc_n
        return out

    @torch.no_grad()
    def q(self, z, a, *, mode="d1", depth=1, beta=None, gamma=None, n_particles=1, flow_steps=0,
          return_logit=False, temperature=None, crn_seed=None, return_lcb=None, **_):
        if gamma is not None and abs(float(gamma) - self.gamma_trained) > 1e-9:
            raise RuntimeError(                                           # N4
                f"TD-MPC2 checkpoint was trained at gamma={self.gamma_trained} (H="
                f"{1/(1-self.gamma_trained):.1f}) but this cell asks for gamma={gamma}.  Its value "
                f"head and its two-hot range are both pinned to the trained gamma (td_corpus T1/T2), "
                f"so scoring at another gamma would read a head fitted to a different horizon.  "
                f"Train the matching cell instead.")
        if return_lcb is not None:
            raise RuntimeError(                                           # N1, made loud
                "plan_score=conformal_lcb has no meaning for TD-MPC2: its world model is "
                "deterministic, every particle is the same rollout and the per-particle quantile is "
                "the mean.  Reporting an LCB here would invent dispersion the model does not have.")
        x = self.normalize(z.float()).to(self.device)
        acts = a.float().to(self.device).view(a.shape[0], self.chunk, self.adim).permute(1, 0, 2)
        acts = acts.clamp(-1.0, 1.0)             # upstream's action space is [-1, 1]; ours is the
                                                 # OSC action already in those units.
        zl = self.core.encode(x, None)
        v, rsum, termq = self._estimate_value_split(zl, acts)
        v = v.squeeze(-1)
        vmax = 1.0 / (1.0 - self.gamma_trained)
        qbar = (v / vmax).clamp(0.0, 1.0)
        self.last_stats = {"mode_in": mode, "depth_in": int(depth),
                           "n_particles_in": int(n_particles), "n_particles_effective": 1,
                           "flow_steps_in": int(flow_steps), "spread": 0.0,
                           "value_raw_mean": float(v.mean()), "value_raw_max": float(v.max()),
                           "value_raw_min": float(v.min()), "vmax": vmax,
                           "gamma": self.gamma_trained, "step": self.step,
                           # run 46 (#274 run-45 next-action (d)): the value decomposition.  Means
                           # over the SAME candidate batch v is read from, so rsum + termq == v
                           # candidate-by-candidate and therefore also in the mean.
                           "value_rsum_mean": (float(rsum.mean()) if torch.is_tensor(rsum) else 0.0),
                           "value_termq_mean": float(termq.mean()),
                           "rsum_ceil": float((1.0 - self.gamma_trained ** self.chunk)
                                              / (1.0 - self.gamma_trained)),
                           "termq_ceil": float(self.gamma_trained ** self.chunk
                                               / (1.0 - self.gamma_trained))}
        # LAZY INIT, not a bare `self._acc_n += 1`.  run 46: the first version of this line raised
        # AttributeError on any instance not built through __init__ -- which is exactly how
        # scripts/nb/test_jsplit.py builds one, and how a future caller that restores a backend from
        # a pickle would.  A DIAGNOSTIC must never be the thing that takes a scored eval down, so the
        # counter creates itself here instead of depending on construction order.
        if not hasattr(self, "_acc_n"):
            self._acc_n = 0
            self._acc = {"value_raw_mean": 0.0, "value_rsum_mean": 0.0, "value_termq_mean": 0.0}
        self._acc_n += 1
        for k in self._acc:
            self._acc[k] += float(self.last_stats[k])
        if not return_logit:
            return qbar
        p = qbar.clamp(1e-6, 1 - 1e-6)
        return qbar, torch.log(p) - torch.log1p(-p)