diff --git a/src/openpi/models/gemma.py b/src/openpi/models/gemma.py index d1623d1..364d8cb 100644 --- a/src/openpi/models/gemma.py +++ b/src/openpi/models/gemma.py @@ -1,3 +1,4 @@ +import os # Copyright 2024 Big Vision Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); @@ -213,22 +214,26 @@ class Attention(nn.Module): k = jnp.concatenate([cache_k, k], axis=1) v = jnp.concatenate([cache_v, v], axis=1) - q = einops.rearrange(q, "B T (K G) H -> B T K G H", K=self.configs[0].num_kv_heads) - logits = jnp.einsum("BTKGH,BSKH->BKGTS", q, k, preferred_element_type=jnp.float32) - if attn_mask.shape != (q.shape[0], 1, q.shape[1], k.shape[1]): raise ValueError( f"Attention mask with shape {attn_mask.shape} but shapes for q and k are: {q.shape} and {k.shape}" ) - # big_neg = jnp.finfo(logits.dtype).min - big_neg = -2.3819763e38 # See gemma/modules.py - masked_logits = jnp.where(attn_mask[:, :, None, :, :], logits, big_neg) + if os.environ.get("OPENPI_ATTN_IMPL") == "cudnn": + # Fused cuDNN attention (same math; q is already scaled above, so scale=1). Opt-in via env var. + encoded = jax.nn.dot_product_attention(q, k, v, mask=attn_mask, scale=1.0, implementation="cudnn") + else: + q = einops.rearrange(q, "B T (K G) H -> B T K G H", K=self.configs[0].num_kv_heads) + logits = jnp.einsum("BTKGH,BSKH->BKGTS", q, k, preferred_element_type=jnp.float32) + + # big_neg = jnp.finfo(logits.dtype).min + big_neg = -2.3819763e38 # See gemma/modules.py + masked_logits = jnp.where(attn_mask[:, :, None, :, :], logits, big_neg) - probs = jax.nn.softmax(masked_logits, axis=-1).astype(dtype) + probs = jax.nn.softmax(masked_logits, axis=-1).astype(dtype) - encoded = jnp.einsum("BKGTS,BSKH->BTKGH", probs, v) - encoded = einops.rearrange(encoded, "B T K G H -> B T (K G) H") + encoded = jnp.einsum("BKGTS,BSKH->BTKGH", probs, v) + encoded = einops.rearrange(encoded, "B T K G H -> B T (K G) H") out = [] start = 0 diff --git a/src/openpi/models/pi0.py b/src/openpi/models/pi0.py index ae7c459..483b164 100644 --- a/src/openpi/models/pi0.py +++ b/src/openpi/models/pi0.py @@ -1,4 +1,5 @@ import logging +import os import einops import flax.nnx as nnx @@ -110,7 +111,13 @@ class Pi0(_model.BaseModel): ar_mask = [] tokens = [] # embed images + # OPENPI_SKIP_IMAGE_KEYS: comma-separated image keys that are ALWAYS masked out in this dataset (e.g. the + # zero-filled right wrist view of MobileManipBench). Their tokens never contribute (input_mask=False removes + # them from attention and from the cumsum positions), so skipping them is exact and saves their compute. + skip = {k for k in os.environ.get("OPENPI_SKIP_IMAGE_KEYS", "").split(",") if k} for name in obs.images: + if name in skip: + continue image_tokens, _ = self.PaliGemma.img(obs.images[name], train=False) tokens.append(image_tokens) diff --git a/src/openpi/training/config.py b/src/openpi/training/config.py index 4ca47e1..eb9874c 100644 --- a/src/openpi/training/config.py +++ b/src/openpi/training/config.py @@ -20,6 +20,7 @@ import openpi.models.tokenizer as _tokenizer import openpi.policies.aloha_policy as aloha_policy import openpi.policies.droid_policy as droid_policy import openpi.policies.libero_policy as libero_policy +import openpi.policies.mmb_policy as mmb_policy import openpi.shared.download as _download import openpi.shared.normalize as _normalize import openpi.training.droid_rlds_dataset as droid_rlds_dataset @@ -86,6 +87,9 @@ class DataConfig: # sequence is defined by the `action_horizon` field in the model config. This should be adjusted if your # LeRobot dataset is using different keys to represent the action. action_sequence_keys: Sequence[str] = ("actions",) + # If set, this key is loaded for frames t .. t+action_horizon (action_horizon + 1 frames); used when the action + # chunk is derived from future states (MobileManipBench v2: actions = f(state(t), state(t+1 .. t+H))). + state_chunk_key: str | None = None # If true, will use the LeRobot dataset task to define the prompt. prompt_from_task: bool = False @@ -355,6 +359,61 @@ class LeRobotLiberoDataConfig(DataConfigFactory): ) +@dataclasses.dataclass(frozen=True) +class LeRobotMMBDataConfig(DataConfigFactory): + """MobileManipBench (all robots) for pi0.5 warm-up. Per-robot quantile normalisation happens in + mmb_policy.PerRobotNormalize; the global Normalize step receives identity statistics. + canonical_v2: Canonical Action Protocol v2 dataset (convert_merge.py --v2); chunks become canonical 12D actions.""" + + canonical_v2: bool = False + # v2 EEF action source: "state" = future measured EEF (state chunk), "target" = expert sparse targets + action_source: str = "state" + # v2 action rotation (relative to the current EEF): "rot6d" (14D action) or legacy "rpy" (11D: pi05_mmb_v2 / v2t) + action_rot: str = "rot6d" + # v2 EEF action reference: None = module default (rot6d: "base" = target pose in the body frame); "eef" = relative + action_ref: str | None = None + + @override + def create(self, assets_dirs: pathlib.Path, model_config: _model.BaseModelConfig) -> DataConfig: + base = self.create_base_config(assets_dirs, model_config) + stats_dir = pathlib.Path(self.assets.assets_dir or assets_dirs) / (self.assets.asset_id or self.repo_id) + per_robot = mmb_policy.load_per_robot_stats(stats_dir / mmb_policy.PER_ROBOT_STATS_FILE) + repack_transform = _transforms.Group( + inputs=[ + _transforms.RepackTransform( + { + "observation/image": "observation.images.head", + "observation/wrist_image": "observation.images.wrist", + # v2: canonical 14D state chunk t .. t+H (base frame, no world coordinates); actions derived from it + "observation/state": "observation.state_canonical" if self.canonical_v2 else "observation.state", + "robot_id": "robot_id", + **({"commands": "action.command"} if self.canonical_v2 else {"actions": "actions"}), + **({"targets": "action.eef_target"} if self.canonical_v2 and self.action_source == "target" else {}), + "prompt": "prompt", + } + ) + ] + ) + data_transforms = _transforms.Group( + inputs=[mmb_policy.MMBInputs(model_type=model_config.model_type), + *([mmb_policy.MMBActionsFromTargets(rot=self.action_rot, ref=self.action_ref) if self.action_source == "target" + else mmb_policy.MMBActionsFromStates(rot=self.action_rot, ref=self.action_ref)] + if self.canonical_v2 else []), + mmb_policy.PerRobotNormalize(per_robot)], + ) + return dataclasses.replace( + base, + repack_transforms=repack_transform, + data_transforms=data_transforms, + model_transforms=ModelTransformFactory()(model_config), + # v2: no action column; the chunk is built from state(t .. t+H) of the canonical state column + **(({"action_sequence_keys": ("action.command", "action.eef_target"), "state_chunk_key": None} + if self.action_source == "target" else + {"action_sequence_keys": ("action.command",), "state_chunk_key": "observation.state_canonical"}) + if self.canonical_v2 else {}), + ) + + @dataclasses.dataclass(frozen=True) class RLDSDroidDataConfig(DataConfigFactory): """ @@ -740,6 +799,137 @@ _CONFIGS = [ # Turn off EMA for LoRA finetuning. ema_decay=None, ), + TrainConfig( + # pi0.5 full fine-tuning "warm-up" on all of prlq/mobilemanipbench-data (rev 356ec43), 3 robots, 80k steps. + # Recipe = pi05_libero except: steps, batch (multiple of 6 GPUs), loader workers, checkpoint cadence. + name="pi05_mmb_warmup", + model=pi0_config.Pi0Config(pi05=True, action_horizon=10, discrete_state_input=False), + data=LeRobotMMBDataConfig( + repo_id="mmb/all", + base_config=DataConfig(prompt_from_task=True), + ), + batch_size=252, + lr_schedule=_optimizer.CosineDecaySchedule( + warmup_steps=10_000, + peak_lr=5e-5, + decay_steps=1_000_000, + decay_lr=5e-5, + ), + optimizer=_optimizer.AdamW(clip_gradient_norm=1.0), + ema_decay=0.999, + weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"), + num_train_steps=80_000, + num_workers=80, # 48 saturated (~37 cores busy, occasional 3 s steps); node has ~70% CPU idle + save_interval=2000, # ~45 min at 1.3 s/step (each 42 GB save stalls training ~1 min) + keep_period=10_000, + wandb_enabled=False, + ), + TrainConfig( + # Canonical Action Protocol v2 (docs/writing-block.md): same recipe as pi05_mmb_warmup, fresh from pi05_base, + # on the v2 dataset (raw chunks -> canonical 12D chunk-relative actions at load time, new per-robot stats). + name="pi05_mmb_v2", + # discrete_state_input=True: the canonical 12D state is discretised (256 bins) into the prompt, the native pi0.5 + # way; with False (pi05_libero / pi05_mmb_warmup) pi0.5 ignores the state entirely. + model=pi0_config.Pi0Config(pi05=True, action_horizon=10, discrete_state_input=True), + data=LeRobotMMBDataConfig( + repo_id="mmb/v2", + base_config=DataConfig(prompt_from_task=True), + canonical_v2=True, + action_rot="rpy", + ), + batch_size=252, + lr_schedule=_optimizer.CosineDecaySchedule( + warmup_steps=10_000, + peak_lr=5e-5, + decay_steps=1_000_000, + decay_lr=5e-5, + ), + optimizer=_optimizer.AdamW(clip_gradient_norm=1.0), + ema_decay=0.999, + weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"), + num_train_steps=80_000, + num_workers=80, + save_interval=2000, + keep_period=10_000, + wandb_enabled=False, + ), + TrainConfig( + # v2 with the EEF action from the expert sparse targets (yiqi 11-13); otherwise identical to pi05_mmb_v2. + # Canonical Action Protocol v2 (docs/writing-block.md): same recipe as pi05_mmb_warmup, fresh from pi05_base, + # on the v2 dataset (raw chunks -> canonical 12D chunk-relative actions at load time, new per-robot stats). + name="pi05_mmb_v2t", + # discrete_state_input=True: the canonical 12D state is discretised (256 bins) into the prompt, the native pi0.5 + # way; with False (pi05_libero / pi05_mmb_warmup) pi0.5 ignores the state entirely. + model=pi0_config.Pi0Config(pi05=True, action_horizon=10, discrete_state_input=True), + data=LeRobotMMBDataConfig( + repo_id="mmb/v2t", + base_config=DataConfig(prompt_from_task=True), + canonical_v2=True, + action_source="target", + action_rot="rpy", + ), + batch_size=252, + lr_schedule=_optimizer.CosineDecaySchedule( + warmup_steps=10_000, + peak_lr=5e-5, + decay_steps=1_000_000, + decay_lr=5e-5, + ), + optimizer=_optimizer.AdamW(clip_gradient_norm=1.0), + ema_decay=0.999, + weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"), + num_train_steps=80_000, + num_workers=80, + save_interval=2000, + keep_period=10_000, + wandb_enabled=False, + ), + TrainConfig( + # v3 (yiqi 11-13/14): EEF action = the expert sparse target pose seen from the body frame (the base projected to + # the floor, heading only - same reference on all robots), all rotations rot6d (first two columns) - the 14D + # action [base cmd 4 | target xyz 3 | target rot6d 6 | gripper cmd 1]; dataset merged_v2t (patch_frame.py + # --frame ground); same recipe as pi05_mmb_v2; stats assets/pi05_mmb_v3/mmb/v2t (compute_stats_v3.py: base + + # EEF xyz one q01/q99 set for all robots and for state and action; rot6d and gripper not normalised). + name="pi05_mmb_v3", + # discrete_state_input=True: the canonical 14D state is discretised (256 bins) into the prompt, the native pi0.5 + # way; with False pi0.5 ignores the state entirely. + model=pi0_config.Pi0Config(pi05=True, action_horizon=10, discrete_state_input=True), + data=LeRobotMMBDataConfig( + repo_id="mmb/v2t", + base_config=DataConfig(prompt_from_task=True), + canonical_v2=True, + action_source="target", + action_rot="rot6d", + ), + batch_size=252, + lr_schedule=_optimizer.CosineDecaySchedule( + warmup_steps=10_000, + peak_lr=5e-5, + decay_steps=1_000_000, + decay_lr=5e-5, + ), + optimizer=_optimizer.AdamW(clip_gradient_norm=1.0), + ema_decay=0.999, + weight_loader=weight_loaders.CheckpointWeightLoader("gs://openpi-assets/checkpoints/pi05_base/params"), + num_train_steps=80_000, + num_workers=80, + save_interval=2000, + keep_period=10_000, + wandb_enabled=False, + ), + TrainConfig( + # Compute-only speed benchmark for pi05_mmb_warmup (same model/batch, fake data, random init). + name="pi05_mmb_bench", + model=pi0_config.Pi0Config(pi05=True, action_horizon=10, discrete_state_input=False), + data=FakeDataConfig(), + batch_size=252, + num_workers=16, + num_train_steps=45, + log_interval=10, + save_interval=100000, + overwrite=True, + wandb_enabled=False, + ), TrainConfig( name="pi05_libero", model=pi0_config.Pi0Config(pi05=True, action_horizon=10, discrete_state_input=False), diff --git a/src/openpi/training/data_loader.py b/src/openpi/training/data_loader.py index e2ee7dd..8a69450 100644 --- a/src/openpi/training/data_loader.py +++ b/src/openpi/training/data_loader.py @@ -141,8 +141,13 @@ def create_torch_dataset( dataset = lerobot_dataset.LeRobotDataset( data_config.repo_id, delta_timestamps={ - key: [t / dataset_meta.fps for t in range(action_horizon)] for key in data_config.action_sequence_keys + **{key: [t / dataset_meta.fps for t in range(action_horizon)] for key in data_config.action_sequence_keys}, + # actions derived from future states: frames t .. t+H of this key (see DataConfig.state_chunk_key) + **({data_config.state_chunk_key: [t / dataset_meta.fps for t in range(action_horizon + 1)]} + if data_config.state_chunk_key else {}), }, + # B300 cluster: torchcodec has no FFmpeg shared libs here; PyAV bundles FFmpeg (with libdav1d for AV1). + video_backend=os.environ.get("OPENPI_VIDEO_BACKEND") or None, ) if data_config.prompt_from_task: diff --git a/src/openpi/policies/mmb_canonical_action.py b/src/openpi/policies/mmb_canonical_action.py new file mode 100644 index 0000000..a2eaae4 --- /dev/null +++ b/src/openpi/policies/mmb_canonical_action.py @@ -0,0 +1,485 @@ +"""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____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 asset_offset(robot, base_quat, state): + """Online / per-episode: the constant asset-frame offset c (axis-aligned rotation, identity except e.g. Sawyer + N051/N053/N058/N059 Ry(-90 deg)) from the simulator base_quat [..., 4] (w-x-y-z, same link as sim_states.npz) and + the raw observation.state [..., D] of one or more frames of the episode. Compute once per episode, then use + base_pose_online for every frame. Same rule as base_pose_from_sim_states.""" + q = qnorm(np.atleast_2d(np.asarray(base_quat, np.float64))) + off = qmul(qconj(qnorm(base_heading_pose(robot, np.atleast_2d(np.asarray(state, np.float64)))[..., 3:7])), q) + return AXIS_ALIGNED_QUATS[int(np.argmax(np.abs(off @ AXIS_ALIGNED_QUATS.T).sum(0)))] + + +def base_pose_online(base_pos, base_quat, offset): + """Online: measured base pose [..., 7] = [x, y, z, qw, qx, qy, qz] with the asset offset removed (as stored in + observation.base_pose), from the simulator base_pos [..., 3] / base_quat [..., 4] taken at the observation time.""" + q = qnorm(qmul(qnorm(np.asarray(base_quat, np.float64)), qconj(np.asarray(offset, np.float64)))) + q = np.where(q[..., :1] < 0, -q, q) + return np.concatenate([np.asarray(base_pos, np.float64), q], -1) + + +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/src/openpi/policies/mmb_policy.py b/src/openpi/policies/mmb_policy.py new file mode 100644 index 0000000..f4b3275 --- /dev/null +++ b/src/openpi/policies/mmb_policy.py @@ -0,0 +1,169 @@ +"""MobileManipBench (prlq/mobilemanipbench-data) inputs/outputs for pi0.5 warm-up on all three robots. + +Dataset (built by /data/changyi/mmb/convert_merge.py): actions[12] and observation.state[26] are each robot's +raw vectors zero-padded (no semantic alignment across robots, as in pi0 pretraining); robot_id selects the +robot's own normalisation statistics (PerRobotNormalize). The global openpi Normalize step is fed identity +statistics, so all real normalisation happens here. + +v2 (dataset built with convert_merge.py --v2; definitions in mmb_canonical_action.py, shared with GR00T / OpenWAM): +state = observation.state_canonical, 14D [base vel + height | EEF xyz in base frame | EEF rot6d | gripper closure]; +actions = built by MMBActionsFromTargets (expert sparse targets action.eef_target at t .. t+H-1) or MMBActionsFromStates +(future measured states t+1 .. t+H), 14D per step [recorded base command | EEF target xyz in the body frame | EEF +target rot6d in the body frame | recorded gripper command] (rot="rot6d", ref="base", default; legacy ref="eef": +relative to the current EEF; legacy rot="rpy": 11D, relative, roll/pitch/yaw) - the only training-time processing +besides chunking and normalisation. Inactive dimensions (sawyer height; stretch vy, height) are exactly 0 before and after +normalisation; like openpi's 32D padding they DO contribute to the flow-matching loss (target 0). MMBOutputs zeros +them again at inference. +""" +import dataclasses +import json +import pathlib + +import einops +import numpy as np + +from openpi import transforms +from openpi.models import model as _model +from openpi.policies import mmb_canonical_action as canon + +ROBOT_NAMES = {0: "go2_arm", 1: "sawyer_umi", 2: "stretch3"} +ACTION_DIMS = {0: 12, 1: 11, 2: 11} +PER_ROBOT_STATS_FILE = "norm_stats_per_robot.json" + + +def _parse_image(image) -> np.ndarray: + image = np.asarray(image) + if np.issubdtype(image.dtype, np.floating): + image = (255 * image).astype(np.uint8) + if image.shape[0] == 3: + image = einops.rearrange(image, "c h w -> h w c") + return image + + +@dataclasses.dataclass(frozen=True) +class MMBInputs(transforms.DataTransformFn): + model_type: _model.ModelType + + def __call__(self, data: dict) -> dict: + head = _parse_image(data["observation/image"]) + wrist = _parse_image(data["observation/wrist_image"]) + inputs = { + "state": np.asarray(data["observation/state"], np.float32), + "robot_id": int(np.asarray(data["robot_id"]).reshape(-1)[0]), + "image": {"base_0_rgb": head, "left_wrist_0_rgb": wrist, "right_wrist_0_rgb": np.zeros_like(head)}, + "image_mask": { + "base_0_rgb": np.True_, + "left_wrist_0_rgb": np.True_, + "right_wrist_0_rgb": np.True_ if self.model_type == _model.ModelType.PI0_FAST else np.False_, + }, + } + if "actions" in data: + inputs["actions"] = np.asarray(data["actions"], np.float32) + if "prompt" in data: + inputs["prompt"] = data["prompt"] + if "commands" in data: # v2: recorded commands [vx, vy, wz, height, gripper] at t .. t+H-1 + inputs["commands"] = np.asarray(data["commands"], np.float32) + if "targets" in data: # v2 (expert-target variant): expert EEF targets [xyz | rot6d] at t .. t+H-1 + inputs["targets"] = np.asarray(data["targets"], np.float32) + return inputs + + +@dataclasses.dataclass(frozen=True) +class MMBActionsFromStates(transforms.DataTransformFn): + """v2 (training): the state arrives as a chunk state(t .. t+H) [H+1, 14] and the recorded commands as [H, 5]; + the action chunk [H, 14] (rot6d; [H, 11] rpy) is derived from them (canon.action_chunk_from_states) and the + state becomes state(t). Must run before normalisation.""" + + rot: str = "rot6d" + ref: str | None = None + + def __call__(self, data: dict) -> dict: + st = np.asarray(data["state"], np.float64) + if st.ndim == 1: # inference: only the current state + return data + out = dict(data) + robot = ROBOT_NAMES[int(np.asarray(data["robot_id"]).reshape(-1)[0])] + out["actions"] = canon.action_chunk_from_states(robot, st[0], st[1:], out.pop("commands"), self.rot, self.ref).astype(np.float32) + out["state"] = st[0].astype(np.float32) + return out + + +@dataclasses.dataclass(frozen=True) +class MMBActionsFromTargets(transforms.DataTransformFn): + """v2, expert-target variant (training): action chunk [H, 14] (rot6d; [H, 11] rpy) from state(t) [14], the expert + EEF targets [H, 9] and the recorded commands [H, 5] at t .. t+H-1 (canon.action_chunk_from_targets). Before + normalisation.""" + + rot: str = "rot6d" + ref: str | None = None + + def __call__(self, data: dict) -> dict: + if "targets" not in data: # inference + return data + out = dict(data) + robot = ROBOT_NAMES[int(np.asarray(data["robot_id"]).reshape(-1)[0])] + out["actions"] = canon.action_chunk_from_targets(robot, np.asarray(data["state"], np.float64), out.pop("targets"), + out.pop("commands"), self.rot, self.ref).astype(np.float32) + return out + + +def load_per_robot_stats(path: str | pathlib.Path) -> dict: + raw = json.loads(pathlib.Path(path).read_text()) + return {int(rid): {k: {s: np.asarray(v, np.float32) for s, v in d.items()} for k, d in keys.items()} + for rid, keys in raw.items()} + + +def _quantile_norm(x, q01, q99): + span = q99 - q01 + ok = span > 1e-6 # padded / constant dimensions stay exactly 0 + n = x.shape[-1] + q01, span, ok = q01[:n], span[:n], ok[:n] + y = np.where(ok, (x - q01) / np.where(ok, span, 1.0) * 2.0 - 1.0, 0.0) + return y.astype(np.float32) + + +def _quantile_unnorm(y, q01, q99): + span = q99 - q01 + ok = span > 1e-6 + n = y.shape[-1] + q01, span, ok = q01[:n], span[:n], ok[:n] + return np.where(ok, (y + 1.0) / 2.0 * span + q01, 0.0).astype(np.float32) + + +@dataclasses.dataclass(frozen=True) +class PerRobotNormalize(transforms.DataTransformFn): + """Quantile-normalise state and actions with the statistics of the sample's own robot.""" + + stats: dict # robot_id -> {"state"|"actions": {"q01","q99",...}} + + def __call__(self, data: dict) -> dict: + st = self.stats[int(data["robot_id"])] + out = dict(data) + out["state"] = _quantile_norm(np.asarray(data["state"], np.float32), st["state"]["q01"], st["state"]["q99"]) + if "actions" in data: + out["actions"] = _quantile_norm(np.asarray(data["actions"], np.float32), st["actions"]["q01"], st["actions"]["q99"]) + out.pop("robot_id") + return out + + +@dataclasses.dataclass(frozen=True) +class MMBOutputs(transforms.DataTransformFn): + """Inference only: undo the per-robot normalisation and return the robot's own action dimensions. + canonical_v2: return the 14D (rot6d; 11D rpy) action chunk (inactive dims zeroed); the execution adapter converts it to controller + commands with canon.decode_action_chunk(robot, actions, state_t, base_pose_at_execution), where state_t is the + (unnormalised) canonical state of the observation that produced the chunk.""" + + stats: dict + robot_id: int + canonical_v2: bool = False + rot: str = "rot6d" + + def __call__(self, data: dict) -> dict: + st = self.stats[self.robot_id] + n = canon.action_layout(self.rot)[0] if self.canonical_v2 else 12 + a = np.asarray(data["actions"])[..., :n] + a = _quantile_unnorm(a, st["actions"]["q01"], st["actions"]["q99"]) + if not self.canonical_v2: + return {"actions": a[..., : ACTION_DIMS[self.robot_id]]} + robot = ROBOT_NAMES[self.robot_id] + return {"actions": np.where(canon.action_layout(self.rot)[3][robot], a, 0.0).astype(np.float32)} diff --git a/assets/pi05_mmb_v3/mmb/v2t/norm_stats_per_robot.json b/assets/pi05_mmb_v3/mmb/v2t/norm_stats_per_robot.json new file mode 100644 index 0000000..9ce5298 --- /dev/null +++ b/assets/pi05_mmb_v3/mmb/v2t/norm_stats_per_robot.json @@ -0,0 +1 @@ +{"0": {"state": {"q01": [-0.30000001192092896, -0.2997402250766754, -0.7999288439750671, 0.28999999165534973, -0.160398930311203, -0.7775490880012512, 0.16975568234920502, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0], "q99": [0.3499999940395355, 0.16914814397692687, 0.800000011920929, 0.41369785636663436, 0.9592860096693039, 0.2369463916122912, 1.3730802536010742, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "mean": [0.06909525805149054, -0.003308204971539885, 0.019374634107881785, 0.3640675575727502, 0.34041552462654767, -0.15113465219859984, 0.7745604179620226, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "std": [0.138943109349931, 0.04951923437360962, 0.20712037634151662, 0.025289301915518446, 0.2849244620208932, 0.24881026083948993, 0.21464410493892133, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}, "actions": {"q01": [-0.30000001192092896, -0.2997402250766754, -0.7999288439750671, 0.28999999165534973, -0.160398930311203, -0.7775490880012512, 0.16975568234920502, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0], "q99": [0.3499999940395355, 0.16914814397692687, 0.800000011920929, 0.41369785636663436, 0.9592860096693039, 0.2369463916122912, 1.3730802536010742, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "mean": [0.06909525805149054, -0.003308204971539885, 0.019374634107881785, 0.3640675575727502, 0.34041552462654767, -0.15113465219859984, 0.7745604179620226, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "std": [0.138943109349931, 0.04951923437360962, 0.20712037634151662, 0.025289301915518446, 0.2849244620208932, 0.24881026083948993, 0.21464410493892133, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}}, "1": {"state": {"q01": [-0.30000001192092896, -0.2997402250766754, -0.7999288439750671, 0.0, -0.160398930311203, -0.7775490880012512, 0.16975568234920502, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0], "q99": [0.3499999940395355, 0.16914814397692687, 0.800000011920929, 0.0, 0.9592860096693039, 0.2369463916122912, 1.3730802536010742, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "mean": [0.06909525805149054, -0.003308204971539885, 0.019374634107881785, 0.0, 0.34041552462654767, -0.15113465219859984, 0.7745604179620226, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "std": [0.138943109349931, 0.04951923437360962, 0.20712037634151662, 0.0, 0.2849244620208932, 0.24881026083948993, 0.21464410493892133, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}, "actions": {"q01": [-0.30000001192092896, -0.2997402250766754, -0.7999288439750671, 0.0, -0.160398930311203, -0.7775490880012512, 0.16975568234920502, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0], "q99": [0.3499999940395355, 0.16914814397692687, 0.800000011920929, 0.0, 0.9592860096693039, 0.2369463916122912, 1.3730802536010742, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "mean": [0.06909525805149054, -0.003308204971539885, 0.019374634107881785, 0.0, 0.34041552462654767, -0.15113465219859984, 0.7745604179620226, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "std": [0.138943109349931, 0.04951923437360962, 0.20712037634151662, 0.0, 0.2849244620208932, 0.24881026083948993, 0.21464410493892133, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}}, "2": {"state": {"q01": [-0.30000001192092896, 0.0, -0.7999288439750671, 0.0, -0.160398930311203, -0.7775490880012512, 0.16975568234920502, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0], "q99": [0.3499999940395355, 0.0, 0.800000011920929, 0.0, 0.9592860096693039, 0.2369463916122912, 1.3730802536010742, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "mean": [0.06909525805149054, 0.0, 0.019374634107881785, 0.0, 0.34041552462654767, -0.15113465219859984, 0.7745604179620226, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "std": [0.138943109349931, 0.0, 0.20712037634151662, 0.0, 0.2849244620208932, 0.24881026083948993, 0.21464410493892133, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}, "actions": {"q01": [-0.30000001192092896, 0.0, -0.7999288439750671, 0.0, -0.160398930311203, -0.7775490880012512, 0.16975568234920502, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0], "q99": [0.3499999940395355, 0.0, 0.800000011920929, 0.0, 0.9592860096693039, 0.2369463916122912, 1.3730802536010742, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], "mean": [0.06909525805149054, 0.0, 0.019374634107881785, 0.0, 0.34041552462654767, -0.15113465219859984, 0.7745604179620226, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], "std": [0.138943109349931, 0.0, 0.20712037634151662, 0.0, 0.2849244620208932, 0.24881026083948993, 0.21464410493892133, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]}}} \ No newline at end of file diff --git a/assets/pi05_mmb_v3/mmb/v2t/norm_stats.json b/assets/pi05_mmb_v3/mmb/v2t/norm_stats.json new file mode 100644 index 0000000..f60d7f3 --- /dev/null +++ b/assets/pi05_mmb_v3/mmb/v2t/norm_stats.json @@ -0,0 +1,280 @@ +{ + "norm_stats": { + "state": { + "mean": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "std": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "q01": [ + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0 + ], + "q99": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + }, + "actions": { + "mean": [ + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0, + 0.0 + ], + "std": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ], + "q01": [ + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0, + -1.0 + ], + "q99": [ + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0, + 1.0 + ] + } + } +} \ No newline at end of file