UFR-Fing / src /models /backbone.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
1.3 kB
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)