UFR-Fing / src /models /mdgt /vit_backbone.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
6.57 kB
from __future__ import annotations
"""ViT backbone wrapper with per-layer attention map extraction.
Wraps a pretrained ViT from timm and extracts:
- Patch tokens ``(B, P, D)`` where ``P = grid_h * grid_w``
- Attention maps from all L layers, each ``(B, H, N, N)``
(N = P + num_prefix_tokens; includes CLS / register tokens)
Compatible with any timm ViT variant: DINOv2, MAE, DINO, standard ViT.
DINOv2 is recommended for fingerprints — attention maps overlap IoU ~0.41
with minutiae locations (DINOv2-FP), confirming that the network discovers
salient keypoints similar to classical minutiae extraction.
"""
import torch
import torch.nn as nn
try:
import timm
except ImportError:
timm = None
class ViTBackbone(nn.Module):
"""Pretrained ViT backbone with per-layer attention extraction.
At forward time, runs the ViT block-by-block and captures pre-dropout
attention weights from each layer. When ``freeze=True``, the entire
forward runs under ``torch.no_grad()`` for memory efficiency.
Parameters
----------
model_name : str
timm model identifier (e.g. ``"vit_base_patch14_dinov2.lvd142m"``).
pretrained : bool
Load pretrained weights from timm hub.
freeze : bool
Freeze all ViT parameters (feature-extraction mode).
image_size : int
Input resolution (square). Position embeddings are interpolated
automatically if this differs from the model's training resolution.
"""
def __init__(
self,
model_name: str = "vit_base_patch14_dinov2.lvd142m",
pretrained: bool = True,
freeze: bool = True,
image_size: int = 224,
):
super().__init__()
if timm is None:
raise ImportError(
"timm is required for ViT backbone: pip install timm"
)
self.vit = timm.create_model(
model_name,
pretrained=pretrained,
img_size=image_size,
num_classes=0,
)
self._frozen = freeze
if freeze:
for p in self.vit.parameters():
p.requires_grad = False
self.embed_dim: int = self.vit.embed_dim
self.grid_size: tuple[int, int] = self.vit.patch_embed.grid_size
self.num_patches: int = self.grid_size[0] * self.grid_size[1]
self.num_prefix_tokens: int = getattr(
self.vit, "num_prefix_tokens", 1
)
# ------------------------------------------------------------------
def forward(
self, images: torch.Tensor
) -> tuple[torch.Tensor, list[torch.Tensor]]:
"""
Args:
images: ``(B, 3, H, W)`` RGB input.
Grayscale images should be repeated to 3 channels
*before* calling this method.
Returns:
patch_tokens: ``(B, P, D)`` — patch features only (no CLS /
register tokens).
attn_maps: list of *L* tensors, each ``(B, H, N, N)`` with
pre-dropout attention weights.
"""
if self._frozen:
with torch.no_grad():
return self._forward_impl(images)
return self._forward_impl(images)
# ------------------------------------------------------------------
def _forward_impl(
self, images: torch.Tensor
) -> tuple[torch.Tensor, list[torch.Tensor]]:
# 1. Patch embedding
x = self.vit.patch_embed(images)
# 2. CLS / register tokens + positional embedding
# timm >= 0.9 exposes _pos_embed(); fall back for older versions.
if hasattr(self.vit, "_pos_embed"):
x = self.vit._pos_embed(x)
else:
cls = self.vit.cls_token.expand(x.shape[0], -1, -1)
x = torch.cat([cls, x], dim=1)
x = self.vit.pos_drop(x + self.vit.pos_embed)
# 3. Transformer blocks — extract attention at every layer
attn_maps: list[torch.Tensor] = []
for blk in self.vit.blocks:
x, attn = self._block_with_attn(blk, x)
attn_maps.append(attn)
# 4. Final layer norm
x = self.vit.norm(x)
# 5. Strip prefix tokens (CLS + optional registers)
patch_tokens = x[:, self.num_prefix_tokens :] # (B, P, D)
return patch_tokens, attn_maps
# ------------------------------------------------------------------
@staticmethod
def _block_with_attn(
blk: nn.Module, x: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
"""Forward one ViT block; return (updated x, attention weights).
Re-implements the block forward to capture pre-dropout attention.
Handles both old-style (shared drop_path) and new-style timm
blocks (drop_path1/2, ls1/2, q_norm/k_norm).
"""
attn_mod = blk.attn
B, N, C = x.shape
num_heads = attn_mod.num_heads
scale = attn_mod.scale
# ---- Self-attention with weight extraction ----
residual = x
x_norm = blk.norm1(x)
qkv = attn_mod.qkv(x_norm)
inner_dim = qkv.shape[-1] // 3
head_dim = inner_dim // num_heads
qkv = qkv.reshape(B, N, 3, num_heads, head_dim).permute(
2, 0, 3, 1, 4
)
q, k, v = qkv.unbind(0)
# QK normalization (DINOv2 / timm >= 0.9)
if hasattr(attn_mod, "q_norm") and attn_mod.q_norm is not None:
q = attn_mod.q_norm(q)
if hasattr(attn_mod, "k_norm") and attn_mod.k_norm is not None:
k = attn_mod.k_norm(k)
attn_weights = (q @ k.transpose(-2, -1)) * scale
attn_weights = attn_weights.softmax(dim=-1) # (B, H, N, N)
# Keep pre-dropout copy for TRAM (detached — no grad needed)
attn_out = attn_weights.detach()
y = (attn_mod.attn_drop(attn_weights) @ v)
y = y.transpose(1, 2).reshape(B, N, C)
y = attn_mod.proj(y)
y = attn_mod.proj_drop(y)
# Layer scale + drop path (version-agnostic)
if hasattr(blk, "ls1"):
y = blk.ls1(y)
dp1 = getattr(blk, "drop_path1", getattr(blk, "drop_path", None))
x = residual + (dp1(y) if dp1 is not None else y)
# ---- FFN ----
residual = x
ffn_out = blk.mlp(blk.norm2(x))
if hasattr(blk, "ls2"):
ffn_out = blk.ls2(ffn_out)
dp2 = getattr(blk, "drop_path2", getattr(blk, "drop_path", None))
x = residual + (dp2(ffn_out) if dp2 is not None else ffn_out)
return x, attn_out