File size: 2,318 Bytes
0a3f650 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | """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()
|