File size: 3,027 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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
"""Terminal intent from query-zero features, without changing action10 semantics.

Labels supervise whether to hold after this request completes. They are never
model observations or a success signal. Training uses posterior features;
inference logits must be read from the latest native zero-latent prior forward.
"""

import hashlib

import torch
from pydantic import BaseModel, ConfigDict
from torch import nn


class KeyposeStopHeadConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    action_head: nn.Linear
    """Original native action10 projection, reused without reinitialization."""


class KeyposeStopHead(nn.Module):
    def __init__(self, config: KeyposeStopHeadConfig):
        super().__init__()
        self.config = config
        self.action = config.action_head
        if self.action.out_features != 10:
            raise ValueError("Stop intent requires the original keypose10 projection")
        device = self.action.weight.device
        devices = [device.index] if device.type == "cuda" else []
        # Preserve subsequent context/EMA initialization and sampling/dropout RNG.
        with torch.random.fork_rng(devices=devices):
            self.stop = nn.Linear(
                self.action.in_features,
                1,
                device=device,
                dtype=self.action.weight.dtype,
            )
        self.stop_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.stop_logits = self.stop(features[:, 0]).squeeze(-1)
        return actions


def read_stop_logits(model):
    """Return batch logits from the latest forward without detaching or rerunning it."""
    heads = [part for part in model.modules() if isinstance(part, KeyposeStopHead)]
    if len(heads) != 1:
        raise ValueError("Expected exactly one enabled keypose stop head")
    logits = heads[0].stop_logits
    if logits is None:
        raise RuntimeError("Stop logits require a completed policy forward")
    return logits


def original_state_sha256(model):
    """Hash original parameters/buffers in native order, excluding only the new head.

    The complete state_dict hash intentionally changes when the head is present.
    Reversing the action wrapper's key prefix permits comparison with precision.
    """
    digest = hashlib.sha256()
    for name, tensor in model.state_dict().items():
        if ".action_head.dense." in name:
            continue
        name = name.replace(".action_head.primary.", ".action_head.")
        if ".action_head.stop." in name:
            continue
        original = name.replace(".action_head.action.", ".action_head.")
        digest.update(original.encode())
        digest.update(tensor.detach().cpu().contiguous().numpy().tobytes())
    return digest.hexdigest()