Download fair-comparison/flow-v1/code/lim/action_objective.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 6.28 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/action_objective.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/action_objective.py
-
curl -L -o action_objective.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/action_objective.py
6.28 kB
| """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. | |
| """ | |
| 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", | |
| } | |