Download code_src/df_rise/df_poolcmp2.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 28.7 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_poolcmp2.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_poolcmp2.py
-
curl -L -o df_poolcmp2.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_poolcmp2.py
28.7 kB
| """THREE CHEAP EXTENSIONS OF df_poolcmp.py (gen_q#274 / #282) -- ALL DIAGNOSTICS, NO SUCCESS NUMBER. | |
| df_poolcmp.py answered the question it was registered for: the POOL IS ALIVE (oracle_gain 0.30-1.40 | |
| on held-out states) and the OBJECTIVE IS THE PROBLEM (spearman(J,-err) <= +0.05 in 3 of 4 cells, | |
| argmaxJ_gain NEGATIVE in 3 of 4 -- executing the argmax-J candidate is WORSE than drawing one at | |
| random). This file asks the three follow-ups, on the SAME held-out machinery: no environment, no | |
| rollout, no success number, and the expert action is used ONLY to compute the error that the rank | |
| diagnostics are scored against and the r2_oracle upper bound. Nothing from RSM/IQL touches DF's | |
| candidates (fairness rule 7); no goal observation is used anywhere. | |
| E1 PLAN-LENGTH SWEEP. Upstream's own maze2d recipe on the main branch plans chunk_size = 600 | |
| frames = 60 tokens and executes open_loop_horizon = 50; our RISE cells plan ceil(20/8) = 3 tokens | |
| and execute 8. Does spearman(J, -err) turn POSITIVE at a longer plan? Each arm re-diffuses the | |
| pool at a different horizon_frames H and re-scores it at several execute windows E. | |
| THE CEILING, MEASURED, NOT ASSUMED (reported in the JSON as `ceiling`): | |
| * the backbone is upstream models/transformer.py, whose position embedding is a SinusoidalPosEmb | |
| evaluated on `torch.arange(seq_len)` at call time -- there is NO learned table and therefore NO | |
| hard context cap. Any token count runs. | |
| * the checkpoints were TRAINED on 1 conditioning token + n_tokens plan tokens = 1 + 8 = 9 tokens | |
| of frame_stack 8, i.e. a 64-frame plan. H <= 64 is IN DISTRIBUTION; H > 64 needs more plan | |
| tokens than the model ever saw and is flagged `extrapolation: true` on the arm. | |
| * the GROUND TRUTH also has to exist: scoring frame h needs bundle[h+1], so the data window must | |
| be at least H+1 frames. DFCacheData's window is independent of the model, so this file widens | |
| it (n_tokens = ceil((maxH+1)/frame_stack)) purely to have targets; every episode in both | |
| corpora is >= 194 frames, so the widening costs only the usual tail masking. | |
| E2 RANK-RULE PANEL. The same pools, scored by several rules: | |
| J the planner's own objective, argmax == what every landed DF cell executes | |
| J_neg argmin J -- THE ANTI-OBJECTIVE, A DIAGNOSTIC. If it beats random while argmax J | |
| loses to random, J is anti-correlated with matching the expert. It is a | |
| measurement of J's sign, NOT a proposed column and never to be quoted as a rule. | |
| absJ argmax |J| | |
| J_final r_hat at the FINAL predicted frame of the plan | |
| J_plansum r_hat summed over the plan horizon with UNIFORM weights (no discount, no cond term) | |
| J_wplan the discounted plan part of J only (J with the conditioning term removed) | |
| J_cond the conditioning-frame part of J. This is not a curiosity: the weights are | |
| [w_cond]*frame_stack + gamma^j, so at frame_stack 8 / gamma 0.95 / H 20 the | |
| conditioning term carries W_cond_total 80 of the W_cond_total + W_plan_total 92.8 | |
| total weight -- 86% of the objective is the model's reconstruction of r_hat on the | |
| token it was GIVEN. J_cond's gain says how much of the ranking that share drives. | |
| Every rule reports r2, gain over random, and spearman(score, -err). | |
| E3 WHAT J ACTUALLY REWARDS. The standing hypothesis (brief, lead 3): the provenance reward is ~1 | |
| wherever the model believes it is in distribution, so "maximise predicted provenance" is solved by | |
| STANDING STILL. For the argmax-J candidate vs a random one we report how far the predicted | |
| observation latent MOVES over the plan -- L2 between the first and last predicted latent, the | |
| per-step latent delta norm, and the distance from the conditioning observation -- plus the | |
| predicted provenance trajectory r_hat_j and its terminal value, plus the action norm. The single | |
| number is `latent_travel_ratio_argmaxJ_over_random`: < 1 confirms the hypothesis. | |
| The data's OWN travel over the same H at the same states is reported as the scale. | |
| E4 THE REWARD CLAMP (`--r-max`, added 2026-09-24 -- THE READ-OUT IS REGISTERED HERE, BEFORE ANY | |
| NUMBER EXISTS). | |
| THE PREMISE, MEASURED FIRST (see `status/nb/df_clamp.txt` header and df_plan.py's docstring): | |
| `plan_bundles` returns `model.unnorm(model.unstack(plan))` and `objective` reads r through the | |
| same `model.unnorm`, so BOTH are in RAW LABEL UNITS -- the units of DFCacheData's `ep_success`, | |
| which is the binary data-provenance label and lives in {0, 1}. Raw r = 0 reads as 0.000 and raw | |
| r = 1 reads as 1.000; nothing here is z-scored. The landed unclamped run | |
| (status/nb/df_poolcmp2.txt, job 1897107) reports `rhat_final_argmaxJ` 2.073 / 2.285 / 3.092 at | |
| guidance 5.0 -- 2-3x ABOVE the label's own maximum -- while the same cells at guidance 0.0 sit at | |
| 0.18-0.55, right on the corpora's own label means (mug train label mean 0.148, threading 0.568). | |
| So guidance IS driving r_hat out of the label's range, and the clamp tests whether that is what | |
| breaks the ranking. | |
| WHAT THE CLAMP CHANGES AND WHAT IT DOES NOT. Only the planner's objective/guidance: | |
| r_hat -> min(r_hat, r_max) inside `objective`, which is used both for the J that ranks candidates | |
| and inside `guidance_fn`, whose gradient upstream takes through this expression | |
| (models/diffusion.py:424-440). The gradient of a clamp in the saturated region is ZERO, so a | |
| frame already at the label maximum stops attracting guidance. NOTHING IS RETRAINED, no weights | |
| change, the vendored checkout is untouched, and `--r-max` unset reproduces every landed number. | |
| FAIRNESS. r_max = 1.0 is the maximum of the binary provenance reward itself -- the reward every | |
| column in tab:flagship shares. It is not privileged simulator state, not an outcome reward, not | |
| a success bit, and no RSM/IQL critic touches DF's candidates (stream rule 7). Only the | |
| DEFINITION of the shared label is used, so every column could apply it. | |
| REGISTERED READ-OUT (written down before the number exists): | |
| * If under clamping `argmaxJ_gain` turns POSITIVE and `spearman(J,-err)` turns POSITIVE, the | |
| UNBOUNDED reward channel is the cause of the planner failure and the clamp is the fix; the | |
| next wave is a real RISE eval with controls. | |
| * If they stay <= 0 under clamping, the clamp is NOT the fix. Report it plainly as a negative | |
| result and name the remaining candidate causes. | |
| The clamped and unclamped arms run side by side at the same seed, states, checkpoints and | |
| guidance grid, so the only difference between two matched rows is min(r_hat, r_max). | |
| THE J-DERIVED RULES ARE CLAMPED TOO, and they have to be: J_cond is computed as J - J_wplan, an | |
| identity that only holds if both halves use the same r_hat. E3's r_hat reporting stays RAW on | |
| purpose -- it is how far outside the label range the sample still goes even when the objective | |
| can no longer see it. | |
| """ | |
| from __future__ import annotations | |
| import argparse, json, math, os, sys | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) | |
| OBS_DIM, ACT_DIM = 1545, 7 | |
| A0, A1 = OBS_DIM, OBS_DIM + ACT_DIM | |
| # ---------------------------------------------------------------- rank helpers | |
| def _rank(x): | |
| """ordinal ranks along the last axis of a [B, K] array (ties by order; J and err are continuous).""" | |
| x = np.asarray(x, np.float64) | |
| order = np.argsort(x, axis=-1) | |
| r = np.empty_like(order) | |
| np.put_along_axis(r, order, np.broadcast_to(np.arange(x.shape[-1]), x.shape).copy(), axis=-1) | |
| return r.astype(np.float64) | |
| def spearman_rows(a, b): | |
| """per-row spearman between two [B, K] arrays -> (mean, std, frac>0, per-row array).""" | |
| ra, rb = _rank(a), _rank(b) | |
| ra = ra - ra.mean(-1, keepdims=True) | |
| rb = rb - rb.mean(-1, keepdims=True) | |
| sp = (ra * rb).sum(-1) / np.sqrt((ra ** 2).sum(-1) * (rb ** 2).sum(-1) + 1e-12) | |
| return float(sp.mean()), float(sp.std()), float((sp > 0).mean()), sp | |
| def panel(scores, err_k, den, r2_random): | |
| """scores/err_k [B,K] numpy, den [B] numpy -> r2 / gain / spearman for argmax(scores).""" | |
| idx = scores.argmax(-1) | |
| e = np.take_along_axis(err_k, idx[:, None], -1).squeeze(-1) | |
| r2 = float(1.0 - e.sum() / max(den.sum(), 1e-12)) | |
| m, s, f, _ = spearman_rows(scores, -err_k) | |
| # A rule whose score does not VARY across the pool selects an arbitrary candidate: its "gain" is | |
| # then one draw of noise, not a ranking. J_cond is exactly this -- token 0 is never denoised, so | |
| # the conditioning frames are identical in every candidate. Emitted so no table can hide it. | |
| sd = float(np.std(scores, axis=-1).mean()) | |
| return dict(r2=r2, gain_over_random=r2 - r2_random, | |
| spearman_vs_negerr_mean=m, spearman_vs_negerr_std=s, spearman_frac_positive=f, | |
| score_std_within_state=sd, | |
| degenerate_constant_score=bool(sd < 1e-9)) | |
| # ---------------------------------------------------------------- arm scoring | |
| def score_arm(acts, rhat, trav, step_d, from_cond, actnorm, J, bundle, mask, den_act, | |
| H, gamma, execute_list, data_travel, data_step, data_actnorm, r_max=None): | |
| """Everything downstream of the diffusion for ONE horizon arm. Pure numpy/torch on CPU tensors. | |
| acts [H, B, K, ACT] predicted actions of every candidate | |
| rhat [H, B, K] predicted provenance channel over the plan frames | |
| trav [B, K] ||obs_pred[H-1] - obs_pred[0]|| | |
| step_d [B, K] mean_j ||obs_pred[j] - obs_pred[j-1]|| | |
| from_cond [B, K] ||obs_pred[H-1] - obs_cond|| | |
| actnorm [B, K] mean_j ||act_pred[j]|| | |
| J [B, K] the planner's own objective | |
| bundle [W, B, C] / mask [W, B] the held-out window (EXPERT ACTION USED ONLY HERE) | |
| """ | |
| res = {} | |
| wplan = (gamma ** np.arange(H, dtype=np.float64)) if gamma > 0 else np.ones(H) | |
| # E4: the J-derived rules must use the SAME r_hat the objective used, or `J_cond = J - J_wplan` | |
| # stops being an identity. `rhat` itself stays RAW for the E3 reporting below. | |
| rc = rhat if r_max is None else np.minimum(rhat, float(r_max)) | |
| J_wplan = (rc * wplan[:, None, None]).sum(0) | |
| J_cond = J - J_wplan # exact: weights are [w_cond]*fs + gamma^j + 0*pad | |
| J_plansum = rc.sum(0) | |
| J_final = rc[H - 1] | |
| r_ref = 1.0 if r_max is None else float(r_max) | |
| res["reward_range"] = dict( | |
| r_max=(None if r_max is None else float(r_max)), clamped=bool(r_max is not None), | |
| label_max=1.0, | |
| units="RAW label units -- plan_bundles returns model.unnorm(...), so 0.0 IS raw r=0 and " | |
| "1.0 IS raw r=1; the provenance label is binary so 1.0 is its maximum", | |
| rhat_plan_mean=float(rhat.mean()), rhat_plan_max=float(rhat.max()), | |
| rhat_plan_min=float(rhat.min()), | |
| rhat_plan_p99=float(np.quantile(rhat, 0.99)), | |
| frac_plan_frames_above_label_max=float((rhat > r_ref).mean()), | |
| frac_plan_frames_above_1=float((rhat > 1.0).mean())) | |
| res["J_decomposition"] = dict( | |
| J_mean=float(J.mean()), J_cond_mean=float(J_cond.mean()), J_wplan_mean=float(J_wplan.mean()), | |
| J_cond_share_of_mean=float(J_cond.mean() / J.mean()) if abs(J.mean()) > 1e-9 else float("nan"), | |
| J_std_within_state=float(J.std(-1).mean()), | |
| J_cond_std_within_state=float(J_cond.std(-1).mean()), | |
| J_wplan_std_within_state=float(J_wplan.std(-1).mean()), | |
| # which part of J does the WITHIN-STATE ranking actually come from? | |
| spearman_J_vs_Jcond=spearman_rows(J, J_cond)[0], | |
| spearman_J_vs_Jwplan=spearman_rows(J, J_wplan)[0], | |
| ) | |
| # ---- E3: what does J reward? (prediction-side only; no mask needed) | |
| def arm_travel(v): | |
| amax = np.take_along_axis(v, J.argmax(-1)[:, None], -1).squeeze(-1) | |
| amin = np.take_along_axis(v, J.argmin(-1)[:, None], -1).squeeze(-1) | |
| rnd = v.mean(-1) # random-of-K in expectation | |
| return dict(argmaxJ=float(amax.mean()), argminJ=float(amin.mean()), random=float(rnd.mean()), | |
| ratio_argmaxJ_over_random=float(amax.mean() / max(rnd.mean(), 1e-12)), | |
| ratio_argminJ_over_random=float(amin.mean() / max(rnd.mean(), 1e-12))) | |
| sp_trav = spearman_rows(J, trav) | |
| e3 = dict(latent_travel=arm_travel(trav), latent_step_delta=arm_travel(step_d), | |
| latent_dist_from_cond=arm_travel(from_cond), act_norm=arm_travel(actnorm), | |
| spearman_J_vs_latent_travel_mean=sp_trav[0], | |
| spearman_J_vs_latent_travel_frac_positive=sp_trav[2], | |
| data_latent_travel=data_travel, data_latent_step_delta=data_step, | |
| data_act_norm=data_actnorm) | |
| e3["latent_travel_ratio_argmaxJ_over_random"] = e3["latent_travel"]["ratio_argmaxJ_over_random"] | |
| e3["latent_travel_ratio_argmaxJ_over_data"] = float( | |
| e3["latent_travel"]["argmaxJ"] / max(data_travel, 1e-12)) | |
| # predicted provenance trajectory of the executed candidate vs a random one | |
| iamax = J.argmax(-1) | |
| rh_amax = np.take_along_axis(rhat, iamax[None, :, None], -1)[:, :, 0] # [H, B] | |
| e3["rhat_traj_argmaxJ"] = [float(v) for v in rh_amax.mean(-1)] | |
| e3["rhat_traj_random"] = [float(v) for v in rhat.mean((1, 2))] | |
| e3["rhat_final_argmaxJ"] = float(rh_amax[H - 1].mean()) | |
| e3["rhat_final_random"] = float(rhat[H - 1].mean()) | |
| e3["rhat_first_argmaxJ"] = float(rh_amax[0].mean()) | |
| e3["rhat_first_random"] = float(rhat[0].mean()) | |
| e3["rhat_pool_std_within_state"] = float(rhat.std(-1).mean()) | |
| res["what_J_rewards"] = e3 | |
| # ---- E1/E2: rank panel per execute window (EXPERT ACTION ENTERS ONLY BELOW) | |
| res["execute"] = {} | |
| for E in execute_list: | |
| hs = [h for h in range(min(E, H)) if h + 1 < bundle.shape[0]] | |
| if not hs: | |
| continue | |
| w = mask[[h + 1 for h in hs]].astype(bool).all(0) # [B] | |
| nB = int(w.sum()) | |
| if nB < 8: | |
| res["execute"][str(E)] = dict(n_states_used=nB, note="too few valid states, skipped") | |
| continue | |
| pred = acts[hs][:, w] # [e, B', K, A] | |
| tgt = bundle[[h + 1 for h in hs]][:, w, A0:A1] # [e, B', A] | |
| den = ((den_act[None, None, :] - tgt) ** 2).mean((0, 2)) # [B'] | |
| err_k = ((pred - tgt[:, :, None, :]) ** 2).mean((0, 3)) # [B', K] | |
| Jw = J[w] | |
| def r2_from(e): | |
| return float(1.0 - e.sum() / max(den.sum(), 1e-12)) | |
| r2_random = r2_from(err_k.mean(-1)) | |
| cell = dict(n_states_used=nB, execute_frames=len(hs), | |
| r2_random=r2_random, | |
| r2_Kmean=r2_from(((pred.mean(2) - tgt) ** 2).mean((0, 2))), | |
| r2_oracle=r2_from(err_k.min(-1)), | |
| r2_antioracle=r2_from(err_k.max(-1))) | |
| cell["oracle_gain"] = cell["r2_oracle"] - r2_random | |
| rules = dict(J=Jw, J_neg=-Jw, absJ=np.abs(Jw), J_final=J_final[w], | |
| J_plansum=J_plansum[w], J_wplan=J_wplan[w], J_cond=J_cond[w]) | |
| cell["rules"] = {k: panel(v, err_k, den, r2_random) for k, v in rules.items()} | |
| cell["captured_by_J"] = (cell["rules"]["J"]["gain_over_random"] / cell["oracle_gain"] | |
| if abs(cell["oracle_gain"]) > 1e-9 else float("nan")) | |
| cell["act_pool_std"] = float(pred.std(2).mean()) | |
| cell["act_tgt_std"] = float(tgt.std(1).mean()) | |
| cell["act_pool_std_over_tgt"] = cell["act_pool_std"] / max(cell["act_tgt_std"], 1e-9) | |
| res["execute"][str(E)] = cell | |
| return res | |
| # ---------------------------------------------------------------- self test | |
| def selftest(): | |
| """Metric math on synthetic pools, no model and no GPU. Two planted cases: | |
| a score that IS the negative error must show gain > 0 and spearman ~ +1; its negation must show | |
| the mirror image. This is the guard that the panel's sign convention is right.""" | |
| rng = np.random.default_rng(0) | |
| B, K, H, W = 16, 32, 5, 12 | |
| bundle = rng.normal(size=(W, B, A1 + 1)).astype(np.float32) | |
| mask = np.ones((W, B), np.float32) | |
| acts = rng.normal(size=(H, B, K, ACT_DIM)).astype(np.float32) | |
| tgt = bundle[1:H + 1, :, A0:A1] | |
| err = ((acts - tgt[:, :, None, :]) ** 2).mean((0, 3)) | |
| J = (-err + 0.01 * rng.normal(size=(B, K))).astype(np.float32) # a PERFECT-ish objective | |
| rhat = rng.normal(size=(H, B, K)).astype(np.float32) | |
| trav = rng.random((B, K)).astype(np.float32) + 0.5 | |
| out = score_arm(acts, rhat, trav, trav, trav, trav, J, bundle, mask, | |
| np.zeros(ACT_DIM, np.float32), H, 0.95, [H], 1.0, 1.0, 1.0) | |
| c = out["execute"][str(H)] | |
| gJ, gN = c["rules"]["J"]["gain_over_random"], c["rules"]["J_neg"]["gain_over_random"] | |
| sJ = c["rules"]["J"]["spearman_vs_negerr_mean"] | |
| sN = c["rules"]["J_neg"]["spearman_vs_negerr_mean"] | |
| ok = (gJ > 0 > gN) and (sJ > 0.9) and (sN < -0.9) and (c["oracle_gain"] > 0) | |
| assert abs(sJ + sN) < 1e-9, (sJ, sN) | |
| assert c["r2_oracle"] >= c["rules"]["J"]["r2"] >= c["r2_antioracle"] | |
| print(f"[selftest] gain(J) {gJ:+.4f} gain(J_neg) {gN:+.4f} spearman(J) {sJ:+.4f} " | |
| f"spearman(J_neg) {sN:+.4f} oracle_gain {c['oracle_gain']:+.4f} -> {'PASS' if ok else 'FAIL'}") | |
| # E4 guard: a clamp far above the data must be an EXACT no-op, so any difference a real clamped | |
| # arm shows is the clamp biting and not a code path change. | |
| big = score_arm(acts, rhat, trav, trav, trav, trav, J, bundle, mask, | |
| np.zeros(ACT_DIM, np.float32), H, 0.95, [H], 1.0, 1.0, 1.0, r_max=1e9) | |
| assert json.dumps(big["execute"]) == json.dumps(out["execute"]), "r_max=1e9 changed the panel" | |
| assert big["reward_range"]["clamped"] and not out["reward_range"]["clamped"] | |
| low = score_arm(acts, rhat, trav, trav, trav, trav, J, bundle, mask, | |
| np.zeros(ACT_DIM, np.float32), H, 0.95, [H], 1.0, 1.0, 1.0, r_max=0.0) | |
| lo = low["execute"][str(H)]["rules"] | |
| un = out["execute"][str(H)]["rules"] | |
| assert lo["J_final"]["score_std_within_state"] < un["J_final"]["score_std_within_state"], \ | |
| "clamping at 0.0 must flatten J_final on a standard-normal r_hat" | |
| # J itself is an INPUT to score_arm, so argmax-J rules must be untouched by the clamp; only the | |
| # r_hat-derived rules move. This is the contract the clamped arm relies on. | |
| assert json.dumps(lo["J"]) == json.dumps(un["J"]) | |
| print(f"[selftest] clamp: r_max=1e9 no-op OK; r_max=0.0 flattens J_final " | |
| f"{un['J_final']['score_std_within_state']:.4f} -> {lo['J_final']['score_std_within_state']:.4f}; " | |
| f"rule J untouched -> PASS") | |
| # the anti-objective must be exactly the mirror of the objective on a symmetric pool | |
| assert ok | |
| return 0 | |
| # ---------------------------------------------------------------- main | |
| def main(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--selftest", action="store_true") | |
| p.add_argument("--ckpt") | |
| p.add_argument("--cache") | |
| p.add_argument("--out") | |
| p.add_argument("--n-states", type=int, default=128) | |
| p.add_argument("--n-plans", type=int, default=128) | |
| p.add_argument("--horizons", default="8,20,40,64,80", | |
| help="plan lengths in FRAMES; > train plan frames is flagged extrapolation") | |
| p.add_argument("--execute-base", type=int, default=8, | |
| help="the fixed execute window scored on every arm, so arms are comparable") | |
| p.add_argument("--guidance-scale", type=float, default=0.0) | |
| p.add_argument("--r-max", type=float, default=None, | |
| help="E4 REWARD CLAMP (opt-in). Saturate the predicted provenance reward at this " | |
| "value in J AND in the guidance gradient: r_hat -> min(r_hat, r_max). The " | |
| "units are RAW label units and the binary provenance label's maximum is 1.0, " | |
| "so --r-max 1.0 is the label's own range and nothing outside it. Unset = the " | |
| "original unbounded objective, bit-identical to every landed number.") | |
| p.add_argument("--gamma", type=float, default=0.95) | |
| p.add_argument("--seed", type=int, default=0) | |
| p.add_argument("--micro", type=int, default=8, help="states per diffusion chunk (memory knob)") | |
| a = p.parse_args() | |
| if a.selftest: | |
| return selftest() | |
| for r in ("ckpt", "cache", "out"): | |
| if getattr(a, r) is None: | |
| raise SystemExit(f"--{r} is required") | |
| from df_data import DFCacheData # noqa: E402 | |
| from df_probe import load_df # noqa: E402 | |
| from df_plan import plan_bundles # noqa: E402 | |
| dev = "cuda" if torch.cuda.is_available() else "cpu" | |
| torch.manual_seed(a.seed) | |
| model, meta, step = load_df(a.ckpt, dev) | |
| fs = int(meta["frame_stack"]) | |
| train_tokens = int(meta["n_tokens"]) | |
| horizons = [int(h) for h in a.horizons.split(",") if h.strip()] | |
| maxH = max(horizons) | |
| # widen the DATA window only, so a target frame exists for every plan frame | |
| data_tokens = max(train_tokens, int(math.ceil((maxH + 1) / fs))) | |
| data = DFCacheData(a.cache, frame_stack=fs, n_tokens=data_tokens, seed=int(meta.get("seed", 0))) | |
| rng = np.random.default_rng(a.seed) | |
| bundle_t, mask_t = data.sample(a.n_states, rng, split="val", device=dev) # [W,B,C], [W,B] | |
| init_obs = bundle_t[0, :, :OBS_DIM] | |
| bundle = bundle_t.cpu().numpy() | |
| mask = mask_t.cpu().numpy() | |
| B = bundle.shape[1] | |
| mean_act = np.asarray(data.act, np.float32).mean(0) | |
| data_actnorm = float(np.linalg.norm(np.asarray(data.act, np.float32), axis=-1).mean()) | |
| ceiling = dict( | |
| train_plan_tokens=train_tokens, train_plan_frames=fs * train_tokens, frame_stack=fs, | |
| data_window_frames=int(data.W), data_plan_frames=int(data.T), | |
| pos_emb="SinusoidalPosEmb computed on torch.arange(seq_len) at call time -- no learned table, " | |
| "so the backbone has NO hard context cap; the limit is training distribution, not shape", | |
| in_distribution_max_horizon_frames=fs * train_tokens, | |
| note=("H <= %d frames uses at most the 1+%d tokens the checkpoint was trained on; larger H is " | |
| "token-count EXTRAPOLATION and is flagged per arm. Ground truth needs H+1 frames of " | |
| "window, which is why the data window was widened to %d frames (model untouched)." | |
| % (fs * train_tokens, train_tokens, int(data.W)))) | |
| arms = [] | |
| for H in horizons: | |
| plan_tokens = int(math.ceil(H / fs)) | |
| acts = torch.zeros(H, B, a.n_plans, ACT_DIM) | |
| rhat = torch.zeros(H, B, a.n_plans) | |
| trav = torch.zeros(B, a.n_plans) | |
| stepd = torch.zeros(B, a.n_plans) | |
| fcond = torch.zeros(B, a.n_plans) | |
| anorm = torch.zeros(B, a.n_plans) | |
| Jall = torch.zeros(B, a.n_plans) | |
| diags = [] | |
| for s in range(0, B, a.micro): | |
| e = min(B, s + a.micro) | |
| out = plan_bundles(model, init_obs[s:e], horizon_frames=H, guidance_scale=a.guidance_scale, | |
| gamma=a.gamma, n_plans=a.n_plans, device=dev, r_max=a.r_max) | |
| body = out["plan"] # [H, b, K, C] | |
| obs = body[..., :OBS_DIM] | |
| acts[:, s:e] = body[..., A0:A1].cpu() | |
| rhat[:, s:e] = body[..., -1].cpu() | |
| trav[s:e] = (obs[-1] - obs[0]).norm(dim=-1).cpu() | |
| stepd[s:e] = ((obs[1:] - obs[:-1]).norm(dim=-1).mean(0).cpu() if H > 1 | |
| else torch.zeros(e - s, a.n_plans)) | |
| fcond[s:e] = (obs[-1] - init_obs[s:e][:, None, :]).norm(dim=-1).cpu() | |
| anorm[s:e] = body[..., A0:A1].norm(dim=-1).mean(0).cpu() | |
| Jall[s:e] = out["J"].cpu() | |
| diags.append(out["diag"]) | |
| del out, body, obs | |
| if dev == "cuda": | |
| torch.cuda.empty_cache() | |
| # the data's own motion over the same H at the same states, as the scale for E3 | |
| okH = mask[min(H, mask.shape[0] - 1)].astype(bool) | |
| if okH.sum() >= 4: | |
| o = bundle[:, okH, :OBS_DIM] | |
| data_travel = float(np.linalg.norm(o[H] - o[1], axis=-1).mean()) | |
| data_step = float(np.linalg.norm(o[2:H + 1] - o[1:H], axis=-1).mean()) | |
| else: | |
| data_travel = data_step = float("nan") | |
| execute_list = sorted({min(a.execute_base, H), H}) | |
| arm = dict(horizon_frames=H, plan_tokens=plan_tokens, total_tokens=plan_tokens + 1, | |
| extrapolation=bool(plan_tokens > train_tokens), | |
| n_states=B, n_plans=a.n_plans, | |
| planner_diag={k: float(np.mean([d[k] for d in diags])) for k in | |
| ("J_mean", "J_std", "J_spread", "J_gain", "W_cond_total", | |
| "W_plan_total", "sched_rows", | |
| "rhat_raw_mean", "rhat_raw_max", "rhat_raw_min", "rhat_raw_p99", | |
| "frac_frames_above_rmax", "frac_cond_frames_above_rmax", | |
| "frac_plan_frames_above_rmax", "J_excess_above_rmax")}, | |
| r_max=(None if a.r_max is None else float(a.r_max)), | |
| clamped=bool(a.r_max is not None), | |
| data_latent_travel=data_travel, data_latent_step_delta=data_step) | |
| arm.update(score_arm(acts.numpy(), rhat.numpy(), trav.numpy(), stepd.numpy(), fcond.numpy(), | |
| anorm.numpy(), Jall.numpy(), bundle, mask, mean_act, H, a.gamma, | |
| execute_list, data_travel, data_step, data_actnorm, r_max=a.r_max)) | |
| arms.append(arm) | |
| c8 = arm["execute"].get(str(min(a.execute_base, H)), {}) | |
| rj = c8.get("rules", {}).get("J", {}) | |
| rn = c8.get("rules", {}).get("J_neg", {}) | |
| print(f"[df_poolcmp2] H={H:3d} ({plan_tokens} tok{' EXTRAP' if arm['extrapolation'] else ''}) " | |
| f"E={min(a.execute_base, H)} n={c8.get('n_states_used')} " | |
| f"oracle_gain {c8.get('oracle_gain', float('nan')):+.4f} " | |
| f"argmaxJ_gain {rj.get('gain_over_random', float('nan')):+.4f} " | |
| f"argminJ_gain {rn.get('gain_over_random', float('nan')):+.4f} " | |
| f"spearman(J,-err) {rj.get('spearman_vs_negerr_mean', float('nan')):+.4f} " | |
| f"travel argmaxJ/rand " | |
| f"{arm['what_J_rewards']['latent_travel_ratio_argmaxJ_over_random']:.3f} " | |
| f"rmax {'off' if a.r_max is None else f'{a.r_max:g}'} " | |
| f"fr_above {arm['planner_diag']['frac_frames_above_rmax']:.3f} " | |
| f"rhat_max {arm['planner_diag']['rhat_raw_max']:.3f}", flush=True) | |
| res = dict(ckpt=a.ckpt, cache=a.cache, step=step, n_states=B, n_plans=a.n_plans, | |
| guidance_scale=a.guidance_scale, gamma=a.gamma, seed=a.seed, | |
| r_max=(None if a.r_max is None else float(a.r_max)), | |
| clamped=bool(a.r_max is not None), | |
| clamp_note=("E4: r_hat -> min(r_hat, r_max) in the planner's objective AND in the " | |
| "guidance gradient (zero gradient above r_max). r_hat is in RAW label " | |
| "units (plan_bundles unnorms), and the binary data-provenance label's " | |
| "maximum is 1.0, so r_max=1.0 uses only the shared reward's own " | |
| "definition -- no privileged state, no outcome reward, no success bit, " | |
| "no RSM/IQL contact. Nothing retrained; the vendored checkout untouched."), | |
| act_align=str(meta.get("act_align", "ours")), ceiling=ceiling, | |
| execute_base=a.execute_base, horizons=horizons, arms=arms, | |
| kind="DIAGNOSTIC -- held-out states, no environment, no rollout, NO SUCCESS NUMBER. " | |
| "The expert action enters ONLY as the error the rank rules are scored against and " | |
| "the r2_oracle upper bound; it is never given to the planner or the scorer. " | |
| "r2_oracle and the J_neg (argmin-J) rule are DIAGNOSTICS, never DF columns.") | |
| 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_poolcmp2] wrote", a.out, flush=True) | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |