"""Per-item end of the demonstration, predicted beside every chunk item. Label of item i at observation t: t + i is past the demonstration's last action, i.e. exactly the items that carry terminal padding. The action labels, padding and normalization are unchanged. Every label row is 0...0 1...1 and item 0 is never done, so the end is read from one prediction only: what the policy does once a demonstration has ended was never observed. """ import hashlib import torch from pydantic import BaseModel, ConfigDict from torch import nn DONE_LOGIT = 0.0 """An item counts as done at probability >= 0.5 (logit >= 0); fixed before any run.""" class ChunkDoneHeadConfig(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 or switch head.""" def wrapped_linear(module): """The native action projection inside any chain of `.action` wrappers.""" while not isinstance(module, nn.Linear): if not hasattr(module, "action"): raise ValueError("Done head wraps a linear action projection") module = module.action return module class ChunkDoneHead(nn.Module): def __init__(self, config: ChunkDoneHeadConfig): super().__init__() self.config = config self.action = config.action_head linear = wrapped_linear(self.action) device = linear.weight.device devices = [device.index] if device.type == "cuda" else [] # Preserve the original parameters' initialization, later EMA # construction and every sampling/dropout RNG draw. with torch.random.fork_rng(devices=devices): self.done = nn.Linear( linear.in_features, 1, device=device, dtype=linear.weight.dtype ) self.done_logits = 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.done_logits = self.done(features).squeeze(-1) return actions def read_done_logits(model): """Batch x query logits from the latest forward, without detaching or rerunning it.""" heads = [part for part in model.modules() if isinstance(part, ChunkDoneHead)] if len(heads) != 1: raise ValueError("Expected exactly one enabled chunk done head") logits = heads[0].done_logits if logits is None: raise RuntimeError("Done logits require a completed policy forward") return logits def labels_from_valid(valid): """Float labels from the dataset's in-range mask: 1 exactly on padded items.""" return (~valid).float() def batch_done_items(logits): """Items before the end under the suffix rule, for every row of batch x items: the end is the first item from which every later item is also done. All items if the last one is not done; 0 if every item is done.""" pending = logits < DONE_LOGIT index = torch.arange(1, logits.shape[-1] + 1, device=logits.device) return (pending * index).amax(-1) def done_items(logits): """batch_done_items for one prediction's logits.""" if logits.ndim != 1 or not torch.isfinite(logits).all(): raise ValueError("Expected one finite logit per chunk item") return int(batch_done_items(logits[None])[0]) def first_done_item(logits): """Diagnostic only: index of the first done item, all items if none is.""" if logits.ndim != 1 or not torch.isfinite(logits).all(): raise ValueError("Expected one finite logit per chunk item") done = torch.nonzero(logits >= DONE_LOGIT).flatten() return int(done[0]) if len(done) else len(logits) def original_state_sha256(model): """Hash parameters/buffers as they would be named without the done head. With the same seed this equals the full initial-state hash of the matching recipe trained without the head, because the head draws no RNG. """ digest = hashlib.sha256() for name, tensor in model.state_dict().items(): if ".action_head.done." in name: continue name = name.replace(".action_head.action.", ".action_head.", 1) digest.update(name.encode()) digest.update(tensor.detach().cpu().contiguous().numpy().tobytes()) return digest.hexdigest()