File size: 1,302 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
from __future__ import annotations

import torch
import torch.nn as nn
import timm


class SIFQBackbone(nn.Module):
    """Backbone wrapper around timm models for grayscale fingerprints."""

    def __init__(self, model_name: str = "tiny_vit_5m_224.dist_in22k", pretrained: bool = True):
        super().__init__()
        self.encoder = timm.create_model(
            model_name,
            pretrained=pretrained,
            num_classes=0,
            in_chans=1,
        )
        self.feature_dim = int(getattr(self.encoder, "num_features", 0))
        if self.feature_dim <= 0:
            raise ValueError("Backbone num_features is missing or invalid")

    def forward_spatial(self, x: torch.Tensor) -> torch.Tensor:
        """Return spatial/token features where possible."""

        feats = self.encoder.forward_features(x)
        if feats.ndim == 4:
            b, c, h, w = feats.shape
            return feats.permute(0, 2, 3, 1).reshape(b, h * w, c)
        if feats.ndim == 3:
            return feats
        if feats.ndim == 2:
            return feats.unsqueeze(1)
        raise ValueError(f"Unexpected feature tensor shape: {tuple(feats.shape)}")

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        spatial = self.forward_spatial(x)
        return spatial.mean(dim=1)