"""PoP policy for pretraining on joint-space robot data without referents. Same trunk, head and parameter names as PoP's `PopPolicy` (pop/model/policy.py, iface "ref"), so a pretrained checkpoint loads into the fine-tuning model by name: trunk DINOv2 ViT-S/14 (22.06M), fine-tuned; agent and wrist view, 224 px, 16x16 patch tokens each head adaLN-zero transformer decoder (width 224, 4 layers, 7 heads, chunk 16) with L1 action chunks Differences, all forced by the data (RGB only, no referent labels, joint-space SO-100 arm): - Referents: both roles use PoP's learned null vectors (`referent.null`), and the skill code is a reserved "unspecified" entry (index 5 of 6). No sentence or task identity reaches the policy. - State and action are the arm's 6 joint values (5 joints + gripper), normalized per dataset. - A dataset without a wrist camera masks the wrist tokens out of the head's memory. Fine-tuning adds PoP's referent encoder (form B on the SO-101: RGB only) and the five skill codes; `referent.enc`, `referent.role` and `skill.weight[:5]` start untrained there. """ from __future__ import annotations import math import os import sys import warnings import torch import torch.nn as nn import torch.nn.functional as F _TP = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "third_party") if _TP not in sys.path: sys.path.insert(0, _TP) os.environ.setdefault("XFORMERS_DISABLED", "1") # same attention path everywhere (PyTorch SDPA) warnings.filterwarnings("ignore", message="xFormers is") MEAN = torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1) STD = torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1) N_SKILLS = 5 # PoP's skill codes; index N_SKILLS = "unspecified" IMG = 224 def sample_affine(B: int, crop_min: float, device) -> torch.Tensor: """Per-sample crop (scale s, offset tx, ty in normalized coordinates); identity when crop_min >= 1.""" if crop_min >= 1.0: return torch.tensor([1.0, 0.0, 0.0], device=device).expand(B, 3).clone() s = torch.empty(B, device=device).uniform_(crop_min, 1.0) tx = (torch.rand(B, device=device) * 2 - 1) * (1 - s) ty = (torch.rand(B, device=device) * 2 - 1) * (1 - s) return torch.stack([s, tx, ty], 1) def warp(img_u8: torch.Tensor, aff: torch.Tensor) -> torch.Tensor: """(B, H, W, 3) uint8 -> (B, 3, 224, 224) normalized float, cropping by `aff` and resizing.""" x = img_u8.permute(0, 3, 1, 2).float().div_(255) B = x.shape[0] theta = torch.zeros(B, 2, 3, device=x.device) theta[:, 0, 0] = aff[:, 0]; theta[:, 1, 1] = aff[:, 0] theta[:, 0, 2] = aff[:, 1]; theta[:, 1, 2] = aff[:, 2] grid = F.affine_grid(theta, (B, 3, IMG, IMG), align_corners=False) x = F.grid_sample(x, grid, mode="bilinear", padding_mode="border", align_corners=False) return (x - MEAN.to(x.device)) / STD.to(x.device) def mlp(i, h, o): return nn.Sequential(nn.Linear(i, h), nn.GELU(), nn.Linear(h, o)) class Fourier(nn.Module): """PoP's Fourier features (pop/model/policy.py): x, sin and cos of x * 2^k * pi, k < n_freq.""" def __init__(self, in_dim: int, n_freq: int = 6): super().__init__() self.register_buffer("f", (2.0 ** torch.arange(n_freq)) * math.pi, persistent=False) self.out_dim = in_dim * (2 * n_freq + 1) def forward(self, x): y = x[..., None] * self.f return torch.cat([x, y.sin().flatten(-2), y.cos().flatten(-2)], -1) class DinoTrunk(nn.Module): """DINOv2 ViT-S/14 built as torch.hub's `dinov2_vits14` builds it (vendored code, third_party/dinov2).""" dim, grid = 384, 16 def __init__(self, weights: str | None): super().__init__() from dinov2.models.vision_transformer import vit_small self.net = vit_small(patch_size=14, img_size=518, init_values=1.0, ffn_layer="mlp", block_chunks=0, num_register_tokens=0, interpolate_antialias=False, interpolate_offset=0.1) if weights: self.net.load_state_dict(torch.load(weights, map_location="cpu", weights_only=True), strict=True) # used only by DINOv2's masked-image training; never gets a gradient here (PoP's optimizer skips it too), # and DDP requires every trainable parameter to get one self.net.mask_token.requires_grad_(False) def forward(self, x): # (B, 3, 224, 224) -> (B, 256, 384) return self.net.forward_features(x)["x_norm_patchtokens"] class NullReferent(nn.Module): """PoP's per-role null vectors (what, where); the referent encoder itself is added at fine-tuning.""" def __init__(self, d: int): super().__init__() self.null = nn.Parameter(torch.randn(2, d) * 0.02) class AdaLNDecoderLayer(nn.Module): """Pre-norm decoder block (self-attention over the action queries, cross-attention to the memory, MLP) with adaLN-zero modulation from the conditioning vector. As in PoP, plus an optional memory padding mask.""" def __init__(self, d: int, heads: int, mlp_ratio: float = 4.0): super().__init__() self.n1 = nn.LayerNorm(d, elementwise_affine=False) self.sa = nn.MultiheadAttention(d, heads, batch_first=True) self.n2 = nn.LayerNorm(d, elementwise_affine=False) self.ca = nn.MultiheadAttention(d, heads, batch_first=True) self.n3 = nn.LayerNorm(d, elementwise_affine=False) self.ff = mlp(d, int(d * mlp_ratio), d) self.mod = nn.Linear(d, 9 * d) nn.init.zeros_(self.mod.weight); nn.init.zeros_(self.mod.bias) def forward(self, x, mem, c, mem_mask=None): s1, b1, g1, s2, b2, g2, s3, b3, g3 = self.mod(c).unsqueeze(1).chunk(9, -1) h = self.n1(x) * (1 + s1) + b1 x = x + g1 * self.sa(h, h, h, need_weights=False)[0] h = self.n2(x) * (1 + s2) + b2 x = x + g2 * self.ca(h, mem, mem, key_padding_mask=mem_mask, need_weights=False)[0] h = self.n3(x) * (1 + s3) + b3 return x + g3 * self.ff(h) class PopPretrain(nn.Module): def __init__(self, d: int = 224, layers: int = 4, heads: int = 7, chunk: int = 16, act_dim: int = 6, state_dim: int = 6, dino_weights: str | None = None): super().__init__() self.chunk = chunk self.trunk = DinoTrunk(dino_weights) td, g = DinoTrunk.dim, DinoTrunk.grid self.referent = NullReferent(d) self.skill = nn.Embedding(N_SKILLS + 1, d) self.proj = nn.ModuleList([nn.Linear(td, d), nn.Linear(td, d)]) self.pos = nn.Parameter(torch.randn(2, g * g, d) * 0.02) self.state = mlp(state_dim, d, d) self.cond = mlp(3 * d, d, d) self.mem_norm = nn.LayerNorm(d) self.queries = nn.Parameter(torch.randn(1, chunk, d) * 0.02) self.blocks = nn.ModuleList([AdaLNDecoderLayer(d, heads) for _ in range(layers)]) self.out_norm = nn.LayerNorm(d, elementwise_affine=False) self.out_mod = nn.Linear(d, 2 * d) nn.init.zeros_(self.out_mod.weight); nn.init.zeros_(self.out_mod.bias) self.out = nn.Linear(d, act_dim) self.n_img = g * g def param_counts(self) -> dict: n = lambda m: sum(p.numel() for p in m.parameters()) # noqa: E731 trunk, iface, total = n(self.trunk), n(self.referent) + n(self.skill), n(self) return {"trunk": trunk, "interface": iface, "head": total - trunk - iface, "total": total} def forward(self, agent, wrist, state, wrist_valid, sk=None, roles=None): """agent, wrist (B, 3, 224, 224) normalized; state (B, 6) normalized; wrist_valid (B,) bool. sk (B, d): the vector in the skill slot (default: the "unspecified" entry); roles (B, 2, d): the referent slots (default: the null vectors). Returns normalized action chunks (B, chunk, 6).""" B = agent.shape[0] tok = self.trunk(torch.cat([agent, wrist], 0)) ta, tw = tok[:B], tok[B:] img = [self.proj[0](ta) + self.pos[0], self.proj[1](tw) + self.pos[1]] st = self.state(state)[:, None] if sk is None: sk = self.skill(torch.full((B,), N_SKILLS, dtype=torch.long, device=agent.device)) if roles is None: roles = self.referent.null.unsqueeze(0).expand(B, -1, -1).to(sk.dtype) c = self.cond(torch.cat([sk, roles[:, 0], roles[:, 1]], 1)) mem = self.mem_norm(torch.cat(img + [st, sk[:, None], roles], 1)) mask = torch.zeros(B, mem.shape[1], dtype=torch.bool, device=agent.device) mask[:, self.n_img:2 * self.n_img] = ~wrist_valid.view(B, 1) x = self.queries.expand(B, -1, -1) for blk in self.blocks: x = blk(x, mem, c, mask) s, b = self.out_mod(c).unsqueeze(1).chunk(2, -1) return self.out(self.out_norm(x) * (1 + s) + b) class FormB(nn.Module): """PoP's form B referent (pop/model/policy.py Referent, form "B"): per role, Fourier features of the point's normalized position in the (cropped) fixed view and of its offset from the projected gripper, an MLP, plus a role vector; a missing destination uses the null vector. Parameter names as PoP's (referent.enc, .role, .null).""" def __init__(self, d: int): super().__init__() self.pos = Fourier(4) self.enc = mlp(self.pos.out_dim, d, d) self.role = nn.Parameter(torch.randn(2, d) * 0.02) self.null = nn.Parameter(torch.randn(2, d) * 0.02) def forward(self, what_xy, where_xy, where_valid, tip_xy): out = [] for r, xy in enumerate((what_xy, where_xy)): v = self.enc(self.pos(torch.cat([xy, xy - tip_xy], 1))) + self.role[r] if r == 1: v = torch.where(where_valid.view(-1, 1), v, self.null[r].expand_as(v).to(v.dtype)) out.append(v) return torch.stack(out, 1) class PopFinetune(PopPretrain): """The pretrained network plus a conditioning interface, for fine-tuning on the target robot. Every pretrained parameter loads by name (load_pretrained); only the interface's own parameters start untrained. iface "sent" sentence baseline: T5-Efficient-Tiny (fine-tuned with the policy, as in simulation interface 2), mean-pooled over tokens and projected to d, takes the skill code's place (adaLN conditioning and one memory token); the referent slots keep the pretrained null vectors. The skill embedding is unused. iface "ref" PoP: form B referents (FormB) in the referent slots and the step's skill code (rows 0-4 of the pretrained skill embedding; row 5 was "unspecified" in pretraining). """ def __init__(self, iface: str = "sent", t5_dir: str | None = None, t5_pretrained: bool = True, **kw): super().__init__(**kw) assert iface in ("sent", "ref"), iface self.iface = iface d = self.queries.shape[-1] if iface == "sent": from popt.t5 import T5Encoder self.text = T5Encoder(pretrained=t5_pretrained, root=t5_dir) self.text_proj = nn.Linear(self.text.dim, d) else: self.referent = FormB(d) def param_counts(self) -> dict: n = lambda m: sum(p.numel() for p in m.parameters()) # noqa: E731 trunk, total = n(self.trunk), n(self) if self.iface == "sent": text, iface, unused = n(self.text), n(self.text_proj) + n(self.referent), n(self.skill) else: text, iface, unused = 0, n(self.referent) + n(self.skill), 0 return {"trunk": trunk, "text": text, "interface": iface, "head": total - trunk - text - iface - unused, "unused_skill": unused, "total": total} def load_pretrained(self, ema_state: dict) -> dict: """Load a pretraining checkpoint's EMA weights; every parameter of PopPretrain must be present.""" missing, unexpected = self.load_state_dict(ema_state, strict=False) assert not unexpected, unexpected new = ("text.", "text_proj.") if self.iface == "sent" else ("referent.enc.", "referent.role") assert all(k.startswith(new) for k in missing), missing return {"missing": len(missing), "loaded": len(ema_state)} def forward(self, agent, wrist, state, wrist_valid, cond: dict): if self.iface == "sent": h = self.text(cond["ids"], cond["mask"]) m = cond["mask"].to(h.dtype)[..., None] sk = self.text_proj((h * m).sum(1) / m.sum(1)) return super().forward(agent, wrist, state, wrist_valid, sk=sk) roles = self.referent(cond["what"], cond["where"], cond["where_valid"], cond["tip"]) sk = self.skill(cond["skill"]) return super().forward(agent, wrist, state, wrist_valid, sk=sk, roles=roles.to(sk.dtype)) def prepare(batch: dict, crop_min: float, device, return_aff: bool = False): """Batch from ShardDataset -> model inputs on the device. Agent view gets crop/shift augmentation (PoP's recipe); the wrist view is only resized.""" b = {k: v.to(device, non_blocking=True) for k, v in batch.items()} B = b["agent"].shape[0] aff = sample_affine(B, crop_min, device) agent = warp(b["agent"], aff) wrist = warp(b["wrist"], sample_affine(B, 1.0, device)) if return_aff: return agent, wrist, b["state"], b["wrist_valid"], b["actions"], b["act_mask"], aff return agent, wrist, b["state"], b["wrist_valid"], b["actions"], b["act_mask"]