Download fair-comparison/flow-v1/code/lim/action_encoding.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 5.04 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/action_encoding.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/action_encoding.py
-
curl -L -o action_encoding.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/action_encoding.py
5.04 kB
| """Continuous 6D rotation targets, distinct from the low-level controller ABI.""" | |
| from typing import Any, Literal | |
| import gymnasium as gym | |
| import numpy as np | |
| import torch | |
| from mani_skill.utils.geometry.rotation_conversions import ( | |
| euler_angles_to_matrix, | |
| matrix_to_euler_angles, | |
| ) | |
| from pydantic import BaseModel, ConfigDict | |
| ActionEncoding = Literal["controller", "rotation6d"] | |
| ROTATION_SCALE = -0.1 # Installed ManiSkill 3.0.1 CPU PDEEPoseController. | |
| SIXD_SCALE = 0.1 # Affine label scaling; zero is the identity rotation. | |
| def encoded_dimension(controller_dimension, encoding): | |
| if encoding == "controller": | |
| return controller_dimension | |
| if encoding != "rotation6d" or controller_dimension != 7: | |
| raise ValueError("Rotation6D requires the seven-dimensional pose controller") | |
| return 10 | |
| def matrix_to_sixd(matrix): | |
| identity = torch.eye(3, dtype=matrix.dtype, device=matrix.device)[:, :2] | |
| return ((matrix[..., :, :2] - identity) / SIXD_SCALE).flatten(-2) | |
| def sixd_to_matrix(sixd): | |
| if not torch.isfinite(sixd).all(): | |
| raise ValueError("Nonfinite 6D rotation") | |
| identity = torch.eye(3, dtype=sixd.dtype, device=sixd.device) | |
| columns = sixd.reshape(*sixd.shape[:-1], 3, 2) * SIXD_SCALE + identity[:, :2] | |
| first, second = columns[..., 0], columns[..., 1] | |
| norm = torch.linalg.vector_norm(first, dim=-1, keepdim=True) | |
| x = torch.where(norm > 1e-6, first / norm.clamp(min=1e-6), identity[:, 0]) | |
| second = second - (second * x).sum(-1, keepdim=True) * x | |
| norm = torch.linalg.vector_norm(second, dim=-1, keepdim=True) | |
| # Undefined zero/collinear network outputs get a deterministic orthogonal basis. | |
| basis = identity[x.abs().argmin(-1)] | |
| fallback = basis - (basis * x).sum(-1, keepdim=True) * x | |
| fallback = fallback / torch.linalg.vector_norm(fallback, dim=-1, keepdim=True) | |
| y = torch.where(norm > 1e-6, second / norm.clamp(min=1e-6), fallback) | |
| return torch.stack([x, y, torch.linalg.cross(x, y, dim=-1)], dim=-1) | |
| def controller_to_sixd(actions): | |
| if actions.shape[-1] != 7: | |
| raise ValueError("Expected seven-dimensional controller commands") | |
| rotation = actions[..., 3:6] | |
| rotation = rotation / torch.linalg.vector_norm( | |
| rotation, dim=-1, keepdim=True | |
| ).clamp(min=1) | |
| matrix = euler_angles_to_matrix(rotation * ROTATION_SCALE, "XYZ") | |
| return torch.cat([actions[..., :3], matrix_to_sixd(matrix), actions[..., -1:]], -1) | |
| def sixd_to_controller(actions): | |
| if actions.shape[-1] != 10 or not torch.isfinite(actions).all(): | |
| raise ValueError("Expected finite ten-dimensional policy actions") | |
| matrix = sixd_to_matrix(actions[..., 3:9]) | |
| # A 0.2-rad SO(3) ball avoids gimbal lock and contains all valid controller | |
| # rotations: Euler norm<=0.1 implies angle<=sqrt(3)*0.1. Do not cap at0.1: | |
| # some valid compound Euler commands have a geodesic angle slightly above0.1. | |
| from mani_skill.utils.geometry.rotation_conversions import ( | |
| axis_angle_to_matrix, | |
| matrix_to_axis_angle, | |
| ) | |
| vector = matrix_to_axis_angle(matrix) | |
| angle = torch.linalg.vector_norm(vector, dim=-1, keepdim=True) | |
| bounded = axis_angle_to_matrix(vector * (0.2 / angle.clamp(min=1e-8)).clamp(max=1)) | |
| euler = matrix_to_euler_angles(bounded, "XYZ") / ROTATION_SCALE | |
| euler = euler / torch.linalg.vector_norm(euler, dim=-1, keepdim=True).clamp(min=1) | |
| return torch.cat([actions[..., :3], euler, actions[..., -1:]], -1) | |
| def encode_dataset_actions(dataset, encoding): | |
| if encoding == "controller": | |
| return dataset | |
| if encoding != "rotation6d" or not dataset.delta_control: | |
| raise ValueError("Expected unnormalized delta-control demonstration labels") | |
| # Precompute once. RGB, sample ordering, original H5, and temporal slices stay intact. | |
| dataset.trajectories["actions"] = [ | |
| controller_to_sixd(a) for a in dataset.trajectories["actions"] | |
| ] | |
| dataset.pad_action_arm = torch.zeros(9) | |
| return dataset | |
| class EncodedEnvConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict(arbitrary_types_allowed=True, extra="forbid") | |
| env: Any | |
| """Native evaluator transport; step receives ensembled policy coordinates.""" | |
| class Rotation6DEnv: | |
| def __init__(self, config: EncodedEnvConfig): | |
| self.config = config | |
| if config.env.action_space.shape[-1] != 7: | |
| raise ValueError( | |
| "Rotation6D transport requires a seven-dimensional controller" | |
| ) | |
| self.action_space = gym.spaces.Box( | |
| -np.inf, np.inf, (config.env.num_envs, 10), dtype=np.float32 | |
| ) | |
| self.single_action_space = gym.spaces.Box( | |
| -np.inf, np.inf, (10,), dtype=np.float32 | |
| ) | |
| def __getattr__(self, name): | |
| return getattr(self.config.env, name) | |
| def step(self, actions): | |
| # Called AFTER the pinned evaluator averages overlapping 10D predictions. | |
| command = sixd_to_controller(torch.as_tensor(actions)).numpy() | |
| return self.config.env.step(command) | |