Download openwam_v3/code/openwam_mmb.patch from prlq/mobilemanipbench-data: direct link, hf CLI and curl.
- Browser
- Download file 118 kB
-
https://huggingface.co/datasets/prlq/mobilemanipbench-data/resolve/main/openwam_v3/code/openwam_mmb.patch
- Command line
-
hf download hf://datasets/prlq/mobilemanipbench-data/openwam_v3/code/openwam_mmb.patch
-
curl -L -o openwam_mmb.patch https://huggingface.co/datasets/prlq/mobilemanipbench-data/resolve/main/openwam_v3/code/openwam_mmb.patch
118 kB
diff --git a/configs/dataloader/mmb.yaml b/configs/dataloader/mmb.yaml
new file mode 100644
index 0000000..e495c06
--- /dev/null
+++ b/configs/dataloader/mmb.yaml
@@ -0,0 +1,23 @@
+type: mmb
+
+# MobileManipBench (prlq/mobilemanipbench-data @356ec43), merged to one LeRobot v2.1
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_ow
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_canon.yaml b/configs/dataloader/mmb_canon.yaml
new file mode 100644
index 0000000..baa6507
--- /dev/null
+++ b/configs/dataloader/mmb_canon.yaml
@@ -0,0 +1,23 @@
+type: mmb_canon
+
+# MobileManipBench, canonical action protocol v2 (openwam/dataloader/mmb_canon.py): chunk-start base-frame EEF delta.
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_ow
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_final.yaml b/configs/dataloader/mmb_final.yaml
new file mode 100644
index 0000000..c33301b
--- /dev/null
+++ b/configs/dataloader/mmb_final.yaml
@@ -0,0 +1,23 @@
+type: mmb_final
+
+# MobileManipBench, final canonical definition (openwam/dataloader/mmb_final.py; shared convert_merge.py output per robot).
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_hf
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_v4.yaml b/configs/dataloader/mmb_v4.yaml
new file mode 100644
index 0000000..2a743c6
--- /dev/null
+++ b/configs/dataloader/mmb_v4.yaml
@@ -0,0 +1,23 @@
+type: mmb_v4
+
+# MobileManipBench, final definition 11-14 (openwam/dataloader/mmb_v4.py; shared convert_merge.py @ 8d0b031 output per robot).
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_v4
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max; stats from the shared file (pooled base + EEF xyz, rot6d / gripper identity)
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/openwam/dataloader/mmb.py b/openwam/dataloader/mmb.py
new file mode 100644
index 0000000..2ca8398
--- /dev/null
+++ b/openwam/dataloader/mmb.py
@@ -0,0 +1,433 @@
+"""MobileManipBench (``prlq/mobilemanipbench-data``) reader for OpenWAM-alpha fine-tuning.
+
+Input: one merged LeRobot v2.1 dataset per robot (``<dataset_dir>/<robot>/``,
+per-episode parquet + mp4, 25 fps, cameras ``observation.images.head`` /
+``observation.images.wrist``). Three single-arm mobile manipulators:
+
+ * ``go2_arm`` action 12-D: ``base_action_0..3`` + ``eef0`` xyz + quat(wxyz) + gripper
+ * ``sawyer_umi`` action 11-D: base ``x, y, yaw`` + ``frame0`` xyz + quat(wxyz) + gripper
+ * ``stretch3`` action 11-D: base ``x, y, yaw`` + ``arm_action_0..6`` (xyz + quat(wxyz)) + gripper
+
+The arm action is an absolute end-effector pose target in the same world frame
+as ``observation.eef_pose`` (xyz + quat wxyz), which is the proprio source.
+The base action is a velocity command; there is no measured base velocity, so
+the proprio base slots are masked. The gripper command is ``0 = open,
+1 = closed`` and becomes the alpha convention ``+1 = open, -1 = closed``. The
+state finger joints use different conventions per robot, so the proprio
+gripper slot is masked.
+
+Raw vector (both streams): ``[xyz3, rot6d6, gripper1, base...]`` scattered to
+the alpha 80-D layout as single-arm slots ``0:10`` (as LIBERO / DROID) and the
+mobile-base slots ``68`` forward, ``69`` lateral, ``70`` yaw (as AgiBotWorld),
+``71`` go2's fourth base command. Base dims that are constant over a robot's
+data (stretch3 lateral) are masked.
+
+Normalization is per robot, min-max, with separate action and proprio stats
+fitted on the whole dataset; rot6d and gripper stats are pinned to ``[-1, 1]``
+(identity), as the alpha contract requires. Stats are built once by
+``build_mmb_stats`` (``meta/mmb_normalization_stats.npy`` per robot).
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_normalization_stats.npy"
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def raw_action(action: np.ndarray, layout: dict) -> np.ndarray:
+ """``(T, A)`` native action -> ``(T, 10 + n_base)`` raw ``[xyz, rot6d, gripper(+1 open), base]``."""
+ a = np.asarray(action, dtype=np.float32)
+ pose = a[:, layout["pose"]]
+ grip = 1.0 - 2.0 * a[:, layout["gripper"] : layout["gripper"] + 1]
+ return np.concatenate([pose[:, :3], _quat_wxyz_to_rot6d(pose[:, 3:7]), grip, a[:, layout["base"]]], axis=-1)
+
+
+def raw_proprio(eef_pose: np.ndarray, n_base: int) -> np.ndarray:
+ """``(T, 7)`` measured EEF pose -> raw vector; gripper and base are zero (masked)."""
+ e = np.asarray(eef_pose, dtype=np.float32)
+ out = np.zeros((e.shape[0], ARM_DIM + n_base), dtype=np.float32)
+ out[:, :3] = e[:, :3]
+ out[:, ROT6D] = _quat_wxyz_to_rot6d(e[:, 3:7])
+ return out
+
+
+def _min_max_stats(arr: np.ndarray) -> dict:
+ arr = np.asarray(arr, dtype=np.float64)
+ st = {"min": arr.min(0), "max": arr.max(0), "mean": arr.mean(0), "std": arr.std(0),
+ "q01": np.quantile(arr, 0.01, axis=0), "q99": np.quantile(arr, 0.99, axis=0)}
+ for k in st: # rot6d + gripper: identity under min-max
+ st[k][ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ st[k][GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+def build_mmb_stats(robot_dir: str, workers: int = 32) -> dict:
+ """Scan every episode of one robot and write ``meta/mmb_normalization_stats.npy``."""
+ from concurrent.futures import ProcessPoolExecutor
+
+ robot_dir = Path(robot_dir)
+ info = json.loads((robot_dir / "meta" / "info.json").read_text())
+ layout = robot_layout(info)
+ paths = sorted(robot_dir.glob("data/chunk-*/episode_*.parquet"))
+ with ProcessPoolExecutor(workers) as ex:
+ parts = list(ex.map(_scan_episode, [(str(p), layout) for p in paths], chunksize=8))
+ act = np.concatenate([p[0] for p in parts])
+ st = np.concatenate([p[1] for p in parts])
+ n_base = len(layout["base"])
+ action_stats = _min_max_stats(act)
+ proprio_stats = _min_max_stats(st)
+ rng = action_stats["max"] - action_stats["min"]
+ action_valid = np.ones(ARM_DIM + n_base, dtype=bool)
+ action_valid[ARM_DIM:] = rng[ARM_DIM:] > CONST_EPS
+ proprio_valid = np.zeros(ARM_DIM + n_base, dtype=bool)
+ proprio_valid[:GRIPPER] = True # xyz + rot6d; gripper and base masked
+ payload = {
+ "robot": robot_dir.name,
+ "action_names": info["features"]["action"]["names"],
+ "layout": layout,
+ "eef": action_stats,
+ "eef_state": proprio_stats,
+ "action_valid": action_valid,
+ "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(n_base),
+ "num_timesteps": int(act.shape[0]),
+ "gripper_convention": "minus1_closed_plus1_open (native 0=open,1=closed -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def _scan_episode(args):
+ path, layout = args
+ df = pq.read_table(path, columns=["action", "observation.eef_pose"]).to_pandas()
+ a = raw_action(np.stack(df["action"].to_numpy()), layout)
+ s = raw_proprio(np.stack(df["observation.eef_pose"].to_numpy()), len(layout["base"]))
+ return a, s
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBRobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples."""
+
+ DATASET_NAME = "MMB"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+ self._layout = robot_layout(info)
+ self._n_base = len(self._layout["base"])
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats["layout"] != self._layout:
+ raise MMBDataError(f"{self._robot}: stats layout {self._stats['layout']} != data {self._layout}")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(self._n_base), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 2
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("action", "observation.eef_pose"))
+ frame = table.slice(offset, n_raw).to_pandas()
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(n_raw, T)
+ raw_a = raw_action(np.stack(frame["action"].to_numpy()[:n_valid]), self._layout)
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = raw_proprio(np.stack(frame["observation.eef_pose"].to_numpy()[:1]), self._n_base)
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBDataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBRobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBDataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBRobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBDataset", "MMBRobotDataset", "build_mmb_stats", "raw_action", "raw_proprio"]
diff --git a/openwam/dataloader/mmb_canon.py b/openwam/dataloader/mmb_canon.py
new file mode 100644
index 0000000..2762a23
--- /dev/null
+++ b/openwam/dataloader/mmb_canon.py
@@ -0,0 +1,479 @@
+"""MobileManipBench reader for OpenWAM-alpha with the canonical action protocol v2.
+
+Same data, cameras, windows and alpha 80-D contract as ``mmb.py``; only the action / proprio definition differs:
+
+ canonical 12D (shared numpy module ``mmb_canonical_action``, identical to the pi0.5 / GR00T pipelines):
+ [vx, vy, wz, height | dp (3) | dq xyzw (4) | gripper]
+ dp = R_B(t)^T (p_target(t+k) - p_E(t)), dq = conj(q_E(t)) * q_target(t+k), relative to the window start t
+ (the OpenWAM action chunk = rows t .. t+31 of the window); base commands and gripper as recorded,
+ placeholders 0 (sawyer height, stretch vy and height).
+ alpha slots: dp -> 0:3, rot6d(dq) -> 3:9, gripper (1 - 2g: +1 open, -1 closed) -> 9,
+ base [vx, vy, wz, height] -> 68, 69, 70, 71 (unsupported dims masked per robot).
+ proprio: the window-start EEF pose in the base frame, p = R_B^T (p_E - p_B), R = R_B^T R_E (rot6d) -> 0:9;
+ gripper and base proprio masked (no world-frame quantity is fed to the model).
+ base pose: full measured pose from sim_info/0/sim_states.npz (meta/sim_base_pose/episode_XXXXXX.npy,
+ aligned with parquet sim_step_idx - 1, validated against observation.eef_pose / state).
+
+Normalization: per robot, min-max over every valid chunk element of every window, rot6d and gripper pinned to
+[-1, 1] (``build_mmb_canon_stats`` -> meta/mmb_canon_normalization_stats.npy).
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader import mmb_canonical_action as ca
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_canon_normalization_stats.npy"
+BASE_POSE_DIR = "sim_base_pose"
+CHUNK = 32 # alpha action horizon (num_frames - 1)
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def canon_raw_action(robot: str, action_rows: np.ndarray, base_t: np.ndarray, eef_t: np.ndarray) -> np.ndarray:
+ """Recorded action rows of one window + window-start poses -> (n, 14) alpha raw
+ ``[dp(3), rot6d(dq)(6), gripper(+1 open), vx, vy, wz, height]``."""
+ c = ca.encode_chunk(robot, np.asarray(action_rows, np.float64), base_t, eef_t)
+ rot6d = quat_xyzw_to_rot6d(c[:, 7:11]).astype(np.float64)
+ return np.concatenate([c[:, 4:7], rot6d, 1.0 - 2.0 * c[:, 11:12], c[:, 0:4]], -1).astype(np.float32)
+
+
+def canon_raw_proprio(base_t: np.ndarray, eef_t: np.ndarray) -> np.ndarray:
+ """Window-start EEF pose in the base frame -> (1, 14) raw ``[p(3), rot6d(6), 0 ...]``."""
+ base_t, eef_t = np.asarray(base_t, np.float64), np.asarray(eef_t, np.float64)
+ R_b = ca.qrotmat(base_t[3:7])
+ p = R_b.T @ (eef_t[:3] - base_t[:3])
+ q = ca.qmul(ca.qconj(ca.qnorm(base_t[3:7])), ca.qnorm(eef_t[3:7]))
+ out = np.zeros((1, ARM_DIM + 4), np.float32)
+ out[0, :3] = p
+ out[0, ROT6D] = quat_xyzw_to_rot6d(ca.wxyz_to_xyzw(q)[None])[0]
+ return out
+
+
+def _min_max_stats(arr: np.ndarray) -> dict:
+ arr = np.asarray(arr, dtype=np.float64)
+ st = {"min": arr.min(0), "max": arr.max(0), "mean": arr.mean(0), "std": arr.std(0),
+ "q01": np.quantile(arr, 0.01, axis=0), "q99": np.quantile(arr, 0.99, axis=0)}
+ for k in st: # rot6d + gripper: identity under min-max
+ st[k][ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ st[k][GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+class _RunningMinMax:
+ def __init__(self):
+ self.lo = self.hi = None
+ self.sum = self.sq = 0.0
+ self.n = 0
+
+ def add(self, x: np.ndarray):
+ x = np.asarray(x, np.float64).reshape(-1, x.shape[-1])
+ lo, hi = x.min(0), x.max(0)
+ self.lo = lo if self.lo is None else np.minimum(self.lo, lo)
+ self.hi = hi if self.hi is None else np.maximum(self.hi, hi)
+ self.sum = self.sum + x.sum(0)
+ self.sq = self.sq + (x * x).sum(0)
+ self.n += x.shape[0]
+
+ def merge(self, o: "_RunningMinMax"):
+ if o.n == 0:
+ return
+ self.lo = o.lo if self.lo is None else np.minimum(self.lo, o.lo)
+ self.hi = o.hi if self.hi is None else np.maximum(self.hi, o.hi)
+ self.sum, self.sq, self.n = self.sum + o.sum, self.sq + o.sq, self.n + o.n
+
+ def stats(self) -> dict:
+ mean = self.sum / self.n
+ st = {"min": self.lo.copy(), "max": self.hi.copy(), "mean": mean,
+ "std": np.sqrt(np.maximum(self.sq / self.n - mean * mean, 0.0))}
+ st["q01"], st["q99"] = st["min"].copy(), st["max"].copy() # min-max mode only
+ for k, v in st.items(): # rot6d + gripper: identity under min-max
+ v[ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ v[GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _scan_episode(args):
+ robot, data_path, base_path = args
+ df = pq.read_table(data_path, columns=["action", "observation.eef_pose"]).to_pandas()
+ A = np.stack(df["action"].to_numpy()).astype(np.float64)
+ E = np.stack(df["observation.eef_pose"].to_numpy()).astype(np.float64)
+ B = np.load(base_path).astype(np.float64)
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ T = len(A)
+ for t in range(max(T - 1, 1)): # every window start (train windows need >= 2 rows)
+ rows = A[t:min(t + CHUNK, T)]
+ act.add(canon_raw_action(robot, rows, B[t], E[t]))
+ prop.add(canon_raw_proprio(B[t], E[t]))
+ return act, prop
+
+
+def build_mmb_canon_stats(robot_dir: str, workers: int = 32) -> dict:
+ """Scan every window of one robot and write ``meta/mmb_canon_normalization_stats.npy``."""
+ from concurrent.futures import ProcessPoolExecutor
+
+ robot_dir = Path(robot_dir)
+ robot = robot_dir.name
+ info = json.loads((robot_dir / "meta" / "info.json").read_text())
+ eps = _read_jsonl(robot_dir / "meta" / "episodes.jsonl")
+ excl_path = robot_dir / "meta" / "excluded_episodes.json"
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ eps = [e for e in eps if int(e["episode_index"]) not in excluded]
+ cs = int(info.get("chunks_size", 1000))
+ jobs = [(robot, str(robot_dir / info["data_path"].format(episode_chunk=e["episode_index"] // cs,
+ episode_index=e["episode_index"])),
+ str(robot_dir / "meta" / BASE_POSE_DIR / f"episode_{e['episode_index']:06d}.npy")) for e in eps]
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ with ProcessPoolExecutor(workers) as ex:
+ for a, p in ex.map(_scan_episode, jobs, chunksize=4):
+ act.merge(a)
+ prop.merge(p)
+ action_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ action_valid[ARM_DIM:] = ca.VALID_MASK[robot][:4]
+ proprio_valid = np.zeros(ARM_DIM + 4, dtype=bool)
+ proprio_valid[:GRIPPER] = True # base-frame EEF xyz + rot6d
+ payload = {
+ "robot": robot,
+ "protocol": "canonical_action_v2",
+ "action_names": ["dp_x", "dp_y", "dp_z"] + [f"dq_rot6d_{i}" for i in range(6)] +
+ ["gripper_open_scale", "vx", "vy", "wz", "height"],
+ "eef": act.stats(),
+ "eef_state": prop.stats(),
+ "action_valid": action_valid,
+ "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(4),
+ "num_timesteps": int(act.n),
+ "gripper_convention": "minus1_closed_plus1_open (native 0=open,1=closed -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBCanonRobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples (canonical action protocol v2)."""
+
+ DATASET_NAME = "MMB-canon"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+ self._layout = robot_layout(info)
+ self._n_base = len(self._layout["base"])
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_canon_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats.get("protocol") != "canonical_action_v2" or self._stats["robot"] != self._robot:
+ raise MMBDataError(f"{self._robot}: {stats_path} is not canonical_action_v2 stats for this robot")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(4), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ excl_path = self._dir / "meta" / "excluded_episodes.json" # episodes without a measured base pose
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ self._episodes = [e for e in self._episodes if int(e["episode_index"]) not in excluded]
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 2
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("action", "observation.eef_pose"))
+ frame = table.slice(offset, n_raw).to_pandas()
+ base_t = np.load(self._dir / "meta" / BASE_POSE_DIR / f"episode_{ep_idx:06d}.npy", mmap_mode="r")[offset]
+ eef_t = np.asarray(frame["observation.eef_pose"].iloc[0], np.float64)
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(n_raw, T)
+ raw_a = canon_raw_action(self._robot, np.stack(frame["action"].to_numpy()[:n_valid]), base_t, eef_t)
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = canon_raw_proprio(base_t, eef_t)
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBCanonDataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBCanonRobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBCanonDataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBCanonRobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_canon_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBCanonDataset", "MMBCanonRobotDataset", "build_mmb_canon_stats", "canon_raw_action", "canon_raw_proprio"]
diff --git a/openwam/dataloader/mmb_canonical_action.py b/openwam/dataloader/mmb_canonical_action.py
new file mode 100644
index 0000000..16bb3e1
--- /dev/null
+++ b/openwam/dataloader/mmb_canonical_action.py
@@ -0,0 +1,467 @@
+"""MobileManipBench canonical state and action chunks (v3, yiqi 11-13/14) - framework-agnostic, numpy only, shared
+by pi0.5, GR00T N1.7 and OpenWAM. The dataset (convert_merge.py --v2, patch_frame.py) stores per frame the canonical
+state (observation.state_canonical), the expert's EEF target seen from the body (action.eef_target) and the recorded
+commands (action.command); the data loader only builds chunks (action_chunk_from_targets) and normalises.
+
+Body frame (BODY_FRAME = "ground", same reference on all robots): origin = the measured base position projected to the
+floor (x_B, y_B, 0), z up, x = base heading (yaw only; Go2 gait roll / pitch and height are not part of the frame).
+Raw recordings (world frame, quaternions w-x-y-z): observation.eef_pose = measured EEF pose; base pose = measured, from
+sim_info/0/sim_states.npz (base_pose_from_sim_states: npz row sim_step_idx - 1; constant asset-frame offsets removed,
+e.g. Sawyer N051/N053/N058/N059 Ry(-90 deg)).
+
+STATE, 14D (canonical_state): [vx, vy, wz, height | x, y, z | r6 (6) | gripper]
+ vx, vy, wz = measured base velocity in the body frame from this and the previous frame (0 at frame 0);
+ height = measured Go2 base height; x, y, z = EEF position in the body frame (z = height above the floor);
+ r6 = rot6d of the EEF orientation in the body frame = first two COLUMNS [R[:,0], R[:,1]] (Zhou et al.);
+ gripper = measured finger closure 0 (open) .. 1 (closed), continuous.
+ Placeholders: Sawyer height; Stretch vy, height are exactly 0.
+
+ACTION chunk, 14D per step k = 0 .. H-1 (action_chunk_from_targets, ref "base", rot "rot6d"):
+ [vx, vy, wz, height | x, y, z | r6 (6) | gripper]
+ base part = recorded base command at t+k; gripper = recorded gripper command at t+k (0 open / 1 close);
+ x, y, z, r6 = the expert's (planner's) sparse EEF target at t+k seen from the body frame at t+k: where the EEF has
+ to be relative to the body (quasi-static, decoupled from base motion); nothing is subtracted.
+ Steps past the episode end repeat the last frame (LeRobot padding).
+Execution (decode_action_chunk): EEF target pose = (x, y, z, R(r6) orthonormalised), placed in the world with the body
+frame of the base pose measured when the step is executed, solved by the low-level IK; base command = the base part;
+gripper command = gripper > 0.5.
+Legacy layouts (older checkpoints only): rot="rpy" (11D, relative to the current EEF, roll/pitch/yaw), ref="eef"
+(relative to the current EEF), frame="base" (measured base pose as the body frame), future measured states as the EEF
+source (action_chunk_from_states).
+"""
+import numpy as np
+
+ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+RAW_DIM = {"go2_arm": 12, "sawyer_umi": 11, "stretch3": 11}
+STATE_DIM, ACTION_DIM = 14, 14
+S_POS, S_ROT, S_GRIP = slice(4, 7), slice(7, 13), 13
+A_POS, A_ROT, A_GRIP = slice(4, 7), slice(7, 13), 13 # rot = "rot6d" (default)
+ACTION_DIM_RPY, A_ROT_RPY, A_GRIP_RPY = 11, slice(7, 10), 10 # rot = "rpy" (legacy: pi05_v2, GR00T v2 / v3)
+ROT_REPRS = ("rot6d", "rpy")
+EEF_REFS = ("base", "eef") # EEF action: pose in the body frame ("base") or relative to the current EEF ("eef")
+DEFAULT_EEF_REF = "base"
+# body frame the EEF is seen from: "base" = measured base pose (Go2: torso, 0.31-0.42 m above the floor, with gait
+# roll/pitch; Sawyer / Stretch: 0.06 m); "ground" = the base projected to the floor: origin (x_B, y_B, 0), z up, base
+# heading (yaw) only - the same reference on all robots
+BODY_FRAMES = ("base", "ground")
+BODY_FRAME = "ground" # yiqi 11-14: unified frame # rot6d default (yiqi 11-13: "相对于当前底盘,我的末端要走到什么位置去?什么角度去?")
+GRIPPER_CLOSE_THRESHOLD = 0.5 # execution: closure > 0.5 -> close command (1)
+_BASE_MASK = {"go2_arm": [1, 1, 1, 1], "sawyer_umi": [1, 1, 1, 0], "stretch3": [1, 0, 1, 0]}
+STATE_MASK = {r: np.array(m + [1] * (STATE_DIM - 4), bool) for r, m in _BASE_MASK.items()}
+ACTION_MASK = {r: np.array(m + [1] * (ACTION_DIM - 4), bool) for r, m in _BASE_MASK.items()}
+ACTION_MASK_RPY = {r: np.array(m + [1] * (ACTION_DIM_RPY - 4), bool) for r, m in _BASE_MASK.items()}
+ROT6D_LAYOUT = "cols" # first two COLUMNS [R[:,0], R[:,1]] (Zhou et al.; OpenWAM). "rows" = pytorch3d / GR00T N1.7 pose.py
+# observation.state slots of the base (x, y, yaw, z); verified against the measured base pose (all tasks):
+STATE_BASE_SLOTS = {"go2_arm": (20, 21, 22, 23), "sawyer_umi": (0, 1, 2, None), "stretch3": (0, 1, 2, None)}
+# finger joints in observation.state and their fully-open magnitude (closed = 0 on all robots; verified per task)
+GRIPPER_JOINTS = {"go2_arm": ((24, 25), 0.035), "sawyer_umi": ((11, 12), 0.021), "stretch3": ((13, 14), 0.25)}
+IDENTITY_R6 = np.array([1.0, 0.0, 0.0, 0.0, 1.0, 0.0])
+
+
+# ---------------------------------------------------------------- quaternion helpers (w-x-y-z unless noted)
+def qnorm(q):
+ q = np.asarray(q, np.float64)
+ return q / np.linalg.norm(q, axis=-1, keepdims=True)
+
+
+def qconj(q):
+ return q * np.array([1.0, -1.0, -1.0, -1.0])
+
+
+def qmul(a, b):
+ aw, ax, ay, az = np.moveaxis(a, -1, 0)
+ bw, bx, by, bz = np.moveaxis(b, -1, 0)
+ return np.stack([aw * bw - ax * bx - ay * by - az * bz,
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw], -1)
+
+
+def qrotmat(q):
+ w, x, y, z = np.moveaxis(qnorm(q), -1, 0)
+ return np.stack([
+ np.stack([1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], -1),
+ np.stack([2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], -1),
+ np.stack([2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)], -1)], -2)
+
+
+def wxyz_to_xyzw(q):
+ return np.concatenate([q[..., 1:], q[..., :1]], -1)
+
+
+def xyzw_to_wxyz(q):
+ return np.concatenate([q[..., 3:], q[..., :3]], -1)
+
+
+def geodesic_deg(qa, qb):
+ d = np.abs(np.sum(qnorm(qa) * qnorm(qb), -1)).clip(0, 1)
+ return np.degrees(2 * np.arccos(d))
+
+
+def rotmat_to_quat(R):
+ """Rotation matrices [..., 3, 3] -> unit quaternions w-x-y-z (w >= 0); Shepperd's method (numerically stable,
+ also for near-identity and near-180-degree rotations)."""
+ R = np.asarray(R, np.float64)
+ m00, m11, m22 = R[..., 0, 0], R[..., 1, 1], R[..., 2, 2]
+ tr = m00 + m11 + m22
+ cand = []
+ w = np.sqrt(np.maximum(1 + tr, 1e-300)) / 2 # case w largest
+ cand.append(np.stack([w, (R[..., 2, 1] - R[..., 1, 2]) / (4 * w), (R[..., 0, 2] - R[..., 2, 0]) / (4 * w), (R[..., 1, 0] - R[..., 0, 1]) / (4 * w)], -1))
+ x = np.sqrt(np.maximum(1 + m00 - m11 - m22, 1e-300)) / 2 # case x largest
+ cand.append(np.stack([(R[..., 2, 1] - R[..., 1, 2]) / (4 * x), x, (R[..., 0, 1] + R[..., 1, 0]) / (4 * x), (R[..., 0, 2] + R[..., 2, 0]) / (4 * x)], -1))
+ y = np.sqrt(np.maximum(1 - m00 + m11 - m22, 1e-300)) / 2 # case y largest
+ cand.append(np.stack([(R[..., 0, 2] - R[..., 2, 0]) / (4 * y), (R[..., 0, 1] + R[..., 1, 0]) / (4 * y), y, (R[..., 1, 2] + R[..., 2, 1]) / (4 * y)], -1))
+ z = np.sqrt(np.maximum(1 - m00 - m11 + m22, 1e-300)) / 2 # case z largest
+ cand.append(np.stack([(R[..., 1, 0] - R[..., 0, 1]) / (4 * z), (R[..., 0, 2] + R[..., 2, 0]) / (4 * z), (R[..., 1, 2] + R[..., 2, 1]) / (4 * z), z], -1))
+ pick = np.argmax(np.stack([tr, m00, m11, m22], -1), -1)[..., None, None]
+ q = np.take_along_axis(np.stack(cand, -2), pick, -2)[..., 0, :]
+ q = np.where(q[..., :1] < 0, -q, q)
+ return qnorm(q)
+
+
+def rotmat_to_rot6d(R):
+ """[..., 3, 3] -> [..., 6]: the first two rows (ROT6D_LAYOUT = "rows") or columns ("cols") of R."""
+ R = np.asarray(R, np.float64)
+ if ROT6D_LAYOUT == "rows":
+ return R[..., :2, :].reshape(R.shape[:-2] + (6,))
+ return np.concatenate([R[..., :, 0], R[..., :, 1]], -1)
+
+
+def rot6d_to_rotmat(r6):
+ """[..., 6] -> [..., 3, 3] by Gram-Schmidt (also valid for non-orthonormal network outputs)."""
+ r6 = np.asarray(r6, np.float64)
+ a1, a2 = r6[..., :3], r6[..., 3:6]
+ b1 = a1 / np.linalg.norm(a1, axis=-1, keepdims=True)
+ b2 = a2 - np.sum(b1 * a2, -1, keepdims=True) * b1
+ b2 = b2 / np.linalg.norm(b2, axis=-1, keepdims=True)
+ b3 = np.cross(b1, b2)
+ return np.stack([b1, b2, b3], -2) if ROT6D_LAYOUT == "rows" else np.stack([b1, b2, b3], -1)
+
+
+def rotmat_to_rotvec(R):
+ """[..., 3, 3] -> rotation vectors [..., 3] (axis * angle, angle in [0, pi])."""
+ q = rotmat_to_quat(R)
+ s = np.linalg.norm(q[..., 1:], axis=-1, keepdims=True)
+ ang = 2 * np.arctan2(s, q[..., :1])
+ return np.where(s > 1e-12, q[..., 1:] / np.maximum(s, 1e-12) * ang, 2 * q[..., 1:])
+
+
+def rotvec_to_rotmat(v):
+ v = np.asarray(v, np.float64)
+ ang = np.linalg.norm(v, axis=-1, keepdims=True)
+ axis = v / np.maximum(ang, 1e-12)
+ q = np.concatenate([np.cos(ang / 2), axis * np.sin(ang / 2)], -1)
+ return qrotmat(q)
+
+
+
+
+def rotmat_to_rpy(R):
+ """[..., 3, 3] -> [..., 3] = (roll, pitch, yaw), R = Rz(yaw) Ry(pitch) Rx(roll) (ROS / URDF convention)."""
+ R = np.asarray(R, np.float64)
+ pitch = np.arcsin(np.clip(-R[..., 2, 0], -1.0, 1.0))
+ return np.stack([np.arctan2(R[..., 2, 1], R[..., 2, 2]), pitch, np.arctan2(R[..., 1, 0], R[..., 0, 0])], -1)
+
+
+def rpy_to_rotmat(rpy):
+ r, p, y = np.moveaxis(np.asarray(rpy, np.float64), -1, 0)
+ cr, sr, cp, sp, cy, sy = np.cos(r), np.sin(r), np.cos(p), np.sin(p), np.cos(y), np.sin(y)
+ return np.stack([np.stack([cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr], -1),
+ np.stack([sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr], -1),
+ np.stack([-sp, cp * sr, cp * cr], -1)], -2)
+
+
+def rot_angle_deg(R):
+ """Rotation angle of rotation matrices [..., 3, 3] in degrees."""
+ return np.degrees(np.arccos(np.clip((np.trace(R, axis1=-2, axis2=-1) - 1) / 2, -1, 1)))
+
+
+def yaw_quat(yaw):
+ yaw = np.asarray(yaw, np.float64)
+ z = np.zeros_like(yaw)
+ return np.stack([np.cos(yaw / 2), z, z, np.sin(yaw / 2)], -1)
+
+
+def base_heading_pose(robot, state):
+ """observation.state [..., D] -> base heading pose [..., 7] = [x, y, z, qw, 0, 0, qz] (world frame)."""
+ state = np.asarray(state, np.float64)
+ ix, iy, iyaw, iz = STATE_BASE_SLOTS[robot]
+ z = state[..., iz] if iz is not None else np.zeros(state.shape[:-1])
+ return np.concatenate([np.stack([state[..., ix], state[..., iy], z], -1), yaw_quat(state[..., iyaw])], -1)
+
+
+def _axis_aligned_quats():
+ """The 24 rotations that map coordinate axes onto coordinate axes (w-x-y-z, w >= 0)."""
+ out = []
+ for perm in ((0, 1, 2), (0, 2, 1), (1, 0, 2), (1, 2, 0), (2, 0, 1), (2, 1, 0)):
+ for signs in np.ndindex(2, 2, 2):
+ M = np.zeros((3, 3))
+ for r, (c, sg) in enumerate(zip(perm, signs)):
+ M[r, c] = -1.0 if sg else 1.0
+ if np.linalg.det(M) < 0:
+ continue
+ w = np.sqrt(max(0.0, 1 + np.trace(M))) / 2
+ if w > 1e-6:
+ q = np.array([w, (M[2, 1] - M[1, 2]) / (4 * w), (M[0, 2] - M[2, 0]) / (4 * w), (M[1, 0] - M[0, 1]) / (4 * w)])
+ else: # 180 deg rotations
+ axis = np.sqrt(np.clip((np.diag(M) + 1) / 2, 0, 1))
+ i = int(np.argmax(axis))
+ for j in range(3):
+ if j != i and M[i, j] + M[j, i] < 0:
+ axis[j] = -axis[j]
+ q = np.r_[0.0, axis]
+ out.append(q)
+ return np.array(out)
+
+
+AXIS_ALIGNED_QUATS = _axis_aligned_quats()
+
+
+def base_pose_from_sim_states(sim_states, sim_step_idx, robot, state, return_offset=False):
+ """Full world base pose [T, 7] = [x, y, z, qw, qx, qy, qz] for parquet frames with the given sim_step_idx [T].
+ sim_states: path to sim_info/0/sim_states.npz or the loaded npz mapping (keys robot__<Name>__base_pos/base_quat,
+ 50 Hz control steps; parquet keeps every 2nd step). Frame s <- npz row with sim_step_idx == s - 1.
+ A constant asset-frame offset in base_quat (e.g. Ry(-90 deg) for Sawyer in N051/N053/N058/N059) is removed: the
+ mean of heading(state)^-1 * base_quat is snapped to the nearest axis-aligned rotation c and base_quat * c^-1 is
+ returned, so the body frame is x forward / z up everywhere (Go2 keeps its real roll / pitch)."""
+ z = np.load(sim_states) if isinstance(sim_states, (str, bytes)) or hasattr(sim_states, "__fspath__") else sim_states
+ key = [k for k in z.files if k.startswith("robot__") and k.endswith("__base_pos")]
+ assert len(key) == 1, key
+ key = key[0][: -len("__base_pos")]
+ row = {int(v): i for i, v in enumerate(np.asarray(z["sim_step_idx"]))}
+ idx = np.array([row.get(int(s) - 1, -1) for s in np.asarray(sim_step_idx).reshape(-1)])
+ assert (idx >= 0).all(), f"{(idx < 0).sum()} frames have no sim state at sim_step_idx - 1"
+ q = qnorm(np.asarray(z[key + "__base_quat"], np.float64)[idx])
+ off = qmul(qconj(qnorm(base_heading_pose(robot, state)[..., 3:7])), q) # [T, 4]
+ c = AXIS_ALIGNED_QUATS[int(np.argmax(np.abs(off @ AXIS_ALIGNED_QUATS.T).sum(0)))]
+ q = qnorm(qmul(q, qconj(c)[None]))
+ q = np.where(q[:, :1] < 0, -q, q)
+ pose = np.concatenate([np.asarray(z[key + "__base_pos"], np.float64)[idx], q], -1)
+ return (pose, c) if return_offset else pose
+
+
+def sim_states_alignment_error(sim_states, sim_step_idx, eef_pose):
+ """Consistency check of the npz <-> parquet alignment: max |npz EEF - observation.eef_pose| as (position m,
+ rotation deg) over the episode. Both are ~0 (float32 precision) when the npz belongs to the same recording."""
+ z = np.load(sim_states) if isinstance(sim_states, (str, bytes)) or hasattr(sim_states, "__fspath__") else sim_states
+ key = [k for k in z.files if k.startswith("robot__") and k.endswith("__eef_pos")][0][: -len("__eef_pos")]
+ row = {int(v): i for i, v in enumerate(np.asarray(z["sim_step_idx"]))}
+ idx = np.array([row[int(s) - 1] for s in np.asarray(sim_step_idx).reshape(-1)])
+ eef_pose = np.asarray(eef_pose, np.float64)
+ pos = np.abs(np.asarray(z[key + "__eef_pos"], np.float64)[idx] - eef_pose[:, :3]).max()
+ rot = geodesic_deg(np.asarray(z[key + "__eef_quat"], np.float64)[idx], eef_pose[:, 3:7]).max()
+ return float(pos), float(rot)
+
+
+
+
+# ---------------------------------------------------------------- raw <-> parts
+def split_raw(robot, raw):
+ raw = np.asarray(raw, np.float64)
+ assert raw.shape[-1] == RAW_DIM[robot], (robot, raw.shape)
+ if robot == "go2_arm":
+ base = raw[..., 0:4]
+ eef = raw[..., 4:11]
+ else:
+ base = np.concatenate([raw[..., 0:3], np.zeros(raw.shape[:-1] + (1,))], -1)
+ eef = raw[..., 3:10]
+ if robot == "stretch3":
+ base = base.copy(); base[..., 1] = 0.0 # differential drive: vy is never executable
+ return base, eef[..., :3], eef[..., 3:7], raw[..., -1:]
+
+
+def join_raw(robot, base, pos, quat_wxyz, grip):
+ if robot == "go2_arm":
+ return np.concatenate([base, pos, quat_wxyz, grip], -1)
+ b = base[..., :3].copy()
+ if robot == "stretch3":
+ b[..., 1] = 0.0
+ return np.concatenate([b, pos, quat_wxyz, grip], -1)
+
+
+# ---------------------------------------------------------------- canonical state / actions
+def body_frame(base_poses, frame=None):
+ """Measured base poses [..., 7] -> pose of the body frame the EEF is seen from [..., 7] (BODY_FRAME by default)."""
+ B = np.asarray(base_poses, np.float64)
+ frame = frame or BODY_FRAME
+ if frame == "base":
+ return np.concatenate([B[..., :3], qnorm(B[..., 3:7])], -1)
+ if frame != "ground":
+ raise ValueError(f"frame must be one of {BODY_FRAMES}, got {frame!r}")
+ R = qrotmat(B[..., 3:7])
+ yaw = np.arctan2(R[..., 1, 0], R[..., 0, 0]) # heading of the base x-axis in the horizontal plane
+ return np.concatenate([B[..., :2], np.zeros(B.shape[:-1] + (1,)), yaw_quat(yaw)], -1)
+
+
+def canonical_state(robot, base_poses, eef_poses, state, timestamps, frame=None):
+ """Per-frame canonical state [T, 14] of one episode (see module docstring); EEF and base velocity are expressed in
+ body_frame(base_poses, frame); height = measured base height."""
+ B0, E = np.asarray(base_poses, np.float64), np.asarray(eef_poses, np.float64)
+ B = body_frame(B0, frame)
+ S, ts = np.asarray(state, np.float64), np.asarray(timestamps, np.float64).reshape(-1)
+ T = len(B)
+ qb = qnorm(B[:, 3:7]); R = qrotmat(qb)
+ out = np.zeros((T, STATE_DIM))
+ if T > 1:
+ dt = np.diff(ts)[:, None]
+ v = np.einsum("ti,tij->tj", (B[1:, :3] - B[:-1, :3]) / dt, R[1:]) # world velocity -> current base frame
+ dq = qmul(qconj(qb[:-1]), qb[1:]); dq = np.where(dq[:, :1] < 0, -dq, dq) # base rotation over the step
+ ang = 2 * np.arctan2(np.linalg.norm(dq[:, 1:], axis=1), dq[:, 0])
+ axis = dq[:, 1:] / np.maximum(np.linalg.norm(dq[:, 1:], axis=1, keepdims=True), 1e-12)
+ out[1:, 0:2] = v[:, :2]
+ out[1:, 2] = (axis[:, 2] * ang) / dt[:, 0]
+ out[:, 3] = B0[:, 2]
+ out[:, S_POS] = np.einsum("ti,tij->tj", E[:, :3] - B[:, :3], R) # R_B^T (p_E - p_B)
+ out[:, S_ROT] = rotmat_to_rot6d(np.einsum("tji,tjk->tik", R, qrotmat(E[:, 3:7]))) # R_B^T R_E
+ idx, open_mag = GRIPPER_JOINTS[robot]
+ out[:, S_GRIP] = np.clip(1 - np.abs(S[:, list(idx)]).mean(1) / open_mag, 0, 1)
+ out[:, ~STATE_MASK[robot]] = 0.0
+ return out
+
+
+def command_columns(robot, raw_actions):
+ """Recorded commands per frame [T, 5] = [vx, vy, wz, height, gripper] (dataset column action.command;
+ placeholders 0: Sawyer height, Stretch vy and height)."""
+ base, _, _, grip = split_raw(robot, raw_actions)
+ out = np.concatenate([base, grip], -1)
+ out[:, :4][:, ~ACTION_MASK[robot][:4]] = 0.0
+ return out
+
+
+def action_layout(rot="rot6d"):
+ """(action dim, rotation slice, gripper index, per-robot mask) of an action chunk with rotation representation rot."""
+ if rot == "rot6d":
+ return ACTION_DIM, A_ROT, A_GRIP, ACTION_MASK
+ if rot == "rpy":
+ return ACTION_DIM_RPY, A_ROT_RPY, A_GRIP_RPY, ACTION_MASK_RPY
+ raise ValueError(f"rot must be one of {ROT_REPRS}, got {rot!r}")
+
+
+def rot_from_action_dim(dim):
+ return {ACTION_DIM: "rot6d", ACTION_DIM_RPY: "rpy"}[dim]
+
+
+def relative_rotation(R_s, R_x, rot="rot6d"):
+ """R_s^T R_x (rotation of x relative to the current EEF, in the current EEF frame) as rot6d (cols) or roll/pitch/yaw.
+ Always a relative rotation - never a difference of absolute angles."""
+ R = np.einsum("...ji,...jk->...ik", R_s, R_x)
+ return rotmat_to_rot6d(R) if rot == "rot6d" else rotmat_to_rpy(R)
+
+
+def relative_rotation_matrix(a_rot, rot="rot6d"):
+ """Inverse of relative_rotation: rot6d (Gram-Schmidt, tolerates non-orthonormal model outputs) or rpy -> R."""
+ return rot6d_to_rotmat(a_rot) if rot == "rot6d" else rpy_to_rotmat(a_rot)
+
+
+def _eef_ref(rot, ref):
+ ref = ref or ("eef" if rot == "rpy" else DEFAULT_EEF_REF)
+ if ref not in EEF_REFS or (rot == "rpy" and ref != "eef"):
+ raise ValueError(f"unsupported EEF reference {ref!r} for rot {rot!r}")
+ return ref
+
+
+def eef_action(state_t, pos, R, rot="rot6d", ref=None):
+ """EEF part of the action steps from body-frame EEF poses (pos [..., H, 3], R [..., H, 3, 3]):
+ ref "base" (default, rot6d only): [pos | rot6d(R)] - where the EEF has to be, seen from the body;
+ ref "eef" (legacy): [pos - state(t).xyz | relative_rotation(R(state(t).r6), R)] - relative to the current EEF."""
+ ref = _eef_ref(rot, ref)
+ if ref == "base":
+ return np.concatenate([pos, rotmat_to_rot6d(R)], -1)
+ s = np.asarray(state_t, np.float64)
+ R_s = rot6d_to_rotmat(s[..., None, S_ROT])
+ return np.concatenate([pos - s[..., None, S_POS], relative_rotation(R_s, R, rot)], -1)
+
+
+def eef_pose_from_action(state_t, a_pos, a_rot, rot="rot6d", ref=None):
+ """Inverse of eef_action -> body-frame EEF pose (pos [..., H, 3], R [..., H, 3, 3]); rot6d outputs are
+ orthonormalised (Gram-Schmidt), so non-orthonormal model outputs give proper rotations."""
+ ref = _eef_ref(rot, ref)
+ if ref == "base":
+ return np.asarray(a_pos, np.float64), rot6d_to_rotmat(a_rot)
+ s = np.asarray(state_t, np.float64)
+ return s[..., None, S_POS] + a_pos, rot6d_to_rotmat(s[..., None, S_ROT]) @ relative_rotation_matrix(a_rot, rot)
+
+
+def action_chunk_from_states(robot, state_t, future_states, commands, rot="rot6d", ref=None):
+ """Action chunk from the future measured states: state(t) [..., 14], state(t+1 .. t+H) [..., H, 14] and the
+ recorded commands at t .. t+H-1 [..., H, 5] -> [..., H, 14] (rot6d) / [..., H, 11] (legacy rpy)."""
+ f, c = np.asarray(future_states, np.float64), np.asarray(commands, np.float64)
+ out = np.concatenate([c[..., 0:4], eef_action(state_t, f[..., S_POS], rot6d_to_rotmat(f[..., S_ROT]), rot, ref),
+ c[..., 4:5]], -1)
+ out[..., ~action_layout(rot)[3][robot]] = 0.0
+ return out
+
+
+def expert_target_columns(robot, raw_actions, base_poses, frame=None):
+ """Per-frame expert EEF target seen from the body at the same frame [T, 9] = [x, y, z | rot6d] (dataset column
+ action.eef_target): R_B(t)^T (p_target(t) - p_B(t)) and rot6d(R_B(t)^T R_target(t))."""
+ _, p_tgt, q_tgt, _ = split_raw(robot, raw_actions)
+ B = body_frame(base_poses, frame)
+ R = qrotmat(B[..., 3:7])
+ pos = np.einsum("...i,...ij->...j", p_tgt - B[..., :3], R)
+ rot = rotmat_to_rot6d(np.einsum("...ji,...jk->...ik", R, qrotmat(q_tgt)))
+ return np.concatenate([pos, rot], -1)
+
+
+def action_chunk_from_targets(robot, state_t, targets, commands, rot="rot6d", ref=None):
+ """Action chunk from the expert targets at t .. t+H-1 [..., H, 9] (body frame of their own frame) and the recorded
+ commands at t .. t+H-1 [..., H, 5] -> [..., H, 14]: [base cmd | target xyz | target rot6d | gripper cmd] (ref
+ "base", default; state(t) is not used). Legacy: ref "eef" (relative to state(t)), rot "rpy" (11D)."""
+ g, c = np.asarray(targets, np.float64), np.asarray(commands, np.float64)
+ out = np.concatenate([c[..., 0:4], eef_action(state_t, g[..., 0:3], rot6d_to_rotmat(g[..., 3:9]), rot, ref),
+ c[..., 4:5]], -1)
+ out[..., ~action_layout(rot)[3][robot]] = 0.0
+ return out
+
+
+def episode_target_chunks(robot, canon_states, targets, commands, horizon, rot="rot6d", ref=None):
+ """All training chunks of one episode [T, H, A] from expert targets and commands at t .. t+H-1 (clamped)."""
+ S, G, Cm = (np.asarray(x, np.float64) for x in (canon_states, targets, commands))
+ T = len(S)
+ idx = np.minimum(np.arange(T)[:, None] + np.arange(horizon)[None, :], T - 1)
+ return action_chunk_from_targets(robot, S, G[idx], Cm[idx], rot, ref)
+
+
+def future_states_from_chunk(robot, state_t, action_chunk, rot=None, ref=None):
+ """Inverse of action_chunk_from_states / _from_targets for the EEF: -> predicted EEF part of the state [..., H, 14]
+ (base / gripper slots carry the commands). rot defaults to the one implied by the action dim (14 rot6d, 11 rpy),
+ ref to DEFAULT_EEF_REF for rot6d ("eef" for rpy)."""
+ a = np.asarray(action_chunk, np.float64).copy()
+ rot = rot or rot_from_action_dim(a.shape[-1])
+ _, a_rot, a_grip, mask = action_layout(rot)
+ a[..., ~mask[robot]] = 0.0
+ pos, R = eef_pose_from_action(state_t, a[..., A_POS], a[..., a_rot], rot, ref)
+ out = np.zeros(a.shape[:-1] + (STATE_DIM,))
+ out[..., 0:4] = a[..., 0:4]
+ out[..., S_POS] = pos
+ out[..., S_ROT] = rotmat_to_rot6d(R)
+ out[..., S_GRIP] = a[..., a_grip] # the gripper command (not a measured closure)
+ return out
+
+
+def decode_action_chunk(robot, action_chunk, state_t, base_poses_now, rot=None, ref=None, frame=None):
+ """Model output [H, 14] (legacy rpy [H, 11]) + current canonical state [14] (used only by the legacy ref "eef") +
+ body pose measured when each step is executed [H, 7] -> controller commands in the recorded format [H, D_robot]:
+ base velocity command, world EEF target (wxyz) and gripper command (closure > GRIPPER_CLOSE_THRESHOLD).
+ Unsupported dimensions are never emitted."""
+ a = np.asarray(action_chunk, np.float64)
+ rot = rot or rot_from_action_dim(a.shape[-1])
+ f = future_states_from_chunk(robot, state_t, a, rot, ref)
+ B = body_frame(base_poses_now, frame) # measured base pose -> body frame
+ R_b = qrotmat(B[..., 3:7])
+ p = B[..., :3] + np.einsum("...ij,...j->...i", R_b, f[..., S_POS])
+ q = rotmat_to_quat(R_b @ rot6d_to_rotmat(f[..., S_ROT]))
+ a_grip = action_layout(rot)[2]
+ grip = (a[..., a_grip:a_grip + 1] > GRIPPER_CLOSE_THRESHOLD).astype(np.float64)
+ return join_raw(robot, f[..., 0:4], p, q, grip)
+
+
+def episode_action_chunks(robot, canon_states, commands, horizon, rot="rot6d", ref=None):
+ """All training chunks of one episode [T, H, A] from its canonical states (future steps t+1 .. t+H) and the
+ recorded commands [T, 5] (steps t .. t+H-1); indices are clamped to the last frame like LeRobot."""
+ S = np.asarray(canon_states, np.float64)
+ Cm = np.asarray(commands, np.float64)
+ T = len(S)
+ k = np.arange(horizon)[None, :]
+ return action_chunk_from_states(robot, S, S[np.minimum(np.arange(T)[:, None] + k + 1, T - 1)],
+ Cm[np.minimum(np.arange(T)[:, None] + k, T - 1)], rot, ref)
diff --git a/openwam/dataloader/mmb_final.py b/openwam/dataloader/mmb_final.py
new file mode 100644
index 0000000..0ffa596
--- /dev/null
+++ b/openwam/dataloader/mmb_final.py
@@ -0,0 +1,456 @@
+"""MobileManipBench reader for OpenWAM-alpha, final canonical definition (yiqi 11-13).
+
+Dataset: the shared ``convert_merge.py --v2 --robots <robot>`` output (one LeRobot v2.1 dataset per robot) with
+``observation.state_canonical`` (14D) and ``action.command`` (5D). All math is the shared ``mmb_canonical_action``
+(identical to the pi0.5 / GR00T pipelines):
+
+ state [vx, vy, wz, h | x, y, z | rot6d (cols) | gripper closure] -> proprio of the window start t
+ action ``action_chunk_from_states(state(t), state(t+1..t+32), command(t..t+31))`` =
+ [base cmd (4) | dxyz | droll, dpitch, dyaw | gripper cmd 0/1]
+
+alpha 80-D slots (fixed contract): EEF xyz -> 0:3, rotation as rot6d -> 3:9 (the action's roll/pitch/yaw delta is
+converted to its rotation matrix and then rot6d; the state's rot6d is used as is), gripper -> 9 as +1 open / -1 closed
+(1 - 2x), base [vx, vy, wz, h] -> 68..71; unsupported base dims (Sawyer h, Stretch vy and h) are masked. Steps past
+the episode end (state index >= T) are masked. Normalization: per robot min-max (alpha contract), rot6d and gripper
+pinned to [-1, 1] (``build_mmb_final_stats`` -> meta/mmb_final_normalization_stats.npy).
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader import mmb_canonical_action as ca
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_final_normalization_stats.npy"
+CHUNK = 32 # alpha action horizon (num_frames - 1)
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def final_raw_action(robot: str, state_t, future_states, commands) -> np.ndarray:
+ """(n,) steps -> (n, 14) alpha raw [dxyz, rot6d(drpy), gripper(+1 open), vx, vy, wz, h]."""
+ a = ca.action_chunk_from_states(robot, state_t, future_states, commands)
+ r6 = ca.rotmat_to_rot6d(ca.rpy_to_rotmat(a[:, 7:10]))
+ return np.concatenate([a[:, 4:7], r6, 1.0 - 2.0 * a[:, 10:11], a[:, 0:4]], -1).astype(np.float32)
+
+
+def final_raw_proprio(state_t) -> np.ndarray:
+ """(14,) canonical state -> (1, 14) alpha raw [xyz, rot6d, gripper(+1 open), vx, vy, wz, h]."""
+ s = np.asarray(state_t, np.float64)
+ return np.concatenate([s[4:7], s[7:13], [1.0 - 2.0 * s[13]], s[0:4]])[None].astype(np.float32)
+
+
+def _min_max_stats(arr: np.ndarray) -> dict:
+ arr = np.asarray(arr, dtype=np.float64)
+ st = {"min": arr.min(0), "max": arr.max(0), "mean": arr.mean(0), "std": arr.std(0),
+ "q01": np.quantile(arr, 0.01, axis=0), "q99": np.quantile(arr, 0.99, axis=0)}
+ for k in st: # rot6d + gripper: identity under min-max
+ st[k][ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ st[k][GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+class _RunningMinMax:
+ def __init__(self):
+ self.lo = self.hi = None
+ self.sum = self.sq = 0.0
+ self.n = 0
+
+ def add(self, x: np.ndarray):
+ x = np.asarray(x, np.float64).reshape(-1, x.shape[-1])
+ lo, hi = x.min(0), x.max(0)
+ self.lo = lo if self.lo is None else np.minimum(self.lo, lo)
+ self.hi = hi if self.hi is None else np.maximum(self.hi, hi)
+ self.sum = self.sum + x.sum(0)
+ self.sq = self.sq + (x * x).sum(0)
+ self.n += x.shape[0]
+
+ def merge(self, o: "_RunningMinMax"):
+ if o.n == 0:
+ return
+ self.lo = o.lo if self.lo is None else np.minimum(self.lo, o.lo)
+ self.hi = o.hi if self.hi is None else np.maximum(self.hi, o.hi)
+ self.sum, self.sq, self.n = self.sum + o.sum, self.sq + o.sq, self.n + o.n
+
+ def stats(self) -> dict:
+ mean = self.sum / self.n
+ st = {"min": self.lo.copy(), "max": self.hi.copy(), "mean": mean,
+ "std": np.sqrt(np.maximum(self.sq / self.n - mean * mean, 0.0))}
+ st["q01"], st["q99"] = st["min"].copy(), st["max"].copy() # min-max mode only
+ for k, v in st.items(): # rot6d + gripper: identity under min-max
+ v[ROT6D] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ v[GRIPPER] = {"min": -1, "max": 1, "mean": 0, "std": 1, "q01": -1, "q99": 1}[k]
+ return {k: v.astype(np.float32) for k, v in st.items()}
+
+
+def _scan_episode(args):
+ robot, data_path = args
+ t = pq.read_table(data_path, columns=["observation.state_canonical", "action.command"])
+ S = np.asarray(t["observation.state_canonical"].to_pylist(), np.float64)
+ C = np.asarray(t["action.command"].to_pylist(), np.float64)
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ T = len(S)
+ for s0 in range(max(T - 1, 1)): # every train window start (needs >= 1 future state)
+ n = min(CHUNK, T - 1 - s0)
+ act.add(final_raw_action(robot, S[s0], S[s0 + 1:s0 + 1 + n], C[s0:s0 + n]))
+ prop.add(final_raw_proprio(S[s0]))
+ return act, prop
+
+
+def build_mmb_final_stats(robot_dir: str, workers: int = 32) -> dict:
+ """Scan every window of one robot and write ``meta/mmb_final_normalization_stats.npy``."""
+ from concurrent.futures import ProcessPoolExecutor
+
+ robot_dir = Path(robot_dir)
+ robot = robot_dir.name
+ info = json.loads((robot_dir / "meta" / "info.json").read_text())
+ eps = _read_jsonl(robot_dir / "meta" / "episodes.jsonl")
+ cs = int(info.get("chunks_size", 1000))
+ jobs = [(robot, str(robot_dir / info["data_path"].format(episode_chunk=e["episode_index"] // cs,
+ episode_index=e["episode_index"]))) for e in eps]
+ act, prop = _RunningMinMax(), _RunningMinMax()
+ with ProcessPoolExecutor(workers) as ex:
+ for a_, p_ in ex.map(_scan_episode, jobs, chunksize=4):
+ act.merge(a_)
+ prop.merge(p_)
+ action_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ action_valid[ARM_DIM:] = ca.ACTION_MASK[robot][:4]
+ proprio_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ proprio_valid[ARM_DIM:] = ca.STATE_MASK[robot][:4]
+ payload = {
+ "robot": robot, "protocol": "canonical_final_11_13",
+ "eef": act.stats(), "eef_state": prop.stats(),
+ "action_valid": action_valid, "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(4), "num_timesteps": int(act.n),
+ "gripper_convention": "alpha: +1 open / -1 closed (canonical 0/1 command and closure -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBFinalRobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples (canonical action protocol v2)."""
+
+ DATASET_NAME = "MMB-final"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_final_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats.get("protocol") != "canonical_final_11_13" or self._stats["robot"] != self._robot:
+ raise MMBDataError(f"{self._robot}: {stats_path} is not the final canonical stats for this robot")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(4), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ excl_path = self._dir / "meta" / "excluded_episodes.json" # episodes without a measured base pose
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ self._episodes = [e for e in self._episodes if int(e["episode_index"]) not in excluded]
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 2 # >= 1 future state
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("observation.state_canonical", "action.command"))
+ n_rows = min(ep_len - offset, self._num_frames)
+ frame = table.slice(offset, n_rows).to_pandas()
+ S = np.stack(frame["observation.state_canonical"].to_numpy()).astype(np.float64)
+ Cm = np.stack(frame["action.command"].to_numpy()).astype(np.float64)
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(T, n_rows - 1) # step k needs state(t+k) inside the episode
+ raw_a = final_raw_action(self._robot, S[0], S[1:1 + n_valid], Cm[:n_valid])
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = final_raw_proprio(S[0])
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBFinalDataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBFinalRobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBFinalDataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBFinalRobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_final_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBFinalDataset", "MMBFinalRobotDataset", "build_mmb_final_stats", "final_raw_action", "final_raw_proprio"]
diff --git a/openwam/dataloader/mmb_v4.py b/openwam/dataloader/mmb_v4.py
new file mode 100644
index 0000000..3999436
--- /dev/null
+++ b/openwam/dataloader/mmb_v4.py
@@ -0,0 +1,405 @@
+"""MobileManipBench reader for OpenWAM-alpha, final definition (yiqi 11-14; shared canonical_action.py @ 8d0b031).
+
+Dataset: the shared ``convert_merge.py --v2 --robots <robot>`` output (one LeRobot v2.1 dataset per robot, unified
+ground frame) with ``observation.state_canonical`` (14D), ``action.command`` (5D) and ``action.eef_target`` (9D).
+All math is the shared ``mmb_canonical_action`` (identical to the pi0.5 / GR00T pipelines):
+
+ state [vx, vy, wz, h | x, y, z | rot6d (cols) | gripper closure] -> proprio of the window start t
+ action ``action_chunk_from_targets(state(t), eef_target(t..t+31), command(t..t+31))`` =
+ [base cmd (4) | target xyz | target rot6d | gripper cmd 0/1] (absolute target, ground frame)
+
+alpha 80-D slots (fixed contract): EEF xyz -> 0:3, rot6d -> 3:9, gripper -> 9 as +1 open / -1 closed (1 - 2x),
+base [vx, vy, wz, h] -> 68..71; unsupported base dims (Sawyer h, Stretch vy and h) are masked. Steps past the episode
+end are masked. Normalization: the shared stats (stats/norm_stats_v3_per_robot.json): base and EEF xyz pooled over the
+robots and shared by state / action (q01 / q99 used as alpha's min / max), rot6d and gripper identity, missing dims
+identity (they are 0 and masked) -> ``build_mmb_v4_stats`` -> meta/mmb_v4_normalization_stats.npy.
+"""
+
+from __future__ import annotations
+
+import functools
+import json
+import logging
+import os
+from pathlib import Path
+from typing import Any, List, Optional, Sequence
+
+import numpy as np
+import pandas as pd
+import pyarrow.parquet as pq
+import torch
+from PIL import Image
+
+from openwam.dataloader.bases import BaseDataset
+from openwam.dataloader.transforms.multiview import assemble_multiview_layout
+from openwam.dataloader.transforms.video import VideoColorJitter, color_jitter_enabled
+from openwam.dataloader import mmb_canonical_action as ca
+from openwam.dataloader.utils.eef import quat_xyzw_to_rot6d
+from openwam.dataloader.utils.normalization import apply_normalization
+from openwam.dataloader.utils.unify_action import UNIFY_DIM, map_to_unify, parse_unify_spec
+from openwam.dataloader.utils.video_io import decode_video_frames as _decode_video_frames
+
+logger = logging.getLogger(__name__)
+
+MMB_ROBOTS = ("go2_arm", "sawyer_umi", "stretch3")
+HEAD_CAMERA = "observation.images.head"
+WRIST_CAMERA = "observation.images.wrist"
+STATS_FILENAME = "mmb_v4_normalization_stats.npy"
+CHUNK = 32 # alpha action horizon (num_frames - 1)
+ARM_DIM = 10 # xyz3 + rot6d6 + gripper1
+ROT6D = slice(3, 9)
+GRIPPER = 9
+BASE_SLOTS = (68, 69, 70, 71)
+CONST_EPS = 1e-6
+_GETITEM_MAX_RETRIES = 64
+_WRIST_DECODE_TOLERATED: tuple = (FileNotFoundError, OSError, RuntimeError)
+
+
+class MMBDataError(ValueError):
+ """Deterministic data-contract violation; never retried away."""
+
+
+def _quat_wxyz_to_rot6d(q: np.ndarray) -> np.ndarray:
+ q = np.asarray(q, dtype=np.float64)
+ norm = np.linalg.norm(q, axis=-1, keepdims=True)
+ if not np.all(np.abs(norm - 1.0) < 0.05):
+ raise MMBDataError(f"non-unit quaternion, norms {norm.ravel()[:4]}")
+ xyzw = np.concatenate([q[..., 1:4], q[..., 0:1]], axis=-1) / norm
+ return quat_xyzw_to_rot6d(xyzw.reshape(-1, 4)).reshape(*q.shape[:-1], 6).astype(np.float32)
+
+
+def robot_layout(info: dict) -> dict:
+ """Column indices of the base, EEF pose and gripper inside ``action`` (from info.json names)."""
+ names = list(info["features"]["action"]["names"])
+ if names[-1] != "gripper":
+ raise MMBDataError(f"last action dim must be the gripper, got {names[-1]!r}")
+ pos = next(i for i, n in enumerate(names) if n.endswith("pos_x") or n == "arm_action_0")
+ base = list(range(pos))
+ if pos + 7 != len(names) - 1:
+ raise MMBDataError(f"expected 7 pose dims between base and gripper, names={names}")
+ eef_w = info["features"]["observation.eef_pose"]["shape"][0]
+ if eef_w != 7:
+ raise MMBDataError(f"observation.eef_pose must be 7-D, got {eef_w}")
+ return {"base": base, "pose": list(range(pos, pos + 7)), "gripper": len(names) - 1}
+
+
+def final_raw_action(robot: str, state_t, targets, commands) -> np.ndarray:
+ """(n,) steps -> (n, 14) alpha raw [target xyz, target rot6d, gripper(+1 open), vx, vy, wz, h]."""
+ a = ca.action_chunk_from_targets(robot, state_t, targets, commands)
+ return np.concatenate([a[:, ca.A_POS], a[:, ca.A_ROT], 1.0 - 2.0 * a[:, ca.A_GRIP:ca.A_GRIP + 1], a[:, 0:4]],
+ -1).astype(np.float32)
+
+
+def final_raw_proprio(state_t) -> np.ndarray:
+ """(14,) canonical state -> (1, 14) alpha raw [xyz, rot6d, gripper(+1 open), vx, vy, wz, h]."""
+ s = np.asarray(state_t, np.float64)
+ return np.concatenate([s[4:7], s[7:13], [1.0 - 2.0 * s[13]], s[0:4]])[None].astype(np.float32)
+
+
+def _read_jsonl(path: Path) -> list:
+ with path.open() as f:
+ return [json.loads(line) for line in f if line.strip()]
+
+
+def _shared_to_alpha(src: dict, robot: str) -> dict:
+ """Shared 14D canonical q01 / q99 [base4 | xyz | rot6d | grip] -> alpha raw-order min-max stats
+ [xyz | rot6d | gripper | base4]; rot6d, gripper and the robot's missing base dims -> identity [-1, 1]."""
+ order = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 0, 1, 2, 3]
+ lo = np.asarray(src["q01"], np.float64)[order]
+ hi = np.asarray(src["q99"], np.float64)[order]
+ ident = np.zeros(ARM_DIM + 4, bool)
+ ident[ROT6D] = True
+ ident[GRIPPER] = True
+ ident[ARM_DIM:] = ~ca.ACTION_MASK[robot][:4]
+ lo[ident], hi[ident] = -1.0, 1.0
+ mean, std = (lo + hi) / 2, (hi - lo) / 2
+ return {k: v.astype(np.float32) for k, v in
+ dict(min=lo, max=hi, q01=lo.copy(), q99=hi.copy(), mean=mean, std=std).items()}
+
+
+def build_mmb_v4_stats(robot_dir: str, shared_stats_path: str) -> dict:
+ """Write ``meta/mmb_v4_normalization_stats.npy`` for one robot from the shared normalization stats."""
+ robot_dir = Path(robot_dir)
+ robot = robot_dir.name
+ shared = json.loads(Path(shared_stats_path).read_text())[str(ca.ROBOTS.index(robot))]
+ action_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ action_valid[ARM_DIM:] = ca.ACTION_MASK[robot][:4]
+ proprio_valid = np.ones(ARM_DIM + 4, dtype=bool)
+ proprio_valid[ARM_DIM:] = ca.STATE_MASK[robot][:4]
+ payload = {
+ "robot": robot, "protocol": "canonical_v4_11_14",
+ "eef": _shared_to_alpha(shared["actions"], robot), "eef_state": _shared_to_alpha(shared["state"], robot),
+ "action_valid": action_valid, "proprio_valid": proprio_valid,
+ "unify_map": unify_map_for(4), "shared_stats": str(shared_stats_path),
+ "gripper_convention": "alpha: +1 open / -1 closed (canonical 0/1 command and closure -> 1-2x)",
+ }
+ out = robot_dir / "meta" / STATS_FILENAME
+ tmp = out.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, out)
+ return payload
+
+
+def unify_map_for(n_base: int) -> list:
+ """Raw ``[arm10, base...]`` -> alpha slots ``0..9`` + ``68..68+n_base-1``."""
+ return list(range(ARM_DIM)) + list(BASE_SLOTS[:n_base])
+
+
+@functools.lru_cache(maxsize=4)
+def _load_parquet_table(path: str, columns: tuple):
+ return pq.read_table(path, memory_map=True, columns=list(columns))
+
+
+class MMBV4RobotDataset(BaseDataset):
+ """One robot's merged dataset -> alpha 80-D samples (final definition, absolute targets)."""
+
+ DATASET_NAME = "MMB-v4"
+
+ def __init__(
+ self,
+ robot_dir: str,
+ *,
+ split: str = "train",
+ num_frames: int = 33,
+ video_stride: int = 4,
+ window_stride: int = 1,
+ height: int = 384,
+ width: int = 320,
+ multiview: bool = True,
+ normalize_mode: Optional[str] = "min-max",
+ color_jitter: Optional[Any] = None,
+ **_unused: Any,
+ ):
+ self._dir = Path(robot_dir)
+ self._robot = self._dir.name
+ self._split = split
+ self._num_frames = int(num_frames)
+ self._video_stride = max(1, int(video_stride))
+ self._window_stride = max(1, int(window_stride))
+ self._height, self._width = int(height), int(width)
+ self._multiview = bool(multiview)
+ self._camera_layout = [HEAD_CAMERA, WRIST_CAMERA, "__missing_right__"]
+ if normalize_mode != "min-max":
+ raise ValueError("OpenWAM-alpha fine-tuning fixes normalize_mode=min-max")
+ self._normalize_mode = normalize_mode
+ self._color_jitter = None
+ if color_jitter_enabled(color_jitter) and split == "train":
+ cj = color_jitter.get if hasattr(color_jitter, "get") else (lambda k, d: d)
+ self._color_jitter = VideoColorJitter(
+ brightness=float(cj("brightness", 0.2)), contrast=float(cj("contrast", 0.2)),
+ saturation=float(cj("saturation", 0.2)), hue=float(cj("hue", 0.0)))
+
+ info = json.loads((self._dir / "meta" / "info.json").read_text())
+ if int(info["fps"]) != 25:
+ raise MMBDataError(f"{self._robot}: expected 25 fps, got {info['fps']}")
+ self._chunks_size = int(info.get("chunks_size", 1000))
+ self._data_path_template = info["data_path"]
+ self._video_path_template = info["video_path"]
+
+ stats_path = self._dir / "meta" / STATS_FILENAME
+ if not stats_path.exists():
+ raise FileNotFoundError(f"{stats_path} missing: run build_mmb_v4_stats first")
+ self._stats = np.load(stats_path, allow_pickle=True).item()
+ if self._stats.get("protocol") != "canonical_v4_11_14" or self._stats["robot"] != self._robot:
+ raise MMBDataError(f"{self._robot}: {stats_path} is not the v4 stats for this robot")
+ self.normalization_stats_path = str(stats_path)
+ self._dst = parse_unify_spec(unify_map_for(4), UNIFY_DIM)
+ self._action_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._action_dim_mask[self._dst[self._stats["action_valid"]]] = True
+ self._proprio_dim_mask = np.zeros(UNIFY_DIM, dtype=bool)
+ self._proprio_dim_mask[self._dst[self._stats["proprio_valid"]]] = True
+
+ self._episodes = _read_jsonl(self._dir / "meta" / "episodes.jsonl")
+ excl_path = self._dir / "meta" / "excluded_episodes.json" # episodes without a measured base pose
+ excluded = set(json.loads(excl_path.read_text())["episode_indices"]) if excl_path.exists() else set()
+ self._episodes = [e for e in self._episodes if int(e["episode_index"]) not in excluded]
+ self._video_sample_indices = np.arange(0, self._num_frames, self._video_stride, dtype=np.int64)
+ self._num_video_frames = int(self._video_sample_indices.size)
+ lengths = np.asarray([int(e["length"]) for e in self._episodes], dtype=np.int64)
+ min_len = self._num_frames if split == "val" else 1 # step k reads the target row t+k-1
+ n_starts = np.where(lengths >= min_len, (lengths - min_len) // self._window_stride + 1, 0)
+ self._cum = np.concatenate([[0], np.cumsum(n_starts)]).astype(np.int64)
+ self._n_total = int(self._cum[-1])
+ self._fail_count = 0
+ logger.info("MMB(%s, %s): %d episodes, %d windows, action slots %s, proprio slots %s",
+ self._robot, split, len(self._episodes), self._n_total,
+ np.flatnonzero(self._action_dim_mask).tolist(), np.flatnonzero(self._proprio_dim_mask).tolist())
+
+ def __len__(self) -> int:
+ return self._n_total
+
+ def __getitem__(self, idx: int) -> dict:
+ if not 0 <= idx < self._n_total:
+ raise IndexError(idx)
+ for attempt in range(_GETITEM_MAX_RETRIES):
+ try:
+ return self._getitem_impl(idx)
+ except MMBDataError:
+ raise
+ except Exception as e:
+ if attempt == _GETITEM_MAX_RETRIES - 1:
+ raise
+ self._fail_count += 1
+ if self._fail_count == 1 or self._fail_count % 100 == 0:
+ logger.warning("MMB(%s): %d getitem failures (idx=%d, %s: %s)",
+ self._robot, self._fail_count, idx, type(e).__name__, e)
+ ep = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ idx = int(self._cum[(ep + 1) % len(self._episodes)]) % self._n_total
+ raise RuntimeError("unreachable")
+
+ def _normalize(self, raw: np.ndarray, stats: dict) -> np.ndarray:
+ if not np.isfinite(raw).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite raw values")
+ out = apply_normalization(raw, stats, self._normalize_mode)
+ if not np.isfinite(out).all():
+ raise MMBDataError(f"MMB({self._robot}): non-finite normalized values")
+ return out.astype(np.float32)
+
+ def _getitem_impl(self, idx: int) -> dict:
+ ep_local = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ offset = (idx - int(self._cum[ep_local])) * self._window_stride
+ ep = self._episodes[ep_local]
+ ep_idx, ep_len = int(ep["episode_index"]), int(ep["length"])
+ n_raw = min(self._num_frames, ep_len - offset)
+
+ chunk = ep_idx // self._chunks_size
+ table = _load_parquet_table(
+ str(self._dir / self._data_path_template.format(episode_chunk=chunk, episode_index=ep_idx)),
+ ("observation.state_canonical", "action.command", "action.eef_target"))
+ n_rows = min(ep_len - offset, self._num_frames)
+ frame = table.slice(offset, n_rows).to_pandas()
+ S = np.stack(frame["observation.state_canonical"].to_numpy()).astype(np.float64)
+ Cm = np.stack(frame["action.command"].to_numpy()).astype(np.float64)
+ G = np.stack(frame["action.eef_target"].to_numpy()).astype(np.float64)
+
+ T = self._num_frames - 1
+ action = np.zeros((T, UNIFY_DIM), dtype=np.float32)
+ action_mask = np.zeros((T, UNIFY_DIM), dtype=bool)
+ n_valid = min(T, n_rows) # step k reads the target / command row t+k-1 inside the episode
+ raw_a = final_raw_action(self._robot, S[0], G[:n_valid], Cm[:n_valid])
+ action[:n_valid] = map_to_unify(self._normalize(raw_a, self._stats["eef"]), self._dst, UNIFY_DIM)[0]
+ action_mask[:n_valid] = self._action_dim_mask
+
+ raw_p = final_raw_proprio(S[0])
+ proprio = map_to_unify(self._normalize(raw_p, self._stats["eef_state"]), self._dst, UNIFY_DIM)[0]
+ proprio = proprio * self._proprio_dim_mask
+ proprio_mask = self._proprio_dim_mask[None, :].copy()
+
+ video = self._decode_window_video(ep_idx, offset, n_raw)
+ if self._color_jitter is not None:
+ video = self._color_jitter.apply({"video": video})["video"]
+ prompt = str((ep.get("tasks") or [""])[0]).strip()
+ if not prompt:
+ raise MMBDataError(f"MMB({self._robot}): episode {ep_idx} has no task text")
+ return {
+ "video": video,
+ "vace_video": None,
+ "first_frame_image": [video[0]],
+ "action": torch.from_numpy(action),
+ "action_mask": torch.from_numpy(action_mask),
+ "video_mask": torch.from_numpy(self._video_sample_indices < n_raw),
+ "proprio": torch.from_numpy(proprio.astype(np.float32)),
+ "proprio_mask": torch.from_numpy(proprio_mask),
+ "prompt": prompt,
+ }
+
+ def _video_path(self, camera: str, ep_idx: int) -> Path:
+ chunk = ep_idx // self._chunks_size
+ return self._dir / self._video_path_template.format(
+ episode_chunk=chunk, video_key=camera, episode_index=ep_idx)
+
+ def _slot_size(self, slot: int) -> tuple:
+ if not self._multiview:
+ return self._height, self._width
+ top_h = int(round(self._height * 2.0 / 3.0))
+ return (top_h, self._width) if slot == 0 else (self._height - top_h, self._width // 2)
+
+ def _decode_window_video(self, ep_idx: int, offset: int, n_raw: int) -> List:
+ real = (self._video_sample_indices[self._video_sample_indices < n_raw] + offset).tolist() or [offset]
+ cams = self._camera_layout if self._multiview else [HEAD_CAMERA]
+ frames = {}
+ for slot, cam in enumerate(cams):
+ if cam.startswith("__missing"):
+ continue
+ h, w = self._slot_size(slot)
+ if slot == 0:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ else:
+ try:
+ frames[cam] = _decode_video_frames(str(self._video_path(cam, ep_idx)), real, h, w)
+ except _WRIST_DECODE_TOLERATED:
+ frames[cam] = [Image.new("RGB", (w, h), (0, 0, 0)) for _ in real]
+ for cam, fr in frames.items():
+ if len(fr) < self._num_video_frames:
+ frames[cam] = fr + [fr[-1]] * (self._num_video_frames - len(fr))
+ if not self._multiview:
+ return frames[HEAD_CAMERA]
+ return [assemble_multiview_layout({c: f[i] for c, f in frames.items()}, list(cams),
+ out_h=self._height, out_w=self._width)
+ for i in range(self._num_video_frames)]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None # samples leave pre-normalized
+
+
+class MMBV4Dataset(BaseDataset):
+ """All robots concatenated: uniform over windows, i.e. robots in proportion to their data."""
+
+ def __init__(self, readers: Sequence[MMBV4RobotDataset], normalization_stats_path: Optional[str]):
+ self._readers = list(readers)
+ lens = np.asarray([len(r) for r in self._readers], dtype=np.int64)
+ self._cum = np.concatenate([[0], np.cumsum(lens)]).astype(np.int64)
+ self.normalization_stats_path = normalization_stats_path
+ logger.info("MMBV4Dataset: %s windows", dict(zip([r._robot for r in self._readers], lens.tolist())))
+
+ def __len__(self) -> int:
+ return int(self._cum[-1])
+
+ def __getitem__(self, idx: int) -> dict:
+ b = int(np.searchsorted(self._cum, idx, side="right") - 1)
+ return self._readers[b][idx - int(self._cum[b])]
+
+ @property
+ def action_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def state_dim(self) -> int:
+ return UNIFY_DIM
+
+ @property
+ def normalization_stats(self) -> Optional[dict]:
+ return None
+
+ @classmethod
+ def from_config(cls, config, split: str = "train"):
+ get = (lambda k, d=None: config.get(k, d)) if hasattr(config, "get") else (lambda k, d=None: getattr(config, k, d))
+ root = Path(get("dataset_dir"))
+ robots = list(get("robots", MMB_ROBOTS))
+ common = {k: get(k, d) for k, d in [("num_frames", 33), ("video_stride", 4), ("window_stride", 1),
+ ("height", 384), ("width", 320), ("multiview", True),
+ ("normalize_mode", "min-max"), ("color_jitter", None)]}
+ readers = [MMBV4RobotDataset(str(root / r), split=split, **common) for r in robots]
+ # Deploy artifact: every robot's raw stats + slot map in one file next to the robot dirs.
+ combined = root / "mmb_v4_normalization_stats_all.npy"
+ rank = int(os.environ.get("RANK", os.environ.get("LOCAL_RANK", 0)))
+ if rank == 0:
+ payload = {r._robot: r._stats for r in readers}
+ tmp = combined.with_suffix(f".{os.getpid()}.tmp")
+ with tmp.open("wb") as f:
+ np.save(f, payload)
+ os.replace(tmp, combined)
+ return cls(readers, normalization_stats_path=str(combined))
+
+
+__all__ = ["MMBV4Dataset", "MMBV4RobotDataset", "build_mmb_v4_stats", "final_raw_action", "final_raw_proprio"]
diff --git a/openwam/dataloader/registry.py b/openwam/dataloader/registry.py
index 3db5beb..dc2aae1 100644
--- a/openwam/dataloader/registry.py
+++ b/openwam/dataloader/registry.py
@@ -79,6 +79,10 @@ def _register_builtins():
from openwam.dataloader.interndata_a1 import InternDataA1Dataset
from openwam.dataloader.libero import LiberoDataset
from openwam.dataloader.mixture import MixtureDataset
+ from openwam.dataloader.mmb import MMBDataset
+ from openwam.dataloader.mmb_canon import MMBCanonDataset
+ from openwam.dataloader.mmb_final import MMBFinalDataset
+ from openwam.dataloader.mmb_v4 import MMBV4Dataset
from openwam.dataloader.oxe_droid import OxeDroidDataset
from openwam.dataloader.robocasa365 import MultiTaskRoboCasa365Dataset
from openwam.dataloader.robocasa_gr1 import MultiRoboCasaGR1Dataset
@@ -102,6 +106,10 @@ def _register_builtins():
# points at a bucket or at the dataset root.
register_dataset("interndata_a1")(InternDataA1Dataset)
register_dataset("vlabench")(VLABenchDataset)
+ register_dataset("mmb")(MMBDataset)
+ register_dataset("mmb_canon")(MMBCanonDataset)
+ register_dataset("mmb_final")(MMBFinalDataset)
+ register_dataset("mmb_v4")(MMBV4Dataset)
_register_builtins()
diff --git a/configs/dataloader/mmb.yaml b/configs/dataloader/mmb.yaml
new file mode 100644
index 0000000..e495c06
--- /dev/null
+++ b/configs/dataloader/mmb.yaml
+type: mmb
+
+# MobileManipBench (prlq/mobilemanipbench-data @356ec43), merged to one LeRobot v2.1
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_ow
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_canon.yaml b/configs/dataloader/mmb_canon.yaml
new file mode 100644
index 0000000..baa6507
--- /dev/null
+++ b/configs/dataloader/mmb_canon.yaml
+type: mmb_canon
+
+# MobileManipBench, canonical action protocol v2 (openwam/dataloader/mmb_canon.py): chunk-start base-frame EEF delta.
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_ow
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_final.yaml b/configs/dataloader/mmb_final.yaml
new file mode 100644
index 0000000..c33301b
--- /dev/null
+++ b/configs/dataloader/mmb_final.yaml
+type: mmb_final
+
+# MobileManipBench, final canonical definition (openwam/dataloader/mmb_final.py; shared convert_merge.py output per robot).
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_hf
+robots: [go2_arm, sawyer_umi, stretch3]
+
+# alpha temporal contract: 32-action chunk, 9 video frames
+num_frames: 33
+video_stride: 4
+window_stride: 1
+split: train
+
+# 3-slot canvas [head, wrist, black]
+height: 384
+width: 320
+multiview: true
+
+# alpha fixes min-max (rot6d and gripper pinned to identity); stats per robot
+normalize_mode: min-max
+
+color_jitter:
+ enabled: false
diff --git a/configs/dataloader/mmb_v4.yaml b/configs/dataloader/mmb_v4.yaml
new file mode 100644
index 0000000..2a743c6
--- /dev/null
+++ b/configs/dataloader/mmb_v4.yaml
+type: mmb_v4
+
+# MobileManipBench, final definition 11-14 (openwam/dataloader/mmb_v4.py; shared convert_merge.py @ 8d0b031 output per robot).
+# dataset per robot under dataset_dir (see openwam/dataloader/mmb.py for the slot map).
+dataset_dir: /home/teams/posttraining/changyi_tmp/gr00t_mmb/merged_v4
+robots: [go2_arm, sawyer_umi, stretch3]
+