UFR-Fing / src /models /mdgt /dinov2_backbone.py
anbinh39's picture
Add files using upload-large-folder tool
dadf189 verified
Raw
History Blame Contribute Delete
6.04 kB
from __future__ import annotations
"""DINOv2 pretrained backbone with attention map extraction for TRAM.
Wraps facebook's DINOv2 ViT-S/14 (or ViT-B/14) and monkey-patches
the attention modules to capture per-layer attention weights needed by
TRAM token selection.
Returns the same 3-tuple interface as the custom ViT::
(patch_tokens, cls_token, attn_maps)
The monkey-patch replaces MemEffAttention/Attention forwards with standard
scaled-dot-product attention that stores the attention weight matrices.
This disables xformers memory-efficient attention but is necessary because
TRAM requires explicit (B, H, N, N) attention maps from every layer.
"""
import torch
import torch.nn as nn
class DINOv2Backbone(nn.Module):
"""Pretrained DINOv2 ViT backbone with attention map extraction.
Parameters
----------
model_name : str
DINOv2 hub model name (e.g. ``"dinov2_vits14"``).
image_size : int
Input resolution (square).
"""
KNOWN_MODELS = {
"dinov2_vits14", "dinov2_vitb14", "dinov2_vitl14",
"dinov2_vits14_reg", "dinov2_vitb14_reg", "dinov2_vitl14_reg",
}
def __init__(
self,
model_name: str = "dinov2_vits14",
image_size: int = 224,
):
super().__init__()
self.backbone = torch.hub.load(
"facebookresearch/dinov2",
model_name,
pretrained=True,
)
self.embed_dim: int = self.backbone.embed_dim
self._model_name = model_name
# ---- Grayscale -> RGB adapter (learned, init to equal mix) ----
self.gray_adapter = nn.Conv2d(1, 3, kernel_size=1, bias=False)
nn.init.constant_(self.gray_adapter.weight, 1.0 / 3.0)
# ---- Grid geometry ----
ps = self.backbone.patch_embed.patch_size
ps = ps[0] if isinstance(ps, (tuple, list)) else ps
self.patch_size: int = ps
self.grid_size: tuple[int, int] = (image_size // ps, image_size // ps)
# Number of prefix tokens (CLS + optional registers) for TRAM
self.num_prefix_tokens: int = 1 + getattr(
self.backbone, "num_register_tokens", 0
)
# ---- Attention map capture ----
self._attn_maps: list[torch.Tensor] = []
self._patch_attention_modules()
# ------------------------------------------------------------------
def _patch_attention_modules(self):
"""Replace each block's attention forward to capture weights.
DINOv2 uses ``MemEffAttention`` which delegates to xformers and
does NOT produce explicit attention matrices. We replace each
attention module's ``forward`` with a standard implementation
that computes and stores the (B, H, N, N) attention weights so
TRAM can compute per-layer centrality.
"""
for block in self.backbone.blocks:
attn_module = block.attn
# Grab layer references before closure
qkv_layer = attn_module.qkv
proj_layer = attn_module.proj
# DINOv2 may store attn_drop as float or nn.Dropout
raw_ad = attn_module.attn_drop
attn_drop_fn = raw_ad if callable(raw_ad) else nn.Dropout(float(raw_ad))
proj_drop_fn = getattr(attn_module, "proj_drop", nn.Identity())
if not callable(proj_drop_fn):
proj_drop_fn = nn.Dropout(float(proj_drop_fn))
num_heads = attn_module.num_heads
head_dim = self.embed_dim // num_heads
scale = head_dim ** -0.5
store = self._attn_maps
def _make_fwd(_qkv, _proj, _a_drop, _p_drop, _H, _s, _store):
def fwd(x):
B, N, C = x.shape
out = _qkv(x).reshape(B, N, 3, _H, C // _H).permute(2, 0, 3, 1, 4)
q, k, v = out.unbind(0)
w = (q * _s) @ k.transpose(-2, -1)
w = w.softmax(dim=-1)
_store.append(w.detach())
x = (_a_drop(w) @ v).transpose(1, 2).reshape(B, N, C)
x = _p_drop(_proj(x))
return x
return fwd
attn_module.forward = _make_fwd(
qkv_layer, proj_layer, attn_drop_fn, proj_drop_fn,
num_heads, scale, store,
)
# ------------------------------------------------------------------
def forward(
self, images: torch.Tensor,
) -> tuple[torch.Tensor, torch.Tensor, list[torch.Tensor]]:
"""
Args:
images: ``(B, C, H, W)`` grayscale (1-ch) or RGB (3-ch).
Returns:
patch_tokens: ``(B, P, D)`` patch features.
cls_token: ``(B, D)`` CLS token.
attn_maps: list of L tensors ``(B, H, N, N)`` per-layer
attention weights (N = P + num_prefix_tokens).
"""
# Grayscale -> RGB
if images.shape[1] == 1:
images = self.gray_adapter(images)
self._attn_maps.clear()
# Run through DINOv2 manually to collect attention maps
x = self.backbone.prepare_tokens_with_masks(images)
for block in self.backbone.blocks:
x = block(x)
x = self.backbone.norm(x)
# Split CLS / registers / patches
cls_token = x[:, 0] # (B, D)
nr = self.num_prefix_tokens - 1 # register count
patch_tokens = x[:, 1 + nr:] # (B, P, D)
attn_maps = list(self._attn_maps)
self._attn_maps.clear()
return patch_tokens, cls_token, attn_maps
# ------------------------------------------------------------------
def freeze(self):
"""Freeze backbone parameters (gray_adapter stays trainable)."""
for p in self.backbone.parameters():
p.requires_grad = False
def unfreeze(self):
"""Unfreeze backbone parameters."""
for p in self.backbone.parameters():
p.requires_grad = True