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