File size: 9,596 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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
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