File size: 8,052 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 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | 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
|