Download code_src/df_rise/df_probe.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 8.8 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_probe.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_probe.py
-
curl -L -o df_probe.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_probe.py
8.8 kB
| """INTERROGATE THE DF PLANNER'S OBJECTIVE (gen_q#274, brief leads 2 and 3). | |
| Three questions, one job, no environment and no success number -- this is a diagnostic, not a score. | |
| P1 IS THE OBJECTIVE INFORMATIVE AT ALL? | |
| The guidance maximises J = sum_j w_j * r_hat_j where r_hat is DF's own predicted reward | |
| channel and the reward is the binary data-provenance label (constant over an episode). If | |
| r_hat cannot separate a held-out expert episode from a held-out non-expert one, then J is | |
| noise and "the optimiser improves its objective" (J_gain +5.71/+12.63/+16.33) means only that | |
| it is ascending an undertrained head adversarially. Reported as AUC over val episodes plus the | |
| raw spread of r_hat -- a head whose spread is ~0 has nothing to rank with. | |
| P2 IS THE GUIDANCE SCALE CONNECTED? (the brief's explicit request) | |
| Same conditioning observation, same generator seed, guidance in {0,1,5,20,100,500}. Report the | |
| L2 between each plan and the guidance-0 plan, split into the obs part and the act part. ~0 means | |
| the knob is inert and the four-point 0..5 sweep measured nothing. | |
| P3 DOES THE CHOSEN PLAN MOVE? | |
| ||obs_pred[h] - obs_cond|| for the argmax-J candidate, against the DATA's own | |
| ||obs[t+h] - obs[t]|| at the same h and the same states. A ratio << 1 is a planner whose | |
| predicted future is the present -- i.e. one that maximises in-distribution-ness by standing still. | |
| Also emitted per guidance scale: act_absmax / act_clip_frac (the action marginal, FINDING C). | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, os, sys | |
| from pathlib import Path | |
| 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, BUNDLE_DIM # noqa: E402 | |
| from df_core import DFRise # noqa: E402 | |
| from df_plan import plan_bundles # noqa: E402 | |
| def load_df(ckpt, device): | |
| ck = torch.load(ckpt, map_location="cpu", weights_only=False) | |
| meta = ck["meta"] | |
| m = DFRise(frame_stack=int(meta["frame_stack"]), n_tokens=int(meta["n_tokens"]), | |
| mean=ck["mean"], std=ck["std"], cfg=ck["cfg"]).to(device) | |
| m.load_state_dict(ck["model"]) | |
| m.eval() | |
| return m, meta, int(ck["step"]) | |
| def auc(scores, labels): | |
| """rank AUC; 0.5 = uninformative.""" | |
| s, y = np.asarray(scores, float), np.asarray(labels, float) | |
| pos, neg = s[y > 0.5], s[y <= 0.5] | |
| if len(pos) == 0 or len(neg) == 0: | |
| return float("nan") | |
| order = np.argsort(np.concatenate([pos, neg]), kind="mergesort") | |
| ranks = np.empty(len(order), float); ranks[order] = np.arange(1, len(order) + 1) | |
| # average ties | |
| allv = np.concatenate([pos, neg]) | |
| for v in np.unique(allv): | |
| m = allv == v | |
| if m.sum() > 1: | |
| ranks[m] = ranks[m].mean() | |
| return float((ranks[:len(pos)].sum() - len(pos) * (len(pos) + 1) / 2) / (len(pos) * len(neg))) | |
| 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("--horizon", type=int, default=16) | |
| p.add_argument("--n-plans", type=int, default=128) | |
| p.add_argument("--gamma", type=float, default=0.99) | |
| p.add_argument("--w-cond", type=float, default=10.0) | |
| p.add_argument("--n-states", type=int, default=24, help="conditioning states for P1/P3") | |
| p.add_argument("--act-limit", type=float, default=1.0) | |
| 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) | |
| res = dict(ckpt=a.ckpt, cache=a.cache, step=step, horizon=a.horizon, n_plans=a.n_plans, | |
| gamma=a.gamma, w_cond=a.w_cond, frame_stack=int(meta["frame_stack"]), | |
| chan_share=meta.get("chan_share", ""), train_steps=int(meta.get("steps", -1))) | |
| # ---- conditioning states drawn from HELD-OUT episodes, balanced over the provenance label ---- | |
| picks = [] # (row, label, ep, t) | |
| for e in data.val_eps: | |
| L = int(data.ep_len[e]) | |
| for t in rng.integers(0, max(1, L - a.horizon - 1), size=max(1, a.n_states // max(1, len(data.val_eps)))): | |
| picks.append((int(data.ep_from[e] + t), float(data.ep_success[e]), int(e), int(t))) | |
| rng.shuffle(picks) | |
| picks = picks[:a.n_states] | |
| rows = np.array([p_[0] for p_ in picks]); labs = np.array([p_[1] for p_ in picks]) | |
| res["n_val_eps"] = int(len(data.val_eps)) | |
| res["val_label_mean"] = float(data.ep_success[data.val_eps].mean()) | |
| res["n_states"] = int(len(picks)) | |
| obs = torch.from_numpy(data.obs_rows(rows).astype(np.float32)).to(dev) # [S, OBS] | |
| # ---- P2 + P1 + P3: one pass per guidance scale, SAME generator seed every time ---- | |
| scales = [0.0, 1.0, 5.0, 20.0, 100.0, 500.0] | |
| per_scale, ref_plan = {}, None | |
| for gs in scales: | |
| g = torch.Generator(device=dev); g.manual_seed(1234 + a.seed) | |
| out = plan_bundles(model, obs, a.horizon, gs, a.gamma, n_plans=a.n_plans, device=dev, | |
| generator=g, w_cond=a.w_cond, collect_iters=True) | |
| plan, J = out["plan"], out["J"] # [H, S, n_plans, C], [S, n_plans] | |
| idx = J.argmax(-1) | |
| sel = plan[:, torch.arange(plan.shape[1], device=dev), idx] # [H, S, C] | |
| act = sel[..., OBS_DIM:OBS_DIM + ACT_DIM] | |
| d = dict(out["diag"]) | |
| d["act_absmax"] = float(act.abs().max()) | |
| d["act_clip_frac"] = float((act.abs() > a.act_limit).float().mean()) | |
| # P1: the score the guidance actually reads, per conditioning state (mean over candidates | |
| # AND the argmax candidate) -> AUC against the episode's true provenance label. | |
| r_pred = sel[..., -1] # [H, S] | |
| d["rhat_mean"] = float(r_pred.mean()); d["rhat_std"] = float(r_pred.std()) | |
| d["rhat_frame_spread"] = float((r_pred.max(0).values - r_pred.min(0).values).mean()) | |
| score_argmax = r_pred.mean(0).cpu().numpy() | |
| score_pool = plan[..., -1].mean((0, 2)).cpu().numpy() | |
| d["auc_rhat_argmax"] = auc(score_argmax, labs) | |
| d["auc_rhat_pool"] = auc(score_pool, labs) | |
| d["rhat_by_label"] = {"expert": float(score_pool[labs > 0.5].mean()) if (labs > 0.5).any() else None, | |
| "other": float(score_pool[labs <= 0.5].mean()) if (labs <= 0.5).any() else None} | |
| # P3: does the predicted latent move? | |
| mv = {} | |
| for h in (1, 2, 4, 8, 16): | |
| if h > a.horizon: | |
| continue | |
| pm = float((sel[h - 1, :, :OBS_DIM] - obs).norm(dim=-1).mean()) | |
| dm = [] | |
| for (row, _l, e, t) in picks: | |
| L = int(data.ep_len[e]); tt = min(t + h, L - 1) | |
| o2 = data.obs_rows(np.array([data.ep_from[e] + tt]))[0] | |
| o1 = data.obs_rows(np.array([row]))[0] | |
| dm.append(float(np.linalg.norm(o2 - o1))) | |
| mv[f"h{h}"] = dict(plan_move=pm, data_move=float(np.mean(dm)), | |
| ratio=pm / max(1e-8, float(np.mean(dm)))) | |
| d["move"] = mv | |
| # P2: L2 against the guidance-0 plan, same seed | |
| if ref_plan is None: | |
| ref_plan = plan.detach().clone() | |
| d["l2_vs_g0_obs"] = 0.0; d["l2_vs_g0_act"] = 0.0; d["l2_vs_g0_rew"] = 0.0 | |
| else: | |
| df_ = plan - ref_plan | |
| d["l2_vs_g0_obs"] = float(df_[..., :OBS_DIM].norm(dim=-1).mean()) | |
| d["l2_vs_g0_act"] = float(df_[..., OBS_DIM:OBS_DIM + ACT_DIM].norm(dim=-1).mean()) | |
| d["l2_vs_g0_rew"] = float(df_[..., -1].abs().mean()) | |
| # scale-free: the obs L2 relative to the plan's own obs norm at guidance 0 | |
| d["l2_vs_g0_obs_rel"] = d["l2_vs_g0_obs"] / max(1e-8, float(ref_plan[..., :OBS_DIM].norm(dim=-1).mean())) | |
| per_scale[str(gs)] = d | |
| print(f"[df_probe] gs={gs}: J_mean={d['J_mean']:.4g} J_gain={d['J_gain']:.4g} " | |
| f"spread={d['J_spread']:.4g} auc_pool={d['auc_rhat_pool']:.3f} " | |
| f"l2obs={d['l2_vs_g0_obs']:.4g} (rel {d['l2_vs_g0_obs_rel']:.3g}) " | |
| f"actmax={d['act_absmax']:.3f} clip={d['act_clip_frac']:.4f} " | |
| f"move_h8={mv.get('h8', {}).get('ratio', float('nan')):.3f}", flush=True) | |
| res["per_scale"] = per_scale | |
| Path(a.out).parent.mkdir(parents=True, exist_ok=True) | |
| Path(a.out).write_text(json.dumps(res, indent=1)) | |
| print("[df_probe] wrote " + a.out, flush=True) | |
| if __name__ == "__main__": | |
| main() | |