from __future__ import annotations """TRAM — Token Reduction via Attention-based Multilayer network centrality. Original paper implementation adapted for post-hoc token selection: 1. For each ViT layer, extract patch-to-patch attention (max across heads). 2. Compute weighted in-degree centrality: c_l[j] = Σ_i A[i,j] * d_in[i] where d_in[i] = Σ_j A[i,j] is the in-degree of the source token. 3. Accumulate across layers with linear weighting: centrality = c_l * (l/L) + centrality_prev 4. Select top-K tokens by centrality score. Reference: Marchetti et al. — TRAM: Token Reduction via Attention-based Multilayer network centrality (Neural Networks, 2024). """ import torch import torch.nn as nn class TRAMSelector(nn.Module): """Select K most important tokens using TRAM centrality. Parameters ---------- num_tokens : int Number of tokens to keep (K). method : str Centrality method: - ``"tram"``: original paper weighted in-degree centrality (default). - ``"incoming_sum"``: simple incoming attention sum across layers. """ def __init__( self, num_tokens: int = 30, method: str = "tram", ): super().__init__() self.num_tokens = num_tokens self.method = method # ------------------------------------------------------------------ def forward( self, patch_tokens: torch.Tensor, attn_maps: list[torch.Tensor], num_prefix_tokens: int = 1, ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: """ 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: how many prefix tokens (CLS + registers) to skip when extracting patch-to-patch attention. Returns: selected_tokens: ``(B, K, D)`` features of selected tokens. selected_indices: ``(B, K)`` indices into the P patch tokens (sorted to preserve spatial order). centrality_scores: ``(B, P)`` centrality score for every patch. """ B, P, D = patch_tokens.shape K = min(self.num_tokens, P) # ---- Compute centrality (no grad — discrete selection) ---- if self.method == "incoming_sum": indices, centrality = self._compute_incoming_sum( attn_maps, num_prefix_tokens, B, P, patch_tokens.device, ) else: indices, centrality = self._compute_tram_centrality( attn_maps, num_prefix_tokens, B, P, patch_tokens.device, ) # ---- Gather selected tokens (WITH grad for end-to-end ViT finetune) ---- selected = torch.gather( patch_tokens, dim=1, index=indices.unsqueeze(-1).expand(-1, -1, D), ) # (B, K, D) return selected, indices, centrality # ------------------------------------------------------------------ @torch.no_grad() def _compute_tram_centrality( self, attn_maps: list[torch.Tensor], num_prefix_tokens: int, B: int, P: int, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: """Original TRAM paper centrality (Marchetti et al.). For each layer l (0-indexed): 1. Extract patch attention: max across heads, drop CLS/prefix. 2. In-degree: d_in[j] = Σ_i A[i,j] 3. Rescale: A'[i,j] = A[i,j] * d_in[i] (weight attention by source token importance) 4. Weighted centrality: c_l[j] = Σ_i A'[i,j] 5. Accumulate: centrality = c_l * ((l+1)/L) + centrality_prev Deeper layers get higher weight via linear scaling ``(l+1)/L``. """ K = min(self.num_tokens, P) L = len(attn_maps) centrality = torch.zeros(B, P, device=device) for idx, attn in enumerate(attn_maps): # Max across heads (paper's create_matrices) 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[j] = Σ_i A[i,j] — sum over source dim d_in = a_pp.sum(dim=1) # (B, P) # Rescale matrix: weight rows by source's in-degree # A'[i,j] = A[i,j] * d_in[i] a_rescaled = a_pp * d_in.unsqueeze(-1) # (B, P, P) # Weighted in-degree for this layer # c_l[j] = Σ_i A'[i,j] = Σ_i A[i,j] * d_in[i] centrality_l = a_rescaled.sum(dim=1) # (B, P) # Accumulate with linear layer weighting: (l+1)/L layer_weight = (idx + 1) / L centrality = centrality_l * layer_weight + centrality _, top_indices = centrality.topk(K, dim=-1) return top_indices.sort(dim=-1).values, centrality # ------------------------------------------------------------------ @torch.no_grad() def _compute_incoming_sum( self, attn_maps: list[torch.Tensor], num_prefix_tokens: int, B: int, P: int, device: torch.device, ) -> tuple[torch.Tensor, torch.Tensor]: """Simple incoming attention sum across layers (fallback method). For each layer, max across heads then sum incoming attention. """ K = min(self.num_tokens, P) centrality = torch.zeros(B, P, device=device) for attn in attn_maps: a = attn.max(dim=1).values # (B, N, N) a_pp = a[:, num_prefix_tokens:, num_prefix_tokens:] # (B, P, P) centrality = centrality + a_pp.sum(dim=1) # (B, P) _, top_indices = centrality.topk(K, dim=-1) return top_indices.sort(dim=-1).values, centrality