from __future__ import annotations """ViTGraph — ViT + TRAM Sparse Token Selection + GNN. Replaces hand-crafted minutiae extraction with learned sparse token selection: a pretrained ViT extracts dense patch features, TRAM picks the K most important tokens via attention centrality, and a lightweight GNN refines their representations through message passing on a dynamic k-NN graph with grid-based relational positional encoding. Pipeline:: Image (B, 1, H, W) │ repeat to 3ch + resize ▼ ViT backbone → P patch tokens (B, P, 768) + L attention maps │ TRAM centrality selection → K tokens (B, K, 768) │ Input projection: 768 → embed_dim (256) │ Grid RPE from (row, col) positions → (B, K, K, rpe_dim) │ L × LocalGraphAttention (k-NN + RPE, PT-V2 style) │ Attentive pooling → (B, embed_dim) │ Projection head → L2-norm → (B, output_dim) Key design choices: • **Sparse over dense**: K=30 tokens instead of all P=256 → O(K²) edges vs O(P²). Graph becomes semantically meaningful rather than grid connectivity, and noise from background patches is eliminated. • **Learned sparse keypoints**: TRAM centrality serves the same role as minutiae (30–80 sparse semantic keypoints) but is learned end-to-end rather than hand-crafted. • **Fewer GNN layers**: 2–4 vs 6 in MDGT. Node features are already very rich (768-D, 12 layers of ViT self-attention) — the GNN only needs to add explicit local topology reasoning. • **RPE from grid positions**: Relative (Δrow, Δcol) encoding preserves distortion-invariant geometric inductive bias, analogous to the minutiae RPE in MDGT. """ import torch import torch.nn as nn import torch.nn.functional as F from ..configs.default import ViTGraphConfig from .vit_backbone import ViTBackbone from .tram import TRAMSelector from .grid_rpe import GridRelationalPE from .attention import LocalGraphAttention from .pooling import AttentivePool, MeanMaxPool, MultiHeadPool from .dynamic_graph import knn class ViTGraph(nn.Module): """ViT backbone + TRAM token selection + GNN message passing. Parameters ---------- cfg : ViTGraphConfig Full configuration for the ViT-Graph model. """ def __init__(self, cfg: ViTGraphConfig | None = None): super().__init__() if cfg is None: cfg = ViTGraphConfig() # ---- ViT backbone (pretrained, optionally frozen) ---- self.vit = ViTBackbone( model_name=cfg.vit.model_name, pretrained=cfg.vit.pretrained, freeze=cfg.vit.freeze, image_size=cfg.vit.image_size, ) vit_dim = self.vit.embed_dim self._vit_image_size = (cfg.vit.image_size, cfg.vit.image_size) # ---- TRAM token selector (training-free) ---- self.tram = TRAMSelector( num_tokens=cfg.tram.num_tokens, method="tram", ) # ---- Input projection: vit_dim → embed_dim ---- self.input_proj = nn.Sequential( nn.Linear(vit_dim, cfg.embed_dim), nn.LayerNorm(cfg.embed_dim), nn.GELU(), nn.Linear(cfg.embed_dim, cfg.embed_dim), ) # ---- Grid RPE ---- rpe_cfg = cfg.grid_rpe self.grid_rpe = GridRelationalPE( input_dim=rpe_cfg.input_dim, hidden_dim=rpe_cfg.hidden_dim, output_dim=rpe_cfg.output_dim, num_layers=rpe_cfg.num_layers, activation=rpe_cfg.activation, ) # ---- GNN layers (reuse MDGT attention module) ---- self.layers = nn.ModuleList([ LocalGraphAttention( embed_dim=cfg.embed_dim, num_heads=cfg.attention.num_heads, head_dim=cfg.attention.head_dim, rpe_dim=rpe_cfg.output_dim, k=cfg.graph.k, dropout=cfg.attention.dropout, distance_metric=cfg.graph.distance_metric, ) for _ in range(cfg.num_layers) ]) # ---- Pooling ---- pool_cfg = cfg.pooling if pool_cfg.method == "meanmax": self.pool = MeanMaxPool(cfg.embed_dim) pool_out_dim = cfg.embed_dim * 2 elif pool_cfg.method == "attentive": self.pool = AttentivePool( cfg.embed_dim, hidden_dim=pool_cfg.hidden_dim, ) pool_out_dim = cfg.embed_dim elif pool_cfg.method == "multihead": self.pool = MultiHeadPool( cfg.embed_dim, num_heads=pool_cfg.num_heads, hidden_dim=pool_cfg.hidden_dim, ) pool_out_dim = cfg.embed_dim else: raise ValueError(f"Unknown pooling method: {pool_cfg.method}") # ---- Projection head ---- self.head = nn.Sequential( nn.Linear(pool_out_dim, cfg.embed_dim), nn.BatchNorm1d(cfg.embed_dim), nn.GELU(), nn.Linear(cfg.embed_dim, cfg.output_dim), nn.BatchNorm1d(cfg.output_dim), ) # ---- Graph settings ---- self.dynamic_graph = cfg.graph.dynamic_graph self._graph_k = cfg.graph.k self._graph_metric = cfg.graph.distance_metric # Init only non-pretrained modules (preserve ViT weights) for module in [self.input_proj, self.layers, self.pool, self.head]: module.apply(self._init_weights) # ------------------------------------------------------------------ @staticmethod def _init_weights(m: nn.Module): if isinstance(m, nn.Linear): nn.init.xavier_uniform_(m.weight) if m.bias is not None: nn.init.zeros_(m.bias) # ------------------------------------------------------------------ def forward( self, images: torch.Tensor, ) -> torch.Tensor: """ Args: images: ``(B, 1, H, W)`` grayscale fingerprint images. Automatically repeated to 3 channels and resized for the ViT backbone. Returns: emb: ``(B, output_dim)`` L2-normalised fingerprint embedding. """ # 0. Grayscale → 3-channel + resize for ViT if images.shape[1] == 1: images = images.expand(-1, 3, -1, -1) if images.shape[-2:] != self._vit_image_size: images = F.interpolate( images, size=self._vit_image_size, mode="bilinear", align_corners=False, ) # 1. ViT → patch tokens + attention maps patch_tokens, attn_maps = self.vit(images) # 2. TRAM → K sparse tokens selected_tokens, selected_indices, _ = self.tram( patch_tokens, attn_maps, num_prefix_tokens=self.vit.num_prefix_tokens, ) # (B, K, vit_dim), (B, K) # 3. Input projection x = self.input_proj(selected_tokens) # (B, K, embed_dim) # 4. Grid RPE from token positions rpe_emb = self.grid_rpe( selected_indices, self.vit.grid_size, ) # (B, K, K, rpe_dim) # 5. GNN message passing (no mask — all K tokens are valid) K = x.shape[1] graph_k = min(self._graph_k, K) static_idx = None if not self.dynamic_graph: static_idx = knn(x, graph_k, metric=self._graph_metric) for layer in self.layers: x = layer(x, rpe=rpe_emb, mask=None, precomputed_idx=static_idx) # 6. Pool → fixed-size embedding emb = self.pool(x, mask=None) # 7. Project + L2-normalise emb = self.head(emb) emb = F.normalize(emb, p=2, dim=-1) return emb