Download code_src/df_rise/df_poolcmp.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 9.06 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_poolcmp.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_poolcmp.py
-
curl -L -o df_poolcmp.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_poolcmp.py
9.06 kB
| """IS DF'S CANDIDATE POOL SELECTABLE AT ALL, AND DOES ITS OBJECTIVE RANK IT? (gen_q#274 / #282) | |
| Every DF cell reads 0.000: argmax_J, random-of-128 and mean-of-128 are all exactly 0.000 on 50 | |
| episodes x 2 seeds x 2 tasks. Three decoding rules that differ only in WHICH of the same 128 | |
| candidates gets executed cannot all land on the same number unless one of two things is true: | |
| (H1) THE POOL IS DEAD. The 128 candidates are effectively the same chunk, so selection is a no-op | |
| by construction. Then no objective -- not DF's, not a perfect one -- can ever make the | |
| planner route work, and the route is dead until the GENERATOR is fixed. | |
| (H2) THE POOL IS FINE AND THE OBJECTIVE IS BLIND. The pool contains good chunks and J does not | |
| rank them, so every rule draws an equally bad candidate. Then the generator is fine and the | |
| whole problem is the objective (consistent with J_gain = +5.71..+16.33 while success = 0.000: | |
| DF maximises something, just not success). | |
| This probe separates them on held-out episodes with NO environment and NO success number. It draws | |
| one pool per state exactly as df_policy does (same plan_bundles, same guidance, same gamma) and | |
| scores each candidate's EXECUTED chunk against the expert's actions. | |
| r2_random mean over candidates == what the random-of-N control executes | |
| r2_Kmean the K-sample mean chunk == what the mean-of-N arm executes | |
| r2_argmaxJ the candidate J picks == what every landed DF cell executes | |
| r2_oracle the per-state BEST candidate == the ceiling of ANY selection rule | |
| `r2_oracle` uses the expert action to pick, so it is a DIAGNOSTIC UPPER BOUND, NOT A DF COLUMN and is | |
| never to be quoted as a score. It bounds what a perfect scorer could extract from this pool. | |
| oracle_gain = r2_oracle - r2_random the headroom selection could possibly capture | |
| captured = (r2_argmaxJ - r2_random) / oracle_gain the fraction J actually captures | |
| spearman_J corr(J_k, -err_k) within a state does J rank candidates in the right direction? | |
| READ-OUT, REGISTERED IN ADVANCE (gen_q#274, before the numbers land): | |
| * oracle_gain <= 0.05 -> H1. The pool is dead; argmax == random == mean is FORCED by the | |
| generator and no objective fix can reach 10%. Report the planner route as blocked on the | |
| decoder, with this number as the evidence. | |
| * oracle_gain >= 0.20 and spearman_J <= 0.05 -> H2. The pool carries the headroom and J is blind | |
| to it; the objective is the entire problem and is worth unlimited effort. | |
| * spearman_J <= -0.05 -> J is ANTI-correlated with matching the expert: DF's objective actively | |
| prefers the worse candidate, which would explain argmax being no better than random. | |
| """ | |
| 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 _rank(x, axis=-1): | |
| """average-free ordinal ranks along axis (ties broken by order; adequate for continuous J/err).""" | |
| order = np.argsort(x, axis=axis) | |
| r = np.empty_like(order) | |
| np.put_along_axis(r, order, np.arange(x.shape[axis]).reshape( | |
| [1] * (x.ndim - 1) + [x.shape[axis]]).repeat(x.shape[0], 0), axis=axis) | |
| return r.astype(np.float64) | |
| 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=64) | |
| p.add_argument("--n-plans", type=int, default=128) | |
| p.add_argument("--execute-frames", type=int, default=8) | |
| p.add_argument("--horizon-frames", type=int, default=20) | |
| p.add_argument("--guidance-scale", type=float, default=0.0) | |
| p.add_argument("--gamma", type=float, default=0.95) | |
| 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) | |
| bundle, mask = data.sample(a.n_states, rng, split="val", device=dev) # [W, B, C] | |
| init_obs = bundle[0, :, :OBS_DIM] | |
| H = min(a.horizon_frames, data.T) | |
| out = plan_bundles(model, init_obs, horizon_frames=H, guidance_scale=a.guidance_scale, | |
| gamma=a.gamma, n_plans=a.n_plans, device=dev) | |
| plan, J = out["plan"], out["J"] # [H,B,K,C], [B,K] | |
| K = a.n_plans | |
| # executed chunk: plan indices 0..execute_frames-1, scored against bundle[h+1] (lag 0, as | |
| # implemented). keep only states whose whole chunk is inside the episode. | |
| hs = [h for h in range(min(a.execute_frames, H)) if h + 1 < bundle.shape[0]] | |
| w = mask[[h + 1 for h in hs]].bool().all(0) # [B] | |
| nB = int(w.sum()) | |
| pred = torch.stack([plan[h][w][..., A0:A1] for h in hs]) # [h,B',K,A] | |
| tgt = torch.stack([bundle[h + 1][w, A0:A1] for h in hs]) # [h,B',A] | |
| Jw = J[w] # [B',K] | |
| mean_act = torch.as_tensor(np.asarray(data.act, np.float32).mean(0), device=dev) | |
| den = ((mean_act[None, None, :] - tgt) ** 2).mean((0, 2)) # [B'] per-state baseline MSE | |
| def r2_from(errs): | |
| """errs [B'] per-state MSE -> pooled R2 against the constant mean-action predictor.""" | |
| return float(1.0 - errs.sum().item() / den.sum().clamp_min(1e-12).item()) | |
| err_k = ((pred - tgt[:, :, None, :]) ** 2).mean((0, 3)) # [B',K] per candidate MSE | |
| err_rand = err_k.mean(1) # random-of-K in expectation | |
| err_km = ((pred.mean(2) - tgt) ** 2).mean((0, 2)) # mean-of-K chunk | |
| err_best = err_k.min(1).values # ORACLE (diagnostic only) | |
| err_worst = err_k.max(1).values | |
| err_amax = err_k.gather(1, Jw.argmax(1, keepdim=True)).squeeze(1) # what the planner executes | |
| r2 = dict(r2_random=r2_from(err_rand), r2_Kmean=r2_from(err_km), | |
| r2_argmaxJ=r2_from(err_amax), r2_oracle=r2_from(err_best), | |
| r2_antioracle=r2_from(err_worst)) | |
| r2["oracle_gain"] = r2["r2_oracle"] - r2["r2_random"] | |
| r2["argmaxJ_gain"] = r2["r2_argmaxJ"] - r2["r2_random"] | |
| r2["captured"] = (r2["argmaxJ_gain"] / r2["oracle_gain"]) if abs(r2["oracle_gain"]) > 1e-9 else float("nan") | |
| # does J rank the pool in the right direction? spearman(J_k, -err_k) within each state. | |
| Jn, en = Jw.cpu().numpy(), err_k.cpu().numpy() | |
| rJ, re = _rank(Jn), _rank(-en) | |
| rJ -= rJ.mean(1, keepdims=True); re -= re.mean(1, keepdims=True) | |
| sp = (rJ * re).sum(1) / np.sqrt((rJ ** 2).sum(1) * (re ** 2).sum(1) + 1e-12) | |
| r2["spearman_J_vs_negerr_mean"] = float(sp.mean()) | |
| r2["spearman_J_vs_negerr_std"] = float(sp.std()) | |
| r2["spearman_frac_positive"] = float((sp > 0).mean()) | |
| # pool diversity: how different ARE the candidates, in action and in predicted observation? | |
| r2["act_pool_std"] = float(pred.std(2).mean()) | |
| r2["act_tgt_std"] = float(tgt.std(1).mean()) | |
| r2["act_pool_std_over_tgt"] = r2["act_pool_std"] / max(r2["act_tgt_std"], 1e-9) | |
| obs = torch.stack([plan[h][w][..., :OBS_DIM] for h in hs]) | |
| r2["obs_pool_std"] = float(obs.std(2).mean()) | |
| r2["J_spread"] = float((Jw.max(1).values - Jw.min(1).values).mean()) | |
| r2["J_std_within_state"] = float(Jw.std(1).mean()) | |
| res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=int(a.n_states), n_states_used=nB, | |
| n_plans=K, execute_frames=a.execute_frames, horizon_frames=H, | |
| guidance_scale=a.guidance_scale, gamma=a.gamma, seed=a.seed, | |
| act_align=str(meta.get("act_align", "ours")), planner_diag=out["diag"], **r2) | |
| 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(f"[df_poolcmp] step {step} n_states {nB} n_plans {K} g {a.guidance_scale}") | |
| print(f" R2 random {r2['r2_random']:+.4f} Kmean {r2['r2_Kmean']:+.4f} " | |
| f"argmaxJ {r2['r2_argmaxJ']:+.4f} ORACLE {r2['r2_oracle']:+.4f} (diagnostic only)") | |
| print(f" oracle_gain {r2['oracle_gain']:+.4f} argmaxJ_gain {r2['argmaxJ_gain']:+.4f} " | |
| f"captured {r2['captured']:.3f}") | |
| print(f" spearman(J, -err) {r2['spearman_J_vs_negerr_mean']:+.4f} " | |
| f"+-{r2['spearman_J_vs_negerr_std']:.3f} frac>0 {r2['spearman_frac_positive']:.2f}") | |
| print(f" pool act std/tgt {r2['act_pool_std_over_tgt']:.3f} J_spread {r2['J_spread']:.3f}") | |
| print("[df_poolcmp] wrote", a.out) | |
| if __name__ == "__main__": | |
| main() | |