File size: 2,752 Bytes
2a723eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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 torch
from pydantic import BaseModel, ConfigDict
from torch import nn

KEYPOSE_PHASE_NAMES = (
    "approach",
    "grasp_pose",
    "close_gripper",
    "lift",
    "place_pose",
    "open_gripper",
)


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."""


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,
            )
        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)
        self.phase_logits = self.phase(
            features if self.config.all_queries else features[:, 0]
        )
        return actions


def read_phase_logits(model):
    """Return six raw class logits from the latest forward, before/after normalization.

    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