from __future__ import annotations """Custom Vision Transformer trained from scratch. Supports ViT-Tiny (192-D, 5.7M), ViT-Small (384-D), ViT-Base (768-D), and a DINOv2-compatible ViT-B/14 profile (``dinov2_vitb14_reg``). Returns patch tokens, CLS token, and all per-layer attention maps for TRAM. Unlike the timm-based ``vit_backbone.py`` (pretrained models), this module is designed to be trained from scratch on fingerprint data with 1-channel (grayscale) input — no 3-channel replication needed. """ import torch import torch.nn as nn # ───────────────────────────────────────────── DropPath ──── class DropPath(nn.Module): """Stochastic depth (per-sample drop of residual branches).""" def __init__(self, drop_prob: float = 0.0): super().__init__() self.drop_prob = drop_prob def forward(self, x: torch.Tensor) -> torch.Tensor: if self.drop_prob == 0.0 or not self.training: return x keep = 1.0 - self.drop_prob shape = (x.shape[0],) + (1,) * (x.ndim - 1) mask = torch.rand(shape, dtype=x.dtype, device=x.device).add_(keep).floor_() return x / keep * mask # ───────────────────────────────────────────── PatchEmbed ── class PatchEmbed(nn.Module): """Image → non-overlapping patch tokens via Conv2d.""" def __init__( self, img_size: int = 224, patch_size: int = 16, in_chans: int = 1, embed_dim: int = 192, ): super().__init__() self.in_chans = in_chans self.grid_size = (img_size // patch_size, img_size // patch_size) self.num_patches = self.grid_size[0] * self.grid_size[1] self.proj = nn.Conv2d( in_chans, embed_dim, kernel_size=patch_size, stride=patch_size, ) def forward(self, x: torch.Tensor) -> torch.Tensor: if x.shape[1] != self.in_chans: # Allow transparent conversion between RGB and grayscale inputs. if self.in_chans == 1 and x.shape[1] == 3: x = x.mean(dim=1, keepdim=True) elif self.in_chans == 3 and x.shape[1] == 1: x = x.repeat(1, 3, 1, 1) else: raise RuntimeError( f"PatchEmbed expected {self.in_chans} channels, got {x.shape[1]}" ) return self.proj(x).flatten(2).transpose(1, 2) # (B, N, D) # ───────────────────────────────────────────── Attention ─── class Attention(nn.Module): """Multi-head self-attention — returns output AND attention weights.""" def __init__( self, dim: int, num_heads: int = 12, attn_drop: float = 0.0, proj_drop: float = 0.0, ): super().__init__() self.num_heads = num_heads self.head_dim = dim // num_heads self.scale = self.head_dim ** -0.5 self.qkv = nn.Linear(dim, dim * 3) self.attn_drop = nn.Dropout(attn_drop) self.proj = nn.Linear(dim, dim) self.proj_drop = nn.Dropout(proj_drop) def forward( self, x: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: B, N, C = x.shape H, d = self.num_heads, self.head_dim qkv = self.qkv(x).reshape(B, N, 3, H, d).permute(2, 0, 3, 1, 4) q, k, v = qkv.unbind(0) # each (B, H, N, d) attn = (q @ k.transpose(-2, -1)) * self.scale attn = attn.softmax(dim=-1) # (B, H, N, N) attn_weights = attn.detach() # save for TRAM out = (self.attn_drop(attn) @ v).transpose(1, 2).reshape(B, N, C) out = self.proj_drop(self.proj(out)) return out, attn_weights # ───────────────────────────────────────────── Block ─────── class Block(nn.Module): """Pre-norm Transformer block with stochastic depth.""" def __init__( self, dim: int, num_heads: int, mlp_ratio: float = 4.0, drop: float = 0.0, attn_drop: float = 0.0, drop_path: float = 0.0, ): super().__init__() self.norm1 = nn.LayerNorm(dim) self.attn = Attention(dim, num_heads, attn_drop, drop) self.drop_path = DropPath(drop_path) if drop_path > 0 else nn.Identity() self.norm2 = nn.LayerNorm(dim) hidden = int(dim * mlp_ratio) self.mlp = nn.Sequential( nn.Linear(dim, hidden), nn.GELU(), nn.Dropout(drop), nn.Linear(hidden, dim), nn.Dropout(drop), ) def forward( self, x: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor]: attn_out, attn_weights = self.attn(self.norm1(x)) x = x + self.drop_path(attn_out) x = x + self.drop_path(self.mlp(self.norm2(x))) return x, attn_weights # ───────────────────────────────────────────── ViT ───────── class ViT(nn.Module): """Vision Transformer with per-layer attention extraction. Preset configurations:: tiny: 192-D, 12 layers, 12 heads (~5.7M params, 1ch input) small: 384-D, 12 layers, 12 heads (~22M params) base: 768-D, 12 layers, 12 heads (~86M params) dinov2_vitb14_reg: 768-D, 12 layers, 12 heads (profile-compatible) Parameters ---------- variant : str ``"tiny"`` | ``"small"`` | ``"base"`` | ``"dinov2_vitb14_reg"``. img_size : int Input image resolution (square). patch_size : int Patch side length in pixels. in_chans : int Input channels (1 for grayscale, 3 for RGB). drop_rate : float Dropout for embeddings and MLP. attn_drop_rate : float Dropout on attention weights. drop_path_rate : float Stochastic depth max rate (linearly increased per layer). """ PRESETS: dict[str, dict] = { "tiny": dict(embed_dim=192, depth=12, num_heads=12), "small": dict(embed_dim=384, depth=12, num_heads=12), "base": dict(embed_dim=768, depth=12, num_heads=12), "dinov2_vitb14_reg": dict(embed_dim=768, depth=12, num_heads=12), } def __init__( self, variant: str = "tiny", img_size: int = 224, patch_size: int = 16, in_chans: int = 1, drop_rate: float = 0.0, attn_drop_rate: float = 0.0, drop_path_rate: float = 0.1, ): super().__init__() preset = self.PRESETS[variant] self.embed_dim: int = preset["embed_dim"] depth: int = preset["depth"] num_heads: int = preset["num_heads"] self.patch_embed = PatchEmbed(img_size, patch_size, in_chans, self.embed_dim) num_patches = self.patch_embed.num_patches self.grid_size = self.patch_embed.grid_size self.cls_token = nn.Parameter(torch.zeros(1, 1, self.embed_dim)) self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, self.embed_dim)) self.pos_drop = nn.Dropout(drop_rate) dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] self.blocks = nn.ModuleList([ Block(self.embed_dim, num_heads, mlp_ratio=4.0, drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i]) for i in range(depth) ]) self.norm = nn.LayerNorm(self.embed_dim) self._init_weights() # ------------------------------------------------------------------ def _init_weights(self): nn.init.trunc_normal_(self.pos_embed, std=0.02) nn.init.trunc_normal_(self.cls_token, std=0.02) for m in self.modules(): if isinstance(m, nn.Linear): nn.init.trunc_normal_(m.weight, std=0.02) if m.bias is not None: nn.init.zeros_(m.bias) elif isinstance(m, nn.LayerNorm): nn.init.ones_(m.weight) nn.init.zeros_(m.bias) elif isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode="fan_out") if m.bias is not None: nn.init.zeros_(m.bias) # ------------------------------------------------------------------ def forward( self, images: torch.Tensor ) -> tuple[torch.Tensor, torch.Tensor, list[torch.Tensor]]: """ Args: images: ``(B, C, H, W)`` fingerprint images. Returns: patch_tokens: ``(B, N, D)`` — patch features (196 tokens for 224px). cls_token: ``(B, D)`` — CLS token (for auxiliary classification). attn_maps: list of L tensors ``(B, H, N+1, N+1)`` attention weights. """ x = self.patch_embed(images) # (B, N, D) cls = self.cls_token.expand(x.shape[0], -1, -1) # (B, 1, D) x = torch.cat([cls, x], dim=1) # (B, N+1, D) x = self.pos_drop(x + self.pos_embed) attn_maps: list[torch.Tensor] = [] for blk in self.blocks: x, attn = blk(x) attn_maps.append(attn) x = self.norm(x) return x[:, 1:], x[:, 0], attn_maps