Download code_src/df_rise/df_idm.py from rli14/rsm_rise_code: direct link, hf CLI and curl.
- Browser
- Download file 25.2 kB
-
https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_idm.py
- Command line
-
hf download hf://rli14/rsm_rise_code/code_src/df_rise/df_idm.py
-
curl -L -o df_idm.py https://huggingface.co/rli14/rsm_rise_code/resolve/main/code_src/df_rise/df_idm.py
25.2 kB
| #!/usr/bin/env python | |
| """INVERSE DYNAMICS MODEL -- the honest, learned analogue of upstream DF's hand-written maze2d | |
| controller (gen_q#274, stream DF_MAKEITWORK, run 36). | |
| ===================================================================================== | |
| DECLARE THE DESIGN CHOICE LOUDLY. This file changes the DF column from | |
| "DF emits actions" (the diffused-action channel of its own bundle) | |
| to | |
| "DF plans OBSERVATION LATENTS, a learned decoder emits actions". | |
| Every number produced with it must carry that sentence, in the report AND in the table caption, | |
| and BOTH arms must be published side by side. | |
| ===================================================================================== | |
| WHY THIS IS FAITHFUL TO HOW THE METHOD IS ACTUALLY RUN, NOT A DODGE. | |
| `code/diffusion_forcing/algorithms/diffusion_forcing/df_planning.py:272-320` (main branch, the | |
| commit our RISE column imports) branches on `action_dim = len(cfg.action_mean)`: | |
| use_diffused_action = False | |
| if self.action_dim != 2: | |
| print("Detected reduced observation/action space, using Diffuser like controller.") | |
| else: | |
| use_diffused_action = True | |
| ... | |
| for t in range(self.open_loop_horizon): | |
| if use_diffused_action: | |
| _, action, _ = self.split_bundle(plan[t]) | |
| else: | |
| plan_vel = plan[t,:,:2] - plan[t-1,:,:2] if t > 0 else plan[t,:,:2] - obs[:,:2] | |
| action = 12.5 * (plan[t,:,:2] - obs[:,:2]) + 1.2 * (plan_vel - obs[:,2:]) | |
| Upstream's RECOMMENDED maze2d recipe (README lines 71/126) passes | |
| `dataset.action_mean=[] dataset.action_std=[]`, so `action_dim = 0`, the model diffuses POSITIONS | |
| ONLY, and the executed action comes from that **hand-written PD controller with gains 12.5 and 1.2** | |
| -- not from the model. Our own main-branch gate (LSF 1895313, 1024 episodes/cell, maze2d-medium) | |
| measured exactly this split: | |
| med_x PD controller on diffused positions 46.3 +- 1.5 normalised | |
| med_xva the model's own diffused actions 15.1 +- 1.1 normalised | |
| and the paper's own "Diffuser w/ diffused action" floor is 13.5 +- 2.3. Upstream says it in their | |
| own words in a COMMENTED-OUT README block (line 86): *"Here is also ckpt where we take diffused | |
| actions ... We haven't got it working as well as original RNN version of diffusion forcing"*. | |
| There is no analytic PD law from a planned 1545-d DINOv2 latent to a 7-DoF robomimic OSC action, so | |
| the general form of upstream's controller is a LEARNED inverse dynamics model: a network that maps | |
| (observation_t, observation_{t+k}) -> the action(s) that get you from one to the other. DF then | |
| plans in the channel our health numbers say is HEALTHY (observations) and the IDM decodes it. That | |
| is how Diffuser / UniPi-style systems execute plans. | |
| ===================================================================================== | |
| FAIRNESS -- exactly the same information every BC column gets, and nothing else. | |
| ===================================================================================== | |
| INPUTS TO THE IDM, exhaustively: the project's normalised 1545-d state | |
| x = clip((concat(DINOv2 z, proprio) - mu) / max(sd, sd_floor), -z_clip, z_clip) | |
| read through `df_data.DFCacheData.obs_rows` from `cache/<task>` -- the SAME cache, the SAME frozen | |
| DINOv2 ViT-S/14 cls+GeM features, the SAME feat_stats, the SAME 9-d proprio (eef pos / quat / | |
| gripper qpos) every other column in tab:flagship reads. No pixels, no object poses, no simulator | |
| state, no goal, no success bit, no reward of any kind, no privileged anything. | |
| SUPERVISION: `cache/<task>/act.f32.npy`, the OSC action the dataset actually executed -- which is | |
| the identical supervision every BC column is trained on. | |
| SPLIT: `DFCacheData(seed=<the DF arm's own seed>)`, i.e. the SAME held-out episodes every other DF | |
| diagnostic (df_actprobe, df_poolcmp, fid/obs_*) validates on. The IDM never sees a val episode. | |
| The reward channel is NOT an input and NOT a target: an IDM has no use for it. | |
| ===================================================================================== | |
| THE THREE DECODER SHAPES, and why the stride matters more than the architecture. | |
| ===================================================================================== | |
| `runs/<task>/wm/df_G0/health.jsonl` at step 40000 -- DF's observation-rollout RMSE as a RATIO to the | |
| "the state never changes" predictor (>= 1 means the roll-out carries no information): | |
| task h=1 h=2 h=4 h=8 h=10 h=20 h=50 | |
| threading 1.485 1.358 1.167 0.981 1.012 1.006 0.910 | |
| mug 1.606 1.482 1.268 1.071 1.094 0.957 0.918 | |
| READ THAT BEFORE READING ANY R2 BELOW. The ONE-STEP planned latent delta is 1.5-1.6x WORSE than | |
| stay-put. A `k1` IDM consumes exactly that delta, so it is being fed the noisiest thing DF | |
| produces. The horizons where DF's observation channel is at or below 1.0 are h>=8. So the shape | |
| that matches where the world model is actually healthy is a CHUNKED IDM that reads a planned | |
| WAYPOINT and emits the whole 8-action chunk -- which is also precisely the cadence the harness | |
| executes (`RR_DF_EXECUTE=8`, and upstream's own controller reads a planned waypoint per step.) | |
| mode "k1" g(o_t, o_{t+1}) -> a_t applied autoregressively, 8x | |
| mode "k8" g(o_t, o_{t+8}) -> a_t .. a_{t+7} one planned waypoint, one chunk | |
| mode "kfull" g(o_t, o_{t+1}, ..., o_{t+8}) -> a_t .. a_{t+7} the whole planned subsequence | |
| `kfull` is strictly the most informed of the three and `k1` the least; all three see ONLY planned | |
| observations. Which one is used in the env is chosen by a HELD-OUT, ENVIRONMENT-FREE metric | |
| (`df_idm_probe.py`'s R2 of decoded actions against the held-out expert action), never by a success | |
| rate, so no eval seed is ever consulted to pick a decoder. | |
| NOISE AUGMENTATION (`--noise-rel`). At plan time the anchor o_t is the TRUE current observation | |
| (the encoder's output on the live frame) but o_{t+1..} are DF's PREDICTIONS, whose error is ~1.0x | |
| the size of the true delta at h=8 (table above). Training on clean pairs alone builds a decoder | |
| that has never seen an input as bad as the one it will get. So the non-anchor frames are corrupted | |
| with per-dimension Gaussian noise of std `noise_rel * std(o_{t+k} - o_t)`; `noise_rel=1.0` matches | |
| the measured ratio. This is standard input augmentation on the model's OWN inputs -- it adds no | |
| information and touches no held-out data. `noise_rel=0.0` is the clean control. | |
| FEATURISATION. Input is [anchor, delta_1, delta_2, ...] -- the anchor observation plus successive | |
| first differences -- because the action is a function of the MOTION and the deltas are ~100x smaller | |
| than the state. Targets are standardised by the dataset's own per-channel action std so the 7 OSC | |
| channels (6 continuous + 1 near-binary gripper) contribute comparably to the loss; predictions are | |
| un-standardised before they leave the model. | |
| ===================================================================================== | |
| REGISTERED READ-OUT -- written here BEFORE any number exists (run 36, 2026-09-24). | |
| ===================================================================================== | |
| BAR 1, DECODER CAPACITY. `r2_oracle_val` = R2 of the IDM on TRUE held-out observation pairs, | |
| against the constant "dataset mean action" predictor (`df_actprobe`'s definition, verbatim). | |
| * >= 0.71 the decoder has real capacity (0.71 is the BEST number DF's own action head reaches, | |
| FINDING H: threading single 0.569 / K=32-mean 0.711; mug 0.283 / 0.474). | |
| * < 0.71 inverse dynamics is NOT learnable from this state at this stride, and the decoder | |
| cannot be the fix. SAY SO PLAINLY AND STOP. | |
| BAR 2, THE DECISIVE ONE (measured in `df_idm_probe.py`, not here). `r2_plan_Kmean` = R2 of the | |
| IDM's actions decoded from DF's OWN PLANNED latents, on the same held-out states, at the same plan | |
| indices, K-sample mean -- against DF's own action head measured on those identical states in the | |
| same script. | |
| * IDM-on-plan > DF-head on both tasks => the decoder swap is a real improvement and the eval is | |
| worth its GPU-hours. | |
| * IDM-on-plan <= DF-head on either task => the decoder is NOT the fix on that task. Report it, | |
| publish the eval anyway (it is already queued and resumable), and do not dress it up. | |
| * Expected in advance, and I am registering the pessimistic prior: because `fid/obs_ratio_h1` is | |
| 1.485 / 1.606, I expect `k1` to be the WORST of the three shapes and possibly at or below | |
| DF's own head; `k8`/`kfull` are the arms with a mechanism behind them. | |
| BAR 3, SUCCESS (the stream's mandate). Mean success over the two flagship tasks, canonical region, | |
| horizon 400, 50 episodes/cell, 3 policy x 3 eval seeds. A number is REPORTABLE only beside | |
| (a) random-of-N over the identical candidate pool, (b) the no-selection floor (n_plans=1), | |
| (c) per-cell score spread / ties-at-max / selection gap, (d) the BC-actor no-selection baseline | |
| already on record (status/nb/df_table.txt:9,90 -- threading 0.000, mug 0.027). A scorer that ties | |
| across most candidates IS random-of-N however good its headline. | |
| usage: | |
| python df_idm.py --cache cache/<task> --out runs/<task>/idm/<tag> --mode k8 --noise-rel 1.0 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import sys | |
| import time | |
| from pathlib import Path | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from df_data import DFCacheData, OBS_DIM, ACT_DIM # noqa: E402 | |
| MODES = { | |
| # mode -> (frame offsets fed to the net, number of actions predicted) | |
| "k1": ((0, 1), 1), | |
| "k8": ((0, 8), 8), | |
| "kfull": (tuple(range(0, 9)), 8), | |
| } | |
| class IDM(nn.Module): | |
| """MLP inverse dynamics: [anchor obs, successive obs deltas] -> k standardised actions.""" | |
| def __init__(self, offsets, n_act, obs_dim=OBS_DIM, act_dim=ACT_DIM, | |
| hidden=1024, layers=3): | |
| super().__init__() | |
| self.offsets = tuple(int(o) for o in offsets) | |
| self.n_act = int(n_act) | |
| self.act_dim = int(act_dim) | |
| self.obs_dim = int(obs_dim) | |
| d_in = obs_dim * len(self.offsets) | |
| blocks, d = [], d_in | |
| for _ in range(int(layers)): | |
| blocks += [nn.Linear(d, hidden), nn.LayerNorm(hidden), nn.GELU()] | |
| d = hidden | |
| blocks += [nn.Linear(d, self.n_act * act_dim)] | |
| self.net = nn.Sequential(*blocks) | |
| # target standardisation, filled by fit_act_stats (buffers so they ride in the ckpt) | |
| self.register_buffer("act_mean", torch.zeros(act_dim)) | |
| self.register_buffer("act_std", torch.ones(act_dim)) | |
| # ---- featurisation ----------------------------------------------------- | |
| def featurise(obs_seq): | |
| """obs_seq [..., L, OBS_DIM] -> [..., L*OBS_DIM] = anchor followed by first differences.""" | |
| anchor = obs_seq[..., :1, :] | |
| deltas = obs_seq[..., 1:, :] - obs_seq[..., :-1, :] | |
| f = torch.cat([anchor, deltas], dim=-2) | |
| return f.reshape(*f.shape[:-2], f.shape[-2] * f.shape[-1]) | |
| def forward(self, obs_seq): | |
| """obs_seq [B, L, OBS_DIM] (L == len(self.offsets)) -> actions [B, n_act, ACT_DIM], | |
| in RAW dataset action units.""" | |
| y = self.net(self.featurise(obs_seq)) | |
| y = y.view(-1, self.n_act, self.act_dim) | |
| return y * self.act_std + self.act_mean | |
| # --------------------------------------------------------------------------- data | |
| class IDMData: | |
| """Frame-level sampler over DFCacheData's OWN train/val episode split. | |
| Holds the normalised state matrix in RAM as f16 (115k x 1545 -> 355 MB on threading) because | |
| every sample needs random rows of it; the f32 cast happens per batch. | |
| """ | |
| def __init__(self, cache, offsets, n_act, seed=0, val_frac=0.1, frame_stack=8, n_tokens=8): | |
| self.d = DFCacheData(cache, frame_stack=frame_stack, n_tokens=n_tokens, | |
| val_frac=val_frac, seed=seed, in_ram=True) | |
| self.offsets = tuple(int(o) for o in offsets) | |
| self.n_act = int(n_act) | |
| self.span = max(self.offsets) # frames of future the sample needs | |
| N = self.d.z.shape[0] | |
| print(f"[df_idm] materialising {N} x {OBS_DIM} normalised states as f16", flush=True) | |
| self.X = np.empty((N, OBS_DIM), np.float16) | |
| for s in range(0, N, 8192): | |
| e = min(N, s + 8192) | |
| self.X[s:e] = self.d.obs_rows(np.arange(s, e)).astype(np.float16) | |
| self.A = np.asarray(self.d.act, np.float32) | |
| # anchors: frame index t such that t+span and t+n_act-1 are inside the SAME episode | |
| need = max(self.span, self.n_act) | |
| self.anchors = {} | |
| for name, eps in (("train", self.d.train_eps), ("val", self.d.val_eps)): | |
| a = [] | |
| for e in eps: | |
| lo, hi = int(self.d.ep_from[e]), int(self.d.ep_to[e]) | |
| if hi - lo > need: | |
| a.append(np.arange(lo, hi - need)) | |
| self.anchors[name] = np.concatenate(a) if a else np.zeros(0, np.int64) | |
| print(f"[df_idm] {name}: {len(eps)} eps, {len(self.anchors[name])} anchors", flush=True) | |
| # per-dim std of the largest delta the net is fed -- the unit the noise augmentation uses | |
| rng = np.random.default_rng(0) | |
| t = self.anchors["train"] | |
| take = t if len(t) <= 20000 else t[rng.choice(len(t), 20000, replace=False)] | |
| self.delta_std = (self.X[take + self.span].astype(np.float32) | |
| - self.X[take].astype(np.float32)).std(0) | |
| self.act_mean = self.A[np.concatenate([np.arange(self.d.ep_from[e], self.d.ep_to[e]) | |
| for e in self.d.train_eps])].mean(0) | |
| self.act_std = np.maximum( | |
| self.A[np.concatenate([np.arange(self.d.ep_from[e], self.d.ep_to[e]) | |
| for e in self.d.train_eps])].std(0), 1e-3) | |
| print(f"[df_idm] delta_std mean {self.delta_std.mean():.4f} " | |
| f"act_std {np.round(self.act_std, 3).tolist()}", flush=True) | |
| def batch(self, n, rng, split="train", device="cpu"): | |
| a = self.anchors[split] | |
| idx = a[rng.integers(0, len(a), size=n)] | |
| obs = np.stack([self.X[idx + o].astype(np.float32) for o in self.offsets], 1) # [n,L,D] | |
| act = np.stack([self.A[idx + j] for j in range(self.n_act)], 1) # [n,k,7] | |
| return (torch.from_numpy(obs).to(device), torch.from_numpy(act).to(device)) | |
| def all_val(self, device="cpu", cap=20000): | |
| a = self.anchors["val"] | |
| if len(a) > cap: | |
| a = a[np.linspace(0, len(a) - 1, cap).astype(np.int64)] | |
| obs = np.stack([self.X[a + o].astype(np.float32) for o in self.offsets], 1) | |
| act = np.stack([self.A[a + j] for j in range(self.n_act)], 1) | |
| return (torch.from_numpy(obs).to(device), torch.from_numpy(act).to(device)) | |
| # --------------------------------------------------------------------------- load / decode | |
| def load_idm(d, device="cuda"): | |
| """<dir>/idm_last.pt -> (module in eval mode, its checkpoint dict). Self-describing.""" | |
| ck = torch.load(Path(d) / "idm_last.pt", map_location="cpu", weights_only=False) | |
| m = IDM(ck["offsets"], ck["n_act"], hidden=ck["hidden"], layers=ck["layers"]) | |
| m.load_state_dict(ck["model"]) | |
| return m.to(device).eval(), ck | |
| def decode_plan(idm, ck, O, n_exec): | |
| """THE DF -> IDM BRIDGE, shared by the offline probe and the live policy so they cannot drift. | |
| O [1+H, B, K, OBS_DIM] is the observation sequence of K candidate plans: | |
| O[0] is the TRUE current observation (what the encoder gives the policy right now), | |
| O[j] (j >= 1) is DF's PREDICTED observation at t+j. | |
| Returns the decoded actions a_t .. a_{t+n_exec-1} as [n_exec, B, K, ACT_DIM]. | |
| """ | |
| offs, n_act = tuple(ck["offsets"]), int(ck["n_act"]) | |
| Hp1, B, K, D = O.shape | |
| if max(offs) + (n_exec - 1 if n_act == 1 else 0) > Hp1 - 1: | |
| raise ValueError(f"IDM needs planned frames up to index " | |
| f"{max(offs) + (n_exec - 1 if n_act == 1 else 0)} but the plan has " | |
| f"{Hp1 - 1} -- raise the planning horizon") | |
| if n_act == 1: # autoregressive single-step decoder, stride = offs[1] | |
| st = offs[1] | |
| outs = [idm(torch.stack([O[h], O[h + st]], dim=2).reshape(B * K, 2, D) | |
| ).view(B, K, 1, ACT_DIM)[:, :, 0] for h in range(n_exec)] | |
| return torch.stack(outs, 0) | |
| seq = torch.stack([O[o] for o in offs], dim=2) # [B,K,L,D] | |
| a = idm(seq.reshape(B * K, seq.shape[2], D)).view(B, K, n_act, ACT_DIM) | |
| return a.permute(2, 0, 1, 3)[:n_exec].contiguous() | |
| # --------------------------------------------------------------------------- metric | |
| def r2_vs_mean_action(pred, tgt, mean_act): | |
| """df_actprobe.py's definition, verbatim: 1 - MSE(pred)/MSE(constant mean-action predictor). | |
| pred/tgt [..., ACT_DIM]; pooled over channels by summing the numerators and denominators, so a | |
| channel with a big natural variance is not double-counted. Also returned per channel. | |
| """ | |
| p = pred.reshape(-1, pred.shape[-1]) | |
| t = tgt.reshape(-1, tgt.shape[-1]) | |
| num = ((p - t) ** 2).mean(0) | |
| den = ((mean_act[None, :] - t) ** 2).mean(0) | |
| pooled = (1.0 - num.sum() / den.sum().clamp_min(1e-12)).item() | |
| per_ch = [(1.0 - n / d).item() for n, d in zip(num, den.clamp_min(1e-12))] | |
| return pooled, per_ch | |
| # --------------------------------------------------------------------------- train | |
| def parse(): | |
| p = argparse.ArgumentParser() | |
| p.add_argument("--cache", required=True) | |
| p.add_argument("--out", required=True) | |
| p.add_argument("--mode", default="k8", choices=sorted(MODES)) | |
| p.add_argument("--noise-rel", type=float, default=1.0) | |
| p.add_argument("--hidden", type=int, default=1024) | |
| p.add_argument("--layers", type=int, default=3) | |
| p.add_argument("--steps", type=int, default=30000) | |
| p.add_argument("--batch", type=int, default=256) | |
| p.add_argument("--lr", type=float, default=3e-4) | |
| p.add_argument("--weight-decay", type=float, default=1e-4) | |
| p.add_argument("--warmup", type=int, default=1000) | |
| p.add_argument("--seed", type=int, default=0) | |
| # the DF arm whose split this must match; df_G0 was trained with --seed 0 | |
| p.add_argument("--split-seed", type=int, default=0) | |
| p.add_argument("--frame-stack", type=int, default=8) | |
| p.add_argument("--n-tokens", type=int, default=8) | |
| p.add_argument("--eval-every", type=int, default=2500) | |
| p.add_argument("--resume", type=int, default=1) | |
| return p.parse_args() | |
| def main(): | |
| a = parse() | |
| offsets, n_act = MODES[a.mode] | |
| dev = "cuda" if torch.cuda.is_available() else "cpu" | |
| out = Path(a.out); out.mkdir(parents=True, exist_ok=True) | |
| ck_path = out / "idm_last.pt" | |
| js_path = out / "idm.json" | |
| data = IDMData(a.cache, offsets, n_act, seed=a.split_seed, | |
| frame_stack=a.frame_stack, n_tokens=a.n_tokens) | |
| model = IDM(offsets, n_act, hidden=a.hidden, layers=a.layers).to(dev) | |
| model.act_mean.copy_(torch.as_tensor(data.act_mean, device=dev)) | |
| model.act_std.copy_(torch.as_tensor(data.act_std, device=dev)) | |
| mean_act = torch.as_tensor(data.act_mean, device=dev) | |
| noise_sd = torch.as_tensor(a.noise_rel * data.delta_std, device=dev) | |
| opt = torch.optim.AdamW(model.parameters(), lr=a.lr, weight_decay=a.weight_decay) | |
| step0 = 0 | |
| if a.resume and ck_path.exists(): | |
| ck = torch.load(ck_path, map_location=dev, weights_only=False) | |
| model.load_state_dict(ck["model"]); opt.load_state_dict(ck["opt"]) | |
| step0 = int(ck["step"]) | |
| print(f"[df_idm] resumed {ck_path} at step {step0}", flush=True) | |
| if step0 >= a.steps: | |
| print(f"[df_idm] already at {step0} >= {a.steps} steps -- nothing to do", flush=True) | |
| if js_path.exists(): | |
| return | |
| rng = np.random.default_rng(a.seed + 1) | |
| torch.manual_seed(a.seed) | |
| astd = torch.as_tensor(data.act_std, device=dev) | |
| amean = torch.as_tensor(data.act_mean, device=dev) | |
| val_obs, val_act = data.all_val(dev) | |
| print(f"[df_idm] mode={a.mode} offsets={offsets} n_act={n_act} noise_rel={a.noise_rel} " | |
| f"params={sum(p.numel() for p in model.parameters())} val_n={val_obs.shape[0]}", flush=True) | |
| def evaluate(): | |
| model.eval() | |
| with torch.no_grad(): | |
| preds = [] | |
| for s in range(0, val_obs.shape[0], 4096): | |
| preds.append(model(val_obs[s:s + 4096])) | |
| pred = torch.cat(preds) | |
| pooled, per_ch = r2_vs_mean_action(pred, val_act, mean_act) | |
| per_j = [] | |
| for j in range(n_act): | |
| pj, _ = r2_vs_mean_action(pred[:, j], val_act[:, j], mean_act) | |
| per_j.append(pj) | |
| # the same thing with the noise the plan will actually carry, so the clean number is | |
| # never the only one on record | |
| no = val_obs.clone() | |
| no[:, 1:] = no[:, 1:] + torch.randn_like(no[:, 1:]) * noise_sd | |
| npreds = [] | |
| for s in range(0, no.shape[0], 4096): | |
| npreds.append(model(no[s:s + 4096])) | |
| npooled, _ = r2_vs_mean_action(torch.cat(npreds), val_act, mean_act) | |
| model.train() | |
| return pooled, per_ch, per_j, npooled | |
| hist = [] | |
| t0 = time.time() | |
| model.train() | |
| for step in range(step0 + 1, a.steps + 1): | |
| lr = a.lr * min(1.0, step / max(1, a.warmup)) | |
| for g in opt.param_groups: | |
| g["lr"] = lr | |
| obs, act = data.batch(a.batch, rng, "train", dev) | |
| if a.noise_rel > 0: | |
| obs = obs.clone() | |
| obs[:, 1:] = obs[:, 1:] + torch.randn_like(obs[:, 1:]) * noise_sd | |
| pred = model(obs) | |
| loss = (((pred - act) / astd) ** 2).mean() | |
| opt.zero_grad(set_to_none=True) | |
| loss.backward() | |
| torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) | |
| opt.step() | |
| if step % a.eval_every == 0 or step == a.steps: | |
| pooled, per_ch, per_j, npooled = evaluate() | |
| rec = dict(step=step, train_loss=float(loss.item()), r2_oracle_val=pooled, | |
| r2_oracle_val_noised=npooled, r2_per_action_index=per_j, | |
| r2_per_channel=per_ch, wall_s=time.time() - t0) | |
| hist.append(rec) | |
| print(f"[df_idm] step {step:>6d} loss {loss.item():.4f} " | |
| f"R2(val, true obs) {pooled:+.4f} R2(val, +plan-scale noise) {npooled:+.4f}", | |
| flush=True) | |
| torch.save(dict(model=model.state_dict(), opt=opt.state_dict(), step=step, | |
| mode=a.mode, offsets=list(offsets), n_act=n_act, | |
| hidden=a.hidden, layers=a.layers, | |
| noise_rel=a.noise_rel, delta_std=data.delta_std, | |
| act_mean=data.act_mean, act_std=data.act_std, | |
| args=vars(a)), ck_path) | |
| if not hist: | |
| # resumed at/after --steps with the JSON missing (e.g. preempted between save and write): | |
| # re-measure rather than crash, so the payload is genuinely resumable. | |
| pooled, per_ch, per_j, npooled = evaluate() | |
| hist.append(dict(step=step0, train_loss=float("nan"), r2_oracle_val=pooled, | |
| r2_oracle_val_noised=npooled, r2_per_action_index=per_j, | |
| r2_per_channel=per_ch, wall_s=0.0)) | |
| else: | |
| pooled, per_ch, per_j, npooled = hist[-1]["r2_oracle_val"], hist[-1]["r2_per_channel"], \ | |
| hist[-1]["r2_per_action_index"], hist[-1]["r2_oracle_val_noised"] | |
| res = dict( | |
| cache=a.cache, out=a.out, mode=a.mode, offsets=list(offsets), n_act=n_act, | |
| noise_rel=a.noise_rel, steps=a.steps, hidden=a.hidden, layers=a.layers, | |
| split_seed=a.split_seed, n_train_eps=len(data.d.train_eps), n_val_eps=len(data.d.val_eps), | |
| n_train_anchors=int(len(data.anchors["train"])), n_val_anchors=int(len(data.anchors["val"])), | |
| params=int(sum(p.numel() for p in model.parameters())), | |
| # BAR 1 of the registered read-out | |
| r2_oracle_val=pooled, r2_oracle_val_noised=npooled, | |
| r2_per_action_index=per_j, r2_per_channel=per_ch, | |
| df_action_head_bar=dict(threading_single=0.569, threading_Kmean=0.711, | |
| mug_single=0.283, mug_Kmean=0.474, | |
| source="status/nb/df_actprobe/*.json, FINDING H"), | |
| bar1_pass=bool(pooled >= 0.711), | |
| delta_std_mean=float(data.delta_std.mean()), | |
| act_mean=[float(v) for v in data.act_mean], act_std=[float(v) for v in data.act_std], | |
| inputs="normalised 1545-d state (DINOv2 z 1536 + proprio 9) from cache/<task> ONLY; " | |
| "supervision = cache/<task>/act.f32.npy; no reward, no goal, no sim state", | |
| history=hist, | |
| ) | |
| js_path.write_text(json.dumps(res, indent=1)) | |
| print(f"[df_idm] wrote {js_path} BAR1 r2_oracle_val={pooled:+.4f} " | |
| f"(bar 0.711) pass={res['bar1_pass']}", flush=True) | |
| if __name__ == "__main__": | |
| main() | |