Download fair-comparison/flow-v1/code/lim/keypose_dense.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 5.09 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/keypose_dense.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/keypose_dense.py
-
curl -L -o keypose_dense.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/keypose_dense.py
5.09 kB
| """Dense future supervision sharing the decoder; never a deployed control branch.""" | |
| import hashlib | |
| from pathlib import Path | |
| from types import SimpleNamespace | |
| from typing import Any | |
| import torch | |
| from pydantic import BaseModel, ConfigDict, PositiveInt | |
| from torch import nn | |
| from torch.utils.data import Dataset | |
| from lim.action_encoding import controller_to_sixd | |
| from lim.normalization import ( | |
| FitNormalizationConfig, | |
| NormalizationConfig, | |
| fit_normalization, | |
| ) | |
| class DenseAuxiliaryHeadConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| primary: nn.Module | |
| """Existing action/stop projections, preserving their parameters and output.""" | |
| hidden_size: PositiveInt | |
| """Native decoder feature width; the experiment retains 256.""" | |
| class DenseAuxiliaryHead(nn.Module): | |
| def __init__(self, config: DenseAuxiliaryHeadConfig): | |
| super().__init__() | |
| self.config = config | |
| self.primary = config.primary | |
| parameter = next(self.primary.parameters()) | |
| devices = [parameter.device.index] if parameter.is_cuda else [] | |
| with torch.random.fork_rng(devices=devices): | |
| self.dense = nn.Linear( | |
| config.hidden_size, 10, device=parameter.device, dtype=parameter.dtype | |
| ) | |
| self.dense_actions = None | |
| def forward(self, features): | |
| if features.ndim != 3 or features.shape[-1] != self.config.hidden_size: | |
| raise ValueError("Expected native batch x query x hidden decoder features") | |
| output = self.primary(features) | |
| self.dense_actions = self.dense(features) | |
| return output | |
| def read_dense_actions(model): | |
| heads = [part for part in model.modules() if isinstance(part, DenseAuxiliaryHead)] | |
| if len(heads) != 1 or heads[0].dense_actions is None: | |
| raise ValueError( | |
| "Expected exactly one dense auxiliary head with a completed forward" | |
| ) | |
| return heads[0].dense_actions | |
| def primary_state_sha256(model): | |
| """Recover the existing stop model's full initial state without the dense head.""" | |
| result = hashlib.sha256() | |
| for name, value in model.state_dict().items(): | |
| if ".action_head.dense." in name: | |
| continue | |
| name = name.replace(".action_head.primary.", ".action_head.") | |
| result.update(name.encode()) | |
| result.update(value.detach().cpu().contiguous().numpy().tobytes()) | |
| return result.hexdigest() | |
| class DenseAuxiliaryDatasetConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| dataset: Any | |
| """Unnormalized current-keypose dataset; its native dataset retains raw control7.""" | |
| source: Path | |
| """Same H5 used for primary keyposes; no extra demonstration or observation.""" | |
| normalization: NormalizationConfig | |
| """The original dense action-zscore algorithm, separately fitted from raw actions.""" | |
| class DenseAuxiliaryDataset(Dataset): | |
| def __init__(self, config: DenseAuxiliaryDatasetConfig): | |
| self.config = config | |
| self.dataset = config.dataset | |
| native = self.dataset.dataset | |
| if ( | |
| self.dataset.slices != native.slices | |
| or self.dataset.num_queries != 30 | |
| or not native.delta_control | |
| or native.norm_stats is not None | |
| or config.normalization.method != "action_zscore" | |
| ): | |
| raise ValueError( | |
| "Dense auxiliary requires all original Q30 raw delta observations" | |
| ) | |
| self.dense = [ | |
| controller_to_sixd(action) for action in native.trajectories["actions"] | |
| ] | |
| population = SimpleNamespace( | |
| delta_control=True, | |
| norm_stats=None, | |
| trajectories={**native.trajectories, "actions": self.dense}, | |
| ) | |
| self.dense_statistics = fit_normalization( | |
| FitNormalizationConfig( | |
| dataset=population, | |
| normalization=config.normalization, | |
| action_encoding="rotation6d", | |
| source=config.source, | |
| ) | |
| ) | |
| self.center = torch.tensor(self.dense_statistics.action.center) | |
| self.scale = torch.tensor(self.dense_statistics.action.scale) | |
| def __getattr__(self, name): | |
| return getattr(self.dataset, name) | |
| def __len__(self): | |
| return len(self.dataset) | |
| def __getitem__(self, index): | |
| sample = self.dataset[index] | |
| trajectory, step = self.dataset.slices[index] | |
| actions = self.dense[trajectory][step : step + self.num_queries] | |
| if len(actions) < self.num_queries: | |
| # Native delta padding: zero arm motion, retain last continuous gripper. | |
| pad = torch.cat([actions.new_zeros(9), actions[-1, -1:]]) | |
| actions = torch.cat( | |
| [actions, pad.repeat(self.num_queries - len(actions), 1)] | |
| ) | |
| return {**sample, "dense_actions": (actions - self.center) / self.scale} | |