File size: 6,569 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 | 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
|