File size: 14,027 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
233
234
235
236
237
238
239
240
241
242
"""Diffusion Forcing as a VALUE ESTIMATOR -- the read-out (gen_q#274 / tracking #282, stream DF_VALUE).

WHAT THIS IS, AND HOW IT DIFFERS FROM `df_plan.py` (which this stream does not touch).
`df_plan.plan_bundles` runs DF as a PLANNER: it lets the diffusion model propose its own action
channels and steers them with a guidance gradient on the predicted reward.  This file runs the same
model as a VALUE FUNCTION over somebody ELSE's candidate actions -- the shape every other column in
tab:flagship is scored in (a proposer emits N action chunks, the column ranks them).  Concretely:

    guidance_fn = None, ALWAYS.                      no gradient steering of any kind
    the candidate action chunk is INPAINTED instead.  Diffuser-style replacement conditioning
    the value is DF's own predicted reward channel r_hat, read off the rolled-out bundle.

The sampling loop below MIRRORS `df_plan.plan_bundles` line for line -- same pyramid scheduling
matrix (`model.scheduling`), same conditioning token construction, same
`model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=...)` call -- so a difference
between the planner route and the value route cannot come from a difference in the sampler.

DESIGN DECISIONS D1..D4 (status/real/DF_VALUE.md, run 1; binding, implemented exactly)

  D1  ACTION CLAMP = REPLACEMENT CONDITIONING, RE-IMPOSED AFTER EVERY SCHEDULING STEP.
      `frame_stack == 8 == the project's action chunk`, so one candidate chunk occupies exactly
      plan token 1 (sequence index 1; index 0 is the conditioning token).  Frame f of a token lives
      at `[f*BUNDLE_DIM : (f+1)*BUNDLE_DIM]`, so frame f's action slice is
      `[f*1553 + 1545 : f*1553 + 1552]`.  Those slices are overwritten with the z-scored candidate
      once before the loop and again after every `sample_step`.  `clamp_maxerr` in the returned diag
      is the assertion: the UNNORMALISED actions recovered from token 1 after the last step must
      equal the candidate to < 1e-3, otherwise the value was not computed for the candidate we asked
      about.  The check is an `assert`, not a warning.

  D2  free_tail=True (default): past the 8-frame chunk the action channel is LEFT FREE, i.e.
      model-sampled.  The roll-out then means "this chunk, then the behaviour distribution the model
      was trained on" -- the same semantics as RSM's successor measure under the behaviour policy.
      free_tail=False is the named ABLATION: the tail action channels are clamped to a RAW ZERO
      action (z-scored through the model's own action mean/std), i.e. "this chunk then nothing".
      Note the convention difference against `df_core.make_sequence`, which zeroes the conditioning
      token's action channels AFTER normalisation; here the ablation wants a zero ACTION, not a
      mean action, so the zero is imposed in raw units and then normalised.  Stated because the two
      conventions differ by `-mean/std` and a reader would otherwise have to guess.

  D3  M Monte-Carlo samples = M independent noise draws of the FREE channels, with COMMON RANDOM
      NUMBERS across the N candidates of an anchor: the noise is drawn at shape
      `[plan_tokens, B, 1, M, fs*C]` and expanded over N, so candidate i and candidate j inside the
      same anchor are diffused from the SAME noise and their difference is not a noise difference.
      (DDIM with eta = 0 -- upstream's planning recipe, `ddim_sampling_eta: 0.0` -- makes the sampler
      deterministic given the initial noise, so the initial draw is the whole stochasticity.)
      This is the analogue of RSM's particle count P.

  D4  TWO aggregations of the unnormalised reward channel over plan frames 1..H, both returned:
        terminal  r_hat at plan frame H (absolute frame index fs + H - 1)
        disc      sum_j gamma^j r_hat_j / sum_j gamma^j,  default gamma = 1 - 1/H
      Each is averaged over the M samples; the per-candidate standard deviation over M is returned
      beside it, because std_across_cand / std_across_M is the only number that says whether the
      ranking is signal or Monte-Carlo noise.

UNITS.  `init_obs` is the project's z-scored 1545-d state (`DFCacheData.obs_rows`), exactly what
`plan_bundles` takes.  `cand_act` is in RAW OSC action units -- the same units `DFCacheData.sample`
puts in the bundle's action channel and the same units `plan_bundles` returns, because the model's
z-scoring is applied by `model.norm` to the WHOLE bundle inside this file (see `_act_z`).  The D1
assertion is what proves this end to end: it un-normalises what the sampler actually held and
compares it against the raw candidate that was passed in.

COST / MEMORY.  One sequence is `(1 + plan_tokens) * fs * BUNDLE_DIM` floats = 1.29 MB at H = 200,
and the batch is B*N*M, so the flattened batch is chunked over the candidate axis to a byte budget
(`max_bytes`, default 400 MB of plan tensor).  Chunking is over N only; the noise is drawn ONCE per
call before chunking, so chunking cannot change a single returned number.
"""
from __future__ import annotations

import numpy as np
import torch

from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM


def default_gamma(H):
    """D4's gamma.  H = 1/(1-gamma) is the horizon parameterisation #273 sweeps."""
    return 1.0 - 1.0 / float(H)


def _act_z(model, act_raw):
    """Raw OSC actions -> the model's z-scored action units.

    This is the action block of `model.norm`, and it is written out rather than calling
    `model.norm` on a padded bundle so that the slice indices are visible at the call site."""
    mu = model.data_mean[OBS_DIM:OBS_DIM + ACT_DIM]
    sd = model.data_std[OBS_DIM:OBS_DIM + ACT_DIM]
    return (act_raw - mu) / sd


def _act_unz(model, act_z):
    mu = model.data_mean[OBS_DIM:OBS_DIM + ACT_DIM]
    sd = model.data_std[OBS_DIM:OBS_DIM + ACT_DIM]
    return act_z * sd + mu


@torch.no_grad()
def value_of_candidates(model, init_obs, cand_act, H, M, gamma=None, free_tail=True,
                        device="cuda", seed=0, max_bytes=4.0e8, return_samples=False,
                        assert_clamp=True, clamp_tol=1e-3, crn_rows=False):
    """DF's value of N candidate action chunks at each of B anchors.

    init_obs  [B, OBS_DIM]      project z-scored state (DFCacheData.obs_rows units)
    cand_act  [B, N, fs, ACT_DIM]  candidate action chunks, RAW OSC units, fs = model.frame_stack
    H         plan frames to roll out (the value horizon)
    M         Monte-Carlo noise draws per (anchor, candidate), common across candidates (D3)
    gamma     discount for the `disc` aggregation; None -> 1 - 1/H (D4)
    free_tail True  -> action channel past the chunk is model-sampled (D2, default)
              False -> action channel past the chunk is clamped to a raw zero action (the ablation)
    crn_rows  False -> one noise draw per (anchor, M), common across that anchor's N candidates.
                       This is D3 as written and is what the offline spread gate runs: the anchors
                       there are independent rows of a batch, so sharing noise between them would
                       correlate measurements that are supposed to be independent samples.
              True  -> ONE noise draw per M, common across every anchor AND every candidate in the
                       call.  Needed by the eval harness (df_readout.DFCritic): rsm_scorer flattens
                       (B envs x N candidates) into rows and a backend never learns N, so per-row
                       noise would break common random numbers across exactly the comparison the
                       argmax is taken over.  Strictly stronger CRN, and it cannot bias a ranking --
                       every candidate is diffused from identical noise.

    returns dict:
      terminal      [B, N]  mean over M of r_hat at plan frame H
      disc          [B, N]  mean over M of sum_j gamma^j r_hat_j / sum_j gamma^j
      terminal_std  [B, N]  std over M of the same (population std, ddof=0)
      disc_std      [B, N]
      terminal_samples / disc_samples  [B, N, M]  (only if return_samples)
      diag          dict incl. `clamp_maxerr` (the D1 assertion's measured error)
    """
    fs = int(model.frame_stack)
    C = BUNDLE_DIM
    D = fs * C
    B, N, K, A = cand_act.shape
    assert K == fs, f"candidate chunk is {K} frames but frame_stack is {fs}"
    assert A == ACT_DIM, f"candidate action dim {A} != {ACT_DIM}"
    assert init_obs.shape == (B, OBS_DIM), init_obs.shape
    H = int(H)
    M = int(M)
    gamma = default_gamma(H) if gamma is None else float(gamma)

    plan_tokens = int(np.ceil(H / fs))
    assert plan_tokens >= 1, "H must be >= 1"
    total_frames = fs * (1 + plan_tokens)
    sched = model.scheduling(plan_tokens)
    clip = float(model.cfg.clip_noise)

    init_obs = init_obs.to(device).float()
    cand_act = cand_act.to(device).float()

    # ---- conditioning token, built EXACTLY as df_plan.plan_bundles builds it ------------------
    init = torch.zeros(B, C, device=device)
    init[:, :OBS_DIM] = init_obs
    init = model.norm(init)
    init[:, OBS_DIM:] = 0.0
    init_tok = init.view(B, 1, C).repeat(1, fs, 1).reshape(B, D)          # [B, fs*C]

    cand_z = _act_z(model, cand_act)                                      # [B, N, fs, A]
    zero_z = _act_z(model, torch.zeros(A, device=device))                 # D2 ablation value

    # ---- D3: one noise draw per (anchor, M), expanded over the N candidates -------------------
    g = torch.Generator(device=device)
    g.manual_seed(int(seed))
    # crn_rows collapses the anchor axis to 1; `.expand` below broadcasts it back over B, so the
    # sampler sees identical noise on every row.  Shape is the only difference; nothing else changes.
    noise = torch.randn((plan_tokens, 1 if crn_rows else B, 1, M, D),
                        device=device, generator=g).clamp(-clip, clip)

    # ---- chunking over N only (cannot change a number: the noise is already fixed) ------------
    per_cand = (1 + plan_tokens) * M * 4.0 * D                            # bytes of plan per anchor-candidate
    cn = max(1, int(max_bytes / max(per_cand * B, 1.0)))
    cn = min(cn, N)

    term_s = torch.empty(B, N, M, device=device)
    disc_s = torch.empty(B, N, M, device=device)
    w = torch.from_numpy((gamma ** np.arange(H, dtype=np.float64)).astype(np.float32)).to(device)
    w = w / w.sum()

    clamp_err = 0.0
    n_chunks = 0
    for n0 in range(0, N, cn):
        n1 = min(N, n0 + cn)
        nn = n1 - n0
        bs = B * nn * M
        n_chunks += 1

        chunk = noise.expand(plan_tokens, B, nn, M, D).reshape(plan_tokens, bs, D)
        head = init_tok.view(B, 1, 1, D).expand(B, nn, M, D).reshape(1, bs, D)
        plan = torch.cat([head, chunk], 0)                                # [1+plan_tokens, bs, D]

        az = cand_z[:, n0:n1].view(B, nn, 1, fs, A).expand(B, nn, M, fs, A).reshape(bs, fs, A)

        def clamp_(p):
            """D1 (+ D2 when free_tail is False).  In-place on the plan tensor."""
            p[1].view(bs, fs, C)[:, :, OBS_DIM:OBS_DIM + ACT_DIM] = az
            if not free_tail and plan_tokens > 1:
                p[2:].view(-1, bs, fs, C)[:, :, :, OBS_DIM:OBS_DIM + ACT_DIM] = zero_z

        clamp_(plan)                                                      # once before the loop
        for m in range(sched.shape[0] - 1):
            frm = torch.from_numpy(np.concatenate([[0], sched[m]])).to(device)[:, None].repeat(1, bs)
            to = torch.from_numpy(np.concatenate([[0], sched[m + 1]])).to(device)[:, None].repeat(1, bs)
            plan[1:] = model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=None)[1:]
            clamp_(plan)                                                  # after EVERY step

        # ---- D1 assertion: what the sampler held, in raw units, is the candidate --------------
        got = _act_unz(model, plan[1].view(bs, fs, C)[:, :, OBS_DIM:OBS_DIM + ACT_DIM])
        want = cand_act[:, n0:n1].view(B, nn, 1, fs, A).expand(B, nn, M, fs, A).reshape(bs, fs, A)
        e = float((got - want).abs().max().item())
        clamp_err = max(clamp_err, e)
        if assert_clamp:
            assert e < clamp_tol, (
                f"D1 action clamp FAILED: recovered actions differ from the candidate by {e:.3e} "
                f"(tol {clamp_tol}); the value would not be the value of the candidate")

        # Reward channel only.  `model.unnorm(model.unstack(plan))` would materialise a second
        # copy of the whole (1.29 MB/sequence) plan; the reward is one channel of each frame, and
        # the frame order below IS `unstack`'s order (token-major, then frame within the token).
        r_all = plan.view(1 + plan_tokens, bs, fs, C)[..., -1].permute(0, 2, 1).reshape(
            total_frames, bs)
        r_all = r_all * model.data_std[-1] + model.data_mean[-1]          # unnormalised r_hat
        r = r_all[fs:fs + H].view(H, B, nn, M)                            # plan frames 1..H
        term_s[:, n0:n1] = r[H - 1]
        disc_s[:, n0:n1] = (r * w[:, None, None, None]).sum(0)
        del plan, r_all, r, chunk, head

    out = dict(
        terminal=term_s.mean(-1), disc=disc_s.mean(-1),
        terminal_std=term_s.std(-1, unbiased=False), disc_std=disc_s.std(-1, unbiased=False),
        diag=dict(clamp_maxerr=clamp_err, clamp_tol=float(clamp_tol),
                  H=H, M=M, N=int(N), B=int(B), gamma=float(gamma), free_tail=bool(free_tail),
                  frame_stack=fs, bundle_dim=C, plan_tokens=int(plan_tokens),
                  total_frames=int(total_frames), sched_rows=int(sched.shape[0]), crn_rows=bool(crn_rows),
                  sampling_timesteps=int(model.sampling_timesteps),
                  cand_per_chunk=int(cn), n_chunks=int(n_chunks), seed=int(seed),
                  guidance="none (guidance_fn=None) -- value route, not planner route"),
    )
    if return_samples:
        out["terminal_samples"] = term_s
        out["disc_samples"] = disc_s
    return out


AGGREGATIONS = ("terminal", "disc")