File size: 19,658 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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#!/usr/bin/env python
"""Train Diffusion Forcing on an rsm_rise task corpus (gen_q#274).

  python train_df.py --cache cache/<task> --out runs/<task>/wm/df [--steps 100000] ...

Same corpus, same state definition, same split and the same binary provenance reward every other
column in tab:flagship sees -- see df_data.py's header.  The diffusion model is upstream's
(code/diffusion_forcing @ 475e0bca, main branch); see df_core.py's header for what is ours.

HEALTH NUMBERS ARE PRODUCED HERE, not bolted on later (#274's standing rule).  Every `--eval-every`
steps the trainer reports, on HELD-OUT episodes:
  val/loss                   the diffusion loss on validation windows;
  fid/obs_rmse_h<H>          ROLLOUT FIDELITY: unguided (guidance 0) plans from a true start state,
                             observation RMSE against the TRUE future at H frames, in the same
                             z-scored units the state is defined in, next to
  fid/obs_rmse_h<H>_naive    the RMSE of the trivial "the state never changes" predictor at the same
                             H.  A ratio >= 1 means the model's roll-out carries no information
                             about the future and any planner score built on it must be flagged.
"""
from __future__ import annotations

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

import numpy as np
import torch

sys.path.insert(0, str(Path(__file__).resolve().parent))
from df_data import DFCacheData, OBS_DIM, ACT_DIM, BUNDLE_DIM      # noqa: E402
from df_core import DFRise, default_cfg, DF_COMMIT                  # noqa: E402


def parse():
    p = argparse.ArgumentParser()
    p.add_argument("--cache", required=True)
    p.add_argument("--out", required=True)
    p.add_argument("--frame-stack", type=int, default=8)   # = the project's hop/chunk
    p.add_argument("--n-tokens", type=int, default=8)      # 64-frame training window
    p.add_argument("--batch", type=int, default=32)
    p.add_argument("--micro", type=int, default=8)
    p.add_argument("--lr", type=float, default=1e-4)
    p.add_argument("--weight-decay", type=float, default=1e-4)
    p.add_argument("--warmup-steps", type=int, default=2000)
    p.add_argument("--steps", type=int, default=100000)
    p.add_argument("--network-size", type=int, default=256)
    p.add_argument("--num-layers", type=int, default=12)
    p.add_argument("--attn-heads", type=int, default=4)
    p.add_argument("--dim-feedforward", type=int, default=1024)
    p.add_argument("--sampling-timesteps", type=int, default=50)
    p.add_argument("--ema", type=float, default=0.995)
    p.add_argument("--seed", type=int, default=0)
    p.add_argument("--eval-every", type=int, default=2500)
    p.add_argument("--save-every", type=int, default=10000)
    p.add_argument("--fid-batch", type=int, default=16)
    # run 28: the default used to start at 10, but the planner COMMITS RR_DF_EXECUTE=8 frames per
    # decision, so every published DF health number was measured at horizons the planner never
    # acts on.  status/nb/df_actfid.txt: df_A reads fid/obs_ratio_h10 = 0.962 (healthy) and 1.43
    # at H=1 (worse than stay-put).  Measuring 1..8 as well is a strictly larger diagnostic; it
    # changes no training quantity.
    p.add_argument("--fid-horizons", default="1,2,4,8,10,20,50")
    # run 29 (gen_q#274).  Target GRADIENT SHARE of the three channel groups, "obs:act:rew".
    # "" = the uniform `loss.mean()` every landed DF cell used, which spends 99.49% of the gradient
    # on the 1545 observation channels, 0.45% on the 7 action channels and 0.064% on the reward
    # channel.  "4:2:1" is DF's OWN published planning bundle (obs 4 | act 2 | reward 1), i.e. this
    # knob moves TOWARD the configuration the method works in, not away from it.
    # This is a loss reduction over channels we already train.  It adds no signal: same corpus, same
    # binary provenance reward, same state definition, same split, same evaluation.
    p.add_argument("--chan-share", default="")
    p.add_argument("--wandb-name", default="")
    # run 32 (gen_q#274), FINDING G -- ACTION/OBSERVATION ALIGNMENT.
    # Upstream's own planning trainer (code/diffusion_forcing_paper/algorithms/diffusion_forcing/
    # df_planning.py:_preprocess_batch, L96-101) shifts the OBSERVATIONS by one and leaves the
    # ACTIONS unshifted:
    #     init_obs     = observations[:, 0]
    #     observations = cat([observations[:, 1:], zeros_like(observations[:, -1:])], 1)
    #     actions      = actions                       # <- NOT shifted
    #     bundles      = make_bundle(observations, actions, rewards)
    # so upstream's bundle token t is (obs_{t+1}, a_t, r_t) -- "the action that PRODUCED obs_{t+1}",
    # which is also exactly how its rollout appends frames (df_planning.py:308 make_bundle(obs,
    # action, reward) after envs.step(action)).  Our train_df.py:189 does
    # `make_sequence(bundle[1:], init_obs)`, which shifts BOTH channels, so our token t is
    # (obs_{t+1}, a_{t+1}).  df_plan.best_actions then executes plan[0:k]'s actions starting from
    # s_0 -- i.e. a_1..a_k from s_0 -- and the action for the CURRENT state is never predicted at
    # all (it is zeroed in the conditioning token).  That is a train/execute mismatch, not a
    # convention choice: our EXECUTOR already follows upstream's convention while our TRAINER does
    # not.
    # "ours" reproduces every already-measured cell byte-for-byte; "upstream" is the fix.
    p.add_argument("--act-align", default="ours", choices=["ours", "upstream"])
    # ---- DF_MAKEITWORK mug-WM sweep (2026-09-24).  All three default to the value every landed
    # checkpoint used, so a command that does not pass them is bit-identical to before.
    #
    # --cond-history.  Upstream's conditioning token is ONE observation repeated frame_stack times
    # (df_planning.py:69-71, DFRise.make_sequence, df_plan.plan_bundles), so the model is asked to
    # predict the next frame from a POSITION with no VELOCITY.  That is the most likely mechanism
    # behind the one fidelity defect both tasks share: `ratio_inf` at h=1 is 1.39 (mug) / 1.27
    # (threading) -- worse than standing still with sampling noise removed -- while h>=4 is < 1 on
    # both.  With --cond-history 1 the conditioning token is the agent's OWN last frame_stack
    # observations.  FAIRNESS: an observation history is not privileged information -- DINO-WM and
    # every frame-stacking policy in tab:flagship already read one and the executing policy has its
    # own past for free.  No object pose, no simulator state, no success bit, no outcome reward; the
    # action and reward channels of the conditioning token stay zeroed exactly as before.
    # COST: the plan starts at frame frame_stack instead of frame 1, so a config that wants the same
    # 64-frame plan asks for one more token (--n-tokens 9 at --frame-stack 8).
    p.add_argument("--cond-history", type=int, default=0, choices=[0, 1])
    # --beta-schedule / --objective: upstream's own options (diffusion.py:84-91, :165-178), promoted
    # to knobs.  The measured motivation is that a quarter to a half of every fid/obs_ratio_h* this
    # project published was the sampler's own noise (var_frac 0.24-0.45, status/nb/df_fidmean), which
    # is a statement about the noise schedule and the loss parameterisation, not about capacity.
    p.add_argument("--beta-schedule", default="linear", choices=["linear", "cosine", "sigmoid"])
    p.add_argument("--objective", default="pred_x0", choices=["pred_x0", "pred_noise", "pred_v"])
    # GPU packs run on the preemptable queue, so a run must be able to pick itself up where it was
    # killed.  ckpt_last.pt carries the step and the optimiser state; --resume 0 disables.
    p.add_argument("--resume", type=int, default=1)
    return p.parse_args()


def seq_body(bundle, align):
    """bundle [W,B,C] -> the T=W-1 frames the plan tokens are trained on.

    align="ours"     : token t = bundle[t+1]                  = (obs_{t+1}, a_{t+1}, r)
    align="upstream" : obs from bundle[t+1], act/reward from bundle[t]
                                                              = (obs_{t+1}, a_t,     r)
    See --act-align.  The reward channel here is the episode-constant provenance label, so the
    shift is a no-op on it except at the padded tail; it is shifted anyway so the layout is
    upstream's verbatim and nothing has to be argued about later.
    """
    if align == "ours":
        return bundle[1:]
    return torch.cat([bundle[1:, :, :OBS_DIM], bundle[:-1, :, OBS_DIM:]], dim=-1)


def split_window(bundle, mask, frame_stack, align, cond_history):
    """window [W,B,C] + mask [W,B] -> (cond_obs, body, body_mask), one place for both layouts.

    cond_history=0 (default, and what every checkpoint on disk used):
        cond_obs [B, OBS]        = frame 0, which make_sequence / plan_bundles repeat frame_stack
                                   times.  body = frames 1..T, body_mask = mask[1:].
    cond_history=1 (--cond-history):
        cond_obs [B, fs, OBS]    = the REAL frames 0..fs-1, oldest first.
        body                     = whole plan tokens starting at frame fs, under the SAME --act-align
                                   convention, so body[j] carries (obs_{fs+j}, a_{fs+j-1}).
        body_mask                = mask[fs : fs+len(body)], the padding flag of those same frames.
    In both layouts the LAST CONDITIONING FRAME is the state the plan is predicted from -- frame 0
    in the first, frame fs-1 in the second -- so `body[h]` is h+1 steps into the future either way
    and the stay-put control stays the same comparison.
    """
    if not cond_history:
        return bundle[0, :, :OBS_DIM], seq_body(bundle, align), mask[1:]
    fs = int(frame_stack)
    body = seq_body(bundle[fs - 1:], align)               # [W-fs, B, C], body[j] -> frame fs+j
    n = (body.shape[0] // fs) * fs                        # whole tokens only
    if n == 0:
        raise SystemExit("--cond-history 1 needs at least frame_stack plan frames: raise --n-tokens")
    return (bundle[:fs, :, :OBS_DIM].permute(1, 0, 2).contiguous(), body[:n], mask[fs:fs + n])


@torch.no_grad()
def fidelity(model, data, rng, device, horizons, n=16, align="ours", cond_history=0):
    """Unguided roll-out vs the true future, and the stay-put control at the same horizons."""
    from df_plan import plan_bundles
    model.eval()
    bundle, mask = data.sample(n, rng, split="val", device=device)
    cond_obs, body, m = split_window(bundle, mask, model.frame_stack, align, cond_history)
    T = body.shape[0]
    # the plan is predicted from the LAST conditioning frame; the stay-put control is that frame held
    init_obs = cond_obs if cond_obs.dim() == 2 else cond_obs[:, -1]
    out = {}
    plan = plan_bundles(model, cond_obs, horizon_frames=T, guidance_scale=0.0, gamma=0.0,
                        n_plans=1, device=device)["plan"][:, :, 0, :]        # [T, B, C]
    true_obs = body[:, :, :OBS_DIM]
    pred_obs = plan[:, :, :OBS_DIM]
    for H in horizons:
        h = min(H, T) - 1
        if h < 0 or m[h].sum() == 0:
            continue
        w = m[h].bool()
        err = ((pred_obs[h][w] - true_obs[h][w]) ** 2).mean(-1).sqrt().mean().item()
        naive = ((init_obs[w] - true_obs[h][w]) ** 2).mean(-1).sqrt().mean().item()
        out[f"fid/obs_rmse_h{H}"] = err
        out[f"fid/obs_rmse_h{H}_naive"] = naive
        out[f"fid/obs_ratio_h{H}"] = err / max(naive, 1e-8)
    model.train()
    return out


def channel_weights(spec, device):
    """"obs:act:rew" target gradient shares -> per-channel weight [BUNDLE_DIM], mean 1.

    Group g with n_g channels and target share s_g gets weight s_g/n_g per channel, so the group's
    contribution to the mean is proportional to s_g regardless of how wide it is.  The vector is then
    renormalised to mean 1 so the TOTAL loss scale -- and therefore the effective learning rate --
    is unchanged from the uniform reduction; only the split between the groups moves.
    Returns (tensor, diagnostic dict of the realised shares)."""
    s = [float(x) for x in spec.split(":")]
    if len(s) != 3 or min(s) < 0 or sum(s) <= 0:
        raise SystemExit(f"--chan-share must be 'obs:act:rew' with non-negative entries, got {spec!r}")
    n = [OBS_DIM, ACT_DIM, BUNDLE_DIM - OBS_DIM - ACT_DIM]
    per = [si / sum(s) / ni for si, ni in zip(s, n)]
    w = torch.cat([torch.full((ni,), pi) for ni, pi in zip(n, per)])
    w = w / w.mean()
    tot = float(w.sum())          # loss.mean() weights every channel alike, so a group's share of
                                  # the gradient is its share of sum(w)
    shares = {g: float(w[a_:b_].sum() / tot) for g, (a_, b_) in
              zip(("obs", "act", "rew"), ((0, OBS_DIM), (OBS_DIM, OBS_DIM + ACT_DIM),
                                          (OBS_DIM + ACT_DIM, BUNDLE_DIM)))}
    return w.to(device), shares


def main():
    a = parse()
    dev = "cuda" if torch.cuda.is_available() else "cpu"
    torch.manual_seed(a.seed); np.random.seed(a.seed)
    out = Path(a.out); out.mkdir(parents=True, exist_ok=True)
    data = DFCacheData(a.cache, frame_stack=a.frame_stack, n_tokens=a.n_tokens, seed=a.seed)
    mean, std = data.bundle_stats(seed=a.seed)
    cfg = default_cfg(network_size=a.network_size, num_layers=a.num_layers, attn_heads=a.attn_heads,
                      dim_feedforward=a.dim_feedforward, sampling_timesteps=a.sampling_timesteps,
                      frame_stack=a.frame_stack, beta_schedule=a.beta_schedule,
                      objective=a.objective)
    model = DFRise(frame_stack=a.frame_stack, n_tokens=a.n_tokens, mean=mean, std=std, cfg=cfg).to(dev)
    ema = {k: v.detach().clone() for k, v in model.state_dict().items()}
    n_par = sum(p.numel() for p in model.parameters())
    print(f"[train_df] params {n_par/1e6:.2f} M  device {dev}  bundle {BUNDLE_DIM}  "
          f"plan {data.T} frames  upstream {DF_COMMIT[:12]}", flush=True)

    chan_w, chan_shares = (None, None)
    if a.chan_share:
        chan_w, chan_shares = channel_weights(a.chan_share, dev)
        print(f"[train_df] chan_share {a.chan_share!r} -> realised gradient shares "
              f"{ {k: round(v, 4) for k, v in chan_shares.items()} }  "
              f"w_obs {chan_w[0]:.4g} w_act {chan_w[OBS_DIM]:.4g} w_rew {chan_w[-1]:.4g}", flush=True)

    opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=a.weight_decay,
                            betas=(0.9, 0.999))
    rng = np.random.default_rng(a.seed)
    wb = None
    if a.wandb_name and os.environ.get("RSM_WANDB_ENTITY"):
        import wandb
        wb = wandb.init(entity=os.environ["RSM_WANDB_ENTITY"], project=os.environ.get("WANDB_PROJECT", "rsm_rise"),
                        name=a.wandb_name, config=vars(a))
    horizons = [int(x) for x in a.fid_horizons.split(",")]
    meta = dict(vars(a), upstream_commit=DF_COMMIT, bundle_dim=BUNDLE_DIM, obs_dim=OBS_DIM,
                act_dim=ACT_DIM, params=n_par, plan_frames=data.T, window_frames=data.W,
                n_train_eps=int(len(data.train_eps)), n_val_eps=int(len(data.val_eps)),
                n_expert_eps=int(data.ep_success.sum()))
    (out / "META.json").write_text(json.dumps(meta, indent=1, default=str))

    start_step = 0
    last = out / "ckpt_last.pt"
    if a.resume and last.exists():
        ck = torch.load(last, map_location=dev, weights_only=False)
        model.load_state_dict(ck["online"] if "online" in ck else ck["model"])
        ema = {k: v.to(dev) for k, v in ck["ema"].items()}
        if "opt" in ck:
            opt.load_state_dict(ck["opt"])
        start_step = int(ck["step"])
        rng = np.random.default_rng(a.seed + start_step)   # do not replay the same window order
        print(f"[train_df] RESUMED from {last} at step {start_step}", flush=True)
        if start_step >= a.steps:
            print("[train_df] already complete", flush=True); return

    t0 = time.time()
    for step in range(start_step + 1, a.steps + 1):
        for g in opt.param_groups:                       # upstream's manual warmup (df_base.py:63)
            g["lr"] = a.lr * min(1.0, step / max(1, a.warmup_steps))
        opt.zero_grad(set_to_none=True)
        tot, nmb = 0.0, 0
        for _ in range(max(1, a.batch // a.micro)):
            bundle, mask = data.sample(a.micro, rng, "train", dev)
            cond_obs, body, bmask = split_window(bundle, mask, a.frame_stack, a.act_align,
                                                 a.cond_history)
            xs = model.make_sequence(body, cond_obs)
            # per-frame weight: 1 on the conditioning token and on real frames, 0 on tail padding
            fw = torch.cat([torch.ones(a.frame_stack, bundle.shape[1], device=dev), bmask], 0)
            fw = fw.view(-1, a.frame_stack, bundle.shape[1]).permute(0, 2, 1)     # [t, B, fs]
            tok_mask = fw.amax(-1)
            k = model.noise_levels(xs, tok_mask)
            _, loss = model.loss(xs, k, weight=fw, chan_w=chan_w)
            (loss / max(1, a.batch // a.micro)).backward()
            tot += float(loss.detach()); nmb += 1
        torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
        opt.step()
        with torch.no_grad():
            for k_, v in model.state_dict().items():
                if v.dtype.is_floating_point:
                    ema[k_].mul_(a.ema).add_(v, alpha=1 - a.ema)
                else:
                    ema[k_].copy_(v)

        if step % 100 == 0:
            msg = {"step": step, "loss": tot / nmb, "lr": opt.param_groups[0]["lr"],
                   "s_per_step": (time.time() - t0) / max(1, step - start_step)}
            print("[train_df] " + json.dumps(msg), flush=True)
            if wb: wb.log(msg, step=step)
        if step % a.eval_every == 0 or step == a.steps:
            vb, vm = data.sample(a.micro, rng, "val", dev)
            with torch.no_grad():
                vcond, vbody, vbmask = split_window(vb, vm, a.frame_stack, a.act_align,
                                                    a.cond_history)
                xs = model.make_sequence(vbody, vcond)
                fw = torch.cat([torch.ones(a.frame_stack, vb.shape[1], device=dev), vbmask], 0)
                fw = fw.view(-1, a.frame_stack, vb.shape[1]).permute(0, 2, 1)
                _, vl = model.loss(xs, model.noise_levels(xs, fw.amax(-1)), weight=fw,
                                   chan_w=chan_w)
            h = fidelity(model, data, np.random.default_rng(a.seed + 1), dev, horizons, a.fid_batch,
                         align=a.act_align, cond_history=a.cond_history)
            rec = {"step": step, "val/loss": float(vl), **h}
            print("[train_df] EVAL " + json.dumps(rec), flush=True)
            (out / "health.jsonl").open("a").write(json.dumps(rec) + "\n")
            if wb: wb.log(rec, step=step)
        if step % a.save_every == 0 or step == a.steps:
            # ckpt_s*: the EMA weights (what the planner loads).  ckpt_last: EMA + online + optimiser,
            # so a preempted run resumes exactly rather than restarting.
            torch.save({"model": ema, "cfg": cfg, "meta": meta,
                        "mean": mean, "std": std, "step": step}, out / f"ckpt_s{step}.pt")
            tmp = out / "ckpt_last.pt.tmp"
            torch.save({"model": ema, "ema": ema, "online": model.state_dict(),
                        "opt": opt.state_dict(), "cfg": cfg, "meta": meta,
                        "mean": mean, "std": std, "step": step}, tmp)
            os.replace(tmp, out / "ckpt_last.pt")
    print("[train_df] done", flush=True)


if __name__ == "__main__":
    main()