| from __future__ import annotations |
|
|
| """MDGTv2 — DINOv2/ViT + TRAM + GNN full pipeline. |
| |
| End-to-end fingerprint embedding without external minutiae extraction:: |
| |
| Image (B, 1, 224, 224) |
| ├─ DINOv2 backbone → P patch tokens + CLS token + 12 attn maps |
| │ │ │ |
| │ TRAM selection → K tokens cls_head → cls_logits |
| │ │ |
| │ Input projection → gnn_dim |
| │ │ |
| │ k-NN graph + GridRelationalPE (5→64-dim) |
| │ │ |
| │ L × GATLayerRPE (3-way RPE modulation) |
| │ │ |
| │ Multi-head attentive pooling |
| │ │ |
| └──────────── Projection → 256-D → L2-norm → embedding |
| |
| Backbone options: |
| ``"dinov2_vits14"`` — pretrained DINOv2 ViT-S/14 (384-D, default). |
| ``"dinov2_vitb14"`` — pretrained DINOv2 ViT-B/14 (768-D). |
| ``"tiny"`` / ``"small"`` / ``"base"`` — custom ViT from scratch. |
| |
| Returns both ``embedding`` (for ArcFace + Triplet) and ``cls_logits`` |
| (for auxiliary CLS classification loss). |
| """ |
|
|
| import torch |
| import torch.nn as nn |
| import torch.nn.functional as F |
|
|
| from .dinov2_backbone import DINOv2Backbone |
| from .vit import ViT |
| from .tram import TRAMSelector |
| from .gat_rpe import GATLayerRPE |
| from .grid_rpe import GridRelationalPE |
| from .pooling import MultiHeadPool, AttentivePool |
| from .dynamic_graph import knn |
|
|
|
|
| def _knn_to_mask(idx: torch.Tensor, K: int) -> torch.Tensor: |
| """Convert k-NN indices ``(B, K, k)`` to adjacency mask ``(B, K, K)``.""" |
| B = idx.shape[0] |
| k = idx.shape[2] |
| mask = torch.zeros(B, K, K, dtype=torch.bool, device=idx.device) |
| batch = torch.arange(B, device=idx.device)[:, None, None].expand_as(idx) |
| nodes = torch.arange(K, device=idx.device)[None, :, None].expand_as(idx) |
| mask[batch, nodes, idx] = True |
| return mask |
|
|
|
|
| class MDGTv2(nn.Module): |
| """MDGT v2: DINOv2/ViT + TRAM + GNN pipeline. |
| |
| Parameters |
| ---------- |
| vit_variant : str |
| Backbone selector. DINOv2 pretrained names (``"dinov2_vits14"``, |
| ``"dinov2_vitb14"``) load from torch.hub. Custom ViT names |
| (``"tiny"``, ``"small"``, ``"base"``) train from scratch. |
| num_classes : int |
| Number of training identities (for auxiliary CLS head). |
| tram_k : int |
| Number of tokens selected by TRAM. |
| gnn_layers : int |
| Number of GATLayerRPE layers. |
| gnn_dim : int |
| GNN hidden dimension. If 0, defaults to 256. |
| gnn_heads : int |
| Number of attention heads in GNN. |
| gnn_k : int |
| k-NN neighbor count for graph construction. |
| pool_heads : int |
| Number of seed vectors for multi-head attentive pooling. |
| output_dim : int |
| Final embedding dimension (L2-normalised). |
| image_size : int |
| Input image resolution (square). |
| rpe_dim : int |
| GridRelationalPE output dimension (fed into GNN 3-way RPE). |
| drop_rate : float |
| Dropout rate for embeddings and MLP. |
| drop_path_rate : float |
| Stochastic depth rate (custom ViT only; DINOv2 ignores this). |
| patch_size : int |
| ViT patch size (custom ViT only; DINOv2 uses its own). |
| """ |
|
|
| DINOV2_MODELS = DINOv2Backbone.KNOWN_MODELS |
|
|
| def __init__( |
| self, |
| vit_variant: str = "dinov2_vits14", |
| num_classes: int = 100, |
| tram_k: int = 30, |
| gnn_layers: int = 4, |
| gnn_dim: int = 0, |
| gnn_heads: int = 4, |
| gnn_k: int = 9, |
| pool_heads: int = 4, |
| output_dim: int = 256, |
| image_size: int = 224, |
| rpe_dim: int = 64, |
| drop_rate: float = 0.0, |
| drop_path_rate: float = 0.1, |
| patch_size: int = 0, |
| ): |
| super().__init__() |
|
|
| |
| self._use_dinov2 = vit_variant in self.DINOV2_MODELS |
|
|
| if self._use_dinov2: |
| self.vit = DINOv2Backbone( |
| model_name=vit_variant, |
| image_size=image_size, |
| ) |
| else: |
| if patch_size <= 0: |
| patch_size = 14 if vit_variant == "dinov2_vitb14_reg" else 16 |
| self.vit = ViT( |
| variant=vit_variant, |
| img_size=image_size, |
| patch_size=patch_size, |
| in_chans=1, |
| drop_rate=drop_rate, |
| drop_path_rate=drop_path_rate, |
| ) |
|
|
| vit_dim = self.vit.embed_dim |
|
|
| |
| if gnn_dim <= 0: |
| gnn_dim = vit_dim if vit_variant == "tiny" else 256 |
| self._gnn_dim = gnn_dim |
|
|
| |
| self.tram = TRAMSelector( |
| num_tokens=tram_k, |
| method="tram", |
| ) |
|
|
| |
| self.input_proj = nn.Sequential( |
| nn.Linear(vit_dim, gnn_dim), |
| nn.LayerNorm(gnn_dim), |
| nn.GELU(), |
| ) |
|
|
| |
| self.grid_rpe = GridRelationalPE( |
| input_dim=5, |
| hidden_dim=rpe_dim, |
| output_dim=rpe_dim, |
| ) |
| self._rpe_dim = rpe_dim |
|
|
| |
| self._gnn_k = gnn_k |
| self.gnn_layers = nn.ModuleList([ |
| GATLayerRPE( |
| dim=gnn_dim, |
| num_heads=gnn_heads, |
| rpe_dim=rpe_dim, |
| dropout=drop_rate, |
| ) |
| for _ in range(gnn_layers) |
| ]) |
|
|
| |
| self.pool = MultiHeadPool( |
| gnn_dim, num_heads=pool_heads, hidden_dim=gnn_dim, |
| ) |
|
|
| |
| self.cls_proj = nn.Sequential( |
| nn.Linear(vit_dim, gnn_dim), |
| nn.LayerNorm(gnn_dim), |
| nn.GELU(), |
| ) |
|
|
| |
| |
| self.head = nn.Sequential( |
| nn.Linear(gnn_dim * 2, gnn_dim), |
| nn.BatchNorm1d(gnn_dim), |
| nn.GELU(), |
| nn.Linear(gnn_dim, output_dim), |
| nn.BatchNorm1d(output_dim), |
| ) |
|
|
| |
| |
| |
| self.cls_head = nn.Linear(output_dim, num_classes) |
|
|
| |
| self._warmup_mode = False |
|
|
| |
| for module in [self.input_proj, self.cls_proj, self.gnn_layers, |
| self.pool, self.head, self.grid_rpe]: |
| module.apply(self._init_weights) |
| nn.init.trunc_normal_(self.cls_head.weight, std=0.02) |
| nn.init.zeros_(self.cls_head.bias) |
|
|
| |
| @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 |
| ) -> tuple[torch.Tensor, torch.Tensor]: |
| """ |
| Args: |
| images: ``(B, 1, 224, 224)`` grayscale fingerprint. |
| |
| Returns: |
| emb: ``(B, output_dim)`` L2-normalised embedding. |
| cls_logits: ``(B, num_classes)`` CLS-token classification logits. |
| """ |
| |
| patch_tokens, cls_token, attn_maps = self.vit(images) |
|
|
| |
| cls_emb = self.cls_proj(cls_token) |
|
|
| |
| if self._warmup_mode: |
| x = self.input_proj(patch_tokens) |
| gnn_emb = self.pool(x, mask=None) |
| pre_norm = self.head(torch.cat([gnn_emb, cls_emb], dim=-1)) |
| cls_logits = self.cls_head(pre_norm) |
| emb = F.normalize(pre_norm, p=2, dim=-1) |
| return emb, cls_logits |
|
|
| |
| num_prefix = getattr(self.vit, "num_prefix_tokens", 1) |
| selected_tokens, selected_indices, _ = self.tram( |
| patch_tokens, attn_maps, num_prefix_tokens=num_prefix, |
| ) |
|
|
| |
| x = self.input_proj(selected_tokens) |
| K = x.shape[1] |
|
|
| |
| graph_k = min(self._gnn_k, K) |
| idx = knn(x, graph_k, metric="euclidean") |
| edge_mask = _knn_to_mask(idx, K) |
|
|
| |
| rpe = self.grid_rpe(selected_indices, self.vit.grid_size) |
|
|
| |
| for layer in self.gnn_layers: |
| x = layer(x, rpe, edge_mask) |
|
|
| |
| gnn_emb = self.pool(x, mask=None) |
| pre_norm = self.head(torch.cat([gnn_emb, cls_emb], dim=-1)) |
|
|
| |
| cls_logits = self.cls_head(pre_norm) |
| emb = F.normalize(pre_norm, p=2, dim=-1) |
|
|
| return emb, cls_logits |
|
|
| |
| def set_warmup_mode(self, enabled: bool): |
| self._warmup_mode = bool(enabled) |
|
|
| |
| def freeze_vit(self): |
| """Freeze only the backbone (ViT or DINOv2). |
| |
| The auxiliary ``cls_head`` stays trainable so phase-2 runs can still |
| use a learnable softmax head on top of frozen CLS features. |
| """ |
| if self._use_dinov2: |
| self.vit.freeze() |
| else: |
| for p in self.vit.parameters(): |
| p.requires_grad = False |
|
|
| def unfreeze_vit(self): |
| """Unfreeze backbone.""" |
| if self._use_dinov2: |
| self.vit.unfreeze() |
| else: |
| for p in self.vit.parameters(): |
| p.requires_grad = True |
|
|