File size: 12,127 Bytes
d18db74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""DOES DECODING DF'S PLANNED LATENTS WITH AN IDM BEAT DF'S OWN DIFFUSED ACTION CHANNEL?
(gen_q#274, stream DF_MAKEITWORK, run 36.)  Held-out episodes, NO environment, NO success number.

This is BAR 2 of the read-out registered in `df_idm.py`'s header, and it is the decisive one.
It measures, ON THE SAME held-out states, in the SAME script, with the SAME R2 definition:

  1. `df_head`   DF's own diffused ACTION channel  -- the arm every landed RISE DF cell executed.
                 Scored at every lag in {-2,-1,0,+1,+2} the way `df_actprobe.py` does, and the BEST
                 lag is the number the IDM must beat, so DF's own head is never handicapped by an
                 indexing convention.  (df_G0 is trained with `act_align=upstream`, so its bundle
                 token h is (obs_{t+h+1}, a_{t+h}) and lag -1 in df_actprobe's indexing is the
                 aligned one; both are reported.)
  2. `idm_plan`  the IDM decoding DF's PLANNED OBSERVATION LATENTS -- the proposed arm.  The anchor
                 is the TRUE current observation (exactly what the encoder gives the policy at
                 planning time); every other frame is DF's prediction.  Nothing else enters.
  3. `idm_oracle` the IDM decoding the TRUE future observations on the same states.  A DIAGNOSTIC
                 UPPER BOUND ONLY -- it reads the future and can never be a policy.  Labelled as
                 such everywhere, exactly like `df_poolcmp.py`'s `r2_oracle`.

and, because a selection rule that ties across its own pool IS random-of-N however good its number,
the OFFLINE form of the fairness controls, over the IDENTICAL candidate pool:
  `argmaxJ` / `random` / `Kmean` decoded R2, the selection gap (argmaxJ - random), the J spread,
  the fraction of states whose J ties at the max, and the pool's own action spread.

FAIRNESS.  The held-out expert action is used ONLY as the R2 target and for the oracle diagnostic;
it never reaches the planner, the guidance or the decoder.  No RSM / IQL critic touches any
candidate (rule 7).  No goal guidance.  Guidance scale is swept over the same {0, 5} the rest of the
stream uses; nothing privileged is added at any scale.

usage:
  python df_idm_probe.py --ckpt runs/<task>/wm/df_G0/ckpt_s40000.pt --cache cache/<task> \
      --idm-dir runs/<task>/idm/k1_n0 --idm-dir runs/<task>/idm/k8_n1 ... \
      --out status/nb/df_idm/<task>_probe.json
"""
from __future__ import annotations

import argparse
import json
import os
import sys
from pathlib import Path

import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from df_data import DFCacheData, OBS_DIM, ACT_DIM        # noqa: E402
from df_probe import load_df                             # noqa: E402
from df_plan import plan_bundles                         # noqa: E402
from df_idm import MODES, load_idm, decode_plan as decode, r2_vs_mean_action  # noqa: E402

A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM


@torch.no_grad()
def main():
    p = argparse.ArgumentParser()
    p.add_argument("--ckpt", required=True)
    p.add_argument("--cache", required=True)
    p.add_argument("--idm-dir", action="append", default=[])
    p.add_argument("--out", required=True)
    p.add_argument("--best-out", default="")
    p.add_argument("--n-states", type=int, default=64)
    p.add_argument("--kmax", type=int, default=32)
    p.add_argument("--execute-frames", type=int, default=8)
    p.add_argument("--guidance", type=float, action="append", default=[])
    p.add_argument("--gamma", type=float, default=0.95)
    p.add_argument("--seed", type=int, default=0)
    a = p.parse_args()
    guids = a.guidance or [0.0, 5.0]
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    model, meta, step = load_df(a.ckpt, dev)
    data = DFCacheData(a.cache, frame_stack=int(meta["frame_stack"]),
                       n_tokens=int(meta["n_tokens"]), seed=int(meta.get("seed", 0)))
    rng = np.random.default_rng(a.seed)
    T = data.T
    bundle, mask = data.sample(a.n_states, rng, split="val", device=dev)   # [W,B,C], W=T+1
    init_obs = bundle[0, :, :OBS_DIM]
    B = init_obs.shape[0]
    mean_act = torch.as_tensor(np.asarray(data.act, np.float32).mean(0), device=dev)
    ne = int(a.execute_frames)

    idms = []
    for d in a.idm_dir:
        try:
            m, ck = load_idm(d, dev)
        except FileNotFoundError:
            print(f"[df_idm_probe] MISSING idm {d} -- skipped", flush=True)
            continue
        idms.append((Path(d).name, d, m, ck))
    if not idms:
        raise SystemExit("[df_idm_probe] no IDM checkpoints found -- train first")

    res = dict(ckpt=a.ckpt, cache=a.cache, df_step=step, n_states=B, kmax=a.kmax,
               execute_frames=ne, gamma=a.gamma, guidances=guids,
               frame_stack=int(meta["frame_stack"]), act_align=meta.get("act_align"),
               note=("DF plans observation latents; the IDM decodes them into actions. "
                     "idm_oracle reads the TRUE future and is a DIAGNOSTIC UPPER BOUND, never a "
                     "policy."),
               by_guidance={})

    # true-future observation sequence for the oracle diagnostic: O_true[j] = obs_{t+j}
    O_true = bundle[:, :, :OBS_DIM]                                            # [W,B,D]
    valid = mask.bool()                                                        # [W,B]

    for g in guids:
        out = plan_bundles(model, init_obs, horizon_frames=T, guidance_scale=g, gamma=a.gamma,
                           n_plans=a.kmax, device=dev)
        plan, J = out["plan"], out["J"]                     # [T,B,K,C], [B,K]
        K = plan.shape[2]
        P = plan[..., :OBS_DIM]                             # planned obs, P[h] = obs_{t+h+1}
        O = torch.cat([init_obs[None, :, None, :].expand(1, B, K, OBS_DIM), P], 0)   # [T+1,B,K,D]

        # ---- the candidate-selection controls, computed once per guidance --------------------
        jn = J.detach().cpu().numpy()
        idx_max = J.argmax(-1)
        gen = torch.Generator(device=dev); gen.manual_seed(1234)
        idx_rnd = torch.randint(K, (B,), device=dev, generator=gen)
        ties = float(np.mean([(np.abs(r - r.max()) <= 1e-8).sum() for r in jn]))
        cell = dict(J_mean=float(jn.mean()), J_spread=float((jn.max(1) - jn.min(1)).mean()),
                    J_std_within_state=float(jn.std(1).mean()),
                    ties_at_max_mean=ties, ties_at_max_frac=float(ties / K),
                    frac_states_all_tied=float(np.mean(
                        [(np.abs(r - r.max()) <= 1e-8).sum() == K for r in jn])),
                    n_candidates=int(K))

        def score(actKBA, tag, store):
            """actKBA [ne,B,K,ACT] -> R2 of Kmean / argmaxJ / random picks against a_{t..t+ne-1}."""
            ar = torch.arange(B, device=dev)
            picks = dict(Kmean=actKBA.mean(2),
                         argmaxJ=actKBA[:, ar, idx_max],
                         random=actKBA[:, ar, idx_rnd],
                         single=actKBA[:, :, 0])
            o = {}
            for name, pr in picks.items():
                Pp, Tg = [], []
                for h in range(ne):
                    w = valid[h]
                    if w.sum() == 0:
                        continue
                    Pp.append(pr[h][w]); Tg.append(bundle[h][w, A0:A1])
                pooled, per_ch = r2_vs_mean_action(torch.cat(Pp), torch.cat(Tg), mean_act)
                o[name] = dict(r2=pooled, r2_per_channel=per_ch,
                               n=int(sum(x.shape[0] for x in Pp)))
            o["selection_gap_argmaxJ_minus_random"] = o["argmaxJ"]["r2"] - o["random"]["r2"]
            o["pool_act_std_over_tgt"] = float(
                (actKBA.std(2).mean() / bundle[:ne][valid[:ne]][:, A0:A1].std(0).mean()).item())
            store[tag] = o
            return o

        arms = {}
        # ---- arm 1: DF's own diffused action channel, every lag (df_actprobe's protocol) -------
        dfa = plan[..., A0:A1]                                            # [T,B,K,ACT]
        per_lag = {}
        for lag in (-2, -1, 0, 1, 2):
            Pp, Tg = [], []
            for h in range(ne):
                j = h + lag                     # plan index h predicts a_{t+h+lag}
                if j < 0 or j >= bundle.shape[0]:
                    continue
                w = valid[j]
                if w.sum() == 0:
                    continue
                Pp.append(dfa[h][w].mean(1)); Tg.append(bundle[j][w, A0:A1])
            if not Pp:
                continue
            pooled, _ = r2_vs_mean_action(torch.cat(Pp), torch.cat(Tg), mean_act)
            per_lag[str(lag)] = dict(r2_Kmean=pooled, n=int(sum(x.shape[0] for x in Pp)))
        best_lag = max(per_lag, key=lambda k: per_lag[k]["r2_Kmean"]) if per_lag else None
        score(dfa[:ne], "df_head", arms)
        arms["df_head"]["per_lag_Kmean"] = per_lag
        arms["df_head"]["best_lag"] = best_lag
        arms["df_head"]["r2_best_lag_Kmean"] = per_lag[best_lag]["r2_Kmean"] if best_lag else None

        # ---- arms 2/3: each IDM on planned latents, and on the true future (diagnostic) --------
        for name, d, m, ck in idms:
            score(decode(m, ck, O, ne), f"idm_plan::{name}", arms)
            Ot = O_true[:, :, None, :].expand(-1, -1, 1, -1)              # [W,B,1,D]
            arms[f"idm_oracle::{name}"] = {}
            oc = decode(m, ck, Ot, ne)                                     # [ne,B,1,ACT]
            Pp, Tg = [], []
            for h in range(ne):
                w = valid[h]
                if w.sum() == 0:
                    continue
                Pp.append(oc[h][w][:, 0]); Tg.append(bundle[h][w, A0:A1])
            pooled, per_ch = r2_vs_mean_action(torch.cat(Pp), torch.cat(Tg), mean_act)
            arms[f"idm_oracle::{name}"] = dict(
                r2=pooled, r2_per_channel=per_ch, n=int(sum(x.shape[0] for x in Pp)),
                DIAGNOSTIC_UPPER_BOUND="reads the TRUE future observation; never a policy")

        cell["arms"] = arms
        res["by_guidance"][str(g)] = cell

        dfb = arms["df_head"]["r2_best_lag_Kmean"]
        print(f"\n[df_idm_probe] guidance {g}  DF head R2 (best lag {best_lag}) {dfb:+.4f} "
              f"| lag0 {arms['df_head']['Kmean']['r2']:+.4f}", flush=True)
        for name, *_ in idms:
            ip = arms[f"idm_plan::{name}"]
            io = arms[f"idm_oracle::{name}"]
            print(f"  IDM {name:<12s} on-plan Kmean {ip['Kmean']['r2']:+.4f}  "
                  f"argmaxJ {ip['argmaxJ']['r2']:+.4f}  random {ip['random']['r2']:+.4f}  "
                  f"gap {ip['selection_gap_argmaxJ_minus_random']:+.4f}  "
                  f"| oracle-obs {io['r2']:+.4f} (diagnostic)", flush=True)

    # ---- BAR 2 verdict, decided on a held-out, environment-free metric only -------------------
    g0 = str(guids[0])
    base = res["by_guidance"][g0]["arms"]["df_head"]
    df_bar = max(v for v in [base["r2_best_lag_Kmean"], base["Kmean"]["r2"]] if v is not None)
    best, best_r2 = None, -1e9
    for name, *_ in idms:
        r = res["by_guidance"][g0]["arms"][f"idm_plan::{name}"]["Kmean"]["r2"]
        if r > best_r2:
            best, best_r2 = name, r
    res["bar2"] = dict(df_head_bar=df_bar, best_idm=best, best_idm_r2_on_plan=best_r2,
                       pass_=bool(best_r2 > df_bar), guidance_used=float(guids[0]),
                       rule="IDM decoding DF's OWN planned latents must beat DF's own action head "
                            "at its BEST lag, on the same held-out states, or the decoder is not "
                            "the fix and that is what gets reported.")
    Path(a.out).parent.mkdir(parents=True, exist_ok=True)
    Path(a.out).write_text(json.dumps(res, indent=1))
    if a.best_out:
        Path(a.best_out).parent.mkdir(parents=True, exist_ok=True)
        Path(a.best_out).write_text(f"{best}\n")
    print(f"\n[df_idm_probe] BAR2  df_head {df_bar:+.4f}  best IDM {best} {best_r2:+.4f}  "
          f"pass={res['bar2']['pass_']}\n[df_idm_probe] wrote {a.out}", flush=True)


if __name__ == "__main__":
    main()