File size: 7,874 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
158
159
160
161
162
163
164
165
166
"""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.
"""

import math
from typing import Any

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


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
        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 []
        # 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)
            self.time_in = nn.Linear(2 * width, width, device=device)
            self.time_out = nn.Linear(width, width, device=device)
        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 velocity(self, noisy, time, 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)