File size: 11,811 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
"""Diffusion Forcing AS A PLANNER, guided by the binary data-provenance reward (gen_q#274).

This is upstream's `df_planning.py:plan()` loop -- the same pyramid scheduling matrix, the same
conditioning token, the same `diffusion_model.sample_step(..., guidance_fn=...)` -- with ONE
substitution, and it is the substitution the issue asks for:

    upstream guides toward a GOAL observation (`goal_guidance`, df_planning.py:148).
    we guide toward the REWARD channel.

Why the substitution is forced rather than chosen: a goal observation is privileged information no
other column in tab:flagship receives, so a goal-guided DF would not be a fair baseline; and
upstream's own reward branch is inert --

    df_planning.py:180-182
        else:
            # dense reward seeting, guide with reward
            raise NotImplementedError("reward guidance not officially supported yet, although implemented")

-- so there is no released reward-guidance code to run.  The three lines beneath that raise are the
recipe we implement: a reconstruction weight on the conditioning frames, a geometric weight over the
plan horizon, zero on the padding.  Upstream hard-codes 0.997; we use the cell's own gamma, because
#274 asks for the horizon to be reported as H = 1/(1-gamma), the same family #273 sweeps.

GUIDANCE OBJECTIVE.  With the plan's predicted x0 bundle decoded to (obs, act, r_hat):
    J = sum_j w_j * r_hat_j,   w = [w_cond]*frame_stack + [gamma^j for j < H] + [0]*pad
    guidance_fn returns guidance_scale * J, and upstream's sample_step adds
    grad_x J to the denoiser's mean (models/diffusion.py:424-440).
r_hat is DF's own predicted reward channel, trained on the provenance label -- so nothing outside
the shared reward enters, and DF needs none of the project's separate reward heads.

CANDIDATES.  `n_plans` independent plans are diffused in one batch from the same conditioning
observation and the executed one is argmax_J.  This is NOT the shared 128-candidate set the value
columns rank -- DF proposes its own actions, which is what "run it as a planner" means -- so the
number is disclosed with every score, per #274 ("never compare a 16-candidate planner to a
128-candidate one silently").

PLANNER DIAGNOSTICS, returned on every call and logged per control step:
    J_mean / J_std / J_spread   the guidance objective across the n_plans candidates (sample spread);
    J_iter                      J after each step of the scheduling matrix (per-iteration improvement);
    J_gain                      J_iter[-1] - J_iter[0].
A cell whose J_spread is ~0 has a planner that is not discriminating between its own samples, and a
cell whose J_gain is <= 0 has guidance that is not working; both must be visible next to the score.

THE REWARD CHANNEL IS UNBOUNDED, AND `r_max` IS THE OPT-IN SATURATION (gen_q#274/#282, 2026-09-24).
r_hat is not a bounded head: it is one raw continuous channel of the diffused bundle
(df_core.py:94, "Bundle = [obs (1545) | act (7) | reward (1)]"), read back through
`model.unnorm(...)` -- so the units of `plan` and of `objective` are RAW LABEL UNITS, the same units
as DFCacheData's `ep_success`, which is BINARY and lives in {0, 1}.  Nothing in the diffusion or in
the guidance constrains r_hat to that interval, so ascending J can be solved by pushing r_hat ABOVE
the label's own maximum, which is a region the model only ever extrapolates into.
`r_max=None` (the default) is the original, unbounded objective -- byte-identical to every landed
number.  `r_max=1.0` replaces r_hat by min(r_hat, 1.0) EVERYWHERE the objective is evaluated: in the
J returned for candidate ranking AND inside `guidance_fn`, whose gradient upstream takes with
`torch.autograd.grad` (models/diffusion.py:424-440) -- and the gradient of `clamp` in the saturated
region is exactly ZERO, which is the whole point: once a frame's predicted provenance has reached the
label maximum, guidance stops pushing on it.
FAIRNESS: 1.0 is the maximum of the binary data-provenance label itself, which is the reward every
column in tab:flagship shares.  It is not privileged simulator state, not an outcome reward, not a
success bit, and no RSM/IQL critic is involved.  Only the DEFINITION of the shared reward is used.
"""
from __future__ import annotations

import numpy as np
import torch

from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM


def _guidance_weights(frame_stack, horizon_frames, total_frames, gamma, w_cond=10.0, device="cpu"):
    """Upstream's dead-code recipe: [10]*frame_stack + [gamma**j]*horizon + [0]*pad."""
    w = np.zeros(total_frames, np.float32)
    w[:frame_stack] = w_cond
    h = min(horizon_frames, total_frames - frame_stack)
    if gamma > 0:
        w[frame_stack:frame_stack + h] = gamma ** np.arange(h, dtype=np.float32)
    else:
        w[frame_stack:frame_stack + h] = 1.0
    return torch.from_numpy(w).to(device)


@torch.no_grad()
def plan_bundles(model, init_obs, horizon_frames, guidance_scale, gamma, n_plans=1,
                 device="cuda", generator=None, w_cond=10.0, collect_iters=True, r_max=None):
    """init_obs [B, OBS_DIM] (already in the project's z-scored state units).

    init_obs may also be [B, frame_stack, OBS_DIM] -- the agent's own last `frame_stack`
    observations, oldest first -- for a checkpoint trained with `--cond-history 1`
    (DF_MAKEITWORK mug-WM sweep, 2026-09-24).  The 2-D path is untouched and bit-identical, so every
    landed number and every existing checkpoint reads exactly as before.  See
    `DFRise.make_sequence` for why an observation history is not privileged information.

    r_max: None = the original unbounded objective (default, bit-identical to every landed number);
           a float = saturate the predicted reward at that value in J and in the guidance gradient.

    Returns dict:
      plan   [horizon_frames, B, n_plans, BUNDLE_DIM]  UNNORMALISED bundles (obs | act | r_hat)
      J      [B, n_plans]        guidance objective of each candidate at the end of diffusion
      J_iter [M, B, n_plans]     the same objective after each scheduling-matrix step
      diag   dict of the planner diagnostics described in the module docstring
    """
    fs = model.frame_stack
    B = init_obs.shape[0]
    plan_tokens = int(np.ceil(horizon_frames / fs))
    total_frames = fs * (1 + plan_tokens)
    sched = model.scheduling(plan_tokens)
    S = model.sampling_timesteps

    # conditioning token: the current observation, actions/rewards zeroed after normalisation
    if init_obs.dim() == 3:                      # [B, fs, OBS_DIM] -- real observation history
        assert init_obs.shape[1] == fs, (init_obs.shape, fs)
        init = torch.zeros(B * n_plans, fs, BUNDLE_DIM, device=device)
        init[:, :, :OBS_DIM] = init_obs.repeat_interleave(n_plans, 0)
        init = model.norm(init)
        init[:, :, OBS_DIM:] = 0.0
        init_tok = init.reshape(1, B * n_plans, fs * BUNDLE_DIM)
    else:
        init = torch.zeros(B * n_plans, BUNDLE_DIM, device=device)
        init[:, :OBS_DIM] = init_obs.repeat_interleave(n_plans, 0)
        init = model.norm(init)
        init[:, OBS_DIM:] = 0.0
        init_tok = init.view(1, B * n_plans, 1, BUNDLE_DIM).repeat(1, 1, fs, 1).reshape(
            1, B * n_plans, fs * BUNDLE_DIM)

    clip = float(model.cfg.clip_noise)
    chunk = torch.randn((plan_tokens, B * n_plans, fs * BUNDLE_DIM), device=device,
                        generator=generator).clamp(-clip, clip)
    plan = torch.cat([init_tok, chunk], 0)

    wts = _guidance_weights(fs, horizon_frames, total_frames, gamma, w_cond, device)

    def objective(x_stacked):
        """x_stacked [t, b, fs*C] (normalised x0) -> scalar sum over the batch of weighted r_hat.

        `model.unnorm` puts r in RAW LABEL UNITS (the binary provenance label's own {0,1}), so the
        clamp below is stated in those units and nothing else has to be converted."""
        r = model.unnorm(model.unstack(x_stacked))[..., -1]        # [total_frames, b]
        if r_max is not None:
            r = r.clamp(max=float(r_max))                          # zero gradient above r_max
        return (r * wts[:, None]).sum(0)

    def guidance_fn(x0):
        return guidance_scale * objective(x0).sum()

    gfn = guidance_fn if guidance_scale else None
    J_iter = []
    if collect_iters:
        J_iter.append(objective(plan).view(B, n_plans).cpu().numpy())
    for m in range(sched.shape[0] - 1):
        frm = torch.from_numpy(np.concatenate([[0], sched[m]])).to(device)
        to = torch.from_numpy(np.concatenate([[0], sched[m + 1]])).to(device)
        frm = frm[:, None].repeat(1, B * n_plans)
        to = to[:, None].repeat(1, B * n_plans)
        plan[1:] = model.diffusion_model.sample_step(plan, None, frm, to, guidance_fn=gfn)[1:]
        if collect_iters:
            J_iter.append(objective(plan).view(B, n_plans).cpu().numpy())

    full = model.unnorm(model.unstack(plan))                        # [total_frames, b, C]
    body = full[fs:fs + horizon_frames].view(horizon_frames, B, n_plans, BUNDLE_DIM)
    J = objective(plan).view(B, n_plans)
    # RAW (never clamped) predicted reward over the whole sequence, so the saturation diagnostic is
    # measurable in both arms: how much of the objective's weight sits above the label maximum.
    r_raw = full[..., -1]                                           # [total_frames, b]
    r_ref = 1.0 if r_max is None else float(r_max)
    wpos = wts > 0
    Ji = np.stack(J_iter) if collect_iters else None
    Jn = J.cpu().numpy()
    diag = dict(J_mean=float(Jn.mean()), J_std=float(Jn.std()),
                J_spread=float((Jn.max(1) - Jn.min(1)).mean()) if n_plans > 1 else 0.0,
                J_gain=float((Ji[-1] - Ji[0]).mean()) if Ji is not None else float("nan"),
                n_plans=int(n_plans), guidance_scale=float(guidance_scale), gamma=float(gamma),
                w_cond=float(w_cond),        # so status/nb/df_jrange.py never has to assume 10.0
                W_cond_total=float(w_cond) * int(fs),
                W_plan_total=float(wts[fs:].sum().item()),
                horizon_frames=int(horizon_frames), plan_tokens=int(plan_tokens),
                sampling_steps=int(S), sched_rows=int(sched.shape[0]),
                # --- reward-range diagnostics, in RAW label units (label max = 1.0) ---
                r_max=(None if r_max is None else float(r_max)),
                clamped=bool(r_max is not None),
                rhat_raw_mean=float(r_raw[wpos].mean().item()),
                rhat_raw_max=float(r_raw[wpos].max().item()),
                rhat_raw_min=float(r_raw[wpos].min().item()),
                rhat_raw_p99=float(torch.quantile(r_raw[wpos].flatten().float(), 0.99).item()),
                # fraction of the OBJECTIVE-CARRYING frames whose raw r_hat is above the label max
                frac_frames_above_rmax=float((r_raw[wpos] > r_ref).float().mean().item()),
                frac_cond_frames_above_rmax=float((r_raw[:fs] > r_ref).float().mean().item()),
                frac_plan_frames_above_rmax=float(
                    (r_raw[fs:fs + horizon_frames] > r_ref).float().mean().item()),
                # share of J's weight that the clamp would remove / removed
                J_excess_above_rmax=float(
                    (((r_raw - r_ref).clamp(min=0)) * wts[:, None]).sum(0).mean().item()))
    return dict(plan=body, J=J, J_iter=Ji, diag=diag)


def best_actions(out, execute_frames):
    """argmax_J candidate -> [execute_frames, B, ACT_DIM] actions to execute before replanning."""
    plan, J = out["plan"], out["J"]
    idx = J.argmax(-1)                                              # [B]
    B = plan.shape[1]
    sel = plan[:, torch.arange(B, device=plan.device), idx]         # [H, B, C]
    return sel[:execute_frames, :, OBS_DIM:OBS_DIM + ACT_DIM], sel