from __future__ import annotations """Grid-based Relational Positional Encoding for sparse ViT tokens. After TRAM selects K sparse tokens from a ViT patch grid, their spatial relationships need to be explicitly re-encoded. This module computes pairwise geometric features based on grid positions and projects them through an MLP — the ViT analog of ``RelationalPE`` used in MDGT. For each pair of selected tokens (i, j) at grid positions ``(row_i, col_i)`` and ``(row_j, col_j)``: r_ij = [Δrow_n, Δcol_n, dist_n, cos(α_ij), sin(α_ij)] ∈ R^5 PE(i,j) = MLP(r_ij) ∈ R^d Components: (Δrow, Δcol) Relative grid displacement — translation-invariant. dist Euclidean grid distance (explicit for convergence). (cos α, sin α) Direction angle on the grid — complete polar representation with dist. All spatial features are normalised per-sample by the maximum grid distance, keeping all 5 dims in ~ [-1, 1] range. Note: Unlike minutiae-based RPE (7-dim), grid RPE has no orientation component — ViT patch tokens carry no explicit ridge direction. The directional information is implicitly encoded in the ViT features. """ import torch import torch.nn as nn def compute_grid_pairwise( row: torch.Tensor, col: torch.Tensor, ) -> torch.Tensor: """Compute pairwise 5-dim relational features among grid positions. Args: row: ``(B, K)`` row indices (float). col: ``(B, K)`` column indices (float). Returns: rel: ``(B, K, K, 5)`` — ``[Δrow_n, Δcol_n, dist_n, cos α, sin α]`` """ dr = row.unsqueeze(2) - row.unsqueeze(1) # (B, K, K) dc = col.unsqueeze(2) - col.unsqueeze(1) dist = (dr ** 2 + dc ** 2 + 1e-8).sqrt() # Per-sample normalisation (keeps all dims ~ [-1, 1]) scale = dist.amax(dim=(1, 2), keepdim=True).clamp(min=1.0) dr_n = dr / scale dc_n = dc / scale dist_n = dist / scale alpha = torch.atan2(dc, dr) cos_a = torch.cos(alpha) sin_a = torch.sin(alpha) return torch.stack([dr_n, dc_n, dist_n, cos_a, sin_a], dim=-1) class GridRelationalPE(nn.Module): """Project grid-position pairwise relations into a learned embedding. Architecture mirrors ``RelationalPE`` from MDGT but uses 5-dim grid features instead of 7-dim minutiae features. Parameters ---------- input_dim : raw relation dimensionality (5 for grid positions). hidden_dim : MLP hidden width. output_dim : final embedding size (fed into attention RPE projections). num_layers : depth of the projection MLP. activation : nonlinearity (``"gelu"`` | ``"relu"``). """ def __init__( self, input_dim: int = 5, hidden_dim: int = 64, output_dim: int = 64, num_layers: int = 2, activation: str = "gelu", ): super().__init__() act = nn.GELU() if activation == "gelu" else nn.ReLU() layers: list[nn.Module] = [] dims = [input_dim] + [hidden_dim] * (num_layers - 1) + [output_dim] for i in range(len(dims) - 1): layers.append(nn.Linear(dims[i], dims[i + 1])) if i < len(dims) - 2: layers.append(nn.LayerNorm(dims[i + 1])) layers.append(act) self.mlp = nn.Sequential(*layers) self._init_weights() def _init_weights(self): for m in self.mlp: if isinstance(m, nn.Linear): nn.init.kaiming_normal_(m.weight, nonlinearity="relu") if m.bias is not None: nn.init.zeros_(m.bias) # ------------------------------------------------------------------ def forward( self, selected_indices: torch.Tensor, grid_size: tuple[int, int], ) -> torch.Tensor: """ Args: selected_indices: ``(B, K)`` indices into the flattened patch grid (0 … P-1). grid_size: ``(grid_h, grid_w)`` spatial grid dims. Returns: rpe: ``(B, K, K, output_dim)`` learned relational embeddings. """ row = (selected_indices // grid_size[1]).float() col = (selected_indices % grid_size[1]).float() rel = compute_grid_pairwise(row, col) # (B, K, K, 5) return self.mlp(rel) # (B, K, K, output_dim)