File size: 6,167 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
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