Download fair-comparison/flow-v1/code/lim/keypose_context.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 6.47 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/keypose_context.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/keypose_context.py
-
curl -L -o keypose_context.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/keypose_context.py
6.47 kB
| """Explicit completed-goal context for both native ACT state projections. | |
| Training supplies the previous primitive's recorded target. Deployment must | |
| supply only a model target whose path and gripper execution have completed. | |
| The wrapper never infers a phase, advances a state machine, or reads task state. | |
| """ | |
| from typing import Literal | |
| import torch | |
| from pydantic import BaseModel, ConfigDict | |
| from torch import nn | |
| from lim.normalization import FittedNormalizationConfig | |
| KeyposeContextMode = Literal["none", "zero", "previous_target"] | |
| STATE_DIM = 25 | |
| CONTEXT_DIM = 11 | |
| class ContextProjectionConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| state_projection: nn.Linear | |
| """Existing state25 projection; preserve its parameters and bias verbatim.""" | |
| class StateContextProjection(nn.Module): | |
| """Project concatenated state25/context11 through separate additive paths.""" | |
| def __init__(self, config: ContextProjectionConfig): | |
| super().__init__() | |
| self.config = config | |
| self.state = config.state_projection | |
| if self.state.in_features != STATE_DIM: | |
| raise ValueError( | |
| "Completed-goal context requires the audited state25 projection" | |
| ) | |
| self.in_features = STATE_DIM + CONTEXT_DIM | |
| self.out_features = self.state.out_features | |
| self.context = nn.Linear( | |
| CONTEXT_DIM, | |
| self.state.out_features, | |
| bias=False, | |
| device=self.state.weight.device, | |
| dtype=self.state.weight.dtype, | |
| ) | |
| def forward(self, combined): | |
| if combined.shape[-1] != self.in_features: | |
| raise ValueError("Expected concatenated state25 and completed-target11") | |
| return self.state(combined[..., :STATE_DIM]) + self.context( | |
| combined[..., STATE_DIM:] | |
| ) | |
| class KeyposeContextModelConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| model: nn.Module | |
| """Pinned DETRVAE before NormalizedModel wraps the state/action contract.""" | |
| mode: KeyposeContextMode | |
| """Zero ablation or previous_target; none must keep the original model unwrapped.""" | |
| statistics: FittedNormalizationConfig | |
| """Original checkpoint-owned affine action statistics for the context target10.""" | |
| class KeyposeContextModel(nn.Module): | |
| def __init__(self, config: KeyposeContextModelConfig): | |
| super().__init__() | |
| self.config = config | |
| if config.mode == "none": | |
| raise ValueError( | |
| "Disabled completed-goal context must not wrap the native model" | |
| ) | |
| if len(config.statistics.action.center) != 10: | |
| raise ValueError( | |
| "Completed-goal context requires world keypose10 statistics" | |
| ) | |
| self.base = config.model | |
| prior = self.base.input_proj_robot_state | |
| posterior = self.base.encoder_state_proj | |
| if ( | |
| not isinstance(prior, nn.Linear) | |
| or not isinstance(posterior, nn.Linear) | |
| or prior.in_features != STATE_DIM | |
| or posterior.in_features != STATE_DIM | |
| or prior.out_features != posterior.out_features | |
| or prior.weight.device != posterior.weight.device | |
| ): | |
| raise ValueError( | |
| "Expected matching native prior/posterior state25 projections" | |
| ) | |
| devices = [prior.weight.device.index] if prior.weight.is_cuda else [] | |
| # One fork for both draws gives distinct context projections while | |
| # preserving all caller RNG streams (native weights, EMA and sampling). | |
| with torch.random.fork_rng(devices=devices): | |
| self.base.input_proj_robot_state = StateContextProjection( | |
| ContextProjectionConfig(state_projection=prior) | |
| ) | |
| self.base.encoder_state_proj = StateContextProjection( | |
| ContextProjectionConfig(state_projection=posterior) | |
| ) | |
| self.register_buffer( | |
| "action_center", | |
| torch.tensor(config.statistics.action.center), | |
| persistent=False, | |
| ) | |
| self.register_buffer( | |
| "action_scale", | |
| torch.tensor(config.statistics.action.scale), | |
| persistent=False, | |
| ) | |
| def encode_context(self, obs): | |
| state = obs["state"] | |
| if state.ndim != 2 or state.shape[-1] != STATE_DIM: | |
| raise ValueError( | |
| "Expected batch x state25 before appending completed-goal context" | |
| ) | |
| if self.config.mode == "zero": | |
| # Ablation carries no completed-goal signal, including the valid bit. | |
| return state.new_zeros((state.shape[0], CONTEXT_DIM)) | |
| if "completed_target" not in obs: | |
| raise ValueError( | |
| "previous_target policy requires explicit completed_target observations" | |
| ) | |
| context = torch.as_tensor( | |
| obs["completed_target"], device=state.device, dtype=state.dtype | |
| ) | |
| if context.shape != (state.shape[0], CONTEXT_DIM): | |
| raise ValueError("Expected completed_target shape batch x 11") | |
| validity = context[:, -1] | |
| if not ((validity == 0) | (validity == 1)).all(): | |
| raise ValueError("Completed-target validity must be exactly zero or one") | |
| valid = validity.bool() | |
| if not torch.isfinite(context[valid, :10]).all(): | |
| raise ValueError( | |
| "A valid completed target must contain finite world keypose10" | |
| ) | |
| # Mask before and after normalization: invalid placeholders can never | |
| # leak a centering offset, NaN, or previous episode's target. | |
| target = context[:, :10].masked_fill(~valid[:, None], 0) | |
| target = ((target - self.action_center) / self.action_scale).masked_fill( | |
| ~valid[:, None], 0 | |
| ) | |
| return torch.cat([target, validity[:, None]], dim=-1) | |
| def forward(self, obs, actions=None): | |
| context = self.encode_context(obs) | |
| combined = torch.cat([obs["state"], context], dim=-1) | |
| # The native forward sees the combined vector in both state projections; | |
| # action targets and RGB pass through unchanged. No hooks/global state. | |
| return self.base({**obs, "state": combined}, actions) | |