File size: 4,755 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
"""Demo-to-Live Object Correspondence (TRACE-VLA v2.0 spec, section VI).

Given the target embedding from Demo Object Binding and the live
ANCHOR patch grid of both cameras, score a set of candidate object
regions and return a softmax distribution over them:

    score_i = Match(E_demo, o_i);  p_i = softmax(score_i)

Candidates are supplied as binary masks over the flattened live
patch grid [B, K, C*64]. In training and in the standalone R3
evaluation the masks come from simulator object poses (privileged,
training/diagnostic only, spec 5.4). At deployment a region proposer
would supply them instead; this module does not care where the
masks come from.

Outputs (spec 6.3): probs [B, K], best_idx [B], confidence [B, 1]
(max prob), target_features [B, 256] (probability-weighted region
features), target_features_512 [B, 512] (projected, for C_object),
heatmap [B, C, 8, 8] (per-patch bilinear match score), and the raw
scores. The scorer sees [region, target, region * target], so it
can learn identity matching; nothing in the scorer receives the
candidate's coordinates, which is deliberate: position must not be
a shortcut feature (spec 6.3, 6.4).

Parameter budget (spec XXII): 2-5M (a ceiling, not a target).
"""
import torch
import torch.nn as nn


class DemoToLiveCorrespondence(nn.Module):
    def __init__(self, vision_width: int = 768, hidden: int = 256,
                 d_model: int = 512, n_cameras: int = 2,
                 pooled_grid: int = 8, n_heads: int = 4):
        super().__init__()
        self.hidden = hidden
        self.n_cameras = n_cameras
        self.pooled_grid = pooled_grid
        n_patches = n_cameras * pooled_grid * pooled_grid
        self.patch_proj = nn.Linear(vision_width, hidden)
        self.patch_pos_emb = nn.Parameter(torch.zeros(n_patches, hidden))
        # Candidate refinement: region tokens attend to the patches.
        self.refine_attn = nn.MultiheadAttention(hidden, n_heads,
                                                 batch_first=True)
        self.refine_norm = nn.LayerNorm(hidden)
        self.score_mlp = nn.Sequential(
            nn.Linear(hidden * 3, hidden), nn.SiLU(),
            nn.Linear(hidden, 1))
        self.patch_key = nn.Linear(hidden, hidden)
        self.out_proj = nn.Linear(hidden, d_model)
        nn.init.normal_(self.patch_pos_emb, std=0.02)

    def forward(self, target_embedding: torch.Tensor,
                live_pooled: torch.Tensor,
                cand_mask: torch.Tensor,
                cand_valid: torch.Tensor | None = None) -> dict:
        """target_embedding [B, 256]; live_pooled [B, C, 64, 768];
        cand_mask [B, K, C*64] bool or float (patch membership);
        cand_valid [B, K] bool, False = padded candidate slot."""
        b, k = cand_mask.shape[0], cand_mask.shape[1]
        device = live_pooled.device
        patch = self.patch_proj(live_pooled.flatten(1, 2)) \
            + self.patch_pos_emb[None]                       # [B,128,H]
        m = cand_mask.to(patch.dtype)
        denom = m.sum(dim=-1, keepdim=True).clamp(min=1.0)
        region = (m @ patch) / denom                         # [B,K,H]
        if cand_valid is None:
            cand_valid = cand_mask.flatten(2).any(dim=-1) \
                if cand_mask.dim() == 3 else torch.ones(
                    b, k, dtype=torch.bool, device=device)
        # Refine region tokens against the patch tokens.
        refined, _ = self.refine_attn(region, patch, patch,
                                      need_weights=False)
        region = self.refine_norm(region + refined)
        region = region * cand_valid.unsqueeze(-1).to(region.dtype)

        te = target_embedding.unsqueeze(1).expand(-1, k, -1)
        score_in = torch.cat([region, te, region * te], dim=-1)
        scores = self.score_mlp(score_in).squeeze(-1)        # [B,K]
        scores = scores.masked_fill(~cand_valid, -1e9)
        probs = torch.softmax(scores, dim=1)
        probs = probs * cand_valid.to(probs.dtype)
        best_idx = probs.argmax(dim=1)
        confidence = probs.max(dim=1, keepdim=True).values   # [B,1]
        target_features = (probs.unsqueeze(-1) * region).sum(dim=1)

        heat = torch.einsum("bnh,bh->bn", self.patch_key(patch),
                            target_embedding) / (self.hidden ** 0.5)
        heatmap = heat.view(b, self.n_cameras, self.pooled_grid,
                            self.pooled_grid)
        return {"probs": probs,
                "scores": scores,
                "best_idx": best_idx,
                "confidence": confidence,
                "target_features": target_features,
                "target_features_512": self.out_proj(target_features),
                "heatmap": heatmap,
                "region_features": region}