BIue-Jay commited on
Commit
a47346f
·
verified ·
1 Parent(s): 3e1fabd

a10v3: add the FastWAM inference adapter (code/ad_fastwam.py and the modules it imports), refresh protocol.json

Browse files
a10-trolley-push-v3/b512/step-002000/code/ad_fastwam.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastWAM adapter (2026-11-16). Deployment path of FastWAM's own policy (experiments/robotwin/fastwam_policy/
2
+ deploy_policy.py, WorldActionRobotWinPolicy._infer_action_chunk: model.infer_action, the action-only path = first-frame
3
+ video KV cache + action-expert denoising, no future video) fed exactly like our training dataset (RobotVideoDataset +
4
+ FastWAMProcessor of the run's config.yaml, no HB augmentation):
5
+ * cameras in shape_meta order (g1 ego_view + chest, h2 head + chest): uint8 [1,C,H,W] -> processor val transforms
6
+ (ToTensor /255 + Resize 224x224), concatenated horizontally (224 x 448), dataset ResizeSmallestSide/CenterCrop
7
+ (no-op at 224 x 448), Normalize(0.5, 0.5) -> [-1, 1];
8
+ * state: processor.action_state_transform -> normalizer.forward (min/max of the run's
9
+ dataset_stats.json), the proprio of the first frame;
10
+ * text: the run's T5 cache for DEFAULT_PROMPT.format(task=instruction) with context[~mask] = 0 and mask = ones, as in
11
+ training (the text encoder is not loaded in training either; deploy_policy encodes the same prompt with T5 online);
12
+ * infer_action(action_horizon = num_frames - 1 = 16, num_inference_steps = config eval_num_inference_steps (10),
13
+ text_cfg_scale 1, seed 42 = native trainer eval), denormalised with normalizer.normalizers["action"][key].backward.
14
+ ckpt = .../fastwam/runs/<task>/out/checkpoints/weights/step_<N>.pt (config.yaml + dataset_stats.json in .../out).
15
+ Weights: model built from the config (Wan2.2 + ActionDiT init), then the checkpoint's mot + proprio_encoder are
16
+ loaded STRICTLY (FastWAM.load_checkpoint uses strict=False for mot; a missing key here is an error).
17
+ """
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+
24
+ import hb_eval_common as E
25
+
26
+ FW = E.G / "fastwam"
27
+
28
+
29
+ def setup_env():
30
+ os.environ.setdefault("FASTWAM_SRC", str(FW / "FastWAM"))
31
+ os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", str(FW / "models"))
32
+ os.environ.setdefault("DIFFSYNTH_SKIP_DOWNLOAD", "true")
33
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
34
+ src = str(Path(os.environ["FASTWAM_SRC"]) / "src")
35
+ if src not in sys.path:
36
+ sys.path.insert(0, src)
37
+
38
+
39
+ class Inputs:
40
+ """model-agnostic cache query -> FastWAM inputs (shared by the post-hoc adapter and the in-training eval)"""
41
+
42
+ def __init__(self, cfg, stats_path):
43
+ setup_env()
44
+ from hydra.utils import instantiate
45
+ from omegaconf import OmegaConf
46
+ from fastwam.datasets.dataset_utils import CenterCrop, Normalize, ResizeSmallestSideAspectPreserving
47
+ from fastwam.datasets.lerobot.robot_video_dataset import DEFAULT_PROMPT
48
+ from fastwam.datasets.lerobot.utils.normalizer import load_dataset_stats_from_json
49
+ d = cfg.data.train
50
+ self.DEFAULT_PROMPT = DEFAULT_PROMPT
51
+ self.proc = instantiate(d.processor).eval()
52
+ self.proc.set_normalizer_from_stats(load_dataset_stats_from_json(str(stats_path)))
53
+ self.cams = [m["key"] for m in self.proc.shape_meta["images"]]
54
+ if d.concat_multi_camera != "horizontal":
55
+ raise ValueError(f"concat_multi_camera {d.concat_multi_camera} not supported")
56
+ vs = list(d.video_size)
57
+ self.resize = ResizeSmallestSideAspectPreserving(args={"img_w": vs[1], "img_h": vs[0]})
58
+ self.crop = CenterCrop(args={"img_w": vs[1], "img_h": vs[0]})
59
+ self.norm = Normalize(args={"mean": 0.5, "std": 0.5})
60
+ self.cache_dir = d.text_embedding_cache_dir
61
+ self.context_len = int(d.context_len)
62
+ self.horizon = int(d.num_frames) - 1
63
+ self.skey = self.proc.shape_meta["state"][0]["key"]
64
+ self.akey = self.proc.shape_meta["action"][0]["key"]
65
+ if len(self.proc.shape_meta["state"]) != 1 or len(self.proc.shape_meta["action"]) != 1:
66
+ raise ValueError("expected one merged state key and one merged action key")
67
+ self._ctx = {}
68
+ self.OmegaConf = OmegaConf
69
+
70
+ def image(self, images):
71
+ import torch
72
+ per = []
73
+ for c in self.cams:
74
+ x = torch.from_numpy(np.ascontiguousarray(images[c])).permute(2, 0, 1).unsqueeze(0) # [1,C,H,W] uint8
75
+ for tr in self.proc.val_transforms:
76
+ x = tr(x)
77
+ per.append(x)
78
+ v = torch.cat(per, dim=-1) # [1, C, 224, 448]
79
+ v = self.norm(self.crop(self.resize(v)))
80
+ return v # [1, 3, H, W] in [-1, 1], float32
81
+
82
+ def proprio(self, state):
83
+ import torch
84
+ b = {"state": {self.skey: torch.as_tensor(np.asarray(state, dtype=np.float32)).unsqueeze(0)}}
85
+ b = self.proc.action_state_transform(b)
86
+ b = self.proc.normalizer.forward(b) # = deploy_policy._normalize_state (one merged key: merger is identity)
87
+ return b["state"][self.skey] # [1, D]
88
+
89
+ def context(self, instruction):
90
+ import hashlib
91
+ import torch
92
+ prompt = self.DEFAULT_PROMPT.format(task=instruction)
93
+ if prompt not in self._ctx:
94
+ h = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
95
+ p = os.path.join(self.cache_dir, f"{h}.t5_len{self.context_len}.wan22ti2v5b.pt")
96
+ if not os.path.exists(p):
97
+ raise FileNotFoundError(f"no T5 cache for the instruction ({p}): {instruction[:80]!r}")
98
+ obj = torch.load(p, map_location="cpu")
99
+ ctx, mask = obj["context"], obj["mask"]
100
+ ctx = ctx.clone()
101
+ ctx[~mask.bool()] = 0.0
102
+ self._ctx[prompt] = (ctx, torch.ones_like(mask.bool()))
103
+ return self._ctx[prompt]
104
+
105
+ def denorm(self, action):
106
+ import torch
107
+ a = action
108
+ if a.ndim == 2:
109
+ a = a.unsqueeze(0)
110
+ n = self.proc.normalizer.normalizers["action"][self.akey]
111
+ return n.backward(a.to(dtype=torch.float32, device="cpu")).numpy()[0]
112
+
113
+
114
+ def infer(model, inp, obs, steps, seed=42):
115
+ import torch
116
+ img = inp.image(obs["images"]).to(device=model.device, dtype=model.torch_dtype)
117
+ ctx, mask = inp.context(obs["prompt"])
118
+ with torch.no_grad():
119
+ out = model.infer_action(prompt=None, input_image=img, action_horizon=inp.horizon, proprio=inp.proprio(obs["state"]),
120
+ context=ctx, context_mask=mask, text_cfg_scale=1.0, num_inference_steps=steps, seed=seed,
121
+ rand_device="cpu", tiled=False)
122
+ return inp.denorm(out["action"])
123
+
124
+
125
+ class Adapter:
126
+ def __init__(self, ckpt, task, split, meta, device="cuda:0", steps=None, seed="42"):
127
+ setup_env()
128
+ import torch
129
+ from hydra.utils import instantiate
130
+ from omegaconf import OmegaConf
131
+ self.torch = torch
132
+ ckpt = Path(ckpt)
133
+ out = ckpt.parent.parent.parent
134
+ self.cfg = OmegaConf.load(out / "config.yaml")
135
+ self.inp = Inputs(self.cfg, out / "dataset_stats.json")
136
+ miss = [c for c in self.inp.cams if c not in meta["cams"]]
137
+ if miss:
138
+ raise KeyError(f"cameras {miss} not in the cache {meta['cams']}")
139
+ self.device = device if torch.cuda.is_available() else "cpu"
140
+ mp = str(self.cfg.get("mixed_precision", "bf16")).lower()
141
+ dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "no": torch.float32}[mp]
142
+ self.model = instantiate(self.cfg.model, model_dtype=dtype, device=self.device)
143
+ payload = torch.load(str(ckpt), map_location="cpu")
144
+ miss_k, unexp = self.model.mot.load_state_dict(payload["mot"], strict=False)
145
+ if miss_k or unexp:
146
+ raise RuntimeError(f"checkpoint mot keys: missing {list(miss_k)[:5]} unexpected {list(unexp)[:5]}")
147
+ if self.model.proprio_encoder is not None:
148
+ self.model.proprio_encoder.load_state_dict(payload["proprio_encoder"], strict=True)
149
+ self.ckpt_step = payload.get("step")
150
+ del payload
151
+ self.model = self.model.to(self.device).eval()
152
+ self.native_steps = int(self.cfg.eval_num_inference_steps)
153
+ self.steps = int(steps or self.native_steps)
154
+ self.seed = int(seed)
155
+ self.ckpt = str(ckpt)
156
+
157
+ def info(self):
158
+ return {"model": "fastwam", "ckpt": self.ckpt, "ckpt_step": self.ckpt_step, "denoising_steps": self.steps,
159
+ "native_steps_in_config": self.native_steps, "cams": self.inp.cams, "chunk": self.inp.horizon,
160
+ "seed": self.seed, "path": "FastWAM.infer_action (action-only, deploy_policy)"}
161
+
162
+ def predict(self, obs):
163
+ return infer(self.model, self.inp, obs, self.steps, self.seed)
a10-trolley-push-v3/b512/step-002000/code/hb_eval_common.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Humanoid Benchmark open-loop action-reconstruction evaluation: shared task table, cache layout and metrics.
2
+
3
+ Protocol (identical for every model; mirrors Isaac-GR00T gr00t/eval/open_loop_eval.py):
4
+ * query frames t = 0, 16, 32, ... over the whole episode (non-overlapping 16-step chunks);
5
+ * the model sees the observation at t exactly as at deployment (cameras, raw benchmark state 44/78, instruction;
6
+ Delta Flow also its native 16-step past-action history), all augmentation off;
7
+ * the predicted chunk (first 16 steps, raw action units) is compared with the recorded actions t..t+15;
8
+ rows beyond the episode end are excluded (no clamped / padded targets);
9
+ * metrics: raw MSE / MAE, and nMSE = MSE after dividing every action dim by its std over the task's TRAINING
10
+ frames (floored, see STD_FLOOR_FRAC), overall, per action group and per horizon step.
11
+ Splits: "heldout" = recorded episodes that were never trained on (B6 100-148, trolley 100-102, B7 100-106);
12
+ "train10" = 10 fixed, evenly spaced training episodes (fit on seen data, NOT generalisation).
13
+ Only numpy here: imported by every model environment.
14
+ """
15
+ import json
16
+ import os
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ G = Path(os.environ.get("G", "/mnt/nas/cross/Team/RobotAgent/Personal/baijiaqi/humanoid-benchmark-work/"
23
+ "preflight-20261104T1648Z/policies-20261109"))
24
+ P = G.parent
25
+ ROOT = G / "eval-action-mse"
26
+ CACHE = Path(os.environ.get("HB_EVAL_CACHE", ROOT / "cache"))
27
+ HORIZON = 16
28
+ STRIDE = 16
29
+ N_TRAIN_EVAL = 10
30
+ STD_FLOOR_FRAC = 0.05 # per-dim std floor = 5 % of the median std of the action vector
31
+
32
+ # task -> (source LeRobot v2.1 root, number of TRAINING episodes = fixed first N (None = all recorded), layout)
33
+ TASKS = {
34
+ "b6": (P / "b6-v5t7-ready-start-60ep-20261109/data/deliveries/g1/b6-v5t7-ready-start-20261109", 100, "g1"),
35
+ "basket": (P / "basket-current-dynamics-100-v21-b0ff522/data", None, "g1"),
36
+ "trolley": (P / "trolley-push-expert-v1-20261110/data/trolley_push", 100, "g1"),
37
+ "b7": (P / "b7-black-clothes-hamper-v1-1bb002a/data", 100, "g1"),
38
+ "b7green": (P / "b7-green-clothes-hamper-v1-ada288c/data", None, "g1"),
39
+ "a6": (P / "a6-door-pull-v1-cf3ee9b/data/door_pull", None, "g1"),
40
+ "a10v2": (P / "a10-trolley-push-v2-d3abb4c/data", None, "g1"),
41
+ "a1": (P / "a1-ground-object-pickup-v1-f47f07e/data", None, "g1"),
42
+ "c6": (P / "c6-bathroom-door-fetch-v1-3afba69/data", None, "g1"),
43
+ "a3": (P / "a3-a7-20261109/a3-fridge-open-expert-v1/780fcf1e4bd7db947a8c2d8f7b92e61f24f71b45", None, "g1"),
44
+ "a7": (P / "a3-a7-20261109/a7-cabinet-close-expert-v1/1935a98e8f55d4d1d2d1615ddb97c2679713595c", None, "g1"),
45
+ "a18": (P / "a18-h2-dataset-audit-8e956a10/dataset", None, "h2"),
46
+ "a17": (P / "a17-unscrew-bottle-v1-407e6e2/data", None, "h2"),
47
+ "a14": (P / "a14-unscrew-bulb-v1-b4390fc/data", None, "h2"),
48
+ # 2026-11-15: newer datasets (GR00T in-training eval needs a cache for every task it trains on)
49
+ "a10v3": (P / "a10-trolley-push-v3-6e410c5/data", None, "g1"),
50
+ "a7v2": (P / "a7-cabinet-close-v2-aecf070/data", None, "g1"),
51
+ "b1": (P / "b1-riceball-microwave-v1-36da298/data", None, "g1"),
52
+ "b7greenv2": (P / "b7-green-clothes-hamper-v2-c12757e/data", None, "g1"),
53
+ "b8": (P / "b8-table-wipe-v1-3b2e618/data", None, "g1"),
54
+ "basketv2": (P / "basket-trimv2-c4df4d4/data", None, "g1"),
55
+ "a14v2": (P / "a14-unscrew-bulb-v2-8411a6d/data", None, "h2p"), # action 82 = hb75 + SONIC planner 7
56
+ # 2026-11-15 evening: v6/v4 datasets (a3v3, a7v3 retired, not registered)
57
+ "b6v6": (P / "b6-pedal-bin-v6-ad2f5bf/data", None, "g1"), # 542 ep, all used (B6 first-100 rule is v5t7 only)
58
+ "b5": (P / "b5-chair-push-v1-b85b7e9/data", None, "g1"),
59
+ "a3v4": (P / "a3-fridge-open-v4-6393d4a/data", None, "g1"),
60
+ "a7v4": (P / "a7-cabinet-close-v4-90cc2b5/data", None, "g1"),
61
+ # 2026-11-16: B5 standing start (HF b5-chair-push-standing-start-expert-v1 @913f5a16, 100 ep; FastWAM b5ss)
62
+ "b5ss": (P / "b5-chair-push-standing-start-v1-913f5a1/data", None, "g1"),
63
+ # 2026-11-15 night: H2 cropped v2 (GR00T h32 relay item 71); head+chest only -> build_cache --cams head,chest
64
+ "a18cr2": (P / "a18-pour-water-cropped-v2-44cdd57/data", None, "h2"), # HF a18-pour-water-expert-cropped-v2 @44cdd571
65
+ "a17cr2": (P / "a17-unscrew-bottle-cropped-v2-3520b70/data", None, "h2"), # HF a17-unscrew-bottle-expert-cropped-v2 @3520b70f
66
+ }
67
+
68
+
69
+ def task_for_source(source):
70
+ """benchmark task whose recording root is <source> (groot-data/<view>/hb-dataset-receipt.json "source")"""
71
+ src = Path(source).resolve()
72
+ hits = [t for t, (root, _, _) in TASKS.items() if Path(root).resolve() == src]
73
+ return hits[0] if hits else None
74
+ G1_BODY = ["left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint",
75
+ "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint",
76
+ "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint",
77
+ "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_shoulder_pitch_joint",
78
+ "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint",
79
+ "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint",
80
+ "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint",
81
+ "right_wrist_pitch_joint", "right_wrist_yaw_joint"]
82
+ LAYOUTS = {
83
+ # state: body29 | inspire L6 | inspire R6 | projected_gravity3 ; action: motion_token64 | inspire L6 | R6 (same row)
84
+ "g1": dict(state_dim=44, action_dim=76, cams=("ego_view", "chest"),
85
+ groups={"motion_token": (0, 64), "hands": (64, 76)}),
86
+ # state: observation.state75 (legs12 waist3 arms14 head2 hands22+22) | gravity3 ; action: body_target31 | hands44
87
+ "h2": dict(state_dim=78, action_dim=75, cams=("head", "chest", "wrist"),
88
+ groups={"body_target": (0, 31), "hands": (31, 75)}),
89
+ # 2026-11-15 user: A14 v2 is trained on action82 = body_target31 | hands44 | action.planner7 (SONIC planner
90
+ # command); all 82 dims are scored (planner reported as its own group)
91
+ "h2p": dict(state_dim=78, action_dim=82, cams=("head", "chest"),
92
+ groups={"body_target": (0, 31), "hands": (31, 75), "planner": (75, 82)}),
93
+ }
94
+
95
+
96
+ def jl(path):
97
+ return [json.loads(x) for x in Path(path).read_text().splitlines() if x.strip()]
98
+
99
+
100
+ def layout(task):
101
+ return LAYOUTS[TASKS[task][2]]
102
+
103
+
104
+ def split_episodes(task, split, n_recorded):
105
+ _, n_train, _ = TASKS[task]
106
+ n_train = n_recorded if n_train is None else n_train
107
+ if split == "heldout":
108
+ return list(range(n_train, n_recorded))
109
+ if split == "train10":
110
+ return sorted({int(round(x)) for x in np.linspace(0, n_train - 1, N_TRAIN_EVAL)})
111
+ if split.startswith("ep:"): # explicit list, e.g. ep:100,101
112
+ return [int(x) for x in split[3:].split(",")]
113
+ raise ValueError(f"unknown split {split!r}")
114
+
115
+
116
+ def split_dir(task, split):
117
+ return CACHE / task / split
118
+
119
+
120
+ def load_meta(task, split):
121
+ return json.loads((split_dir(task, split) / "meta.json").read_text())
122
+
123
+
124
+ def load_stats(task):
125
+ z = np.load(CACHE / task / "stats.npz")
126
+ return {k: z[k] for k in z.files}
127
+
128
+
129
+ def norm_std(stats):
130
+ std = stats["action_std"].astype(np.float64)
131
+ return np.maximum(std, STD_FLOOR_FRAC * float(np.median(std)))
132
+
133
+
134
+ def iter_episodes(task, split, max_episodes=None):
135
+ meta = load_meta(task, split)
136
+ eps = meta["episodes"][: max_episodes or None]
137
+ for ep in eps:
138
+ with np.load(split_dir(task, split) / f"ep_{ep:06d}.npz") as z:
139
+ yield ep, {k: z[k] for k in z.files}
140
+
141
+
142
+ class Accumulator:
143
+ """Sums of squared / absolute errors; everything is computed in float64 over valid (row, dim) entries."""
144
+
145
+ def __init__(self, std, groups, horizon=HORIZON):
146
+ self.std = np.asarray(std, dtype=np.float64)
147
+ self.groups = groups
148
+ D = len(self.std)
149
+ self.sse_raw = np.zeros(D)
150
+ self.sae_raw = np.zeros(D)
151
+ self.sse_n = np.zeros(D)
152
+ self.rows = 0
153
+ self.step_sse_n = np.zeros(horizon)
154
+ self.step_rows = np.zeros(horizon)
155
+ self.per_episode = {}
156
+
157
+ def add(self, ep, pred, gt, valid):
158
+ pred = np.asarray(pred, dtype=np.float64)
159
+ gt = np.asarray(gt, dtype=np.float64)
160
+ v = np.asarray(valid, dtype=bool)
161
+ if pred.shape != gt.shape:
162
+ raise ValueError(f"pred {pred.shape} vs gt {gt.shape}")
163
+ if not np.isfinite(pred[v]).all():
164
+ raise FloatingPointError("non-finite prediction")
165
+ e = (pred - gt)[v]
166
+ en = e / self.std
167
+ self.sse_raw += (e ** 2).sum(0)
168
+ self.sae_raw += np.abs(e).sum(0)
169
+ self.sse_n += (en ** 2).sum(0)
170
+ self.rows += int(v.sum())
171
+ k = np.nonzero(v)[0]
172
+ self.step_sse_n[k] += (en ** 2).sum(1)
173
+ self.step_rows[k] += 1
174
+ s = self.per_episode.setdefault(int(ep), [0.0, 0])
175
+ s[0] += float((en ** 2).sum())
176
+ s[1] += int(v.sum()) * len(self.std)
177
+
178
+ def result(self):
179
+ D = len(self.std)
180
+ n = max(self.rows, 1)
181
+ out = {"rows": self.rows, "mse_raw": float(self.sse_raw.sum() / (n * D)),
182
+ "mae_raw": float(self.sae_raw.sum() / (n * D)), "nmse": float(self.sse_n.sum() / (n * D)),
183
+ "groups": {}, "nmse_by_step": (self.step_sse_n / np.maximum(self.step_rows, 1) / D).tolist(),
184
+ "nmse_by_dim": (self.sse_n / n).tolist()}
185
+ for g, (a, b) in self.groups.items():
186
+ out["groups"][g] = {"mse_raw": float(self.sse_raw[a:b].sum() / (n * (b - a))),
187
+ "nmse": float(self.sse_n[a:b].sum() / (n * (b - a)))}
188
+ pe = {ep: s / max(c, 1) for ep, (s, c) in sorted(self.per_episode.items())}
189
+ out["nmse_per_episode"] = pe
190
+ vals = np.array(list(pe.values()))
191
+ if len(vals) > 1: # bootstrap-free spread: std error over episodes
192
+ out["nmse_episode_sem"] = float(vals.std(ddof=1) / np.sqrt(len(vals)))
193
+ return out
194
+
195
+
196
+ def queries(T):
197
+ return list(range(0, T, STRIDE))
198
+
199
+
200
+ def gt_chunk(action, t, horizon=HORIZON):
201
+ T = len(action)
202
+ idx = np.arange(t, t + horizon)
203
+ valid = idx < T
204
+ return action[np.minimum(idx, T - 1)], valid
205
+
206
+
207
+ def run(adapter, task, split, out_path, max_episodes=None, max_queries=None, save_pred=True, log_every=50):
208
+ """Evaluate one adapter on one cached split; writes <out_path> (json) and <out_path>.pred.npz."""
209
+ meta = load_meta(task, split)
210
+ lay = LAYOUTS[meta["layout"]]
211
+ stats = load_stats(task)
212
+ acc = Accumulator(norm_std(stats), lay["groups"])
213
+ preds, keys = [], []
214
+ t0 = time.time()
215
+ infer_s = 0.0
216
+ nq = 0
217
+ for ep, z in iter_episodes(task, split, max_episodes):
218
+ state, action = z["state"], z["action"]
219
+ qts = list(z["query_t"])
220
+ for qi, t in enumerate(qts):
221
+ obs = {"episode": ep, "t": int(t), "T": len(action), "state": state[t], "prompt": meta["prompts"][str(int(z["task_index"]))],
222
+ "images": {c: z[f"img_{c}"][qi] for c in meta["cams"]},
223
+ "past_action": action[max(0, t - HORIZON):t],
224
+ "_gt_check": action[t:t + HORIZON]} # only for adapters' input-pipeline consistency checks
225
+ s = time.time()
226
+ pred = np.asarray(adapter.predict(obs), dtype=np.float64)
227
+ infer_s += time.time() - s
228
+ if pred.ndim != 2 or pred.shape[0] < HORIZON or pred.shape[1] != lay["action_dim"]:
229
+ raise ValueError(f"adapter returned {pred.shape}, need (>={HORIZON}, {lay['action_dim']})")
230
+ pred = pred[:HORIZON]
231
+ gt, valid = gt_chunk(action, t)
232
+ acc.add(ep, pred, gt, valid)
233
+ if save_pred:
234
+ preds.append(pred.astype(np.float32))
235
+ keys.append((ep, int(t)))
236
+ nq += 1
237
+ if log_every and nq % log_every == 0:
238
+ print(f"[eval] {task}/{split} {nq} queries, running nMSE {acc.result()['nmse']:.4f}, "
239
+ f"{infer_s / nq:.3f} s/query", flush=True)
240
+ if max_queries and nq >= max_queries:
241
+ break
242
+ if max_queries and nq >= max_queries:
243
+ break
244
+ res = acc.result()
245
+ res.update(task=task, split=split, layout=meta["layout"], episodes=sorted(acc.per_episode), queries=nq,
246
+ horizon=HORIZON, stride=STRIDE, std_floor_frac=STD_FLOOR_FRAC, wall_s=round(time.time() - t0, 1),
247
+ infer_s_per_query=round(infer_s / max(nq, 1), 4), adapter=adapter.info(),
248
+ baselines=meta.get("baselines", {}), cache_created=meta.get("created"),
249
+ partial=bool(max_episodes or max_queries), finished_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
250
+ out_path = Path(out_path)
251
+ out_path.parent.mkdir(parents=True, exist_ok=True)
252
+ tmp = out_path.with_suffix(".tmp")
253
+ tmp.write_text(json.dumps(res, indent=1))
254
+ tmp.replace(out_path)
255
+ if save_pred and preds:
256
+ np.savez_compressed(str(out_path) + ".pred.npz", pred=np.stack(preds).astype(np.float16),
257
+ keys=np.asarray(keys, dtype=np.int64))
258
+ return res
a10-trolley-push-v3/b512/step-002000/code/hb_inloop_core.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared machinery of the in-training open-loop action MSE (Psi-Zero, Delta Flow; GR00T has its own tested copy in
2
+ hb_groot/hb_inloop_eval.py with the same protocol).
3
+
4
+ InLoop(model_name, task, split, out_jsonl, prepare, predict):
5
+ prepare(queries) -> optional per-model setup on this rank's queries (first eval only, inside the RNG fork)
6
+ predict(batch, seed) -> np.ndarray (B, >=16, >=Da) in raw action units; the first 16 steps and the first Da dims
7
+ (Da = benchmark action dim of the layout) are scored.
8
+ InLoop.evaluate(step, model): all train/eval modes of model.modules() and every RNG state (torch CPU + this CUDA device,
9
+ numpy, python) are restored afterwards; partial sums are all-reduced once (error flag included, so a failure on one
10
+ rank cannot leave the others waiting); rank 0 appends one json line per eval. Any failure disables later evals.
11
+ Protocol and metrics = hb_eval_common (post-hoc eval): queries every 16 frames, nMSE with the training-frame std.
12
+ """
13
+ import json
14
+ import os
15
+ import random
16
+ import sys
17
+ import time
18
+ import traceback
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ if str(HERE) not in sys.path:
26
+ sys.path.insert(0, str(HERE))
27
+ import hb_eval_common as E # noqa: E402
28
+
29
+ EVERY = int(os.environ.get("HB_INLOOP_EVERY", "250"))
30
+ BATCH = int(os.environ.get("HB_INLOOP_BATCH", "8"))
31
+ MAX_Q = int(os.environ.get("HB_INLOOP_MAX_QUERIES", "0"))
32
+ SEED = 1234
33
+
34
+
35
+ def dist_info():
36
+ import torch.distributed as dist
37
+ if dist.is_available() and dist.is_initialized():
38
+ return dist.get_rank(), dist.get_world_size()
39
+ return int(os.environ.get("RANK", "0")), int(os.environ.get("WORLD_SIZE", "1"))
40
+
41
+
42
+ def pick_split(task):
43
+ split = os.environ.get("HB_INLOOP_SPLIT")
44
+ if not split:
45
+ split = "heldout" if (E.split_dir(task, "heldout") / "meta.json").exists() else "train10"
46
+ if not (E.split_dir(task, split) / "meta.json").exists():
47
+ raise FileNotFoundError(f"eval cache {task}/{split} missing (build_cache.py {task} {split})")
48
+ return split
49
+
50
+
51
+ class InLoop:
52
+ def __init__(self, model_name, task, split, out_jsonl, predict, prepare=None, cams=None, info=None):
53
+ self.model_name, self.task, self.split = model_name, task, split
54
+ self.out = Path(out_jsonl)
55
+ self.predict, self.prepare = predict, prepare
56
+ self.cams = cams
57
+ self.info = info or {}
58
+ self.disabled = False
59
+ self.ready = False
60
+ self.done_steps = set()
61
+
62
+ def say(self, *a):
63
+ if dist_info()[0] == 0:
64
+ print("HB_INLOOP", *a, flush=True)
65
+
66
+ def _setup(self):
67
+ rank, world = dist_info()
68
+ meta = E.load_meta(self.task, self.split)
69
+ self.meta, self.lay = meta, E.LAYOUTS[meta["layout"]]
70
+ self.std = E.norm_std(E.load_stats(self.task))
71
+ cams = self.cams or meta["cams"]
72
+ miss = [c for c in cams if c not in meta["cams"]]
73
+ if miss:
74
+ raise KeyError(f"cameras {miss} not in the eval cache {meta['cams']}")
75
+ allq = []
76
+ for ep in meta["episodes"]:
77
+ with np.load(E.split_dir(self.task, self.split) / f"ep_{ep:06d}.npz") as z:
78
+ allq += [(ep, qi, int(t)) for qi, t in enumerate(z["query_t"])]
79
+ if MAX_Q:
80
+ allq = allq[:MAX_Q]
81
+ self.n_total = len(allq)
82
+ mine = [q for i, q in enumerate(allq) if i % world == rank]
83
+ self.eps = list(meta["episodes"])
84
+ by_ep = {}
85
+ for ep, qi, t in mine:
86
+ by_ep.setdefault(ep, []).append((qi, t))
87
+ self.q = []
88
+ for ep, lst in by_ep.items():
89
+ with np.load(E.split_dir(self.task, self.split) / f"ep_{ep:06d}.npz") as z:
90
+ state, action = z["state"], z["action"]
91
+ prompt = meta["prompts"][str(int(z["task_index"]))]
92
+ imgs = {c: z[f"img_{c}"] for c in cams}
93
+ for qi, t in lst:
94
+ gt, valid = E.gt_chunk(action, t)
95
+ self.q.append(dict(episode=int(ep), t=int(t), T=len(action), state=state[t].copy(), prompt=prompt,
96
+ images={c: imgs[c][qi].copy() for c in cams}, gt=gt, valid=valid,
97
+ past_action=action[max(0, t - E.HORIZON):t].copy()))
98
+ if self.prepare:
99
+ self.prepare(self.q)
100
+ self.ready = True
101
+ self.say(f"{self.model_name} ready: task {self.task} split {self.split} queries {self.n_total} "
102
+ f"(rank {rank}/{world}: {len(self.q)}), every {EVERY} steps, batch {BATCH}, cams {cams}")
103
+
104
+ def evaluate(self, step, model):
105
+ if self.disabled or step in self.done_steps:
106
+ return
107
+ self.done_steps.add(step)
108
+ rank, world = dist_info()
109
+ t0 = time.time()
110
+ err, msg = 0.0, ""
111
+ acc, nq, infer = None, 0, 0.0
112
+ modes = [(m, m.training) for m in model.modules()]
113
+ dev = torch.cuda.current_device() if torch.cuda.is_available() else None
114
+ np_state, py_state = np.random.get_state(), random.getstate()
115
+ try:
116
+ with torch.random.fork_rng(devices=[dev] if dev is not None else []):
117
+ if not self.ready:
118
+ self._setup()
119
+ D = self.lay["action_dim"]
120
+ model.eval()
121
+ acc = E.Accumulator(self.std, self.lay["groups"])
122
+ for bi in range(0, len(self.q), BATCH):
123
+ batch = self.q[bi:bi + BATCH]
124
+ seed = SEED + 1000 * rank + bi
125
+ torch.default_generator.manual_seed(seed)
126
+ if dev is not None:
127
+ torch.cuda.manual_seed(seed)
128
+ s = time.time()
129
+ with torch.no_grad():
130
+ pred = np.asarray(self.predict(batch, seed), dtype=np.float64)
131
+ infer += time.time() - s
132
+ if pred.ndim != 3 or pred.shape[0] != len(batch) or pred.shape[1] < E.HORIZON or pred.shape[2] < D:
133
+ raise ValueError(f"prediction {pred.shape}, need ({len(batch)}, >={E.HORIZON}, >={D})")
134
+ for q, p in zip(batch, pred):
135
+ acc.add(q["episode"], p[:E.HORIZON, :D], q["gt"], q["valid"])
136
+ nq += 1
137
+ except Exception as e: # noqa: BLE001 - never stop training
138
+ err, msg = 1.0, f"{type(e).__name__}: {e}"
139
+ print(f"HB_INLOOP {self.model_name} rank {rank} step {step} FAILED: {msg}\n{traceback.format_exc()}",
140
+ file=sys.stderr, flush=True)
141
+ finally:
142
+ for m, tr in modes:
143
+ m.training = tr
144
+ np.random.set_state(np_state)
145
+ random.setstate(py_state)
146
+ D = self.lay["action_dim"] if self.ready else 0
147
+ H = E.HORIZON
148
+ eps = self.eps if self.ready else []
149
+ nE = len(eps)
150
+ vec = np.zeros(3 * D + 1 + 2 * H + 2 * nE + 3)
151
+ if acc is not None and not err:
152
+ o = 0
153
+ vec[o:o + D] = acc.sse_raw; o += D
154
+ vec[o:o + D] = acc.sae_raw; o += D
155
+ vec[o:o + D] = acc.sse_n; o += D
156
+ vec[o] = acc.rows; o += 1
157
+ vec[o:o + H] = acc.step_sse_n; o += H
158
+ vec[o:o + H] = acc.step_rows; o += H
159
+ for j, ep in enumerate(eps):
160
+ s_, c_ = acc.per_episode.get(int(ep), (0.0, 0))
161
+ vec[o + j], vec[o + nE + j] = s_, c_
162
+ o += 2 * nE
163
+ vec[o], vec[o + 1] = nq, infer
164
+ vec[-1] = err
165
+ tot = self._allreduce(vec)
166
+ if tot is None or tot[-1] > 0 or not self.ready:
167
+ self.disabled = True
168
+ nfail = None if tot is None else int(tot[-1])
169
+ self._write({"step": step, "error": msg or "failed on another rank / collective failed",
170
+ "ranks_failed": nfail})
171
+ self.say(f"{self.model_name} step {step}: eval failed ({nfail} rank(s)) -> in-training eval disabled: {msg}")
172
+ return
173
+ o = 0
174
+ acc = E.Accumulator(self.std, self.lay["groups"])
175
+ acc.sse_raw = tot[o:o + D]; o += D
176
+ acc.sae_raw = tot[o:o + D]; o += D
177
+ acc.sse_n = tot[o:o + D]; o += D
178
+ acc.rows = int(round(tot[o])); o += 1
179
+ acc.step_sse_n = tot[o:o + H]; o += H
180
+ acc.step_rows = tot[o:o + H]; o += H
181
+ acc.per_episode = {int(ep): [float(tot[o + j]), int(round(tot[o + nE + j]))]
182
+ for j, ep in enumerate(eps) if tot[o + nE + j] > 0}
183
+ o += 2 * nE
184
+ n_q, infer_sum = int(round(tot[o])), float(tot[o + 1])
185
+ res = acc.result()
186
+ res.pop("nmse_by_dim", None)
187
+ rec = {"step": step, "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "model": self.model_name,
188
+ "task": self.task, "split": self.split, "queries": n_q, "ranks": world,
189
+ "wall_s": round(time.time() - t0, 1), "infer_s_per_query": round(infer_sum / max(n_q, 1), 4),
190
+ "seed": SEED, **self.info, **res}
191
+ self._write(rec)
192
+ g = " ".join(f"{k} {v['nmse']:.4f}" for k, v in res["groups"].items())
193
+ self.say(f"{self.model_name} step {step}: {self.task}/{self.split} nMSE {res['nmse']:.4f} ({g}) on {n_q} "
194
+ f"queries, {rec['wall_s']} s")
195
+
196
+ @staticmethod
197
+ def _allreduce(vec):
198
+ import torch.distributed as dist
199
+ if not (dist.is_available() and dist.is_initialized()) or dist.get_world_size() == 1:
200
+ return vec
201
+ try:
202
+ dev = "cuda" if dist.get_backend() == "nccl" else "cpu"
203
+ n = torch.tensor([float(len(vec))], dtype=torch.float64, device=dev)
204
+ mx, mn = n.clone(), n.clone()
205
+ dist.all_reduce(mx, op=dist.ReduceOp.MAX)
206
+ dist.all_reduce(mn, op=dist.ReduceOp.MIN)
207
+ if mx.item() != mn.item():
208
+ return None
209
+ t = torch.from_numpy(vec).to(device=dev, dtype=torch.float64)
210
+ dist.all_reduce(t)
211
+ return t.cpu().numpy()
212
+ except Exception as e: # noqa: BLE001
213
+ print(f"HB_INLOOP all_reduce failed: {e!r}", file=sys.stderr, flush=True)
214
+ return None
215
+
216
+ def _write(self, rec):
217
+ if dist_info()[0] != 0:
218
+ return
219
+ try:
220
+ self.out.parent.mkdir(parents=True, exist_ok=True)
221
+ with open(self.out, "a") as f:
222
+ f.write(json.dumps(rec) + "\n")
223
+ except Exception as e: # noqa: BLE001
224
+ print(f"HB_INLOOP write failed: {e!r}", flush=True)
225
+
226
+
227
+ class TempAttrs:
228
+ """set attributes on an object for the duration of a block, then restore (or delete) them"""
229
+ _MISSING = object()
230
+
231
+ def __init__(self, obj, **kw):
232
+ self.obj, self.kw, self.old = obj, kw, {}
233
+
234
+ def __enter__(self):
235
+ for k, v in self.kw.items():
236
+ self.old[k] = self.obj.__dict__.get(k, self._MISSING)
237
+ setattr(self.obj, k, v)
238
+ return self.obj
239
+
240
+ def __exit__(self, *exc):
241
+ for k, v in self.old.items():
242
+ if v is self._MISSING:
243
+ try:
244
+ delattr(self.obj, k)
245
+ except AttributeError:
246
+ pass
247
+ else:
248
+ setattr(self.obj, k, v)
249
+ return False
a10-trolley-push-v3/b512/step-002000/code/hb_inloop_fastwam.py CHANGED
@@ -94,9 +94,13 @@ def install():
94
 
95
  def __init__(self, *a, **kw):
96
  orig_init(self, *a, **kw)
97
- if self.val_dataset is None and int(self.eval_every) == 0:
 
 
 
98
  self.eval_every = C.EVERY
99
- self.val_dataset = _Marker()
 
100
  self._hb_inloop_on = True
101
  else: # a native eval is configured: leave it alone
102
  self._hb_inloop_on = False
 
94
 
95
  def __init__(self, *a, **kw):
96
  orig_init(self, *a, **kw)
97
+ # native eval off (eval_every 0 on our command line). NB runtime.build_datasets sets val_ds = train_ds when
98
+ # there is no data.val, so val_dataset is never None here (11-16 smoke: the old "val_dataset is None" test
99
+ # silently left the in-loop eval off).
100
+ if int(self.eval_every) == 0:
101
  self.eval_every = C.EVERY
102
+ if self.val_dataset is None:
103
+ self.val_dataset = _Marker()
104
  self._hb_inloop_on = True
105
  else: # a native eval is configured: leave it alone
106
  self._hb_inloop_on = False
a10-trolley-push-v3/b512/step-002000/code/test_fastwam_inputs.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU check (no model): the FastWAM adapter's inputs built from the model-agnostic eval cache == the inputs our FastWAM
2
+ training dataset (RobotVideoDataset of the run's config, no HB augmentation) builds for the same frame.
3
+ python test_fastwam_inputs.py <task> <run out dir> [n_queries]"""
4
+ import json
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ HERE = Path(__file__).resolve().parent
12
+ sys.path.insert(0, str(HERE))
13
+ sys.path.insert(0, str(HERE / "adapters"))
14
+ import hb_eval_common as E # noqa: E402
15
+ import ad_fastwam as A # noqa: E402
16
+
17
+ task, out = sys.argv[1], Path(sys.argv[2])
18
+ nq = int(sys.argv[3]) if len(sys.argv) > 3 else 3
19
+ A.setup_env()
20
+ import torch # noqa: E402
21
+ from omegaconf import OmegaConf # noqa: E402
22
+ import fastwam.runtime as native # noqa: E402
23
+ from fastwam.utils import misc # noqa: E402
24
+
25
+ cfg = OmegaConf.load(out / "config.yaml")
26
+ inp = A.Inputs(cfg, out / "dataset_stats.json")
27
+ misc.register_work_dir("/tmp/hbfw-inputs-check")
28
+ OmegaConf.update(cfg, "data.train.pretrained_norm_stats", str(out / "dataset_stats.json"), merge=False, force_add=True)
29
+ tr, _ = native.build_datasets(cfg.data)
30
+ ddir = Path(cfg.data.train.dataset_dirs[0])
31
+ lens = [json.loads(l)["length"] for l in (ddir / "meta/episodes.jsonl").read_text().splitlines() if l.strip()]
32
+ meta = E.load_meta(task, "train10")
33
+ split = "train10"
34
+ worst = {}
35
+ done = 0
36
+ for ep, z in E.iter_episodes(task, split, None):
37
+ base = int(sum(lens[:ep]))
38
+ for qi, t in enumerate(list(z["query_t"])[1:1 + nq], start=1):
39
+ t = int(t)
40
+ s = tr[base + t]
41
+ obs = {"images": {c: z[f"img_{c}"][qi] for c in meta["cams"]}, "state": z["state"][t],
42
+ "prompt": meta["prompts"][str(int(z["task_index"]))]}
43
+ img = inp.image(obs["images"])[0]
44
+ d_img = float((img - s["video"][:, 0].float()).abs().max())
45
+ pr = inp.proprio(obs["state"])[0]
46
+ d_pr = float((pr - s["proprio"][0].float()).abs().max())
47
+ ctx, mask = inp.context(obs["prompt"])
48
+ d_ctx = float((ctx.float() - s["context"].float()).abs().max())
49
+ d_mask = int((mask != s["context_mask"].bool()).sum())
50
+ gt = z["action"][t:t + 16]
51
+ a = inp.denorm(s["action"][:16])
52
+ d_act = float(np.abs(a[:len(gt)] - gt).max())
53
+ row = dict(ep=ep, t=t, idx=base + t, img=d_img, proprio=d_pr, ctx=d_ctx, mask=d_mask, act_denorm_vs_cache=d_act,
54
+ prompt_same=s["prompt"] == inp.DEFAULT_PROMPT.format(task=obs["prompt"]))
55
+ print("CHECK", json.dumps(row), flush=True)
56
+ for k in ("img", "proprio", "ctx", "act_denorm_vs_cache"):
57
+ worst[k] = max(worst.get(k, 0.0), row[k])
58
+ done += 1
59
+ if done >= 2 * nq:
60
+ break
61
+ print("WORST", json.dumps(worst))
a10-trolley-push-v3/b512/step-002000/protocol.json CHANGED
@@ -36,19 +36,23 @@
36
  "batch_selection": "largest per-GPU batch that fits on A800 80 GB: 16 trains at ~58 GB, 32 runs out of memory (batch_benchmark/)",
37
  "normalization": "dataset_stats.json (FastWAM min / max statistics of this task)",
38
  "config": "training_config.yaml (resolved FastWAM config; absolute paths refer to the training NAS), model_config.yaml (the model part)",
39
- "inference": "FastWAM: build the model from model_config.yaml, load model.pt (DiT state dict), the normalizer from dataset_stats.json and the prompt embedding from text_embeddings/; code/hb_fastwam_convert.py documents the state / action layout of the benchmark interface",
40
  "training_records_included": true,
41
  "resume_state_included": false,
42
  "files": {
43
  "batch_benchmark/chosen.json": 210,
44
  "batch_benchmark/summary.txt": 127,
 
45
  "code/fastwam_prep.sh": 3634,
46
  "code/fastwam_task.sh": 3719,
47
  "code/hb_aug_v2.py": 7475,
 
48
  "code/hb_fastwam_aug.py": 3345,
49
  "code/hb_fastwam_convert.py": 7101,
50
  "code/hb_fastwam_train.py": 5570,
51
- "code/hb_inloop_fastwam.py": 5137,
 
 
52
  "complete.json": 660,
53
  "dataset_meta/hb_fastwam_interface.json": 338,
54
  "dataset_meta/info.json": 11456,
@@ -63,12 +67,13 @@
63
  "model.pt": 12042313337,
64
  "model_config.yaml": 1350,
65
  "text_embeddings/012c1778878f57dcfd1251771b96657ba3238ab1ec1875c0fede3b26ef6ecb86.t5_len128.wan22ti2v5b.pt": 12587613,
66
- "text_embeddings/2b20df4838f4dbf93ca5e7c2ea5ad0e903bc5b844775b6917e1a61ca1eb8d191.t5_len128.wan22ti2v5b.pt": 12587613,
67
  "text_embeddings/31e0f5d5a4ce6c1e4fbf5beb2283e83b63b79b777b162019e79997769ffd1013.t5_len128.wan22ti2v5b.pt": 12587613,
68
  "text_embeddings/3c22d73f4422b8ecdb2085a7cde039d5565ab26cdb312fd41c802987c2d19d1b.t5_len128.wan22ti2v5b.pt": 12587613,
69
  "text_embeddings/52510cc822aba2c8234a8da323bd0091b23a933cb8232d2fe82bc8085f47cd71.t5_len128.wan22ti2v5b.pt": 12587613,
70
  "text_embeddings/5a20e43a27564ea8978edc7394a96e0c1295e82528d59dba0c4169f3bba9a630.t5_len128.wan22ti2v5b.pt": 12587613,
71
  "text_embeddings/7649f0a497710702f2a47162bf5c56e45fc1ca53b81f935c9a048b61c231f130.t5_len128.wan22ti2v5b.pt": 12587613,
 
72
  "text_embeddings/d82ae9ce680248c4bb47e139992293855384c2e769939796b7d59b722ba7a37a.t5_len128.wan22ti2v5b.pt": 12587613,
73
  "text_embeddings/db6124d444ef41566d73455e3547ac6a113fae4c3e6c94d5f79b2a8be8298814.t5_len128.wan22ti2v5b.pt": 12587613,
74
  "text_embeddings/e0bf8801f26f15c00e43f58ba954054499fa70c490444b8f01c0b224db95c905.t5_len128.wan22ti2v5b.pt": 12587613,
 
36
  "batch_selection": "largest per-GPU batch that fits on A800 80 GB: 16 trains at ~58 GB, 32 runs out of memory (batch_benchmark/)",
37
  "normalization": "dataset_stats.json (FastWAM min / max statistics of this task)",
38
  "config": "training_config.yaml (resolved FastWAM config; absolute paths refer to the training NAS), model_config.yaml (the model part)",
39
+ "inference": "FastWAM: build the model from model_config.yaml, load model.pt (DiT state dict), the normalizer from dataset_stats.json and the prompt embedding from text_embeddings/; code/hb_fastwam_convert.py documents the state / action layout of the benchmark interface; code/ad_fastwam.py is the inference adapter of our evaluation (action-only FastWAM.infer_action, 10 denoising steps, seed 42; its default paths refer to the training NAS)",
40
  "training_records_included": true,
41
  "resume_state_included": false,
42
  "files": {
43
  "batch_benchmark/chosen.json": 210,
44
  "batch_benchmark/summary.txt": 127,
45
+ "code/ad_fastwam.py": 8413,
46
  "code/fastwam_prep.sh": 3634,
47
  "code/fastwam_task.sh": 3719,
48
  "code/hb_aug_v2.py": 7475,
49
+ "code/hb_eval_common.py": 13273,
50
  "code/hb_fastwam_aug.py": 3345,
51
  "code/hb_fastwam_convert.py": 7101,
52
  "code/hb_fastwam_train.py": 5570,
53
+ "code/hb_inloop_core.py": 11206,
54
+ "code/hb_inloop_fastwam.py": 5431,
55
+ "code/test_fastwam_inputs.py": 2724,
56
  "complete.json": 660,
57
  "dataset_meta/hb_fastwam_interface.json": 338,
58
  "dataset_meta/info.json": 11456,
 
67
  "model.pt": 12042313337,
68
  "model_config.yaml": 1350,
69
  "text_embeddings/012c1778878f57dcfd1251771b96657ba3238ab1ec1875c0fede3b26ef6ecb86.t5_len128.wan22ti2v5b.pt": 12587613,
70
+ "text_embeddings/2b20df4838f4dbf93ca5e7c2ea5ad0e903bc5b844775b6917e1a61ca1eb8d191.t5_len128.wan22ti2v5b.pt": 1051869,
71
  "text_embeddings/31e0f5d5a4ce6c1e4fbf5beb2283e83b63b79b777b162019e79997769ffd1013.t5_len128.wan22ti2v5b.pt": 12587613,
72
  "text_embeddings/3c22d73f4422b8ecdb2085a7cde039d5565ab26cdb312fd41c802987c2d19d1b.t5_len128.wan22ti2v5b.pt": 12587613,
73
  "text_embeddings/52510cc822aba2c8234a8da323bd0091b23a933cb8232d2fe82bc8085f47cd71.t5_len128.wan22ti2v5b.pt": 12587613,
74
  "text_embeddings/5a20e43a27564ea8978edc7394a96e0c1295e82528d59dba0c4169f3bba9a630.t5_len128.wan22ti2v5b.pt": 12587613,
75
  "text_embeddings/7649f0a497710702f2a47162bf5c56e45fc1ca53b81f935c9a048b61c231f130.t5_len128.wan22ti2v5b.pt": 12587613,
76
+ "text_embeddings/cd0ca5d7666fa68fe2141dfac894ceea404ab7cf2a88b8617a489f124dfdfdf2.t5_len128.wan22ti2v5b.pt": 1051869,
77
  "text_embeddings/d82ae9ce680248c4bb47e139992293855384c2e769939796b7d59b722ba7a37a.t5_len128.wan22ti2v5b.pt": 12587613,
78
  "text_embeddings/db6124d444ef41566d73455e3547ac6a113fae4c3e6c94d5f79b2a8be8298814.t5_len128.wan22ti2v5b.pt": 12587613,
79
  "text_embeddings/e0bf8801f26f15c00e43f58ba954054499fa70c490444b8f01c0b224db95c905.t5_len128.wan22ti2v5b.pt": 12587613,
a10-trolley-push-v3/b512/step-004000/code/ad_fastwam.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """FastWAM adapter (2026-11-16). Deployment path of FastWAM's own policy (experiments/robotwin/fastwam_policy/
2
+ deploy_policy.py, WorldActionRobotWinPolicy._infer_action_chunk: model.infer_action, the action-only path = first-frame
3
+ video KV cache + action-expert denoising, no future video) fed exactly like our training dataset (RobotVideoDataset +
4
+ FastWAMProcessor of the run's config.yaml, no HB augmentation):
5
+ * cameras in shape_meta order (g1 ego_view + chest, h2 head + chest): uint8 [1,C,H,W] -> processor val transforms
6
+ (ToTensor /255 + Resize 224x224), concatenated horizontally (224 x 448), dataset ResizeSmallestSide/CenterCrop
7
+ (no-op at 224 x 448), Normalize(0.5, 0.5) -> [-1, 1];
8
+ * state: processor.action_state_transform -> normalizer.forward (min/max of the run's
9
+ dataset_stats.json), the proprio of the first frame;
10
+ * text: the run's T5 cache for DEFAULT_PROMPT.format(task=instruction) with context[~mask] = 0 and mask = ones, as in
11
+ training (the text encoder is not loaded in training either; deploy_policy encodes the same prompt with T5 online);
12
+ * infer_action(action_horizon = num_frames - 1 = 16, num_inference_steps = config eval_num_inference_steps (10),
13
+ text_cfg_scale 1, seed 42 = native trainer eval), denormalised with normalizer.normalizers["action"][key].backward.
14
+ ckpt = .../fastwam/runs/<task>/out/checkpoints/weights/step_<N>.pt (config.yaml + dataset_stats.json in .../out).
15
+ Weights: model built from the config (Wan2.2 + ActionDiT init), then the checkpoint's mot + proprio_encoder are
16
+ loaded STRICTLY (FastWAM.load_checkpoint uses strict=False for mot; a missing key here is an error).
17
+ """
18
+ import os
19
+ import sys
20
+ from pathlib import Path
21
+
22
+ import numpy as np
23
+
24
+ import hb_eval_common as E
25
+
26
+ FW = E.G / "fastwam"
27
+
28
+
29
+ def setup_env():
30
+ os.environ.setdefault("FASTWAM_SRC", str(FW / "FastWAM"))
31
+ os.environ.setdefault("DIFFSYNTH_MODEL_BASE_PATH", str(FW / "models"))
32
+ os.environ.setdefault("DIFFSYNTH_SKIP_DOWNLOAD", "true")
33
+ os.environ.setdefault("HF_HUB_OFFLINE", "1")
34
+ src = str(Path(os.environ["FASTWAM_SRC"]) / "src")
35
+ if src not in sys.path:
36
+ sys.path.insert(0, src)
37
+
38
+
39
+ class Inputs:
40
+ """model-agnostic cache query -> FastWAM inputs (shared by the post-hoc adapter and the in-training eval)"""
41
+
42
+ def __init__(self, cfg, stats_path):
43
+ setup_env()
44
+ from hydra.utils import instantiate
45
+ from omegaconf import OmegaConf
46
+ from fastwam.datasets.dataset_utils import CenterCrop, Normalize, ResizeSmallestSideAspectPreserving
47
+ from fastwam.datasets.lerobot.robot_video_dataset import DEFAULT_PROMPT
48
+ from fastwam.datasets.lerobot.utils.normalizer import load_dataset_stats_from_json
49
+ d = cfg.data.train
50
+ self.DEFAULT_PROMPT = DEFAULT_PROMPT
51
+ self.proc = instantiate(d.processor).eval()
52
+ self.proc.set_normalizer_from_stats(load_dataset_stats_from_json(str(stats_path)))
53
+ self.cams = [m["key"] for m in self.proc.shape_meta["images"]]
54
+ if d.concat_multi_camera != "horizontal":
55
+ raise ValueError(f"concat_multi_camera {d.concat_multi_camera} not supported")
56
+ vs = list(d.video_size)
57
+ self.resize = ResizeSmallestSideAspectPreserving(args={"img_w": vs[1], "img_h": vs[0]})
58
+ self.crop = CenterCrop(args={"img_w": vs[1], "img_h": vs[0]})
59
+ self.norm = Normalize(args={"mean": 0.5, "std": 0.5})
60
+ self.cache_dir = d.text_embedding_cache_dir
61
+ self.context_len = int(d.context_len)
62
+ self.horizon = int(d.num_frames) - 1
63
+ self.skey = self.proc.shape_meta["state"][0]["key"]
64
+ self.akey = self.proc.shape_meta["action"][0]["key"]
65
+ if len(self.proc.shape_meta["state"]) != 1 or len(self.proc.shape_meta["action"]) != 1:
66
+ raise ValueError("expected one merged state key and one merged action key")
67
+ self._ctx = {}
68
+ self.OmegaConf = OmegaConf
69
+
70
+ def image(self, images):
71
+ import torch
72
+ per = []
73
+ for c in self.cams:
74
+ x = torch.from_numpy(np.ascontiguousarray(images[c])).permute(2, 0, 1).unsqueeze(0) # [1,C,H,W] uint8
75
+ for tr in self.proc.val_transforms:
76
+ x = tr(x)
77
+ per.append(x)
78
+ v = torch.cat(per, dim=-1) # [1, C, 224, 448]
79
+ v = self.norm(self.crop(self.resize(v)))
80
+ return v # [1, 3, H, W] in [-1, 1], float32
81
+
82
+ def proprio(self, state):
83
+ import torch
84
+ b = {"state": {self.skey: torch.as_tensor(np.asarray(state, dtype=np.float32)).unsqueeze(0)}}
85
+ b = self.proc.action_state_transform(b)
86
+ b = self.proc.normalizer.forward(b) # = deploy_policy._normalize_state (one merged key: merger is identity)
87
+ return b["state"][self.skey] # [1, D]
88
+
89
+ def context(self, instruction):
90
+ import hashlib
91
+ import torch
92
+ prompt = self.DEFAULT_PROMPT.format(task=instruction)
93
+ if prompt not in self._ctx:
94
+ h = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
95
+ p = os.path.join(self.cache_dir, f"{h}.t5_len{self.context_len}.wan22ti2v5b.pt")
96
+ if not os.path.exists(p):
97
+ raise FileNotFoundError(f"no T5 cache for the instruction ({p}): {instruction[:80]!r}")
98
+ obj = torch.load(p, map_location="cpu")
99
+ ctx, mask = obj["context"], obj["mask"]
100
+ ctx = ctx.clone()
101
+ ctx[~mask.bool()] = 0.0
102
+ self._ctx[prompt] = (ctx, torch.ones_like(mask.bool()))
103
+ return self._ctx[prompt]
104
+
105
+ def denorm(self, action):
106
+ import torch
107
+ a = action
108
+ if a.ndim == 2:
109
+ a = a.unsqueeze(0)
110
+ n = self.proc.normalizer.normalizers["action"][self.akey]
111
+ return n.backward(a.to(dtype=torch.float32, device="cpu")).numpy()[0]
112
+
113
+
114
+ def infer(model, inp, obs, steps, seed=42):
115
+ import torch
116
+ img = inp.image(obs["images"]).to(device=model.device, dtype=model.torch_dtype)
117
+ ctx, mask = inp.context(obs["prompt"])
118
+ with torch.no_grad():
119
+ out = model.infer_action(prompt=None, input_image=img, action_horizon=inp.horizon, proprio=inp.proprio(obs["state"]),
120
+ context=ctx, context_mask=mask, text_cfg_scale=1.0, num_inference_steps=steps, seed=seed,
121
+ rand_device="cpu", tiled=False)
122
+ return inp.denorm(out["action"])
123
+
124
+
125
+ class Adapter:
126
+ def __init__(self, ckpt, task, split, meta, device="cuda:0", steps=None, seed="42"):
127
+ setup_env()
128
+ import torch
129
+ from hydra.utils import instantiate
130
+ from omegaconf import OmegaConf
131
+ self.torch = torch
132
+ ckpt = Path(ckpt)
133
+ out = ckpt.parent.parent.parent
134
+ self.cfg = OmegaConf.load(out / "config.yaml")
135
+ self.inp = Inputs(self.cfg, out / "dataset_stats.json")
136
+ miss = [c for c in self.inp.cams if c not in meta["cams"]]
137
+ if miss:
138
+ raise KeyError(f"cameras {miss} not in the cache {meta['cams']}")
139
+ self.device = device if torch.cuda.is_available() else "cpu"
140
+ mp = str(self.cfg.get("mixed_precision", "bf16")).lower()
141
+ dtype = {"bf16": torch.bfloat16, "fp16": torch.float16, "no": torch.float32}[mp]
142
+ self.model = instantiate(self.cfg.model, model_dtype=dtype, device=self.device)
143
+ payload = torch.load(str(ckpt), map_location="cpu")
144
+ miss_k, unexp = self.model.mot.load_state_dict(payload["mot"], strict=False)
145
+ if miss_k or unexp:
146
+ raise RuntimeError(f"checkpoint mot keys: missing {list(miss_k)[:5]} unexpected {list(unexp)[:5]}")
147
+ if self.model.proprio_encoder is not None:
148
+ self.model.proprio_encoder.load_state_dict(payload["proprio_encoder"], strict=True)
149
+ self.ckpt_step = payload.get("step")
150
+ del payload
151
+ self.model = self.model.to(self.device).eval()
152
+ self.native_steps = int(self.cfg.eval_num_inference_steps)
153
+ self.steps = int(steps or self.native_steps)
154
+ self.seed = int(seed)
155
+ self.ckpt = str(ckpt)
156
+
157
+ def info(self):
158
+ return {"model": "fastwam", "ckpt": self.ckpt, "ckpt_step": self.ckpt_step, "denoising_steps": self.steps,
159
+ "native_steps_in_config": self.native_steps, "cams": self.inp.cams, "chunk": self.inp.horizon,
160
+ "seed": self.seed, "path": "FastWAM.infer_action (action-only, deploy_policy)"}
161
+
162
+ def predict(self, obs):
163
+ return infer(self.model, self.inp, obs, self.steps, self.seed)
a10-trolley-push-v3/b512/step-004000/code/hb_eval_common.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Humanoid Benchmark open-loop action-reconstruction evaluation: shared task table, cache layout and metrics.
2
+
3
+ Protocol (identical for every model; mirrors Isaac-GR00T gr00t/eval/open_loop_eval.py):
4
+ * query frames t = 0, 16, 32, ... over the whole episode (non-overlapping 16-step chunks);
5
+ * the model sees the observation at t exactly as at deployment (cameras, raw benchmark state 44/78, instruction;
6
+ Delta Flow also its native 16-step past-action history), all augmentation off;
7
+ * the predicted chunk (first 16 steps, raw action units) is compared with the recorded actions t..t+15;
8
+ rows beyond the episode end are excluded (no clamped / padded targets);
9
+ * metrics: raw MSE / MAE, and nMSE = MSE after dividing every action dim by its std over the task's TRAINING
10
+ frames (floored, see STD_FLOOR_FRAC), overall, per action group and per horizon step.
11
+ Splits: "heldout" = recorded episodes that were never trained on (B6 100-148, trolley 100-102, B7 100-106);
12
+ "train10" = 10 fixed, evenly spaced training episodes (fit on seen data, NOT generalisation).
13
+ Only numpy here: imported by every model environment.
14
+ """
15
+ import json
16
+ import os
17
+ import time
18
+ from pathlib import Path
19
+
20
+ import numpy as np
21
+
22
+ G = Path(os.environ.get("G", "/mnt/nas/cross/Team/RobotAgent/Personal/baijiaqi/humanoid-benchmark-work/"
23
+ "preflight-20261104T1648Z/policies-20261109"))
24
+ P = G.parent
25
+ ROOT = G / "eval-action-mse"
26
+ CACHE = Path(os.environ.get("HB_EVAL_CACHE", ROOT / "cache"))
27
+ HORIZON = 16
28
+ STRIDE = 16
29
+ N_TRAIN_EVAL = 10
30
+ STD_FLOOR_FRAC = 0.05 # per-dim std floor = 5 % of the median std of the action vector
31
+
32
+ # task -> (source LeRobot v2.1 root, number of TRAINING episodes = fixed first N (None = all recorded), layout)
33
+ TASKS = {
34
+ "b6": (P / "b6-v5t7-ready-start-60ep-20261109/data/deliveries/g1/b6-v5t7-ready-start-20261109", 100, "g1"),
35
+ "basket": (P / "basket-current-dynamics-100-v21-b0ff522/data", None, "g1"),
36
+ "trolley": (P / "trolley-push-expert-v1-20261110/data/trolley_push", 100, "g1"),
37
+ "b7": (P / "b7-black-clothes-hamper-v1-1bb002a/data", 100, "g1"),
38
+ "b7green": (P / "b7-green-clothes-hamper-v1-ada288c/data", None, "g1"),
39
+ "a6": (P / "a6-door-pull-v1-cf3ee9b/data/door_pull", None, "g1"),
40
+ "a10v2": (P / "a10-trolley-push-v2-d3abb4c/data", None, "g1"),
41
+ "a1": (P / "a1-ground-object-pickup-v1-f47f07e/data", None, "g1"),
42
+ "c6": (P / "c6-bathroom-door-fetch-v1-3afba69/data", None, "g1"),
43
+ "a3": (P / "a3-a7-20261109/a3-fridge-open-expert-v1/780fcf1e4bd7db947a8c2d8f7b92e61f24f71b45", None, "g1"),
44
+ "a7": (P / "a3-a7-20261109/a7-cabinet-close-expert-v1/1935a98e8f55d4d1d2d1615ddb97c2679713595c", None, "g1"),
45
+ "a18": (P / "a18-h2-dataset-audit-8e956a10/dataset", None, "h2"),
46
+ "a17": (P / "a17-unscrew-bottle-v1-407e6e2/data", None, "h2"),
47
+ "a14": (P / "a14-unscrew-bulb-v1-b4390fc/data", None, "h2"),
48
+ # 2026-11-15: newer datasets (GR00T in-training eval needs a cache for every task it trains on)
49
+ "a10v3": (P / "a10-trolley-push-v3-6e410c5/data", None, "g1"),
50
+ "a7v2": (P / "a7-cabinet-close-v2-aecf070/data", None, "g1"),
51
+ "b1": (P / "b1-riceball-microwave-v1-36da298/data", None, "g1"),
52
+ "b7greenv2": (P / "b7-green-clothes-hamper-v2-c12757e/data", None, "g1"),
53
+ "b8": (P / "b8-table-wipe-v1-3b2e618/data", None, "g1"),
54
+ "basketv2": (P / "basket-trimv2-c4df4d4/data", None, "g1"),
55
+ "a14v2": (P / "a14-unscrew-bulb-v2-8411a6d/data", None, "h2p"), # action 82 = hb75 + SONIC planner 7
56
+ # 2026-11-15 evening: v6/v4 datasets (a3v3, a7v3 retired, not registered)
57
+ "b6v6": (P / "b6-pedal-bin-v6-ad2f5bf/data", None, "g1"), # 542 ep, all used (B6 first-100 rule is v5t7 only)
58
+ "b5": (P / "b5-chair-push-v1-b85b7e9/data", None, "g1"),
59
+ "a3v4": (P / "a3-fridge-open-v4-6393d4a/data", None, "g1"),
60
+ "a7v4": (P / "a7-cabinet-close-v4-90cc2b5/data", None, "g1"),
61
+ # 2026-11-16: B5 standing start (HF b5-chair-push-standing-start-expert-v1 @913f5a16, 100 ep; FastWAM b5ss)
62
+ "b5ss": (P / "b5-chair-push-standing-start-v1-913f5a1/data", None, "g1"),
63
+ # 2026-11-15 night: H2 cropped v2 (GR00T h32 relay item 71); head+chest only -> build_cache --cams head,chest
64
+ "a18cr2": (P / "a18-pour-water-cropped-v2-44cdd57/data", None, "h2"), # HF a18-pour-water-expert-cropped-v2 @44cdd571
65
+ "a17cr2": (P / "a17-unscrew-bottle-cropped-v2-3520b70/data", None, "h2"), # HF a17-unscrew-bottle-expert-cropped-v2 @3520b70f
66
+ }
67
+
68
+
69
+ def task_for_source(source):
70
+ """benchmark task whose recording root is <source> (groot-data/<view>/hb-dataset-receipt.json "source")"""
71
+ src = Path(source).resolve()
72
+ hits = [t for t, (root, _, _) in TASKS.items() if Path(root).resolve() == src]
73
+ return hits[0] if hits else None
74
+ G1_BODY = ["left_hip_pitch_joint", "left_hip_roll_joint", "left_hip_yaw_joint", "left_knee_joint",
75
+ "left_ankle_pitch_joint", "left_ankle_roll_joint", "right_hip_pitch_joint", "right_hip_roll_joint",
76
+ "right_hip_yaw_joint", "right_knee_joint", "right_ankle_pitch_joint", "right_ankle_roll_joint",
77
+ "waist_yaw_joint", "waist_roll_joint", "waist_pitch_joint", "left_shoulder_pitch_joint",
78
+ "left_shoulder_roll_joint", "left_shoulder_yaw_joint", "left_elbow_joint", "left_wrist_roll_joint",
79
+ "left_wrist_pitch_joint", "left_wrist_yaw_joint", "right_shoulder_pitch_joint",
80
+ "right_shoulder_roll_joint", "right_shoulder_yaw_joint", "right_elbow_joint", "right_wrist_roll_joint",
81
+ "right_wrist_pitch_joint", "right_wrist_yaw_joint"]
82
+ LAYOUTS = {
83
+ # state: body29 | inspire L6 | inspire R6 | projected_gravity3 ; action: motion_token64 | inspire L6 | R6 (same row)
84
+ "g1": dict(state_dim=44, action_dim=76, cams=("ego_view", "chest"),
85
+ groups={"motion_token": (0, 64), "hands": (64, 76)}),
86
+ # state: observation.state75 (legs12 waist3 arms14 head2 hands22+22) | gravity3 ; action: body_target31 | hands44
87
+ "h2": dict(state_dim=78, action_dim=75, cams=("head", "chest", "wrist"),
88
+ groups={"body_target": (0, 31), "hands": (31, 75)}),
89
+ # 2026-11-15 user: A14 v2 is trained on action82 = body_target31 | hands44 | action.planner7 (SONIC planner
90
+ # command); all 82 dims are scored (planner reported as its own group)
91
+ "h2p": dict(state_dim=78, action_dim=82, cams=("head", "chest"),
92
+ groups={"body_target": (0, 31), "hands": (31, 75), "planner": (75, 82)}),
93
+ }
94
+
95
+
96
+ def jl(path):
97
+ return [json.loads(x) for x in Path(path).read_text().splitlines() if x.strip()]
98
+
99
+
100
+ def layout(task):
101
+ return LAYOUTS[TASKS[task][2]]
102
+
103
+
104
+ def split_episodes(task, split, n_recorded):
105
+ _, n_train, _ = TASKS[task]
106
+ n_train = n_recorded if n_train is None else n_train
107
+ if split == "heldout":
108
+ return list(range(n_train, n_recorded))
109
+ if split == "train10":
110
+ return sorted({int(round(x)) for x in np.linspace(0, n_train - 1, N_TRAIN_EVAL)})
111
+ if split.startswith("ep:"): # explicit list, e.g. ep:100,101
112
+ return [int(x) for x in split[3:].split(",")]
113
+ raise ValueError(f"unknown split {split!r}")
114
+
115
+
116
+ def split_dir(task, split):
117
+ return CACHE / task / split
118
+
119
+
120
+ def load_meta(task, split):
121
+ return json.loads((split_dir(task, split) / "meta.json").read_text())
122
+
123
+
124
+ def load_stats(task):
125
+ z = np.load(CACHE / task / "stats.npz")
126
+ return {k: z[k] for k in z.files}
127
+
128
+
129
+ def norm_std(stats):
130
+ std = stats["action_std"].astype(np.float64)
131
+ return np.maximum(std, STD_FLOOR_FRAC * float(np.median(std)))
132
+
133
+
134
+ def iter_episodes(task, split, max_episodes=None):
135
+ meta = load_meta(task, split)
136
+ eps = meta["episodes"][: max_episodes or None]
137
+ for ep in eps:
138
+ with np.load(split_dir(task, split) / f"ep_{ep:06d}.npz") as z:
139
+ yield ep, {k: z[k] for k in z.files}
140
+
141
+
142
+ class Accumulator:
143
+ """Sums of squared / absolute errors; everything is computed in float64 over valid (row, dim) entries."""
144
+
145
+ def __init__(self, std, groups, horizon=HORIZON):
146
+ self.std = np.asarray(std, dtype=np.float64)
147
+ self.groups = groups
148
+ D = len(self.std)
149
+ self.sse_raw = np.zeros(D)
150
+ self.sae_raw = np.zeros(D)
151
+ self.sse_n = np.zeros(D)
152
+ self.rows = 0
153
+ self.step_sse_n = np.zeros(horizon)
154
+ self.step_rows = np.zeros(horizon)
155
+ self.per_episode = {}
156
+
157
+ def add(self, ep, pred, gt, valid):
158
+ pred = np.asarray(pred, dtype=np.float64)
159
+ gt = np.asarray(gt, dtype=np.float64)
160
+ v = np.asarray(valid, dtype=bool)
161
+ if pred.shape != gt.shape:
162
+ raise ValueError(f"pred {pred.shape} vs gt {gt.shape}")
163
+ if not np.isfinite(pred[v]).all():
164
+ raise FloatingPointError("non-finite prediction")
165
+ e = (pred - gt)[v]
166
+ en = e / self.std
167
+ self.sse_raw += (e ** 2).sum(0)
168
+ self.sae_raw += np.abs(e).sum(0)
169
+ self.sse_n += (en ** 2).sum(0)
170
+ self.rows += int(v.sum())
171
+ k = np.nonzero(v)[0]
172
+ self.step_sse_n[k] += (en ** 2).sum(1)
173
+ self.step_rows[k] += 1
174
+ s = self.per_episode.setdefault(int(ep), [0.0, 0])
175
+ s[0] += float((en ** 2).sum())
176
+ s[1] += int(v.sum()) * len(self.std)
177
+
178
+ def result(self):
179
+ D = len(self.std)
180
+ n = max(self.rows, 1)
181
+ out = {"rows": self.rows, "mse_raw": float(self.sse_raw.sum() / (n * D)),
182
+ "mae_raw": float(self.sae_raw.sum() / (n * D)), "nmse": float(self.sse_n.sum() / (n * D)),
183
+ "groups": {}, "nmse_by_step": (self.step_sse_n / np.maximum(self.step_rows, 1) / D).tolist(),
184
+ "nmse_by_dim": (self.sse_n / n).tolist()}
185
+ for g, (a, b) in self.groups.items():
186
+ out["groups"][g] = {"mse_raw": float(self.sse_raw[a:b].sum() / (n * (b - a))),
187
+ "nmse": float(self.sse_n[a:b].sum() / (n * (b - a)))}
188
+ pe = {ep: s / max(c, 1) for ep, (s, c) in sorted(self.per_episode.items())}
189
+ out["nmse_per_episode"] = pe
190
+ vals = np.array(list(pe.values()))
191
+ if len(vals) > 1: # bootstrap-free spread: std error over episodes
192
+ out["nmse_episode_sem"] = float(vals.std(ddof=1) / np.sqrt(len(vals)))
193
+ return out
194
+
195
+
196
+ def queries(T):
197
+ return list(range(0, T, STRIDE))
198
+
199
+
200
+ def gt_chunk(action, t, horizon=HORIZON):
201
+ T = len(action)
202
+ idx = np.arange(t, t + horizon)
203
+ valid = idx < T
204
+ return action[np.minimum(idx, T - 1)], valid
205
+
206
+
207
+ def run(adapter, task, split, out_path, max_episodes=None, max_queries=None, save_pred=True, log_every=50):
208
+ """Evaluate one adapter on one cached split; writes <out_path> (json) and <out_path>.pred.npz."""
209
+ meta = load_meta(task, split)
210
+ lay = LAYOUTS[meta["layout"]]
211
+ stats = load_stats(task)
212
+ acc = Accumulator(norm_std(stats), lay["groups"])
213
+ preds, keys = [], []
214
+ t0 = time.time()
215
+ infer_s = 0.0
216
+ nq = 0
217
+ for ep, z in iter_episodes(task, split, max_episodes):
218
+ state, action = z["state"], z["action"]
219
+ qts = list(z["query_t"])
220
+ for qi, t in enumerate(qts):
221
+ obs = {"episode": ep, "t": int(t), "T": len(action), "state": state[t], "prompt": meta["prompts"][str(int(z["task_index"]))],
222
+ "images": {c: z[f"img_{c}"][qi] for c in meta["cams"]},
223
+ "past_action": action[max(0, t - HORIZON):t],
224
+ "_gt_check": action[t:t + HORIZON]} # only for adapters' input-pipeline consistency checks
225
+ s = time.time()
226
+ pred = np.asarray(adapter.predict(obs), dtype=np.float64)
227
+ infer_s += time.time() - s
228
+ if pred.ndim != 2 or pred.shape[0] < HORIZON or pred.shape[1] != lay["action_dim"]:
229
+ raise ValueError(f"adapter returned {pred.shape}, need (>={HORIZON}, {lay['action_dim']})")
230
+ pred = pred[:HORIZON]
231
+ gt, valid = gt_chunk(action, t)
232
+ acc.add(ep, pred, gt, valid)
233
+ if save_pred:
234
+ preds.append(pred.astype(np.float32))
235
+ keys.append((ep, int(t)))
236
+ nq += 1
237
+ if log_every and nq % log_every == 0:
238
+ print(f"[eval] {task}/{split} {nq} queries, running nMSE {acc.result()['nmse']:.4f}, "
239
+ f"{infer_s / nq:.3f} s/query", flush=True)
240
+ if max_queries and nq >= max_queries:
241
+ break
242
+ if max_queries and nq >= max_queries:
243
+ break
244
+ res = acc.result()
245
+ res.update(task=task, split=split, layout=meta["layout"], episodes=sorted(acc.per_episode), queries=nq,
246
+ horizon=HORIZON, stride=STRIDE, std_floor_frac=STD_FLOOR_FRAC, wall_s=round(time.time() - t0, 1),
247
+ infer_s_per_query=round(infer_s / max(nq, 1), 4), adapter=adapter.info(),
248
+ baselines=meta.get("baselines", {}), cache_created=meta.get("created"),
249
+ partial=bool(max_episodes or max_queries), finished_utc=time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()))
250
+ out_path = Path(out_path)
251
+ out_path.parent.mkdir(parents=True, exist_ok=True)
252
+ tmp = out_path.with_suffix(".tmp")
253
+ tmp.write_text(json.dumps(res, indent=1))
254
+ tmp.replace(out_path)
255
+ if save_pred and preds:
256
+ np.savez_compressed(str(out_path) + ".pred.npz", pred=np.stack(preds).astype(np.float16),
257
+ keys=np.asarray(keys, dtype=np.int64))
258
+ return res
a10-trolley-push-v3/b512/step-004000/code/hb_inloop_core.py ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared machinery of the in-training open-loop action MSE (Psi-Zero, Delta Flow; GR00T has its own tested copy in
2
+ hb_groot/hb_inloop_eval.py with the same protocol).
3
+
4
+ InLoop(model_name, task, split, out_jsonl, prepare, predict):
5
+ prepare(queries) -> optional per-model setup on this rank's queries (first eval only, inside the RNG fork)
6
+ predict(batch, seed) -> np.ndarray (B, >=16, >=Da) in raw action units; the first 16 steps and the first Da dims
7
+ (Da = benchmark action dim of the layout) are scored.
8
+ InLoop.evaluate(step, model): all train/eval modes of model.modules() and every RNG state (torch CPU + this CUDA device,
9
+ numpy, python) are restored afterwards; partial sums are all-reduced once (error flag included, so a failure on one
10
+ rank cannot leave the others waiting); rank 0 appends one json line per eval. Any failure disables later evals.
11
+ Protocol and metrics = hb_eval_common (post-hoc eval): queries every 16 frames, nMSE with the training-frame std.
12
+ """
13
+ import json
14
+ import os
15
+ import random
16
+ import sys
17
+ import time
18
+ import traceback
19
+ from pathlib import Path
20
+
21
+ import numpy as np
22
+ import torch
23
+
24
+ HERE = Path(__file__).resolve().parent
25
+ if str(HERE) not in sys.path:
26
+ sys.path.insert(0, str(HERE))
27
+ import hb_eval_common as E # noqa: E402
28
+
29
+ EVERY = int(os.environ.get("HB_INLOOP_EVERY", "250"))
30
+ BATCH = int(os.environ.get("HB_INLOOP_BATCH", "8"))
31
+ MAX_Q = int(os.environ.get("HB_INLOOP_MAX_QUERIES", "0"))
32
+ SEED = 1234
33
+
34
+
35
+ def dist_info():
36
+ import torch.distributed as dist
37
+ if dist.is_available() and dist.is_initialized():
38
+ return dist.get_rank(), dist.get_world_size()
39
+ return int(os.environ.get("RANK", "0")), int(os.environ.get("WORLD_SIZE", "1"))
40
+
41
+
42
+ def pick_split(task):
43
+ split = os.environ.get("HB_INLOOP_SPLIT")
44
+ if not split:
45
+ split = "heldout" if (E.split_dir(task, "heldout") / "meta.json").exists() else "train10"
46
+ if not (E.split_dir(task, split) / "meta.json").exists():
47
+ raise FileNotFoundError(f"eval cache {task}/{split} missing (build_cache.py {task} {split})")
48
+ return split
49
+
50
+
51
+ class InLoop:
52
+ def __init__(self, model_name, task, split, out_jsonl, predict, prepare=None, cams=None, info=None):
53
+ self.model_name, self.task, self.split = model_name, task, split
54
+ self.out = Path(out_jsonl)
55
+ self.predict, self.prepare = predict, prepare
56
+ self.cams = cams
57
+ self.info = info or {}
58
+ self.disabled = False
59
+ self.ready = False
60
+ self.done_steps = set()
61
+
62
+ def say(self, *a):
63
+ if dist_info()[0] == 0:
64
+ print("HB_INLOOP", *a, flush=True)
65
+
66
+ def _setup(self):
67
+ rank, world = dist_info()
68
+ meta = E.load_meta(self.task, self.split)
69
+ self.meta, self.lay = meta, E.LAYOUTS[meta["layout"]]
70
+ self.std = E.norm_std(E.load_stats(self.task))
71
+ cams = self.cams or meta["cams"]
72
+ miss = [c for c in cams if c not in meta["cams"]]
73
+ if miss:
74
+ raise KeyError(f"cameras {miss} not in the eval cache {meta['cams']}")
75
+ allq = []
76
+ for ep in meta["episodes"]:
77
+ with np.load(E.split_dir(self.task, self.split) / f"ep_{ep:06d}.npz") as z:
78
+ allq += [(ep, qi, int(t)) for qi, t in enumerate(z["query_t"])]
79
+ if MAX_Q:
80
+ allq = allq[:MAX_Q]
81
+ self.n_total = len(allq)
82
+ mine = [q for i, q in enumerate(allq) if i % world == rank]
83
+ self.eps = list(meta["episodes"])
84
+ by_ep = {}
85
+ for ep, qi, t in mine:
86
+ by_ep.setdefault(ep, []).append((qi, t))
87
+ self.q = []
88
+ for ep, lst in by_ep.items():
89
+ with np.load(E.split_dir(self.task, self.split) / f"ep_{ep:06d}.npz") as z:
90
+ state, action = z["state"], z["action"]
91
+ prompt = meta["prompts"][str(int(z["task_index"]))]
92
+ imgs = {c: z[f"img_{c}"] for c in cams}
93
+ for qi, t in lst:
94
+ gt, valid = E.gt_chunk(action, t)
95
+ self.q.append(dict(episode=int(ep), t=int(t), T=len(action), state=state[t].copy(), prompt=prompt,
96
+ images={c: imgs[c][qi].copy() for c in cams}, gt=gt, valid=valid,
97
+ past_action=action[max(0, t - E.HORIZON):t].copy()))
98
+ if self.prepare:
99
+ self.prepare(self.q)
100
+ self.ready = True
101
+ self.say(f"{self.model_name} ready: task {self.task} split {self.split} queries {self.n_total} "
102
+ f"(rank {rank}/{world}: {len(self.q)}), every {EVERY} steps, batch {BATCH}, cams {cams}")
103
+
104
+ def evaluate(self, step, model):
105
+ if self.disabled or step in self.done_steps:
106
+ return
107
+ self.done_steps.add(step)
108
+ rank, world = dist_info()
109
+ t0 = time.time()
110
+ err, msg = 0.0, ""
111
+ acc, nq, infer = None, 0, 0.0
112
+ modes = [(m, m.training) for m in model.modules()]
113
+ dev = torch.cuda.current_device() if torch.cuda.is_available() else None
114
+ np_state, py_state = np.random.get_state(), random.getstate()
115
+ try:
116
+ with torch.random.fork_rng(devices=[dev] if dev is not None else []):
117
+ if not self.ready:
118
+ self._setup()
119
+ D = self.lay["action_dim"]
120
+ model.eval()
121
+ acc = E.Accumulator(self.std, self.lay["groups"])
122
+ for bi in range(0, len(self.q), BATCH):
123
+ batch = self.q[bi:bi + BATCH]
124
+ seed = SEED + 1000 * rank + bi
125
+ torch.default_generator.manual_seed(seed)
126
+ if dev is not None:
127
+ torch.cuda.manual_seed(seed)
128
+ s = time.time()
129
+ with torch.no_grad():
130
+ pred = np.asarray(self.predict(batch, seed), dtype=np.float64)
131
+ infer += time.time() - s
132
+ if pred.ndim != 3 or pred.shape[0] != len(batch) or pred.shape[1] < E.HORIZON or pred.shape[2] < D:
133
+ raise ValueError(f"prediction {pred.shape}, need ({len(batch)}, >={E.HORIZON}, >={D})")
134
+ for q, p in zip(batch, pred):
135
+ acc.add(q["episode"], p[:E.HORIZON, :D], q["gt"], q["valid"])
136
+ nq += 1
137
+ except Exception as e: # noqa: BLE001 - never stop training
138
+ err, msg = 1.0, f"{type(e).__name__}: {e}"
139
+ print(f"HB_INLOOP {self.model_name} rank {rank} step {step} FAILED: {msg}\n{traceback.format_exc()}",
140
+ file=sys.stderr, flush=True)
141
+ finally:
142
+ for m, tr in modes:
143
+ m.training = tr
144
+ np.random.set_state(np_state)
145
+ random.setstate(py_state)
146
+ D = self.lay["action_dim"] if self.ready else 0
147
+ H = E.HORIZON
148
+ eps = self.eps if self.ready else []
149
+ nE = len(eps)
150
+ vec = np.zeros(3 * D + 1 + 2 * H + 2 * nE + 3)
151
+ if acc is not None and not err:
152
+ o = 0
153
+ vec[o:o + D] = acc.sse_raw; o += D
154
+ vec[o:o + D] = acc.sae_raw; o += D
155
+ vec[o:o + D] = acc.sse_n; o += D
156
+ vec[o] = acc.rows; o += 1
157
+ vec[o:o + H] = acc.step_sse_n; o += H
158
+ vec[o:o + H] = acc.step_rows; o += H
159
+ for j, ep in enumerate(eps):
160
+ s_, c_ = acc.per_episode.get(int(ep), (0.0, 0))
161
+ vec[o + j], vec[o + nE + j] = s_, c_
162
+ o += 2 * nE
163
+ vec[o], vec[o + 1] = nq, infer
164
+ vec[-1] = err
165
+ tot = self._allreduce(vec)
166
+ if tot is None or tot[-1] > 0 or not self.ready:
167
+ self.disabled = True
168
+ nfail = None if tot is None else int(tot[-1])
169
+ self._write({"step": step, "error": msg or "failed on another rank / collective failed",
170
+ "ranks_failed": nfail})
171
+ self.say(f"{self.model_name} step {step}: eval failed ({nfail} rank(s)) -> in-training eval disabled: {msg}")
172
+ return
173
+ o = 0
174
+ acc = E.Accumulator(self.std, self.lay["groups"])
175
+ acc.sse_raw = tot[o:o + D]; o += D
176
+ acc.sae_raw = tot[o:o + D]; o += D
177
+ acc.sse_n = tot[o:o + D]; o += D
178
+ acc.rows = int(round(tot[o])); o += 1
179
+ acc.step_sse_n = tot[o:o + H]; o += H
180
+ acc.step_rows = tot[o:o + H]; o += H
181
+ acc.per_episode = {int(ep): [float(tot[o + j]), int(round(tot[o + nE + j]))]
182
+ for j, ep in enumerate(eps) if tot[o + nE + j] > 0}
183
+ o += 2 * nE
184
+ n_q, infer_sum = int(round(tot[o])), float(tot[o + 1])
185
+ res = acc.result()
186
+ res.pop("nmse_by_dim", None)
187
+ rec = {"step": step, "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "model": self.model_name,
188
+ "task": self.task, "split": self.split, "queries": n_q, "ranks": world,
189
+ "wall_s": round(time.time() - t0, 1), "infer_s_per_query": round(infer_sum / max(n_q, 1), 4),
190
+ "seed": SEED, **self.info, **res}
191
+ self._write(rec)
192
+ g = " ".join(f"{k} {v['nmse']:.4f}" for k, v in res["groups"].items())
193
+ self.say(f"{self.model_name} step {step}: {self.task}/{self.split} nMSE {res['nmse']:.4f} ({g}) on {n_q} "
194
+ f"queries, {rec['wall_s']} s")
195
+
196
+ @staticmethod
197
+ def _allreduce(vec):
198
+ import torch.distributed as dist
199
+ if not (dist.is_available() and dist.is_initialized()) or dist.get_world_size() == 1:
200
+ return vec
201
+ try:
202
+ dev = "cuda" if dist.get_backend() == "nccl" else "cpu"
203
+ n = torch.tensor([float(len(vec))], dtype=torch.float64, device=dev)
204
+ mx, mn = n.clone(), n.clone()
205
+ dist.all_reduce(mx, op=dist.ReduceOp.MAX)
206
+ dist.all_reduce(mn, op=dist.ReduceOp.MIN)
207
+ if mx.item() != mn.item():
208
+ return None
209
+ t = torch.from_numpy(vec).to(device=dev, dtype=torch.float64)
210
+ dist.all_reduce(t)
211
+ return t.cpu().numpy()
212
+ except Exception as e: # noqa: BLE001
213
+ print(f"HB_INLOOP all_reduce failed: {e!r}", file=sys.stderr, flush=True)
214
+ return None
215
+
216
+ def _write(self, rec):
217
+ if dist_info()[0] != 0:
218
+ return
219
+ try:
220
+ self.out.parent.mkdir(parents=True, exist_ok=True)
221
+ with open(self.out, "a") as f:
222
+ f.write(json.dumps(rec) + "\n")
223
+ except Exception as e: # noqa: BLE001
224
+ print(f"HB_INLOOP write failed: {e!r}", flush=True)
225
+
226
+
227
+ class TempAttrs:
228
+ """set attributes on an object for the duration of a block, then restore (or delete) them"""
229
+ _MISSING = object()
230
+
231
+ def __init__(self, obj, **kw):
232
+ self.obj, self.kw, self.old = obj, kw, {}
233
+
234
+ def __enter__(self):
235
+ for k, v in self.kw.items():
236
+ self.old[k] = self.obj.__dict__.get(k, self._MISSING)
237
+ setattr(self.obj, k, v)
238
+ return self.obj
239
+
240
+ def __exit__(self, *exc):
241
+ for k, v in self.old.items():
242
+ if v is self._MISSING:
243
+ try:
244
+ delattr(self.obj, k)
245
+ except AttributeError:
246
+ pass
247
+ else:
248
+ setattr(self.obj, k, v)
249
+ return False
a10-trolley-push-v3/b512/step-004000/code/hb_inloop_fastwam.py CHANGED
@@ -94,9 +94,13 @@ def install():
94
 
95
  def __init__(self, *a, **kw):
96
  orig_init(self, *a, **kw)
97
- if self.val_dataset is None and int(self.eval_every) == 0:
 
 
 
98
  self.eval_every = C.EVERY
99
- self.val_dataset = _Marker()
 
100
  self._hb_inloop_on = True
101
  else: # a native eval is configured: leave it alone
102
  self._hb_inloop_on = False
 
94
 
95
  def __init__(self, *a, **kw):
96
  orig_init(self, *a, **kw)
97
+ # native eval off (eval_every 0 on our command line). NB runtime.build_datasets sets val_ds = train_ds when
98
+ # there is no data.val, so val_dataset is never None here (11-16 smoke: the old "val_dataset is None" test
99
+ # silently left the in-loop eval off).
100
+ if int(self.eval_every) == 0:
101
  self.eval_every = C.EVERY
102
+ if self.val_dataset is None:
103
+ self.val_dataset = _Marker()
104
  self._hb_inloop_on = True
105
  else: # a native eval is configured: leave it alone
106
  self._hb_inloop_on = False
a10-trolley-push-v3/b512/step-004000/code/test_fastwam_inputs.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """CPU check (no model): the FastWAM adapter's inputs built from the model-agnostic eval cache == the inputs our FastWAM
2
+ training dataset (RobotVideoDataset of the run's config, no HB augmentation) builds for the same frame.
3
+ python test_fastwam_inputs.py <task> <run out dir> [n_queries]"""
4
+ import json
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ import numpy as np
10
+
11
+ HERE = Path(__file__).resolve().parent
12
+ sys.path.insert(0, str(HERE))
13
+ sys.path.insert(0, str(HERE / "adapters"))
14
+ import hb_eval_common as E # noqa: E402
15
+ import ad_fastwam as A # noqa: E402
16
+
17
+ task, out = sys.argv[1], Path(sys.argv[2])
18
+ nq = int(sys.argv[3]) if len(sys.argv) > 3 else 3
19
+ A.setup_env()
20
+ import torch # noqa: E402
21
+ from omegaconf import OmegaConf # noqa: E402
22
+ import fastwam.runtime as native # noqa: E402
23
+ from fastwam.utils import misc # noqa: E402
24
+
25
+ cfg = OmegaConf.load(out / "config.yaml")
26
+ inp = A.Inputs(cfg, out / "dataset_stats.json")
27
+ misc.register_work_dir("/tmp/hbfw-inputs-check")
28
+ OmegaConf.update(cfg, "data.train.pretrained_norm_stats", str(out / "dataset_stats.json"), merge=False, force_add=True)
29
+ tr, _ = native.build_datasets(cfg.data)
30
+ ddir = Path(cfg.data.train.dataset_dirs[0])
31
+ lens = [json.loads(l)["length"] for l in (ddir / "meta/episodes.jsonl").read_text().splitlines() if l.strip()]
32
+ meta = E.load_meta(task, "train10")
33
+ split = "train10"
34
+ worst = {}
35
+ done = 0
36
+ for ep, z in E.iter_episodes(task, split, None):
37
+ base = int(sum(lens[:ep]))
38
+ for qi, t in enumerate(list(z["query_t"])[1:1 + nq], start=1):
39
+ t = int(t)
40
+ s = tr[base + t]
41
+ obs = {"images": {c: z[f"img_{c}"][qi] for c in meta["cams"]}, "state": z["state"][t],
42
+ "prompt": meta["prompts"][str(int(z["task_index"]))]}
43
+ img = inp.image(obs["images"])[0]
44
+ d_img = float((img - s["video"][:, 0].float()).abs().max())
45
+ pr = inp.proprio(obs["state"])[0]
46
+ d_pr = float((pr - s["proprio"][0].float()).abs().max())
47
+ ctx, mask = inp.context(obs["prompt"])
48
+ d_ctx = float((ctx.float() - s["context"].float()).abs().max())
49
+ d_mask = int((mask != s["context_mask"].bool()).sum())
50
+ gt = z["action"][t:t + 16]
51
+ a = inp.denorm(s["action"][:16])
52
+ d_act = float(np.abs(a[:len(gt)] - gt).max())
53
+ row = dict(ep=ep, t=t, idx=base + t, img=d_img, proprio=d_pr, ctx=d_ctx, mask=d_mask, act_denorm_vs_cache=d_act,
54
+ prompt_same=s["prompt"] == inp.DEFAULT_PROMPT.format(task=obs["prompt"]))
55
+ print("CHECK", json.dumps(row), flush=True)
56
+ for k in ("img", "proprio", "ctx", "act_denorm_vs_cache"):
57
+ worst[k] = max(worst.get(k, 0.0), row[k])
58
+ done += 1
59
+ if done >= 2 * nq:
60
+ break
61
+ print("WORST", json.dumps(worst))
a10-trolley-push-v3/b512/step-004000/protocol.json CHANGED
@@ -36,19 +36,23 @@
36
  "batch_selection": "largest per-GPU batch that fits on A800 80 GB: 16 trains at ~58 GB, 32 runs out of memory (batch_benchmark/)",
37
  "normalization": "dataset_stats.json (FastWAM min / max statistics of this task)",
38
  "config": "training_config.yaml (resolved FastWAM config; absolute paths refer to the training NAS), model_config.yaml (the model part)",
39
- "inference": "FastWAM: build the model from model_config.yaml, load model.pt (DiT state dict), the normalizer from dataset_stats.json and the prompt embedding from text_embeddings/; code/hb_fastwam_convert.py documents the state / action layout of the benchmark interface",
40
  "training_records_included": true,
41
  "resume_state_included": false,
42
  "files": {
43
  "batch_benchmark/chosen.json": 210,
44
  "batch_benchmark/summary.txt": 127,
 
45
  "code/fastwam_prep.sh": 3634,
46
  "code/fastwam_task.sh": 3719,
47
  "code/hb_aug_v2.py": 7475,
 
48
  "code/hb_fastwam_aug.py": 3345,
49
  "code/hb_fastwam_convert.py": 7101,
50
  "code/hb_fastwam_train.py": 5570,
51
- "code/hb_inloop_fastwam.py": 5137,
 
 
52
  "complete.json": 660,
53
  "dataset_meta/hb_fastwam_interface.json": 338,
54
  "dataset_meta/info.json": 11456,
@@ -63,12 +67,13 @@
63
  "model.pt": 12042313337,
64
  "model_config.yaml": 1350,
65
  "text_embeddings/012c1778878f57dcfd1251771b96657ba3238ab1ec1875c0fede3b26ef6ecb86.t5_len128.wan22ti2v5b.pt": 12587613,
66
- "text_embeddings/2b20df4838f4dbf93ca5e7c2ea5ad0e903bc5b844775b6917e1a61ca1eb8d191.t5_len128.wan22ti2v5b.pt": 12587613,
67
  "text_embeddings/31e0f5d5a4ce6c1e4fbf5beb2283e83b63b79b777b162019e79997769ffd1013.t5_len128.wan22ti2v5b.pt": 12587613,
68
  "text_embeddings/3c22d73f4422b8ecdb2085a7cde039d5565ab26cdb312fd41c802987c2d19d1b.t5_len128.wan22ti2v5b.pt": 12587613,
69
  "text_embeddings/52510cc822aba2c8234a8da323bd0091b23a933cb8232d2fe82bc8085f47cd71.t5_len128.wan22ti2v5b.pt": 12587613,
70
  "text_embeddings/5a20e43a27564ea8978edc7394a96e0c1295e82528d59dba0c4169f3bba9a630.t5_len128.wan22ti2v5b.pt": 12587613,
71
  "text_embeddings/7649f0a497710702f2a47162bf5c56e45fc1ca53b81f935c9a048b61c231f130.t5_len128.wan22ti2v5b.pt": 12587613,
 
72
  "text_embeddings/d82ae9ce680248c4bb47e139992293855384c2e769939796b7d59b722ba7a37a.t5_len128.wan22ti2v5b.pt": 12587613,
73
  "text_embeddings/db6124d444ef41566d73455e3547ac6a113fae4c3e6c94d5f79b2a8be8298814.t5_len128.wan22ti2v5b.pt": 12587613,
74
  "text_embeddings/e0bf8801f26f15c00e43f58ba954054499fa70c490444b8f01c0b224db95c905.t5_len128.wan22ti2v5b.pt": 12587613,
 
36
  "batch_selection": "largest per-GPU batch that fits on A800 80 GB: 16 trains at ~58 GB, 32 runs out of memory (batch_benchmark/)",
37
  "normalization": "dataset_stats.json (FastWAM min / max statistics of this task)",
38
  "config": "training_config.yaml (resolved FastWAM config; absolute paths refer to the training NAS), model_config.yaml (the model part)",
39
+ "inference": "FastWAM: build the model from model_config.yaml, load model.pt (DiT state dict), the normalizer from dataset_stats.json and the prompt embedding from text_embeddings/; code/hb_fastwam_convert.py documents the state / action layout of the benchmark interface; code/ad_fastwam.py is the inference adapter of our evaluation (action-only FastWAM.infer_action, 10 denoising steps, seed 42; its default paths refer to the training NAS)",
40
  "training_records_included": true,
41
  "resume_state_included": false,
42
  "files": {
43
  "batch_benchmark/chosen.json": 210,
44
  "batch_benchmark/summary.txt": 127,
45
+ "code/ad_fastwam.py": 8413,
46
  "code/fastwam_prep.sh": 3634,
47
  "code/fastwam_task.sh": 3719,
48
  "code/hb_aug_v2.py": 7475,
49
+ "code/hb_eval_common.py": 13273,
50
  "code/hb_fastwam_aug.py": 3345,
51
  "code/hb_fastwam_convert.py": 7101,
52
  "code/hb_fastwam_train.py": 5570,
53
+ "code/hb_inloop_core.py": 11206,
54
+ "code/hb_inloop_fastwam.py": 5431,
55
+ "code/test_fastwam_inputs.py": 2724,
56
  "complete.json": 660,
57
  "dataset_meta/hb_fastwam_interface.json": 338,
58
  "dataset_meta/info.json": 11456,
 
67
  "model.pt": 12042313337,
68
  "model_config.yaml": 1350,
69
  "text_embeddings/012c1778878f57dcfd1251771b96657ba3238ab1ec1875c0fede3b26ef6ecb86.t5_len128.wan22ti2v5b.pt": 12587613,
70
+ "text_embeddings/2b20df4838f4dbf93ca5e7c2ea5ad0e903bc5b844775b6917e1a61ca1eb8d191.t5_len128.wan22ti2v5b.pt": 1051869,
71
  "text_embeddings/31e0f5d5a4ce6c1e4fbf5beb2283e83b63b79b777b162019e79997769ffd1013.t5_len128.wan22ti2v5b.pt": 12587613,
72
  "text_embeddings/3c22d73f4422b8ecdb2085a7cde039d5565ab26cdb312fd41c802987c2d19d1b.t5_len128.wan22ti2v5b.pt": 12587613,
73
  "text_embeddings/52510cc822aba2c8234a8da323bd0091b23a933cb8232d2fe82bc8085f47cd71.t5_len128.wan22ti2v5b.pt": 12587613,
74
  "text_embeddings/5a20e43a27564ea8978edc7394a96e0c1295e82528d59dba0c4169f3bba9a630.t5_len128.wan22ti2v5b.pt": 12587613,
75
  "text_embeddings/7649f0a497710702f2a47162bf5c56e45fc1ca53b81f935c9a048b61c231f130.t5_len128.wan22ti2v5b.pt": 12587613,
76
+ "text_embeddings/cd0ca5d7666fa68fe2141dfac894ceea404ab7cf2a88b8617a489f124dfdfdf2.t5_len128.wan22ti2v5b.pt": 1051869,
77
  "text_embeddings/d82ae9ce680248c4bb47e139992293855384c2e769939796b7d59b722ba7a37a.t5_len128.wan22ti2v5b.pt": 12587613,
78
  "text_embeddings/db6124d444ef41566d73455e3547ac6a113fae4c3e6c94d5f79b2a8be8298814.t5_len128.wan22ti2v5b.pt": 12587613,
79
  "text_embeddings/e0bf8801f26f15c00e43f58ba954054499fa70c490444b8f01c0b224db95c905.t5_len128.wan22ti2v5b.pt": 12587613,