File size: 6,245 Bytes
ae1ed83
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Demo Object Binding — PDF core version (TRACE-ARCH-002,
sections 6.2-6.4), used by arm R5/R6.

Differences from binding.py (the reduced v2 binding of R3/R4):
- Region candidates are the per-frame patch regions themselves,
  scored by a SOFT relevance distribution over (frame, region)
  pairs (6.2/6.3 of the PDF) instead of only frame-level
  relevance plus free-form query pooling.
- The binding returns an explicit RECORD (6.4): the target
  embedding, a role distribution, a time span (relevance-weighted
  mean/std of frame time) and a confidence.

Region grid: the finest grid available from the existing feature
caches is the pooled 8x8 grid (64 regions per frame, main camera).
Opening the raw 16x16 grid would require rebuilding every cache;
the pooled grid is kept and the choice is recorded in the run
WORKLOG (Young's instruction, 2026-11-22 00:32).

The demo is RGB only: no actions, states, or instruction.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F

N_ROLES = 3  # 0 = manipulated target, 1 = container, 2 = other


class RegionRoleHead(nn.Module):
    """Shared role classifier (PDF 6.4 binding record).

    Trained on LIVE candidate regions with factory labels (target
    candidate -> 0, any other candidate -> 2; the container class
    exists in the record format but receives no candidates in the
    current scenes, whose candidate sets are the free objects).
    The same head reads the demo target embedding to fill the
    binding record's role field.
    """

    def __init__(self, hidden: int = 256):
        super().__init__()
        self.mlp = nn.Sequential(
            nn.Linear(hidden, hidden // 2), nn.SiLU(),
            nn.Linear(hidden // 2, N_ROLES))

    def forward(self, feats: torch.Tensor) -> torch.Tensor:
        return self.mlp(feats)


class RegionBindingV3(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)
        # Per-region relevance scorer: sees the region feature and
        # its frame's temporal context.
        self.region_scorer = nn.Sequential(
            nn.Linear(hidden * 2, hidden // 2), nn.SiLU(),
            nn.Linear(hidden // 2, 1))
        self.queries = nn.Parameter(torch.zeros(n_queries, hidden))
        self.query_attn = nn.MultiheadAttention(hidden, n_heads,
                                                batch_first=True)
        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))
        self.role_head = RegionRoleHead(hidden)
        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."""
        b, t = demo_pooled.shape[0], demo_pooled.shape[1]
        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)

        # Soft relevance over (frame, region) pairs.
        ctx = frame_enc.unsqueeze(2).expand(-1, -1,
                                            self.patches_per_frame, -1)
        rel_logits = self.region_scorer(
            torch.cat([patch, ctx], dim=-1)).squeeze(-1)  # [B,T,64]
        valid = frame_mask.unsqueeze(-1).expand_as(rel_logits)
        rel_logits = rel_logits.masked_fill(~valid, -1e9)
        relevance = torch.softmax(rel_logits.flatten(1), dim=1) \
            .view(b, t, self.patches_per_frame)
        relevance = relevance * valid.to(relevance.dtype)
        frame_relevance = relevance.sum(dim=2)            # [B,T]

        # Time span of the interaction (record field, PDF 6.4).
        times = torch.linspace(0.0, 1.0, t, device=patch.device)
        t_mean = (frame_relevance * times[None]).sum(dim=1)
        t_var = (frame_relevance
                 * (times[None] - t_mean.unsqueeze(1)) ** 2).sum(dim=1)
        time_span = torch.stack([t_mean, t_var.clamp(min=0).sqrt()],
                                dim=-1)                   # [B,2]

        region_pooled = (relevance.unsqueeze(-1) * patch).sum(dim=(1, 2))
        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), region_pooled], dim=-1)
        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": frame_relevance,
                "region_relevance": relevance,
                "time_span": time_span,
                "role_logits": self.role_head(target),
                "frame_enc": frame_enc}