File size: 9,118 Bytes
d26db08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Pose ACT loss groups and binary-gripper inference semantics."""

import hashlib
from typing import Any, Literal

import numpy as np
import torch
import torch.nn.functional as F
from pydantic import (
    BaseModel,
    ConfigDict,
    NonNegativeFloat,
    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.
    """
    group_weights: tuple[NonNegativeFloat, NonNegativeFloat, NonNegativeFloat] = (
        1.0,
        1.0,
        1.0,
    )
    """Position, rotation and gripper multipliers inside the group_balanced mean.

    The reconstruction is (w_p L_p + w_R L_R + w_g L_g) / 3: (0.9, 1.8, 0.3)
    is the per-coordinate 3:6:1 mean, (1, 1, 0) drops the gripper term with
    the pose terms unchanged.
    """
    gripper_objective: Literal["l1", "bce"] = "l1"
    """group_balanced only: the gripper group as L1 on +-1, or BCE on its logit
    (then decoded as 2 p(open) - 1, as gripper_bce)."""

    @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)
            or self.group_weights != (1.0, 1.0, 1.0)
            or self.gripper_objective != "l1"
        ):
            raise ValueError(
                "Non-default position or group weights and the gripper objective"
                " require group_balanced"
            )
        if not any(self.group_weights[:2]):
            raise ValueError("At least one pose group must keep a positive weight")
        return self

    @property
    def binary_gripper(self):
        """Whether the last output is a gripper logit with binary execution."""
        return self.method == "gripper_bce" or self.gripper_objective == "bce"

    @property
    def plain_groups(self):
        """group_balanced with its historical equal groups and L1 gripper."""
        return (
            self.method == "group_balanced"
            and self.group_weights == (1.0, 1.0, 1.0)
            and self.gripper_objective == "l1"
        )


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:
        if config.gripper_objective == "bce":
            labels = (actions[..., -1] + 1) / 2
            gripper = F.binary_cross_entropy_with_logits(prediction[..., -1], labels)
            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
            if config.group_weights == (1.0, 1.0, 1.0):
                reconstruction = (weighted_position + rotation + gripper) / 3
            else:
                w_p, w_r, w_g = config.group_weights
                reconstruction = (
                    w_p * weighted_position + w_r * rotation + w_g * 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


def unwrapped_state_sha256(model):
    """Hash parameters/buffers as named without the BinaryGripperModel wrapper.

    The wrapper draws no RNG and adds no parameters, so with the same seed this
    equals the full initial-state hash of the same recipe with an L1 gripper.
    """
    prefixes = [f"{name}." for name, m in model.named_modules() if isinstance(m, BinaryGripperModel)]
    if len(prefixes) != 1:
        raise ValueError("Expected exactly one binary-gripper wrapper")
    wrapped = prefixes[0] + "base."
    digest = hashlib.sha256()
    for name, tensor in model.state_dict().items():
        if not name.startswith(wrapped):
            raise ValueError(f"State outside the wrapped model: {name}")
        digest.update((prefixes[0] + name[len(wrapped):]).encode())
        digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
    return digest.hexdigest()


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",
        }