File size: 5,650 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
"""gen_q#274, stream DF_MAKEITWORK run 41 -- IS THE GUIDANCE KNOB ACTUALLY CONNECTED?

The brief's lead 2 names this test verbatim: "report the L2 between plans sampled at guidance 0
and at guidance 5 from the same seed.  If it is ~0, the parameter is inert and the sweep was
measuring nothing -- that has happened on this project before (an inert `plan_temp`)."

A bare cross-guidance L2 is NOT sufficient on its own, and this script refuses to report one
alone.  `plan_bundles` draws fresh diffusion noise per call, so two calls differ even at the SAME
guidance; a large cross-guidance L2 would prove nothing unless it is large COMPARED TO that.  So
every cross-guidance number here is published beside its own null:

  * SIGNAL   L2( plan(g) , plan(g0) )  with the diffusion noise draw HELD IDENTICAL across the two
             calls (torch.manual_seed set to the same value before each), so the only thing that
             differs between the two plans is the guidance scale.
  * NULL     L2( plan(g0, seed s1) , plan(g0, seed s2) )  -- same guidance, different noise.  This
             is how far apart two plans land for reasons that have nothing to do with the knob.

READING:  signal / null >> 1  => the knob moves the plan far more than resampling does: connected.
          signal / null ~  0  => inert; any sweep of it was measuring noise (the `plan_temp` bug).
          signal / null ~  1  => the knob perturbs the plan no more than a reseed: uninformative.

FAIRNESS.  Diagnostic only -- it produces no success rate and no ranking.  It reads the val split
of the same cache the column trains on, uses DF's own predicted binary-provenance reward channel
for J, and never touches a simulator, a success bit, or an RSM/IQL critic (rules 1, 2, 7).
"""
import argparse
import json
import os
import sys

import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from df_data import DFCacheData, OBS_DIM          # noqa: E402
from df_probe import load_df                      # noqa: E402
from df_plan import plan_bundles                   # noqa: E402


@torch.no_grad()
def main():
    p = argparse.ArgumentParser()
    p.add_argument("--ckpt", required=True)
    p.add_argument("--cache", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--n-states", type=int, default=64)
    p.add_argument("--kmax", type=int, default=32)
    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)
    p.add_argument("--noise-seed", type=int, default=1234)
    a = p.parse_args()
    guids = a.guidance or [0.0, 0.5, 1.0, 2.0, 5.0, 10.0]
    g0 = guids[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, _ = data.sample(a.n_states, rng, split="val", device=dev)
    init_obs = bundle[0, :, :OBS_DIM]

    def draw(g, noise_seed):
        """One planning call with the diffusion noise draw pinned to `noise_seed`."""
        torch.manual_seed(noise_seed)
        if dev == "cuda":
            torch.cuda.manual_seed_all(noise_seed)
        out = plan_bundles(model, init_obs, horizon_frames=T, guidance_scale=g, gamma=a.gamma,
                           n_plans=a.kmax, device=dev)
        return out["plan"][..., :OBS_DIM].float(), out["J"].float()   # [T,B,K,D], [B,K]

    def l2(x, y):
        """mean over (h,b,k) of the per-vector L2 distance."""
        return float(torch.linalg.vector_norm(x - y, dim=-1).mean())

    P0, J0 = draw(g0, a.noise_seed)
    scale = float(torch.linalg.vector_norm(P0, dim=-1).mean())

    # the NULL: same guidance, a different diffusion noise draw.
    Pn, _ = draw(g0, a.noise_seed + 777)
    null = l2(P0, Pn)

    res = dict(ckpt=a.ckpt, cache=a.cache, df_step=step, n_states=int(init_obs.shape[0]),
               kmax=a.kmax, gamma=a.gamma, guidances=guids, g_ref=g0,
               plan_latent_rms_norm=scale, null_same_guidance_reseed_l2=null,
               note=("SIGNAL is plan(g) vs plan(g_ref) with the noise draw held identical; NULL is "
                     "plan(g_ref) vs plan(g_ref) under a different noise draw.  signal/null >> 1 "
                     "means the guidance knob is connected.  Diagnostic only: no success rate, no "
                     "simulator, no success bit, no RSM/IQL contact."),
               by_guidance={})
    print(f"[df_guid_l2] step {step}  n_states {init_obs.shape[0]}  K {a.kmax}  "
          f"plan latent |P| {scale:.4f}")
    print(f"[df_guid_l2] NULL (g={g0} reseeded)  L2 {null:.5f}  ({null/max(scale,1e-9):.4f} of |P|)")
    for g in guids:
        Pg, Jg = draw(g, a.noise_seed)
        d = l2(Pg, P0)
        cell = dict(l2_vs_ref=d, l2_rel_to_plan_norm=d / max(scale, 1e-9),
                    ratio_to_null=d / max(null, 1e-9),
                    J_mean=float(Jg.mean()),
                    J_spread=float((Jg.max(dim=1).values - Jg.min(dim=1).values).mean()))
        res["by_guidance"][str(g)] = cell
        print(f"[df_guid_l2] g={g:<5} SIGNAL L2 {d:.5f}  = {cell['ratio_to_null']:.2f}x NULL   "
              f"J_mean {cell['J_mean']:.3f}  J_spread {cell['J_spread']:.3f}")
    os.makedirs(os.path.dirname(a.out), exist_ok=True)
    with open(a.out, "w") as f:
        json.dump(res, f, indent=2)
    print(f"[df_guid_l2] wrote {a.out}")


if __name__ == "__main__":
    main()