File size: 6,284 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""Pose ACT loss groups and binary-gripper inference semantics."""

from typing import Any, Literal

import numpy as np
import torch
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, PositiveFloat, model_validator
from torch import nn


class ActionLossConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        extra="forbid", use_attribute_docstrings=True, allow_inf_nan=False
    )
    method: Literal["native", "gripper_bce", "group_balanced"] = "native"
    """Native 3:6:1 L1; 3:6:1 with gripper BCE; or equal means of the three L1 groups."""
    position_axis_weights: tuple[PositiveFloat, PositiveFloat, PositiveFloat] = (
        1.0,
        1.0,
        1.0,
    )
    """XYZ absolute-error weights before averaging in group_balanced only.

    Errors are in the coordinates supplied to the loss, including any fitted
    normalization; this changes no labels, normalization or inference decoding.
    """

    @model_validator(mode="after")
    def check_position_weights(self):
        if self.method != "group_balanced" and self.position_axis_weights != (
            1.0,
            1.0,
            1.0,
        ):
            raise ValueError("Non-default position weights require group_balanced")
        return self


def pose_reconstruction(prediction, actions, config: ActionLossConfig):
    if prediction.shape != actions.shape or actions.shape[-1] != 10:
        raise ValueError(
            "Pose objectives require matching ten-dimensional action chunks"
        )
    position = F.l1_loss(prediction[..., :3], actions[..., :3])
    rotation = F.l1_loss(prediction[..., 3:9], actions[..., 3:9])
    groups = {"position_l1": position, "rotation_l1": rotation}
    if config.method == "gripper_bce":
        labels = (actions[..., -1] + 1) / 2
        gripper = F.binary_cross_entropy_with_logits(prediction[..., -1], labels)
        reconstruction = 0.3 * position + 0.6 * rotation + 0.1 * gripper
        groups["gripper_bce"] = gripper
    else:
        gripper = F.l1_loss(prediction[..., -1], actions[..., -1])
        groups["gripper_l1"] = gripper
        if config.method == "group_balanced":
            # Reuse the original tensor/graph at the default, preserving the
            # exact historical loss and gradients rather than multiplying by 1.
            weighted_position = position
            if config.position_axis_weights != (1.0, 1.0, 1.0):
                weighted_position = (
                    (prediction[..., :3] - actions[..., :3]).abs()
                    * prediction.new_tensor(config.position_axis_weights)
                ).mean()
            groups["weighted_position_l1"] = weighted_position
            reconstruction = (weighted_position + rotation + gripper) / 3
        else:
            reconstruction = F.l1_loss(prediction, actions)
    return {"reconstruction": reconstruction, **groups}


def validate_binary_gripper(dataset):
    """Validate every unpadded training label once; padding holds its final label."""
    for actions in dataset.trajectories["actions"]:
        gripper = actions[..., -1]
        if not torch.all((gripper == -1) | (gripper == 1)):
            raise ValueError("Binary gripper supervision requires exactly -1/+1 labels")


class BinaryGripperModelConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    model: Any
    """Native CVAE; the last output coordinate is a logit during training."""


class BinaryGripperModel(nn.Module):
    def __init__(self, config: BinaryGripperModelConfig):
        super().__init__()
        self.config = config
        self.base = config.model

    def forward(self, obs, actions=None):
        prediction, latent = self.base(obs, actions)
        if actions is None:
            # Native temporal aggregation averages 2*p(open)-1, equivalent to
            # averaging probabilities. Do not threshold each chunk in isolation.
            prediction = torch.cat(
                [prediction[..., :-1], 2 * prediction[..., -1:].sigmoid() - 1], dim=-1
            )
        return prediction, latent


class BinaryGripperEnvConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    env: Any
    """Physical environment receiving controller commands after temporal averaging."""


class BinaryGripperEnv:
    def __init__(self, config: BinaryGripperEnvConfig):
        self.config = config
        self.commands = 0
        self.open_commands = 0
        self.close_commands = 0
        self.switches = 0
        self.previous_gripper = None

    def __getattr__(self, name):
        return getattr(self.config.env, name)

    def reset(self, *args, **kwargs):
        self.previous_gripper = None
        return self.config.env.reset(*args, **kwargs)

    def step(self, action):
        command = np.array(action, copy=True)
        score = command[..., -1]
        if not np.isfinite(score).all():
            raise ValueError("Nonfinite ensembled gripper probability")
        gripper = np.where(score >= 0, 1.0, -1.0)
        command[..., -1] = gripper  # p(open)>=0.5 opens, including exact ties.
        self.commands += gripper.size
        self.open_commands += int((gripper == 1).sum())
        self.close_commands += int((gripper == -1).sum())
        if self.previous_gripper is not None:
            self.switches += int(
                (
                    np.isfinite(self.previous_gripper)
                    & (self.previous_gripper != gripper)
                ).sum()
            )
        result = self.config.env.step(command)
        # Vector SAME_STEP autoreset starts a new episode after this last command.
        done = np.asarray(result[2]) | np.asarray(result[3])
        self.previous_gripper = np.where(done, np.nan, gripper)
        return result

    def diagnostics(self):
        return {
            "commands": self.commands,
            "open_commands": self.open_commands,
            "close_commands": self.close_commands,
            "within_episode_switches": self.switches,
            "rule": "average p(open) with native weights; >=0.5 opens; no hysteresis",
        }