Download code_src/df_rise/df_actprobe.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 7.08 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_actprobe.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_actprobe.py
-
curl -L -o df_actprobe.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_actprobe.py
7.08 kB
| """DOES DF'S ACTION CHANNEL PREDICT THE EXPERT'S ACTION, AND IS IT ALIGNED? (gen_q#274) | |
| Run 28 measured random-of-128 == argmax == 0.000 on RISE. Both arms sample from DF's OWN action | |
| distribution and execute it, so 0.000 says DF's actions are non-functional REGARDLESS of selection -- | |
| the planner's ranking is not what is being tested there. This probe tests the action path alone, on | |
| held-out episodes, with no environment and no success number. | |
| Q1 IS THE ACTION HEAD INFORMATIVE AT ALL? | |
| R2 = 1 - MSE(pred) / MSE(predict the dataset's mean action), per channel and pooled. R2 <= 0 | |
| means the action channel carries no information about what the expert did, and 0.000 success is | |
| fully explained without any reference to the planner, the guidance, or the world model. | |
| Reported for a single sample and for the K-sample mean (the action a policy should execute is the | |
| posterior mean, not one draw -- see df_fidmean.py). | |
| Q2 IS IT ALIGNED? `df_data.sample` builds bundle[t] = (obs_t, act_t, rew) -- act_t is the action | |
| taken AT obs_t (df_data.py:123-124). `plan_bundles` conditions on bundle[0] and predicts frames | |
| 1..T. `best_actions` (df_plan.py:141) then returns plan[0:execute_frames]'s actions, which are | |
| a_1..a_8, and df_policy executes them starting from s_0. If bundle[t]'s action is a_t, the first | |
| action executed at s_0 should be a_0 -- so the chunk may be one frame early. This scores the | |
| predicted action at plan index h against the data's action at bundle[h+1+lag] for | |
| lag in {-2,-1,0,+1,+2} and reports which lag maximises R2. If the best lag is not 0, the | |
| executed chunk is misaligned and that is an integration bug, not a fact about the method. | |
| A misalignment cannot be diagnosed from success rate (every cell reads 0.000) nor from | |
| act_absmax/act_clip_frac (a shifted expert action is still in the box), which is why it needs its own | |
| measurement. | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, os, 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, ACT_DIM # noqa: E402 | |
| from df_probe import load_df # noqa: E402 | |
| from df_plan import plan_bundles # noqa: E402 | |
| A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM | |
| 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=128) | |
| p.add_argument("--kmax", type=int, default=32) | |
| p.add_argument("--execute-frames", type=int, default=8) | |
| p.add_argument("--seed", type=int, default=0) | |
| a = p.parse_args() | |
| 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, mask = data.sample(a.n_states, rng, split="val", device=dev) # [W, B, BUNDLE_DIM] | |
| init_obs = bundle[0, :, :OBS_DIM] | |
| plan = plan_bundles(model, init_obs, horizon_frames=T, guidance_scale=0.0, gamma=0.0, | |
| n_plans=a.kmax, device=dev)["plan"] # [T, B, K, C] | |
| pred_act = plan[..., A0:A1] # [T, B, K, ACT_DIM] | |
| # the baseline every R2 is against: the dataset's own mean action (a constant predictor) | |
| mean_act = torch.as_tensor(np.asarray(data.act, np.float32).mean(0), device=dev) # [ACT_DIM] | |
| res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=int(a.n_states), kmax=a.kmax, | |
| execute_frames=a.execute_frames, frame_stack=int(meta["frame_stack"]), | |
| train_steps=int(meta.get("steps", -1)), | |
| mean_act=[float(v) for v in mean_act.cpu()], per_lag={}, per_h={}) | |
| def r2(pred, tgt): | |
| """1 - MSE(pred)/MSE(constant mean-action predictor), pooled and per channel.""" | |
| num = ((pred - tgt) ** 2).mean(0) # [ACT_DIM] | |
| den = ((mean_act[None, :] - tgt) ** 2).mean(0) | |
| return (1.0 - num.sum() / den.sum().clamp_min(1e-12)).item(), \ | |
| [(1.0 - n / d).item() for n, d in zip(num, den.clamp_min(1e-12))] | |
| # ---- Q2: alignment. score the EXECUTED chunk (plan indices 0..execute_frames-1) at each lag ---- | |
| for lag in (-2, -1, 0, 1, 2): | |
| P, Tg = [], [] | |
| for h in range(a.execute_frames): | |
| j = h + 1 + lag # bundle index the plan index h is being scored against | |
| if j < 0 or j >= bundle.shape[0]: | |
| continue | |
| w = mask[j].bool() | |
| if w.sum() == 0: | |
| continue | |
| P.append(pred_act[h][w].mean(1)) # K-sample mean, the action a policy should execute | |
| Tg.append(bundle[j][w, A0:A1]) | |
| if not P: | |
| continue | |
| pooled, per_ch = r2(torch.cat(P), torch.cat(Tg)) | |
| res["per_lag"][str(lag)] = {"r2_pooled_Kmean": pooled, "r2_per_channel_Kmean": per_ch, | |
| "n": int(sum(x.shape[0] for x in P))} | |
| best = max(res["per_lag"], key=lambda k: res["per_lag"][k]["r2_pooled_Kmean"]) if res["per_lag"] else None | |
| res["best_lag"] = best | |
| res["as_implemented_lag"] = 0 | |
| res["misaligned"] = (best is not None and int(best) != 0) | |
| # ---- Q1: informativeness per plan index, single sample vs K-sample mean, at lag 0 ---- | |
| for h in range(min(a.execute_frames, T)): | |
| j = h + 1 | |
| if j >= bundle.shape[0]: | |
| continue | |
| w = mask[j].bool() | |
| if w.sum() == 0: | |
| continue | |
| tgt = bundle[j][w, A0:A1] | |
| one, _ = r2(pred_act[h][w][:, 0, :], tgt) | |
| km, per_ch = r2(pred_act[h][w].mean(1), tgt) | |
| res["per_h"][str(h)] = {"r2_single_sample": one, "r2_Kmean": km, | |
| "r2_per_channel_Kmean": per_ch, | |
| "pred_std_over_K": pred_act[h][w].std(1).mean().item(), | |
| "tgt_std": tgt.std(0).mean().item(), "n": int(w.sum())} | |
| os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True) | |
| with open(a.out, "w") as f: | |
| json.dump(res, f, indent=1) | |
| print("[df_actprobe] step", step, "R2 vs mean-action baseline (K-sample mean):") | |
| for lag, r in sorted(res["per_lag"].items(), key=lambda kv: int(kv[0])): | |
| flag = " <-- as implemented" if int(lag) == 0 else "" | |
| star = " *BEST*" if lag == best else "" | |
| print(f" lag {int(lag):+d} R2 {r['r2_pooled_Kmean']:+.4f} (n={r['n']}){flag}{star}") | |
| for h, r in sorted(res["per_h"].items(), key=lambda kv: int(kv[0])): | |
| print(f" plan idx {h:>2s} R2 single {r['r2_single_sample']:+.4f} Kmean {r['r2_Kmean']:+.4f}" | |
| f" predstd/tgtstd {r['pred_std_over_K']/max(r['tgt_std'],1e-9):.2f}") | |
| print("[df_actprobe] wrote", a.out) | |
| if __name__ == "__main__": | |
| main() | |