File size: 5,040 Bytes
0a3f650
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
"""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)