File size: 6,468 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
"""Explicit completed-goal context for both native ACT state projections.

Training supplies the previous primitive's recorded target. Deployment must
supply only a model target whose path and gripper execution have completed.
The wrapper never infers a phase, advances a state machine, or reads task state.
"""

from typing import Literal

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

from lim.normalization import FittedNormalizationConfig

KeyposeContextMode = Literal["none", "zero", "previous_target"]
STATE_DIM = 25
CONTEXT_DIM = 11


class ContextProjectionConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    state_projection: nn.Linear
    """Existing state25 projection; preserve its parameters and bias verbatim."""


class StateContextProjection(nn.Module):
    """Project concatenated state25/context11 through separate additive paths."""

    def __init__(self, config: ContextProjectionConfig):
        super().__init__()
        self.config = config
        self.state = config.state_projection
        if self.state.in_features != STATE_DIM:
            raise ValueError(
                "Completed-goal context requires the audited state25 projection"
            )
        self.in_features = STATE_DIM + CONTEXT_DIM
        self.out_features = self.state.out_features
        self.context = nn.Linear(
            CONTEXT_DIM,
            self.state.out_features,
            bias=False,
            device=self.state.weight.device,
            dtype=self.state.weight.dtype,
        )

    def forward(self, combined):
        if combined.shape[-1] != self.in_features:
            raise ValueError("Expected concatenated state25 and completed-target11")
        return self.state(combined[..., :STATE_DIM]) + self.context(
            combined[..., STATE_DIM:]
        )


class KeyposeContextModelConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    model: nn.Module
    """Pinned DETRVAE before NormalizedModel wraps the state/action contract."""
    mode: KeyposeContextMode
    """Zero ablation or previous_target; none must keep the original model unwrapped."""
    statistics: FittedNormalizationConfig
    """Original checkpoint-owned affine action statistics for the context target10."""


class KeyposeContextModel(nn.Module):
    def __init__(self, config: KeyposeContextModelConfig):
        super().__init__()
        self.config = config
        if config.mode == "none":
            raise ValueError(
                "Disabled completed-goal context must not wrap the native model"
            )
        if len(config.statistics.action.center) != 10:
            raise ValueError(
                "Completed-goal context requires world keypose10 statistics"
            )
        self.base = config.model
        prior = self.base.input_proj_robot_state
        posterior = self.base.encoder_state_proj
        if (
            not isinstance(prior, nn.Linear)
            or not isinstance(posterior, nn.Linear)
            or prior.in_features != STATE_DIM
            or posterior.in_features != STATE_DIM
            or prior.out_features != posterior.out_features
            or prior.weight.device != posterior.weight.device
        ):
            raise ValueError(
                "Expected matching native prior/posterior state25 projections"
            )
        devices = [prior.weight.device.index] if prior.weight.is_cuda else []
        # One fork for both draws gives distinct context projections while
        # preserving all caller RNG streams (native weights, EMA and sampling).
        with torch.random.fork_rng(devices=devices):
            self.base.input_proj_robot_state = StateContextProjection(
                ContextProjectionConfig(state_projection=prior)
            )
            self.base.encoder_state_proj = StateContextProjection(
                ContextProjectionConfig(state_projection=posterior)
            )
        self.register_buffer(
            "action_center",
            torch.tensor(config.statistics.action.center),
            persistent=False,
        )
        self.register_buffer(
            "action_scale",
            torch.tensor(config.statistics.action.scale),
            persistent=False,
        )

    def encode_context(self, obs):
        state = obs["state"]
        if state.ndim != 2 or state.shape[-1] != STATE_DIM:
            raise ValueError(
                "Expected batch x state25 before appending completed-goal context"
            )
        if self.config.mode == "zero":
            # Ablation carries no completed-goal signal, including the valid bit.
            return state.new_zeros((state.shape[0], CONTEXT_DIM))
        if "completed_target" not in obs:
            raise ValueError(
                "previous_target policy requires explicit completed_target observations"
            )
        context = torch.as_tensor(
            obs["completed_target"], device=state.device, dtype=state.dtype
        )
        if context.shape != (state.shape[0], CONTEXT_DIM):
            raise ValueError("Expected completed_target shape batch x 11")
        validity = context[:, -1]
        if not ((validity == 0) | (validity == 1)).all():
            raise ValueError("Completed-target validity must be exactly zero or one")
        valid = validity.bool()
        if not torch.isfinite(context[valid, :10]).all():
            raise ValueError(
                "A valid completed target must contain finite world keypose10"
            )
        # Mask before and after normalization: invalid placeholders can never
        # leak a centering offset, NaN, or previous episode's target.
        target = context[:, :10].masked_fill(~valid[:, None], 0)
        target = ((target - self.action_center) / self.action_scale).masked_fill(
            ~valid[:, None], 0
        )
        return torch.cat([target, validity[:, None]], dim=-1)

    def forward(self, obs, actions=None):
        context = self.encode_context(obs)
        combined = torch.cat([obs["state"], context], dim=-1)
        # The native forward sees the combined vector in both state projections;
        # action targets and RGB pass through unchanged. No hooks/global state.
        return self.base({**obs, "state": combined}, actions)