trace-vla-code / code /trace_vla /pkg /binding.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report (part 2)
ae1ed83 verified
Raw History Blame Contribute Delete
4.58 kB
"""Demo Object Binding (TRACE-VLA v2.0 spec, section V).
Lightweight object-interaction encoder over the demonstration. The
demo is RGB only: the input is the frozen ANCHOR patch grid of the
demo main camera, [B, T, 64, 768], exactly as stored in the feature
caches. No demo actions, states, or instruction are consumed.
Output (spec 5.3):
E_demo = {target_embedding [B, 256] (L2-normalized),
interaction_tokens [B, n_queries, 256],
confidence [B, 1] in (0, 1),
relevance [B, T] frame weights}
Design: patch features are projected 768 -> 256 once. Frame tokens
(patch means) pass through a small temporal Transformer so the
relevance head can score frames by interaction content, not by
position. Learned object queries cross-attend to ALL patch tokens
(frame-masked), so the interaction tokens keep spatial appearance.
The target embedding fuses the query summary with the
relevance-pooled frame summary.
Parameter budget (spec XXII): 2-4M. Actual count is printed by
tests/test_v2_modules.py.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class DemoObjectBinding(nn.Module):
def __init__(self, vision_width: int = 768, hidden: int = 256,
n_queries: int = 4, n_temporal_layers: int = 2,
n_heads: int = 4, max_frames: int = 64,
patches_per_frame: int = 64):
super().__init__()
self.hidden = hidden
self.patches_per_frame = patches_per_frame
self.patch_proj = nn.Linear(vision_width, hidden)
self.frame_pos_emb = nn.Parameter(torch.zeros(max_frames, hidden))
layer = nn.TransformerEncoderLayer(
d_model=hidden, nhead=n_heads, dim_feedforward=hidden * 4,
batch_first=True, activation="gelu")
self.temporal = nn.TransformerEncoder(layer,
num_layers=n_temporal_layers)
self.queries = nn.Parameter(torch.zeros(n_queries, hidden))
self.query_attn = nn.MultiheadAttention(hidden, n_heads,
batch_first=True)
self.relevance_head = nn.Sequential(
nn.Linear(hidden, hidden // 2), nn.SiLU(),
nn.Linear(hidden // 2, 1))
self.target_head = nn.Sequential(
nn.Linear(hidden * 2, hidden), nn.SiLU(),
nn.Linear(hidden, hidden))
self.confidence_head = nn.Sequential(
nn.Linear(hidden * 2, hidden // 2), nn.SiLU(),
nn.Linear(hidden // 2, 1))
for p in (self.frame_pos_emb, self.queries):
nn.init.normal_(p, std=0.02)
def forward(self, demo_pooled: torch.Tensor,
frame_mask: torch.Tensor) -> dict:
"""demo_pooled [B, T, 64, 768]; frame_mask [B, T] bool
(True = valid frame)."""
b, t = demo_pooled.shape[0], demo_pooled.shape[1]
device = demo_pooled.device
patch = self.patch_proj(demo_pooled) # [B,T,64,H]
frame_tok = patch.mean(dim=2) \
+ self.frame_pos_emb[:t][None] # [B,T,H]
pad = ~frame_mask
all_pad = pad.all(dim=1, keepdim=True)
frame_enc = self.temporal(
frame_tok, src_key_padding_mask=pad & ~all_pad)
frame_enc = frame_enc * frame_mask.unsqueeze(-1).to(frame_enc.dtype)
# Interaction relevance over frames (masked softmax).
rel_logits = self.relevance_head(frame_enc).squeeze(-1) # [B,T]
rel_logits = rel_logits.masked_fill(pad, -1e9)
relevance = torch.softmax(rel_logits, dim=1) \
* frame_mask.to(frame_enc.dtype)
pooled = (relevance.unsqueeze(-1) * frame_enc).sum(dim=1) # [B,H]
# Object queries attend to every patch token of valid frames.
kv = patch.flatten(1, 2) # [B,T*64,H]
patch_pad = pad.repeat_interleave(self.patches_per_frame, dim=1)
q = self.queries[None].expand(b, -1, -1)
inter, _ = self.query_attn(
q, kv, kv,
key_padding_mask=patch_pad & ~patch_pad.all(dim=1, keepdim=True),
need_weights=False) # [B,Q,H]
fused = torch.cat([inter.mean(dim=1), pooled], dim=-1) # [B,2H]
target = F.normalize(self.target_head(fused), dim=-1)
confidence = torch.sigmoid(self.confidence_head(fused))
return {"target_embedding": target,
"interaction_tokens": inter,
"confidence": confidence,
"relevance": relevance}