import math from pathlib import Path from typing import Optional, Sequence, Tuple import torch from safetensors import safe_open from torch import Tensor, nn import torch.nn.functional as F import timm class LoRAQKV(nn.Module): def __init__( self, qkv: nn.Linear, rank: int, use_layer_norm: bool = False, use_qkv: bool = False, ): super().__init__() self.qkv = qkv self.dim = qkv.in_features self.use_qkv = use_qkv self.linear_a_q = nn.Linear(self.dim, rank, bias=False) self.linear_b_q = nn.Linear(rank, self.dim, bias=False) self.linear_a_v = nn.Linear(self.dim, rank, bias=False) self.linear_b_v = nn.Linear(rank, self.dim, bias=False) self.linear_a_k = nn.Linear(self.dim, rank, bias=False) if use_qkv else nn.Identity() self.linear_b_k = nn.Linear(rank, self.dim, bias=False) if use_qkv else nn.Identity() self.layernorm_q = nn.LayerNorm(self.dim) if use_layer_norm else nn.Identity() self.layernorm_v = nn.LayerNorm(self.dim) if use_layer_norm else nn.Identity() self.layernorm_k = nn.LayerNorm(self.dim) if use_layer_norm and use_qkv else nn.Identity() self.reset_parameters() def reset_parameters(self): for module in (self.linear_a_q, self.linear_a_v, self.linear_a_k): if isinstance(module, nn.Linear): nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5)) for module in (self.linear_b_q, self.linear_b_v, self.linear_b_k): if isinstance(module, nn.Linear): nn.init.zeros_(module.weight) def forward(self, x: Tensor) -> Tensor: qkv = self.qkv(x) qkv[:, :, : self.dim] += self.linear_b_q(self.linear_a_q(self.layernorm_q(x))) qkv[:, :, -self.dim :] += self.linear_b_v(self.linear_a_v(self.layernorm_v(x))) if self.use_qkv: qkv[:, :, self.dim : 2 * self.dim] += self.linear_b_k(self.linear_a_k(self.layernorm_k(x))) return qkv def _load_checkpoint(path: str): path_obj = Path(path) if not path_obj.exists(): raise FileNotFoundError(f"DINOv2 checkpoint does not exist: {path}") try: state_dict = {} with safe_open(str(path_obj), framework="pt", device="cpu") as f: for key in f.keys(): state_dict[key] = f.get_tensor(key) return state_dict except Exception: checkpoint = torch.load(path_obj, map_location="cpu") if isinstance(checkpoint, dict): for key in ("state_dict", "model", "teacher"): if key in checkpoint and isinstance(checkpoint[key], dict): checkpoint = checkpoint[key] break return checkpoint class DinoV2LoRAEncoderModel(nn.Module): """ DINOv2 vision encoder following the DrivoR adaptation pattern: frozen timm DINOv2 backbone + LoRA injected into attention q/v + trainable neck. """ def __init__( self, model_name: str = "timm/vit_small_patch14_reg4_dinov2.lvd142m", model_weights: Optional[str] = None, embed_dim: int = 512, image_size: Tuple[int, int] = (224, 224), use_lora: bool = True, lora_rank: int = 16, lora_layers: Optional[Sequence[int]] = None, lora_use_layer_norm: bool = False, lora_use_qkv: bool = False, finetune: bool = False, num_register_tokens: int = 4, use_feature_pooling: bool = False, freeze: bool = False, max_frames: int = 4, max_cameras: int = 6, use_global_img: bool = False, ): super().__init__() self.token_size = embed_dim self.image_size = tuple(image_size) self.num_register_tokens = num_register_tokens self.use_feature_pooling = use_feature_pooling self.max_frames = max_frames self.max_cameras = max_cameras self.use_global_img = use_global_img self.model = timm.create_model( model_name, pretrained=False, num_classes=0, img_size=self.image_size, ) if model_weights: state_dict = _load_checkpoint(model_weights) missing, unexpected = self.model.load_state_dict(state_dict, strict=False) if unexpected: print(f"DINOv2 checkpoint unexpected keys: {unexpected[:10]}") if missing: print(f"DINOv2 checkpoint missing keys: {missing[:10]}") self.num_features = self.model.num_features self.neck = nn.Linear(self.num_features, embed_dim) self.temporal_encoding = nn.Parameter(0.02 * torch.randn(1, max_frames, 1, 1, embed_dim)) self.camera_encoding = nn.Parameter(0.02 * torch.randn(1, 1, max_cameras, 1, embed_dim)) if use_lora: self._freeze_backbone() self._inject_lora(lora_rank, lora_layers, lora_use_layer_norm, lora_use_qkv) elif finetune: for param in self.model.parameters(): param.requires_grad = True else: self._freeze_backbone() if freeze: for param in self.parameters(): param.requires_grad = False self.register_buffer( "image_mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1), persistent=False, ) self.register_buffer( "image_std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1), persistent=False, ) def _freeze_backbone(self): for param in self.model.parameters(): param.requires_grad = False def _inject_lora( self, rank: int, layers: Optional[Sequence[int]], use_layer_norm: bool, use_qkv: bool, ): if rank <= 0: return selected_layers = set(layers) if layers is not None else set(range(len(self.model.blocks))) for layer_idx, block in enumerate(self.model.blocks): if layer_idx not in selected_layers: continue block.attn.qkv = LoRAQKV( block.attn.qkv, rank=rank, use_layer_norm=use_layer_norm, use_qkv=use_qkv, ) def _select_tokens(self, tokens: Tensor) -> Tensor: if self.use_feature_pooling: return F.adaptive_avg_pool1d(tokens.transpose(1, 2), self.num_register_tokens).transpose(1, 2) reg_token = getattr(self.model, "reg_token", None) if reg_token is not None: start = 1 if getattr(self.model, "cls_token", None) is not None else 0 end = start + self.num_register_tokens return tokens[:, start:end] return tokens[:, : self.num_register_tokens] def forward(self, pixel_values: Tensor, image_sizes: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]: if pixel_values.ndim != 6: raise ValueError( "DinoV2LoRAEncoderModel expects images shaped [B, T, N, C, H, W], " f"got {tuple(pixel_values.shape)}." ) batch_size, num_frames, num_cameras, channels, height, width = pixel_values.shape if channels != 3: raise ValueError(f"Expected RGB images with 3 channels, got {channels}.") if num_frames > self.max_frames: raise ValueError(f"num_frames={num_frames} exceeds max_frames={self.max_frames}.") if num_cameras > self.max_cameras: raise ValueError(f"num_cameras={num_cameras} exceeds max_cameras={self.max_cameras}.") x = pixel_values.reshape(batch_size * num_frames * num_cameras, channels, height, width) x = x.to(device=self.neck.weight.device, dtype=self.neck.weight.dtype) x = x / 255.0 x = (x - self.image_mean.to(dtype=x.dtype)) / self.image_std.to(dtype=x.dtype) if (height, width) != self.image_size: x = F.interpolate(x, size=self.image_size, mode="bilinear", align_corners=False) tokens = self.model.forward_features(x) tokens = self._select_tokens(tokens) tokens = self.neck(tokens) tokens = tokens.view(batch_size, num_frames, num_cameras, self.num_register_tokens, -1) tokens = tokens + self.temporal_encoding[:, :num_frames].to(dtype=tokens.dtype) tokens = tokens + self.camera_encoding[:, :, :num_cameras].to(dtype=tokens.dtype) embeds = tokens.reshape(batch_size, num_frames * num_cameras * self.num_register_tokens, -1) attention_mask = torch.ones(embeds.shape[:2], dtype=torch.long, device=embeds.device) return embeds, attention_mask