Download fair-comparison/flow-v1/code/lim/keypose_phase.py from OpenGHz/keypose-vs-dense: direct link, hf CLI and curl.
- Browser
- Download file 5.06 kB
-
https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/keypose_phase.py
- Command line
-
hf download hf://datasets/OpenGHz/keypose-vs-dense/fair-comparison/flow-v1/code/lim/keypose_phase.py
-
curl -L -o keypose_phase.py https://huggingface.co/datasets/OpenGHz/keypose-vs-dense/resolve/main/fair-comparison/flow-v1/code/lim/keypose_phase.py
5.06 kB
| """Auxiliary primitive classification from the same ACT decoder forward. | |
| Training features include the native CVAE posterior; inference uses its zero | |
| latent prior. Classification accuracy on training forwards is therefore not a | |
| substitute for prior-mode phase accuracy. Phase labels never enter either branch | |
| as observations, conditioning, or an execution state machine. | |
| """ | |
| import hashlib | |
| import torch | |
| from pydantic import BaseModel, ConfigDict | |
| from torch import nn | |
| KEYPOSE_PHASE_NAMES = ( | |
| "approach", | |
| "grasp_pose", | |
| "close_gripper", | |
| "lift", | |
| "place_pose", | |
| "open_gripper", | |
| ) | |
| DONE_PHASE = len(KEYPOSE_PHASE_NAMES) | |
| """Seventh class of a done-class head: the item lies past the demonstration's end.""" | |
| class KeyposePhaseHeadConfig(BaseModel, frozen=True): | |
| model_config = ConfigDict( | |
| arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True | |
| ) | |
| action_head: nn.Linear | |
| """Existing native action projection, reused without reinitialization.""" | |
| all_queries: bool = False | |
| """Classify every future action; false retains the original query-zero head.""" | |
| done_class: bool = False | |
| """Add a seventh "done" class (DONE_PHASE) as a separate one-row projection, so | |
| the six original rows and every other parameter start exactly as without it.""" | |
| class KeyposePhaseHead(nn.Module): | |
| def __init__(self, config: KeyposePhaseHeadConfig): | |
| super().__init__() | |
| self.config = config | |
| self.action = config.action_head | |
| device = self.action.weight.device | |
| devices = [device.index] if device.type == "cuda" else [] | |
| # The extra head must not perturb later model/EMA construction, dropout, | |
| # native posterior sampling, or the training sample-order RNG. | |
| with torch.random.fork_rng(devices=devices): | |
| self.phase = nn.Linear( | |
| self.action.in_features, | |
| len(KEYPOSE_PHASE_NAMES), | |
| device=device, | |
| dtype=self.action.weight.dtype, | |
| ) | |
| if config.done_class: | |
| if not config.all_queries: | |
| raise ValueError("The done class labels padded chunk items") | |
| with torch.random.fork_rng(devices=devices): | |
| # The seventh row a seven-class projection would draw from the | |
| # same RNG state (its first six weight rows equal self.phase's). | |
| full = nn.Linear( | |
| self.action.in_features, | |
| len(KEYPOSE_PHASE_NAMES) + 1, | |
| device=device, | |
| dtype=self.action.weight.dtype, | |
| ) | |
| self.done_class = nn.Linear( | |
| self.action.in_features, 1, device=device, dtype=self.action.weight.dtype | |
| ) | |
| with torch.no_grad(): | |
| self.done_class.weight.copy_(full.weight[DONE_PHASE:]) | |
| self.done_class.bias.copy_(full.bias[DONE_PHASE:]) | |
| self.phase_logits = None | |
| def forward(self, features): | |
| if features.ndim != 3 or features.shape[1] < 1: | |
| raise ValueError( | |
| "Expected ACT decoder features with shape batch, query, hidden" | |
| ) | |
| actions = self.action(features) | |
| selected = features if self.config.all_queries else features[:, 0] | |
| self.phase_logits = self.phase(selected) | |
| if self.config.done_class: | |
| self.phase_logits = torch.cat([self.phase_logits, self.done_class(selected)], -1) | |
| return actions | |
| def done_phase_logits(phase_logits): | |
| """Items x classes logits -> +1 where the argmax is DONE_PHASE, else -1: the | |
| signal lim.chunk_done's suffix rule reads, so both heads end chunks alike.""" | |
| if phase_logits.ndim != 2 or phase_logits.shape[-1] != DONE_PHASE + 1: | |
| raise ValueError("Expected items x seven phase logits") | |
| return torch.where(phase_logits.argmax(-1) == DONE_PHASE, 1.0, -1.0) | |
| def done_class_free_state_sha256(model): | |
| """Hash of the state without the done-class row; with the same seed it equals | |
| initial_state_sha256 of the six-class recipe, because the row draws no RNG.""" | |
| digest = hashlib.sha256() | |
| for name, tensor in model.state_dict().items(): | |
| if ".action_head.done_class." in name: | |
| continue | |
| digest.update(name.encode()) | |
| digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) | |
| return digest.hexdigest() | |
| def read_phase_logits(model): | |
| """Return six (seven with a done class) raw class logits from the latest forward. | |
| Accept the native agent or any registered model wrapper. Does not invoke the | |
| network, sample a latent, detach gradients, or change the action output. | |
| """ | |
| heads = [part for part in model.modules() if isinstance(part, KeyposePhaseHead)] | |
| if len(heads) != 1: | |
| raise ValueError("Expected exactly one enabled keypose phase head") | |
| logits = heads[0].phase_logits | |
| if logits is None: | |
| raise RuntimeError("Phase logits require a completed policy forward") | |
| return logits | |