| 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__() |
|
|
| |
| 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 |
|
|
| |
| 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) |
|
|
| |
| total_k = self.k_attention + self.k_uniform + self.k_random |
| if total_k != num_tokens: |
| |
| 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 |
|
|
| |
| centrality, attention_indices = self._select_by_attention( |
| attn_maps, num_prefix_tokens, B, P, device |
| ) |
|
|
| |
| uniform_indices = self._select_uniform_spatial(B, P, device) |
|
|
| |
| random_indices = self._select_random( |
| attention_indices, uniform_indices, B, P, device |
| ) |
|
|
| |
| all_selected = torch.cat([attention_indices, uniform_indices, random_indices], dim=1) |
| all_selected_sorted, _ = all_selected.sort(dim=-1) |
|
|
| |
| 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": |
| |
| for attn in attn_maps: |
| |
| a = attn.max(dim=1).values |
| a_pp = a[:, num_prefix_tokens:, num_prefix_tokens:] |
| |
| centrality = centrality + a_pp.sum(dim=1) |
|
|
| elif self.method in ("eigenvector", "tram"): |
| |
| L = len(attn_maps) |
| for idx, attn in enumerate(attn_maps): |
| a = attn.max(dim=1).values |
| a_pp = a[:, num_prefix_tokens:, num_prefix_tokens:] |
| |
| d_in = a_pp.sum(dim=1) |
| |
| a_rescaled = a_pp * d_in.unsqueeze(-1) |
| |
| centrality_l = a_rescaled.sum(dim=1) |
| |
| layer_weight = (idx + 1) / L |
| centrality = centrality_l * layer_weight + centrality |
| else: |
| raise ValueError(f"Unknown method: {self.method}") |
|
|
| |
| _, 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: |
| |
| indices = torch.randint(0, P, (B, self.k_uniform), device=device) |
| return indices |
|
|
| |
| |
| 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) |
|
|
| |
| 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) |
|
|
| |
| while len(uniform_indices_flat) < self.k_uniform: |
| uniform_indices_flat.append(P // 2) |
|
|
| 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) |
|
|
| |
| 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) |
|
|
| |
| 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: |
| |
| perm = torch.randperm(len(available), device=device)[:self.k_random] |
| random_idx = available[perm] |
| else: |
| |
| 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}" |
| ) |
|
|