Download code_src/df_rise/smoke_df_plan.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 11.3 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/smoke_df_plan.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/smoke_df_plan.py
-
curl -L -o smoke_df_plan.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/smoke_df_plan.py
11.3 kB
| """CPU smoke for the Diffusion Forcing PLANNER (gen_q#274, item 1). | |
| WHY THIS EXISTS. `train_df.py` has a smoke (status/nb/df_train_smoke.txt) and `td_plan.py` has one | |
| (status/nb/td_plan_smoke.txt), but `df_plan.py` -- the file that carries the ONLY piece of the DF | |
| column that is our code rather than upstream's (the reward-guidance branch upstream leaves as | |
| `raise NotImplementedError`) -- has never been executed. Everything it could get wrong is silent: | |
| a guidance SIGN error would make DF minimise the provenance reward and still return a plausible | |
| success rate; a wrong weight vector would guide on the conditioning frames only; a padding bug would | |
| guide on frames the plan does not execute. None of those raise. | |
| The model here is randomly initialised and tiny -- this tests the PLANNER, not the world model. | |
| Everything asserted is a property that must hold for ANY weights. | |
| """ | |
| import sys, json, math | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| import numpy as np | |
| import torch | |
| from df_data import OBS_DIM, ACT_DIM, BUNDLE_DIM | |
| from df_core import DFRise, default_cfg | |
| from df_plan import plan_bundles, best_actions, _guidance_weights | |
| FAIL = [] | |
| def check(name, cond, extra=""): | |
| print(f"[{'PASS' if cond else 'FAIL'}] {name} {extra}") | |
| if not cond: | |
| FAIL.append(name) | |
| torch.manual_seed(0); np.random.seed(0) | |
| print(f"dims OBS={OBS_DIM} ACT={ACT_DIM} BUNDLE={BUNDLE_DIM} torch={torch.__version__}") | |
| # ---------------------------------------------------------------- T1 weights | |
| FS, GAMMA = 4, 0.9 | |
| w = _guidance_weights(FS, 6, 12, GAMMA, w_cond=10.0).numpy() | |
| exp = np.concatenate([np.full(FS, 10.0), GAMMA ** np.arange(6), np.zeros(12 - FS - 6)]) | |
| check("T1 weight vector == [w_cond]*fs + gamma^j + zero pad", np.allclose(w, exp, atol=1e-6), | |
| f"w={np.round(w,4).tolist()}") | |
| check("T1 padding frames carry ZERO weight", float(w[FS + 6:].sum()) == 0.0) | |
| # horizon longer than the room available must be truncated, not wrap around | |
| w2 = _guidance_weights(FS, 100, 12, GAMMA, w_cond=10.0).numpy() | |
| check("T1 over-long horizon truncates to the available frames", | |
| w2.shape == (12,) and np.allclose(w2[FS:], GAMMA ** np.arange(12 - FS), atol=1e-6)) | |
| # ---------------------------------------------------------------- tiny model | |
| cfg = default_cfg(network_size=32, num_layers=2, attn_heads=2, dim_feedforward=64, | |
| timesteps=100, sampling_timesteps=4, frame_stack=FS) | |
| mean = np.zeros(BUNDLE_DIM, np.float32) | |
| std = np.full(BUNDLE_DIM, 2.0, np.float32) # non-trivial, so unnorm() is exercised | |
| mean[-1], std[-1] = 0.25, 0.5 # reward channel gets its own scale | |
| model = DFRise(frame_stack=FS, n_tokens=4, mean=mean, std=std, cfg=cfg).eval() | |
| nparam = sum(p.numel() for p in model.parameters()) | |
| print(f"tiny model params={nparam/1e6:.2f}M sampling_timesteps={model.sampling_timesteps}") | |
| B, NP, H = 2, 4, 6 | |
| obs = torch.randn(B, OBS_DIM) | |
| def run(scale, seed=0, n_plans=NP, horizon=H): | |
| g = torch.Generator(device="cpu"); g.manual_seed(seed) | |
| return plan_bundles(model, obs, horizon, scale, GAMMA, n_plans=n_plans, | |
| device="cpu", generator=g) | |
| # ---------------------------------------------------------------- T2 shapes | |
| o0 = run(0.0) | |
| plan_tokens = int(math.ceil(H / FS)) | |
| check("T2 plan shape [H, B, n_plans, BUNDLE]", tuple(o0["plan"].shape) == (H, B, NP, BUNDLE_DIM), | |
| str(tuple(o0["plan"].shape))) | |
| check("T2 J shape [B, n_plans]", tuple(o0["J"].shape) == (B, NP), str(tuple(o0["J"].shape))) | |
| check("T2 J_iter has one row per scheduling step + 1", | |
| o0["J_iter"].shape == (o0["diag"]["sched_rows"], B, NP), str(o0["J_iter"].shape)) | |
| check("T2 plan_tokens = ceil(H/frame_stack)", o0["diag"]["plan_tokens"] == plan_tokens, | |
| f"{o0['diag']['plan_tokens']} vs {plan_tokens}") | |
| check("T2 no NaN/Inf in the plan", bool(torch.isfinite(o0["plan"]).all())) | |
| check("T2 unguided run reports guidance_scale 0.0", o0["diag"]["guidance_scale"] == 0.0) | |
| # ---------------------------------------------------------------- T3 determinism | |
| a = run(2.0, seed=7); b = run(2.0, seed=7) | |
| check("T3 same seed -> identical plan", torch.allclose(a["plan"], b["plan"], atol=0, rtol=0)) | |
| c = run(2.0, seed=8) | |
| check("T3 different seed -> different plan", not torch.allclose(a["plan"], c["plan"], atol=1e-6)) | |
| # ---------------------------------------------------------------- T4 GUIDANCE SIGN | |
| # The one that matters. Guidance must RAISE the objective it is handed. Upstream's sample_step | |
| # computes grad = -d(guidance_fn)/dx and ADDS sqrt(1-a)*grad to pred_noise, which is classifier | |
| # guidance in the ASCENT direction (diffusion.py:423-441) -- so a correct wiring means J at the end | |
| # of diffusion grows with guidance_scale. A sign error here would publish a DF column that actively | |
| # avoids the expert partition, at a success rate that would still look like a number. | |
| SEEDS = list(range(6)) | |
| J0 = np.array([float(run(0.0, seed=s)["J"].mean()) for s in SEEDS]) | |
| J3 = np.array([float(run(3.0, seed=s)["J"].mean()) for s in SEEDS]) | |
| J9 = np.array([float(run(9.0, seed=s)["J"].mean()) for s in SEEDS]) | |
| print(f"T4 J(scale=0) mean={J0.mean():.4f} J(3)={J3.mean():.4f} J(9)={J9.mean():.4f}") | |
| print(f"T4 per-seed J0={np.round(J0,3).tolist()}") | |
| print(f"T4 per-seed J3={np.round(J3,3).tolist()}") | |
| print(f"T4 per-seed J9={np.round(J9,3).tolist()}") | |
| check("T4 guidance INCREASES the objective (scale 3 > scale 0, every seed)", bool((J3 > J0).all()), | |
| f"wins={int((J3>J0).sum())}/{len(SEEDS)}") | |
| check("T4 more guidance -> more objective (scale 9 > scale 3, every seed)", bool((J9 > J3).all()), | |
| f"wins={int((J9>J3).sum())}/{len(SEEDS)}") | |
| check("T4 the effect is not numerical noise (mean gain > 1e-3)", | |
| float((J3 - J0).mean()) > 1e-3, f"gain={float((J3-J0).mean()):.5f}") | |
| # ---------------------------------------------------------------- T5 diagnostics are real | |
| o = run(3.0, seed=1) | |
| d = o["diag"] | |
| check("T5 J_spread > 0 with n_plans>1 (planner discriminates among its own samples)", | |
| d["J_spread"] > 0, f"J_spread={d['J_spread']:.5f}") | |
| check("T5 J_std > 0", d["J_std"] > 0, f"J_std={d['J_std']:.5f}") | |
| o1 = run(3.0, seed=1, n_plans=1) | |
| check("T5 n_plans=1 reports J_spread exactly 0 (documented, not an accident)", | |
| o1["diag"]["J_spread"] == 0.0) | |
| check("T5 J_gain == J_iter[-1]-J_iter[0] mean", | |
| abs(d["J_gain"] - float((o["J_iter"][-1] - o["J_iter"][0]).mean())) < 1e-5) | |
| check("T5 diag records gamma / horizon / n_plans verbatim", | |
| d["gamma"] == GAMMA and d["horizon_frames"] == H and d["n_plans"] == NP) | |
| # ---------------------------------------------------------------- T6 best_actions | |
| acts, sel = best_actions(o, execute_frames=3) | |
| check("T6 action shape [execute_frames, B, ACT_DIM]", tuple(acts.shape) == (3, B, ACT_DIM), | |
| str(tuple(acts.shape))) | |
| idx = o["J"].argmax(-1) | |
| man = torch.stack([o["plan"][:, i, idx[i]] for i in range(B)], 1) | |
| check("T6 best_actions selects the argmax-J candidate per batch element", | |
| torch.allclose(sel, man, atol=0, rtol=0), f"idx={idx.tolist()}") | |
| check("T6 executed actions are the ACT slice of the bundle", | |
| torch.allclose(acts, man[:3, :, OBS_DIM:OBS_DIM + ACT_DIM], atol=0, rtol=0)) | |
| # What the env will actually be handed. DF's action channel is unconstrained -- report the range so | |
| # a future clamp decision is made on evidence, not assumed. | |
| amax = float(acts.abs().max()) | |
| print(f"T6 |action|_max on an UNTRAINED model = {amax:.3f} " | |
| f"(env limit is 1.0; a trained model's range goes in the cell JSON)") | |
| check("T6 actions are finite", bool(torch.isfinite(acts).all())) | |
| # ---------------------------------------------------------------- T7 execute_frames > H must not | |
| # silently return a short queue that the policy then drains into an index error. | |
| acts_long, _ = best_actions(o, execute_frames=H + 5) | |
| check("T7 execute_frames > horizon returns at most H frames (caller must not over-request)", | |
| acts_long.shape[0] == H, f"got {acts_long.shape[0]} for H={H}") | |
| # ---------------------------------------------------------------- T8 horizon not a multiple of fs | |
| o7 = run(3.0, seed=2, horizon=7) # 7 frames, frame_stack 4 -> 2 tokens, 1 pad frame | |
| check("T8 non-multiple horizon returns exactly H frames", o7["plan"].shape[0] == 7) | |
| w7 = _guidance_weights(FS, 7, FS * (1 + 2), GAMMA).numpy() | |
| check("T8 the padded frame is excluded from the objective", float(w7[FS + 7:].sum()) == 0.0, | |
| f"tail={np.round(w7[FS:],4).tolist()}") | |
| # ------------------------------------------------- T9 DFPlannerPolicy: queue, clamp, health | |
| # `df_policy.DFPlannerPolicy.__init__` builds the DINOv2 encoder, which needs the RISE robomimic env | |
| # this venv does not have. Everything AFTER the encoder -- the replan cadence, the action clamp and | |
| # the action-range health -- is testable here, and it is the part that decides what the env is | |
| # actually handed. The encoder itself is exercised by the GPU smoke through the eval harness. | |
| import df_policy as dfp | |
| pol = object.__new__(dfp.DFPlannerPolicy) | |
| pol.model, pol.device = model, "cpu" | |
| pol.H, pol.guidance_scale, pol.gamma = H, 3.0, GAMMA | |
| pol.n_plans, pol.execute_frames = NP, 3 | |
| pol.step, pol.diag_path, pol.act_limit = 12345, "", 1.0 | |
| pol.gen = torch.Generator(device="cpu"); pol.gen.manual_seed(0) | |
| pol.enc = lambda obs_t: obs_t["state"] # stand in for PooledDinoState | |
| pol.reset() | |
| class _FakeObs(dict): | |
| pass | |
| ob = {"state": obs} # the stub encoder returns it as the [B, OBS] state | |
| # get_action indexes v[:, -1]; give the stub a tensor it can handle by bypassing that path | |
| pol.enc = lambda obs_t: obs | |
| a1 = pol.get_action({"state": obs.unsqueeze(1).repeat(1, 2, 1)}) | |
| check("T9 get_action returns [B, ACT_DIM]", tuple(a1.shape) == (B, ACT_DIM), str(tuple(a1.shape))) | |
| check("T9 one plan after the first action", len(pol._diag) == 1, f"plans={len(pol._diag)}") | |
| for _ in range(pol.execute_frames - 1): | |
| pol.get_action({"state": obs.unsqueeze(1).repeat(1, 2, 1)}) | |
| check("T9 no replan while the queue has actions (execute_frames=3 -> still 1 plan)", | |
| len(pol._diag) == 1, f"plans={len(pol._diag)}") | |
| pol.get_action({"state": obs.unsqueeze(1).repeat(1, 2, 1)}) | |
| check("T9 replans exactly when the queue empties", len(pol._diag) == 2, f"plans={len(pol._diag)}") | |
| check("T9 every emitted action is inside the env box", float(a1.abs().max()) <= 1.0 + 1e-6, | |
| f"|a|max={float(a1.abs().max()):.3f}") | |
| d9 = pol.diagnostics() | |
| print("T9 health: " + json.dumps({k: d9[k] for k in | |
| ("act_limit", "act_absmax", "act_clip_frac", "act_components", "plans", "n_plans")})) | |
| check("T9 act_absmax records the PRE-clamp magnitude (the clamp is not hidden)", | |
| d9["act_absmax"] > 1.0, f"act_absmax={d9['act_absmax']:.3f}") | |
| check("T9 act_clip_frac in [0,1] and >0 on this untrained model", | |
| 0.0 < d9["act_clip_frac"] <= 1.0, f"clip_frac={d9['act_clip_frac']:.3f}") | |
| check("T9 diagnostics carry J_spread / J_gain and the DF train step", | |
| "J_spread" in d9 and "J_gain" in d9 and d9["df_train_step"] == 12345) | |
| pol.reset() | |
| check("T9 reset() clears the plan log and the action-range counters", | |
| pol._diag == [] and pol._n_act == 0 and pol._a_absmax == 0.0) | |
| print("\nSMOKE " + ("FAILED: " + ", ".join(FAIL) if FAIL else "PASSED (all checks)")) | |
| sys.exit(1 if FAIL else 0) | |