File size: 11,671 Bytes
d26db08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
"""Flow-matching action head on the native ACT observation encoder (PLAN.md).

The observation is encoded exactly as the native DETRVAE encodes it at
inference: both cameras' backbone features, the proprioceptive token and the
z = 0 latent token through the same transformer encoder. The CVAE posterior is
not used. The decoder's input, zeros in the native model, becomes the embedded
noisy action and flow time of every item; the query embeddings, the decoder
output taken (stack entry 0) and the action head are the native ones, so with
a zero decoder input the model reproduces native zero-latent inference.

Path, time sampling and embedding follow openpi's pi0
(src/openpi/models/pi0.py): x_t = t * noise + (1 - t) * actions, t = 1 is
noise, the target is noise - actions, t = 0.001 + 0.999 * Beta(1.5, 1), and the
item embedding is out(swish(in(concat(W a, posemb(t))))). Inference integrates
from t = 1 to 0 with Euler steps. Everything is in the normalized action space.

The "modulated" decoder (PLAN.md, flow-mod-v1) differs in two places only. The
output is the last decoder layer's (all layers act), and time enters only
through per-layer modulation, as pi0.5's adaRMSNorm conditioning: the noisy
action is projected linearly, posemb(t) goes through a two-layer swish MLP, and
a zero-initialized linear map of it gives each self-attention, cross-attention
and FFN sublayer a scale, shift and gate, LN(x + (1 + gate) f(x)) (1 + scale) +
shift on ACT's own post-norm LayerNorms; the final LayerNorm gets a scale and
shift. At initialization every layer equals the native one.
"""

import math
from typing import Any, Literal

import torch
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, PositiveInt
from torch import nn

TIME_MIN, TIME_SCALE = 0.001, 0.999
"""Training flow time t = 0.001 + 0.999 * Beta(1.5, 1) (openpi compute_loss)."""
BETA_ALPHA = 1.5
PERIOD_MIN, PERIOD_MAX = 4e-3, 4.0
"""Sine-cosine periods of the flow-time embedding (openpi embed_suffix)."""
GROUPS = {"position": slice(0, 3), "rotation": slice(3, 9), "gripper": slice(9, 10)}
"""The group_balanced groups of a pose6D item."""


def sample_time(batch, device):
    """Beta(1.5, 1) has CDF x**1.5, so r**(2/3) with r ~ U(0, 1) samples it exactly."""
    return TIME_MIN + TIME_SCALE * torch.rand(batch, device=device) ** (1 / BETA_ALPHA)


def time_embedding(time, width):
    """openpi posemb_sincos: batch -> batch x width."""
    fraction = torch.linspace(0, 1, width // 2, device=time.device, dtype=time.dtype)
    period = PERIOD_MIN * (PERIOD_MAX / PERIOD_MIN) ** fraction
    angles = time[:, None] * (1.0 / period * 2 * math.pi)[None]
    return torch.cat([angles.sin(), angles.cos()], dim=-1)


def flow_reconstruction(velocity, target):
    """Mean squared velocity error per group, averaged over the three groups."""
    if velocity.shape != target.shape or target.shape[-1] != 10:
        raise ValueError("Flow objectives require matching ten-dimensional pose chunks")
    groups = {f"{name}_mse": F.mse_loss(velocity[..., part], target[..., part])
              for name, part in GROUPS.items()}
    return {"reconstruction": sum(groups.values()) / len(groups), **groups}


class ChunkFlowConfig(BaseModel, frozen=True):
    model_config = ConfigDict(
        arbitrary_types_allowed=True, extra="forbid", use_attribute_docstrings=True
    )
    native_model: Any
    """Newly initialized pinned DETRVAE; its encoder-side modules are reused."""
    steps: PositiveInt
    """Euler steps from t = 1 to t = 0 per fresh observation."""
    decoder: Literal["native", "modulated"] = "native"
    """native: decoder stack entry 0 with time in the input (pi0); modulated: the
    last layer, time through per-layer modulation (pi0.5-style)."""


SUBLAYERS = 3
"""Self-attention, cross-attention and FFN of a DETR decoder layer."""


def modulated_layer(layer, tgt, memory, pos, query_pos, modulation):
    """One post-norm DETR decoder layer (forward_post) with every sublayer's
    norm(x + (1 + gate) f(x)) * (1 + scale) + shift; zero modulation is the layer.
    tgt: query x batch x width, modulation: batch x (3 * 3 * width)."""
    parts = modulation.unsqueeze(0).chunk(3 * SUBLAYERS, dim=-1)

    def residual(x, y, index, norm):
        scale, shift, gate = parts[3 * index : 3 * index + 3]
        return norm(x + (1 + gate) * y) * (1 + scale) + shift

    q = k = layer.with_pos_embed(tgt, query_pos)
    tgt = residual(tgt, layer.dropout1(layer.self_attn(q, k, value=tgt)[0]), 0, layer.norm1)
    attended = layer.multihead_attn(
        query=layer.with_pos_embed(tgt, query_pos), key=layer.with_pos_embed(memory, pos), value=memory
    )[0]
    tgt = residual(tgt, layer.dropout2(attended), 1, layer.norm2)
    hidden = layer.linear2(layer.dropout(layer.activation(layer.linear1(tgt))))
    return residual(tgt, layer.dropout3(hidden), 2, layer.norm3)


class ChunkFlowModel(nn.Module):
    def __init__(self, config: ChunkFlowConfig):
        super().__init__()
        native = config.native_model
        self.steps = config.steps
        # Only these native modules are registered: the CVAE posterior (encoder,
        # cls/state/action projections, latent_proj, pos_table) is dropped.
        self.backbones = native.backbones
        self.input_proj = native.input_proj
        self.input_proj_robot_state = native.input_proj_robot_state
        self.transformer = native.transformer
        self.query_embed = native.query_embed
        self.action_head = native.action_head
        self.additional_pos_embed = native.additional_pos_embed
        self.latent_out_proj = native.latent_out_proj
        self.latent_dim = native.latent_dim
        self.num_queries = native.num_queries
        self.decoder = config.decoder
        width, dimension = self.transformer.d_model, self.action_head.out_features
        device = self.action_head.weight.device
        devices = [device.index] if device.type == "cuda" else []
        layers = self.transformer.decoder.layers
        # Preserve the native parameters' initialization, later EMA
        # construction and every sampling/dropout RNG draw.
        with torch.random.fork_rng(devices=devices):
            self.action_in = nn.Linear(dimension, width, device=device)
            if self.decoder == "native":
                self.time_in = nn.Linear(2 * width, width, device=device)
                self.time_out = nn.Linear(width, width, device=device)
            else:
                if any(layer.normalize_before for layer in layers):
                    raise ValueError("Modulation is written for ACT's post-norm decoder layers")
                self.time_mlp_in = nn.Linear(width, width, device=device)
                self.time_mlp_out = nn.Linear(width, width, device=device)
                self.modulation = nn.ModuleList(
                    nn.Linear(width, 3 * SUBLAYERS * width, device=device) for _ in layers
                )
                self.final_modulation = nn.Linear(width, 2 * width, device=device)
                for linear in [*self.modulation, self.final_modulation]:
                    nn.init.zeros_(linear.weight)
                    nn.init.zeros_(linear.bias)
        self.generator = None

    def encode(self, obs):
        """Encoder memory and positions, as DETRVAE builds them with z = 0."""
        state = obs["state"]
        batch = state.shape[0]
        features, positions = [], []
        for camera in range(obs["rgb"].shape[1]):
            feature, position = self.backbones[0](obs["rgb"][:, camera])
            features.append(self.input_proj(feature[0]))
            positions.append(position[0])
        src = torch.cat(features, dim=3).flatten(2).permute(2, 0, 1)
        pos = torch.cat(positions, dim=3).flatten(2).permute(2, 0, 1).repeat(1, batch, 1)
        extra = self.additional_pos_embed.weight.unsqueeze(1).repeat(1, batch, 1)
        latent = self.latent_out_proj(
            torch.zeros(batch, self.latent_dim, dtype=torch.float32, device=state.device)
        )
        src = torch.cat([torch.stack([latent, self.input_proj_robot_state(state)]), src])
        pos = torch.cat([extra, pos])
        return self.transformer.encoder(src, src_key_padding_mask=None, pos=pos), pos

    def decode(self, target, memory, pos):
        """batch x query x width decoder input -> batch x query x action."""
        queries = self.query_embed.weight.unsqueeze(1).repeat(1, target.shape[0], 1)
        hidden = self.transformer.decoder(
            target.transpose(0, 1), memory, memory_key_padding_mask=None, pos=pos,
            query_pos=queries,
        ).transpose(1, 2)[0]
        return self.action_head(hidden)

    def modulated_decode(self, target, condition, memory, pos):
        """All decoder layers, modulated by the time condition; the last layer's output."""
        queries = self.query_embed.weight.unsqueeze(1).repeat(1, target.shape[0], 1)
        tgt = target.transpose(0, 1)
        for layer, modulation in zip(self.transformer.decoder.layers, self.modulation, strict=True):
            tgt = modulated_layer(layer, tgt, memory, pos, queries, modulation(condition))
        scale, shift = self.final_modulation(condition).unsqueeze(0).chunk(2, dim=-1)
        hidden = self.transformer.decoder.norm(tgt) * (1 + scale) + shift
        return self.action_head(hidden.transpose(0, 1))

    def velocity(self, noisy, time, memory, pos):
        if self.decoder == "modulated":
            embedded = time_embedding(time, self.time_mlp_in.in_features)
            condition = F.silu(self.time_mlp_out(F.silu(self.time_mlp_in(embedded))))
            return self.modulated_decode(self.action_in(noisy), condition, memory, pos)
        embedded = time_embedding(time, self.time_in.out_features)
        embedded = embedded[:, None].expand(-1, noisy.shape[1], -1)
        target = self.time_out(F.silu(self.time_in(torch.cat([self.action_in(noisy), embedded], -1))))
        return self.decode(target, memory, pos)

    def forward(self, obs, actions=None):
        """Training (normalized labels given): (predicted velocity, velocity target)
        in place of (prediction, latent). Inference: (actions, (None, None))."""
        memory, pos = self.encode(obs)
        if actions is not None:
            noise = torch.randn_like(actions)
            time = sample_time(actions.shape[0], actions.device)
            noisy = time[:, None, None] * noise + (1 - time[:, None, None]) * actions
            return self.velocity(noisy, time, memory, pos), noise - actions
        if self.generator is None:
            raise RuntimeError("Flow inference noise must be seeded (seed_flow_noise)")
        batch = obs["state"].shape[0]
        sample = torch.randn(
            batch, self.num_queries, self.action_head.out_features,
            device=memory.device, generator=self.generator,
        )
        step = 1 / self.steps
        for index in range(self.steps):
            time = sample.new_full((batch,), 1 - index * step)
            sample = sample - step * self.velocity(sample, time, memory, pos)
        return sample, (None, None)


def flow_model(model):
    """The one flow head inside a policy's wrappers."""
    heads = [part for part in model.modules() if isinstance(part, ChunkFlowModel)]
    if len(heads) != 1:
        raise ValueError("Expected exactly one flow-matching head")
    return heads[0]


def seed_flow_noise(model, seed):
    """Restart the inference noise stream (the evaluator does this per episode)."""
    head = flow_model(model)
    device = head.action_head.weight.device
    head.generator = torch.Generator(device=device)
    head.generator.manual_seed(seed)