Download fair-comparison/flow-v1/code/lim/normalization.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 10.4 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/normalization.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/normalization.py
-
curl -L -o normalization.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/normalization.py
10.4 kB
| """Training-fitted affine transforms, independent of native delta-control stats.""" | |
| import hashlib | |
| from pathlib import Path | |
| from typing import Any, Literal | |
| import torch | |
| from pydantic import ( | |
| BaseModel, | |
| ConfigDict, | |
| Field, | |
| PositiveFloat, | |
| PositiveInt, | |
| model_validator, | |
| ) | |
| from torch import nn | |
| from torch.utils.data import Dataset | |
| from lim.action_encoding import ActionEncoding | |
| class NormalizationConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) | |
| method: Literal["none", "state_zscore", "action_zscore", "action_quantile"] = "none" | |
| """One independent transform; RGB and gripper retain their native treatment.""" | |
| state_floor: tuple[PositiveFloat, ...] = ( | |
| (0.01,) * 7 | |
| + (0.001,) * 2 | |
| + (0.01,) * 7 | |
| + (0.001,) * 2 | |
| + (0.001,) * 3 | |
| + (0.01,) * 4 | |
| ) | |
| """State25 scale floors: joint rad/rad/s .01, finger m/m/s .001, TCP m .001, quaternion .01.""" | |
| action_floor: PositiveFloat = 0.01 | |
| """Minimum std or quantile half-span in ENCODED action coordinates, not physical units.""" | |
| def check_layout(self): | |
| if len(self.state_floor) != 25: | |
| raise ValueError( | |
| "State floors must follow qpos9, qvel9, TCP position3/quaternion4" | |
| ) | |
| return self | |
| class AffineConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| extra="forbid", allow_inf_nan=False, use_attribute_docstrings=True | |
| ) | |
| center: tuple[float, ...] | |
| """Training mean or q01/q99 midpoint, with gripper center fixed to zero.""" | |
| scale: tuple[PositiveFloat, ...] | |
| """Floored std or half-span, with gripper scale fixed to one.""" | |
| def check_lengths(self): | |
| if not self.center or len(self.center) != len(self.scale): | |
| raise ValueError( | |
| "Affine center and scale must have matching nonempty shapes" | |
| ) | |
| return self | |
| class FittedNormalizationConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict(extra="forbid", use_attribute_docstrings=True) | |
| config: NormalizationConfig | |
| """Exact fitting recipe; compared against the declared policy on reload.""" | |
| action_encoding: ActionEncoding | |
| """Coordinates in which action statistics were fitted.""" | |
| source_sha256: str = Field(pattern=r"^[0-9a-f]{64}$") | |
| """Training HDF5 identity, never evaluation data.""" | |
| trajectories: PositiveInt | |
| """Number of loaded training trajectories used to fit statistics.""" | |
| samples: PositiveInt | |
| """Number of unpadded encoded targets fitted; default is one per original obs_t.""" | |
| state: AffineConfig | |
| """State25 transform; identity for action-only candidates.""" | |
| action: AffineConfig | |
| """Encoded action transform; identity for the state-only candidate.""" | |
| def check_contract(self): | |
| dim = len(self.action.center) | |
| if len(self.state.center) != 25 or dim not in ( | |
| # 11: B-spline segment rows, a knot column before target10. | |
| (10, 11) if self.action_encoding == "rotation6d" else (4, 7) | |
| ): | |
| raise ValueError( | |
| "Fitted statistics differ from the supported state/action layout" | |
| ) | |
| if self.config.method == "none": | |
| raise ValueError("The unnormalized control must not have fitted statistics") | |
| if self.action.center[-1] != 0 or self.action.scale[-1] != 1: | |
| raise ValueError("Gripper must remain unchanged") | |
| identity = self.action if self.config.method == "state_zscore" else self.state | |
| if any(identity.center) or any(s != 1 for s in identity.scale): | |
| raise ValueError( | |
| "An independent candidate must leave the other modality unchanged" | |
| ) | |
| return self | |
| class FitNormalizationConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| dataset: Any | |
| """Native delta dataset after action encoding, before chunk/padding normalization.""" | |
| normalization: NormalizationConfig | |
| """Single-factor fitting recipe.""" | |
| action_encoding: ActionEncoding | |
| """Coordinates of the dataset actions.""" | |
| source: Path | |
| """Training HDF5 used by this dataset.""" | |
| action_samples: Any | None = None | |
| """Explicit encoded population for sample-dependent labels; excludes padding.""" | |
| def fit_normalization(config: FitNormalizationConfig): | |
| if config.normalization.method == "none": | |
| return None | |
| dataset = config.dataset | |
| if not dataset.delta_control or dataset.norm_stats is not None: | |
| raise ValueError( | |
| "Normalization requires raw native delta-control observations/actions" | |
| ) | |
| actions, states = [], [] | |
| for action, obs in zip( | |
| dataset.trajectories["actions"], | |
| dataset.trajectories["observations"], | |
| strict=True, | |
| ): | |
| state = obs["state"] | |
| if not len(action) or len(state) != len(action) + 1: | |
| raise ValueError("Expected one terminal observation per trajectory") | |
| actions.append(action.double()) | |
| states.append(state[: len(action)].double()) | |
| action = torch.cat(actions) | |
| if config.action_samples is not None: | |
| action = torch.as_tensor(config.action_samples).double() | |
| if action.ndim != 2 or not len(action): | |
| raise ValueError("Expected nonempty encoded action population") | |
| state = torch.cat(states) | |
| if not torch.isfinite(action).all() or not torch.isfinite(state).all(): | |
| raise ValueError("Nonfinite training data") | |
| state_center, state_scale = ( | |
| torch.zeros(state.shape[-1]), | |
| torch.ones(state.shape[-1]), | |
| ) | |
| action_center, action_scale = ( | |
| torch.zeros(action.shape[-1]), | |
| torch.ones(action.shape[-1]), | |
| ) | |
| method = config.normalization.method | |
| if method == "state_zscore": | |
| state_center = state.mean(0) | |
| state_scale = torch.maximum( | |
| state.std(0, correction=0), | |
| state.new_tensor(config.normalization.state_floor), | |
| ) | |
| elif method == "action_zscore": | |
| action_center = action.mean(0) | |
| action_scale = action.std(0, correction=0).clamp_min( | |
| config.normalization.action_floor | |
| ) | |
| else: | |
| low, high = torch.quantile(action, action.new_tensor([0.01, 0.99]), dim=0) | |
| action_center = (low + high) / 2 | |
| action_scale = ((high - low) / 2).clamp_min(config.normalization.action_floor) | |
| action_center[-1], action_scale[-1] = 0, 1 | |
| with config.source.open("rb") as stream: | |
| source_sha256 = hashlib.file_digest(stream, "sha256").hexdigest() | |
| return FittedNormalizationConfig( | |
| config=config.normalization, | |
| action_encoding=config.action_encoding, | |
| source_sha256=source_sha256, | |
| trajectories=len(actions), | |
| samples=len(action), | |
| state=AffineConfig(center=state_center.tolist(), scale=state_scale.tolist()), | |
| action=AffineConfig(center=action_center.tolist(), scale=action_scale.tolist()), | |
| ) | |
| class NormalizedDatasetConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| dataset: Any | |
| """Encoded native dataset, still owning physical stop padding.""" | |
| statistics: FittedNormalizationConfig | |
| """Training-only fitted affine parameters.""" | |
| class NormalizedDataset(Dataset): | |
| def __init__(self, config: NormalizedDatasetConfig): | |
| self.config = config | |
| self.dataset = config.dataset | |
| self.center = torch.tensor(config.statistics.action.center) | |
| self.scale = torch.tensor(config.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] | |
| # Native dataset has already padded zero motion and held the last gripper. | |
| return {**sample, "actions": (sample["actions"] - self.center) / self.scale} | |
| class NormalizedModelConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| model: Any | |
| """Native CVAE; receives normalized labels and the same normalized state in both branches.""" | |
| statistics: FittedNormalizationConfig | |
| """Checkpoint-owned transforms; these do not consume random initialization draws.""" | |
| class NormalizedModel(nn.Module): | |
| def __init__(self, config: NormalizedModelConfig): | |
| super().__init__() | |
| self.config = config | |
| self.base = config.model | |
| # Saved once as checkpoint metadata, not averaged as EMA parameters/buffers. | |
| for name, values in ( | |
| ("state_center", config.statistics.state.center), | |
| ("state_scale", config.statistics.state.scale), | |
| ("action_center", config.statistics.action.center), | |
| ("action_scale", config.statistics.action.scale), | |
| ): | |
| self.register_buffer(name, torch.tensor(values), persistent=False) | |
| def forward(self, obs, actions=None): | |
| obs = {**obs, "state": (obs["state"] - self.state_center) / self.state_scale} | |
| prediction, latent = self.base(obs, actions) | |
| if actions is None: | |
| # Invert BEFORE native time ensembling and Rotation6DEnv projection. | |
| # No clipping, including predictions outside q01/q99. | |
| prediction = prediction * self.action_scale + self.action_center | |
| return prediction, latent | |
| def checked_statistics(raw, normalization, encoding): | |
| if normalization.method == "none": | |
| if raw is not None: | |
| raise ValueError( | |
| "Unnormalized control unexpectedly contains fitted statistics" | |
| ) | |
| return None | |
| if raw is None: | |
| raise ValueError( | |
| "Normalized policy requires its training-fitted checkpoint statistics" | |
| ) | |
| fitted = FittedNormalizationConfig.model_validate(raw) | |
| if fitted.config != normalization or fitted.action_encoding != encoding: | |
| raise ValueError( | |
| "Fitted statistics differ from the policy normalization contract" | |
| ) | |
| return fitted | |