OpenGHz's picture
Add fair-comparison/extract-train-v1
d26db08 verified
Raw History Blame Contribute Delete
11.7 kB
"""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)