Download fair-comparison/flow-v1/code/lim/chunk_switch.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 2.32 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/chunk_switch.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/chunk_switch.py
-
curl -L -o chunk_switch.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/chunk_switch.py
2.32 kB
| """Remaining-steps regression for two-segment phase endpoint outputs.""" | |
| import torch | |
| from pydantic import BaseModel, ConfigDict | |
| from torch import nn | |
| SWITCH_HORIZON = 30 | |
| """Remaining steps are clipped to this horizon and supervised as a fraction of it.""" | |
| class ChunkSwitchHeadConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| action_head: nn.Module | |
| """Existing action projection (optionally wrapped by the phase head).""" | |
| class ChunkSwitchHead(nn.Module): | |
| def __init__(self, config: ChunkSwitchHeadConfig): | |
| super().__init__() | |
| self.config = config | |
| self.action = config.action_head | |
| linear = getattr(self.action, "action", self.action) | |
| if not isinstance(linear, nn.Linear): | |
| raise ValueError("Switch head wraps a linear action projection") | |
| device = linear.weight.device | |
| devices = [device.index] if device.type == "cuda" else [] | |
| # Preserve subsequent EMA initialization and sampling/dropout RNG. | |
| with torch.random.fork_rng(devices=devices): | |
| self.switch = nn.Linear( | |
| linear.in_features, | |
| 1, | |
| device=device, | |
| dtype=linear.weight.dtype, | |
| ) | |
| self.switch_fraction = None | |
| def forward(self, features): | |
| if features.ndim != 3 or features.shape[1] < 1: | |
| raise ValueError("Expected ACT decoder features batch x query x hidden") | |
| actions = self.action(features) | |
| self.switch_fraction = self.switch(features[:, 0]).squeeze(-1) | |
| return actions | |
| def read_switch_fraction(model): | |
| """Raw remaining-steps fraction from the latest forward, not clipped or rerun.""" | |
| heads = [part for part in model.modules() if isinstance(part, ChunkSwitchHead)] | |
| if len(heads) != 1: | |
| raise ValueError("Expected exactly one enabled chunk switch head") | |
| fraction = heads[0].switch_fraction | |
| if fraction is None: | |
| raise RuntimeError("Switch fraction requires a completed policy forward") | |
| return fraction | |
| def switch_steps(fraction): | |
| """Predicted steps until the second segment applies, rounded and bounded.""" | |
| return torch.round(fraction.clamp(0, 1) * SWITCH_HORIZON).long() | |