File size: 4,857 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
"""Demo-to-Live Correspondence — PDF core version
(TRACE-ARCH-002, section 7.2), used by arm R5/R6.

Differences from correspondence.py (the reduced v2 version):
- Identity features contain NO positional embedding anywhere:
  patch features are a plain projection of the ANCHOR features,
  so a candidate's identity score cannot read its coordinates.
  (In the v2 module a learned patch position embedding was added
  before pooling and refinement — a position leak.)
- The spatial heatmap is built exactly as the PDF prescribes:
  per camera, pi = sum_i p_i * mask_i, the match-probability-
  weighted sum of candidate soft masks.
- Target features are pooled PER CAMERA (f_c), and the map
  centre mu_c of pi_c is returned as the position descriptor
  consumed by the adapter. Position enters only through pi/mu,
  i.e. as an output of matching, never as an identity input.
"""
import torch
import torch.nn as nn


class CorrespondenceV3(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
        self.patch_proj = nn.Linear(vision_width, hidden)
        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.out_proj = nn.Linear(hidden, d_model)

    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] soft or binary patch membership;
        cand_valid [B, K] bool."""
        b, k = cand_mask.shape[0], cand_mask.shape[1]
        device = live_pooled.device
        c, g = self.n_cameras, self.pooled_grid
        # Identity features: NO positional embedding (PDF 7.2).
        patch = self.patch_proj(live_pooled.flatten(1, 2))  # [B,C*64,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 = torch.ones(b, k, dtype=torch.bool,
                                    device=device)
        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)
        scores = self.score_mlp(
            torch.cat([region, te, region * te], dim=-1)).squeeze(-1)
        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

        # Per-camera heatmap pi_c = sum_i p_i * mask_{i,c} (PDF 7.2).
        m_cam = m.view(b, k, c, g * g)
        pi = torch.einsum("bk,bkcn->bcn", probs, m_cam)      # [B,C,64]
        heatmap = pi.view(b, c, g, g)
        # Per-camera target features f_c.
        patch_cam = patch.view(b, c, g * g, -1)
        denom_cam = m_cam.sum(dim=-1, keepdim=True).clamp(min=1.0)
        region_cam = torch.einsum("bkcn,bcnh->bkch", m_cam,
                                  patch_cam) / denom_cam
        target_features_cam = torch.einsum("bk,bkch->bch", probs,
                                           region_cam)      # [B,C,H]
        target_features = (probs.unsqueeze(-1) * region).sum(dim=1)
        # Map centre mu_c of pi_c (patch coords in [0,1]^2).
        ys, xs = torch.meshgrid(
            torch.linspace(0.0, 1.0, g, device=device),
            torch.linspace(0.0, 1.0, g, device=device), indexing="ij")
        coords = torch.stack([xs, ys], dim=-1).view(g * g, 2)
        pi_sum = pi.sum(dim=-1, keepdim=True).clamp(min=1e-6)
        mu = torch.einsum("bcn,nk->bck", pi, coords) / pi_sum
        return {"probs": probs,
                "scores": scores,
                "best_idx": best_idx,
                "confidence": confidence,
                "target_features": target_features,
                "target_features_cam": target_features_cam,
                "target_features_512": self.out_proj(target_features),
                "heatmap": heatmap,
                "pi": pi,
                "mu": mu,
                "region_features": region}