Download code_src/df_rise/df_policy.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 27.6 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_policy.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_policy.py
-
curl -L -o df_policy.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_policy.py
27.6 kB
| """Diffusion Forcing driving the REAL eval harness, as a planner (gen_q#274, order-of-work item 1). | |
| WHY A WRAPPER AND NOT A SCORER BACKEND. Every other column in tab:flagship is a *value function*: | |
| RISE's diffusion policy proposes 128 action chunks and the column ranks them (rsm_planner.py:377, | |
| `plan_get_action`). Diffusion Forcing is not a value function -- #274 asks for it "as a planner", and | |
| a planner proposes its OWN actions. So DF cannot enter through `rsm_backend`; it replaces the action | |
| instead of ranking someone else's. That is also why its candidate count is reported separately and | |
| never silently compared against a 128-candidate value column. | |
| WHAT IS HELD FIXED, so the DF row is comparable with the RSM / DINO-WM / IDQL / IFQL rows: | |
| * the env, the initial-state distribution, the rollout loop, the horizon and the success test -- | |
| untouched, because we install ourselves by replacing `policy.policy.get_action` on the ALREADY | |
| CONSTRUCTED robomimic policy object (`install(policy, ...)` below). No harness file is edited, | |
| which also keeps this stream out of gen_q#273's way in rsm_planner.py / rsm_scorer.py. | |
| * the observation encoder -- `rsm_scorer.PooledDinoState`, the project's own frozen DINOv2 ViT-S/14 | |
| cls+GeM pooling with the task cache's feat_stats. DF sees exactly the state the RSM scorer sees. | |
| * the control rate -- DF executes `execute_frames` (default 8 = the project's hop/chunk) actions per | |
| plan and then replans, which is the same cadence at which the value columns commit a chunk. | |
| * the reward -- DF's own predicted reward channel, trained on the binary provenance label. Nothing | |
| outside the shared reward enters the guidance (df_plan.py's module docstring). | |
| WHAT IS NOT UPSTREAM'S. The guidance is our implementation of the configuration upstream leaves as | |
| `raise NotImplementedError` (df_planning.py:180-182). Finding F1 in status/NEW_BASELINES_DONE; it | |
| must be printed beside every DF number. | |
| HEALTH, published beside every score (#274 item 3): | |
| * rollout fidelity vs the true future -- written by the TRAINER into health.jsonl | |
| (`fid/obs_rmse_h<H>` against `fid/obs_rmse_h<H>_naive`, the stay-put predictor). A ratio >= 1 | |
| means the model predicts nothing and the score is flagged, not published bare. | |
| * planner diagnostics -- accumulated here over every control step of every episode and written to | |
| the cell JSON: J_mean / J_std / J_spread (sample spread) and J_gain (per-iteration improvement). | |
| A cell with J_spread ~ 0 is not discriminating among its own samples; a cell with J_gain <= 0 has | |
| guidance that is not doing anything. Both are failure modes that would otherwise hide inside a | |
| plausible-looking success rate. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from df_core import DFRise # noqa: E402 | |
| from df_data import OBS_DIM, ACT_DIM # noqa: E402 | |
| from df_plan import plan_bundles, best_actions # noqa: E402 | |
| def load_df(ckpt, device="cuda"): | |
| """ckpt_s*.pt / ckpt_last.pt are self-describing: model, cfg, meta, mean, std, step.""" | |
| 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"]) | |
| m.load_state_dict(ck["model"]) # the EMA weights | |
| return m.to(device).eval(), meta, int(ck.get("step", -1)) | |
| class DFPlannerPolicy: | |
| """Replaces `get_action` on a robomimic policy. Same signature, same units, same cadence.""" | |
| def __init__(self, ckpt, feat_stats, *, horizon_frames, guidance_scale, gamma, | |
| n_plans=128, execute_frames=8, device="cuda", seed=0, | |
| img_layout="chw", diag_path="", act_limit=1.0, select="argmax"): | |
| from robomimic.algo.rsm_scorer import PooledDinoState | |
| self.model, self.meta, self.step = load_df(ckpt, device) | |
| self.enc = PooledDinoState(feat_stats, img_layout=img_layout).to(device).eval() \ | |
| if _accepts_layout() else PooledDinoState(feat_stats).to(device).eval() | |
| self.device = device | |
| self.H = int(horizon_frames) | |
| self.guidance_scale = float(guidance_scale) | |
| self.gamma = float(gamma) | |
| self.n_plans = int(n_plans) | |
| # select="random" -- the RANDOM-OF-N CONTROL the owner requires beside every guidance arm | |
| # (blocker, 2026-09-23 19:45Z). IDENTICAL candidates: same model, same guidance scale, same | |
| # generator and the same n_plans bundle; only the pick among them changes from argmax_J to a | |
| # uniform draw. Without it, a guided arm that lands on the BC floor cannot be told apart | |
| # from a planner whose J does not order its own samples. | |
| self.select = str(select) | |
| # select="mean" -- run 32 (gen_q#274). NOT a selection rule: it is a DECODING rule, and it | |
| # is published as such. `df_actprobe` measured, on held-out episodes with no environment, | |
| # that DF's action head IS informative but that a SINGLE diffusion sample is a much worse | |
| # estimate of the expert action than the mean of several samples: | |
| # threading df_A s20000 R2 vs mean-action baseline single 0.569 -> K=32 mean 0.711 | |
| # mug df_A s20000 single 0.283 -> K=32 mean 0.474 | |
| # (status/nb/df_actprobe/*.json, `per_h["0"]`). The planner executes ONE sampled candidate | |
| # -- argmax_J or, in the control, a uniform draw -- so every landed DF cell has been acting | |
| # on the 0.569 estimator while the 0.711 one costs nothing extra: the n_plans candidates are | |
| # already drawn. Averaging them is the model's own posterior mean over its own samples. | |
| # NO NEW INFORMATION ENTERS: same checkpoint, same state, same reward, same candidates. | |
| # Its control is the single-sample arm, which is already measured (select=random, 0.000). | |
| # Because it does not rank, `J_rank_executed` is undefined and reported as -1. | |
| if self.select not in ("argmax", "random", "mean"): | |
| raise ValueError(f"select must be argmax|random|mean, got {select!r}") | |
| # w_cond -- the weight df_plan.py's guidance puts on EACH of the frame_stack conditioning | |
| # frames' reward channel. 10.0 is upstream's number, but upstream's reward-guidance block is | |
| # dead code that cannot execute (undefined `h`; `episode_return` never reduced to a scalar -- | |
| # df_planning.py:180-186), so the 10.0 has never been run by anyone and is a free | |
| # hyper-parameter here, not a published setting. It matters because its TOTAL weight is | |
| # w_cond*frame_stack = 80.0 against W_plan = 31.8 at H = 50, i.e. most of the guidance | |
| # gradient asks the denoiser to re-explain the CURRENT observation as expert-provenance | |
| # rather than to plan a better future (status/nb/df_jrange.txt). Default unchanged, so every | |
| # already-measured cell is reproduced byte-for-byte; RR_DF_WCOND=0 is the arm that tests it. | |
| self.w_cond = float(os.environ.get("RR_DF_WCOND", "10.0")) | |
| # ---- RR_DF_DECODE (run 36, stream DF_MAKEITWORK) -- ADDITIVE, default unchanged -------- | |
| # "diffused" (default) executes DF's OWN diffused action channel -- byte-identical to every | |
| # cell measured so far. "idm" executes a LEARNED INVERSE DYNAMICS DECODER applied to DF's | |
| # planned OBSERVATION latents. | |
| # | |
| # DECLARE IT LOUDLY, every time: with RR_DF_DECODE=idm this column is no longer "DF emits | |
| # actions", it is "DF plans states, a learned decoder emits actions". That is what | |
| # upstream's own headline maze2d numbers do -- df_planning.py:272-320 executes a HAND-WRITTEN | |
| # PD controller (gains 12.5 / 1.2) on diffused POSITIONS whenever action_dim != 2, which is | |
| # upstream's own recommended recipe (README 71/126, `dataset.action_mean=[]`), and our | |
| # main-branch gate measured 46.3 +- 1.5 for that arm against 15.1 +- 1.1 for the diffused- | |
| # action arm (LSF 1895313). There is no analytic PD law from a 1545-d DINOv2 latent to a | |
| # 7-DoF OSC action, so the general form of that controller is a learned IDM. Both arms are | |
| # published side by side and the swap is never silent: it is in the CELL NAME, in the diag | |
| # JSON below, and it must be in the table caption. | |
| # | |
| # NO NEW INFORMATION ENTERS. The IDM is trained on cache/<task>'s own (obs_t, obs_{t+k}) -> | |
| # act_t pairs -- the same corpus, the same frozen encoder, the same held-out split, and | |
| # actions as supervision, which is exactly what every BC column is trained on. It sees no | |
| # reward, no goal, no success bit and no simulator state (code/df_rise/df_idm.py's header | |
| # enumerates its inputs). At run time its anchor frame is the TRUE current observation from | |
| # the same PooledDinoState encoder every other column uses; every other frame it reads is | |
| # DF's own prediction. | |
| self.decode = str(os.environ.get("RR_DF_DECODE", "diffused")) | |
| if self.decode not in ("diffused", "idm"): | |
| raise ValueError(f"RR_DF_DECODE must be diffused|idm, got {self.decode!r}") | |
| self.idm = self.idm_ck = None | |
| self.idm_dir = "" | |
| if self.decode == "idm": | |
| from df_idm import load_idm | |
| self.idm_dir = os.environ.get("RR_DF_IDM", "") | |
| if not self.idm_dir: | |
| raise RuntimeError("RR_DF_DECODE=idm needs RR_DF_IDM=<idm run dir>") | |
| self.idm, self.idm_ck = load_idm(self.idm_dir, device) | |
| print(f"[gen_q#274 run36] DF -> IDM decoder: {self.idm_dir} mode={self.idm_ck['mode']} " | |
| f"offsets={self.idm_ck['offsets']} n_act={self.idm_ck['n_act']} " | |
| f"noise_rel={self.idm_ck['noise_rel']} idm_step={self.idm_ck['step']} -- " | |
| f"THIS COLUMN IS 'DF PLANS STATES, A LEARNED DECODER EMITS ACTIONS'") | |
| self.execute_frames = int(execute_frames) | |
| self.gen = torch.Generator(device=device); self.gen.manual_seed(int(seed)) | |
| self.diag_path = diag_path | |
| self.act_limit = float(act_limit) | |
| self.reset() | |
| # ---- state ------------------------------------------------------------ | |
| def reset(self): | |
| # NOTE: no action queue is kept here on purpose -- `get_action` returns the whole chunk and | |
| # `rollout.py` executes it before calling again (see get_action's docstring). | |
| self._diag = [] # one record per PLAN (not per env step) | |
| # action-range health (gen_q#274 run 5). DF's action channel is a DIFFUSED CONTINUOUS | |
| # VARIABLE with nothing constraining it to the env's box: `best_actions` slices the raw | |
| # unnormalised bundle (df_plan.py:best_actions). The CPU smoke measured |a|_max = 2.48 on an | |
| # untrained model (status/nb/df_plan_smoke.txt, T6). robosuite clips to the action spec | |
| # anyway, so an unclipped DF is not unfair -- but it means the trajectory the planner scored | |
| # is NOT the trajectory the env executed, which silently breaks the guidance's own premise. | |
| # So we clamp to the same box the env enforces and PUBLISH how often it bit: a cell with a | |
| # high clip fraction is a cell whose planner is planning outside the action space. | |
| self._n_act = 0 # scalar action components emitted | |
| self._n_clip = 0 # how many of them were outside the box | |
| self._a_absmax = 0.0 | |
| # ---- resume: carry THIS planner's state across a preemption ------------ | |
| # FINDING AJ (stream DF_MAKEITWORK, 2026-09-24). The plan sampler's whole stochasticity is one | |
| # draw per plan from `self.gen` (df_plan.py:111), and `self.gen` is seeded ONCE in __init__ | |
| # (:148). eval.py's episode-level resume restores the env's numpy MT19937 state exactly | |
| # (eval.py:_rng_state_dump / _rng_state_load), so a resumed cell ran the RIGHT initial states | |
| # with the WRONG noise: episode k drew from the generator's INITIAL state instead of its | |
| # post-k-episodes state. Measured on | |
| # runs/threading_expert_play/eval_onactor/df274idm/ | |
| # E1-DFG0s40000-R0.95-20-plan-Ndf128-g0.0-idmk8_n10-DF274IDM-es1-sS0As0-s0.json | |
| # (resumed_from_episode=44): episodes 0..43 identical to the two fresh cells of that column, | |
| # episodes 44..49 0/6 successes against 3/6 fresh. | |
| # The health accumulators have the same shape of bug for REPORTING: nothing clears or carries | |
| # them either (this harness never calls robomimic's `start_episode`, so install()'s reset() | |
| # chain below never fires), so a resumed cell published TAIL-ONLY health as if it were the whole | |
| # cell -- `plans` read 300 against 2500 on the cell above. | |
| # So the resume carries both, through the same per-episode snapshot the numpy state uses. A | |
| # FRESH run never calls state_load(), which is why this leaves every landed cell reproducible | |
| # bit for bit. The generator's STATE is written in exactly two places -- manual_seed() in | |
| # __init__ (:148) and set_state() in state_load() below -- and is otherwise only CONSUMED, by | |
| # the plan draw (df_plan.py:112) and by the random-of-N pick (_random_actions / the IDM branch's | |
| # torch.randint). get_state() does not advance the stream, so snapshotting it every episode | |
| # costs a fresh run nothing and changes nothing. | |
| def _json_safe(rec): | |
| """A diag record with every value a JSON scalar. | |
| plan_bundles already wraps every value in float()/int()/bool()/None (df_plan.py's `diag`), | |
| so this is a no-op today. It exists because this dict is now written into the .partial on | |
| EVERY episode: if a future diagnostic ever added a numpy scalar or a tensor, an unguarded | |
| json.dump would raise inside the per-episode snapshot and kill a RUNNING cell. Resume | |
| scaffolding must never be able to do that. | |
| """ | |
| out = {} | |
| for k, v in rec.items(): | |
| if v is None or isinstance(v, (bool, int, float, str)): | |
| out[str(k)] = v | |
| else: | |
| try: | |
| out[str(k)] = float(v) | |
| except Exception: | |
| out[str(k)] = repr(v) | |
| return out | |
| def state_dump(self): | |
| """Everything of this planner that a resumed process must not restart from scratch.""" | |
| return { | |
| 'gen_device': str(self.device), | |
| # get_state() is a uint8 ByteTensor (CUDA: seed+offset, 16 B; CPU MT19937: 5056 B). | |
| 'gen_state_hex': bytes(self.gen.get_state().cpu().numpy().tobytes()).hex(), | |
| 'n_act': int(self._n_act), | |
| 'n_clip': int(self._n_clip), | |
| 'a_absmax': float(self._a_absmax), | |
| # The per-PLAN records verbatim, so the restored aggregate is computed by | |
| # diagnostics() over the same records in the same order a fresh run would have had -- | |
| # i.e. the resumed cell's health is identical, not merely close. ~30 JSON-safe scalars | |
| # per plan, 50 plans per episode; only ever written into "<cell>.json.partial". | |
| 'diag': [self._json_safe(d) for d in self._diag], | |
| } | |
| def state_load(self, d): | |
| """Restore a state_dump(). True on success; False leaves the planner untouched.""" | |
| if not isinstance(d, dict) or not d.get('gen_state_hex'): | |
| return False | |
| # Parse EVERYTHING before mutating anything, so a malformed snapshot leaves this planner in | |
| # its fresh-from-__init__ state (the old behaviour, which the caller then warns about) | |
| # rather than half-restored. | |
| try: | |
| raw = bytes.fromhex(str(d['gen_state_hex'])) | |
| st = torch.frombuffer(bytearray(raw), dtype=torch.uint8).clone() | |
| n_act, n_clip = int(d.get('n_act', 0)), int(d.get('n_clip', 0)) | |
| a_absmax, diag = float(d.get('a_absmax', 0.0)), list(d.get('diag') or []) | |
| if not all(isinstance(r, dict) for r in diag): | |
| raise ValueError('diag is not a list of records') | |
| self.gen.set_state(st) | |
| except Exception as ex: | |
| print(f"[gen_q#274] DF resume: cannot restore the plan sampler's state ({ex!r}) -- " | |
| f"NOT restored") | |
| return False | |
| self._n_act, self._n_clip, self._a_absmax, self._diag = n_act, n_clip, a_absmax, diag | |
| return True | |
| def diagnostics(self): | |
| """Aggregate over every plan of the cell -- what gets published beside the score.""" | |
| if not self._diag: | |
| return dict(n_plans=self.n_plans, plans=0) | |
| k = ["J_mean", "J_std", "J_spread", "J_gain"] | |
| out = {f"{x}": float(np.mean([d[x] for d in self._diag])) for x in k} | |
| out.update(bypassed_planner=getattr(self, "bypassed_planner", None), | |
| plans=len(self._diag), n_plans=self.n_plans, select=self.select, | |
| # run 36: which map from the chosen plan to the executed action was used. | |
| # "idm" means THIS CELL IS "DF plans states, a learned decoder emits actions". | |
| decode=self.decode, idm_dir=self.idm_dir, | |
| idm_mode=(self.idm_ck["mode"] if self.idm_ck else None), | |
| idm_offsets=(list(self.idm_ck["offsets"]) if self.idm_ck else None), | |
| idm_noise_rel=(float(self.idm_ck["noise_rel"]) if self.idm_ck else None), | |
| idm_step=(int(self.idm_ck["step"]) if self.idm_ck else None), | |
| guidance_scale=self.guidance_scale, gamma=self.gamma, | |
| horizon_frames=self.H, execute_frames=self.execute_frames, | |
| df_train_step=self.step, | |
| J_rank_executed=float(np.mean([d.get("J_rank_executed", 0.0) for d in self._diag])), | |
| J_spread_frac_zero=float(np.mean([d["J_spread"] <= 1e-8 for d in self._diag])), | |
| J_gain_frac_nonpositive=float(np.mean([d["J_gain"] <= 0 for d in self._diag])), | |
| act_limit=self.act_limit, act_absmax=self._a_absmax, | |
| act_clip_frac=(self._n_clip / self._n_act) if self._n_act else 0.0, | |
| act_components=self._n_act) | |
| if self.diag_path: | |
| Path(self.diag_path).write_text(json.dumps(out, indent=2)) | |
| return out | |
| # ---- the harness entry point ----------------------------------------- | |
| def get_action(self, obs_dict, goal_dict=None): | |
| """obs_dict [B, To, ...] exactly as robomimic hands it to the released get_action. | |
| RETURNS AN ACTION CHUNK [B, execute_frames, ACT_DIM], which is the contract every IDQL cell | |
| in this project already runs under and NOT what an earlier revision of this file returned. | |
| Measured 2026-09-23 13:35Z (LSF 1881480): returning a single [B, ACT_DIM] action killed the | |
| cell at | |
| rollout_policies/robomimic_sampling_rollout_policy.py:94 actions = actions[:, 0, :] | |
| IndexError: too many indices for tensor of dimension 2 | |
| `get_policy_info` sets `action_chunking = True` for ROBOMIMIC+IDQL (eval.py:549-551) and | |
| `rollout.py:174-179` then queues `actions[:, i]` for i over the chunk axis -- i.e. the HARNESS | |
| owns the execute-k-then-replan cadence. Keeping a second queue in here would have made DF | |
| replan on a schedule no other column uses; the chunk is returned instead, so DF's cadence and | |
| the value columns' cadence are the same object. | |
| """ | |
| obs_t = {k: (v[:, -1] if v.dim() > 3 or (v.dim() == 3 and v.shape[1] > 1) else v[:, -1]) | |
| for k, v in obs_dict.items()} | |
| x = self.enc(obs_t) # [B, 1545] project state | |
| out = plan_bundles(self.model, x, self.H, self.guidance_scale, self.gamma, | |
| n_plans=self.n_plans, device=self.device, generator=self.gen, | |
| w_cond=self.w_cond) | |
| self._diag.append(dict(out["diag"])) | |
| if self.diag_path: # flush every plan: an eval that dies still has its health | |
| self.diagnostics() | |
| if self.decode == "idm": | |
| acts, rank = self._idm_actions(out, x) | |
| self._diag[-1]["J_rank_executed"] = float(rank) | |
| L = self.act_limit | |
| self._a_absmax = max(self._a_absmax, float(acts.abs().max())) | |
| self._n_act += int(acts.numel()) | |
| self._n_clip += int((acts.abs() > L).sum()) | |
| return acts.clamp(-L, L).permute(1, 0, 2).contiguous() | |
| if self.select == "argmax": | |
| acts, _ = best_actions(out, self.execute_frames) # [k, B, ACT_DIM] | |
| rank = 0.0 # argmax is rank 0 by construction | |
| elif self.select == "mean": | |
| plan = out["plan"] # [H, B, N, C] | |
| acts = plan[:self.execute_frames, :, :, | |
| OBS_DIM:OBS_DIM + ACT_DIM].mean(2) # [k, B, ACT_DIM] | |
| rank = -1.0 # no ranking happened | |
| else: | |
| # same bundle, uniform pick. Drawn from this policy's OWN generator so the control is | |
| # reproducible from (seed, cell) exactly like the argmax arm is. | |
| acts, rank = _random_actions(out, self.execute_frames, self.gen) | |
| # J_rank_executed: where the EXECUTED plan sat in the J ordering (0 = best). 0 on every | |
| # argmax plan by construction; ~ (N-1)/2 on the control. Published so the two arms cannot be | |
| # confused after the fact by reading the diag alone. | |
| self._diag[-1]["J_rank_executed"] = float(rank) | |
| L = self.act_limit | |
| self._a_absmax = max(self._a_absmax, float(acts.abs().max())) | |
| self._n_act += int(acts.numel()) | |
| self._n_clip += int((acts.abs() > L).sum()) | |
| return acts.clamp(-L, L).permute(1, 0, 2).contiguous() # [B, k, ACT_DIM] | |
| def _idm_actions_impl(self, out, cur_obs): | |
| """DF plans observation latents -> the learned IDM decodes the executed chunk (run 36). | |
| THE SELECTION RULE IS UNCHANGED AND THE CANDIDATE POOL IS IDENTICAL to the diffused-action arm: | |
| the same model, the same guidance scale, the same generator, the same `n_plans` bundle and the | |
| same J. Only the map from the CHOSEN plan to the executed action changes -- which is exactly | |
| the substitution upstream makes on maze2d (a PD controller instead of the diffused action), and | |
| it is measured beside the arm it replaces, never instead of it. | |
| `select="random"` remains the random-of-N control over that identical pool; `select="mean"` | |
| decodes EVERY candidate and averages the decoded actions (the model's own posterior mean over | |
| its own samples, the same decoding rule the diffused arm's "mean" uses), so the controls the | |
| fairness rules require exist for this arm too. | |
| """ | |
| from df_idm import decode_plan | |
| plan, J = out["plan"], out["J"] # [H, B, N, C], [B, N] | |
| B, N = J.shape | |
| ar = torch.arange(B, device=plan.device) | |
| P = plan[..., :OBS_DIM] # planned observations, P[h] = o_{t+h+1} | |
| if self.select == "mean": | |
| sel = P # [H, B, N, OBS] | |
| idx, rank = None, -1.0 | |
| else: | |
| if self.select == "argmax": | |
| idx, rank = J.argmax(-1), 0.0 | |
| else: | |
| idx = torch.randint(N, (B,), device=plan.device, generator=self.gen) | |
| rank = (J > J.gather(1, idx[:, None])).sum(-1).float().mean().item() | |
| sel = P[:, ar, idx][:, :, None, :] # [H, B, 1, OBS] | |
| K = sel.shape[2] | |
| # O[0] is the TRUE current observation from the live encoder; O[j>=1] is DF's prediction. | |
| O = torch.cat([cur_obs[None, :, None, :].expand(1, B, K, OBS_DIM), sel], 0) | |
| acts = decode_plan(self.idm, self.idm_ck, O, self.execute_frames) # [k, B, K, ACT] | |
| return acts.mean(2), rank | |
| DFPlannerPolicy._idm_actions = _idm_actions_impl | |
| def _random_actions(out, execute_frames, gen): | |
| """best_actions() with a UNIFORM pick instead of argmax_J -- the random-of-N control. | |
| Deliberately a sibling of df_plan.best_actions rather than a flag inside it: df_plan.py is | |
| vendored DF-adjacent code and the control is ours, so the diff stays on our side of the line.""" | |
| from df_plan import OBS_DIM, ACT_DIM | |
| plan, J = out["plan"], out["J"] # [H, B, N, C], [B, N] | |
| B, N = J.shape | |
| idx = torch.randint(N, (B,), device=plan.device, generator=gen) | |
| sel = plan[:, torch.arange(B, device=plan.device), idx] | |
| rank = (J > J.gather(1, idx[:, None])).sum(-1).float().mean().item() # 0 = the argmax was drawn | |
| return sel[:execute_frames, :, OBS_DIM:OBS_DIM + ACT_DIM], rank | |
| def _accepts_layout(): | |
| import inspect | |
| from robomimic.algo.rsm_scorer import PooledDinoState | |
| return "img_layout" in inspect.signature(PooledDinoState.__init__).parameters | |
| def install(policy, **kw): | |
| """Monkey-patch an already-built robomimic RolloutPolicy so the harness runs DF instead. | |
| Returns the DFPlannerPolicy so the caller can read `diagnostics()` after the rollouts. The | |
| harness's own `start_episode` is chained to DF's `reset`, so each episode replans from scratch. | |
| """ | |
| df = DFPlannerPolicy(**kw) | |
| inner = getattr(policy, "policy", policy) | |
| # gen_q#274 run 5, disclosure guard. Replacing `get_action` SHADOWS the RISE planner entirely: | |
| # if the cell's config also has plan_n > 1, `plan_get_action` is never reached, yet | |
| # `planner_describe()` would still write that scorer's describe() into the cell JSON and the row | |
| # would read as if the RSM/IQL scorer had contributed to a DF number. Record the bypass so the | |
| # JSON says so, and say it on stdout where the slot log keeps it. | |
| try: | |
| _pn = inner.planner_cfg().get("plan_n") if hasattr(inner, "planner_cfg") else None | |
| _on = bool(getattr(inner, "planning_enabled", False)) | |
| except Exception: | |
| _pn, _on = None, False | |
| df.bypassed_planner = dict(plan_n=_pn, planning_was_enabled=_on) | |
| if _on: | |
| print(f"[gen_q#274] DF planner BYPASSES the cell's own ranked planner (plan_n={_pn}); " | |
| f"no RSM/IQL scorer contributes to this row -- DF proposes and selects its own " | |
| f"{df.n_plans} candidates.") | |
| inner.get_action = df.get_action | |
| # FINDING AJ: the handle eval.py's episode-level resume reaches this planner through, to carry | |
| # `self.gen` and the health accumulators across a preemption (see state_dump/state_load). It is | |
| # set on `inner` -- the algo -- so the harness finds it at policy.policy.policy, which is the | |
| # same handle eval.py already uses for `planner_describe` / `pop_plan_log`. | |
| # NOT a substitute for the start_episode chain below, and vice versa: THIS harness never calls | |
| # start_episode at all (no call site in sim_pipeline), which is why the chain never fires. | |
| inner._rr_df_planner = df | |
| if hasattr(policy, "start_episode"): | |
| _orig = policy.start_episode | |
| def start_episode(*a, **k): | |
| df.reset() | |
| return _orig(*a, **k) | |
| policy.start_episode = start_episode | |
| return df | |