File size: 10,742 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
from __future__ import annotations

"""Multi-Scale TRAM — Robust token selection combining multiple strategies.

Unlike standard TRAM which relies solely on attention centrality, MultiScaleTRAM
combines three complementary selection strategies:
    1. Attention-based (70%) — discriminative regions via ViT attention
    2. Uniform spatial (20%) — guaranteed spatial coverage
    3. Random sampling (10%) — regularization to prevent selection bias

This design makes token selection more robust to:
    - Domain shift (attention bias from different distributions)
    - Training instability (poor early-stage attention)
    - Over-concentration (selecting only high-attention regions)
"""

import math

import torch
import torch.nn as nn


class MultiScaleTRAM(nn.Module):
    """Multi-scale token selection for robust feature extraction.

    Parameters
    ----------
    num_tokens : int
        Total number of tokens to select (K). Default 30 for fingerprints.
    attention_ratio : float
        Fraction of tokens selected via attention centrality (0-1).
    uniform_ratio : float
        Fraction of tokens selected via uniform spatial sampling (0-1).
    random_ratio : float
        Fraction of tokens selected randomly (0-1).
        Note: attention_ratio + uniform_ratio + random_ratio must equal 1.0
    grid_size : tuple[int, int]
        Spatial grid dimensions (H, W) for uniform sampling.
        Default (14, 14) for 224px images with 16px patches.
    method : str
        Attention aggregation method: "incoming_sum" (default) | "eigenvector".
    """

    def __init__(
        self,
        num_tokens: int = 30,
        attention_ratio: float = 0.7,
        uniform_ratio: float = 0.2,
        random_ratio: float = 0.1,
        grid_size: tuple[int, int] = (14, 14),
        method: str = "incoming_sum",
    ):
        super().__init__()

        # Validate ratios sum to 1
        total_ratio = attention_ratio + uniform_ratio + random_ratio
        if not math.isclose(total_ratio, 1.0, abs_tol=1e-6):
            raise ValueError(
                f"Ratios must sum to 1.0, got {total_ratio:.4f} "
                f"({attention_ratio} + {uniform_ratio} + {random_ratio})"
            )

        self.num_tokens = num_tokens
        self.attention_ratio = attention_ratio
        self.uniform_ratio = uniform_ratio
        self.random_ratio = random_ratio
        self.grid_size = grid_size
        self.method = method

        # Compute number of tokens per strategy
        self.k_attention = max(1, int(num_tokens * attention_ratio))
        self.k_uniform = max(1, int(num_tokens * uniform_ratio))
        self.k_random = max(0, num_tokens - self.k_attention - self.k_uniform)

        # Adjust if rounding causes mismatch
        total_k = self.k_attention + self.k_uniform + self.k_random
        if total_k != num_tokens:
            # Give extra tokens to attention strategy
            self.k_attention += (num_tokens - total_k)

    # ------------------------------------------------------------------
    def forward(
        self,
        patch_tokens: torch.Tensor,
        attn_maps: list[torch.Tensor],
        num_prefix_tokens: int = 1,
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """Select K tokens using multi-scale strategy.

        Args:
            patch_tokens: (B, P, D) patch features from ViT.
            attn_maps: List of L tensors, each (B, H, N, N) where N = P + num_prefix_tokens.
            num_prefix_tokens: Number of prefix tokens (CLS + registers) to skip.

        Returns:
            selected_tokens: (B, K, D) features of selected tokens.
            selected_indices: (B, K) indices into the P patch tokens (sorted).
            centrality_scores: (B, P) attention centrality score for every patch.
        """
        B, P, D = patch_tokens.shape
        device = patch_tokens.device

        # 1. Attention-based selection
        centrality, attention_indices = self._select_by_attention(
            attn_maps, num_prefix_tokens, B, P, device
        )

        # 2. Uniform spatial selection
        uniform_indices = self._select_uniform_spatial(B, P, device)

        # 3. Random selection (avoid already selected)
        random_indices = self._select_random(
            attention_indices, uniform_indices, B, P, device
        )

        # 4. Combine all indices and sort to preserve spatial order
        all_selected = torch.cat([attention_indices, uniform_indices, random_indices], dim=1)
        all_selected_sorted, _ = all_selected.sort(dim=-1)

        # 5. Gather selected token features (WITH gradient for end-to-end training)
        selected_tokens = torch.gather(
            patch_tokens,
            dim=1,
            index=all_selected_sorted.unsqueeze(-1).expand(-1, -1, D),
        )

        return selected_tokens, all_selected_sorted, centrality

    # ------------------------------------------------------------------
    def _select_by_attention(
        self,
        attn_maps: list[torch.Tensor],
        num_prefix_tokens: int,
        B: int,
        P: int,
        device: torch.device,
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """Select tokens based on attention centrality.

        Returns:
            centrality: (B, P) centrality scores.
            indices: (B, k_attention) selected token indices.
        """
        centrality = torch.zeros(B, P, device=device)

        if self.method == "incoming_sum":
            # Aggregate incoming attention across all layers
            for attn in attn_maps:
                # attn: (B, H, N, N)
                a = attn.max(dim=1).values  # (B, N, N) - max across heads
                a_pp = a[:, num_prefix_tokens:, num_prefix_tokens:]  # (B, P, P)
                # Incoming attention: sum over source dimension
                centrality = centrality + a_pp.sum(dim=1)  # (B, P)

        elif self.method in ("eigenvector", "tram"):
            # Original TRAM paper centrality (Marchetti et al.)
            L = len(attn_maps)
            for idx, attn in enumerate(attn_maps):
                a = attn.max(dim=1).values  # (B, N, N)
                a_pp = a[:, num_prefix_tokens:, num_prefix_tokens:]  # (B, P, P)
                # In-degree: how much each token is attended to
                d_in = a_pp.sum(dim=1)  # (B, P)
                # Rescale: weight rows by source's in-degree
                a_rescaled = a_pp * d_in.unsqueeze(-1)  # (B, P, P)
                # Weighted in-degree for this layer
                centrality_l = a_rescaled.sum(dim=1)  # (B, P)
                # Accumulate with linear layer weighting
                layer_weight = (idx + 1) / L
                centrality = centrality_l * layer_weight + centrality
        else:
            raise ValueError(f"Unknown method: {self.method}")

        # Select top-k by centrality
        _, top_indices = centrality.topk(self.k_attention, dim=-1)

        return centrality, top_indices

    # ------------------------------------------------------------------
    def _select_uniform_spatial(
        self,
        B: int,
        P: int,
        device: torch.device,
    ) -> torch.Tensor:
        """Select tokens uniformly from spatial grid.

        Strategy: Divide grid into regions and sample 1 token per region.

        Returns:
            indices: (B, k_uniform) selected token indices.
        """
        grid_h, grid_w = self.grid_size
        expected_P = grid_h * grid_w

        if P != expected_P:
            # Fallback: random sampling if grid size mismatch
            indices = torch.randint(0, P, (B, self.k_uniform), device=device)
            return indices

        # Compute step size for uniform sampling
        # Want sqrt(k_uniform) regions per dimension
        n_regions_per_dim = max(1, int(math.sqrt(self.k_uniform) + 0.5))
        step_h = max(1, grid_h // n_regions_per_dim)
        step_w = max(1, grid_w // n_regions_per_dim)

        # Generate uniform grid indices
        uniform_indices_flat: list[int] = []
        for i in range(0, grid_h, step_h):
            for j in range(0, grid_w, step_w):
                if len(uniform_indices_flat) < self.k_uniform:
                    idx = i * grid_w + j
                    uniform_indices_flat.append(idx)

        # Pad if needed
        while len(uniform_indices_flat) < self.k_uniform:
            uniform_indices_flat.append(P // 2)  # Center token as fallback

        uniform_indices_flat = uniform_indices_flat[:self.k_uniform]
        uniform_indices = torch.tensor(
            uniform_indices_flat, device=device, dtype=torch.long
        ).unsqueeze(0).expand(B, -1)

        return uniform_indices

    # ------------------------------------------------------------------
    def _select_random(
        self,
        attention_indices: torch.Tensor,
        uniform_indices: torch.Tensor,
        B: int,
        P: int,
        device: torch.device,
    ) -> torch.Tensor:
        """Select random tokens, avoiding already selected ones.

        Returns:
            indices: (B, k_random) selected token indices.
        """
        if self.k_random == 0:
            return torch.zeros(B, 0, dtype=torch.long, device=device)

        # Build mask of already selected tokens
        selected_mask = torch.zeros(B, P, dtype=torch.bool, device=device)
        selected_mask.scatter_(1, attention_indices, True)
        selected_mask.scatter_(1, uniform_indices, True)

        # Sample from remaining tokens
        random_indices_list: list[torch.Tensor] = []
        all_indices = torch.arange(P, device=device)

        for b in range(B):
            available = all_indices[~selected_mask[b]]

            if len(available) >= self.k_random:
                # Sample without replacement
                perm = torch.randperm(len(available), device=device)[:self.k_random]
                random_idx = available[perm]
            else:
                # Not enough unique tokens - sample with replacement from all tokens
                random_idx = all_indices[
                    torch.randint(0, P, (self.k_random,), device=device)
                ]

            random_indices_list.append(random_idx)

        random_indices = torch.stack(random_indices_list, dim=0)
        return random_indices

    # ------------------------------------------------------------------
    def extra_repr(self) -> str:
        """String representation for debugging."""
        return (
            f"num_tokens={self.num_tokens}, "
            f"attention={self.k_attention}, "
            f"uniform={self.k_uniform}, "
            f"random={self.k_random}, "
            f"grid_size={self.grid_size}, "
            f"method={self.method}"
        )